haori 0.22.1 → 0.22.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.ja.md +1 -1
- package/README.md +1 -1
- package/dist/haori.cjs.js +1 -1
- package/dist/haori.es.js +65 -58
- package/dist/haori.iife.js +5 -5
- package/package.json +1 -1
package/README.ja.md
CHANGED
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
|
|
4
4
|
|
|
5
|
-
Version: 0.22.
|
|
5
|
+
Version: 0.22.2
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
package/dist/haori.cjs.js
CHANGED
|
@@ -15,7 +15,7 @@ ${y}
|
|
|
15
15
|
"use strict";
|
|
16
16
|
${b}
|
|
17
17
|
`)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(g.attrName(t,"dialog")).replace(/\\n/g,`
|
|
18
|
-
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k?(document.body.querySelectorAll(k).forEach(j=>{const $=T.get(j);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`)):C.push(e),C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await x.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(he))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(he,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(he),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return Be(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();$e.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Qe]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
18
|
+
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k)document.body.querySelectorAll(k).forEach(j=>{const $=T.get(j);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`);else if(b==="open"||b==="close"){const O=e.getTarget().closest("dialog");O?C.push(T.get(O)):m.error("Haori",`Ancestor <dialog> not found (${S})`)}else C.push(e);if(C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await x.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(he))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(he,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(he),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return Be(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();$e.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Qe]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
19
19
|
`)});for(const u of h)o.push({message:u})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,h]of Object.entries(a.errors))Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
20
20
|
`)}):typeof h=="string"?o.push({key:l,message:h}):h!=null&&o.push({key:l,message:String(h)});if(o.length===0)for(const[l,h]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
21
21
|
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(x.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(x.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return x.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=c.runtime==="demo"&&!_e(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=tt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[v,R]of Object.entries(t))R==null?p.append(v,""):R instanceof Blob?p.append(v,R):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[v,R]of Object.entries(t))R!==void 0&&(R===null?p.append(v,""):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:it(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(x.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let q=g;class nt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Be(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof M?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new q(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${c.prefix}importing`,""),F.importStart(t,n),nt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=T.get(h);u instanceof M?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),F.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=$e.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const v of Object.keys(l))v in i||(i[v]={value:l[v],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(v=>{if(v instanceof M){if(d.canSkipUnchangedNestedEach(v))return;p.push(d.evaluateAll(v,t))}else v instanceof V&&p.push(d.evaluateText(v))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof M){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=T.get(l);u instanceof M&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=T.get(l);h instanceof M&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((b,S)=>{const k=d.createListKey(b,n?String(n):null,S);o.push(k),a.set(k,{item:b,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${c.prefix}each-before`)&&!b.hasAttribute(`${c.prefix}each-after`));const p=u.map(b=>b.getListKey());u=u.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const v=u.map(b=>b.getListKey()),R=new Map;u.forEach(b=>{const S=b.getListKey();S!==null&&!R.has(S)&&R.set(S,b)});const I=e.getChildElementFragments().slice(),A=I.filter(b=>b.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((b,S)=>{const{item:k,itemIndex:C}=a.get(b);let O;const j=R.get(b);if(j)O=j,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then(()=>{const ee=I[$]??null;return e.insertBefore(O,ee).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const b=o.filter($=>$!==null),S=v.filter($=>$!==null),k=new Set(S),C=b.filter($=>!k.has($)),j=p.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,j,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let x=d;const _=class _{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=T.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[_.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(_.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof M&&new q(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=T.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof M&&i.syncValue();const n=()=>{new q(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};_.HISTORY_STATE_KEY="__haoriHistoryState__",_.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let fe=_;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=T.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=D.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=D.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Z=D;function st(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=T.get(e);if(!(r instanceof M)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const v=p.target;h.observedRows.has(v)&&(p.isIntersecting?h.visibleRows.has(v)||(h.visibleRows.add(v),u=!0):h.visibleRows.delete(v)&&(u=!0))}),u&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof M&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,st(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);x.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let Y=w;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers();const e=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),new fe().start(),Z.syncTree(document.body),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&x.isAliasedAttributeReflection(n,i.attributeName))break;x.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),Z.syncElement(n),Y.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Z.cleanupTree(n),Y.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),Z.syncTree(n),Y.syncTree(n))}),i.target instanceof Element&&Y.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}};H._initialized=!1,H._mutationObservers=[];let ae=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ae.init):ae.init();const at=()=>Q.waitForRenders(),ot="0.20.0";exports.Core=x;exports.Env=c;exports.Form=E;exports.Fragment=T;exports.Haori=Q;exports.Log=m;exports.Queue=P;exports.default=Q;exports.version=ot;exports.waitForRenders=at;
|
package/dist/haori.es.js
CHANGED
|
@@ -1679,8 +1679,8 @@ const X = class X {
|
|
|
1679
1679
|
}
|
|
1680
1680
|
};
|
|
1681
1681
|
X.FRAGMENT_CACHE = /* @__PURE__ */ new WeakMap();
|
|
1682
|
-
let
|
|
1683
|
-
const K = class K extends
|
|
1682
|
+
let T = X;
|
|
1683
|
+
const K = class K extends T {
|
|
1684
1684
|
/**
|
|
1685
1685
|
* エレメントフラグメントのコンストラクタ。
|
|
1686
1686
|
* アトリビュートや子フラグメントの作成も行います。
|
|
@@ -1710,7 +1710,7 @@ const K = class K extends R {
|
|
|
1710
1710
|
this.attributeMap.set(t, i);
|
|
1711
1711
|
}
|
|
1712
1712
|
}), e.childNodes.forEach((t) => {
|
|
1713
|
-
const r =
|
|
1713
|
+
const r = T.get(t);
|
|
1714
1714
|
r.setParent(this), this.children.push(r);
|
|
1715
1715
|
});
|
|
1716
1716
|
}
|
|
@@ -2242,7 +2242,7 @@ const K = class K extends R {
|
|
|
2242
2242
|
element: a,
|
|
2243
2243
|
rawName: e,
|
|
2244
2244
|
template: r
|
|
2245
|
-
}), l = s.isEvaluate || s.isRawEvaluate, h = e === t && K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()), u = s.isSingleExpression(), p = G.joinEvaluateResults(o.results), v = o.results.length === 1 ? o.results[0] : p,
|
|
2245
|
+
}), l = s.isEvaluate || s.isRawEvaluate, h = e === t && K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()), u = s.isSingleExpression(), p = G.joinEvaluateResults(o.results), v = o.results.length === 1 ? o.results[0] : p, R = !s.isForceEvaluation() && (t !== e || h || u ? o.hasUnresolvedReference || v === null || v === void 0 || v === !1 : l && p === ""), I = s.isForceEvaluation() ? r : u ? v : p, A = i && s.isEvaluate && t === "value" && (a instanceof HTMLInputElement && this.INPUT_EVENT_TYPES.includes(a.type) || a instanceof HTMLTextAreaElement || a instanceof HTMLSelectElement), y = a.getRootNode(), b = A && a === y.activeElement, S = R || I === null || I === !1 ? null : String(I), k = e !== t && a.getAttribute(e) !== r, C = S === null ? a.hasAttribute(t) : a.getAttribute(t) !== S, O = A && !b && S !== null && a.value !== S, j = t === "checked" && a instanceof HTMLInputElement && (a.type === "checkbox" || a.type === "radio"), $ = t === "selected" && a instanceof HTMLOptionElement, _ = y.activeElement, be = _ !== null && (j && a === _ || $ && a.closest("select") === _), te = S !== null, ve = j && !be && a.checked !== te, ye = $ && !be && a.selected !== te;
|
|
2246
2246
|
return !k && !C && !O && !ve && !ye ? (A && !b && S !== null && (this.value = this.normalizeValueForElement(a, S)), Promise.resolve()) : (this.skipMutationAttributes = !0, P.enqueue(() => {
|
|
2247
2247
|
k && a.setAttribute(e, r), S === null ? a.removeAttribute(t) : (C && (a.setAttribute(t, S), t === `${c.prefix}bind` && this.recordSelfWrittenBind(S)), A && !b && (this.value = this.normalizeValueForElement(a, S), O && (a.value = S))), ve && (a.checked = te), ye && (a.selected = te);
|
|
2248
2248
|
}).finally(() => {
|
|
@@ -2341,7 +2341,7 @@ const K = class K extends R {
|
|
|
2341
2341
|
const i = t ? r.nextSibling : r;
|
|
2342
2342
|
let n = t ? r.nextSibling : r;
|
|
2343
2343
|
for (; n !== null; ) {
|
|
2344
|
-
const s =
|
|
2344
|
+
const s = T.get(n);
|
|
2345
2345
|
if (s !== null) {
|
|
2346
2346
|
const a = this.children.indexOf(s);
|
|
2347
2347
|
if (a !== -1)
|
|
@@ -2530,7 +2530,7 @@ K.BOOLEAN_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
|
2530
2530
|
"selected"
|
|
2531
2531
|
]);
|
|
2532
2532
|
let M = K;
|
|
2533
|
-
class V extends
|
|
2533
|
+
class V extends T {
|
|
2534
2534
|
/**
|
|
2535
2535
|
* テキストフラグメントのコンストラクタ。
|
|
2536
2536
|
* 対象テキストノードの内容を初期化します。
|
|
@@ -2608,7 +2608,7 @@ class V extends R {
|
|
|
2608
2608
|
});
|
|
2609
2609
|
}
|
|
2610
2610
|
}
|
|
2611
|
-
class pe extends
|
|
2611
|
+
class pe extends T {
|
|
2612
2612
|
/**
|
|
2613
2613
|
* コメントフラグメントのコンストラクタ。
|
|
2614
2614
|
* 対象コメントノードの内容を初期化します。
|
|
@@ -3264,16 +3264,16 @@ class E {
|
|
|
3264
3264
|
if (Array.isArray(u)) {
|
|
3265
3265
|
const p = e.getChildElementFragments();
|
|
3266
3266
|
for (let v = 0; v < p.length; v++) {
|
|
3267
|
-
const
|
|
3267
|
+
const R = p[v];
|
|
3268
3268
|
u.length > v ? s.push(
|
|
3269
3269
|
E.setPartValues(
|
|
3270
|
-
|
|
3270
|
+
R,
|
|
3271
3271
|
u[v],
|
|
3272
3272
|
v,
|
|
3273
3273
|
i,
|
|
3274
3274
|
n
|
|
3275
3275
|
)
|
|
3276
|
-
) : s.push(E.setPartValues(
|
|
3276
|
+
) : s.push(E.setPartValues(R, {}, v, i, n));
|
|
3277
3277
|
}
|
|
3278
3278
|
}
|
|
3279
3279
|
} else
|
|
@@ -3358,7 +3358,7 @@ class E {
|
|
|
3358
3358
|
t instanceof HTMLFormElement ? r.push(t) : r.push(...Array.from(t.querySelectorAll("form")));
|
|
3359
3359
|
const i = [];
|
|
3360
3360
|
for (const n of r) {
|
|
3361
|
-
const s =
|
|
3361
|
+
const s = T.get(n);
|
|
3362
3362
|
s instanceof M && i.push(s);
|
|
3363
3363
|
}
|
|
3364
3364
|
return i;
|
|
@@ -3746,7 +3746,7 @@ function Ye(f, e) {
|
|
|
3746
3746
|
return null;
|
|
3747
3747
|
if (!t.includes("{{"))
|
|
3748
3748
|
return t;
|
|
3749
|
-
const r =
|
|
3749
|
+
const r = T.get(f), i = r instanceof M ? r.getBindingData() : {}, n = Ge(t, i);
|
|
3750
3750
|
return n === "" ? null : n;
|
|
3751
3751
|
}
|
|
3752
3752
|
function Je(f, e, t) {
|
|
@@ -4075,7 +4075,7 @@ const g = class g {
|
|
|
4075
4075
|
if (y) {
|
|
4076
4076
|
const b = document.body.querySelector(y);
|
|
4077
4077
|
b !== null ? r.formFragment = E.getFormFragment(
|
|
4078
|
-
|
|
4078
|
+
T.get(b)
|
|
4079
4079
|
) : m.error(
|
|
4080
4080
|
"Haori",
|
|
4081
4081
|
`Form element not found: ${y} (${g.attrName(t, "form")})`
|
|
@@ -4224,7 +4224,7 @@ ${y}
|
|
|
4224
4224
|
if (A) {
|
|
4225
4225
|
const y = document.body.querySelectorAll(A);
|
|
4226
4226
|
y.length > 0 ? (r.bindFragments = [], y.forEach((b) => {
|
|
4227
|
-
const S =
|
|
4227
|
+
const S = T.get(b);
|
|
4228
4228
|
S && r.bindFragments.push(S);
|
|
4229
4229
|
})) : m.error(
|
|
4230
4230
|
"Haori",
|
|
@@ -4256,8 +4256,8 @@ ${y}
|
|
|
4256
4256
|
}
|
|
4257
4257
|
const v = t ? g.attrName(t, "bind-merge") : g.attrName(null, "bind-merge", !0);
|
|
4258
4258
|
e.hasAttribute(v) && (r.bindMerge = !0);
|
|
4259
|
-
const
|
|
4260
|
-
e.hasAttribute(
|
|
4259
|
+
const R = t ? g.attrName(t, "bind-transform") : g.attrName(null, "bind-transform", !0);
|
|
4260
|
+
e.hasAttribute(R) && (r.bindTransform = e.getRawAttribute(R));
|
|
4261
4261
|
const I = t ? g.attrName(t, "copy-params") : null;
|
|
4262
4262
|
if (I && e.hasAttribute(I)) {
|
|
4263
4263
|
const A = e.getRawAttribute(I);
|
|
@@ -4271,7 +4271,7 @@ ${y}
|
|
|
4271
4271
|
if (b) {
|
|
4272
4272
|
const S = document.body.querySelectorAll(b);
|
|
4273
4273
|
S.length > 0 ? (r.adjustFragments = [], S.forEach((k) => {
|
|
4274
|
-
const C =
|
|
4274
|
+
const C = T.get(k);
|
|
4275
4275
|
C && r.adjustFragments.push(C);
|
|
4276
4276
|
})) : m.error(
|
|
4277
4277
|
"Haori",
|
|
@@ -4334,7 +4334,7 @@ ${b}
|
|
|
4334
4334
|
if (b) {
|
|
4335
4335
|
const S = document.body.querySelector(b);
|
|
4336
4336
|
S !== null ? r.historyFormFragment = E.getFormFragment(
|
|
4337
|
-
|
|
4337
|
+
T.get(S)
|
|
4338
4338
|
) : m.error(
|
|
4339
4339
|
"Haori",
|
|
4340
4340
|
`Form element not found: ${b} (${g.attrName(t, "history-form")})`
|
|
@@ -4355,10 +4355,17 @@ ${b}
|
|
|
4355
4355
|
if (!e.hasAttribute(S))
|
|
4356
4356
|
return;
|
|
4357
4357
|
const k = e.getRawAttribute(S), C = [];
|
|
4358
|
-
if (k
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4358
|
+
if (k)
|
|
4359
|
+
document.body.querySelectorAll(k).forEach((j) => {
|
|
4360
|
+
const $ = T.get(j);
|
|
4361
|
+
$ && C.push($);
|
|
4362
|
+
}), C.length === 0 && m.error("Haori", `Element not found: ${k} (${S})`);
|
|
4363
|
+
else if (b === "open" || b === "close") {
|
|
4364
|
+
const O = e.getTarget().closest("dialog");
|
|
4365
|
+
O ? C.push(T.get(O)) : m.error("Haori", `Ancestor <dialog> not found (${S})`);
|
|
4366
|
+
} else
|
|
4367
|
+
C.push(e);
|
|
4368
|
+
if (C.length > 0)
|
|
4362
4369
|
switch (b) {
|
|
4363
4370
|
case "reset-before":
|
|
4364
4371
|
r.resetBeforeFragments = C;
|
|
@@ -4391,7 +4398,7 @@ ${b}
|
|
|
4391
4398
|
if (b) {
|
|
4392
4399
|
const S = document.body.querySelector(b);
|
|
4393
4400
|
if (S !== null) {
|
|
4394
|
-
const k =
|
|
4401
|
+
const k = T.get(S);
|
|
4395
4402
|
k ? r.copySourceFragment = k : m.error(
|
|
4396
4403
|
"Haori",
|
|
4397
4404
|
`Element is not managed by Haori: ${b} (${y})`
|
|
@@ -4412,7 +4419,7 @@ ${b}
|
|
|
4412
4419
|
if (A) {
|
|
4413
4420
|
const y = document.body.querySelector(A);
|
|
4414
4421
|
y !== null ? r.formFragment = E.getFormFragment(
|
|
4415
|
-
|
|
4422
|
+
T.get(y)
|
|
4416
4423
|
) : m.error(
|
|
4417
4424
|
"Haori",
|
|
4418
4425
|
`Form element not found: ${A} (${g.attrName(null, "fetch-form", !0)})`
|
|
@@ -4513,7 +4520,7 @@ ${b}
|
|
|
4513
4520
|
}
|
|
4514
4521
|
const a = Object.keys(i).length > 0;
|
|
4515
4522
|
if (n) {
|
|
4516
|
-
const h = { ...s || {} }, u = r.requestedMethod, p = r.effectiveMethod, v = r.transportMode === "query-get",
|
|
4523
|
+
const h = { ...s || {} }, u = r.requestedMethod, p = r.effectiveMethod, v = r.transportMode === "query-get", R = r.queryString;
|
|
4517
4524
|
if (v && m.info("Haori demo fetch normalization", {
|
|
4518
4525
|
runtime: c.runtime,
|
|
4519
4526
|
requestedMethod: u,
|
|
@@ -4521,14 +4528,14 @@ ${b}
|
|
|
4521
4528
|
transportMode: "query-get",
|
|
4522
4529
|
url: n,
|
|
4523
4530
|
payload: a ? i : void 0,
|
|
4524
|
-
queryString:
|
|
4531
|
+
queryString: R
|
|
4525
4532
|
}), this.options.targetFragment && n) {
|
|
4526
4533
|
const I = performance.now(), A = {
|
|
4527
4534
|
runtime: c.runtime,
|
|
4528
4535
|
requestedMethod: u,
|
|
4529
4536
|
effectiveMethod: p,
|
|
4530
4537
|
transportMode: v ? "query-get" : "http",
|
|
4531
|
-
...v ? { queryString:
|
|
4538
|
+
...v ? { queryString: R } : {}
|
|
4532
4539
|
};
|
|
4533
4540
|
return N.fetchStart(
|
|
4534
4541
|
this.options.targetFragment.getTarget(),
|
|
@@ -4713,12 +4720,12 @@ ${b}
|
|
|
4713
4720
|
const l = /* @__PURE__ */ new Map(), h = [];
|
|
4714
4721
|
for (const u of a)
|
|
4715
4722
|
if (u && typeof u == "object" && !Array.isArray(u)) {
|
|
4716
|
-
const p = u.key, v = u.message,
|
|
4723
|
+
const p = u.key, v = u.message, R = typeof p == "string" && p.length > 0 ? p : null, I = typeof v == "string" ? v : v != null ? String(v) : "";
|
|
4717
4724
|
if (I.length === 0)
|
|
4718
4725
|
continue;
|
|
4719
|
-
if (
|
|
4720
|
-
const A = l.get(
|
|
4721
|
-
A.push(I), l.set(
|
|
4726
|
+
if (R !== null) {
|
|
4727
|
+
const A = l.get(R) ?? [];
|
|
4728
|
+
A.push(I), l.set(R, A);
|
|
4722
4729
|
} else
|
|
4723
4730
|
h.push(I);
|
|
4724
4731
|
} else typeof u == "string" && u.length > 0 && h.push(u);
|
|
@@ -4993,13 +5000,13 @@ ${b}
|
|
|
4993
5000
|
if (/multipart\/form-data/i.test(u)) {
|
|
4994
5001
|
s.delete("Content-Type");
|
|
4995
5002
|
const p = new FormData();
|
|
4996
|
-
for (const [v,
|
|
4997
|
-
|
|
5003
|
+
for (const [v, R] of Object.entries(t))
|
|
5004
|
+
R == null ? p.append(v, "") : R instanceof Blob ? p.append(v, R) : Array.isArray(R) ? R.forEach((I) => p.append(v, String(I))) : typeof R == "object" ? p.append(v, JSON.stringify(R)) : p.append(v, String(R));
|
|
4998
5005
|
n.body = p;
|
|
4999
5006
|
} else if (/application\/x-www-form-urlencoded/i.test(u)) {
|
|
5000
5007
|
const p = new URLSearchParams();
|
|
5001
|
-
for (const [v,
|
|
5002
|
-
|
|
5008
|
+
for (const [v, R] of Object.entries(t))
|
|
5009
|
+
R !== void 0 && (R === null ? p.append(v, "") : Array.isArray(R) ? R.forEach((I) => p.append(v, String(I))) : typeof R == "object" ? p.append(v, JSON.stringify(R)) : p.append(v, String(R)));
|
|
5003
5010
|
n.body = p;
|
|
5004
5011
|
} else
|
|
5005
5012
|
s.set("Content-Type", "application/json"), n.body = JSON.stringify(t);
|
|
@@ -5259,7 +5266,7 @@ const d = class d {
|
|
|
5259
5266
|
* @returns data-attr-* の内部反映なら true
|
|
5260
5267
|
*/
|
|
5261
5268
|
static isAliasedAttributeReflection(e, t) {
|
|
5262
|
-
const r =
|
|
5269
|
+
const r = T.get(e);
|
|
5263
5270
|
return r instanceof M ? r.hasAttribute(
|
|
5264
5271
|
`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`
|
|
5265
5272
|
) : !1;
|
|
@@ -5395,7 +5402,7 @@ const d = class d {
|
|
|
5395
5402
|
if (t.removeAttribute(`${c.prefix}importing`), N.importEnd(t, n, o, s), !document.body.hasAttribute("data-haori-ready")) {
|
|
5396
5403
|
const l = [];
|
|
5397
5404
|
return t.childNodes.forEach((h) => {
|
|
5398
|
-
const u =
|
|
5405
|
+
const u = T.get(h);
|
|
5399
5406
|
u instanceof M ? l.push(d.scan(u.getTarget())) : u instanceof V && l.push(d.evaluateText(u));
|
|
5400
5407
|
}), Promise.all(l).then(() => {
|
|
5401
5408
|
});
|
|
@@ -5415,7 +5422,7 @@ const d = class d {
|
|
|
5415
5422
|
* @returns Promise (スキャンが完了したときに解決される)
|
|
5416
5423
|
*/
|
|
5417
5424
|
static scan(e) {
|
|
5418
|
-
const t =
|
|
5425
|
+
const t = T.get(e);
|
|
5419
5426
|
return t ? d.initializeElementFragment(t, !1) : Promise.resolve();
|
|
5420
5427
|
}
|
|
5421
5428
|
/**
|
|
@@ -5529,7 +5536,7 @@ const d = class d {
|
|
|
5529
5536
|
* @returns Promise (DOM操作が完了したときに解決される)
|
|
5530
5537
|
*/
|
|
5531
5538
|
static setAttribute(e, t, r, i = !1) {
|
|
5532
|
-
const n =
|
|
5539
|
+
const n = T.get(e), s = d.getAliasedAttributeName(t);
|
|
5533
5540
|
if (s !== null)
|
|
5534
5541
|
return r === null ? n.removeAliasedAttribute(t, s) : n.setAliasedAttribute(
|
|
5535
5542
|
t,
|
|
@@ -5625,7 +5632,7 @@ const d = class d {
|
|
|
5625
5632
|
* @returns Promise (DOM操作が完了したときに解決される)
|
|
5626
5633
|
*/
|
|
5627
5634
|
static setBindingData(e, t, r = /* @__PURE__ */ new Set(), i = !1, n = !0) {
|
|
5628
|
-
const s =
|
|
5635
|
+
const s = T.get(e), a = s.getRawBindingData();
|
|
5629
5636
|
s.setBindingData(t), n && N.bindChange(e, a, t, "manual");
|
|
5630
5637
|
const o = () => {
|
|
5631
5638
|
s.markBindingWorkStart();
|
|
@@ -5664,7 +5671,7 @@ const d = class d {
|
|
|
5664
5671
|
* `resolved: true` のときは解決済みスコープ(常にオブジェクト)。
|
|
5665
5672
|
*/
|
|
5666
5673
|
static getBindingData(e, t = {}) {
|
|
5667
|
-
const r =
|
|
5674
|
+
const r = T.get(e);
|
|
5668
5675
|
return r instanceof M ? t.resolved ? r.getBindingData() : r.getRawBindingData() : null;
|
|
5669
5676
|
}
|
|
5670
5677
|
/**
|
|
@@ -5683,7 +5690,7 @@ const d = class d {
|
|
|
5683
5690
|
* @return 解決済みスコープと各キーの由来情報
|
|
5684
5691
|
*/
|
|
5685
5692
|
static dumpScope(e) {
|
|
5686
|
-
const t =
|
|
5693
|
+
const t = T.get(e);
|
|
5687
5694
|
if (!t)
|
|
5688
5695
|
return { resolved: {}, sources: {} };
|
|
5689
5696
|
const r = t.getBindingData(), i = {}, n = (l) => {
|
|
@@ -5731,10 +5738,10 @@ const d = class d {
|
|
|
5731
5738
|
* @param node 追加するノード
|
|
5732
5739
|
*/
|
|
5733
5740
|
static addNode(e, t) {
|
|
5734
|
-
const r =
|
|
5741
|
+
const r = T.get(e);
|
|
5735
5742
|
if (r.isSkipMutationNodes())
|
|
5736
5743
|
return;
|
|
5737
|
-
const i =
|
|
5744
|
+
const i = T.get(t.nextSibling), n = T.get(t);
|
|
5738
5745
|
n && (r.insertBefore(n, i), n instanceof M ? d.scan(n.getTarget()) : n instanceof V && d.evaluateText(n));
|
|
5739
5746
|
}
|
|
5740
5747
|
/**
|
|
@@ -5743,7 +5750,7 @@ const d = class d {
|
|
|
5743
5750
|
* @param node 削除するノード
|
|
5744
5751
|
*/
|
|
5745
5752
|
static removeNode(e) {
|
|
5746
|
-
const t =
|
|
5753
|
+
const t = T.get(e);
|
|
5747
5754
|
if (t) {
|
|
5748
5755
|
const r = t.getParent();
|
|
5749
5756
|
if (r && r.isSkipMutationNodes())
|
|
@@ -5758,7 +5765,7 @@ const d = class d {
|
|
|
5758
5765
|
* @param text 新しいテキスト
|
|
5759
5766
|
*/
|
|
5760
5767
|
static changeText(e, t) {
|
|
5761
|
-
const r =
|
|
5768
|
+
const r = T.get(e);
|
|
5762
5769
|
r && r.setContent(t);
|
|
5763
5770
|
}
|
|
5764
5771
|
/**
|
|
@@ -5770,7 +5777,7 @@ const d = class d {
|
|
|
5770
5777
|
* @returns Promise (DOM操作が完了したときに解決される)
|
|
5771
5778
|
*/
|
|
5772
5779
|
static changeValue(e, t) {
|
|
5773
|
-
const r =
|
|
5780
|
+
const r = T.get(e);
|
|
5774
5781
|
if (r.getValue() === t)
|
|
5775
5782
|
return Promise.resolve();
|
|
5776
5783
|
const i = [];
|
|
@@ -6066,10 +6073,10 @@ const d = class d {
|
|
|
6066
6073
|
(l) => !l.hasAttribute(`${c.prefix}each-before`) && !l.hasAttribute(`${c.prefix}each-after`)
|
|
6067
6074
|
).forEach((l) => {
|
|
6068
6075
|
if (!s) {
|
|
6069
|
-
const u =
|
|
6076
|
+
const u = T.get(l);
|
|
6070
6077
|
u instanceof M && (r = u.clone(), d.markFreshInitializationSkippable(r), e.setTemplate(r), s = !0);
|
|
6071
6078
|
}
|
|
6072
|
-
const h =
|
|
6079
|
+
const h = T.get(l);
|
|
6073
6080
|
h instanceof M && e.getChildren().includes(h) && (e.removeChild(h), h.setMounted(!1)), l.parentNode && l.parentNode.removeChild(l);
|
|
6074
6081
|
});
|
|
6075
6082
|
}
|
|
@@ -6332,10 +6339,10 @@ const d = class d {
|
|
|
6332
6339
|
);
|
|
6333
6340
|
const p = u.map((b) => b.getListKey());
|
|
6334
6341
|
u = u.filter((b) => l.has(String(b.getListKey())) ? !0 : (h.push(b.remove()), !1));
|
|
6335
|
-
const v = u.map((b) => b.getListKey()),
|
|
6342
|
+
const v = u.map((b) => b.getListKey()), R = /* @__PURE__ */ new Map();
|
|
6336
6343
|
u.forEach((b) => {
|
|
6337
6344
|
const S = b.getListKey();
|
|
6338
|
-
S !== null && !
|
|
6345
|
+
S !== null && !R.has(S) && R.set(S, b);
|
|
6339
6346
|
});
|
|
6340
6347
|
const I = e.getChildElementFragments().slice(), A = I.filter(
|
|
6341
6348
|
(b) => b.hasAttribute(`${c.prefix}each-before`)
|
|
@@ -6344,7 +6351,7 @@ const d = class d {
|
|
|
6344
6351
|
return o.forEach((b, S) => {
|
|
6345
6352
|
const { item: k, itemIndex: C } = a.get(b);
|
|
6346
6353
|
let O;
|
|
6347
|
-
const j =
|
|
6354
|
+
const j = R.get(b);
|
|
6348
6355
|
if (j)
|
|
6349
6356
|
O = j, y = y.then(
|
|
6350
6357
|
() => d.updateRowFragment(
|
|
@@ -6558,7 +6565,7 @@ const Z = class Z {
|
|
|
6558
6565
|
*/
|
|
6559
6566
|
constructor(e = document) {
|
|
6560
6567
|
this.customEventHandlers = /* @__PURE__ */ new Map(), this.onClick = (t) => this.delegate(t, "click"), this.onChange = (t) => this.delegate(t, "change"), this.onInput = (t) => this.delegate(t, "input"), this.onLoadCapture = (t) => this.delegate(t, "load"), this.onWindowLoad = () => {
|
|
6561
|
-
const t = document.documentElement, r =
|
|
6568
|
+
const t = document.documentElement, r = T.get(t);
|
|
6562
6569
|
r && new q(r, "load").run();
|
|
6563
6570
|
}, this.onPopstate = (t) => {
|
|
6564
6571
|
const r = t.state;
|
|
@@ -6637,7 +6644,7 @@ const Z = class Z {
|
|
|
6637
6644
|
this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach((i) => {
|
|
6638
6645
|
if (i.getAttribute(this.onAttributeName) !== e)
|
|
6639
6646
|
return;
|
|
6640
|
-
const n =
|
|
6647
|
+
const n = T.get(i);
|
|
6641
6648
|
n instanceof M && new q(n, "on", t).run().catch((s) => {
|
|
6642
6649
|
m.error("[Haori]", "Procedure execution error:", s);
|
|
6643
6650
|
});
|
|
@@ -6683,7 +6690,7 @@ const Z = class Z {
|
|
|
6683
6690
|
return;
|
|
6684
6691
|
}
|
|
6685
6692
|
r.hasAttribute(`${c.prefix}${t}-prevent`) && e.preventDefault();
|
|
6686
|
-
const i =
|
|
6693
|
+
const i = T.get(r);
|
|
6687
6694
|
if (!i)
|
|
6688
6695
|
return;
|
|
6689
6696
|
(t === "change" || t === "input") && i instanceof M && i.syncValue();
|
|
@@ -6767,7 +6774,7 @@ const D = class D {
|
|
|
6767
6774
|
}));
|
|
6768
6775
|
}
|
|
6769
6776
|
static syncElement(e) {
|
|
6770
|
-
const t = D.registrations.get(e), r =
|
|
6777
|
+
const t = D.registrations.get(e), r = T.get(e);
|
|
6771
6778
|
if (!r || !D.shouldObserve(r)) {
|
|
6772
6779
|
t && (t.observer.disconnect(), D.registrations.delete(e));
|
|
6773
6780
|
return;
|
|
@@ -6909,7 +6916,7 @@ const w = class w {
|
|
|
6909
6916
|
* @param element 対象要素
|
|
6910
6917
|
*/
|
|
6911
6918
|
static syncElement(e) {
|
|
6912
|
-
const t = w.registrations.get(e), r =
|
|
6919
|
+
const t = w.registrations.get(e), r = T.get(e);
|
|
6913
6920
|
if (!(r instanceof M) || !w.shouldObserve(r)) {
|
|
6914
6921
|
t && (t.observer.disconnect(), w.registrations.delete(e));
|
|
6915
6922
|
return;
|
|
@@ -7245,7 +7252,7 @@ export {
|
|
|
7245
7252
|
x as Core,
|
|
7246
7253
|
c as Env,
|
|
7247
7254
|
E as Form,
|
|
7248
|
-
|
|
7255
|
+
T as Fragment,
|
|
7249
7256
|
ee as Haori,
|
|
7250
7257
|
m as Log,
|
|
7251
7258
|
P as Queue,
|
package/dist/haori.iife.js
CHANGED
|
@@ -3,20 +3,20 @@ var Haori=function(H){"use strict";const Q=class Q{static isEnabled(){return Q.d
|
|
|
3
3
|
${s};
|
|
4
4
|
return (${e});`:`"use strict";
|
|
5
5
|
return (${e});`;try{return n=new Function(...r,a),this.EXPRESSION_CACHE.set(i,n),{bindKeys:r,evaluator:n,compileFailed:!1}}catch(o){return m.error("[Haori]","Failed to compile expression:",e,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,l=t[n-2]||null,h=t[n-3]||null;if(this.startsObjectKey(o,i,l,h)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const u=this.startsMemberAccess(i)?"member":"array";r.push(u);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
6
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...Ke},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.loggedForbiddenKeySignatures=new Set,B.loggedForbiddenKeyResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(e=>!B.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class de{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await de.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const me=class me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};me.ASYNC_QUEUE=new de;let P=me;const x=class x{static reset(){x.ELEMENT_STORES.clear(),x.ensureGlobalAccess()}static snapshot(){return x.ensureGlobalAccess(),[...x.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!L.isEnabled()||!e||t.length===0)return;x.ensureGlobalAccess();const i=x.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=x.getOrCreateCounter(i.attributes,e.rawName,e.template);x.updateCounter(s,t,r);return}const n=x.getOrCreateCounter(i.texts,String(e.childIndex),e.template);x.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[x.GLOBAL_KEY]===void 0&&(e[x.GLOBAL_KEY]={reset:()=>x.reset(),snapshot:()=>x.snapshot()})}static getOrCreateElementStore(e){const t=x.createElementId(e),r=x.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return x.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=x.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=x.now();return{value:e(),durationMs:x.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};x.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",x.ELEMENT_STORES=new Map;let ne=x;const Z=class Z{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Z.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Z.FRAGMENT_CACHE.has(e))return Z.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new N(e);break;case Node.TEXT_NODE:t=new V(e);break;case Node.COMMENT_NODE:t=new fe(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return P.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),Z.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Z.FRAGMENT_CACHE=new WeakMap;let T=Z;const Y=class Y extends T{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new se(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof Y)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new Y(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${c.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${c.prefix}if-false`)),this.children.forEach(e=>{e instanceof Y&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof Y&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,P.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return P.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new se(e,r);if(n){const be=this.attributeMap.get(e);if(be&&(be.isEvaluate||be.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,P.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&Y.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),u=s.isSingleExpression(),p=G.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||h||u?o.hasUnresolvedReference||v===null||v===void 0||v===!1:l&&p===""),I=s.isForceEvaluation()?r:u?v:p,A=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),y=a.getRootNode(),b=A&&a===y.activeElement,S=R||I===null||I===!1?null:String(I),k=e!==t&&a.getAttribute(e)!==r,C=S===null?a.hasAttribute(t):a.getAttribute(t)!==S,O=A&&!b&&S!==null&&a.value!==S,W=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,te=y.activeElement,Be=te!==null&&(W&&a===te||$&&a.closest("select")===te),ce=S!==null,$e=W&&!Be&&a.checked!==ce,Oe=$&&!Be&&a.selected!==ce;return!k&&!C&&!O&&!$e&&!Oe?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{k&&a.setAttribute(e,r),S===null?a.removeAttribute(t):(C&&(a.setAttribute(t,S),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),O&&(a.value=S))),$e&&(a.checked=ce),Oe&&(a.selected=ce)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return P.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:G.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),h=v.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const u=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=u})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${c.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${c.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};Y.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let N=Y;class V extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new G(this.text)}clone(){const e=new V(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new G(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=G.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class fe extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new fe(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const le=class le{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(le.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=ne.measure(()=>z.evaluateDetailed(l.text,e)),u=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||u.unresolvedReference,n.push(u.value)}else n.push(l.text)}catch(h){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};le.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let G=le;const ue=class ue extends G{constructor(e,t){super(t),this.forceEvaluation=ue.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ue.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let se=ue;class J{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return P.waitForIdle()}static dialog(e){return P.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return P.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return J.addMessage(e,t,"error")}static addMessage(e,t,r){return P.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return P.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t,r){return Ae(e,t,r)}static number(e,t){return Se(e,t)}static range(e,t,r){return we(e,t,r)}static pages(e,t,r){return Te(e,t,r)}static monthAdd(e,t){return ie(e,t)}static monthRange(e,t){return Re(e,t)}static pageSummary(e,t){return De(e,t)}static findBy(e,t,r){return Fe(e,t,r)}static sum(e,t){return Ne(e,t)}static distinct(e,t){return xe(e,t)}static groupBy(e,t){return Pe(e,t)}}const ze=["addErrorMessage","clearMessages"];function ke(){const e=globalThis.window?.Haori;return ze.every(r=>typeof e?.[r]=="function")?e:J}class E{static getValues(e){const t={};return E.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${c.prefix}form-object`),n=e.getAttribute(`${c.prefix}form-list`);if(r){if(n)Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()];else if(E.isGroupedCheckable(e)){const s=e.getValue(),a=String(r);s===null?a in t||(t[a]=null):t[a]===null||t[a]===void 0?t[a]=s:Array.isArray(t[a])?t[a].push(s):t[a]=[t[a],s]}else t[String(r)]=e.getValue();i&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())E.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())E.getPartValues(s,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!1)}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${c.prefix}form-object`),l=e.getAttribute(`${c.prefix}form-list`),h=e.getAttribute(`${c.prefix}form-detach`);if(a){if(!h||i){const u=t[String(a)];l&&Array.isArray(u)&&r!==null?s.push(E.applyFragmentValue(e,u[r]??null,n)):typeof u>"u"||(Array.isArray(u)&&E.isGroupedCheckable(e)||typeof u=="string"||typeof u=="number"||typeof u=="boolean"||u===null?s.push(E.applyFragmentValue(e,u,n)):s.push(E.applyFragmentValue(e,String(u),n)))}}else if(o){const u=t[String(o)];if(u&&typeof u=="object")for(const p of e.getChildElementFragments())s.push(E.setPartValues(p,u,null,i,n))}else if(l){const u=t[String(l)];if(Array.isArray(u)){const p=e.getChildElementFragments();for(let v=0;v<p.length;v++){const R=p[v];u.length>v?s.push(E.setPartValues(R,u[v],v,i,n)):s.push(E.setPartValues(R,{},v,i,n))}}}else for(const u of e.getChildElementFragments())s.push(E.setPartValues(u,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await P.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await M.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${c.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await M.setBindingData(r.getTarget(),a)}await M.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:M.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof N&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return ke().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=ke(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=E.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),h=Number(l);if(isNaN(h))m.error("Haori",`Invalid index: ${i}`);else{const u=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));h<u.length&&r.push(...E.findFragmentByKeyParts(u[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class D{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){D.dispatch(document,"ready",{version:e})}static render(e){D.dispatch(e,"render",{target:e})}static importStart(e,t){D.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){D.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){D.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],u=r[l];h!==u&&n.push(l)}D.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){D.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){D.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){D.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){D.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){D.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){D.dispatch(e,"show",{visible:!0})}static hide(e){D.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){D.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){D.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){D.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Ge={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ye(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=z.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Je(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(f),i=r instanceof N?r.getBindingData():{},n=Ye(t,i);return n===""?null:n}function Xe(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Ie(f){const e=Ge[f];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Je(i,t);if(n===null)continue;const s=Xe(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class Ce{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const Qe=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ze="__haoriHistoryState__",ge="data-haori-click-lock";function ae(){const e=globalThis.window?.Haori;return Qe.every(r=>typeof e?.[r]=="function")?e:J}const _e=new Set(["GET","HEAD","OPTIONS"]);function et(f){return _e.has(f.toUpperCase())}function tt(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function rt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return tt(r,e),t.search=r.toString(),t.toString()}function it(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function nt(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:it(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=z.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:M.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:M.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:M.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"confirm")).replace(/\\n/g,`
|
|
7
|
-
`)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const y=e.getRawAttribute(g.attrName(t,"form"));if(y){const b=document.body.querySelector(y);b!==null?r.formFragment=E.getFormFragment(
|
|
6
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...Ke},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.loggedForbiddenKeySignatures=new Set,B.loggedForbiddenKeyResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(e=>!B.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class de{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await de.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const me=class me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};me.ASYNC_QUEUE=new de;let P=me;const x=class x{static reset(){x.ELEMENT_STORES.clear(),x.ensureGlobalAccess()}static snapshot(){return x.ensureGlobalAccess(),[...x.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!L.isEnabled()||!e||t.length===0)return;x.ensureGlobalAccess();const i=x.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=x.getOrCreateCounter(i.attributes,e.rawName,e.template);x.updateCounter(s,t,r);return}const n=x.getOrCreateCounter(i.texts,String(e.childIndex),e.template);x.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[x.GLOBAL_KEY]===void 0&&(e[x.GLOBAL_KEY]={reset:()=>x.reset(),snapshot:()=>x.snapshot()})}static getOrCreateElementStore(e){const t=x.createElementId(e),r=x.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return x.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=x.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=x.now();return{value:e(),durationMs:x.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};x.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",x.ELEMENT_STORES=new Map;let ne=x;const Z=class Z{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Z.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Z.FRAGMENT_CACHE.has(e))return Z.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new N(e);break;case Node.TEXT_NODE:t=new V(e);break;case Node.COMMENT_NODE:t=new fe(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return P.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),Z.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Z.FRAGMENT_CACHE=new WeakMap;let w=Z;const Y=class Y extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new se(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof Y)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new Y(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${c.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${c.prefix}if-false`)),this.children.forEach(e=>{e instanceof Y&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof Y&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,P.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return P.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new se(e,r);if(n){const be=this.attributeMap.get(e);if(be&&(be.isEvaluate||be.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,P.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&Y.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),u=s.isSingleExpression(),p=G.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||h||u?o.hasUnresolvedReference||v===null||v===void 0||v===!1:l&&p===""),I=s.isForceEvaluation()?r:u?v:p,A=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),y=a.getRootNode(),b=A&&a===y.activeElement,S=R||I===null||I===!1?null:String(I),k=e!==t&&a.getAttribute(e)!==r,C=S===null?a.hasAttribute(t):a.getAttribute(t)!==S,O=A&&!b&&S!==null&&a.value!==S,W=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,te=y.activeElement,Be=te!==null&&(W&&a===te||$&&a.closest("select")===te),ce=S!==null,$e=W&&!Be&&a.checked!==ce,Oe=$&&!Be&&a.selected!==ce;return!k&&!C&&!O&&!$e&&!Oe?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{k&&a.setAttribute(e,r),S===null?a.removeAttribute(t):(C&&(a.setAttribute(t,S),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),O&&(a.value=S))),$e&&(a.checked=ce),Oe&&(a.selected=ce)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return P.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:G.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=w.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),h=v.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const u=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=u})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${c.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${c.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};Y.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let N=Y;class V extends w{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new G(this.text)}clone(){const e=new V(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new G(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=G.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class fe extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new fe(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const le=class le{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(le.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=ne.measure(()=>z.evaluateDetailed(l.text,e)),u=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||u.unresolvedReference,n.push(u.value)}else n.push(l.text)}catch(h){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};le.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let G=le;const ue=class ue extends G{constructor(e,t){super(t),this.forceEvaluation=ue.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ue.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let se=ue;class J{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return P.waitForIdle()}static dialog(e){return P.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return P.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return J.addMessage(e,t,"error")}static addMessage(e,t,r){return P.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return P.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t,r){return Ae(e,t,r)}static number(e,t){return Se(e,t)}static range(e,t,r){return we(e,t,r)}static pages(e,t,r){return Te(e,t,r)}static monthAdd(e,t){return ie(e,t)}static monthRange(e,t){return Re(e,t)}static pageSummary(e,t){return De(e,t)}static findBy(e,t,r){return Fe(e,t,r)}static sum(e,t){return Ne(e,t)}static distinct(e,t){return xe(e,t)}static groupBy(e,t){return Pe(e,t)}}const ze=["addErrorMessage","clearMessages"];function ke(){const e=globalThis.window?.Haori;return ze.every(r=>typeof e?.[r]=="function")?e:J}class E{static getValues(e){const t={};return E.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${c.prefix}form-object`),n=e.getAttribute(`${c.prefix}form-list`);if(r){if(n)Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()];else if(E.isGroupedCheckable(e)){const s=e.getValue(),a=String(r);s===null?a in t||(t[a]=null):t[a]===null||t[a]===void 0?t[a]=s:Array.isArray(t[a])?t[a].push(s):t[a]=[t[a],s]}else t[String(r)]=e.getValue();i&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())E.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())E.getPartValues(s,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!1)}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${c.prefix}form-object`),l=e.getAttribute(`${c.prefix}form-list`),h=e.getAttribute(`${c.prefix}form-detach`);if(a){if(!h||i){const u=t[String(a)];l&&Array.isArray(u)&&r!==null?s.push(E.applyFragmentValue(e,u[r]??null,n)):typeof u>"u"||(Array.isArray(u)&&E.isGroupedCheckable(e)||typeof u=="string"||typeof u=="number"||typeof u=="boolean"||u===null?s.push(E.applyFragmentValue(e,u,n)):s.push(E.applyFragmentValue(e,String(u),n)))}}else if(o){const u=t[String(o)];if(u&&typeof u=="object")for(const p of e.getChildElementFragments())s.push(E.setPartValues(p,u,null,i,n))}else if(l){const u=t[String(l)];if(Array.isArray(u)){const p=e.getChildElementFragments();for(let v=0;v<p.length;v++){const R=p[v];u.length>v?s.push(E.setPartValues(R,u[v],v,i,n)):s.push(E.setPartValues(R,{},v,i,n))}}}else for(const u of e.getChildElementFragments())s.push(E.setPartValues(u,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await P.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await M.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${c.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await M.setBindingData(r.getTarget(),a)}await M.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:M.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=w.get(n);s instanceof N&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return ke().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=ke(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=E.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),h=Number(l);if(isNaN(h))m.error("Haori",`Invalid index: ${i}`);else{const u=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));h<u.length&&r.push(...E.findFragmentByKeyParts(u[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class D{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){D.dispatch(document,"ready",{version:e})}static render(e){D.dispatch(e,"render",{target:e})}static importStart(e,t){D.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){D.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){D.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],u=r[l];h!==u&&n.push(l)}D.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){D.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){D.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){D.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){D.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){D.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){D.dispatch(e,"show",{visible:!0})}static hide(e){D.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){D.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){D.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){D.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Ge={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ye(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=z.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Je(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=w.get(f),i=r instanceof N?r.getBindingData():{},n=Ye(t,i);return n===""?null:n}function Xe(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Ie(f){const e=Ge[f];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Je(i,t);if(n===null)continue;const s=Xe(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class Ce{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const Qe=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ze="__haoriHistoryState__",ge="data-haori-click-lock";function ae(){const e=globalThis.window?.Haori;return Qe.every(r=>typeof e?.[r]=="function")?e:J}const _e=new Set(["GET","HEAD","OPTIONS"]);function et(f){return _e.has(f.toUpperCase())}function tt(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function rt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return tt(r,e),t.search=r.toString(),t.toString()}function it(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function nt(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:it(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=z.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:M.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:M.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:M.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"confirm")).replace(/\\n/g,`
|
|
7
|
+
`)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const y=e.getRawAttribute(g.attrName(t,"form"));if(y){const b=document.body.querySelector(y);b!==null?r.formFragment=E.getFormFragment(w.get(b)):m.error("Haori",`Form element not found: ${y} (${g.attrName(t,"form")})`)}else r.formFragment=E.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=E.getFormFragment(e));if(e.hasAttribute(`${c.prefix}${t}-before-run`)){const y=e.getRawAttribute(`${c.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
8
8
|
"use strict";
|
|
9
9
|
${y}
|
|
10
10
|
`)}catch(b){m.error("Haori",`Invalid before script: ${b}`)}}const A=g.attrName(t,"run");if(e.hasAttribute(A)){const y=String(e.getAttribute(A)??"");let b=null;try{b=new Function("event",`"use strict"; return (
|
|
11
11
|
${y}
|
|
12
12
|
);`)}catch{try{b=new Function("event",`"use strict";
|
|
13
13
|
${y}
|
|
14
|
-
`)}catch(S){m.error("Haori",`Invalid run script: ${S}`)}}b&&(r.runScript=b)}}const i=g.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const A=e.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(t){const A=g.attrName(t,"fetch-method");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}else{const A=g.attrName(null,"method",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}if(t){const A=g.attrName(t,"fetch-headers");if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=M.parseDataBind(y)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}else{const A=g.attrName(null,"headers",!0);if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=M.parseDataBind(y)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}if(t){const A=g.attrName(t,"fetch-content-type");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=g.attrName(null,"content-type",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=t?g.attrName(t,"bind"):g.attrName(null,"bind",!0);if(e.hasAttribute(a)){const A=e.getRawAttribute(a);if(A){const y=document.body.querySelectorAll(A);y.length>0?(r.bindFragments=[],y.forEach(b=>{const S=
|
|
14
|
+
`)}catch(S){m.error("Haori",`Invalid run script: ${S}`)}}b&&(r.runScript=b)}}const i=g.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const A=e.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(t){const A=g.attrName(t,"fetch-method");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}else{const A=g.attrName(null,"method",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}if(t){const A=g.attrName(t,"fetch-headers");if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=M.parseDataBind(y)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}else{const A=g.attrName(null,"headers",!0);if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=M.parseDataBind(y)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}if(t){const A=g.attrName(t,"fetch-content-type");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=g.attrName(null,"content-type",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=t?g.attrName(t,"bind"):g.attrName(null,"bind",!0);if(e.hasAttribute(a)){const A=e.getRawAttribute(a);if(A){const y=document.body.querySelectorAll(A);y.length>0?(r.bindFragments=[],y.forEach(b=>{const S=w.get(b);S&&r.bindFragments.push(S)})):m.error("Haori",`Bind element not found: ${A} (${a})`)}}const o=g.attrName(t,"bind-arg"),l=g.attrName(null,"arg",!0),h=g.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(l)?r.bindArg=e.getRawAttribute(l):e.hasAttribute(h)&&(r.bindArg=e.getRawAttribute(h));const u=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(u)){const A=e.getRawAttribute(u);r.bindParams=A.split("&").map(y=>y.trim())}const p=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(p)){const A=e.getRawAttribute(p);r.bindAppendParams=A.split("&").map(y=>y.trim()).filter(Boolean)}const v=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(v)&&(r.bindMerge=!0);const R=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(R)&&(r.bindTransform=e.getRawAttribute(R));const I=t?g.attrName(t,"copy-params"):null;if(I&&e.hasAttribute(I)){const A=e.getRawAttribute(I);r.copyParams=A.split("&").map(y=>y.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const b=e.getRawAttribute(g.attrName(t,"adjust"));if(b){const S=document.body.querySelectorAll(b);S.length>0?(r.adjustFragments=[],S.forEach(k=>{const C=w.get(k);C&&r.adjustFragments.push(C)})):m.error("Haori",`Adjust element not found: ${b} (${g.attrName(t,"adjust")})`)}if(e.hasAttribute(g.attrName(t,"adjust-value"))){const S=e.getRawAttribute(g.attrName(t,"adjust-value")),k=Number(S);isNaN(k)||(r.adjustValue=k)}}if(e.hasAttribute(g.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(g.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(g.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(g.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${c.prefix}${t}-after-run`)){const b=e.getRawAttribute(`${c.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
|
|
15
15
|
"use strict";
|
|
16
16
|
${b}
|
|
17
17
|
`)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(g.attrName(t,"dialog")).replace(/\\n/g,`
|
|
18
|
-
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k?(document.body.querySelectorAll(k).forEach(W=>{const $=T.get(W);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`)):C.push(e),C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return D.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&D.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await M.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(ge))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(ge,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(ge),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ae();if(!e.ok)return Ie(e.status)||(this.options.targetFragment&&t&&D.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&D.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await M.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();Ce.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Ze]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ae().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ae().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
18
|
+
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(w.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k)document.body.querySelectorAll(k).forEach(W=>{const $=w.get(W);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`);else if(b==="open"||b==="close"){const O=e.getTarget().closest("dialog");O?C.push(w.get(O)):m.error("Haori",`Ancestor <dialog> not found (${S})`)}else C.push(e);if(C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=w.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(w.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return D.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&D.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await M.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(ge))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(ge,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(ge),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ae();if(!e.ok)return Ie(e.status)||(this.options.targetFragment&&t&&D.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&D.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await M.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();Ce.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Ze]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ae().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ae().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
19
19
|
`)});for(const u of h)o.push({message:u})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,h]of Object.entries(a.errors))Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
20
20
|
`)}):typeof h=="string"?o.push({key:l,message:h}):h!=null&&o.push({key:l,message:String(h)});if(o.length===0)for(const[l,h]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
21
|
-
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ae().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(M.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(M.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{D.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return M.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=c.runtime==="demo"&&!et(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=rt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[v,R]of Object.entries(t))R==null?p.append(v,""):R instanceof Blob?p.append(v,R):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[v,R]of Object.entries(t))R!==void 0&&(R===null?p.append(v,""):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:nt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(M.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let q=g;class st{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Ie(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof N?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof N?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof N&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new q(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${c.prefix}importing`,""),D.importStart(t,n),st.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),D.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=T.get(h);u instanceof N?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),D.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof N?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof N&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=Ce.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&D.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof N?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const v of Object.keys(l))v in i||(i[v]={value:l[v],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof N?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(v=>{if(v instanceof N){if(d.canSkipUnchangedNestedEach(v))return;p.push(d.evaluateAll(v,t))}else v instanceof V&&p.push(d.evaluateText(v))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{D.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof N?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{D.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof N){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=T.get(l);u instanceof N&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=T.get(l);h instanceof N&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof N?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof N).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof N?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((b,S)=>{const k=d.createListKey(b,n?String(n):null,S);o.push(k),a.set(k,{item:b,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(b=>b instanceof N).filter(b=>!b.hasAttribute(`${c.prefix}each-before`)&&!b.hasAttribute(`${c.prefix}each-after`));const p=u.map(b=>b.getListKey());u=u.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const v=u.map(b=>b.getListKey()),R=new Map;u.forEach(b=>{const S=b.getListKey();S!==null&&!R.has(S)&&R.set(S,b)});const I=e.getChildElementFragments().slice(),A=I.filter(b=>b.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((b,S)=>{const{item:k,itemIndex:C}=a.get(b);let O;const W=R.get(b);if(W)O=W,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then(()=>{const te=I[$]??null;return e.insertBefore(O,te).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const b=o.filter($=>$!==null),S=v.filter($=>$!==null),k=new Set(S),C=b.filter($=>!k.has($)),W=p.filter($=>$!==null).filter($=>!l.has($));D.eachUpdate(e.getTarget(),C,W,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let M=d;const ee=class ee{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=T.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[ee.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ee.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof N&&new q(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=T.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof N&&i.syncValue();const n=()=>{new q(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};ee.HISTORY_STATE_KEY="__haoriHistoryState__",ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let pe=ee;const F=class F{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(F.isHtmlElement(e)&&F.syncElement(e),e.querySelectorAll("*").forEach(t=>{F.syncElement(t)}))}static syncElement(e){const t=F.registrations.get(e),r=T.get(e);if(!r||!F.shouldObserve(r)){t&&(t.observer.disconnect(),F.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=F.resolveRoot(r),n=F.resolveRootMargin(r),s=F.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&F.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),F.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=F.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||F.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),F.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=F.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),F.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(F.isHtmlElement(e)){const t=F.registrations.get(e);t&&(t.observer.disconnect(),F.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=F.registrations.get(t);r&&(r.observer.disconnect(),F.registrations.delete(t))})}static disconnectAll(){F.registrations.forEach(e=>{e.observer.disconnect()}),F.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!F.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return F.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};F.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),F.registrations=new Map;let _=F;function at(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=T.get(e);if(!(r instanceof N)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const v=p.target;h.observedRows.has(v)&&(p.isIntersecting?h.visibleRows.has(v)||(h.visibleRows.add(v),u=!0):h.visibleRows.delete(v)&&(u=!0))}),u&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof N&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,at(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);M.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let X=w;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers();const e=await Promise.allSettled([M.scan(document.head),M.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),new pe().start(),_.syncTree(document.body),X.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&M.isAliasedAttributeReflection(n,i.attributeName))break;M.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),_.syncElement(n),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{_.cleanupTree(n),X.cleanupTree(n),M.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(M.addNode(n.parentElement,n),_.syncTree(n),X.syncTree(n))}),i.target instanceof Element&&X.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?M.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}};U._initialized=!1,U._mutationObservers=[];let oe=U;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",oe.init):oe.init();const ot=()=>J.waitForRenders(),lt="0.20.0";return H.Core=M,H.Env=c,H.Form=E,H.Fragment=T,H.Haori=J,H.Log=m,H.Queue=P,H.default=J,H.version=lt,H.waitForRenders=ot,Object.defineProperties(H,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),H}({});
|
|
21
|
+
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ae().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(M.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(M.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{D.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return M.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=c.runtime==="demo"&&!et(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=rt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[v,R]of Object.entries(t))R==null?p.append(v,""):R instanceof Blob?p.append(v,R):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[v,R]of Object.entries(t))R!==void 0&&(R===null?p.append(v,""):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:nt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(M.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let q=g;class st{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Ie(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof N?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof N?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof N&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new q(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${c.prefix}importing`,""),D.importStart(t,n),st.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),D.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=w.get(h);u instanceof N?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),D.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof N?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=w.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof N&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=Ce.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=w.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&D.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=w.get(e);return r instanceof N?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=w.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const v of Object.keys(l))v in i||(i[v]={value:l[v],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=w.get(e);if(r.isSkipMutationNodes())return;const i=w.get(t.nextSibling),n=w.get(t);n&&(r.insertBefore(n,i),n instanceof N?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(v=>{if(v instanceof N){if(d.canSkipUnchangedNestedEach(v))return;p.push(d.evaluateAll(v,t))}else v instanceof V&&p.push(d.evaluateText(v))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{D.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof N?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{D.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof N){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=w.get(l);u instanceof N&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=w.get(l);h instanceof N&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof N?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof N).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof N?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((b,S)=>{const k=d.createListKey(b,n?String(n):null,S);o.push(k),a.set(k,{item:b,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(b=>b instanceof N).filter(b=>!b.hasAttribute(`${c.prefix}each-before`)&&!b.hasAttribute(`${c.prefix}each-after`));const p=u.map(b=>b.getListKey());u=u.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const v=u.map(b=>b.getListKey()),R=new Map;u.forEach(b=>{const S=b.getListKey();S!==null&&!R.has(S)&&R.set(S,b)});const I=e.getChildElementFragments().slice(),A=I.filter(b=>b.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((b,S)=>{const{item:k,itemIndex:C}=a.get(b);let O;const W=R.get(b);if(W)O=W,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then(()=>{const te=I[$]??null;return e.insertBefore(O,te).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const b=o.filter($=>$!==null),S=v.filter($=>$!==null),k=new Set(S),C=b.filter($=>!k.has($)),W=p.filter($=>$!==null).filter($=>!l.has($));D.eachUpdate(e.getTarget(),C,W,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let M=d;const ee=class ee{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[ee.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ee.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=w.get(i);n instanceof N&&new q(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=w.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof N&&i.syncValue();const n=()=>{new q(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};ee.HISTORY_STATE_KEY="__haoriHistoryState__",ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let pe=ee;const F=class F{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(F.isHtmlElement(e)&&F.syncElement(e),e.querySelectorAll("*").forEach(t=>{F.syncElement(t)}))}static syncElement(e){const t=F.registrations.get(e),r=w.get(e);if(!r||!F.shouldObserve(r)){t&&(t.observer.disconnect(),F.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=F.resolveRoot(r),n=F.resolveRootMargin(r),s=F.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&F.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),F.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=F.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||F.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),F.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=F.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),F.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(F.isHtmlElement(e)){const t=F.registrations.get(e);t&&(t.observer.disconnect(),F.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=F.registrations.get(t);r&&(r.observer.disconnect(),F.registrations.delete(t))})}static disconnectAll(){F.registrations.forEach(e=>{e.observer.disconnect()}),F.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!F.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return F.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};F.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),F.registrations=new Map;let _=F;function at(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const T=class T{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(T.isHtmlElement(e)&&T.syncElement(e),e.querySelectorAll("*").forEach(t=>{T.syncElement(t)}))}static syncElement(e){const t=T.registrations.get(e),r=w.get(e);if(!(r instanceof N)||!T.shouldObserve(r)){t&&(t.observer.disconnect(),T.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=T.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),T.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=T.resolveRoot(r),s=T.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,T.refreshRows(t);return}t&&(t.observer.disconnect(),T.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=T.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const v=p.target;h.observedRows.has(v)&&(p.isIntersecting?h.visibleRows.has(v)||(h.visibleRows.add(v),u=!0):h.visibleRows.delete(v)&&(u=!0))}),u&&T.scheduleCompute(h)},{root:n,rootMargin:s,threshold:T.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};T.registrations.set(e,o),T.refreshRows(o)}static cleanupTree(e){if(T.isHtmlElement(e)){const t=T.registrations.get(e);t&&(t.observer.disconnect(),T.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=T.registrations.get(t);r&&(r.observer.disconnect(),T.registrations.delete(t))})}static disconnectAll(){T.registrations.forEach(e=>{e.observer.disconnect()}),T.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return T.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?T.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof N&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=T.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));T.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,at(()=>{e.scheduled=!1;const t=e.fragment.getTarget();T.registrations.get(t)===e&&T.computeAndPublish(e)}))}static computeAndPublish(e){const t=T.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,T.publish(e,n))}static publish(e,t){const r=T.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);M.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};T.THRESHOLD=0,T.DEFAULT_ROOT_MARGIN="0px",T.registrations=new Map;let X=T;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers();const e=await Promise.allSettled([M.scan(document.head),M.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),new pe().start(),_.syncTree(document.body),X.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&M.isAliasedAttributeReflection(n,i.attributeName))break;M.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),_.syncElement(n),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{_.cleanupTree(n),X.cleanupTree(n),M.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(M.addNode(n.parentElement,n),_.syncTree(n),X.syncTree(n))}),i.target instanceof Element&&X.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?M.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}};U._initialized=!1,U._mutationObservers=[];let oe=U;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",oe.init):oe.init();const ot=()=>J.waitForRenders(),lt="0.20.0";return H.Core=M,H.Env=c,H.Form=E,H.Fragment=w,H.Haori=J,H.Log=m,H.Queue=P,H.default=J,H.version=lt,H.waitForRenders=ot,Object.defineProperties(H,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),H}({});
|
|
22
22
|
//# sourceMappingURL=haori.iife.js.map
|