-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtdeb.mjs
More file actions
67 lines (58 loc) · 1.89 KB
/
Copy pathtdeb.mjs
File metadata and controls
67 lines (58 loc) · 1.89 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
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
/**
* tdeb.js v3 - Tiny DOM Element Builder
* DOM elements without the pain. Zero dependencies. No Virtual DOM.
*
* @author Shinon
* @license MIT
*/
export const htmlToNodes = (string) => {
const tmp = document.createElement("template");
tmp.innerHTML = string;
return tmp.content;
}
export const interleave = (arr, x) => {
return arr.flatMap((e) => [e, x]).slice(0, -1);
}
export const el = (tag, arg1, arg2) => {
const element = document.createElement(tag);
let props = {},
children = [];
if (
arg1 !== undefined &&
arg1 !== null &&
(Array.isArray(arg1) ||
typeof arg1 === "string" ||
typeof arg1 === "number" ||
arg1 instanceof Node)
) {
children = arg1;
} else {
props = arg1 || {};
children = arg2 || [];
}
for (const [key, val] of Object.entries(props)) {
if (val === undefined || val === null) continue;
if (key.startsWith("on") && typeof val === "function") {
element.addEventListener(key.substring(2).toLowerCase(), val);
} else if (key === "className" || key === "classList" || key === "class") {
if (Array.isArray(val)) element.className = val.filter(Boolean).join(" ");
else if (typeof val === "string") element.className = val;
} else if (key === "dataset" && typeof val === "object") {
for (const [dataKey, dataVal] of Object.entries(val))
element.dataset[dataKey] = dataVal;
} else if (key === "style" && typeof val === "object") {
Object.assign(element.style, val);
} else {
if (key in element) element[key] = val;
else element.setAttribute(key, val);
}
}
const append = (c) => {
if (c === undefined || c === null || c === false) return;
if (Array.isArray(c)) c.forEach(append);
else if (c instanceof Node) element.appendChild(c);
else element.appendChild(document.createTextNode(String(c)));
};
append(children);
return element;
};