Buffer modifications to virtual stylesheets (#618)

* Fix sheet insertion

Restore skip duration

Use virtualStyleRulesMap to re-populate stylesheet on Flush event

Clear virtualStyleRulesMap after flush applied

* Support rule deletion in virtual processing

* Simply restoreNodeSheet with early aborts

* Encountered a bug where firstFullSnapshot was played twice because timer was immediately started and reached the snapshot before the setTimeout returned

* Ignoring a FullSnapshot needs to be a one-time only thing, as otherwise we'll ignore it after scrubbing (restarting play head at a particular time). This is a problem if mutations have altered the player state, and we try to replay those mutations, so we e.g. try to remove an element that has already been removed because we haven't reset the FullSnapshot state

* Some `npm run typings` related fixups

* add basic html snapshot functionality

* move restoreNodeSheet to it's own module

* Refactor virtual style rules to buffer changes.
Only applies changes on flush.

`virtualStyleRulesMap` now works with strings instead of CSSRules.
CSSRules can only be via made `.insertRule` on CSSStyleSheet in most browsers.
And `new CSSStyleSheet()` only works in Chrome currently.

* remove unused code

* move VirtualStyleRules from CSSRule to string in tests

* correct paths for tests

* naming

* create and restore style snapshots for virtual nodes

* update replayer snapshot

* move storeCSSRules to virtual-styles.ts

* try/catch access to .sheet in case of access errors

* clean up tests

Co-authored-by: Vladimir Milenko <vladimir.milenko@uber.com>
Co-authored-by: Eoghan Murray <eoghan@getthere.ie>
This commit is contained in:
Justin Halsall
2021-07-08 16:34:02 +02:00
committed by GitHub
parent 7a0e04c574
commit 39c8ba1a24
9 changed files with 1851 additions and 69 deletions

View File

@@ -42,6 +42,13 @@ import {
} from '../utils';
import getInjectStyleRules from './styles/inject-style';
import './styles/style.css';
import {
applyVirtualStyleRulesToNode,
storeCSSRules,
StyleRuleType,
VirtualStyleRules,
VirtualStyleRulesMap,
} from './virtual-styles';
const SKIP_TIME_THRESHOLD = 10 * 1000;
const SKIP_TIME_INTERVAL = 5 * 1000;
@@ -85,6 +92,8 @@ export class Replayer {
private treeIndex!: TreeIndex;
private fragmentParentMap!: Map<INode, INode>;
private elementStateMap!: Map<INode, ElementState>;
// Hold the list of CSSRules for in-memory state restoration
private virtualStyleRulesMap!: VirtualStyleRulesMap;
private imageMap: Map<eventWithTime, HTMLImageElement> = new Map();
@@ -129,14 +138,21 @@ export class Replayer {
this.treeIndex = new TreeIndex();
this.fragmentParentMap = new Map<INode, INode>();
this.elementStateMap = new Map<INode, ElementState>();
this.virtualStyleRulesMap = new Map();
this.emitter.on(ReplayerEvents.Flush, () => {
const { scrollMap, inputMap } = this.treeIndex.flush();
this.fragmentParentMap.forEach((parent, frag) =>
this.restoreRealParent(frag, parent),
);
for (const node of this.virtualStyleRulesMap.keys()) {
// restore css rules of style elements after they are mounted
this.restoreNodeSheet(node);
}
this.fragmentParentMap.clear();
this.elementStateMap.clear();
this.virtualStyleRulesMap.clear();
for (const d of scrollMap.values()) {
this.applyScroll(d);
@@ -909,64 +925,73 @@ export class Replayer {
const styleEl = (target as Node) as HTMLStyleElement;
const parent = (target.parentNode as unknown) as INode;
const usingVirtualParent = this.fragmentParentMap.has(parent);
let placeholderNode;
if (usingVirtualParent) {
/**
* Always use existing DOM node, when it's there.
* In in-memory replay, there is virtual node, but it's `sheet` is inaccessible.
* Hence, we buffer all style changes in virtualStyleRulesMap.
*/
const styleSheet = usingVirtualParent ? null : styleEl.sheet;
let rules: VirtualStyleRules;
if (!styleSheet) {
/**
* styleEl.sheet is only accessible if the styleEl is part of the
* dom. This doesn't work on DocumentFragments so we have to re-add
* it to the dom temporarily.
* dom. This doesn't work on DocumentFragments so we have to add the
* style mutations to the virtualStyleRulesMap.
*/
const domParent = this.fragmentParentMap.get(
(target.parentNode as unknown) as INode,
);
placeholderNode = document.createTextNode('');
parent.replaceChild(placeholderNode, target);
domParent!.appendChild(target);
}
const styleSheet: CSSStyleSheet = styleEl.sheet!;
if (this.virtualStyleRulesMap.has(target)) {
rules = this.virtualStyleRulesMap.get(target) as VirtualStyleRules;
} else {
rules = [];
this.virtualStyleRulesMap.set(target, rules);
}
}
if (d.adds) {
d.adds.forEach(({ rule, index }) => {
try {
const _index =
index === undefined
? undefined
: Math.min(index, styleSheet.rules.length);
if (styleSheet) {
try {
styleSheet.insertRule(rule, _index);
const _index =
index === undefined
? undefined
: Math.min(index, styleSheet.cssRules.length);
try {
styleSheet.insertRule(rule, _index);
} catch (e) {
/**
* sometimes we may capture rules with browser prefix
* insert rule with prefixs in other browsers may cause Error
*/
}
} catch (e) {
/**
* sometimes we may capture rules with browser prefix
* insert rule with prefixs in other browsers may cause Error
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
} else {
rules?.push({ cssText: rule, index, type: StyleRuleType.Insert });
}
});
}
if (d.removes) {
d.removes.forEach(({ index }) => {
try {
styleSheet.deleteRule(index);
} catch (e) {
/**
* same as insertRule
*/
if (usingVirtualParent) {
rules?.push({ index, type: StyleRuleType.Remove });
} else {
try {
styleSheet?.deleteRule(index);
} catch (e) {
/**
* same as insertRule
*/
}
}
});
}
if (usingVirtualParent && placeholderNode) {
parent.replaceChild(target, placeholderNode);
}
break;
}
case IncrementalSource.CanvasMutation: {
@@ -1496,6 +1521,11 @@ export class Replayer {
scroll: [parentElement.scrollLeft, parentElement.scrollTop],
});
}
if (parentElement.tagName === 'STYLE')
storeCSSRules(
parentElement as HTMLStyleElement,
this.virtualStyleRulesMap,
);
const children = parentElement.children;
for (const child of Array.from(children)) {
this.storeState((child as unknown) as INode);
@@ -1527,6 +1557,17 @@ export class Replayer {
}
}
private restoreNodeSheet(node: INode) {
const storedRules = this.virtualStyleRulesMap.get(node);
if (node.nodeName !== 'STYLE') return;
if (!storedRules) return;
const styleNode = (node as unknown) as HTMLStyleElement;
applyVirtualStyleRulesToNode(storedRules, styleNode);
}
private warnNodeNotFound(d: incrementalData, id: number) {
this.warn(`Node with id '${id}' not found in`, d);
}

View File

@@ -0,0 +1,119 @@
import { INode } from 'rrweb-snapshot';
export enum StyleRuleType {
Insert,
Remove,
Snapshot,
}
type InsertRule = {
cssText: string;
type: StyleRuleType.Insert;
index?: number;
};
type RemoveRule = {
type: StyleRuleType.Remove;
index: number;
};
type SnapshotRule = {
type: StyleRuleType.Snapshot;
cssTexts: string[];
};
export type VirtualStyleRules = Array<InsertRule | RemoveRule | SnapshotRule>;
export type VirtualStyleRulesMap = Map<INode, VirtualStyleRules>;
export function applyVirtualStyleRulesToNode(
storedRules: VirtualStyleRules,
styleNode: HTMLStyleElement,
) {
storedRules.forEach((rule) => {
if (rule.type === StyleRuleType.Insert) {
try {
styleNode.sheet?.insertRule(rule.cssText, rule.index);
} catch (e) {
/**
* sometimes we may capture rules with browser prefix
* insert rule with prefixs in other browsers may cause Error
*/
}
} else if (rule.type === StyleRuleType.Remove) {
try {
styleNode.sheet?.deleteRule(rule.index);
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
} else if (rule.type === StyleRuleType.Snapshot) {
restoreSnapshotOfStyleRulesToNode(rule.cssTexts, styleNode);
}
});
}
function restoreSnapshotOfStyleRulesToNode(
cssTexts: string[],
styleNode: HTMLStyleElement,
) {
try {
const existingRules = Array.from(styleNode.sheet?.cssRules || []).map(
(rule) => rule.cssText,
);
const existingRulesReversed = Object.entries(existingRules).reverse();
let lastMatch = existingRules.length;
existingRulesReversed.forEach(([index, rule]) => {
const indexOf = cssTexts.indexOf(rule);
if (indexOf === -1 || indexOf > lastMatch) {
try {
styleNode.sheet?.deleteRule(Number(index));
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
}
lastMatch = indexOf;
});
cssTexts.forEach((cssText, index) => {
try {
if (styleNode.sheet?.cssRules[index]?.cssText !== cssText) {
styleNode.sheet?.insertRule(cssText, index);
}
} catch (e) {
/**
* sometimes we may capture rules with browser prefix
* insert rule with prefixs in other browsers may cause Error
*/
}
});
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
}
export function storeCSSRules(
parentElement: HTMLStyleElement,
virtualStyleRulesMap: VirtualStyleRulesMap,
) {
try {
const cssTexts = Array.from(
(parentElement as HTMLStyleElement).sheet?.cssRules || [],
).map((rule) => rule.cssText);
virtualStyleRulesMap.set((parentElement as unknown) as INode, [
{
type: StyleRuleType.Snapshot,
cssTexts,
},
]);
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
}