add data attribute to element when rebuild

This commit is contained in:
Yanzhen Yu
2026-04-01 12:00:00 +08:00
parent 0434129b00
commit cb3efd427f
2 changed files with 7 additions and 18 deletions

2
index.d.ts vendored
View File

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

View File

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