Skip to content

Commit

Permalink
feat: add support for recording and replaying adoptedStyleSheets API (#…
Browse files Browse the repository at this point in the history
…989)

* test(recording side): add test case for adopted stylesheets in shadow doms and iframe

* add type definition for adopted StyleSheets

* create a StyleSheet Mirror

* enable to record the outermost document's adoptedStyleSheet

* enable to serialize all stylesheets in documents (iframe) and shadow roots

* enable to record adopted stylesheets while building full snapshot

* test: add test case for mutations on adoptedStyleSheets

* defer to record adoptedStyleSheets to avoid create events before full snapshot

* feat: enable to track the mutation of AdoptedStyleSheets

* Merge branch 'fix-shadowdom-record' into construct-style

* fix: incorrect id conditional judgement

* test: add a test case for replaying side

* tweak the style mirror for replayer

* feat: enable to replay adoptedStyleSheet events

* fix: rule index wasn't recorded when serializing the adoptedStyleSheets

* add test case for mutation of stylesheet objects and add support for replace & replaceSync

* refactor: improve the code quality

* feat: monkey patch adoptedStyleSheet API to track its modification

* feat: add support for checkouting fullsnapshot

* CI: fix failed type checks

* test: add test case for nested shadow doms and iframe elements

* feat: add support for adoptedStyleSheets in VirtualDom mode

* style: format files

* test: improve the robustness of the test case

* CI: fix an eslint error

* test: improve the robustness of the test case

* fix: adoptedStyleSheets not applied in fast-forward mode (virtual dom optimization not used)

* refactor the data structure of adoptedStyleSheet event to make it more efficient and robust

* improve the robustness in the live mode

In the live mode where events are transferred over network without strict order guarantee, some newer events are applied before some old events and adopted stylesheets may haven't been created.
Added a retry mechanism to solve this problem.

* apply Yanzhen's review suggestion

* update action name

* test: make the test case more robust for travis CI

* Update packages/rrweb/src/record/constructableStyleSheets.d.ts

Co-authored-by: Justin Halsall <Juice10@users.noreply.github.com>

* Update packages/rrweb/src/record/constructableStyleSheets.d.ts

Co-authored-by: Justin Halsall <Juice10@users.noreply.github.com>

* apply Justin's review suggestions

add more browser compatibility checks

* add eslint-plugin-compat and config

* fix record test  type errors

* make Mirror's replace function act the same with the original one when there's no existed node to replace

* test: increase the robustness of test cases

* remove eslint disable in favor of feature detection

Early returns aren't supported yet unfortunately, otherwise this code would be cleaner amilajack/eslint-plugin-compat#523

* Remove eslint-disable-next-line compat/compat

