From 10000da833b222091c3220e55ee06bb9b18f0052 Mon Sep 17 00:00:00 2001 From: dpilafian Date: Thu, 20 Jun 2024 02:37:18 -0700 Subject: [PATCH] Add convenience function libX.dom.componentState() --- src/js/lib-x.ts | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/js/lib-x.ts b/src/js/lib-x.ts index 731b669..8ee1bf7 100644 --- a/src/js/lib-x.ts +++ b/src/js/lib-x.ts @@ -68,6 +68,17 @@ const libXDom = { libX.dom.forEach(clone.getElementsByClassName('libx-state'), copy); return clone; }, + componentState(elem: Element) { + const component = libX.ui.getComponent(elem); + libX.util.assert(component, 'Component not found for element', elem); + return libX.dom.state(component!); + }, + removeState(elem: Element): Element { + const data = (elem).dataset; + if (data.libXState) + libX.dom.stateDepot[Number(data.libXState)] = {}; + return elem; + }, create(tag: K, options?: { id?: string, subTags?: string[], class?: string, href?: string, html?: string, name?: string, rel?: string, src?: string, text?: string, type?: string }) { const elem = globalThis.document.createElement(tag); if (options?.id) @@ -93,12 +104,6 @@ const libXDom = { subTag => elem.appendChild(globalThis.document.createElement(subTag))); return elem; }, - removeState(elem: Element): Element { - const data = (elem).dataset; - if (data.libXState) - libX.dom.stateDepot[Number(data.libXState)] = {}; - return elem; - }, select(selector: string): HTMLElement | null { return globalThis.document.body.querySelector(selector); }, @@ -632,6 +637,11 @@ const libXUi = { }; return forkMe ? wrap() : null; }, + getComponent(elem: Element): Element | null { + // Returns the component (container element with a data-component attribute) to + // which the element belongs. + return elem?.closest('[data-component]') ?? null; + }, }; const libXUtil = { @@ -650,6 +660,12 @@ const libXUtil = { // libX.util.removeWhitespace('a b \t\n c') === 'abc'; return text.replace(/\s/g, ''); }, + assert(ok: boolean | unknown, message: string, info: unknown): void { + // Oops, file a tps report. + const quoteStr = (info: unknown) => typeof info === 'string' ? `"${info}"` : String(info); + if (!ok) + throw Error(`[dna-engine] ${message} --> ${quoteStr(info)}`); + }, }; const libXNav = {