return id node map when rebuild

This commit is contained in:
Yanzhen Yu
2026-04-01 12:00:00 +08:00
parent b170c3de59
commit 0434129b00
5 changed files with 23 additions and 6 deletions

2
index.d.ts vendored
View File

@@ -2,7 +2,7 @@ import { serializedNodeWithId, idNodeMap } from './src/types';
export * from './src/types';
export function snapshot(n: Document): [serializedNodeWithId | null, idNodeMap];
export function rebuild(n: serializedNodeWithId): Node | null;
export function rebuild(n: serializedNodeWithId): [Node | null, idNodeMap];
export function serializeNodeWithId(
n: Node,
doc: Document,

View File

@@ -1,4 +1,11 @@
import { serializedNodeWithId, NodeType, tagMap, elementNode } from './types';
import {
serializedNodeWithId,
NodeType,
tagMap,
elementNode,
idNodeMap,
INode,
} from './types';
const tagMap: tagMap = {
script: 'noscript',
@@ -54,14 +61,16 @@ function buildNode(n: serializedNodeWithId): Node | null {
}
}
function rebuild(n: serializedNodeWithId): Node | null {
function _rebuild(n: serializedNodeWithId, map: idNodeMap): Node | null {
const root = buildNode(n);
if (!root) {
return null;
}
(root as INode).__sn = n;
map[n.id] = root as INode;
if (n.type === NodeType.Document || n.type === NodeType.Element) {
for (const childN of n.childNodes) {
const childNode = rebuild(childN);
const childNode = _rebuild(childN, map);
if (!childNode) {
console.warn('Failed to rebuild', childN);
} else {
@@ -72,4 +81,9 @@ function rebuild(n: serializedNodeWithId): Node | null {
return root;
}
function rebuild(n: serializedNodeWithId): [Node | null, idNodeMap] {
const idNodeMap: idNodeMap = {};
return [_rebuild(n, idNodeMap), idNodeMap];
}
export default rebuild;

View File

@@ -4,3 +4,6 @@ body {
p {
color: red;
}
body > p {
color: yellow;
}

View File

@@ -25,7 +25,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>with style sheet</title>
<style>body { margin: 0px; }p { color: red; }</style>
<style>body { margin: 0px; }p { color: red; }body > p { color: yellow; }</style>
</head>
<body>

View File

@@ -99,7 +99,7 @@ describe('integration tests', () => {
const rebuildHtml = (await page.evaluate(`${this.code}
const x = new XMLSerializer();
const [snap] = rrweb.snapshot(document);
x.serializeToString(rrweb.rebuild(snap));
x.serializeToString(rrweb.rebuild(snap)[0]);
`)).replace(/\n\n/g, '');
await page.goto(`http://localhost:3030/html`);
await page.setContent(html.dest);