* Standardize browserslist and remove lint exceptions (#1010)

* test: revert deleting virtual style tests and rewrite them to fit the current code base

Co-authored-by: Justin Halsall <Juice10@users.noreply.github.com>
  • Loading branch information
YunFeng0817 and Juice10 authored Sep 29, 2022
1 parent 23e3a73 commit 3809060
Show file tree
Hide file tree
Showing 35 changed files with 3,277 additions and 443 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:compat/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
Expand All @@ -17,7 +18,7 @@ module.exports = {
tsconfigRootDir: __dirname,
project: ['./tsconfig.eslint.json', './packages/*/tsconfig.json'],
},
plugins: ['@typescript-eslint', 'eslint-plugin-tsdoc', 'jest'],
plugins: ['@typescript-eslint', 'eslint-plugin-tsdoc', 'jest', 'compat'],
rules: {
'tsdoc/syntax': 'warn',
},
Expand Down
10 changes: 5 additions & 5 deletions .github/workflows/style-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
run: yarn lint:report
# Continue to the next step even if this fails
continue-on-error: true
- name: Upload ESLint report
- name: Upload ESLint Report
uses: actions/upload-artifact@v3
with:
name: eslint_report.json
Expand All @@ -50,7 +50,7 @@ jobs:
report-json: 'eslint_report.json'

prettier_check:
# In the forked PR, it's hard to format code and push to the branch directly.
# In the forked PR, it's hard to format code and push to the branch directly, so the action only check the format correctness.
if: github.event_name != 'push' && github.event.pull_request.head.repo.full_name != 'rrweb-io/rrweb'
runs-on: ubuntu-latest
name: Format Check
Expand All @@ -66,7 +66,7 @@ jobs:
cache: 'yarn'
- name: Install Dependencies
run: yarn
- name: Prettify code
- name: Prettier Check
run: yarn prettier --check '**/*.{ts,md}'

prettier:
Expand All @@ -86,9 +86,9 @@ jobs:
cache: 'yarn'
- name: Install Dependencies
run: yarn
- name: Prettify code
- name: Prettify Code
run: yarn prettier --write '**/*.{ts,md}'
- name: Commit changes
- name: Commit Changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Apply formatting changes
Expand Down
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
"@monorepo-utils/workspaces-to-typescript-project-references": "^2.8.2",
"@typescript-eslint/eslint-plugin": "^5.25.0",
"@typescript-eslint/parser": "^5.25.0",
"browserslist": "^4.21.4",
"concurrently": "^7.1.0",
"eslint": "^8.19.0",
"eslint-plugin-compat": "^4.0.2",
"eslint-plugin-jest": "^26.5.3",
"eslint-plugin-tsdoc": "^0.2.16",
"lerna": "^4.0.0",
Expand All @@ -44,5 +46,9 @@
},
"resolutions": {
"**/jsdom/cssom": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz"
}
},
"browserslist": [
"defaults",
"not op_mini all"
]
}
5 changes: 4 additions & 1 deletion packages/rrdom-nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,8 @@
"nwsapi": "^2.2.0",
"rrdom": "^0.1.5",
"rrweb-snapshot": "^2.0.0-alpha.2"
}
},
"browserslist": [
"supports es6-class"
]
}
7 changes: 6 additions & 1 deletion packages/rrdom-nodejs/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
},
"compileOnSave": true,
"exclude": ["test"],
"include": ["src", "test.d.ts", "../rrweb/src/record/workers/workers.d.ts"],
"include": [
"src",
"test.d.ts",
"../rrweb/src/record/workers/workers.d.ts",
"../rrweb/src/record/constructable-stylesheets.d.ts"
],
"references": [
{
"path": "../rrdom"
Expand Down
127 changes: 16 additions & 111 deletions packages/rrdom/src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type {
canvasEventWithTime,
inputData,
scrollData,
styleDeclarationData,
styleSheetRuleData,
} from 'rrweb/src/types';
import type {
IRRCDATASection,
Expand Down Expand Up @@ -79,6 +81,10 @@ export type ReplayerHandler = {
) => void;
applyInput: (data: inputData) => void;
applyScroll: (data: scrollData, isSync: boolean) => void;
applyStyleSheetMutation: (
data: styleDeclarationData | styleSheetRuleData,
styleSheet: CSSStyleSheet,
) => void;
};

export function diff(
Expand Down Expand Up @@ -161,20 +167,25 @@ export function diff(
}
break;
case 'STYLE':
applyVirtualStyleRulesToNode(
oldElement as HTMLStyleElement,
(newTree as RRStyleElement).rules,
);
{
const styleSheet = (oldElement as HTMLStyleElement).sheet;
styleSheet &&
(newTree as RRStyleElement).rules.forEach((data) =>
replayer.applyStyleSheetMutation(data, styleSheet),
);
}
break;
}
if (newRRElement.shadowRoot) {
if (!oldElement.shadowRoot) oldElement.attachShadow({ mode: 'open' });
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const oldChildren = oldElement.shadowRoot!.childNodes;
const newChildren = newRRElement.shadowRoot.childNodes;
if (oldChildren.length > 0 || newChildren.length > 0)
diffChildren(
Array.from(oldChildren),
newChildren,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
oldElement.shadowRoot!,
replayer,
rrnodeMirror,
Expand Down Expand Up @@ -335,6 +346,7 @@ function diffChildren(
}
indexInOld = oldIdToIndex[rrnodeMirror.getId(newStartNode)];
if (indexInOld) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const nodeToMove = oldChildren[indexInOld]!;
parentNode.insertBefore(nodeToMove, oldStartNode);
diff(nodeToMove, newStartNode, replayer, rrnodeMirror);
Expand Down Expand Up @@ -439,110 +451,3 @@ export function createOrGetNode(
if (sn) domMirror.add(node, { ...sn });
return node;
}

export function getNestedRule(
rules: CSSRuleList,
position: number[],
): CSSGroupingRule {
const rule = rules[position[0]] as CSSGroupingRule;
if (position.length === 1) {
return rule;
} else {
return getNestedRule(
(rule.cssRules[position[1]] as CSSGroupingRule).cssRules,
position.slice(2),
);
}
}

export enum StyleRuleType {
Insert,
Remove,
Snapshot,
SetProperty,
RemoveProperty,
}
type InsertRule = {
cssText: string;
type: StyleRuleType.Insert;
index?: number | number[];
};
type RemoveRule = {
type: StyleRuleType.Remove;
index: number | number[];
};
type SetPropertyRule = {
type: StyleRuleType.SetProperty;
index: number[];
property: string;
value: string | null;
priority: string | undefined;
};
type RemovePropertyRule = {
type: StyleRuleType.RemoveProperty;
index: number[];
property: string;
};

export type VirtualStyleRules = Array<
InsertRule | RemoveRule | SetPropertyRule | RemovePropertyRule
>;

export function getPositionsAndIndex(nestedIndex: number[]) {
const positions = [...nestedIndex];
const index = positions.pop();
return { positions, index };
}

export function applyVirtualStyleRulesToNode(
styleNode: HTMLStyleElement,
virtualStyleRules: VirtualStyleRules,
) {
const sheet = styleNode.sheet!;

virtualStyleRules.forEach((rule) => {
if (rule.type === StyleRuleType.Insert) {
try {
if (Array.isArray(rule.index)) {
const { positions, index } = getPositionsAndIndex(rule.index);
const nestedRule = getNestedRule(sheet.cssRules, positions);
nestedRule.insertRule(rule.cssText, index);
} else {
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 {
if (Array.isArray(rule.index)) {
const { positions, index } = getPositionsAndIndex(rule.index);
const nestedRule = getNestedRule(sheet.cssRules, positions);
nestedRule.deleteRule(index || 0);
} else {
sheet.deleteRule(rule.index);
}
} catch (e) {
/**
* accessing styleSheet rules may cause SecurityError
* for specific access control settings
*/
}
} else if (rule.type === StyleRuleType.SetProperty) {
const nativeRule = (getNestedRule(
sheet.cssRules,
rule.index,
) as unknown) as CSSStyleRule;
nativeRule.style.setProperty(rule.property, rule.value, rule.priority);
} else if (rule.type === StyleRuleType.RemoveProperty) {
const nativeRule = (getNestedRule(
sheet.cssRules,
rule.index,
) as unknown) as CSSStyleRule;
nativeRule.style.removeProperty(rule.property);
}
});
}
17 changes: 7 additions & 10 deletions packages/rrdom/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import type {
canvasEventWithTime,
inputData,
scrollData,
styleSheetRuleData,
styleDeclarationData,
} from 'rrweb/src/types';
import type { VirtualStyleRules } from './diff';
import {
BaseRRNode as RRNode,
BaseRRCDATASectionImpl,
Expand Down Expand Up @@ -164,7 +165,7 @@ export class RRCanvasElement extends RRElement implements IRRElement {
}

export class RRStyleElement extends RRElement {
public rules: VirtualStyleRules = [];
public rules: (styleSheetRuleData | styleDeclarationData)[] = [];
}

export class RRIFrameElement extends RRElement {
Expand Down Expand Up @@ -312,7 +313,8 @@ export function buildFromDom(
}

if (node.nodeName === 'IFRAME') {
walk((node as HTMLIFrameElement).contentDocument!, rrNode);
const iframeDoc = (node as HTMLIFrameElement).contentDocument;
iframeDoc && walk(iframeDoc, rrNode);
} else if (
node.nodeType === NodeType.DOCUMENT_NODE ||
node.nodeType === NodeType.ELEMENT_NODE ||
Expand All @@ -323,6 +325,7 @@ export function buildFromDom(
node.nodeType === NodeType.ELEMENT_NODE &&
(node as HTMLElement).shadowRoot
)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
walk((node as HTMLElement).shadowRoot!, rrNode);
node.childNodes.forEach((childNode) => walk(childNode, rrNode));
}
Expand Down Expand Up @@ -475,11 +478,5 @@ function walk(node: IRRNode, mirror: IMirror<IRRNode>, blankSpace: string) {

export { RRNode };

export {
diff,
createOrGetNode,
StyleRuleType,
ReplayerHandler,
VirtualStyleRules,
} from './diff';
export { diff, createOrGetNode, ReplayerHandler } from './diff';
export * from './document';
Loading

0 comments on commit 3809060

Please sign in to comment.