1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | var helpers = require('./helpers.js');
|
6 |
|
7 | const pascalToKebab = (string) =>
|
8 | string.replace(/[\w]([A-Z])/g, function (m) {
|
9 | return m[0] + "-" + m[1].toLowerCase()
|
10 | });
|
11 |
|
12 | const kebabToPascal = (string) =>
|
13 | string.replace(/[\w]-([\w])/g, function (m) {
|
14 | return m[0] + m[2].toUpperCase()
|
15 | });
|
16 |
|
17 | const parseStyles = (value) => {
|
18 | let type = typeof value;
|
19 |
|
20 | if (type === "string")
|
21 | return value.split(";").reduce((o, value) => {
|
22 | const [k, v] = value.split(":").map((v) => v.trim());
|
23 | if (k) o[k] = v;
|
24 | return o
|
25 | }, {})
|
26 |
|
27 | if (type === "object") return value
|
28 |
|
29 | return {}
|
30 | };
|
31 |
|
32 | const joinStyles = (value) =>
|
33 | Object.entries(value)
|
34 | .map(([k, v]) => `${k}: ${v};`)
|
35 | .join(" ");
|
36 |
|
37 | const convertStyles = (o) =>
|
38 | Object.keys(o).reduce((a, k) => {
|
39 | a[pascalToKebab(k)] = o[k];
|
40 | return a
|
41 | }, {});
|
42 |
|
43 | const applyAttribute = (node, name, value) => {
|
44 | if (name === "style") {
|
45 | value = joinStyles(
|
46 | convertStyles({
|
47 | ...parseStyles(node.getAttribute("style")),
|
48 | ...parseStyles(value),
|
49 | })
|
50 | );
|
51 | } else if (name === "class") {
|
52 | switch (helpers.typeOf(value)) {
|
53 | case "Array":
|
54 | value = value.join(" ");
|
55 | break
|
56 | case "Object":
|
57 | value = Object.keys(value)
|
58 | .reduce((a, k) => {
|
59 | if (value[k]) a.push(k);
|
60 | return a
|
61 | }, [])
|
62 | .join(" ");
|
63 | break
|
64 | }
|
65 | } else if (!helpers.isPrimitive(value)) {
|
66 | return (node[kebabToPascal(name)] = value)
|
67 | }
|
68 |
|
69 | name = pascalToKebab(name);
|
70 |
|
71 | if (typeof value === "boolean") {
|
72 | if (name.startsWith("aria-")) {
|
73 | value = "" + value;
|
74 | } else if (value) {
|
75 | value = "";
|
76 | }
|
77 | }
|
78 |
|
79 | let current = node.getAttribute(name);
|
80 |
|
81 | if (value === current) return
|
82 |
|
83 | if (typeof value === "string" || typeof value === "number") {
|
84 | node.setAttribute(name, value);
|
85 | } else {
|
86 | node.removeAttribute(name);
|
87 | }
|
88 | };
|
89 |
|
90 | exports.applyAttribute = applyAttribute;
|