Current section
Files
Jump to
Current section
Files
priv/static/phoenix_live_head.cjs.js
// js/phoenix_live_head/index.ts
window.addEventListener("phx:hd", ({ detail }) => {
const CLASS_ATTR = "class-name";
const ATTR = {
"c": CLASS_ATTR,
"h": "href"
};
const QUERY = {
"f": "link[rel*='icon']"
};
const kebabToCamelCase = (s) => s.replace(/-./g, (x) => x[1].toUpperCase());
const camelToKebabCase = (s) => s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
const origValueKey = (attr) => kebabToCamelCase(`orig-${camelToKebabCase(attr)}`);
const isPreserved = (el, attr) => el.dataset[origValueKey(attr)] !== void 0;
const preserveAttrValue = (el, attr) => el.dataset[origValueKey(attr)] = el[kebabToCamelCase(attr)];
const restoreAttrValue = (el, attr) => {
const value = el.dataset[origValueKey(attr)];
attr === CLASS_ATTR ? el.className = value : el.setAttribute(attr, value);
};
for (const [query_input, changes] of Object.entries(detail)) {
const query = QUERY[query_input] || query_input;
const elements = document.querySelectorAll(query);
elements.forEach((el) => changes === "i" ? resetElement(el) : applyToElement(el, changes));
}
function resetElement(el) {
Object.keys(el.dataset).filter((k) => k.includes("orig")).forEach((k) => {
const attr = camelToKebabCase(k).replace("orig-", "");
restoreAttrValue(el, attr);
});
}
function applyToElement(el, changes) {
changes.forEach(function(change) {
const [action, attr_input, value] = change;
const attr = ATTR[attr_input] || attr_input;
!isPreserved(el, attr) && preserveAttrValue(el, attr);
if (attr === CLASS_ATTR) {
switch (action) {
case "s":
el.className = value;
break;
case "a":
el.classList.add(value);
break;
case "r":
el.classList.remove(value);
break;
case "t":
el.classList.toggle(value);
break;
case "i":
restoreAttrValue(el, attr);
break;
default:
null;
}
} else {
switch (action) {
case "s":
el.setAttribute(attr, value);
break;
case "r":
el.removeAttribute(attr);
break;
case "i":
restoreAttrValue(el, attr);
break;
case "d":
const dynAttr = kebabToCamelCase(`dynamic-${attr}`);
const [prefix, suffix] = el.dataset[dynAttr].split("{dynamic}");
el.setAttribute(attr, `${prefix}${value}${suffix}`);
break;
default:
null;
}
}
});
}
;
});
//# sourceMappingURL=phoenix_live_head.cjs.js.map