-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgetKeyForNode.ts
More file actions
34 lines (30 loc) · 1.01 KB
/
Copy pathgetKeyForNode.ts
File metadata and controls
34 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Utility function to generate a unique key for a given node. Is automatically used as the `key` prop in case you're
* using {@link Registry.createReactRenderer}, but you may find it useful in other scenarios too.
*/
export function getKeyForNode(
node: Node & {
hasAttribute?: (name: string) => boolean;
getAttribute?: (name: string) => string;
},
identifierAttribute = 'id',
) {
const pieces = [];
let contextNode = node;
while (contextNode && contextNode.parentNode) {
// If any contextNode has an identifier, assume it to be unique and stop traversing up
if (
identifierAttribute &&
contextNode.nodeType === 1 &&
contextNode.hasAttribute &&
contextNode.getAttribute &&
contextNode.hasAttribute(identifierAttribute)
) {
pieces.push(contextNode.getAttribute(identifierAttribute));
break;
}
pieces.push(Array.prototype.indexOf.call(contextNode.parentNode.childNodes, contextNode));
contextNode = contextNode.parentNode;
}
return 'node-key--' + pieces.reverse().join('-');
}