reuse serialized nodes ids (#12)

* reuse serialized nodes ids

With this patch, each DOM node keeps its id during its existence. This
allows to apply RRWeb events to previous snapshots if needed.

`resetId` has been removed because it loses its meaning: calling it
would not reset the existing nodes ids anymore, only the new ones.

Since we don't reset the id anymore, we may exhaust the available ids
quicker, but Number.MAX_SAFE_INTEGER (2 ** 53 - 1) is pretty large, so I
doubt this'll cause any problem.

* improv TS typing

The `nAsINode` variable was not very elegant.  Simplify this by removing
the cast, and make the INode interface compatible with Node.

* update typings
This commit is contained in:
Benoît Zugmeyer
2019-05-21 11:55:43 +02:00
committed by yz-yu
parent bb1fdac86c
commit 5697c689d9
4 changed files with 16 additions and 17 deletions

View File

@@ -1,5 +1,5 @@
import snapshot, { serializeNodeWithId, resetId } from './snapshot';
import snapshot, { serializeNodeWithId } from './snapshot';
import rebuild, { buildNodeWithSN } from './rebuild';
export * from './types';
export { snapshot, serializeNodeWithId, resetId, rebuild, buildNodeWithSN };
export { snapshot, serializeNodeWithId, rebuild, buildNodeWithSN };

View File

@@ -13,10 +13,6 @@ function genId(): number {
return _id++;
}
export function resetId() {
_id = 1;
}
function getCssRulesString(s: CSSStyleSheet): string | null {
try {
const rules = s.rules || s.cssRules;
@@ -239,7 +235,7 @@ function serializeNode(
}
export function serializeNodeWithId(
n: Node,
n: Node | INode,
doc: Document,
map: idNodeMap,
blockClass: string | RegExp,
@@ -252,11 +248,16 @@ export function serializeNodeWithId(
console.warn(n, 'not serialized');
return null;
}
const serializedNode = Object.assign(_serializedNode, {
id: genId(),
});
let id
// Try to reuse the previous id
if ('__sn' in n) {
id = n.__sn.id
} else {
id = genId()
}
const serializedNode = Object.assign(_serializedNode, { id });
(n as INode).__sn = serializedNode;
map[serializedNode.id] = n as INode;
map[id] = (n as INode);
let recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) {
recordChild = recordChild && !serializedNode.needBlock;
@@ -290,7 +291,6 @@ function snapshot(
blockClass: string | RegExp = 'rr-block',
inlineStylesheet = true,
): [serializedNodeWithId | null, idNodeMap] {
resetId();
const idNodeMap: idNodeMap = {};
return [
serializeNodeWithId(n, n, idNodeMap, blockClass, false, inlineStylesheet),