| 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 |
|