PluginProbe
Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts / trunk
Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts vtrunk
2.8.14 2.8.13 2.8.12 2.7.5 2.7.6 2.7.7 2.7.8 2.7.9 2.8.0 2.8.1 2.8.10 2.8.11 2.8.2 2.8.3 2.8.4 2.8.5 2.8.6 2.8.7 2.8.8 2.8.9 trunk 1.0.1 1.0.2 1.1.0 1.1.1 All 147 releases
content-blocks-builder / src / utils / dom / normalize.js

normalize.js in Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts trunk, at src/utils/dom/normalize.js

90 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * Internal dependencies
3 */
4 import { exposeComponent } from "./utils";
5
6 function normalizeData(value) {
7 if (value === "true") {
8 return true;
9 }
10
11 if (value === "false") {
12 return false;
13 }
14
15 if (value === Number(value).toString()) {
16 return Number(value);
17 }
18
19 if (value === "" || value === "null") {
20 return null;
21 }
22
23 if (typeof value !== "string") {
24 return value;
25 }
26
27 try {
28 return JSON.parse(decodeURIComponent(value));
29 } catch {
30 return value;
31 }
32 }
33
34 function normalizeDataKey(key) {
35 return key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`);
36 }
37
38 function getDataAttributes(
39 element,
40 filterKey = (key) => key,
41 refineKey = (key) => key
42 ) {
43 if (!element) {
44 return {};
45 }
46
47 const attributes = {};
48 const dataKeys = Object.keys(element.dataset).filter(filterKey);
49
50 for (const key of dataKeys) {
51 // let pureKey = key.replace(/^prefix/, "");
52 let pureKey = refineKey(key);
53 pureKey =
54 pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);
55 attributes[pureKey] = normalizeData(element.dataset[key]);
56 }
57
58 return attributes;
59 }
60
61 function getDataAttribute(element, key) {
62 return normalizeData(element.getAttribute(`data-${normalizeDataKey(key)}`));
63 }
64
65 function setDataAttribute(element, key, value) {
66 element.setAttribute(`data-${normalizeDataKey(key)}`, value);
67 }
68
69 function removeDataAttribute(element, key) {
70 element.removeAttribute(`data-${normalizeDataKey(key)}`);
71 }
72
73 exposeComponent("Dataset", {
74 normalizeData,
75 normalizeDataKey,
76 getDataAttributes,
77 getDataAttribute,
78 setDataAttribute,
79 removeDataAttribute,
80 });
81
82 export {
83 normalizeData,
84 normalizeDataKey,
85 getDataAttributes,
86 getDataAttribute,
87 setDataAttribute,
88 removeDataAttribute,
89 };
90