-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
97 lines (85 loc) · 2.38 KB
/
utils.js
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
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Functions are placed here for better encapsulation and readability of the main codebase. This helps to isolate them
* from the DOM API of the implemented web component (particularly if they are static and do not need access to instance
* level information, i.e. they do not call "this").
*/
/**
* Extracted from svelte's internal API @ src/runtime/internal/dom.js
*
* @param {Node} target
* @param {Node} node
* @param {Node} [anchor]
* @returns {void}
*/
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
/**
* Extracted from svelte's internal API @ src/runtime/internal/dom.js
*
* @param {Node} node
* @returns {void}
*/
function detach(node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
/**
* Creates an object where each property represents the slot name and each value represents a Svelte-specific slot
* object containing the lifecycle hooks for each slot. This wraps our slot elements and is passed to Svelte itself.
*
* Much of this witchcraft is from svelte issue - https://github.com/sveltejs/svelte/issues/2588
*/
export function createSvelteSlots(slots) {
const svelteSlots = {};
for(const slotName in slots) {
svelteSlots[slotName] = [createSlotFn(slots[slotName])];
}
function createSlotFn(element) {
return function() {
return {
c: function() {}, // noop
m: function mount(target, anchor) {
insert(target, element.cloneNode(true), anchor);
},
d: function destroy(detaching) {
if (detaching) {
detach(element);
}
},
l: function() {}, // noop
};
};
}
return svelteSlots;
}
/**
* Traverses DOM to find the first custom element that the provided <slot> element happens to belong to.
*
* @param {Element} slot
* @returns {HTMLElement|null}
*/
export function findSlotParent(slot) {
let parentEl = slot.parentElement;
while(parentEl) {
if (parentEl.tagName.indexOf('-') !== -1) return parentEl;
parentEl = parentEl.parentElement;
}
return null;
}
/**
* Carefully "unwraps" the custom element tag itself from its default slot content (particularly if that content
* is just a text node). Only used when not using shadow root.
*
* @param {HTMLElement} from
*
* @returns {DocumentFragment}
*/
export function unwrap(from) {
let node = document.createDocumentFragment();
while(from.firstChild) {
node.appendChild(from.firstChild);
}
return node;
}