haori 0.17.1 → 0.17.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/dist/haori.cjs.js +2 -2
- package/dist/haori.es.js +2 -2
- package/dist/haori.iife.js +2 -2
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/haori.cjs.js
CHANGED
|
@@ -14,7 +14,7 @@ ${v}
|
|
|
14
14
|
"use strict";
|
|
15
15
|
${b}
|
|
16
16
|
`)}catch(S){g.error("Haori",`Invalid after script: ${S}`)}}if(t.hasAttribute(f.attrName(e,"dialog"))&&(r.dialogMessage=t.getAttribute(f.attrName(e,"dialog")).replace(/\\n/g,`
|
|
17
|
-
`)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),x=["info","warning","error","success"].includes(b);r.toastLevel=x?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=y.getFormFragment(T.get(S)):g.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=y.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const x=t.getRawAttribute(S),I=[];if(x?(document.body.querySelectorAll(x).forEach(V=>{const C=T.get(V);C&&I.push(C)}),I.length===0&&g.error("Haori",`Element not found: ${x} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const x=T.get(S);x?r.copySourceFragment=x:g.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else g.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=y.getFormFragment(T.get(v)):g.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=y.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t]),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}constructor(t,e=null,r=null){f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){g.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>y.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(n||null,s||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(n="fetchUrl"in d?d.fetchUrl:n,s="fetchOptions"in d?d.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const d={...s||{}},h=r.requestedMethod,m=r.effectiveMethod,E=r.transportMode==="query-get",w=r.queryString;if(E&&g.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:w}),this.options.targetFragment&&n){const k=performance.now(),A={runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:E?"query-get":"http",...E?{queryString:w}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,A),fetch(n,d).then(v=>this.handleFetchResult(v,n||void 0,k)).catch(v=>{throw n&&R.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,d).then(k=>this.handleFetchResult(k,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),m=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment)
|
|
17
|
+
`)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),x=["info","warning","error","success"].includes(b);r.toastLevel=x?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=y.getFormFragment(T.get(S)):g.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=y.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const x=t.getRawAttribute(S),I=[];if(x?(document.body.querySelectorAll(x).forEach(V=>{const C=T.get(V);C&&I.push(C)}),I.length===0&&g.error("Haori",`Element not found: ${x} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const x=T.get(S);x?r.copySourceFragment=x:g.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else g.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=y.getFormFragment(T.get(v)):g.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=y.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t]),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}constructor(t,e=null,r=null){f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){g.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>y.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(n||null,s||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(n="fetchUrl"in d?d.fetchUrl:n,s="fetchOptions"in d?d.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const d={...s||{}},h=r.requestedMethod,m=r.effectiveMethod,E=r.transportMode==="query-get",w=r.queryString;if(E&&g.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:w}),this.options.targetFragment&&n){const k=performance.now(),A={runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:E?"query-get":"http",...E?{queryString:w}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,A),fetch(n,d).then(v=>this.handleFetchResult(v,n||void 0,k)).catch(v=>{throw n&&R.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,d).then(k=>this.handleFetchResult(k,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),m=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const E=d.getBindingData();Object.assign(E,i),await N.setBindingData(h,E,m)}const o=a?i:{},u=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(u)}finally{this.releaseExecutionLock(t)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment.getTarget();if(f.RUNNING_CLICK_TARGETS.has(e)||e.matches(":disabled")||e.hasAttribute("disabled")||e.hasAttribute(lt))return!1;const r=e.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(e),e.setAttribute(lt,""),r||e.setAttribute("disabled",""),{target:e,appliedDisabledAttribute:!r}}releaseExecutionLock(t){t&&(f.RUNNING_CLICK_TARGETS.delete(t.target),t.target.removeAttribute(lt),t.appliedDisabledAttribute&&t.target.removeAttribute("disabled"))}async handleFetchResult(t,e,r){const i=ut();if(!t.ok)return Mt(t.status)||(this.options.targetFragment&&e&&R.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t)),!1;if(this.options.targetFragment&&e&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const n=[];n.push(this.bindResult(t)),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=>y.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new f(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await N.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return 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)):g.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)):g.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&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=e!=null,n=r!=null;if(!(!t&&!i&&!n))try{const s=t?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+a.toString();g.error("Haori",u);return}const o=u=>{for(const[d,h]of Object.entries(u))h!=null&&(Array.isArray(h)?h.forEach(m=>a.searchParams.append(d,String(m))):typeof h=="object"?a.searchParams.set(d,JSON.stringify(h)):a.searchParams.set(d,String(h)))};i&&o(e),n&&o(r),history.pushState({[jt]:!0},"",a.toString())}catch(s){g.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=y.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async s=>{const a=e?e.getTarget():document.body;await ut().addErrorMessage(a,s)},i=()=>{if(!this.options.scrollOnError)return;const s=e?e.getTarget():document.body;(s.getAttribute("data-message-level")==="error"?s:s.parentElement?.getAttribute("data-message-level")==="error"?s.parentElement:s.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const s=await t.json(),a=[];if(s&&typeof s=="object"){if(typeof s.message=="string"&&a.push({message:s.message}),Array.isArray(s.messages))for(const o of s.messages)typeof o=="string"&&a.push({message:o});if(s.errors&&typeof s.errors=="object")for(const[o,u]of Object.entries(s.errors))Array.isArray(u)?a.push({key:o,message:u.join(`
|
|
18
18
|
`)}):typeof u=="string"?a.push({key:o,message:u}):u!=null&&a.push({key:o,message:String(u)});if(a.length===0)for(const[o,u]of Object.entries(s))o==="message"||o==="messages"||o==="errors"||(Array.isArray(u)?a.push({key:o,message:u.join(`
|
|
19
|
-
`)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await y.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):ut().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindTransform)try{r=z.evaluate(this.options.bindTransform,{response:r})}catch(n){g.error("Haori",`Invalid bind-transform: ${n}`)}if(this.options.bindParams){const n={};this.options.bindParams.forEach(s=>{r&&typeof r=="object"&&s in r&&(n[s]=r[s])}),r=n}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(n=>{const s={...n.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=s[a],u=o&&typeof o=="object"&&!Array.isArray(o)?o:{};s[a]=this.mergeAppendBindingData(n,r,u)}else s[a]=r;i.push(N.setBindingData(n.getTarget(),s))});else{if(typeof r=="string")return g.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(n=>{const s=this.mergeAppendBindingData(n,r),a=this.options.bindMerge?{...n.getRawBindingData()??{},...s}:s;i.push(N.setBindingData(n.getTarget(),a))})}return Promise.all(i).then(()=>{const n=this.options.bindArg??null;this.options.bindFragments.forEach(s=>{R.bindComplete(s.getTarget(),n)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},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 t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};return N.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?y.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?y.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const t={};let e=!1;if(this.options.formFragment&&Object.assign(t,y.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,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=l.runtime==="demo"&&!Wt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Kt(i,e));else if(Object.keys(e).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const m=new FormData;for(const[E,w]of Object.entries(e))w==null?m.append(E,""):w instanceof Blob?m.append(E,w):Array.isArray(w)?w.forEach(k=>m.append(E,String(k))):typeof w=="object"?m.append(E,JSON.stringify(w)):m.append(E,String(w));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(h)){const m=new URLSearchParams;for(const[E,w]of Object.entries(e))w!==void 0&&(w===null?m.append(E,""):Array.isArray(w)?w.forEach(k=>m.append(E,String(k))):typeof w=="object"?m.append(E,JSON.stringify(w)):m.append(E,String(w)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let d;return o&&(d=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:d,transportMode:o?"query-get":"http",signature:Yt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?y.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return y.getValues(this.options.historyFormFragment)}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=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}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];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+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return g.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(g.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(N.evaluateAll(r)),e.push(y.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Xt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Jt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw g.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Mt(r.status);const n=`${r.status} ${r.statusText}`;throw g.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw g.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(g.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return g.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const c=class c{static isDeferredAttributeName(t){return c.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!c.isEvaluateAllExcludedAttributeName(t)&&c.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=T.get(t);return r instanceof P?r.hasAttribute(`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);c.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>c.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof P?e.push(c.evaluateAll(r)):r instanceof U&&e.push(c.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=c.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return c.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=c.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return c.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(c.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(c.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof P&&r.push(c.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=c.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new j(t,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedFetch(t)}))}static executeManagedImport(t){const e=t.getTarget(),r=c.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.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 e.setAttribute(`${l.prefix}importing`,""),R.importStart(e,n),Jt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),R.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(d=>{const h=T.get(d);h instanceof P?u.push(c.scan(h.getTarget())):h instanceof U&&u.push(c.evaluateText(h))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),R.importError(e,n,a),g.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedImport(t)})}static scan(t){const e=T.get(t);return e?c.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return c.initializeElementFragment(t,!0).then(()=>{c.needsScheduledEvaluateAll(t)&&c.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return c.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():c.initializeElementAttributes(t).then(()=>{if(c.shouldSkipChildInitialization(t,e)){c.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof P?r.push(c.initializeElementFragment(i,e)):i instanceof U&&r.push(c.evaluateText(i))}),Promise.all(r).then(()=>{c.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of c.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||c.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>c.setAttribute(t.getTarget(),i,n)))}for(const i of c.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&c.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=T.get(t),s=c.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof P&&n.consumeSelfWrittenBind(r))break;n.setBindingData(c.parseDataBind(r))}break}case`${l.prefix}derive`:u=c.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=c.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=c.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=c.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(c.evaluateIf(n));break;case`${l.prefix}each`:a.push(c.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(c.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(c.executeManagedImport(n));break;case`${l.prefix}url-param`:{const d=n.getAttribute(`${l.prefix}url-arg`),h=Xt.readParams();if(d===null)a.push(c.setBindingData(t,h,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=h,a.push(c.setBindingData(t,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(d=>{if(d)return c.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=T.get(t),s=n.getRawBindingData();n.setBindingData(e),R.bindChange(t,s,e,"manual");const a=()=>{const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const d=n.getAttribute(`${l.prefix}form-arg`),h=d&&o[String(d)]&&typeof o[String(d)]=="object"&&!Array.isArray(o[String(d)])?o[String(d)]:d?{}:o;u=u.then(()=>y.syncValues(n,h))}return u=u.then(()=>c.evaluateAll(n,r)),u=u.then(()=>c.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>{})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=T.get(t);return r instanceof P?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=T.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const d=u.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(u,d,h,m)=>{if(u)for(const E of Object.keys(u))E in i||(i[E]={value:u[E],source:n(d),kind:h,depth:m})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&g.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return g.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.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(t,e){const r=T.get(t);if(r.isSkipMutationNodes())return;const i=T.get(e.nextSibling),n=T.get(e);n&&(r.insertBefore(n,i),n instanceof P?c.scan(n.getTarget()):n instanceof U&&c.evaluateText(n))}static removeNode(t){const e=T.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=T.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=T.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=c.getFormFragment(r);if(n){const s=y.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(c.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?c.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=c.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,d=!1,h=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const m=c.createDeriveInputSignature(t,a,o);m===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==m&&(r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>c.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>c.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}h=c.createDescendantBindingSignature(t,"evaluateAll"),d=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===h,c.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const m=[];return t.getChildren().forEach(E=>{if(E instanceof P){if(c.canSkipUnchangedNestedEach(E))return;m.push(c.evaluateAll(E,e))}else E instanceof U&&m.push(c.evaluateText(E))}),Promise.all(m).then(()=>{})}).then(()=>{d&&h!==null&&t.setDeriveSubtreeSignature(h)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return c.createBindingSignature(i)===c.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=c.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),g.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(c.isHiddenIfCondition(r))H.isEnabled()&&c.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{R.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof P?n.push(s.isMounted()?c.evaluateAll(s):c.scan(s.getTarget())):s instanceof U&&n.push(c.evaluateText(s))}),e.push(t.show().then(()=>{R.show(t.getTarget()),i||c.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{g.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=c.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},c.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=c.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):c.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await c.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=c.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof P){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof P&&(r=h.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const d=T.get(u);d instanceof P&&t.getChildren().includes(d)&&(t.removeChild(d),d.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(g.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||c.hasNonEachDynamicElementState(t))return!1;const r=c.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!c.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof P?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return c.recordDerivedSubtreeSignatureComputation(t,e),c.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:c.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(c.createDescendantBindingSignature(t,"refresh")),c.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=c.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:c.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof P).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof P?!c.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return g.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const x=c.createListKey(b,n?String(n):null,S);o.push(x),a.set(x,{item:b,itemIndex:S})});const u=new Set(o),d=[];let h=t.getChildren().filter(b=>b instanceof P).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const m=h.map(b=>b.getListKey());h=h.filter(b=>u.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const E=h.map(b=>b.getListKey()),w=new Map;h.forEach(b=>{const S=b.getListKey();S!==null&&!w.has(S)&&w.set(S,b)});const k=t.getChildElementFragments().slice(),A=k.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:x,itemIndex:I}=a.get(b);let $;const V=w.get(b);if(V)$=V,v=v.then(()=>c.updateRowFragment($,x,i,I,s?String(s):null,b).then(C=>{if(C)return c.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>c.updateRowFragment($,x,i,I,s?String(s):null,b).then(()=>{const Z=k[C]??null;return t.insertBefore($,Z).then(()=>{k.splice(C,0,$)}).then(()=>c.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=E.filter(C=>C!==null),x=new Set(S),I=b.filter(C=>!x.has(C)),V=m.filter(C=>C!==null).filter(C=>!u.has(C));R.eachUpdate(t.getTarget(),I,V,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&c.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>c.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${c.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{c.evaluateAll(t)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap;let N=c;const Q=class Q{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=T.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Q.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}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[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Q.BUILTIN_EVENT_NAMES.has(t)){g.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=T.get(i);n instanceof P&&new j(n,"on",e).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(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(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=T.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof P&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Q.HISTORY_STATE_KEY="__haoriHistoryState__",Q.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ht=Q;const D=class D{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(D.isHtmlElement(t)&&D.syncElement(t),t.querySelectorAll("*").forEach(e=>{D.syncElement(e)}))}static syncElement(t){const e=D.registrations.get(t),r=T.get(t);if(!r||!D.shouldObserve(r)){e&&(e.observer.disconnect(),D.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&D.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),D.registrations.delete(t));const o=new IntersectionObserver(u=>{const d=D.registrations.get(t);d&&u.forEach(h=>{!h.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new j(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),D.registrations.delete(t))}).catch(m=>{g.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(t);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),D.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(D.isHtmlElement(t)){const e=D.registrations.get(t);e&&(e.observer.disconnect(),D.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=D.registrations.get(e);r&&(r.observer.disconnect(),D.registrations.delete(e))})}static disconnectAll(){D.registrations.forEach(t=>{t.observer.disconnect()}),D.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(g.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);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(t,e){return t.length===1&&t[0]===e}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let J=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(t=>{t.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const t=await Promise.allSettled([N.scan(document.head),N.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ht().start(),J.syncTree(document.body)}static observe(t){const e=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&&N.isAliasedAttributeReflection(n,i.attributeName))break;N.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),J.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{J.cleanupTree(n),N.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(N.addNode(n.parentElement,n),J.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?N.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(e)}};O._initialized=!1,O._mutationObservers=[];let it=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",it.init):it.init();const Qt=()=>X.waitForRenders(),Zt="0.17.1";exports.Core=N;exports.Env=l;exports.Form=y;exports.Fragment=T;exports.Haori=X;exports.Log=g;exports.Queue=M;exports.default=X;exports.version=Zt;exports.waitForRenders=Qt;
|
|
19
|
+
`)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await y.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):ut().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindTransform)try{r=z.evaluate(this.options.bindTransform,{response:r})}catch(n){g.error("Haori",`Invalid bind-transform: ${n}`)}if(this.options.bindParams){const n={};this.options.bindParams.forEach(s=>{r&&typeof r=="object"&&s in r&&(n[s]=r[s])}),r=n}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(n=>{const s={...n.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=s[a],u=o&&typeof o=="object"&&!Array.isArray(o)?o:{};s[a]=this.mergeAppendBindingData(n,r,u)}else s[a]=r;i.push(N.setBindingData(n.getTarget(),s))});else{if(typeof r=="string")return g.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(n=>{const s=this.mergeAppendBindingData(n,r),a=this.options.bindMerge?{...n.getRawBindingData()??{},...s}:s;i.push(N.setBindingData(n.getTarget(),a))})}return Promise.all(i).then(()=>{const n=this.options.bindArg??null;this.options.bindFragments.forEach(s=>{R.bindComplete(s.getTarget(),n)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},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 t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};return N.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?y.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?y.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const t={};let e=!1;if(this.options.formFragment&&Object.assign(t,y.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,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=l.runtime==="demo"&&!Wt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Kt(i,e));else if(Object.keys(e).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const m=new FormData;for(const[E,w]of Object.entries(e))w==null?m.append(E,""):w instanceof Blob?m.append(E,w):Array.isArray(w)?w.forEach(k=>m.append(E,String(k))):typeof w=="object"?m.append(E,JSON.stringify(w)):m.append(E,String(w));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(h)){const m=new URLSearchParams;for(const[E,w]of Object.entries(e))w!==void 0&&(w===null?m.append(E,""):Array.isArray(w)?w.forEach(k=>m.append(E,String(k))):typeof w=="object"?m.append(E,JSON.stringify(w)):m.append(E,String(w)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let d;return o&&(d=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:d,transportMode:o?"query-get":"http",signature:Yt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?y.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return y.getValues(this.options.historyFormFragment)}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=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}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];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+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return g.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(g.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(N.evaluateAll(r)),e.push(y.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Xt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Jt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw g.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Mt(r.status);const n=`${r.status} ${r.statusText}`;throw g.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw g.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(g.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return g.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const c=class c{static isDeferredAttributeName(t){return c.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!c.isEvaluateAllExcludedAttributeName(t)&&c.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=T.get(t);return r instanceof P?r.hasAttribute(`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);c.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>c.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof P?e.push(c.evaluateAll(r)):r instanceof U&&e.push(c.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=c.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return c.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=c.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return c.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(c.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(c.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof P&&r.push(c.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=c.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new j(t,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedFetch(t)}))}static executeManagedImport(t){const e=t.getTarget(),r=c.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.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 e.setAttribute(`${l.prefix}importing`,""),R.importStart(e,n),Jt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),R.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(d=>{const h=T.get(d);h instanceof P?u.push(c.scan(h.getTarget())):h instanceof U&&u.push(c.evaluateText(h))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),R.importError(e,n,a),g.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedImport(t)})}static scan(t){const e=T.get(t);return e?c.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return c.initializeElementFragment(t,!0).then(()=>{c.needsScheduledEvaluateAll(t)&&c.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return c.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():c.initializeElementAttributes(t).then(()=>{if(c.shouldSkipChildInitialization(t,e)){c.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof P?r.push(c.initializeElementFragment(i,e)):i instanceof U&&r.push(c.evaluateText(i))}),Promise.all(r).then(()=>{c.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of c.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||c.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>c.setAttribute(t.getTarget(),i,n)))}for(const i of c.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&c.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=T.get(t),s=c.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof P&&n.consumeSelfWrittenBind(r))break;n.setBindingData(c.parseDataBind(r))}break}case`${l.prefix}derive`:u=c.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=c.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=c.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=c.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(c.evaluateIf(n));break;case`${l.prefix}each`:a.push(c.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(c.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(c.executeManagedImport(n));break;case`${l.prefix}url-param`:{const d=n.getAttribute(`${l.prefix}url-arg`),h=Xt.readParams();if(d===null)a.push(c.setBindingData(t,h,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=h,a.push(c.setBindingData(t,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(d=>{if(d)return c.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=T.get(t),s=n.getRawBindingData();n.setBindingData(e),R.bindChange(t,s,e,"manual");const a=()=>{const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const d=n.getAttribute(`${l.prefix}form-arg`),h=d&&o[String(d)]&&typeof o[String(d)]=="object"&&!Array.isArray(o[String(d)])?o[String(d)]:d?{}:o;u=u.then(()=>y.syncValues(n,h))}return u=u.then(()=>c.evaluateAll(n,r)),u=u.then(()=>c.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>{})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=T.get(t);return r instanceof P?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=T.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const d=u.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(u,d,h,m)=>{if(u)for(const E of Object.keys(u))E in i||(i[E]={value:u[E],source:n(d),kind:h,depth:m})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&g.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return g.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.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(t,e){const r=T.get(t);if(r.isSkipMutationNodes())return;const i=T.get(e.nextSibling),n=T.get(e);n&&(r.insertBefore(n,i),n instanceof P?c.scan(n.getTarget()):n instanceof U&&c.evaluateText(n))}static removeNode(t){const e=T.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=T.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=T.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=c.getFormFragment(r);if(n){const s=y.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(c.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?c.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=c.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,d=!1,h=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const m=c.createDeriveInputSignature(t,a,o);m===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==m&&(r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>c.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>c.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}h=c.createDescendantBindingSignature(t,"evaluateAll"),d=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===h,c.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const m=[];return t.getChildren().forEach(E=>{if(E instanceof P){if(c.canSkipUnchangedNestedEach(E))return;m.push(c.evaluateAll(E,e))}else E instanceof U&&m.push(c.evaluateText(E))}),Promise.all(m).then(()=>{})}).then(()=>{d&&h!==null&&t.setDeriveSubtreeSignature(h)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return c.createBindingSignature(i)===c.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=c.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),g.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(c.isHiddenIfCondition(r))H.isEnabled()&&c.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{R.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof P?n.push(s.isMounted()?c.evaluateAll(s):c.scan(s.getTarget())):s instanceof U&&n.push(c.evaluateText(s))}),e.push(t.show().then(()=>{R.show(t.getTarget()),i||c.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{g.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=c.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},c.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=c.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):c.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await c.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=c.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof P){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof P&&(r=h.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const d=T.get(u);d instanceof P&&t.getChildren().includes(d)&&(t.removeChild(d),d.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(g.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||c.hasNonEachDynamicElementState(t))return!1;const r=c.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!c.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof P?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return c.recordDerivedSubtreeSignatureComputation(t,e),c.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:c.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(c.createDescendantBindingSignature(t,"refresh")),c.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=c.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:c.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof P).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof P?!c.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return g.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const x=c.createListKey(b,n?String(n):null,S);o.push(x),a.set(x,{item:b,itemIndex:S})});const u=new Set(o),d=[];let h=t.getChildren().filter(b=>b instanceof P).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const m=h.map(b=>b.getListKey());h=h.filter(b=>u.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const E=h.map(b=>b.getListKey()),w=new Map;h.forEach(b=>{const S=b.getListKey();S!==null&&!w.has(S)&&w.set(S,b)});const k=t.getChildElementFragments().slice(),A=k.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:x,itemIndex:I}=a.get(b);let $;const V=w.get(b);if(V)$=V,v=v.then(()=>c.updateRowFragment($,x,i,I,s?String(s):null,b).then(C=>{if(C)return c.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>c.updateRowFragment($,x,i,I,s?String(s):null,b).then(()=>{const Z=k[C]??null;return t.insertBefore($,Z).then(()=>{k.splice(C,0,$)}).then(()=>c.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=E.filter(C=>C!==null),x=new Set(S),I=b.filter(C=>!x.has(C)),V=m.filter(C=>C!==null).filter(C=>!u.has(C));R.eachUpdate(t.getTarget(),I,V,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&c.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>c.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${c.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{c.evaluateAll(t)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap;let N=c;const Q=class Q{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=T.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Q.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}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[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Q.BUILTIN_EVENT_NAMES.has(t)){g.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=T.get(i);n instanceof P&&new j(n,"on",e).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(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(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=T.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof P&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Q.HISTORY_STATE_KEY="__haoriHistoryState__",Q.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ht=Q;const D=class D{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(D.isHtmlElement(t)&&D.syncElement(t),t.querySelectorAll("*").forEach(e=>{D.syncElement(e)}))}static syncElement(t){const e=D.registrations.get(t),r=T.get(t);if(!r||!D.shouldObserve(r)){e&&(e.observer.disconnect(),D.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&D.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),D.registrations.delete(t));const o=new IntersectionObserver(u=>{const d=D.registrations.get(t);d&&u.forEach(h=>{!h.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new j(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),D.registrations.delete(t))}).catch(m=>{g.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(t);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),D.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(D.isHtmlElement(t)){const e=D.registrations.get(t);e&&(e.observer.disconnect(),D.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=D.registrations.get(e);r&&(r.observer.disconnect(),D.registrations.delete(e))})}static disconnectAll(){D.registrations.forEach(t=>{t.observer.disconnect()}),D.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(g.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);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(t,e){return t.length===1&&t[0]===e}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let J=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(t=>{t.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const t=await Promise.allSettled([N.scan(document.head),N.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ht().start(),J.syncTree(document.body)}static observe(t){const e=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&&N.isAliasedAttributeReflection(n,i.attributeName))break;N.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),J.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{J.cleanupTree(n),N.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(N.addNode(n.parentElement,n),J.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?N.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(e)}};O._initialized=!1,O._mutationObservers=[];let it=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",it.init):it.init();const Qt=()=>X.waitForRenders(),Zt="0.17.2";exports.Core=N;exports.Env=l;exports.Form=y;exports.Fragment=T;exports.Haori=X;exports.Log=g;exports.Queue=M;exports.default=X;exports.version=Zt;exports.waitForRenders=Qt;
|
|
20
20
|
//# sourceMappingURL=haori.cjs.js.map
|
package/dist/haori.es.js
CHANGED
|
@@ -4317,7 +4317,7 @@ ${b}
|
|
|
4317
4317
|
}
|
|
4318
4318
|
if ((!this.options.bindFragments || this.options.bindFragments.length === 0) && this.options.formFragment && a) {
|
|
4319
4319
|
const d = this.options.formFragment, h = d.getTarget(), g = /* @__PURE__ */ new Set();
|
|
4320
|
-
t && t.appliedDisabledAttribute && this.options.targetFragment && g.add(this.options.targetFragment)
|
|
4320
|
+
t && t.appliedDisabledAttribute && this.options.targetFragment && g.add(this.options.targetFragment);
|
|
4321
4321
|
const E = d.getBindingData();
|
|
4322
4322
|
Object.assign(E, i), await x.setBindingData(h, E, g);
|
|
4323
4323
|
}
|
|
@@ -6651,7 +6651,7 @@ const O = class O {
|
|
|
6651
6651
|
O._initialized = !1, O._mutationObservers = [];
|
|
6652
6652
|
let it = O;
|
|
6653
6653
|
document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", it.init) : it.init();
|
|
6654
|
-
const Qt = () => Z.waitForRenders(), Zt = "0.17.
|
|
6654
|
+
const Qt = () => Z.waitForRenders(), Zt = "0.17.2";
|
|
6655
6655
|
export {
|
|
6656
6656
|
x as Core,
|
|
6657
6657
|
l as Env,
|
package/dist/haori.iife.js
CHANGED
|
@@ -14,7 +14,7 @@ ${v}
|
|
|
14
14
|
"use strict";
|
|
15
15
|
${b}
|
|
16
16
|
`)}catch(S){g.error("Haori",`Invalid after script: ${S}`)}}if(t.hasAttribute(f.attrName(e,"dialog"))&&(r.dialogMessage=t.getAttribute(f.attrName(e,"dialog")).replace(/\\n/g,`
|
|
17
|
-
`)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),P=["info","warning","error","success"].includes(b);r.toastLevel=P?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):g.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const P=t.getRawAttribute(S),I=[];if(P?(document.body.querySelectorAll(P).forEach(q=>{const C=T.get(q);C&&I.push(C)}),I.length===0&&g.error("Haori",`Element not found: ${P} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const P=T.get(S);P?r.copySourceFragment=P:g.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else g.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=E.getFormFragment(T.get(v)):g.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t]),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}constructor(t,e=null,r=null){f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){g.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>E.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(n||null,s||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(n="fetchUrl"in d?d.fetchUrl:n,s="fetchOptions"in d?d.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const d={...s||{}},h=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",w=r.queryString;if(y&&g.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:w}),this.options.targetFragment&&n){const B=performance.now(),A={runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:w}:{}};return D.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,A),fetch(n,d).then(v=>this.handleFetchResult(v,n||void 0,B)).catch(v=>{throw n&&D.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,d).then(B=>this.handleFetchResult(B,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),m=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment)
|
|
17
|
+
`)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),P=["info","warning","error","success"].includes(b);r.toastLevel=P?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):g.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const P=t.getRawAttribute(S),I=[];if(P?(document.body.querySelectorAll(P).forEach(q=>{const C=T.get(q);C&&I.push(C)}),I.length===0&&g.error("Haori",`Element not found: ${P} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const P=T.get(S);P?r.copySourceFragment=P:g.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else g.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=E.getFormFragment(T.get(v)):g.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t]),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}constructor(t,e=null,r=null){f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){g.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>E.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(n||null,s||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(n="fetchUrl"in d?d.fetchUrl:n,s="fetchOptions"in d?d.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const d={...s||{}},h=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",w=r.queryString;if(y&&g.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:w}),this.options.targetFragment&&n){const B=performance.now(),A={runtime:l.runtime,requestedMethod:h,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:w}:{}};return D.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,A),fetch(n,d).then(v=>this.handleFetchResult(v,n||void 0,B)).catch(v=>{throw n&&D.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,d).then(B=>this.handleFetchResult(B,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),m=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const y=d.getBindingData();Object.assign(y,i),await M.setBindingData(h,y,m)}const o=a?i:{},u=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(u)}finally{this.releaseExecutionLock(t)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment.getTarget();if(f.RUNNING_CLICK_TARGETS.has(e)||e.matches(":disabled")||e.hasAttribute("disabled")||e.hasAttribute(ht))return!1;const r=e.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(e),e.setAttribute(ht,""),r||e.setAttribute("disabled",""),{target:e,appliedDisabledAttribute:!r}}releaseExecutionLock(t){t&&(f.RUNNING_CLICK_TARGETS.delete(t.target),t.target.removeAttribute(ht),t.appliedDisabledAttribute&&t.target.removeAttribute("disabled"))}async handleFetchResult(t,e,r){const i=dt();if(!t.ok)return Ft(t.status)||(this.options.targetFragment&&e&&D.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t)),!1;if(this.options.targetFragment&&e&&r&&D.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const n=[];n.push(this.bindResult(t)),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 f(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}))}return 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)):g.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)):g.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&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=e!=null,n=r!=null;if(!(!t&&!i&&!n))try{const s=t?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+a.toString();g.error("Haori",u);return}const o=u=>{for(const[d,h]of Object.entries(u))h!=null&&(Array.isArray(h)?h.forEach(m=>a.searchParams.append(d,String(m))):typeof h=="object"?a.searchParams.set(d,JSON.stringify(h)):a.searchParams.set(d,String(h)))};i&&o(e),n&&o(r),history.pushState({[qt]:!0},"",a.toString())}catch(s){g.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async s=>{const a=e?e.getTarget():document.body;await dt().addErrorMessage(a,s)},i=()=>{if(!this.options.scrollOnError)return;const s=e?e.getTarget():document.body;(s.getAttribute("data-message-level")==="error"?s:s.parentElement?.getAttribute("data-message-level")==="error"?s.parentElement:s.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const s=await t.json(),a=[];if(s&&typeof s=="object"){if(typeof s.message=="string"&&a.push({message:s.message}),Array.isArray(s.messages))for(const o of s.messages)typeof o=="string"&&a.push({message:o});if(s.errors&&typeof s.errors=="object")for(const[o,u]of Object.entries(s.errors))Array.isArray(u)?a.push({key:o,message:u.join(`
|
|
18
18
|
`)}):typeof u=="string"?a.push({key:o,message:u}):u!=null&&a.push({key:o,message:String(u)});if(a.length===0)for(const[o,u]of Object.entries(s))o==="message"||o==="messages"||o==="errors"||(Array.isArray(u)?a.push({key:o,message:u.join(`
|
|
19
|
-
`)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await E.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):dt().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindTransform)try{r=z.evaluate(this.options.bindTransform,{response:r})}catch(n){g.error("Haori",`Invalid bind-transform: ${n}`)}if(this.options.bindParams){const n={};this.options.bindParams.forEach(s=>{r&&typeof r=="object"&&s in r&&(n[s]=r[s])}),r=n}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(n=>{const s={...n.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=s[a],u=o&&typeof o=="object"&&!Array.isArray(o)?o:{};s[a]=this.mergeAppendBindingData(n,r,u)}else s[a]=r;i.push(M.setBindingData(n.getTarget(),s))});else{if(typeof r=="string")return g.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(n=>{const s=this.mergeAppendBindingData(n,r),a=this.options.bindMerge?{...n.getRawBindingData()??{},...s}:s;i.push(M.setBindingData(n.getTarget(),a))})}return Promise.all(i).then(()=>{const n=this.options.bindArg??null;this.options.bindFragments.forEach(s=>{D.bindComplete(s.getTarget(),n)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},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 t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};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 t={};let e=!1;if(this.options.formFragment&&Object.assign(t,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,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=l.runtime==="demo"&&!zt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Gt(i,e));else if(Object.keys(e).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const m=new FormData;for(const[y,w]of Object.entries(e))w==null?m.append(y,""):w instanceof Blob?m.append(y,w):Array.isArray(w)?w.forEach(B=>m.append(y,String(B))):typeof w=="object"?m.append(y,JSON.stringify(w)):m.append(y,String(w));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(h)){const m=new URLSearchParams;for(const[y,w]of Object.entries(e))w!==void 0&&(w===null?m.append(y,""):Array.isArray(w)?w.forEach(B=>m.append(y,String(B))):typeof w=="object"?m.append(y,JSON.stringify(w)):m.append(y,String(w)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let d;return o&&(d=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:d,transportMode:o?"query-get":"http",signature:Xt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.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?f.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(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=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}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];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+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return g.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(g.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(M.evaluateAll(r)),e.push(E.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Jt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Qt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw g.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Ft(r.status);const n=`${r.status} ${r.statusText}`;throw g.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw g.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(g.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return g.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const c=class c{static isDeferredAttributeName(t){return c.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!c.isEvaluateAllExcludedAttributeName(t)&&c.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=T.get(t);return r instanceof x?r.hasAttribute(`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);c.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>c.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof x?e.push(c.evaluateAll(r)):r instanceof U&&e.push(c.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=c.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return c.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=c.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return c.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(c.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(c.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof x&&r.push(c.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=c.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new j(t,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedFetch(t)}))}static executeManagedImport(t){const e=t.getTarget(),r=c.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.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 e.setAttribute(`${l.prefix}importing`,""),D.importStart(e,n),Qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return N.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),D.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(d=>{const h=T.get(d);h instanceof x?u.push(c.scan(h.getTarget())):h instanceof U&&u.push(c.evaluateText(h))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),D.importError(e,n,a),g.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedImport(t)})}static scan(t){const e=T.get(t);return e?c.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return c.initializeElementFragment(t,!0).then(()=>{c.needsScheduledEvaluateAll(t)&&c.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return c.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():c.initializeElementAttributes(t).then(()=>{if(c.shouldSkipChildInitialization(t,e)){c.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof x?r.push(c.initializeElementFragment(i,e)):i instanceof U&&r.push(c.evaluateText(i))}),Promise.all(r).then(()=>{c.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of c.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||c.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>c.setAttribute(t.getTarget(),i,n)))}for(const i of c.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&c.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=T.get(t),s=c.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof x&&n.consumeSelfWrittenBind(r))break;n.setBindingData(c.parseDataBind(r))}break}case`${l.prefix}derive`:u=c.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=c.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=c.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=c.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(c.evaluateIf(n));break;case`${l.prefix}each`:a.push(c.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(c.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(c.executeManagedImport(n));break;case`${l.prefix}url-param`:{const d=n.getAttribute(`${l.prefix}url-arg`),h=Jt.readParams();if(d===null)a.push(c.setBindingData(t,h,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=h,a.push(c.setBindingData(t,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(d=>{if(d)return c.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=T.get(t),s=n.getRawBindingData();n.setBindingData(e),D.bindChange(t,s,e,"manual");const a=()=>{const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const d=n.getAttribute(`${l.prefix}form-arg`),h=d&&o[String(d)]&&typeof o[String(d)]=="object"&&!Array.isArray(o[String(d)])?o[String(d)]:d?{}:o;u=u.then(()=>E.syncValues(n,h))}return u=u.then(()=>c.evaluateAll(n,r)),u=u.then(()=>c.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>{})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=T.get(t);return r instanceof x?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=T.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const d=u.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(u,d,h,m)=>{if(u)for(const y of Object.keys(u))y in i||(i[y]={value:u[y],source:n(d),kind:h,depth:m})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&g.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return g.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.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(t,e){const r=T.get(t);if(r.isSkipMutationNodes())return;const i=T.get(e.nextSibling),n=T.get(e);n&&(r.insertBefore(n,i),n instanceof x?c.scan(n.getTarget()):n instanceof U&&c.evaluateText(n))}static removeNode(t){const e=T.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=T.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=T.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=c.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(c.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?c.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=c.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,d=!1,h=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const m=c.createDeriveInputSignature(t,a,o);m===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==m&&(r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>c.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>c.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}h=c.createDescendantBindingSignature(t,"evaluateAll"),d=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===h,c.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const m=[];return t.getChildren().forEach(y=>{if(y instanceof x){if(c.canSkipUnchangedNestedEach(y))return;m.push(c.evaluateAll(y,e))}else y instanceof U&&m.push(c.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{d&&h!==null&&t.setDeriveSubtreeSignature(h)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return c.createBindingSignature(i)===c.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=c.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),g.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(c.isHiddenIfCondition(r))H.isEnabled()&&c.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{D.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof x?n.push(s.isMounted()?c.evaluateAll(s):c.scan(s.getTarget())):s instanceof U&&n.push(c.evaluateText(s))}),e.push(t.show().then(()=>{D.show(t.getTarget()),i||c.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{g.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=c.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},c.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=c.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):c.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await c.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=c.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof x){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof x&&(r=h.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const d=T.get(u);d instanceof x&&t.getChildren().includes(d)&&(t.removeChild(d),d.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(g.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||c.hasNonEachDynamicElementState(t))return!1;const r=c.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!c.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof x?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return c.recordDerivedSubtreeSignatureComputation(t,e),c.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:c.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(c.createDescendantBindingSignature(t,"refresh")),c.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=c.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:c.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof x).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof x?!c.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return g.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const P=c.createListKey(b,n?String(n):null,S);o.push(P),a.set(P,{item:b,itemIndex:S})});const u=new Set(o),d=[];let h=t.getChildren().filter(b=>b instanceof x).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const m=h.map(b=>b.getListKey());h=h.filter(b=>u.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const y=h.map(b=>b.getListKey()),w=new Map;h.forEach(b=>{const S=b.getListKey();S!==null&&!w.has(S)&&w.set(S,b)});const B=t.getChildElementFragments().slice(),A=B.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:P,itemIndex:I}=a.get(b);let $;const q=w.get(b);if(q)$=q,v=v.then(()=>c.updateRowFragment($,P,i,I,s?String(s):null,b).then(C=>{if(C)return c.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>c.updateRowFragment($,P,i,I,s?String(s):null,b).then(()=>{const _=B[C]??null;return t.insertBefore($,_).then(()=>{B.splice(C,0,$)}).then(()=>c.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=y.filter(C=>C!==null),P=new Set(S),I=b.filter(C=>!P.has(C)),q=m.filter(C=>C!==null).filter(C=>!u.has(C));D.eachUpdate(t.getTarget(),I,q,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&c.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>c.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${c.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{c.evaluateAll(t)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap;let M=c;const Z=class Z{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=T.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Z.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}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[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Z.BUILTIN_EVENT_NAMES.has(t)){g.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=T.get(i);n instanceof x&&new j(n,"on",e).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(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(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=T.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof x&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Z.HISTORY_STATE_KEY="__haoriHistoryState__",Z.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ft=Z;const R=class R{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(R.isHtmlElement(t)&&R.syncElement(t),t.querySelectorAll("*").forEach(e=>{R.syncElement(e)}))}static syncElement(t){const e=R.registrations.get(t),r=T.get(t);if(!r||!R.shouldObserve(r)){e&&(e.observer.disconnect(),R.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=R.resolveRoot(r),n=R.resolveRootMargin(r),s=R.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&R.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),R.registrations.delete(t));const o=new IntersectionObserver(u=>{const d=R.registrations.get(t);d&&u.forEach(h=>{!h.isIntersecting||d.running||R.isDisabled(d.fragment)||(d.running=!0,new j(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),R.registrations.delete(t))}).catch(m=>{g.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=R.registrations.get(t);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),R.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(R.isHtmlElement(t)){const e=R.registrations.get(t);e&&(e.observer.disconnect(),R.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=R.registrations.get(e);r&&(r.observer.disconnect(),R.registrations.delete(e))})}static disconnectAll(){R.registrations.forEach(t=>{t.observer.disconnect()}),R.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!R.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return R.isHtmlElement(i)?i:(g.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);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(t,e){return t.length===1&&t[0]===e}};R.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),R.registrations=new Map;let Q=R;const L=class L{static disconnectMutationObservers(){L._mutationObservers.forEach(t=>{t.disconnect()}),L._mutationObservers.length=0}static async init(){if(L._initialized)return;L._initialized=!0,L.disconnectMutationObservers();const t=await Promise.allSettled([M.scan(document.head),M.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",r.reason),await N.wait(),document.body.setAttribute("data-haori-ready",""),L.observe(document.head),L.observe(document.body),new ft().start(),Q.syncTree(document.body)}static observe(t){const e=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),Q.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Q.cleanupTree(n),M.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(M.addNode(n.parentElement,n),Q.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?M.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),L._mutationObservers.push(e)}};L._initialized=!1,L._mutationObservers=[];let nt=L;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt.init):nt.init();const Zt=()=>Y.waitForRenders(),_t="0.17.1";return O.Core=M,O.Env=l,O.Form=E,O.Fragment=T,O.Haori=Y,O.Log=g,O.Queue=N,O.default=Y,O.version=_t,O.waitForRenders=Zt,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),O}({});
|
|
19
|
+
`)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await E.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):dt().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindTransform)try{r=z.evaluate(this.options.bindTransform,{response:r})}catch(n){g.error("Haori",`Invalid bind-transform: ${n}`)}if(this.options.bindParams){const n={};this.options.bindParams.forEach(s=>{r&&typeof r=="object"&&s in r&&(n[s]=r[s])}),r=n}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(n=>{const s={...n.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=s[a],u=o&&typeof o=="object"&&!Array.isArray(o)?o:{};s[a]=this.mergeAppendBindingData(n,r,u)}else s[a]=r;i.push(M.setBindingData(n.getTarget(),s))});else{if(typeof r=="string")return g.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(n=>{const s=this.mergeAppendBindingData(n,r),a=this.options.bindMerge?{...n.getRawBindingData()??{},...s}:s;i.push(M.setBindingData(n.getTarget(),a))})}return Promise.all(i).then(()=>{const n=this.options.bindArg??null;this.options.bindFragments.forEach(s=>{D.bindComplete(s.getTarget(),n)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},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 t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};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 t={};let e=!1;if(this.options.formFragment&&Object.assign(t,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,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=l.runtime==="demo"&&!zt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Gt(i,e));else if(Object.keys(e).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const m=new FormData;for(const[y,w]of Object.entries(e))w==null?m.append(y,""):w instanceof Blob?m.append(y,w):Array.isArray(w)?w.forEach(B=>m.append(y,String(B))):typeof w=="object"?m.append(y,JSON.stringify(w)):m.append(y,String(w));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(h)){const m=new URLSearchParams;for(const[y,w]of Object.entries(e))w!==void 0&&(w===null?m.append(y,""):Array.isArray(w)?w.forEach(B=>m.append(y,String(B))):typeof w=="object"?m.append(y,JSON.stringify(w)):m.append(y,String(w)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let d;return o&&(d=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:d,transportMode:o?"query-get":"http",signature:Xt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.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?f.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(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=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}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];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+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return g.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(g.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(M.evaluateAll(r)),e.push(E.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Jt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Qt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw g.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Ft(r.status);const n=`${r.status} ${r.statusText}`;throw g.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw g.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(g.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return g.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const c=class c{static isDeferredAttributeName(t){return c.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!c.isEvaluateAllExcludedAttributeName(t)&&c.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=T.get(t);return r instanceof x?r.hasAttribute(`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);c.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>c.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof x?e.push(c.evaluateAll(r)):r instanceof U&&e.push(c.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=c.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return c.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=c.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return c.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(c.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(c.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof x&&r.push(c.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=c.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new j(t,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedFetch(t)}))}static executeManagedImport(t){const e=t.getTarget(),r=c.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.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 e.setAttribute(`${l.prefix}importing`,""),D.importStart(e,n),Qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return N.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),D.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(d=>{const h=T.get(d);h instanceof x?u.push(c.scan(h.getTarget())):h instanceof U&&u.push(c.evaluateText(h))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),D.importError(e,n,a),g.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedImport(t)})}static scan(t){const e=T.get(t);return e?c.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return c.initializeElementFragment(t,!0).then(()=>{c.needsScheduledEvaluateAll(t)&&c.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return c.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():c.initializeElementAttributes(t).then(()=>{if(c.shouldSkipChildInitialization(t,e)){c.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof x?r.push(c.initializeElementFragment(i,e)):i instanceof U&&r.push(c.evaluateText(i))}),Promise.all(r).then(()=>{c.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of c.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||c.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>c.setAttribute(t.getTarget(),i,n)))}for(const i of c.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>c.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&c.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=T.get(t),s=c.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof x&&n.consumeSelfWrittenBind(r))break;n.setBindingData(c.parseDataBind(r))}break}case`${l.prefix}derive`:u=c.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=c.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=c.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=c.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(c.evaluateIf(n));break;case`${l.prefix}each`:a.push(c.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(c.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(c.executeManagedImport(n));break;case`${l.prefix}url-param`:{const d=n.getAttribute(`${l.prefix}url-arg`),h=Jt.readParams();if(d===null)a.push(c.setBindingData(t,h,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=h,a.push(c.setBindingData(t,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(d=>{if(d)return c.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=T.get(t),s=n.getRawBindingData();n.setBindingData(e),D.bindChange(t,s,e,"manual");const a=()=>{const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const d=n.getAttribute(`${l.prefix}form-arg`),h=d&&o[String(d)]&&typeof o[String(d)]=="object"&&!Array.isArray(o[String(d)])?o[String(d)]:d?{}:o;u=u.then(()=>E.syncValues(n,h))}return u=u.then(()=>c.evaluateAll(n,r)),u=u.then(()=>c.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>{})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=T.get(t);return r instanceof x?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=T.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const d=u.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(u,d,h,m)=>{if(u)for(const y of Object.keys(u))y in i||(i[y]={value:u[y],source:n(d),kind:h,depth:m})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&g.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return g.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.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(t,e){const r=T.get(t);if(r.isSkipMutationNodes())return;const i=T.get(e.nextSibling),n=T.get(e);n&&(r.insertBefore(n,i),n instanceof x?c.scan(n.getTarget()):n instanceof U&&c.evaluateText(n))}static removeNode(t){const e=T.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=T.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=T.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=c.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(c.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?c.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=c.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,d=!1,h=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const m=c.createDeriveInputSignature(t,a,o);m===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==m&&(r=r.then(()=>c.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>c.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>c.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}h=c.createDescendantBindingSignature(t,"evaluateAll"),d=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===h,c.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const m=[];return t.getChildren().forEach(y=>{if(y instanceof x){if(c.canSkipUnchangedNestedEach(y))return;m.push(c.evaluateAll(y,e))}else y instanceof U&&m.push(c.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{d&&h!==null&&t.setDeriveSubtreeSignature(h)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return c.createBindingSignature(i)===c.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=c.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),g.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(c.isHiddenIfCondition(r))H.isEnabled()&&c.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{D.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof x?n.push(s.isMounted()?c.evaluateAll(s):c.scan(s.getTarget())):s instanceof U&&n.push(c.evaluateText(s))}),e.push(t.show().then(()=>{D.show(t.getTarget()),i||c.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{g.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=c.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},c.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=c.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):c.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await c.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=c.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof x){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof x&&(r=h.clone(),c.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const d=T.get(u);d instanceof x&&t.getChildren().includes(d)&&(t.removeChild(d),d.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(g.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||c.hasNonEachDynamicElementState(t))return!1;const r=c.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!c.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof x?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return c.recordDerivedSubtreeSignatureComputation(t,e),c.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:c.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!c.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(c.createDescendantBindingSignature(t,"refresh")),c.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=c.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:c.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof x).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=c.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof x?!c.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return g.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const P=c.createListKey(b,n?String(n):null,S);o.push(P),a.set(P,{item:b,itemIndex:S})});const u=new Set(o),d=[];let h=t.getChildren().filter(b=>b instanceof x).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const m=h.map(b=>b.getListKey());h=h.filter(b=>u.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const y=h.map(b=>b.getListKey()),w=new Map;h.forEach(b=>{const S=b.getListKey();S!==null&&!w.has(S)&&w.set(S,b)});const B=t.getChildElementFragments().slice(),A=B.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:P,itemIndex:I}=a.get(b);let $;const q=w.get(b);if(q)$=q,v=v.then(()=>c.updateRowFragment($,P,i,I,s?String(s):null,b).then(C=>{if(C)return c.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>c.updateRowFragment($,P,i,I,s?String(s):null,b).then(()=>{const _=B[C]??null;return t.insertBefore($,_).then(()=>{B.splice(C,0,$)}).then(()=>c.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=y.filter(C=>C!==null),P=new Set(S),I=b.filter(C=>!P.has(C)),q=m.filter(C=>C!==null).filter(C=>!u.has(C));D.eachUpdate(t.getTarget(),I,q,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&c.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>c.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${c.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{c.evaluateAll(t)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap;let M=c;const Z=class Z{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=T.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Z.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}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[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Z.BUILTIN_EVENT_NAMES.has(t)){g.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=T.get(i);n instanceof x&&new j(n,"on",e).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(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(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=T.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof x&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Z.HISTORY_STATE_KEY="__haoriHistoryState__",Z.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ft=Z;const R=class R{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(R.isHtmlElement(t)&&R.syncElement(t),t.querySelectorAll("*").forEach(e=>{R.syncElement(e)}))}static syncElement(t){const e=R.registrations.get(t),r=T.get(t);if(!r||!R.shouldObserve(r)){e&&(e.observer.disconnect(),R.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=R.resolveRoot(r),n=R.resolveRootMargin(r),s=R.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&R.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),R.registrations.delete(t));const o=new IntersectionObserver(u=>{const d=R.registrations.get(t);d&&u.forEach(h=>{!h.isIntersecting||d.running||R.isDisabled(d.fragment)||(d.running=!0,new j(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),R.registrations.delete(t))}).catch(m=>{g.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=R.registrations.get(t);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),R.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(R.isHtmlElement(t)){const e=R.registrations.get(t);e&&(e.observer.disconnect(),R.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=R.registrations.get(e);r&&(r.observer.disconnect(),R.registrations.delete(e))})}static disconnectAll(){R.registrations.forEach(t=>{t.observer.disconnect()}),R.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!R.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return R.isHtmlElement(i)?i:(g.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);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(t,e){return t.length===1&&t[0]===e}};R.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),R.registrations=new Map;let Q=R;const L=class L{static disconnectMutationObservers(){L._mutationObservers.forEach(t=>{t.disconnect()}),L._mutationObservers.length=0}static async init(){if(L._initialized)return;L._initialized=!0,L.disconnectMutationObservers();const t=await Promise.allSettled([M.scan(document.head),M.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",r.reason),await N.wait(),document.body.setAttribute("data-haori-ready",""),L.observe(document.head),L.observe(document.body),new ft().start(),Q.syncTree(document.body)}static observe(t){const e=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),Q.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Q.cleanupTree(n),M.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(M.addNode(n.parentElement,n),Q.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?M.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),L._mutationObservers.push(e)}};L._initialized=!1,L._mutationObservers=[];let nt=L;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt.init):nt.init();const Zt=()=>Y.waitForRenders(),_t="0.17.2";return O.Core=M,O.Env=l,O.Form=E,O.Fragment=T,O.Haori=Y,O.Log=g,O.Queue=N,O.default=Y,O.version=_t,O.waitForRenders=Zt,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),O}({});
|
|
20
20
|
//# sourceMappingURL=haori.iife.js.map
|
package/dist/index.d.ts
CHANGED