@ruledwdl/dom 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -1
- package/dist/wdl-dom.min.js +2 -2
- package/package.json +1 -1
- package/src/index.js +737 -169
package/README.md
CHANGED
|
@@ -136,9 +136,17 @@ hero.registry.addRule({
|
|
|
136
136
|
|
|
137
137
|
### Instance Methods
|
|
138
138
|
- `dom.remount()`: Rebuild the entire DOM from state snapshot.
|
|
139
|
-
- `dom.getLiveMap()`: Returns a snapshot copy of `Map<semanticId, HTMLElement
|
|
139
|
+
- `dom.getLiveMap()`: Returns a snapshot copy of `Map<semanticId, HTMLElement>` (first element per semantic ID).
|
|
140
|
+
- `dom.getLiveNodes(semanticId)`: Returns an array of all live elements matching `semanticId` (e.g. repeated loop rows).
|
|
141
|
+
- `dom.getNode(semanticId, index = 0)`: Returns the live element at the specified index for `semanticId`.
|
|
140
142
|
- `dom.destroy()`: Removes event listeners, empties container, and cleans up style tags.
|
|
141
143
|
|
|
144
|
+
### Repeated Loops & Surgical Data Reconciliation
|
|
145
|
+
`@ruledwdl/dom` natively reconciles repeated WDL loop layers (e.g. `li.feature*features`) without remounting or wiping `innerHTML`:
|
|
146
|
+
- Materializes all items on initial mount with `data-wdl-index="0"`, `data-wdl-index="1"`, etc.
|
|
147
|
+
- Resolves per-item attribute templates (e.g. `${text}`, `${_index}`).
|
|
148
|
+
- On `component.data.set('features', nextItems)`, surgically updates retained rows, appends added rows, and removes deleted rows.
|
|
149
|
+
|
|
142
150
|
---
|
|
143
151
|
|
|
144
152
|
## License
|
package/dist/wdl-dom.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var f=new Set(["text","class","html"]);function p(l){if(typeof l!="string"){if(l&&typeof l=="object")return{tag:String(l.tag||"div").toLowerCase(),semanticId:String(l.semanticId||l.id||"").replace(/^\./,"")};throw new Error("[wdl-dom] invalid layer expression")}let e=l.trim(),i=e.match(/^([a-zA-Z][a-zA-Z0-9_-]*)(?:\.([a-zA-Z0-9_-]+))?$/);return i?{tag:i[1].toLowerCase(),semanticId:(i[2]||"").replace(/^\./,"")}:{tag:e.toLowerCase()||"div",semanticId:""}}function g(l){if(Array.isArray(l))return structuredClone(l);if(typeof l!="string"||!l.trim())return[];let e={tag:"__root__",semanticId:"",children:[]},i=[e],s=0,a=()=>i[i.length-1];for(;s<l.length;){let t=l[s];if(/\s/.test(t)){s++;continue}if(t===">"){let r=a().children[a().children.length-1];r&&i.push(r),s++;continue}if(t==="+"){s++;continue}if(t==="<"){s++,i.length>1&&i.pop();continue}let n="";for(;s<l.length&&/[a-zA-Z0-9_-]/.test(l[s]);)n+=l[s++];let o="";if(l[s]===".")for(s++;s<l.length&&/[a-zA-Z0-9_-]/.test(l[s]);)o+=l[s++];a().children.push({tag:n.toLowerCase()||"div",semanticId:o,children:[]})}return e.children}function h(l){return l==null?"":String(l).replace(/^\./,"")}var m=class{constructor(e={}){let{container:i,component:s,onDataBind:a=null,styleTarget:t=typeof document<"u"?document.head:null,debug:n=!1}=e;if(!i)throw new Error("[wdl-dom] container is required");if(!s)throw new Error("[wdl-dom] component (ComponentState) is required");if(this.container=typeof i=="string"?document.querySelector(i):i,!this.container)throw new Error("[wdl-dom] container not found");this.component=s,this.onDataBind=a,this.styleTarget=t,this.debug=n,this.liveMap=new Map,this._unsubs=[],this._styleEl=null,this._mount(),this._bindStateEvents()}remount(){this._mount()}getLiveMap(){return new Map(this.liveMap)}destroy(){this._unsubs.forEach(e=>{try{e()}catch{}}),this._unsubs=[],this.container.replaceChildren(),this.liveMap.clear(),this._styleEl&&this._styleEl.parentNode&&this._styleEl.parentNode.removeChild(this._styleEl),this._styleEl=null}_mount(){this.container.replaceChildren(),this.liveMap.clear();let e;try{e=typeof this.component.layers?.tree=="function"?this.component.layers.tree():g(this.component.layers?.list?.()??this.component.getSnapshot?.()?.layers)}catch(s){this._log("warn","tree() failed, falling back to simple parse",s);let a=this.component.getSnapshot?.()?.layers??"";e=g(a)}Array.isArray(e)||(e=[]);for(let s of e){let a=this._createElementFromNode(s);this.container.appendChild(a)}let i=this.component.attr?.list?.()??this.component.getSnapshot?.()?.attr??{};for(let[s,a]of Object.entries(i))this._applyAttrs(h(s),a);this._applyRootVariant(),this._syncRegistryStyles(),this._log("mount",`mounted ${this.liveMap.size} nodes`)}_createElementFromNode(e){let i=(e.tag||"div").toLowerCase(),s=h(e.semanticId||e.id||""),a=document.createElement(i);if(s&&(a.classList.add(s),a.setAttribute("wdl-comp",s),this.liveMap.set(s,a)),Array.isArray(e.children))for(let t of e.children)a.appendChild(this._createElementFromNode(t));return a}_bindStateEvents(){let e=this.component;if(typeof e.on!="function"){this._log("warn","component has no .on() \u2014 events will not be applied");return}let i=a=>this._onStateEvent(a),s=["layers:change","attr:change","data:change","variant:change","registry:change"];for(let a of s){let t=e.on(a,i);typeof t=="function"?this._unsubs.push(t):this._unsubs.push(()=>e.off?.(a,i))}}_onStateEvent(e){if(!(!e||!e.type))switch(this._log("event",e.type,e.action,e.targetId,e.payload),e.type){case"layers:change":this._handleLayers(e);break;case"attr:change":this._handleAttr(e);break;case"data:change":this._handleData(e);break;case"variant:change":this._handleVariant(e);break;case"registry:change":this._handleRegistry(e);break;default:this._log("warn","unknown event type",e.type)}}_handleLayers(e){let{action:i,targetId:s,payload:a}=e,t=h(s);switch(i){case"set":{this._mount();break}case"append":{let n=this.liveMap.get(t);if(!n){this._log("warn",`append: parent "${t}" not in liveMap \u2014 remounting`),this._mount();return}let o=p(a),r=this._createElementFromNode({tag:o.tag,semanticId:o.semanticId,children:[]});n.appendChild(r),this._log("op",`append <${o.tag}.${o.semanticId}> \u2192 #${t}`);break}case"prepend":{let n=this.liveMap.get(t);if(!n){this._log("warn",`prepend: parent "${t}" not in liveMap \u2014 remounting`),this._mount();return}let o=p(a),r=this._createElementFromNode({tag:o.tag,semanticId:o.semanticId,children:[]});n.insertBefore(r,n.firstChild),this._log("op",`prepend <${o.tag}.${o.semanticId}> \u2192 #${t}`);break}case"before":case"after":{let n=this.liveMap.get(t);if(!n||!n.parentNode){this._log("warn",`${i}: target "${t}" missing \u2014 remounting`),this._mount();return}let o=p(a),r=this._createElementFromNode({tag:o.tag,semanticId:o.semanticId,children:[]});i==="before"?n.parentNode.insertBefore(r,n):n.parentNode.insertBefore(r,n.nextSibling),this._log("op",`${i} <${o.tag}.${o.semanticId}> relative to #${t}`);break}case"wrap":{let n=this.liveMap.get(t);if(!n||!n.parentNode){this._log("warn",`wrap: target "${t}" missing \u2014 remounting`),this._mount();return}let o=p(a),r=this._createElementFromNode({tag:o.tag,semanticId:o.semanticId,children:[]});n.parentNode.insertBefore(r,n),r.appendChild(n),this._log("op",`wrap #${t} with <${o.tag}.${o.semanticId}>`);break}case"unwrap":{let n=this.liveMap.get(t);if(!n||!n.parentNode){this._log("warn",`unwrap: target "${t}" missing \u2014 remounting`),this._mount();return}let o=n.parentNode;for(;n.firstChild;)o.insertBefore(n.firstChild,n);n.remove(),this.liveMap.delete(t),this._log("op",`unwrap #${t}`);break}case"move":{let n=this.liveMap.get(t),{targetSemanticId:o,position:r}=a||{},c=h(o),d=this.liveMap.get(c);if(!n||!d){this._log("warn",`move: source "${t}" or target "${c}" missing \u2014 remounting`),this._mount();return}r==="before"?d.parentNode?.insertBefore(n,d):r==="after"?d.parentNode?.insertBefore(n,d.nextSibling):d.appendChild(n),this._log("op",`move #${t} -> ${r} #${c}`);break}case"remove":{let n=this.liveMap.get(t);if(!n){this._log("warn",`remove: #${t} not in liveMap`);return}for(let[o,r]of[...this.liveMap])o!==t&&n.contains(r)&&this.liveMap.delete(o);n.remove(),this.liveMap.delete(t),this._log("op",`remove #${t}`);break}case"update":{let n=this.liveMap.get(t);if(!n){this._log("warn",`update: #${t} missing \u2014 remounting`),this._mount();return}let o=a||{};if(o.tag&&o.tag.toLowerCase()!==n.tagName.toLowerCase()){let r=document.createElement(String(o.tag).toLowerCase());for(let c of n.attributes)r.setAttribute(c.name,c.value);for(;n.firstChild;)r.appendChild(n.firstChild);if(n.parentNode?.replaceChild(r,n),this.liveMap.set(t,r),o.semanticId&&h(o.semanticId)!==t){let c=h(o.semanticId);r.classList.remove(t),r.classList.add(c),r.setAttribute("wdl-comp",c),this.liveMap.delete(t),this.liveMap.set(c,r)}}else if(o.semanticId&&h(o.semanticId)!==t){let r=h(o.semanticId);n.classList.remove(t),n.classList.add(r),n.setAttribute("wdl-comp",r),this.liveMap.delete(t),this.liveMap.set(r,n)}this._log("op",`update #${t}`,o);break}default:this._log("warn",`layers: unknown action "${i}" \u2014 remounting`),this._mount()}}_handleAttr(e){let{action:i,targetId:s,payload:a}=e,t=h(s);if(i==="set"||i==="update"){this._applyAttrs(t,a||{}),this._log("op",`attr.${i} #${t}`,a);return}if(i==="remove"){let n=this.liveMap.get(t);if(!n)return;let o=a;o==null||o===""?(n.textContent="",n.className=t,this._log("op",`attr.remove entire #${t}`)):o==="text"?(n.textContent="",this._log("op",`attr.remove text from #${t}`)):o==="class"?(n.className=t,this._log("op",`attr.remove class from #${t}`)):o==="html"?(n.innerHTML="",this._log("op",`attr.remove html from #${t}`)):(n.removeAttribute(o),this._log("op",`attr.remove ${o} from #${t}`))}}_applyAttrs(e,i){if(!i||typeof i!="object")return;let s=this.liveMap.get(e);if(!s){this._log("warn",`attr: #${e} not in liveMap`);return}if(i.text!==void 0&&(s.textContent=String(i.text)),i.html!==void 0&&(s.innerHTML=String(i.html)),i.class!==void 0){let a=String(i.class).trim();s.className=a?`${e} ${a}`:e}for(let[a,t]of Object.entries(i))if(!f.has(a)){if(a==="style"&&t&&typeof t=="object"){Object.assign(s.style,t);continue}t==null?s.removeAttribute(a):s.setAttribute(a,String(t))}}_handleData(e){let{action:i,targetId:s,payload:a}=e,t=s||"";if(typeof this.onDataBind=="function")try{this.onDataBind(this.container,t,i==="remove"?void 0:a)}catch(n){this._log("warn","onDataBind error",n)}this._log("op",`data.${i} ${t}`,i==="remove"?void 0:a)}_handleVariant(e){let{targetId:i,payload:s}=e,a=h(i)||this._rootSemanticId(),t=this.liveMap.get(a);if(!t){let n=this._rootSemanticId(),o=n?this.liveMap.get(n):null;o&&(s?o.dataset.variant=String(s):delete o.dataset.variant,this._log("op",`variant \u2192 ${s||"(none)"} on #${n}`));return}s?t.dataset.variant=String(s):delete t.dataset.variant,this._log("op",`variant \u2192 ${s||"(none)"} on #${a}`)}_applyRootVariant(){let e=this.component.attr?.list?.()??this.component.getSnapshot?.()?.attr??{},i=this._rootSemanticId();if(!i)return;let s="."+i,a=e[s]?.["data-variant"]??e["."]?.["data-variant"]??null;a&&this.liveMap.has(i)&&(this.liveMap.get(i).dataset.variant=String(a))}_rootSemanticId(){for(let[i,s]of this.liveMap)if(s.parentNode===this.container)return i;let e=this.liveMap.keys().next();return e.done?"":e.value}_handleRegistry(e){this._syncRegistryStyles(),this._log("op",`registry.${e.action}`)}_syncRegistryStyles(){if(!this.styleTarget)return;let e=this.component.registry?.get?.()??this.component.getSnapshot?.()?.registry??null,i=this.component.id||this.component.getSnapshot?.()?.id||"comp";if(this._styleEl||(this._styleEl=document.createElement("style"),this._styleEl.setAttribute("data-wdl-dom",i),this.styleTarget.appendChild(this._styleEl)),!e){this._styleEl.textContent="";return}let s=Array.isArray(e.rules)?e.rules:[],a=[];if(e.vars&&typeof e.vars=="object"){let t=Object.entries(e.vars).map(([n,o])=>`--${n}: ${o};`).join(" ");t&&a.push(`:root, [wdl-comp] { ${t} }`)}for(let t of s){if(!t||!t.selector)continue;let n=typeof t.css=="string"?t.css:t.css&&typeof t.css=="object"?Object.entries(t.css).map(([c,d])=>`${u(c)}: ${d};`).join(" "):"";if(!n)continue;let o=t.selector.startsWith("&")?t.selector.replace("&",`[wdl-comp="${i}"]`):t.selector,r=t.media?`@media ${t.media} { ${o} { ${n} } }`:`${o} { ${n} }`;a.push(r)}this._styleEl.textContent=a.join(`
|
|
2
|
-
`)}_log(e,...
|
|
1
|
+
var S=new Set(["text","class","html","alpine","htmx","attr-ref"]);function y(c,e){return!e||c==null?c??"":String(e).split(".").reduce((s,t)=>s!=null?s[t]:"",c)??""}function m(c,e){return typeof c!="string"?c:c.replace(/\$\{([\w.]+)\}/g,(s,t)=>{let o=y(e,t);return o!=null?String(o):""}).replace(/\{\{([\w.]+)\}\}/g,(s,t)=>{let o=y(e,t);return o!=null?String(o):""})}function _(c,e){return c==null?c:typeof c=="function"?"":typeof c=="string"?m(c,e):Array.isArray(c)?c.map(s=>_(s,e)):typeof c=="object"?Object.fromEntries(Object.entries(c).map(([s,t])=>[s,_(t,e)])):c}function w(c){if(typeof c!="string"){if(c&&typeof c=="object")return{tag:String(c.tag||"div").toLowerCase(),semanticId:String(c.semanticId||c.id||"").replace(/^\./,""),repeator:c.repeator||c.loopKey||null};throw new Error("[wdl-dom] invalid layer expression")}let s=c.trim(),t=null,o=s.indexOf("*");o!==-1&&(t=s.slice(o+1),s=s.slice(0,o));let n=s.match(/^([a-zA-Z][a-zA-Z0-9_-]*)(?:\.([a-zA-Z0-9_-]+))?$/);return n?{tag:n[1].toLowerCase(),semanticId:(n[2]||"").replace(/^\./,""),repeator:t}:{tag:s.toLowerCase()||"div",semanticId:"",repeator:t}}function N(c){if(Array.isArray(c))return structuredClone(c);if(typeof c!="string"||!c.trim())return[];let e={tag:"__root__",semanticId:"",children:[]},s=[e],t=0,o=()=>s[s.length-1];for(;t<c.length;){let n=c[t];if(/\s/.test(n)){t++;continue}if(n===">"){let a=o().children[o().children.length-1];a&&s.push(a),t++;continue}if(n==="+"){t++;continue}if(n==="<"){if(t++,t<c.length&&c[t]==="*"){t++;let a="";for(;t<c.length&&/\d/.test(c[t]);)a+=c[t++];let h=a?parseInt(a,10):1;for(let d=0;d<h;d++)s.length>1&&s.pop()}else if(t<c.length&&c[t]==="@"){t++;let a="";for(;t<c.length&&/\d/.test(c[t]);)a+=c[t++];let d=(a?parseInt(a,10):0)+1;for(;s.length>d&&s.length>1;)s.pop()}else{let a=1;for(;t<c.length&&c[t]==="<";)a++,t++;for(let h=0;h<a;h++)s.length>1&&s.pop()}continue}let r="";for(;t<c.length&&/[a-zA-Z0-9_-]/.test(c[t]);)r+=c[t++];let i="";if(c[t]===".")for(t++;t<c.length&&/[a-zA-Z0-9_-]/.test(c[t]);)i+=c[t++];let l=null;if(c[t]==="*"){t++;let a="";for(;t<c.length&&/[a-zA-Z0-9_.]/.test(c[t]);)a+=c[t++];a&&(l=a)}o().children.push({tag:r.toLowerCase()||"div",semanticId:i,repeator:l,children:[]})}return e.children}function u(c){return c==null?"":String(c).replace(/^\./,"")}var C=class{constructor(e={}){let{container:s,component:t,onDataBind:o=null,styleTarget:n=typeof document<"u"?document.head:null,debug:r=!1}=e;if(!s)throw new Error("[wdl-dom] container is required");if(!t)throw new Error("[wdl-dom] component (ComponentState) is required");if(this.container=typeof s=="string"?document.querySelector(s):s,!this.container)throw new Error("[wdl-dom] container not found");this.component=t,this.onDataBind=o,this.styleTarget=n,this.debug=r,this.liveMap=new Map,this.liveNodes=new Map,this._loopBindings=[],this._unsubs=[],this._styleEl=null,this._mount(),this._bindStateEvents()}remount(){this._mount()}getLiveMap(){return new Map(this.liveMap)}getLiveNodes(e){let s=u(e);return[...this.liveNodes.get(s)||[]]}getNode(e,s=0){return this.getLiveNodes(e)[s]||null}destroy(){this._unsubs.forEach(e=>{try{e()}catch{}}),this._unsubs=[],this.container.replaceChildren(),this.liveMap.clear(),this.liveNodes.clear(),this._loopBindings=[],this._styleEl&&this._styleEl.parentNode&&this._styleEl.parentNode.removeChild(this._styleEl),this._styleEl=null}_registerNode(e,s){if(!e)return;let t=u(e);this.liveNodes.has(t)||this.liveNodes.set(t,[]);let o=this.liveNodes.get(t);o.includes(s)||o.push(s),this.liveMap.set(t,o[0])}_unregisterNode(e,s){if(!e)return;let t=u(e);if(this.liveNodes.has(t)){let o=this.liveNodes.get(t),n=o.indexOf(s);n!==-1&&o.splice(n,1),o.length===0?(this.liveNodes.delete(t),this.liveMap.delete(t)):this.liveMap.set(t,o[0])}else this.liveMap.delete(t)}_unregisterElementHierarchy(e){if(!e)return;let s=e.getAttribute?.("wdl-comp");if(s&&this._unregisterNode(s,e),Array.isArray(e.children))for(let t of e.children)this._unregisterElementHierarchy(t)}_getComponentData(){return this.component.data?.get?.()??this.component.getSnapshot?.()?.data??{}}_getComponentAttrMap(){return this.component.attr?.list?.()??this.component.getSnapshot?.()?.attr??{}}_getComponentRegistry(){return this.component.registry?.get?.()??this.component.getSnapshot?.()?.registry??{}}_getRegistryClasses(e,s,t,o){let n=this._getComponentRegistry();if(!n||typeof n!="object")return"";let r=(e?n[e]||n["."+e]:null)||(s?n[s]:null);if(!r)return"";if(typeof r=="string")return m(r,t);if(typeof r!="object"||r===null)return"";let i=[];typeof r.base=="string"&&r.base?i.push(m(r.base,t)):typeof r.class=="string"&&r.class&&i.push(m(r.class,t));let l=o?.dataset?.variant||o?.getAttribute?.("data-variant")||this.component.variant?.get?.(e)||r.defaultVariant||null;if(l&&r.variants&&typeof r.variants=="object"){let a=r.variants[l];typeof a=="string"&&a&&i.push(m(a,t))}if(r.states&&typeof r.states=="object"){for(let[a,h]of Object.entries(r.states))if(typeof h=="string"&&h){let p=m(h,t).split(/\s+/).filter(Boolean).map(f=>f.includes(":")?f:`${a}:${f}`).join(" ");i.push(p)}}if(r.breakpoints&&typeof r.breakpoints=="object"){for(let[a,h]of Object.entries(r.breakpoints))if(typeof h=="string"&&h){let p=m(h,t).split(/\s+/).filter(Boolean).map(f=>f.includes(":")?f:`${a}:${f}`).join(" ");i.push(p)}}return i.filter(Boolean).join(" ")}_resolveLoopItems(e,s){if(!e)return[];if(/^\d+$/.test(String(e))){let o=parseInt(e,10);return Array.from({length:Math.max(0,o)},(n,r)=>({_index:r}))}let t=y(s,e);return Array.isArray(t)?t:typeof t=="number"?Array.from({length:Math.max(0,t)},(o,n)=>({_index:n})):[]}_createItemScope(e,s,t){let o=t||this._getComponentData();return typeof e=="object"&&e!==null?{...o,...e,item:e,_index:s}:{...o,value:e,item:e,_index:s}}_mount(){this.container.replaceChildren(),this.liveMap.clear(),this.liveNodes.clear(),this._loopBindings=[];let e;try{e=typeof this.component.layers?.tree=="function"?this.component.layers.tree():N(this.component.layers?.list?.()??this.component.getSnapshot?.()?.layers)}catch(t){this._log("warn","tree() failed, falling back to simple parse",t);let o=this.component.getSnapshot?.()?.layers??"";e=N(o)}Array.isArray(e)||(e=[]);let s=this._getComponentData();for(let t of e)this._mountLayerNode(this.container,t,s);this._applyRootVariant(),this._syncRegistryStyles(),this._log("mount",`mounted ${this.liveMap.size} semantic keys, ${this._loopBindings.length} loops`)}_mountLayerNode(e,s,t){if(s.repeator){let n=this._resolveLoopItems(s.repeator,t),r=[];for(let l=0;l<n.length;l++){let a=this._createItemScope(n[l],l,t),h=this._createSingleElement(s,a,l);e.appendChild(h),r.push(h)}let i=null;typeof document.createComment=="function"&&(i=document.createComment(`wdl-loop:${s.repeator}`),e.appendChild(i)),this._loopBindings.push({parentEl:e,node:s,repeator:s.repeator,elements:r,anchor:i});return}let o=this._createSingleElement(s,t);e.appendChild(o)}_createSingleElement(e,s,t){let o=(e.tag||"div").toLowerCase(),n=u(e.semanticId||e.id||""),r=document.createElement(o);n&&(r.classList.add(n),r.setAttribute("wdl-comp",n),this._registerNode(n,r));let i=t!==void 0?t:s?._index;if(i!==void 0){let l=String(i);r.setAttribute("data-wdl-index",l),r.dataset&&(r.dataset.wdlIndex=l)}if(this._applyNodeAttrs(r,e,s),Array.isArray(e.children))for(let l of e.children)this._mountLayerNode(r,l,s);return r}_applyNodeAttrs(e,s,t){let o=this._getComponentAttrMap(),n=u(s.semanticId||s.id||""),r=(s.tag||"div").toLowerCase(),i=o[r]||{},l=n?o["."+n]||{}:{},a=n?o[n]||{}:{},h={...i,...l,...a},d=_(h,t),p=this._getRegistryClasses(n,r,t,e),f=typeof d.class=="string"?d.class:"",g=[n,p,f].filter(Boolean).join(" ").split(/\s+/).filter(Boolean),b=Array.from(new Set(g)).join(" ");this._applyPropsToElement(e,n,{...d,class:b})}_refreshElementClasses(e,s){if(!e)return;let t=u(s||e.getAttribute("wdl-comp")||""),o=this._getComponentData(),n=this._getComponentAttrMap(),r=(e.tagName||"div").toLowerCase(),i=e.getAttribute("data-wdl-index"),l=o;if(i!=null){let v=parseInt(i,10),E=this._findLoopForElement(e);if(E){let A=y(o,E.repeator);Array.isArray(A)&&A[v]!==void 0?l=this._createItemScope(A[v],v,o):l={...o,_index:v}}else l={...o,_index:v}}let a=n[r]||{},h=t?n["."+t]||{}:{},d=t?n[t]||{}:{},p={...a,...h,...d},f=_(p,l),g=this._getRegistryClasses(t,r,l,e),b=typeof f.class=="string"?f.class:"",$=[t,g,b].filter(Boolean).join(" ").split(/\s+/).filter(Boolean);e.className=Array.from(new Set($)).join(" ")}_refreshAllElementClasses(){for(let[e,s]of this.liveNodes)for(let t of s)this._refreshElementClasses(t,e)}_applyPropsToElement(e,s,t){if(!(!t||typeof t!="object")){t.text!==void 0&&(e.textContent=String(t.text)),t.html!==void 0&&(e.innerHTML=String(t.html)),t.class!==void 0&&(e.className=String(t.class).trim());for(let[o,n]of Object.entries(t))if(!S.has(o)){if(o==="style"&&n&&typeof n=="object"){Object.assign(e.style,n);continue}n==null?e.removeAttribute(o):e.setAttribute(o,String(n))}}}_bindStateEvents(){let e=this.component;if(typeof e.on!="function"){this._log("warn","component has no .on() \u2014 events will not be applied");return}let s=o=>this._onStateEvent(o),t=["layers:change","attr:change","data:change","variant:change","registry:change"];for(let o of t){let n=e.on(o,s);typeof n=="function"?this._unsubs.push(n):this._unsubs.push(()=>e.off?.(o,s))}}_onStateEvent(e){if(!(!e||!e.type))switch(this._log("event",e.type,e.action,e.targetId,e.payload),e.type){case"layers:change":this._handleLayers(e);break;case"attr:change":this._handleAttr(e);break;case"data:change":this._handleData(e);break;case"variant:change":this._handleVariant(e);break;case"registry:change":this._handleRegistry(e);break;default:this._log("warn","unknown event type",e.type)}}_handleLayers(e){let{action:s,targetId:t,payload:o}=e,n=u(t),r=this._getComponentData();switch(s){case"set":{this._mount();break}case"append":{let i=this.getNode(n);if(!i){this._log("warn",`append: parent "${n}" not in liveMap \u2014 remounting`),this._mount();return}let l=w(o);this._mountLayerNode(i,l,r),this._log("op",`append <${l.tag}.${l.semanticId}> \u2192 #${n}`);break}case"prepend":{let i=this.getNode(n);if(!i){this._log("warn",`prepend: parent "${n}" not in liveMap \u2014 remounting`),this._mount();return}let l=w(o),a=this._createSingleElement(l,r);i.insertBefore(a,i.firstChild),this._log("op",`prepend <${l.tag}.${l.semanticId}> \u2192 #${n}`);break}case"before":case"after":{let i=this.getNode(n);if(!i||!i.parentNode){this._log("warn",`${s}: target "${n}" missing \u2014 remounting`),this._mount();return}let l=w(o),a=this._createSingleElement(l,r);s==="before"?i.parentNode.insertBefore(a,i):i.parentNode.insertBefore(a,i.nextSibling),this._log("op",`${s} <${l.tag}.${l.semanticId}> relative to #${n}`);break}case"wrap":{let i=this.getNode(n);if(!i||!i.parentNode){this._log("warn",`wrap: target "${n}" missing \u2014 remounting`),this._mount();return}let l=w(o),a=this._createSingleElement(l,r);i.parentNode.insertBefore(a,i),a.appendChild(i),this._log("op",`wrap #${n} with <${l.tag}.${l.semanticId}>`);break}case"unwrap":{let i=this.getNode(n);if(!i||!i.parentNode){this._log("warn",`unwrap: target "${n}" missing \u2014 remounting`),this._mount();return}let l=i.parentNode;for(;i.firstChild;)l.insertBefore(i.firstChild,i);this._unregisterElementHierarchy(i),i.remove(),this._log("op",`unwrap #${n}`);break}case"move":{let i=this.getNode(n),{targetSemanticId:l,position:a}=o||{},h=u(l),d=this.getNode(h);if(!i||!d){this._log("warn",`move: source "${n}" or target "${h}" missing \u2014 remounting`),this._mount();return}a==="before"?d.parentNode?.insertBefore(i,d):a==="after"?d.parentNode?.insertBefore(i,d.nextSibling):d.appendChild(i),this._log("op",`move #${n} -> ${a} #${h}`);break}case"remove":{let i=this.getLiveNodes(n);if(i.length===0){this._log("warn",`remove: #${n} not in liveMap`);return}for(let l of i)this._unregisterElementHierarchy(l),l.remove();this._loopBindings=this._loopBindings.filter(l=>l.node.semanticId!==n),this._log("op",`remove #${n}`);break}case"update":{let i=this.getNode(n);if(!i){this._log("warn",`update: #${n} missing \u2014 remounting`),this._mount();return}let l=o||{};if(l.tag&&l.tag.toLowerCase()!==i.tagName.toLowerCase()){let a=document.createElement(String(l.tag).toLowerCase());for(let d of i.attributes)a.setAttribute(d.name,d.value);for(;i.firstChild;)a.appendChild(i.firstChild);i.parentNode?.replaceChild(a,i),this._unregisterNode(n,i);let h=l.semanticId?u(l.semanticId):n;l.semanticId&&h!==n&&(a.classList.remove(n),a.classList.add(h),a.setAttribute("wdl-comp",h)),this._registerNode(h,a)}else if(l.semanticId&&u(l.semanticId)!==n){let a=u(l.semanticId);i.classList.remove(n),i.classList.add(a),i.setAttribute("wdl-comp",a),this._unregisterNode(n,i),this._registerNode(a,i)}this._log("op",`update #${n}`,l);break}default:this._log("warn",`layers: unknown action "${s}" \u2014 remounting`),this._mount()}}_handleAttr(e){let{action:s,targetId:t,payload:o}=e,n=u(t);if(s==="set"||s==="update"){let r=this.getLiveNodes(n);if(r.length===0){this._log("warn",`attr: #${n} not in liveMap`);return}let i=this._getComponentData();for(let l of r){let a=l.getAttribute("data-wdl-index"),h=i;if(a!=null){let p=parseInt(a,10),f=this._findLoopForElement(l);if(f){let g=y(i,f.repeator);Array.isArray(g)&&g[p]!==void 0?h=this._createItemScope(g[p],p,i):h={...i,_index:p}}else h={...i,_index:p}}let d=_(o||{},h);this._applyPropsToElement(l,n,d)}this._log("op",`attr.${s} #${n}`,o);return}if(s==="remove"){let r=this.getLiveNodes(n);if(r.length===0)return;let i=o;for(let l of r)i==null||i===""?(l.textContent="",l.className=n):i==="text"?l.textContent="":i==="class"?l.className=n:i==="html"?l.innerHTML="":l.removeAttribute(i);this._log("op",`attr.remove ${i||"all"} from #${n}`)}}_applyAttrs(e,s){let t=this.getLiveNodes(e);if(t.length===0){this._log("warn",`attr: #${e} not in liveMap`);return}let o=this._getComponentData();for(let n of t){let r=n.getAttribute("data-wdl-index"),i=o;if(r!=null){let a=parseInt(r,10),h=this._findLoopForElement(n);if(h){let d=y(o,h.repeator);Array.isArray(d)&&d[a]!==void 0?i=this._createItemScope(d[a],a,o):i={...o,_index:a}}}let l=_(s||{},i);this._applyPropsToElement(n,e,l)}}_findLoopForElement(e){return this._loopBindings.find(s=>s.elements.includes(e))||null}_handleData(e){let{action:s,targetId:t,payload:o}=e,n=t||"",r=this._getComponentData();if(this._reconcileLoops(n,r),this._reconcileStaticDataBindings(n,r),typeof this.onDataBind=="function")try{this.onDataBind(this.container,n,s==="remove"?void 0:o)}catch(i){this._log("warn","onDataBind error",i)}this._log("op",`data.${s} ${n}`,s==="remove"?void 0:o)}_reconcileLoops(e,s){for(let t of this._loopBindings){if(!(!e||t.repeator===e||e.startsWith(t.repeator+".")||t.repeator.startsWith(e+".")))continue;let n=this._resolveLoopItems(t.repeator,s),r=n.length,i=t.elements.length,l=Math.min(i,r);for(let a=0;a<l;a++){let h=t.elements[a],d=this._createItemScope(n[a],a,s);h.setAttribute("data-wdl-index",String(a)),h.dataset&&(h.dataset.wdlIndex=String(a)),this._updateElementSubtree(h,t.node,d,a)}if(r>i)for(let a=i;a<r;a++){let h=this._createItemScope(n[a],a,s),d=this._createSingleElement(t.node,h,a);if(t.anchor&&t.anchor.parentNode===t.parentEl)t.parentEl.insertBefore(d,t.anchor);else if(t.elements.length>0){let p=t.elements[t.elements.length-1];t.parentEl.insertBefore(d,p.nextSibling)}else t.parentEl.appendChild(d);t.elements.push(d)}if(r<i)for(let a=i-1;a>=r;a--){let h=t.elements[a];this._unregisterElementHierarchy(h),h.remove(),t.elements.pop()}}}_updateElementSubtree(e,s,t,o){if(this._applyNodeAttrs(e,s,t),Array.isArray(s.children)&&Array.isArray(e.children)){let n=0;for(let r of s.children)if(r.repeator){let i=this._loopBindings.find(l=>l.parentEl===e&&l.node===r);i&&this._reconcileLoops(i.repeator,t)}else e.children[n]&&(this._updateElementSubtree(e.children[n],r,t,o),n++)}}_reconcileStaticDataBindings(e,s){let t=this._getComponentAttrMap();for(let[o,n]of Object.entries(t)){let r=u(o),i=JSON.stringify(n);if(!i.includes("${")&&!i.includes("{{")||e&&!i.includes(e))continue;let l=this.getLiveNodes(r);for(let a of l){if(a.hasAttribute("data-wdl-index")||this._findLoopForElement(a))continue;let h=_(n,s);this._applyPropsToElement(a,r,h)}}}_handleVariant(e){let{targetId:s,payload:t}=e,o=u(s)||this._rootSemanticId(),n=this.getNode(o);if(!n){let r=this._rootSemanticId(),i=r?this.getNode(r):null;i&&(t?i.dataset.variant=String(t):delete i.dataset.variant,this._refreshElementClasses(i,r),this._log("op",`variant \u2192 ${t||"(none)"} on #${r}`));return}t?n.dataset.variant=String(t):delete n.dataset.variant,this._refreshElementClasses(n,o),this._log("op",`variant \u2192 ${t||"(none)"} on #${o}`)}_applyRootVariant(){let e=this._getComponentAttrMap(),s=this._rootSemanticId();if(!s)return;let t="."+s,o=e[t]?.["data-variant"]??e["."]?.["data-variant"]??null;if(o&&this.liveMap.has(s)){let n=this.getNode(s);n&&n.dataset&&(n.dataset.variant=String(o),this._refreshElementClasses(n,s))}}_rootSemanticId(){for(let[s,t]of this.liveMap)if(t.parentNode===this.container)return s;let e=this.liveMap.keys().next();return e.done?"":e.value}_handleRegistry(e){this._syncRegistryStyles(),this._refreshAllElementClasses(),this._log("op",`registry.${e.action}`)}_syncRegistryStyles(){if(!this.styleTarget)return;let e=this.component.registry?.get?.()??this.component.getSnapshot?.()?.registry??null,s=this.component.id||this.component.getSnapshot?.()?.id||"comp";if(this._styleEl||(this._styleEl=document.createElement("style"),this._styleEl.setAttribute("data-wdl-dom",s),this.styleTarget.appendChild(this._styleEl)),!e){this._styleEl.textContent="";return}let t=Array.isArray(e.rules)?e.rules:[],o=[];if(e.vars&&typeof e.vars=="object"){let n=Object.entries(e.vars).map(([r,i])=>`--${r}: ${i};`).join(" ");n&&o.push(`:root, [wdl-comp] { ${n} }`)}for(let n of t){if(!n||!n.selector)continue;let r=typeof n.css=="string"?n.css:n.css&&typeof n.css=="object"?Object.entries(n.css).map(([a,h])=>`${I(a)}: ${h};`).join(" "):"";if(!r)continue;let i=n.selector.startsWith("&")?n.selector.replace("&",`[wdl-comp="${s}"]`):n.selector,l=n.media?`@media ${n.media} { ${i} { ${r} } }`:`${i} { ${r} }`;o.push(l)}this._styleEl.textContent=o.join(`
|
|
2
|
+
`)}_log(e,...s){if(!this.debug&&e!=="warn")return;let t=`[wdl-dom:${e}]`;e==="warn"?console.warn(t,...s):console.log(t,...s)}};function I(c){return String(c).replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function x(c){return new C(c)}var L=x;export{C as WdlDom,x as createWdlDom,L as default,u as normalizeId,w as parseLayerToken,N as parseLayersSimple,_ as resolveAll,y as resolvePath,m as resolveStr};
|