This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import-node.ts
85 lines (73 loc) · 2.52 KB
/
import-node.ts
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { nodeDocument } from './node-document';
import { isElementNode } from './node-types';
/**
* Imports DOM node from one document to another.
*
* @typeParam TNode - DOM node type.
* @param from - The node to import.
* @param to - The node to append imported node to.
* @param importContent - A function that imports nodes nested in parent element. {@link importNodeContent} by default.
*
* @returns Imported node.
*/
export function importNode<TNode extends Node>(
from: TNode,
to: Node,
importContent?: (this: void, from: TNode, to: TNode) => void,
): TNode;
/**
* Imports DOM node from one document to another and inserts it before the given node.
*
* @typeParam TNode - DOM node type.
* @param from - The node to import.
* @param to - The node to append imported node to.
* @param before - The node to insert imported node before, or `null` to append it to the end of target one.
* @param importContent - A function that imports nodes nested in parent element. {@link importNodeContent} by default.
*
* @returns Imported node.
*/
export function importNode<TNode extends Node>(
from: TNode,
to: Node,
before?: Node | null,
importContent?: (this: void, from: TNode, to: TNode) => void,
): TNode;
export function importNode<TNode extends Node>(
from: TNode,
to: Node,
beforeOrImport?: Node | null | ((this: void, from: TNode, to: TNode) => void),
importContent: (this: void, from: TNode, to: TNode) => void = importNodeContent,
): TNode {
let before: Node | null;
if (typeof beforeOrImport === 'function') {
importContent = beforeOrImport;
before = null;
} else {
before = beforeOrImport || null;
}
const doc = nodeDocument(to);
if (isElementNode(from)) {
const elementClone = doc.createElement(from.tagName.toLowerCase()) as Node as Element & TNode;
from
.getAttributeNames()
.forEach(attr => elementClone.setAttribute(attr, from.getAttribute(attr)!));
importContent(from, elementClone);
to.insertBefore(elementClone, before);
return elementClone;
}
const nodeClone = doc.importNode(from, false);
to.insertBefore(nodeClone, before);
return nodeClone;
}
/**
* Imports DOM node contents from one document to another.
*
* @param from - The node which contents to import.
* @param to - The node to append imported nodes to.
*/
export function importNodeContent(from: Node, to: Node): void {
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < from.childNodes.length; ++i) {
importNode(from.childNodes[i], to);
}
}