@crosshj/html-next
Version:
A modern, declarative web component framework with reactive state management, conditional rendering, data visualization, and server-side fragment loading. Built for building interactive UIs without heavy frameworks.
122 lines (117 loc) • 140 kB
JavaScript
const t=(t,...e)=>{let n="";for(let s=0;s<t.length;s++)n+=t[s],s<e.length&&(n+=e[s]);return n},e={red:"#f44336",pink:"#e91e63",purple:"#9c27b0",deepPurple:"#673ab7",indigo:"#3f51b5",blue:"#2196f3",lightBlue:"#03a9f4",cyan:"#00bcd4",teal:"#009688",green:"#4caf50",lightGreen:"#8bc34a",lime:"#cddc39",yellow:"#ffeb3b",amber:"#ffc107",orange:"#ff9800",deepOrange:"#ff5722",brown:"#795548",grey:"#9e9e9e",blueGrey:"#607d8b"},n=t=>t&&"string"==typeof t?t.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g,"\n").replace(/ /g,"\r").replace(/	/g,"\t"):"",s=t=>(t=>{const n=t.match(/^(\w+)(A\d+)$/);if(n){const[,t,s]=n,i=e[t];if(!i)return"#9e9e9e";const r={A100:20,A200:40,A400:60,A700:80}[s]||50;return`color-mix(in srgb, ${i} ${r}%, white ${100-r}%)`}const s=t.match(/^([a-zA-Z]+)(\d{2,3})$/);if(s){const[,t,n]=s,i=e[t];if(!i)return"#9e9e9e";const r=parseInt(n);if(500===r)return i;if(r<=400){const t={50:10,100:20,200:30,300:40,400:50}[r]||50;return`color-mix(in srgb, ${i} ${t}%, white ${100-t}%)`}if(r>=600){const t={600:80,700:70,800:60,900:50}[r]||50;return`color-mix(in srgb, ${i} ${t}%, black ${100-t}%)`}}return"#9e9e9e"})(t);function i(t,e){if("string"!=typeof t)return t;if(!e)return t;const n=t.startsWith("DEBUG "),i=n?t.substring(6):t,a=i.match(/^WHEN\s+(.+?)\s+IS\s+(.+?)\s+THEN\s+(.+?)\s+ELSE\s+(.+)$/);if(a){const[,t,s,i,r]=a,o=function(t,e,n,s=!1){if(!n)return!1;const i=t.trim().startsWith("global_")?n[t.trim().substring(7)]:t.trim();if(e.includes("{{")&&e.includes("}}"))return!1;const r=e.trim().startsWith("global_")?n[e.trim().substring(7)]:e.trim(),a=i===r;return s&&(JSON.stringify(i),JSON.stringify(r)),a}(t,s,e,n);return(o?i:r).replace(/^['"]|['"]$/g,"")}const o=i.match(/^WHEN\s+(.+?)\s+THEN\s+(.+?)\s+ELSE\s+(.+)$/);if(o){const[,t,s,i]=o,a=(r(t,e)?s:i).replace(/^['"]|['"]$/g,"");return n&&r(t,e),a}const l=s(i);return"#9e9e9e"!==l||"grey500"===i?l:t}function r(t,e){if(!e)return!1;const n=t.trim();return n.startsWith("global_")?!!e[n.substring(7)]:!!e[n]}function a(t){if(!t||"string"!=typeof t)return"";let e=t.replace(/<script[^>]*type="module"[^>]*>[\s\S]*?<\/script>/gi,"");if(e=e.replace(/<script[^>]*src="[^"]*vite[^"]*"[^>]*>[\s\S]*?<\/script>/gi,""),e=e.replace(/<script[^>]*src="[^"]*\/src\/[^"]*"[^>]*>[\s\S]*?<\/script>/gi,""),e=e.replace(/<link[^>]*rel="modulepreload"[^>]*>/gi,""),e=e.replace(/\n\s*\n\s*\n/g,"\n\n"),e.trim())try{e=function(t){if(!t||"string"!=typeof t)return"";const e="___CODE_BLOCK_PLACEHOLDER___",n=[];let s=t;s=s.replace(/```[\s\S]*?```/g,t=>{const s=n.length;return n.push(t),`${e}${s}`});let i=s;const r=/<x-markdown([^>]*)>/gi;let a;for(;null!==(a=r.exec(i));){const t=a[0],e=a[1],n=a.index;if(e.includes("content="))continue;const r=i.indexOf("</x-markdown>",n+t.length);if(-1===r)continue;let o=i.substring(n+t.length,r),l=o,c=0;for(;;){const t=l.slice(c).match(/<x-map([^>]*)>/);if(!t)break;const e=t[0],n=t[1],s=c+t.index,i=s+e.length;if(n.includes("content=")){c=i;continue}const r=l.slice(i).match(/<\/x-map>/);if(!r){c=i;continue}const a=i+r.index,o=a+r[0].length,u=l.slice(i,a);if(u.includes("<template>")){c=o;continue}const h=`<x-map${n}><template>${u}</template></x-map>`;l=l.slice(0,s)+h+l.slice(o),c=s+h.length}o=l;const u=o.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	"),h=t+s.substring(n+t.length,r)+"</x-markdown>",d=`<x-markdown${e} content="${u}"></x-markdown>`;i=i.replace(h,d)}i=i.replace(new RegExp(`${e}(\\d+)`,"g"),(t,e)=>n[parseInt(e)].replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	"));const o="___MARKDOWN_PLACEHOLDER___",l=[];let c=i;c=c.replace(/<x-markdown[^>]*content="[^"]*"[^>]*><\/x-markdown>/gi,t=>{const e=l.length;return l.push(t),`${o}${e}`}),c=c.replace(/<x-table([^>]*)>([\s\S]*?)<\/x-table>/gi,(t,e,n)=>`<x-table${e} content="${n.replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}"></x-table>`),i=c.replace(new RegExp(`${o}(\\d+)`,"g"),(t,e)=>l[parseInt(e)]);const u="___SCHEMA_MARKDOWN_PLACEHOLDER___",h=[];let d=i;d=d.replace(/<x-markdown[^>]*content="[^"]*"[^>]*><\/x-markdown>/gi,t=>{const e=h.length;return h.push(t),`${u}${e}`}),d=d.replace(/<x-schema([^>]*)>([\s\S]*?)<\/x-schema>/gi,(t,e,n)=>`<x-schema${e} content="${n.replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}"></x-schema>`),i=d.replace(new RegExp(`${u}(\\d+)`,"g"),(t,e)=>h[parseInt(e)]);const f="___FORM_MARKDOWN_PLACEHOLDER___",p=[];let m=i;m=m.replace(/<x-markdown[^>]*content="[^"]*"[^>]*><\/x-markdown>/gi,t=>{const e=p.length;return p.push(t),`${f}${e}`}),m=m.replace(/<x-form([^>]*)>([\s\S]*?)<\/x-form>/gi,(t,e,n)=>`<x-form${e} content="${n.replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}"></x-form>`),i=m.replace(new RegExp(`${f}(\\d+)`,"g"),(t,e)=>p[parseInt(e)]);const g="___FLOW_MARKDOWN_PLACEHOLDER___",b=[];let x=i;x=x.replace(/<x-markdown[^>]*content="[^"]*"[^>]*><\/x-markdown>/gi,t=>{const e=b.length;return b.push(t),`${g}${e}`}),x=x.replace(/<x-flow([^>]*)>([\s\S]*?)<\/x-flow>/gi,(t,e,n)=>`<x-flow${e} content="${n.replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}"></x-flow>`),i=x.replace(new RegExp(`${g}(\\d+)`,"g"),(t,e)=>b[parseInt(e)]);const v="___MAP_MARKDOWN_PLACEHOLDER___",$=[];let w=i;return w=w.replace(/<x-markdown[^>]*content="[^"]*"[^>]*><\/x-markdown>/gi,t=>{const e=$.length;return $.push(t),`${v}${e}`}),w=w.replace(/<x-map([^>]*)>([\s\S]*?)<\/x-map>/gi,(t,e,n)=>e.includes("content=")||n.includes("<template>")?t:`<x-map${e}><template>${n}</template></x-map>`),i=w.replace(new RegExp(`${v}(\\d+)`,"g"),(t,e)=>$[parseInt(e)]),i}(e)}catch(t){console.error("Error transforming content elements:",t)}return e}class o extends HTMLElement{constructor(){super(),this.stateSubscriptions=new Map,this.initialState=null,this.originalAttributes=new Map,this.setupStateSubscriptions()}connectedCallback(){this.initialState=this.getCurrentState(),this.storeOriginalAttributes(),this.applySxStyles(),this.applyConditionalAttributes()}disconnectedCallback(){this.stateSubscriptions.forEach(t=>t()),this.stateSubscriptions.clear()}getCurrentState(){return"undefined"!=typeof window&&window.state?{...window.state}:{}}storeOriginalAttributes(){Array.from(this.attributes).forEach(t=>{this.originalAttributes.set(t.name,t.value)})}setupStateSubscriptions(){(function(t){const e=new Set;return Array.from(t).forEach(t=>{const n=t.value;n.startsWith("DEBUG ")&&(t.name,t.ownerElement);const s=n.match(/global_(\w+)/g);s&&s.forEach(t=>{const n=t.substring(7);e.add(n)})}),Array.from(e)})(this.attributes).forEach(t=>{if("undefined"!=typeof window&&window.subscribeToState){const e=window.subscribeToState(t,t=>{this.handleStateChange(t.state)});this.stateSubscriptions.set(t,e)}})}handleStateChange(t){this.initialState=t||this.getCurrentState(),this.applySxStyles(),this.applyConditionalAttributes(),this.onStateChange(t)}onStateChange(t){}applyConditionalAttributes(){this.originalAttributes.forEach((t,e)=>{if(!e.startsWith("sx:")&&(t.includes("global_")||t.includes("WHEN ")||t.includes("DEBUG "))){t.startsWith("DEBUG ");const n=i(t,this.initialState);"className"!==e&&"class"!==e||(this.className=n),this.setAttribute(e,n)}})}applySxStyles(){const t={};this.originalAttributes.forEach((e,n)=>{if(n.startsWith("sx:")){const s=n.substring(3),r=i(e,this.initialState),a=this.expandShorthandProperty(s,r);Object.assign(t,a)}}),Object.entries(t).forEach(([t,e])=>{["opacity","zIndex","fontWeight","lineHeight"].includes(t)&&"string"==typeof e&&!isNaN(e)?this.style[t]=parseFloat(e):this.style.setProperty(t,e)}),Array.from(this.attributes).forEach(t=>{t.name.startsWith("sx:")&&this.removeAttribute(t.name)})}expandShorthandProperty(t,e){const n={},s={m:"margin",mt:"margin-top",mr:"margin-right",mb:"margin-bottom",ml:"margin-left",mx:"margin-inline",my:"margin-block",p:"padding",pt:"padding-top",pr:"padding-right",pb:"padding-bottom",pl:"padding-left",px:"padding-inline",py:"padding-block",bgcolor:"background-color",bg:"background-color"}[t]||t,i=["gap","flex-gap","row-gap","column-gap","grid-row-gap","grid-column-gap","grid-gap","margin","padding","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height"].some(t=>s.includes(t));return n[s]=i?(t=>/^\d+(\.\d+)?$/.test(t)?8*parseFloat(t)+"px":t)(e):e,n}}class l extends o{constructor(){super(),this.isOpen=!1,this.resolvePromise=null,this.overlay=null,this.modal=null}connectedCallback(){super.connectedCallback(),this.render()}disconnectedCallback(){this.overlay&&this.overlay.removeEventListener("click",this.handleOverlayClick),this.modal&&this.modal.removeEventListener("keydown",this.handleKeydown),super.disconnectedCallback()}render(){const e=this.getAttribute("title")||"",n=this.getAttribute("message")||"",s=this.getAttribute("type")||"alert",i=this.getAttribute("confirmText")||"OK",r=this.getAttribute("cancelText")||"Cancel";this.innerHTML=t`
<div class="modal-overlay" style="display: none;">
<div class="modal-container">
<div class="modal-content">
${e?t`<div class="modal-header">
<h3 class="modal-title">${e}</h3>
</div>`:""}
<div class="modal-body">
<p class="modal-message">${n}</p>
</div>
<div class="modal-footer">
${"confirm"===s?t`
<x-button
class="modal-button-cancel"
variant="text"
label="${r}"
>
</x-button>
`:""}
<x-button
class="modal-button-confirm"
variant="primary"
label="${i}"
>
</x-button>
</div>
</div>
</div>
</div>
`,this.overlay=this.querySelector(".modal-overlay"),this.modal=this.querySelector(".modal-container"),this.setupEventListeners()}setupEventListeners(){if(!this.overlay||!this.modal)return;this.handleOverlayClick&&this.overlay.removeEventListener("click",this.handleOverlayClick),this.handleKeydown&&document.body.removeEventListener("keydown",this.handleKeydown),this.handleOverlayClick=t=>{t.target===this.overlay&&"alert"===this.getAttribute("type")&&this.close(!1)},this.overlay.addEventListener("click",this.handleOverlayClick),this.handleKeydown=t=>{"Escape"===t.key&&"alert"===this.getAttribute("type")&&this.close(!1)},document.body.addEventListener("keydown",this.handleKeydown);const t=this.querySelector(".modal-button-confirm"),e=this.querySelector(".modal-button-cancel");if(t){const e=t.cloneNode(!0);t.parentNode.replaceChild(e,t),e.addEventListener("click",()=>this.close(!0))}if(e){const t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener("click",()=>this.close(!1))}}show(){this.isOpen=!0,this.overlay.style.display="flex",this.modal&&(this.modal.style.display="flex"),document.body.style.overflow="hidden",this.modal.focus(),this.modal.setAttribute("tabindex","-1")}hide(){this.isOpen=!1,this.overlay.style.display="none",document.body.style.overflow=""}close(t){this.handleKeydown&&document.body.removeEventListener("keydown",this.handleKeydown),this.handleOverlayClick&&this.overlay.removeEventListener("click",this.handleOverlayClick),this.resolvePromise&&(this.resolvePromise(t),this.resolvePromise=null)}hideContent(){this.isOpen=!1,this.modal&&(this.modal.style.display="none")}dispose(){this.hide(),setTimeout(()=>{this.parentNode&&this.parentNode.removeChild(this)},100)}updateAndShow(t,e,n="alert",s){this.setAttribute("message",t),this.setAttribute("title",e),this.setAttribute("type",n),this.resolvePromise=s,this.updateContent(t,e,n),requestAnimationFrame(()=>{this.show()})}updateContent(t,e,n){const s=this.querySelector(".modal-title");s&&(s.textContent=e);const i=this.querySelector(".modal-body p");i&&(i.innerHTML=t);const r=this.querySelector(".modal-button-cancel"),a="confirm"===n;r&&(r.style.display=a?"block":"none"),this.setupEventListeners()}updateBody(t){const e=this.querySelector(".modal-body");e&&(e.innerHTML=t)}static findExistingModal(){return document.querySelector('x-modal:not([reuse="false"])')}static async alert(t,e="Alert"){return new Promise(n=>{const s=document.createElement("x-modal");s.setAttribute("type","alert"),s.setAttribute("message",t),s.setAttribute("title",e),s.resolvePromise=n,document.body.appendChild(s);const i=()=>{s.overlay?s.show():requestAnimationFrame(i)};requestAnimationFrame(i)})}static async confirm(t,e="Confirm"){return new Promise(n=>{const s=document.createElement("x-modal");s.setAttribute("type","confirm"),s.setAttribute("message",t),s.setAttribute("title",e),s.resolvePromise=n,document.body.appendChild(s);const i=()=>{s.overlay?s.show():requestAnimationFrame(i)};requestAnimationFrame(i)})}}const c=new class{constructor(){this.state={},this.listeners=new Map,this.dataSources=new Map,this.subscriptions=new Map,this.flows=new Map,this.componentHooks=new Map,this.urlCache=new Map,this.initialized=!1}initialize(t=null){this.initialized||(this.initialized=!0,t&&(this.routerContext=t))}set(t,e){const n=this.state[t];JSON.stringify(n)!==JSON.stringify(e)&&(this.state[t]=e,"undefined"!=typeof window&&(window.state={...this.state}),this.notifyListeners(t,{property:t,oldValue:n,newValue:e,state:{...this.state}}))}get(t){return this.state[t]}async GetData(t){const e=this.dataSources.get(t);return e&&e.url?await this.fetchUrlData(t,e):this.get(t)}async fetchUrlData(t,e){const{url:n,lazy:s,defaultValue:i}=e;if(this.urlCache.has(n)){const t=this.urlCache.get(n);if(void 0!==t.data)return t.data;if(t.promise)return await t.promise}if(s&&!this.urlCache.has(n))return this.urlCache.set(n,{data:void 0,promise:null,loading:!1}),i;const r=this.performUrlFetch(n,t);this.urlCache.set(n,{data:void 0,promise:r,loading:!0});try{const e=await r;return this.urlCache.set(n,{data:e,promise:null,loading:!1}),this.set(t,e),e}catch(e){return console.error(`Error fetching data from ${n}:`,e),this.urlCache.set(n,{data:i,promise:null,loading:!1}),this.set(t,i),i}}async performUrlFetch(t,e){try{const e=await fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const n=await e.text();if(t.endsWith(".json")||this.looksLikeJson(n))try{return JSON.parse(n)}catch(e){return console.warn(`Failed to parse JSON from ${t}, using as text:`,e),n}return n}catch(e){throw new Error(`Failed to fetch ${t}: ${e.message}`)}}looksLikeJson(t){const e=t.trim();return e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")}getState(){return{...this.state}}subscribe(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{const n=this.listeners.get(t);n&&n.delete(e)}}notifyListeners(t,e){const n=this.listeners.get(t);n&&n.forEach(n=>{try{n(e)}catch(e){console.error(`Error in state listener for ${t}:`,e)}})}initializeProperty(t,e){void 0===this.state[t]&&this.set(t,e)}has(t){return t in this.state}getProperties(){return Object.keys(this.state)}registerDataSource(t,e){const{name:n,defaultValue:s,defaultvalue:i,route:r,url:a,lazy:o}=t;if(!n)return;const l=void 0!==s?s:i,c="true"===o||!0===o;if(this.dataSources.set(n,{defaultValue:l,route:r,url:a,lazy:c}),"pathData"===n&&r)this.setupPathDataListener(r);else if(a){if(void 0!==l){let t=l;try{t=JSON.parse(l)}catch(t){}this.initializeProperty(n,t)}c||this.fetchUrlData(n,{url:a,lazy:c,defaultValue:l})}else if(void 0!==l){let t=l;try{t=JSON.parse(l)}catch(t){}this.initializeProperty(n,t)}}unregisterDataSource(t){this.dataSources.delete(t)}registerSubscription(t,e){const{path:n,handler:s}=t;if(!n||!s)return;this.subscriptions.set(n,{handler:s});const i=this.subscribe(n,async t=>{await this.triggerFlow(s,t)}),r=this.get(n);return void 0!==r&&setTimeout(async()=>{await this.triggerFlow(s,{property:n,oldValue:void 0,newValue:r,state:{...this.state}})},0),i}unregisterSubscription(t){this.subscriptions.delete(t)}registerFlow(t,e){const{key:n}=t;n&&e&&this.flows.set(n,e)}unregisterFlow(t){this.flows.delete(t)}async triggerFlow(t,e,n=null){let s=this.flows.get(t);s||(s=function(t){const e=document.querySelector(`script[type="application/flow"][data-key="${t}"]`);return e?e.textContent.trim():null}(t)),s?await this.executeFlow(s,e,n):console.warn(`Flow not found: ${t}`)}async executeFlow(t,e,n=null){if(window.lastFlowEvent=e,t&&t.trim())if("string"==typeof t)if(t.includes("undefined")&&t.includes("null")&&t.length<10)console.warn("Flow execution skipped: potentially malformed code");else try{const s=this,i=s.getState(),r=JSON.parse(JSON.stringify(i)),a={global:r,state:r,get event(){return window.lastFlowEvent||{}},SetState:(t,e)=>s.set(t,e),setState:(t,e)=>s.set(t,e),SetData:(t,e)=>s.SetData(t,e),setData:(t,e)=>s.SetData(t,e),GetData:t=>s.GetData(t),getData:t=>s.GetData(t),Query:t=>s.Query(t),query:t=>s.Query(t),Navigate:t=>s.Navigate(t),navigate:t=>s.Navigate(t),Alert:(t,e)=>s.Alert(t,e),alert:(t,e)=>s.Alert(t,e),Confirm:(t,e)=>s.Confirm(t,e),confirm:(t,e)=>s.Confirm(t,e),Trigger:(t,i)=>{const r=[...e.flowStack||[],n].filter(Boolean);return s.triggerFlow(t,{triggeredBy:"flow",flowStack:r,data:i||{}},t)},get routerBeforeEach(){return s.routerContext?.beforeEach},get routerAfterEach(){return s.routerContext?.afterEach},get router(){return s.routerContext}};let o;try{o=new Function(...Object.keys(a),`"use strict"; return (async () => { ${t} })();`)}catch(e){return console.error("Flow syntax error:",e),void console.error("Problematic code:",t)}await o.apply(a,Object.values(a))}catch(e){console.error("Flow execution error:",e),console.error("Problematic code:",t)}else console.warn("Flow execution skipped: code is not a string");else console.warn("Flow execution skipped: empty code")}setupPathDataListener(t){let e;try{const[n,s]=t.split("#/");if(!s)return;const i=`${window.location.protocol}//${window.location.host}${n}`;e=new URLPattern({baseURL:i,hash:`#/${s}`})}catch(t){return}const n=()=>{const t=window.location.href,n=e.exec(t);let s;if(n&&n.hash&&n.hash.groups)s=n.hash.groups;else{if(!window.location.hash)return void(window.location.hash="#/");s={}}this.set("pathData",s)};n(),window.addEventListener("hashchange",n),window.addEventListener("navigate",()=>{setTimeout(n,0)})}register({type:t,attributes:e,body:n}){switch(t){case"x-data":return this.registerDataSource(e,n);case"x-subscribe":return this.registerSubscription(e,n);case"x-flow":return this.registerFlow(e,n);default:return console.warn(`Unknown component type: ${t}`),()=>{}}}async Query(t){const{url:e}=t;if(!e)return"";const n=e.startsWith("/")?e:`/${e}`;try{const t=await fetch(n);return await t.text()}catch(t){return console.error("Error loading page content:",t),`<div style="padding: 20px; color: red;">Error loading content: ${t.message}</div>`}}Navigate(t,e={}){this.routerContext?this.triggerFlow("routerNavigate",{triggeredBy:e.triggeredBy||"Navigate",href:t,element:e.element}):window.location.hash=t}async Alert(t={}){const{message:e="",title:n="Alert",dispose:s=!0}=t,i=l.findExistingModal();if(i){const t=await new Promise(t=>{i.updateAndShow(e,n,"alert",t)});return s?i.dispose():i.hideContent(),t}const r=await l.alert(e,n),a=l.findExistingModal();return a&&(s?a.dispose():a.hideContent()),r}async Confirm(t={}){const{message:e="",title:n="Confirm",dispose:s=!0}=t,i=l.findExistingModal();if(i){const t=await new Promise(t=>{i.updateAndShow(e,n,"confirm",t)});return s?i.dispose():i.hideContent(),t}const r=await l.confirm(e,n),a=l.findExistingModal();return a&&(s?a.dispose():a.hideContent()),r}async SetData(t,e){const n=e instanceof Promise?await e:e;t.includes(".")?this.setNested(t,n):this.set(t,n)}setNested(t,e){const n=t.split("."),s=n[0];let i=this.state[s]?JSON.parse(JSON.stringify(this.state[s])):{},r=i;for(let t=1;t<n.length-1;t++)r[n[t]]&&"object"==typeof r[n[t]]||(r[n[t]]={}),r=r[n[t]];r[n[n.length-1]]=e,this.set(s,i)}registerComponentHook(t,e){return this.componentHooks.has(t)||this.componentHooks.set(t,new Set),this.componentHooks.get(t).add(e),()=>{const n=this.componentHooks.get(t);n&&n.delete(e)}}unregisterComponentHook(t,e){const n=this.componentHooks.get(t);n&&n.delete(e)}executeComponentHooks(t,e,...n){const s=this.componentHooks.get(t);s&&s.forEach(s=>{try{s(e,...n)}catch(e){console.error(`Error in ${t} hook:`,e)}})}clear(){this.state={},this.listeners.clear(),this.dataSources.clear(),this.subscriptions.clear(),this.flows.clear(),this.componentHooks.clear()}getActiveSubscriptions(){const t={};for(const[e,n]of this.listeners.entries())t[e]={count:n.size,listeners:Array.from(n).map(t=>({name:t.name||"anonymous",toString:t.toString()}))};return t}logActiveSubscriptions(){return this.getActiveSubscriptions()}};function u(t,e){c.set(t,e)}const h=u;function d(t,e){return c.SetData(t,e)}function f(t){return c.GetData(t)}function p(t){return c.get(t)}function m(t,e){return c.subscribe(t,e)}function g(t,e){return c.registerComponentHook(t,e)}function b(t){t&&c.Navigate(t)}async function x(t){return await c.Query(t)}async function v(t={}){return await c.Alert(t)}async function $(t={}){return await c.Confirm(t)}async function w(t,e={},n={}){return await c.triggerFlow(t,{triggeredBy:n.triggeredBy||"manual",data:e,flowStack:n.flowStack||[],element:n.element})}"undefined"!=typeof window&&(window.state={...c.getState()},window.subscribeToState=(t,e)=>c.subscribe(t,e),window.getActiveSubscriptions=()=>c.getActiveSubscriptions(),window.logActiveSubscriptions=()=>c.logActiveSubscriptions());class y extends HTMLElement{constructor(){super();let t=this.getAttribute("content");t=t?t.replace(/"/g,'"').replace(/'/g,"'").replace(/ /g,"\n").replace(/ /g,"\r").replace(/	/g,"\t"):this.textContent?this.textContent.trim():"",t&&"string"==typeof t||(t=""),t.includes("undefined")&&t.includes("null")&&t.length<10&&(console.warn("SystemElement: potentially malformed content detected, using empty string"),t=""),this.unregister=function({type:t,attributes:e,body:n}){return c.register({type:t,attributes:e,body:n})}({type:this.tagName.toLowerCase(),attributes:this.getAllAttributes(),body:t})}getAllAttributes(){const t={};for(let e=0;e<this.attributes.length;e++){const n=this.attributes[e];t[n.name]=n.value}return t}disconnectedCallback(){this.unregister&&this.unregister()}}class k extends y{constructor(){super(),this.removeAttribute("defaultValue")}}class S extends y{}class A extends y{}class F extends o{constructor(){super()}connectedCallback(){this.applySxStyles()}}class E extends o{constructor(){super(),this.unsubscribe=null,this.originalContent=this.innerHTML+""}connectedCallback(){super.connectedCallback();const t=this.getAttribute("titleSource")||"activePath";this.unsubscribe=m(t,()=>{this.updateTitle()}),this.updateTitle()}disconnectedCallback(){this.unsubscribe&&this.unsubscribe()}updateTitle(){const e=this.getAttribute("titleSource")||"activePath",n=this.getAttribute("titleText"),s=p(e)||"";let i=n||"Navigation";if(!n&&s.startsWith("/")){let e=s.substring(1).replace(/\//g,t`<span class="breadcrumb-separator"> > </span>`);e=e.replace(/x-/g,""),i=e.trim().charAt(0).toUpperCase()+e.slice(1)}const r=this.getAttribute("menuButtonShow"),a=this.getAttribute("menuButtonTarget")||"sidebar",o="false"!==r?t`
<button
class="navbar-hamburger"
onclick="document.getElementById('${a}')?.classList?.toggle('open')"
aria-label="Toggle menu"
>
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
</button>
`:"",l=n?t`<div class="navbar-title">${i}</div>`:t`<x-breadcrumb pathSource="${e}"></x-breadcrumb>`;this.innerHTML=t`
<div class="navbar-header">
<div class="navbar-left">${o} ${l}</div>
<div class="navbar-right">
${this.originalContent?`<div class="navbar-actions">${this.originalContent}</div>`:""}
</div>
</div>
`}}class _ extends o{constructor(){super()}connectedCallback(){super.connectedCallback()}}class C extends o{constructor(){super()}}class O extends o{constructor(){super(),this.unsubscribe=null}connectedCallback(){super.connectedCallback();const t=this.getAttribute("pathSource")||"activePath";this.unsubscribe=m(t,()=>{this.render()}),this.render()}disconnectedCallback(){this.unsubscribe&&this.unsubscribe()}render(){const e=p(this.getAttribute("pathSource")||"activePath")||"";if(!e||!e.startsWith("/"))return void(this.innerHTML="");const n=e.split("/").filter(t=>t.length>0),s=[];let i="";n.forEach((t,e)=>{i+="/"+t;const r=e===n.length-1;let a=t.replace(/x-/g,"");a=a.charAt(0).toUpperCase()+a.slice(1),s.push({label:a,path:i,isActive:r})});const r=[];s.forEach((e,n)=>{e.isActive?r.push(t`
<span class="breadcrumb-item breadcrumb-current">${e.label}</span>
`):r.push(t`
<x-link href="${e.path}" class="breadcrumb-item breadcrumb-link"
>${e.label}</x-link
>
`),n<s.length-1&&r.push(t`
<span class="breadcrumb-separator">></span>
`)}),this.innerHTML=t`
<nav
class="breadcrumb-container"
role="navigation"
aria-label="Breadcrumb"
>
${r.join("")}
</nav>
`}}class P extends o{constructor(){super()}static get observedAttributes(){return["disabled"]}attributeChangedCallback(t,e,n){if("disabled"===t){const t=this.querySelector("button");t&&(t.disabled=null!==n)}}connectedCallback(){super.connectedCallback();const t=this.getAttribute("label"),e=this.getAttribute("href"),n=this.getAttribute("handler"),s=this.getAttribute("icon"),i=this.getAttribute("iconPosition")||"left",r=this.getAttribute("variant")||"primary",a=this.getAttribute("size")||"medium",o=this.hasAttribute("disabled"),l=this.hasAttribute("loading"),u=this.hasAttribute("fullWidth"),h=this.getTextContentExcludingIcons(),d=t||h;let f=null;if(s&&!l){f=document.createElement("span");const t=s.startsWith("fa-")?`fa ${s}`:`fa fa-${this.convertToFontAwesome(s)}`;f.className=`${t} button-icon`}let p,m=null;l&&(m=document.createElement("span"),m.className="fa fa-refresh fa-spin button-icon"),p=document.createElement("button"),p.className=`x-button x-button-${r} x-button-${a}`,u&&p.classList.add("x-button-fullwidth"),s&&!d&&p.classList.add("x-button-icon-only"),(o||l)&&(p.disabled=!0),!e||o||l||p.addEventListener("click",async t=>{t.preventDefault(),b(e)}),!n||o||l||p.addEventListener("click",async t=>{t.preventDefault(),await c.triggerFlow(n,{triggeredBy:"button",element:this},n)}),l?(p.appendChild(m),p.appendChild(document.createTextNode("Loading..."))):s&&"left"===i?(p.appendChild(f),d&&p.appendChild(document.createTextNode(d))):s&&"right"===i?(d&&p.appendChild(document.createTextNode(d)),p.appendChild(f)):s&&!d?p.appendChild(f):p.textContent=d,this.innerHTML="",this.appendChild(p),this.copyAttributesToInnerButton()}copyAttributesToInnerButton(){const t=this.querySelector("button, x-link");if(!t)return;const e=this.getAttribute("href");e&&t.setAttribute("href",e);for(let e=0;e<this.style.length;e++){const n=this.style[e],s=this.style.getPropertyValue(n);t.style.setProperty(n,s)}}getTextContentExcludingIcons(){const t=this.cloneNode(!0);return t.querySelectorAll("x-icon").forEach(t=>t.remove()),t.textContent.trim()}convertToFontAwesome(t){return t?{Home:"home",ListAlt:"list-alt",MenuBook:"book",DriveFolderUpload:"upload",AccountTree:"cog",Save:"save",Add:"plus",ArrowForward:"arrow-right",ArrowBack:"arrow-left",Edit:"edit",Delete:"trash-o",Close:"times",Search:"search",Filter:"filter",MoreVert:"ellipsis-v",MoreHoriz:"ellipsis-h",Info:"info-circle",Warning:"exclamation-triangle",Error:"exclamation-circle",Success:"check-circle",Loading:"refresh",People:"users",Person:"user",LineChart:"line-chart",History:"history"}[t]||t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""):"help"}}class z extends o{constructor(){super()}connectedCallback(){super.connectedCallback();const t=this.getAttribute("sx:contents");t&&(this.textContent=t);const e=this.getAttribute("display");if(e)this.style.display=e;else{const t=this.getAttribute("variant");this.style.display="strong"===t?"inline":"block"}}}class T extends HTMLElement{constructor(){super()}connectedCallback(){const t=this.getAttribute("href"),e=this.getAttribute("underline"),n=document.createElement("a");if(t){const e=t.startsWith("#")?t:`#${t}`;n.href=window.location.pathname+window.location.search+e}else n.href="#";n.innerHTML=this.innerHTML,"none"===e&&(n.style.textDecoration="none"),n.addEventListener("click",async e=>{e.preventDefault(),b(t)}),this.innerHTML="",this.appendChild(n)}}class D extends o{constructor(){super(),D.instanceCount||(D.instanceCount=0),D.instanceCount++,this.instanceId=D.instanceCount}connectedCallback(){const t=this.getAttribute("items");this.hasAttribute("data-processed")||(this.setAttribute("data-processed","true"),this.template=this.getTemplate(),this.innerHTML="",super.connectedCallback(),this.processData(t))}disconnectedCallback(){this.selectionMode&&this.removeEventListener("click",this.handleSelectionClick),super.disconnectedCallback()}getTemplate(){const t=this.getAttribute("content");if(t)return t;const e=this.querySelector("template");return e?e.innerHTML:""}handleStateChange(t){if(super.handleStateChange(t),!this.template){const t=this.getTemplate();t&&(this.template=t)}if(this.selectedPath&&this.selectionMode){const e=t[this.selectedPath.startsWith("global_")?this.selectedPath.substring(7):this.selectedPath];this.querySelectorAll("div[data-index]").forEach(t=>{const n=parseInt(t.dataset.index,10);e===n?t.classList.add("is-selected"):t.classList.remove("is-selected")})}const e=this.getAttribute("items");e&&this.processData(e)}processData(t){if(!t)return void console.warn(`x-map #${this.instanceId}: no items attribute provided`);let e=t;t.startsWith("global_")&&(e=t.substring(7));const n=p(e);if(!n)return void console.warn(`x-map #${this.instanceId}: data not found for path: ${t} (tried: ${e})`);if(!Array.isArray(n))return void console.warn(`x-map #${this.instanceId}: data is not an array: ${t}`);this.innerHTML="";const s=this.getAttribute("selectMode"),i=this.getAttribute("selected"),r=this.getAttribute("onSelect");this.selectionMode=s,this.selectedPath=i,this.onSelectHandler=r,s&&this.addEventListener("click",this.handleSelectionClick),n.forEach((t,e)=>{const n=this.processTemplate(this.template,t,e),r=document.createElement("div");if(r.innerHTML=n,s){const n=document.createElement("div");for(n.dataset.index=e,i?p(i.startsWith("global_")?i.substring(7):i)===e&&n.classList.add("is-selected"):t.isSelected&&n.classList.add("is-selected");r.firstChild;)n.appendChild(r.firstChild);this.appendChild(n)}else for(;r.firstChild;)this.appendChild(r.firstChild)}),this.style.removeProperty("display")}processTemplate(t,e,s){let i=t.includes("<")||t.includes(">")||t.includes(""")?n(t):t;return i=i.replace(/\{\{\s*item_([^}]+)\s*\}\}/g,(t,n)=>{const s=n.trim();return e[s]||""}),i=i.replace(/\{\{\s*item\s*\}\}/g,()=>null==e?"":"object"==typeof e?JSON.stringify(e).replace(/"/g,"""):String(e)),i=i.replace(/\{\{index\}\}/g,s+1),i=i.replace(/\{\{#if\s+([^}]+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(t,n,s)=>this.evaluateCondition(n.trim(),e)?s:""),i=i.replace(/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(t,n,s)=>{const i=n.trim();let r;if(i.startsWith("item_")){const t=i.substring(5);r=e[t]}else r=e[i];return Array.isArray(r)?r.map((t,e)=>{let n=s.replace(/\{\{\s*this\s*\}\}/g,t);return this.processTemplate(n,t,e)}).join(""):""}),i=i.replace(/class="WHEN\s+(.+?)\s+IS\s+(.+?)\s+THEN\s+(.+?)\s+ELSE\s+(.+?)"/g,(t,e,n,s,i)=>{const r=this.initialState||{},a=(e.trim().startsWith("global_")?r[e.trim().substring(7)]:e.trim())===n.trim(),o=s.replace(/^['"]|['"]$/g,""),l=i.replace(/^['"]|['"]$/g,"");return`class="${a?o:l}"`}),i}evaluateCondition(t,e){if(t.startsWith("item_")){const n=e[t.substring(5)];return Array.isArray(n)?n.length>0:!!n}const n=e[t];return Array.isArray(n)?n.length>0:!!n}handleSelectionClick=t=>{const e=t.target.closest("div[data-index]");if(!e)return;const n=parseInt(e.dataset.index,10);"single"===this.selectionMode?(this.querySelectorAll("div[data-index]").forEach(t=>{t.classList.remove("is-selected")}),e.classList.add("is-selected")):e.classList.toggle("is-selected"),this.onSelectHandler&&w(this.onSelectHandler,{index:n},{triggeredBy:"x-map",element:e})}}class M extends o{constructor(){super()}connectedCallback(){super.connectedCallback();const t=this.getAttribute("icon")||this.getAttribute("name"),e=this.getAttribute("color")||this.getAttribute("sx:color"),n=this.getAttribute("size")||"medium";if(this.closest("x-button"))this.style.display="none";else{const s=document.createElement("span"),i=t.startsWith("fa-")?`fa ${t}`:`fa fa-${this.convertToFontAwesome(t)}`,r=this.getFontAwesomeSizeClass(n);s.className=`${i} ${r}`,s.style.display="inline-block",s.style.verticalAlign="middle",e&&(s.style.color=e),this.innerHTML="",this.appendChild(s)}}getFontAwesomeSizeClass(t){return{"2x":"fa-2x","3x":"fa-3x","4x":"fa-4x","5x":"fa-5x"}[t]||""}convertToFontAwesome(t){return t?{Home:"home",ListAlt:"list-alt",MenuBook:"book",DriveFolderUpload:"upload",AccountTree:"cog",Save:"save",Add:"plus",ArrowForward:"arrow-right",ArrowBack:"arrow-left",Edit:"edit",Delete:"trash-o",Close:"times",Search:"search",Filter:"filter",MoreVert:"ellipsis-v",MoreHoriz:"ellipsis-h",Info:"info-circle",Warning:"exclamation-triangle",Error:"exclamation-circle",Success:"check-circle",CheckCircle:"check-circle",Loading:"refresh",People:"users",Person:"user",LineChart:"line-chart",History:"history",Construction:"wrench",Settings:"cog",Menu:"bars",Cancel:"times"}[t]||t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""):"help"}}class j extends o{constructor(){super(),this.unsubscribe=null}connectedCallback(){super.connectedCallback();const t=this.getAttribute("contents"),e="false"!==this.getAttribute("showLoading");if(!t)return void console.warn("x-fragment: no contents attribute provided");const n=t.startsWith("global_")?t.substring(7):t;this.unsubscribe=m(n,t=>{this.updateContent(t.newValue,e)});const s=p(n);this.updateContent(s,e)}updateContent(e,n){const s=this.className;if(null!=e&&""!==e)if("string"==typeof e)try{const t=a(e);this.innerHTML=`<div class="${s}">${t}</div>`}catch(t){console.error("Error processing fragment content:",t),this.innerHTML=`<div class="${s}" style="padding: 20px; color: red;">Error processing content</div>`}else try{this.innerHTML=t`<pre class="${s}">
${JSON.stringify(e,null,2)}</pre
>`}catch(t){console.error("Error stringifying fragment content:",t),this.innerHTML=`<div class="${s}" style="padding: 20px; color: red;">Error displaying content</div>`}else this.innerHTML=n?t`
<div
class="fragment-loading-spinner ${s}"
style="display: flex; align-items: center; justify-content: center; height: 100%;"
>
<div
style="width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite;"
></div>
</div>
`:`<div class="fragment-no-loading-spinner ${s}"></div>`}disconnectedCallback(){this.unsubscribe&&this.unsubscribe()}}class N extends o{constructor(){super(),N.instanceCount||(N.instanceCount=0),N.instanceCount++,this.instanceId=N.instanceCount}resolvePath(t,e){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("/")?t:e.substring(0,e.lastIndexOf("/")+1)+t}getCurrentPagePath(){const t=p("currentPath");if(t)return t;const e=new URL(window.location.href).pathname;return e.endsWith(".html"),e.includes("fragments/")?e.substring(e.indexOf("fragments/")):"fragments/"}async connectedCallback(){const e=this.getAttribute("href");if(e)try{const t=this.getCurrentPagePath(),n=this.resolvePath(e,t),s=await fetch(n);if(!s.ok)throw new Error(`Failed to load include: ${s.status} ${s.statusText}`);const i=a(await s.text());this.innerHTML=i,this.applySxStyles()}catch(e){console.error("Error loading include:",e),this.innerHTML=t`<div style="padding: 20px; color: red;">
Error loading include: ${e.message}
</div>`}else console.warn("x-include: no href attribute provided")}}class q extends o{constructor(){super()}connectedCallback(){super.connectedCallback();const t=this.getAttribute("data");if(!t)return void console.warn("x-viz-bar: no data attribute provided");const e=p(t.startsWith("global_")?t.substring(7):t);this.updateChart(e)}onStateChange(t){const e=this.getAttribute("data");if(e){const t=p(e.startsWith("global_")?e.substring(7):e);this.updateChart(t)}}updateChart(t){if(!t||!Array.isArray(t))return void(this.innerHTML='<div class="viz-error">No data available</div>');const e=this.style.color||"var(--palettePrimaryMain)";this.style.setProperty("--bar-base-color",e);const n=Math.max(...t.map(t=>t.value||0));let s="";t.forEach((t,e)=>{const i=t.value/n*100;s+=`\n\t\t\t\t<div class="viz-bar-container">\n\t\t\t\t\t<div \n\t\t\t\t\t\tclass="viz-bar ${e%2==0?"viz-bar-even":"viz-bar-odd"}" \n\t\t\t\t\t\tstyle="height: ${i}%;"\n\t\t\t\t\t>\n\t\t\t\t\t\t<div class="viz-value">\n\t\t\t\t\t\t\t<x-typography variant="caption">${t.value}</x-typography>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class="viz-label">\n\t\t\t\t\t\t<x-typography variant="caption">${t.label||""}</x-typography>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t`}),this.innerHTML=`\n\t\t\t<div class="viz-wrapper">\n\t\t\t\t<div class="viz-chart">\n\t\t\t\t\t${s}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`}}class R extends o{constructor(){super()}connectedCallback(){super.connectedCallback();const t=this.getAttribute("data");if(!t)return void console.warn("x-viz-pie: no data attribute provided");const e=p(t.startsWith("global_")?t.substring(7):t);this.updateChart(e)}onStateChange(t){const e=this.getAttribute("data");if(e){const t=p(e.startsWith("global_")?e.substring(7):e);this.updateChart(t)}}updateChart(t){if(!t||!Array.isArray(t))return void(this.innerHTML='<div class="viz-error">No data available</div>');const e=t.reduce((t,e)=>t+(e.value||0),0);if(0===e)return void(this.innerHTML='<div class="viz-error">No data to display</div>');const n=this.style.color||"var(--palettePrimaryMain)";this.style.setProperty("--pie-base-color",n);const s="donut"===this.getAttribute("variant"),i=s?60:0,r=100,a=100;let o=0,l="",c="";t.forEach((t,n)=>{const u=t.value/e*100,h=t.value/e*360,d=o+h,f=r+98*Math.cos((o-90)*Math.PI/180),p=a+98*Math.sin((o-90)*Math.PI/180),m=r+98*Math.cos((d-90)*Math.PI/180),g=a+98*Math.sin((d-90)*Math.PI/180),b=h>180?1:0;let x;if(s){const t=r+i*Math.cos((o-90)*Math.PI/180),e=a+i*Math.sin((o-90)*Math.PI/180);x=[`M ${f} ${p}`,`A 98 98 0 ${b} 1 ${m} ${g}`,`L ${r+i*Math.cos((d-90)*Math.PI/180)} ${a+i*Math.sin((d-90)*Math.PI/180)}`,`A ${i} ${i} 0 ${b} 0 ${t} ${e}`,"Z"].join(" ")}else x=["M 100 100",`L ${f} ${p}`,`A 98 98 0 ${b} 1 ${m} ${g}`,"Z"].join(" ");l+=`\n\t\t\t\t<path \n\t\t\t\t\td="${x}" \n\t\t\t\t\tclass="viz-slice"\n\t\t\t\t\tdata-index="${n}"\n\t\t\t\t/>\n\t\t\t`,c+=`\n\t\t\t\t<div class="viz-legend-item">\n\t\t\t\t\t<span class="viz-legend-color" data-index="${n}"></span>\n\t\t\t\t\t<span class="viz-legend-label">${t.label||""}</span>\n\t\t\t\t\t<span class="viz-legend-value">${u.toFixed(1)}%</span>\n\t\t\t\t</div>\n\t\t\t`,o=d}),this.innerHTML=`\n\t\t\t<div class="viz-pie-container">\n\t\t\t\t<svg viewBox="0 0 200 200" class="viz-svg">\n\t\t\t\t\t${l}\n\t\t\t\t</svg>\n\t\t\t\t<div class="viz-legend">\n\t\t\t\t\t${c}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`}}class L extends o{constructor(){super(),this.original=Array.from(this.attributes).reduce((t,e)=>(t[e.name]=e.value,t),{})}connectedCallback(){super.connectedCallback();const t=this.getAttribute("data");if(!t)return void console.warn("x-viz-line: no data attribute provided");const e=p(t.startsWith("global_")?t.substring(7):t);this.updateChart(e)}onStateChange(t){const e=this.getAttribute("data");if(e){const t=p(e.startsWith("global_")?e.substring(7):e);this.updateChart(t)}}updateChart(e){if(!e||!Array.isArray(e))return void(this.innerHTML='<div class="viz-error">No data available</div>');const n=this.style.color||"var(--palettePrimaryMain)";this.style.setProperty("--line-base-color",n);const s=Math.max(...e.map(t=>t.value||0)),i=Math.min(...e.map(t=>t.value||0)),r=s-i,a=s+.02*r,o=i-.02*r,l=(a-o)/4,c=Math.pow(10,Math.floor(Math.log10(l))),u=l/c;let h;h=u<=1?1:u<=2?2:u<=5?5:10;const d=h*c,f=o,p=a,m=p-f;let g="";const b=Math.ceil(f/d)*d,x=Math.floor(p/d)*d;for(let t=b;t<=x;t+=d){const e=170-(t-f)/m*150;g+=`\n\t\t\t\t<text \n\t\t\t\t\tx="45" \n\t\t\t\t\ty="${e+4}" \n\t\t\t\t\tclass="viz-y-axis-text"\n\t\t\t\t\ttext-anchor="end"\n\t\t\t\t>\n\t\t\t\t\t${Math.round(t)}\n\t\t\t\t</text>\n\t\t\t\t<line \n\t\t\t\t\tx1="50" \n\t\t\t\t\ty1="${e}" \n\t\t\t\t\tx2="55" \n\t\t\t\t\ty2="${e}" \n\t\t\t\t\tclass="viz-y-axis-tick"\n\t\t\t\t/>\n\t\t\t`}const v=e.map((t,n)=>({x:65+n/(e.length-1)*315,y:170-(t.value-f)/m*150,value:t.value,label:t.label})),$="smooth"===this.getAttribute("variant"),w=this.hasAttribute("fill");let y;y=$?this.createSmoothPath(v):v.map((t,e)=>`${0===e?"M":"L"} ${t.x} ${t.y}`).join(" ");let k="";w&&(k=`<path d="${y+` L ${v[v.length-1].x} 170 L ${v[0].x} 170 Z`}" class="viz-area" />`);let S="",A="";v.forEach((t,e)=>{S+=`\n\t\t\t\t<g class="viz-point-group" data-index="${e}">\n\t\t\t\t\t<circle \n\t\t\t\t\t\tcx="${t.x}" \n\t\t\t\t\t\tcy="${t.y}" \n\t\t\t\t\t\tr="4" \n\t\t\t\t\t\tclass="viz-point"\n\t\t\t\t\t/>\n\t\t\t\t\t<text \n\t\t\t\t\t\tx="${t.x}" \n\t\t\t\t\t\ty="${t.y-10}" \n\t\t\t\t\t\tclass="viz-value-text"\n\t\t\t\t\t\ttext-anchor="middle"\n\t\t\t\t\t>\n\t\t\t\t\t\t${t.value}\n\t\t\t\t\t</text>\n\t\t\t\t</g>\n\t\t\t`,A+=`\n\t\t\t\t<text \n\t\t\t\t\tx="${t.x}" \n\t\t\t\t\ty="190" \n\t\t\t\t\tclass="viz-label-text"\n\t\t\t\t\ttext-anchor="middle"\n\t\t\t\t>\n\t\t\t\t\t${t.label}\n\t\t\t\t</text>\n\t\t\t`}),this.innerHTML=t`
<div class="viz-line-container">
<svg viewBox="0 0 ${400} ${200}" class="viz-svg">
<!-- Grid lines (optional) -->
<defs>
<pattern
id="grid"
width="40"
height="20"
patternUnits="userSpaceOnUse"
>
<path
d="M 40 0 L 0 0 0 20"
fill="none"
stroke="var(--paletteDivider, #e0e0e0)"
stroke-width="0.5"
opacity="0.3"
/>
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
<!-- Y-axis -->
${g}
<!-- Area fill (if enabled) -->
${k}
<!-- Line path -->
<path
d="${y}"
class="viz-line"
fill="none"
stroke="var(--line-base-color)"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<!-- Bottom labels -->
${A}
<!-- Data points with hover values -->
${S}
</svg>
</div>
`}createSmoothPath(t){if(0===t.length)return"";if(1===t.length)return`M ${t[0].x} ${t[0].y}`;if(2===t.length)return`M ${t[0].x} ${t[0].y} L ${t[1].x} ${t[1].y}`;let e=`M ${t[0].x} ${t[0].y}`;const n=[{x:t[0].x-(t[1].x-t[0].x),y:t[0].y-(t[1].y-t[0].y)},...t,{x:t[t.length-1].x+(t[t.length-1].x-t[t.length-2].x),y:t[t.length-1].y+(t[t.length-1].y-t[t.length-2].y)}];for(let s=1;s<t.length;s++){const t=n[s-1],i=n[s],r=n[s+1],a=n[s+2];e+=` C ${i.x+(r.x-t.x)/6} ${i.y+(r.y-t.y)/6}, ${r.x-(a.x-i.x)/6} ${r.y-(a.y-i.y)/6}, ${r.x} ${r.y}`}return e}}function Z(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var B={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function I(t){B=t}var H={exec:()=>null};function V(t,e=""){let n="string"==typeof t?t:t.source,s={replace:(t,e)=>{let i="string"==typeof e?e:e.source;return i=i.replace(U.caret,"$1"),n=n.replace(t,i),s},getRegex:()=>new RegExp(n,e)};return s}var U={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},J=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,W=/(?:[*+-]|\d{1,9}[.)])/,G=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,K=V(G).replace(/bull/g,W).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Q=V(G).replace(/bull/g,W).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),X=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Y=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,tt=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Y).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),et=V(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,W).getRegex(),nt="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",st=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,it=V("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",st).replace("tag",nt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),rt=V(X).replace("hr",J).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",nt).getRegex(),at={blockquote:V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",rt).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:tt,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:J,html:it,lheading:K,list:et,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:rt,table:H,text:/^[^\n]+/},ot=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",J).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",nt).getRegex(),lt={...at,lheading:Q,table:ot,paragraph:V(X).replace("hr",J).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ot).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",nt).getRegex()},ct={...at,html:V("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?: