haori 0.26.0 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/haori.cjs.js +2 -2
- package/dist/haori.es.js +367 -368
- package/dist/haori.iife.js +2 -2
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/haori.iife.js
CHANGED
|
@@ -18,9 +18,9 @@ ${v}
|
|
|
18
18
|
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const v=e.getRawAttribute(g.attrName(t,"toast-level")),C=["info","warning","error","success"].includes(v);r.toastLevel=C?v:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const v=g.attrName(t,"redirect-return-param");e.hasAttribute(v)&&(r.redirectReturnParam=e.getAttribute(v))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const v=e.getRawAttribute(g.attrName(t,"history-form"));if(v){const R=document.body.querySelector(v);R!==null?r.historyFormFragment=A.getFormFragment(S.get(R)):p.error("Haori",`Form element not found: ${v} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(v=>{const R=g.attrName(t,v);if(!e.hasAttribute(R))return;const C=e.getRawAttribute(R),N=[];if(C)document.body.querySelectorAll(C).forEach($=>{const X=S.get($);X&&N.push(X)}),N.length===0&&p.error("Haori",`Element not found: ${C} (${R})`);else if(v==="open"||v==="close"){const q=e.getTarget().closest("dialog");q?N.push(S.get(q)):p.error("Haori",`Ancestor <dialog> not found (${R})`)}else N.push(e);if(N.length>0)switch(v){case"reset-before":r.resetBeforeFragments=N;break;case"reset":r.resetFragments=N;break;case"refetch":r.refetchFragments=N;break;case"click":r.clickFragments=N;break;case"copy":r.copyFragments=N;break;case"open":r.openFragments=N;break;case"close":r.closeFragments=N;break}});const b=g.attrName(t,"copy-source");if(e.hasAttribute(b)){const v=e.getRawAttribute(b);if(v){const R=document.body.querySelector(v);if(R!==null){const C=S.get(R);C?r.copySourceFragment=C:p.error("Haori",`Element is not managed by Haori: ${v} (${b})`)}else p.error("Haori",`Element not found: ${v} (${b})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const E=e.getRawAttribute(g.attrName(null,"form",!0));if(E){const b=document.body.querySelector(E);b!==null?r.formFragment=A.getFormFragment(S.get(b)):p.error("Haori",`Form element not found: ${E} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}const H=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(H)){const E=e.getRawAttribute(H),b=[];E?(document.body.querySelectorAll(E).forEach(R=>{const C=S.get(R);C&&b.push(C)}),b.length===0&&p.error("Haori",`Element not found: ${E} (${H})`)):b.push(e),b.length>0&&(r.fetchStateFragments=b)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null:!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const d=this.options.targetFragment?.getTarget()??null;try{const c=this.options.runScript.call(d,this.domEvent);c===!1&&this.domEvent&&this.domEvent.preventDefault(),c!=null&&typeof c.then=="function"&&await c}catch(c){p.error("Haori",`Run script execution error: ${c}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>A.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||{}},c=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const k=performance.now(),H={runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,H),await this.injectFetchState("loading"),fetch(n,d).then(E=>this.handleFetchResult(E,n||void 0,k)).catch(async E=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,E),await this.injectFetchState("error",null,E instanceof Error?E.message:String(E)),E})}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,c=d.getTarget(),m=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const y=d.getBindingData();Object.assign(y,ye(i)),await P.setBindingData(c,y,m)}this.suppressEmptyReplaceBind=!a&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input");const o=a?ye(i):{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(be))return!1;const r=t.hasAttribute(`${u.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(be,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(be),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=le();if(!e.ok)return Ue(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await P.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):p.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)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const d=new URLSearchParams(window.location.search).get(o);if(d!==null){const c=d.trim();Ve.isSafeLocalPath(c)?a=c:p.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${d}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",l);return}const o=l=>{for(const[d,c]of Object.entries(l))c!=null&&(Array.isArray(c)?c.forEach(m=>a.searchParams.append(d,String(m))):typeof c=="object"?a.searchParams.set(d,JSON.stringify(c)):a.searchParams.set(d,String(c)))};i&&o(t),n&&o(r),history.pushState({[nt]:!0},"",a.toString())}catch(s){p.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await le().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await le().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,d=[];for(const c of a)if(c&&typeof c=="object"&&!Array.isArray(c)){const m=c.key,y=c.message,T=typeof m=="string"&&m.length>0?m:null,k=typeof y=="string"?y:y!=null?String(y):"";if(k.length===0)continue;if(T!==null){const H=l.get(T)??[];H.push(k),l.set(T,H)}else d.push(k)}else typeof c=="string"&&c.length>0&&d.push(c);for(const[c,m]of l)o.push({key:c,message:m.join(`
|
|
19
19
|
`)});for(const c of d)o.push({message:c})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,d]of Object.entries(a.errors))Array.isArray(d)?o.push({key:l,message:d.join(`
|
|
20
20
|
`)}):typeof d=="string"?o.push({key:l,message:d}):d!=null&&o.push({key:l,message:String(d)});if(o.length===0)for(const[l,d]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(d)?o.push({key:l,message:d.join(`
|
|
21
|
-
`)}):typeof d=="string"&&o.push({key:l,message:d}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await A.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):le().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=G.evaluate(this.options.bindTransform,{response:i})}catch(s){p.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${u.prefix}${this.eventType}-form.`);return}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],d=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,d)}else a[o]=i;n.push(P.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(P.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?ue(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?ue(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,A.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=u.runtime==="demo"&&!at(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&re(t)){const c=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(c)?ct(t)&&p.warn("Haori",`A File value nested under ${u.prefix}form-object / ${u.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${u.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=lt(i,t));else if(Object.keys(t).length>0){const c=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){s.delete("Content-Type");const m=new FormData;for(const[y,T]of Object.entries(t))T==null?m.append(y,""):T instanceof Blob?m.append(y,T):Array.isArray(T)?T.forEach(k=>{k instanceof Blob?m.append(y,k):m.append(y,String(k))}):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(c)){const m=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?m.append(y,""):Array.isArray(T)?T.forEach(k=>m.append(y,String(k))):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}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:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:d,transportMode:o?"query-get":"http",signature:dt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?ue(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return ue(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return P.setBindingData(a,o,new Set,!1,!1)}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let K=g;class ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Ue(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=S.get(e);return r instanceof x?r.hasAttribute(`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>h.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof x?t.push(h.evaluateAll(r)):r instanceof V&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=h.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=h.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${u.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(h.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof x&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=h.getReactiveFetchState(t),i=K.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new K(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.getAttributeEvaluation(`${u.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${u.prefix}importing`,""),F.importStart(t,n),ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${u.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(d=>{const c=S.get(d);c instanceof x?l.push(h.scan(c.getTarget())):c instanceof V&&l.push(h.evaluateText(c))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),F.importError(t,n,a),p.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedImport(e)})}static scan(e){const t=S.get(e);return t?h.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e,t)){h.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof x?r.push(h.initializeElementFragment(i,t)):i instanceof V&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>h.setAttribute(e.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&h.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=S.get(e),s=h.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${u.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof x&&n.consumeSelfWrittenBind(r))break;n.setBindingData(h.parseDataBind(r))}break}case`${u.prefix}derive`:l=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),o=h.evaluateDerive(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${u.prefix}derive-name`:l=h.createDeriveInputSignature(n,n.getRawAttribute(`${u.prefix}derive`),r),o=h.evaluateDerive(n,n.getRawAttribute(`${u.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${u.prefix}if`:a.push(h.evaluateIf(n));break;case`${u.prefix}each`:a.push(h.evaluateEach(n));break;case`${u.prefix}fetch`:a.push(h.executeManagedFetch(n));break;case`${u.prefix}import`:typeof r=="string"&&a.push(h.executeManagedImport(n));break;case`${u.prefix}url-param`:{const d=n.getAttribute(`${u.prefix}url-arg`),c=Ve.readParams();if(d===null)a.push(h.setBindingData(e,c,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=c,a.push(h.setBindingData(e,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(d=>{if(d)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=S.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let d=n?s.setAttribute(`${u.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const c=s.getAttribute(`${u.prefix}form-arg`),m=c&&l[String(c)]&&typeof l[String(c)]=="object"&&!Array.isArray(l[String(c)])?l[String(c)]:c?{}:l;d=d.then(()=>A.syncValues(s,m))}return d=d.then(()=>h.evaluateAll(s,r)),d=d.then(()=>h.reevaluateReactiveSpecialAttributes(s,r)),d.then(()=>s.markBindingWorkEnd(),c=>{throw s.markBindingWorkEnd(),c})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=S.get(e);return r instanceof x?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=S.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const d=l.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(l,d,c,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(d),kind:c,depth:m})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return U.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=S.get(e);if(r.isSkipMutationNodes())return;const i=S.get(t.nextSibling),n=S.get(t);n&&(r.insertBefore(n,i),n instanceof x?h.scan(n.getTarget()):n instanceof V&&h.evaluateText(n))}static removeNode(e){const t=S.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=S.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=S.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=h.getFormFragment(r);if(n){const s=A.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(h.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?h.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${u.prefix}derive`),n=e.hasAttribute(`${u.prefix}if`),s=e.hasAttribute(`${u.prefix}each`),a=e.getRawAttribute(`${u.prefix}derive`),o=e.getRawAttribute(`${u.prefix}derive-name`);let l=!1,d=!1,c=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const m=h.createDeriveInputSignature(e,a,o);m===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==m&&(r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>h.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}c=h.createDescendantBindingSignature(e,"evaluateAll"),d=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===c,h.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const m=[];return e.getChildren().forEach(y=>{if(y instanceof x){if(h.canSkipUnchangedNestedEach(y))return;m.push(h.evaluateAll(y,t))}else y instanceof V&&m.push(h.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{d&&c!==null&&e.setDeriveSubtreeSignature(c)}))}static evaluateDerive(e,t=e.getRawAttribute(`${u.prefix}derive`),r=e.getRawAttribute(`${u.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=G.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return h.createBindingSignature(i)===h.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${u.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=h.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(h.isHiddenIfCondition(r))U.isEnabled()&&h.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof x?n.push(s.isMounted()?h.evaluateAll(s):h.scan(s.getTarget())):s instanceof V&&n.push(h.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||h.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${u.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new K(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=h.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=h.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):h.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),h.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}h.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${u.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
21
|
+
`)}):typeof d=="string"&&o.push({key:l,message:d}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await A.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):le().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=G.evaluate(this.options.bindTransform,{response:i})}catch(s){p.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${u.prefix}${this.eventType}-form.`);return}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],d=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,d)}else a[o]=i;n.push(P.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(P.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?ue(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?ue(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,A.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=u.runtime==="demo"&&!at(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&re(t)){const c=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(c)?ct(t)&&p.warn("Haori",`A File value nested under ${u.prefix}form-object / ${u.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${u.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=lt(i,t));else if(Object.keys(t).length>0){const c=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){s.delete("Content-Type");const m=new FormData;for(const[y,T]of Object.entries(t))T==null?m.append(y,""):T instanceof Blob?m.append(y,T):Array.isArray(T)?T.forEach(k=>{k instanceof Blob?m.append(y,k):m.append(y,String(k))}):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(c)){const m=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?m.append(y,""):Array.isArray(T)?T.forEach(k=>m.append(y,String(k))):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}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:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:d,transportMode:o?"query-get":"http",signature:dt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?ue(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return ue(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return P.setBindingData(a,o,new Set,!1,!1)}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let K=g;class ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Ue(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=S.get(e);return r instanceof x?r.hasAttribute(`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>h.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof x?t.push(h.evaluateAll(r)):r instanceof V&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=h.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=h.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${u.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(h.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof x&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=h.getReactiveFetchState(t),i=K.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new K(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.getAttributeEvaluation(`${u.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${u.prefix}importing`,""),F.importStart(t,n),ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${u.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(d=>{const c=S.get(d);c instanceof x?l.push(h.scan(c.getTarget())):c instanceof V&&l.push(h.evaluateText(c))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),F.importError(t,n,a),p.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedImport(e)})}static scan(e){const t=S.get(e);return t?h.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e,t)){h.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof x?r.push(h.initializeElementFragment(i,t)):i instanceof V&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>h.setAttribute(e.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&h.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=S.get(e),s=h.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${u.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof x&&n.consumeSelfWrittenBind(r))break;n.setBindingData(h.parseDataBind(r))}break}case`${u.prefix}derive`:l=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),o=h.evaluateDerive(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${u.prefix}derive-name`:l=h.createDeriveInputSignature(n,n.getRawAttribute(`${u.prefix}derive`),r),o=h.evaluateDerive(n,n.getRawAttribute(`${u.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${u.prefix}if`:a.push(h.evaluateIf(n));break;case`${u.prefix}each`:a.push(h.evaluateEach(n));break;case`${u.prefix}fetch`:a.push(h.executeManagedFetch(n));break;case`${u.prefix}import`:typeof r=="string"&&a.push(h.executeManagedImport(n));break;case`${u.prefix}url-param`:{const d=n.getAttribute(`${u.prefix}url-arg`),c=Ve.readParams();if(d===null)a.push(h.setBindingData(e,c,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=c,a.push(h.setBindingData(e,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(d=>{if(d)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=S.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let d=n?s.setAttribute(`${u.prefix}bind`,JSON.stringify(l)):Promise.resolve();return e.tagName==="FORM"&&(d=d.then(()=>{const c=s.getRawBindingData()??t,m=s.getAttribute(`${u.prefix}form-arg`),y=m&&c[String(m)]&&typeof c[String(m)]=="object"&&!Array.isArray(c[String(m)])?c[String(m)]:m?{}:c;return A.syncValues(s,y)})),d=d.then(()=>h.evaluateAll(s,r)),d=d.then(()=>h.reevaluateReactiveSpecialAttributes(s,r)),d.then(()=>s.markBindingWorkEnd(),c=>{throw s.markBindingWorkEnd(),c})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=S.get(e);return r instanceof x?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=S.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const d=l.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(l,d,c,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(d),kind:c,depth:m})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return U.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=S.get(e);if(r.isSkipMutationNodes())return;const i=S.get(t.nextSibling),n=S.get(t);n&&(r.insertBefore(n,i),n instanceof x?h.scan(n.getTarget()):n instanceof V&&h.evaluateText(n))}static removeNode(e){const t=S.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=S.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=S.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=h.getFormFragment(r);if(n){const s=A.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(h.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?h.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${u.prefix}derive`),n=e.hasAttribute(`${u.prefix}if`),s=e.hasAttribute(`${u.prefix}each`),a=e.getRawAttribute(`${u.prefix}derive`),o=e.getRawAttribute(`${u.prefix}derive-name`);let l=!1,d=!1,c=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const m=h.createDeriveInputSignature(e,a,o);m===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==m&&(r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>h.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}c=h.createDescendantBindingSignature(e,"evaluateAll"),d=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===c,h.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const m=[];return e.getChildren().forEach(y=>{if(y instanceof x){if(h.canSkipUnchangedNestedEach(y))return;m.push(h.evaluateAll(y,t))}else y instanceof V&&m.push(h.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{d&&c!==null&&e.setDeriveSubtreeSignature(c)}))}static evaluateDerive(e,t=e.getRawAttribute(`${u.prefix}derive`),r=e.getRawAttribute(`${u.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=G.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return h.createBindingSignature(i)===h.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${u.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=h.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(h.isHiddenIfCondition(r))U.isEnabled()&&h.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof x?n.push(s.isMounted()?h.evaluateAll(s):h.scan(s.getTarget())):s instanceof V&&n.push(h.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||h.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${u.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new K(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=h.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=h.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):h.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),h.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}h.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${u.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
22
22
|
${r}
|
|
23
23
|
);`)}catch{try{i=new Function(`"use strict";
|
|
24
24
|
${r}
|
|
25
|
-
`)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${u.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(h.EACH_RENDERED_CHANGE_WARNED.has(r)||(h.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),h.countEachRenderedRows(e)!==0){if(!n){if(h.EACH_RENDERED_CHANGE_FIRED.has(r))return;h.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${u.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=h.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${u.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof x){if(a.hasAttribute(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const c=S.get(l);c instanceof x&&(r=c.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const d=S.get(l);d instanceof x&&e.getChildren().includes(d)&&(e.removeChild(d),d.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${u.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(p.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${u.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${u.prefix}derive`)||t?.closestByAttribute(`${u.prefix}derive-name`)||t?.closestByAttribute(`${u.prefix}if`)||t?.closestByAttribute(`${u.prefix}fetch`)||t?.closestByAttribute(`${u.prefix}import`)||h.hasNonEachDynamicElementState(e))return!1;const r=h.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}if`)||e.hasAttribute(`${u.prefix}each`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof x?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return h.recordDerivedSubtreeSignatureComputation(e,t),h.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:h.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(h.createDescendantBindingSignature(e,"refresh")),h.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!U.isEnabled()||!e.hasAttribute(`${u.prefix}derive`))return null;const t=h.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:h.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${u.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof x).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof x?!h.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${u.prefix}attr-`)||t.startsWith(u.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${u.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${u.prefix}each-key`),s=e.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];t.forEach((b,v)=>{const R=h.createListKey(b,n?String(n):null,v);o.push(R),a.set(R,{item:b,itemIndex:v})});const l=new Set(o),d=[];let c=e.getChildren().filter(b=>b instanceof x).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const m=c.map(b=>b.getListKey());c=c.filter(b=>l.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const y=c.map(b=>b.getListKey()),T=new Map;c.forEach(b=>{const v=b.getListKey();v!==null&&!T.has(v)&&T.set(v,b)});const k=e.getChildElementFragments().slice(),H=k.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((b,v)=>{const{item:R,itemIndex:C}=a.get(b);let N;const q=T.get(b);if(q)N=q,E=E.then(()=>h.updateRowFragment(N,R,i,C,s?String(s):null,b).then($=>{if($)return h.evaluateAll(N)}));else{N=r.clone();const $=H+v;E=E.then(()=>h.updateRowFragment(N,R,i,C,s?String(s):null,b).then(()=>{const X=k[$]??null;return e.insertBefore(N,X).then(()=>{k.splice($,0,N)}).then(()=>h.initializeFreshEachRow(N))}))}}),Promise.all(d).then(()=>E).then(()=>{const b=o.filter($=>$!==null),v=y.filter($=>$!==null),R=new Set(v),C=b.filter($=>!R.has($)),q=m.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,q,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=h.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${u.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${u.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>h.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${h.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{h.evaluateAll(e)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap,h.EACH_RENDERED_CHANGE_FIRED=new WeakSet,h.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let P=h;const te=class te{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=S.get(e);t&&new K(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,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))}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),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(te.BUILTIN_EVENT_NAMES.has(e)){p.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=S.get(i);n instanceof x&&new K(n,"on",t).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${u.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${u.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=S.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof x&&(i.syncValue(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=S.get(a);o instanceof x&&o.syncValue()}}const n=()=>{new K(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${u.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${u.prefix}click-`,r=`${u.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__",te.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ve=te;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=S.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${u.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const d=D.registrations.get(e);d&&l.forEach(c=>{!c.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new K(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),D.registrations.delete(e))}).catch(m=>{p.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(e);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${u.prefix}intersect-`))return!1;const r=t.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${u.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(p.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${u.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${u.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let ee=D;function ft(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=S.get(e);if(!(r instanceof x)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),p.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const d=w.registrations.get(e);if(!d)return;let c=!1;l.forEach(m=>{const y=m.target;d.observedRows.has(y)&&(m.isIntersecting?d.visibleRows.has(y)||(d.visibleRows.add(y),c=!0):d.visibleRows.delete(y)&&(c=!0))}),c&&w.scheduleCompute(d)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${u.prefix}each`)&&e.hasAttribute(`${u.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${u.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${u.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof x&&!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,ft(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){p.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);P.setBindingData(i,n,a,!1,!1).catch(o=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${u.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let Q=w;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=new ve;O._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),ee.syncTree(document.body),Q.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return O._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(O.isExternallyManaged(i.target))continue;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&&P.isAliasedAttributeReflection(n,i.attributeName))break;P.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ee.syncElement(n),Q.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ee.cleanupTree(n),Q.cleanupTree(n),P.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(P.addNode(n.parentElement,n),ee.syncTree(n),Q.syncTree(n))}),i.target instanceof Element&&Q.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[],O._dispatcher=null;let ce=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ce.init):ce.init();const gt=()=>W.waitForRenders(),pt="0.26.0";return L.Core=P,L.Env=u,L.Form=A,L.Fragment=S,L.Haori=W,L.Log=p,L.Queue=M,L.default=W,L.version=pt,L.waitForRenders=gt,Object.defineProperties(L,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),L}({});
|
|
25
|
+
`)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${u.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(h.EACH_RENDERED_CHANGE_WARNED.has(r)||(h.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),h.countEachRenderedRows(e)!==0){if(!n){if(h.EACH_RENDERED_CHANGE_FIRED.has(r))return;h.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${u.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=h.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${u.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof x){if(a.hasAttribute(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const c=S.get(l);c instanceof x&&(r=c.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const d=S.get(l);d instanceof x&&e.getChildren().includes(d)&&(e.removeChild(d),d.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${u.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(p.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${u.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${u.prefix}derive`)||t?.closestByAttribute(`${u.prefix}derive-name`)||t?.closestByAttribute(`${u.prefix}if`)||t?.closestByAttribute(`${u.prefix}fetch`)||t?.closestByAttribute(`${u.prefix}import`)||h.hasNonEachDynamicElementState(e))return!1;const r=h.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}if`)||e.hasAttribute(`${u.prefix}each`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof x?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return h.recordDerivedSubtreeSignatureComputation(e,t),h.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:h.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(h.createDescendantBindingSignature(e,"refresh")),h.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!U.isEnabled()||!e.hasAttribute(`${u.prefix}derive`))return null;const t=h.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:h.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${u.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof x).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof x?!h.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${u.prefix}attr-`)||t.startsWith(u.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${u.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${u.prefix}each-key`),s=e.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];t.forEach((b,v)=>{const R=h.createListKey(b,n?String(n):null,v);o.push(R),a.set(R,{item:b,itemIndex:v})});const l=new Set(o),d=[];let c=e.getChildren().filter(b=>b instanceof x).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const m=c.map(b=>b.getListKey());c=c.filter(b=>l.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const y=c.map(b=>b.getListKey()),T=new Map;c.forEach(b=>{const v=b.getListKey();v!==null&&!T.has(v)&&T.set(v,b)});const k=e.getChildElementFragments().slice(),H=k.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((b,v)=>{const{item:R,itemIndex:C}=a.get(b);let N;const q=T.get(b);if(q)N=q,E=E.then(()=>h.updateRowFragment(N,R,i,C,s?String(s):null,b).then($=>{if($)return h.evaluateAll(N)}));else{N=r.clone();const $=H+v;E=E.then(()=>h.updateRowFragment(N,R,i,C,s?String(s):null,b).then(()=>{const X=k[$]??null;return e.insertBefore(N,X).then(()=>{k.splice($,0,N)}).then(()=>h.initializeFreshEachRow(N))}))}}),Promise.all(d).then(()=>E).then(()=>{const b=o.filter($=>$!==null),v=y.filter($=>$!==null),R=new Set(v),C=b.filter($=>!R.has($)),q=m.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,q,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=h.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${u.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${u.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>h.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${h.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{h.evaluateAll(e)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap,h.EACH_RENDERED_CHANGE_FIRED=new WeakSet,h.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let P=h;const te=class te{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=S.get(e);t&&new K(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,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))}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),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(te.BUILTIN_EVENT_NAMES.has(e)){p.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=S.get(i);n instanceof x&&new K(n,"on",t).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${u.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${u.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=S.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof x&&(i.syncValue(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=S.get(a);o instanceof x&&o.syncValue()}}const n=()=>{new K(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${u.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${u.prefix}click-`,r=`${u.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__",te.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ve=te;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=S.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${u.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const d=D.registrations.get(e);d&&l.forEach(c=>{!c.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new K(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),D.registrations.delete(e))}).catch(m=>{p.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(e);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${u.prefix}intersect-`))return!1;const r=t.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${u.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(p.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${u.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${u.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let ee=D;function ft(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=S.get(e);if(!(r instanceof x)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),p.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const d=w.registrations.get(e);if(!d)return;let c=!1;l.forEach(m=>{const y=m.target;d.observedRows.has(y)&&(m.isIntersecting?d.visibleRows.has(y)||(d.visibleRows.add(y),c=!0):d.visibleRows.delete(y)&&(c=!0))}),c&&w.scheduleCompute(d)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${u.prefix}each`)&&e.hasAttribute(`${u.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${u.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${u.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof x&&!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,ft(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){p.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);P.setBindingData(i,n,a,!1,!1).catch(o=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${u.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let Q=w;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=new ve;O._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),ee.syncTree(document.body),Q.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return O._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(O.isExternallyManaged(i.target))continue;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&&P.isAliasedAttributeReflection(n,i.attributeName))break;P.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ee.syncElement(n),Q.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ee.cleanupTree(n),Q.cleanupTree(n),P.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(P.addNode(n.parentElement,n),ee.syncTree(n),Q.syncTree(n))}),i.target instanceof Element&&Q.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[],O._dispatcher=null;let ce=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ce.init):ce.init();const gt=()=>W.waitForRenders(),pt="0.26.1";return L.Core=P,L.Env=u,L.Form=A,L.Fragment=S,L.Haori=W,L.Log=p,L.Queue=M,L.default=W,L.version=pt,L.waitForRenders=gt,Object.defineProperties(L,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),L}({});
|
|
26
26
|
//# sourceMappingURL=haori.iife.js.map
|
package/dist/index.d.ts
CHANGED