@ea-lab/reactive-json
Version:
A REACT-based lib that transforms JSON (or YAML) into interactive HTML markup.
59 lines (58 loc) • 2.14 kB
JavaScript
import { useContext as y, useEffect as E } from "react";
import { GlobalDataContext as D } from "../../engine/GlobalDataContext.js";
import { TemplateContext as O } from "../../engine/TemplateContext.js";
import { evaluateTemplateValue as P } from "../../engine/TemplateSystem.js";
const q = (i) => {
const x = y(D), b = y(O), { attributesHolderRef: l } = i, { name: o, value: m, separator: u = " ", keepAttributeWhenEmpty: V = !1 } = i.actionProps || {};
return E(() => {
if (!(l != null && l.current) || !o || m === void 0)
return;
const p = P({
valueToEvaluate: m,
globalDataContext: x,
templateContext: b
}), g = ((i.componentProps || {}).attributes || {})[o] || "", d = g ? g.split(u).filter((e) => e.trim() !== "") : [];
let n = [...d];
if (Array.isArray(p)) {
const e = p.map((t) => String(t));
if (e.length === 0)
return;
if (e.length === 1) {
const t = e[0], a = n.indexOf(t);
a > -1 ? n.splice(a, 1) : t !== "" && n.push(t);
} else {
let t = -1, a = -1;
for (let s = 0; s < e.length; s++) {
const f = e[s], v = n.indexOf(f);
if (v > -1) {
t = v, a = s;
break;
}
}
if (t > -1) {
const s = (a + 1) % e.length, f = e[s];
n.splice(t, 1), f !== "" && n.push(f);
} else {
const s = e[0];
s !== "" && n.push(s);
}
}
} else {
const e = String(p), t = n.indexOf(e);
t > -1 ? n.splice(t, 1) : n.push(e);
}
const c = l.current, A = c.getAttribute(o) || "", I = A ? A.split(u).filter((e) => e.trim() !== "") : [], T = d.filter((e) => !n.includes(e)), C = n.filter((e) => !d.includes(e));
let r = [...I];
T.forEach((e) => {
const t = r.indexOf(e);
t > -1 && r.splice(t, 1);
}), C.forEach((e) => {
r.includes(e) || r.push(e);
});
const h = r.join(u);
h.trim() === "" ? V ? c.setAttribute(o, "") : c.removeAttribute(o) : c.setAttribute(o, h);
}, [o, m, u, V, x.data, b, l]), i.children;
};
export {
q as ToggleAttributeValue
};