haori 0.41.0 → 0.41.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 +70 -3
- package/dist/haori.iife.js +7 -7
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
|
|
4
4
|
|
|
5
|
-
Version: 0.41.
|
|
5
|
+
Version: 0.41.1
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
package/dist/haori.cjs.js
CHANGED
|
@@ -20,10 +20,10 @@ ${R}
|
|
|
20
20
|
`)}catch(k){m.error("Haori",`Invalid after script: ${k}`)}}if(e.hasAttribute(b.attrName(t,"dialog"))&&(r.dialogMessage=b.unescapeNewlines(b.readLateAttribute(e,r,"dialog",b.attrName(t,"dialog")))),e.hasAttribute(b.attrName(t,"toast"))){r.toastMessage=b.readLateAttribute(e,r,"toast",b.attrName(t,"toast"));const R=e.getRawAttribute(b.attrName(t,"toast-level")),x=["info","warning","error","success"].includes(R);r.toastLevel=x?R:null}if(e.hasAttribute(b.attrName(t,"redirect"))){r.redirectUrl=b.readLateAttribute(e,r,"redirect",b.attrName(t,"redirect"));const R=b.attrName(t,"redirect-return-param");e.hasAttribute(R)&&(r.redirectReturnParam=b.readLateAttribute(e,r,"redirect-return-param",R))}if(e.hasAttribute(b.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(b.attrName(t,"scroll"))&&(r.scrollTarget=b.readLateAttribute(e,r,"scroll",b.attrName(t,"scroll"))),e.hasAttribute(b.attrName(t,"history"))&&(r.historyUrl=b.readLateAttribute(e,r,"history",b.attrName(t,"history"))),e.hasAttribute(b.attrName(t,"history-data"))&&(r.historyDataAttrName=b.attrName(t,"history-data")),e.hasAttribute(b.attrName(t,"history-form"))){const R=z.read(e,b.attrName(t,"history-form"));if(R){const k=z.query(R,b.attrName(t,"history-form"));k!==null?r.historyFormFragment=F.getFormFragment(N.get(k)):m.error("Haori",`Form element not found: ${R} (${b.attrName(t,"history-form")})`)}else r.historyFormFragment=F.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(R=>{const k=b.attrName(t,R);if(!e.hasAttribute(k))return;const x=z.read(e,k),q=[];if(x)z.queryAll(x,k).forEach(_=>{const Z=N.get(_);Z&&q.push(Z)}),q.length===0&&m.error("Haori",`Element not found: ${x} (${k})`);else if(R==="open"||R==="close"){const G=e.getTarget().closest("dialog");G?q.push(N.get(G)):m.error("Haori",`Ancestor <dialog> not found (${k})`)}else q.push(e);if(q.length>0)switch(R){case"reset-before":r.resetBeforeFragments=q;break;case"reset":r.resetFragments=q;break;case"refetch":r.refetchFragments=q;break;case"click":r.clickFragments=q;break;case"copy":r.copyFragments=q;break;case"open":r.openFragments=q;break;case"close":r.closeFragments=q;break}});const v=b.attrName(t,"copy-source");if(e.hasAttribute(v)){const R=z.read(e,v);if(R){const k=z.query(R,v);if(k!==null){const x=N.get(k);x?r.copySourceFragment=x:m.error("Haori",`Element is not managed by Haori: ${R} (${v})`)}else m.error("Haori",`Element not found: ${R} (${v})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(b.attrName(null,"data",!0))&&(r.dataAttrName=b.attrName(null,"data",!0)),e.hasAttribute(b.attrName(null,"form",!0)))){const E=z.read(e,b.attrName(null,"form",!0));if(E){const v=z.query(E,b.attrName(null,"form",!0));v!==null?r.formFragment=F.getFormFragment(N.get(v)):m.error("Haori",`Form element not found: ${E} (${b.attrName(null,"fetch-form",!0)})`)}else r.formFragment=F.getFormFragment(e)}const D=t?b.attrName(t,"fetch-state"):b.attrName(null,"state",!0);if(e.hasAttribute(D)){const E=z.read(e,D),v=[];E?(z.queryAll(E,D).forEach(k=>{const x=N.get(k);x&&v.push(x)}),v.length===0&&m.error("Haori",`Element not found: ${E} (${D})`)):v.push(e),v.length>0&&(r.fetchStateFragments=v)}const B=t?b.attrName(t,"store-clear"):b.attrName(null,"store-clear",!0);if(e.hasAttribute(B)){const E=e.getRawAttribute(B),v=E===null?"":E.trim();if(v==="")m.error("Haori",`ストレージキーが指定されていません (${B})`);else{r.storeClearKey=v;const R=e.getRawAttribute(`${B}-type`),k=R===null?"session":R.trim();k==="local"||k==="session"?r.storeClearKind=k:(m.warn("Haori",`${B}-type は session または local を指定してください(session として扱います): ${k}`),r.storeClearKind="session")}}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),b.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const n=i.getParent();!n||!n.hasAttribute(`${u.prefix}each`)||!n.hasAttribute(`${u.prefix}form-list`)||t.set(i,b.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${u.prefix}form-name`):!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 b(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||(!this.options.formFragment&&this.options.targetFragment&&F.warnUnvalidatedCustomValidity(F.getFormFragment(this.options.targetFragment),`${u.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition()))return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const y=this.options.runScript.call(h,this.domEvent);y===!1&&this.domEvent&&this.domEvent.preventDefault(),y!=null&&typeof y.then=="function"&&await y}catch(y){m.error("Haori",`Run script execution error: ${y}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>F.reset(h,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=T.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(a="fetchUrl"in h,o="fetchOptions"in h,n=a?h.fetchUrl:n,s=o?h.fetchOptions:s)}}const l=Object.keys(i).length>0;if(n){const h=(s?.method||"GET").toUpperCase(),A=!a&&o&&r.transportMode==="query-get"&&Pt(s)&&!Pe(h)?r.baseUrl??n:n,S=$t(A,s);n=S.url;const P={...S.options},D=S.normalized?S.requestedMethod:r.requestedMethod,B=S.effectiveMethod,E=r.transportMode==="query-get"||S.normalized,v=S.queryString??r.queryString;if(E&&m.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:D,effectiveMethod:B,transportMode:"query-get",url:n,payload:l?i:void 0,queryString:v}),this.options.targetFragment&&n){const R=performance.now(),k={runtime:u.runtime,requestedMethod:D,effectiveMethod:B,transportMode:E?"query-get":"http",...E?{queryString:v}:{}};return H.fetchStart(this.options.targetFragment.getTarget(),n,P,l?i:void 0,k),await this.injectFetchState("loading"),fetch(n,P).then(x=>this.handleFetchResult(x,n||void 0,R)).catch(async x=>{throw n&&H.fetchError(this.options.targetFragment.getTarget(),n,x),await this.injectFetchState("error",null,x instanceof Error?x.message:String(x)),x})}return fetch(n,P).then(R=>this.handleFetchResult(R,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&l){const h=this.options.formFragment,y=h.getTarget(),A=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&A.add(this.options.targetFragment);const S=h.getRawBindingData(),P=$e(i),D=h.getAttribute(`${u.prefix}form-arg`);let B;if(D){B={...S??{}};const E=String(D),v=F.resolveAncestorArgOwner(h,E);B[E]=F.mergeCollectedValues((v?v.value:B[E])??null,P)}else B=F.mergeCollectedValues(S,P);await O.setBindingData(y,B,{skipFragments:A,kind:"nonSupply",sequence:this.operationSequence,editedPaths:F.collectEditedPaths(h,D?String(D):"",P)})}this.suppressEmptyReplaceBind=!l&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const c=l?$e(i):{},d=new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(b.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Ce))return!1;const r=t.hasAttribute(`${u.prefix}click-no-disabled`);return b.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Ce,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(b.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(Ce),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=Ae();if(!e.ok)return ct(e.status)||(this.options.targetFragment&&t&&H.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&&H.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const d=this.options.afterCallback(e);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&"response"in d&&(e="response"in d?d.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(d=>F.reset(d,this.operationSequence))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(d=>{s.push(new b(d,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const d of this.options.clickFragments){await O.evaluateAll(d);const h=d.getTarget();typeof h.click=="function"?h.click():h.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(d=>{const h=d.getTarget();h instanceof HTMLElement?s.push(i.openDialog(h)):m.error("Haori","Element is not an HTML element: ",h)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(d=>{const h=d.getTarget();h instanceof HTMLElement?s.push(i.closeDialog(h)):m.error("Haori","Element is not an HTML element: ",h)}),await Promise.all(s);const a=b.unescapeNewlines(this.resolveLateAttribute("dialog",this.options.dialogMessage));a&&await i.dialog(a);const o=this.resolveLateAttribute("toast",this.options.toastMessage);o&&await i.toast(o,this.options.toastLevel??"info"),this.clearStore(),this.pushHistory();const l=this.resolveLateAttribute("scroll",this.options.scrollTarget);l&&z.query(l,b.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const c=this.resolveLateAttribute("redirect",this.options.redirectUrl);if(c){let d=c;const h=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(h){const A=new URLSearchParams(window.location.search).get(h);if(A!==null){const S=A.trim();dt.isSafeLocalPath(S)?d=S:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${A}`)}}window.location.href=d}return!0}clearStore(){const e=this.options.storeClearKey;e&&ge.clear(e,this.options.storeClearKind??"session")}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(j.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const c="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",c);return}const l=c=>{for(const[d,h]of Object.entries(c))h!=null&&(Array.isArray(h)?h.forEach(y=>o.searchParams.append(d,String(y))):typeof h=="object"?o.searchParams.set(d,JSON.stringify(h)):o.searchParams.set(d,String(h)))};n&&l(r),s&&l(i),history.pushState({[xt]:!0},"",o.toString())}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=F.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await Ae().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await Ae().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,c=[];for(const d of a)if(d&&typeof d=="object"&&!Array.isArray(d)){const h=d.key,y=d.message,A=typeof h=="string"&&h.length>0?h:null,S=typeof y=="string"?y:y!=null?String(y):"";if(S.length===0)continue;if(A!==null){const P=l.get(A)??[];P.push(S),l.set(A,P)}else c.push(S)}else typeof d=="string"&&d.length>0&&c.push(d);for(const[d,h]of l)o.push({key:d,message:h.join(`
|
|
21
21
|
`)});for(const d of c)o.push({message:d})}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,c]of Object.entries(a.errors))Array.isArray(c)?o.push({key:l,message:c.join(`
|
|
22
22
|
`)}):typeof c=="string"?o.push({key:l,message:c}):c!=null&&o.push({key:l,message:String(c)});if(o.length===0)for(const[l,c]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(c)?o.push({key:l,message:c.join(`
|
|
23
|
-
`)}):typeof c=="string"&&o.push({key:l,message:c}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await F.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 F.warnUnvalidatedCustomValidity(e,`${u.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${u.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=J.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&j.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${u.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):Ae().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=J.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(l=>{i&&typeof i=="object"&&l in i&&(o[l]=i[l])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.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=[],s=this.eventType?b.attrName(this.eventType,"bind"):b.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){const h=this.options.bindArg;a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const A=this.resolveCurrentRowItem(o,y),S={...A};if(i&&typeof i=="object"&&!Array.isArray(i)){const P=A[h],D=P!==null&&typeof P=="object"&&!Array.isArray(P)?P:{};S[h]=this.mergeAppendBindingData(o,i,D)}else S[h]=i;return this.reconcileRowUserEdits(o,S)}});return}const c={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const h=c[d],y=h&&typeof h=="object"&&!Array.isArray(h)?h:{};c[d]=this.mergeAppendBindingData(o,i,y)}else c[d]=i;n.push(O.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,c),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:h=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,h):h,A=this.mergeAppendBindingData(o,i,y),S=this.options.bindMerge?{...y,...A}:A;return this.reconcileRowUserEdits(o,S)}});return}const c=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...c}:c;n.push(O.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(l=>{H.bindComplete(l.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&O.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=F.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${u.prefix}form-arg`);if(s){const a=String(s),o=t[a],l=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:se(l,n)}}return se(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&O.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:se(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of F.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=F.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],l=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:se(l,a)}}return i}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=b.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:l=>this.applyCopyToRowItem(s,l,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(O.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=F.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:se(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?ve(this.options.copySourceFragment):{...this.options.copySourceFragment.getRawBindingData()??{}}:this.options.formFragment?ve(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getRawBindingData()??{}}:{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=F.getValues(r);Object.assign(e,i),F.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=b.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 e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,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,baseUrl: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"&&!Pe(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&me(t)){const d=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Lt(t)&&m.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.`):m.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=ft(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const h=new FormData;for(const[y,A]of Object.entries(t))A==null?h.append(y,""):A instanceof Blob?h.append(y,A):Array.isArray(A)?A.forEach(S=>{S instanceof Blob?h.append(y,S):h.append(y,ue(S))}):h.append(y,ue(A));n.body=h}else if(/application\/x-www-form-urlencoded/i.test(d)){const h=new URLSearchParams;for(const[y,A]of Object.entries(t))A!==void 0&&(Array.isArray(A)?A.forEach(S=>h.append(y,ue(S))):h.append(y,ue(A)));n.body=h}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let c;return o&&(c=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:c,transportMode:o?"query-get":"http",signature:Ot(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?ve(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return ve(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=b.attrName(this.eventType,e),i=z.read(t,r);if(i!==null&&i.trim()!==""){const s=z.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=N.get(s);return a instanceof T?a.hasAttribute(`${u.prefix}each`)?a:(m.error("Haori",`Row container must have ${u.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e){const t=e.getRawAttribute(`${u.prefix}each`);if(t===null)return m.error("Haori",`Row container has no ${u.prefix}each expression.`),null;const r=t.trim().split(".");if(!(r.length>0&&r.every(o=>/^[A-Za-z_$][\w$]*$/.test(o))))return m.error("Haori",`Row operations require a plain identifier path for ${u.prefix}each (got: ${t}).`),null;let n=e,s=null;for(;n;){const o=n.getRawBindingData();if(o&&r[0]in o){s=o;break}n=n.getParent()}if(!n||!s)return m.error("Haori",`Binding data owner not found for ${u.prefix}each="${t}".`),null;let a=s;for(const o of r){if(a===null||typeof a!="object"||Array.isArray(a)){a=void 0;break}a=a[o]}return Array.isArray(a)?{owner:n,ownerData:s,array:a,path:r}:(m.error("Haori",`${u.prefix}each="${t}" does not resolve to an array.`),null)}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],l={...n[a]};n[a]=l,n=l}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${u.prefix}each container (${t}).`),{kind:"skip"}):b.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${u.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=b.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const c of i){const d=b.resolveRowArrayIndex(c,a);if(d===null)continue;const h=a[d];if(h===null||typeof h!="object"||Array.isArray(h)){m.warn("Haori",`Row data is not an object; the write was skipped (${c.attributeName}).`);continue}const y=c.apply(h);if(b.isSameRowItem(h,y)){c.syncWhenUnchanged&&r.push(b.syncUnchangedRowValues(c.row,y,c.syncWhenUnchanged));continue}a[d]=y,o=!0}if(!o)return;const l=O.setBindingData(s.owner.getTarget(),b.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(O.isEachUpdateRunning(n)){l.catch(c=>{m.error("Haori","Failed to write row data.",c)});return}r.push(l)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&O.clearUserEditMarks(e),F.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){const r=b.getRowFragments(e.container),i=r.indexOf(e.row);if(i===-1)return m.warn("Haori",`The target row is no longer in the ${u.prefix}each container; the write was skipped (${e.attributeName}).`),null;const n=e.container.getAttribute(`${u.prefix}each-key`),s=e.row.getListKey();if(n&&s!==null){const a=[];t.forEach((c,d)=>{O.createListKey(c,String(n),d)===s&&a.push(d)});const o=r.slice(0,i).filter(c=>c.getListKey()===s).length,l=a[o]??-1;return l===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${s}"); the write was skipped (${e.attributeName}).`),null):l}return i>=t.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${e.attributeName}).`),null):i}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(b.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t)=>{if(t<=0||t>=e.length)return!1;const[r]=e.splice(t,1);return e.splice(t-1,0,r),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t)=>{if(t<0||t>=e.length-1)return!1;const[r]=e.splice(t,1);return e.splice(t+1,0,r),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=b.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${u.prefix}row`):null,a=b.getRowFragments(r),o=s?a.indexOf(s):a.length-1,l=i.array.slice();return t(l,o)?O.setBindingData(i.owner.getTarget(),b.withPathValue(i.ownerData,i.path,l),{kind:"nonSupply",sequence:this.operationSequence}):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 O.setBindingData(a,o,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};b.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,b.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,b.RUNNING_CLICK_TARGETS=new WeakSet;let te=b;class Ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ct(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=N.get(e);return r instanceof T?r.hasAttribute(`${u.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof T?t.push(f.evaluateAll(r)):r instanceof Q&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=T.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof T&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.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}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${u.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(f.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof T&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=f.getReactiveFetchState(t),i=te.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 te(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.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`,""),H.importStart(t,n),Ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return V.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${u.prefix}importing`),H.importEnd(t,n,o,s),f.adoptImportedChildren(e);const l=[];return e.getChildren().forEach(c=>{c instanceof T?l.push(f.scan(c.getTarget())):c instanceof Q&&l.push(f.evaluateText(c))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),H.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=N.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){const t=N.get(e);return t?f.initializeElementFragment(t,!1).then(()=>F.restoreInitialValues(e)).then(()=>{ee.applySubtree(e)}):Promise.resolve()}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),ee.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof T?r.push(f.initializeElementFragment(i,t)):i instanceof Q&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.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 f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>f.setAttribute(e.getTarget(),i,n)))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>F.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=N.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let l=null,c=null,d=null;switch(t){case`${u.prefix}bind`:{if(r!==null&&i&&s instanceof T&&s.consumeSelfWrittenBind(r))break;const h=r===null?{}:f.parseDataBind(r);if(i){const y=n??T.nextSequence();return r===null?(o.push(f.setBindingData(e,h,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,h,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(h);break}case`${u.prefix}derive`:c=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${u.prefix}derive-name`)),l=f.evaluateDerive(s,r,s.getRawAttribute(`${u.prefix}derive-name`)),o.push(l.then(()=>{}));break;case`${u.prefix}derive-name`:c=f.createDeriveInputSignature(s,s.getRawAttribute(`${u.prefix}derive`),r),l=f.evaluateDerive(s,s.getRawAttribute(`${u.prefix}derive`),r),o.push(l.then(()=>{}));break;case`${u.prefix}if`:o.push(f.evaluateIf(s));break;case`${u.prefix}each`:o.push(f.evaluateEach(s));break;case`${u.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${u.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${u.prefix}store`:r!==null&&o.push(ge.restore(s));break;case`${u.prefix}validity`:case`${u.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${u.prefix}url-param`:{const h=s.getAttribute(`${u.prefix}url-arg`),y=dt.readParams();h===null&&s.hasAttribute(`${u.prefix}store`)&&m.warn("Haori",`${u.prefix}url-param を ${u.prefix}url-arg なしで ${u.prefix}store と併用すると復元した値が消えます(${u.prefix}url-arg を指定してください)。`);const A={reentrant:!0,kind:"nonSupply",sequence:T.nextSequence()};if(h===null)o.push(f.setBindingData(e,y,A));else{const S=s.getRawBindingData()||{};S[String(h)]=y,o.push(f.setBindingData(e,S,A))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(l!==null)return s.setDeriveInputSignature(c),l.then(h=>{if(h)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=N.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",l=r.sequence??T.nextOperationSequence(),c={sequence:l,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(l);const h=T.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,l);const A=a?f.resolveByPathAuthority(i,y,t,c):t;i.setBindingData(A),a&&(H.bindChange(e,y,A,"manual"),ge.mirror(i));const S=()=>{i.markBindingWorkStart();const P=i.getRawBindingData()??A;let D=a?i.setAttribute(`${u.prefix}bind`,JSON.stringify(P)):Promise.resolve();return e.tagName==="FORM"&&(D=D.then(()=>{if(i.wasResetAfter(h))return;const B=i.getRawBindingData()??A;return F.syncValues(i,F.resolveSyncValues(i,B),!1,c)})),D=D.then(()=>F.syncAncestorArgForms(i,h,c)),D=D.then(()=>f.evaluateAll(i,n)),D=D.then(()=>T.retryUnappliedValueWrites(e,h)),D=D.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),D.then(()=>i.markBindingWorkEnd(),B=>{throw i.markBindingWorkEnd(),B})};return s?S():i.enqueueBindingWork(S)}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const l=t,c=r,d={};let h=Object.keys(l).some(A=>!Object.prototype.hasOwnProperty.call(c,A));const y=new Set([...Object.keys(l),...Object.keys(c)]);for(const A of y){const S=n===""?A:`${n}.${A}`,P=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(l,A)?l[A]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(c,A)?c[A]:f.ABSENT_PATH,i,S);P!==f.ABSENT_PATH&&(d[A]=P),P!==(Object.prototype.hasOwnProperty.call(c,A)?c[A]:f.ABSENT_PATH)&&(h=!0)}return h?d:c}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const l=t,c=r,d=c.map((h,y)=>f.mergePathAuthority(e,l[y],h,i,`${n}[${s[y]}]`));return d.some((h,y)=>h!==c[y])?d:c}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.has(n)?"edit":i.kind,o={sequence:i.sequence,kind:a};return e.canApplyPath(n,o)?(e.markPathApplied(n,o),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,l)=>f.createListKey(o,n,l)),a=r.map((o,l)=>f.createListKey(o,n,l));return s.some((o,l)=>o!==a[l])?null:a}static resolveEachKeyArg(e,t){const r=`${u.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const l=a.getAttribute(`${r}-key`);return l===null?null:l.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${u.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=N.get(e);return r instanceof T?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=N.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const c=l.getTarget(),d=f.resolveElementId(c);return d!==""?`#${d}`:c.tagName.toLowerCase()},s=(l,c,d,h)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(c),kind:d,depth:h})};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 j.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=N.get(e);if(r.isSkipMutationNodes())return;const i=N.get(t.nextSibling),n=N.get(t);if(n){if(n.getParent()===r)return;r.insertBefore(n,i),n instanceof T?f.scan(n.getTarget()):n instanceof Q&&f.evaluateText(n)}}static removeNode(e){const t=N.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=N.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=N.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`),o=n.getRawBindingData();let l;if(a){l={...o??{}};const c=String(a),d=F.resolveAncestorArgOwner(n,c);l[c]=F.mergeCollectedValues((d?d.value:l[c])??null,s)}else l=F.mergeCollectedValues(o,s);i.push(f.setBindingData(n.getTarget(),l,{kind:"nonSupply",sequence:T.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.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,c=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const h=f.createDeriveInputSignature(e,a,o);h===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==h&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(h)})))}return n&&(r=r.then(()=>f.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),c=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const h=[];return e.getChildren().forEach(y=>{if(y instanceof T){if(f.canSkipUnchangedNestedEach(y))return;h.push(f.evaluateAll(y,t))}else y instanceof Q&&h.push(f.evaluateText(y))}),Promise.all(h).then(()=>{})}).then(()=>{c&&d!==null&&e.setDeriveSubtreeSignature(d)}))}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=J.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 f.createBindingSignature(i)===f.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;if(J.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(f.isHiddenIfCondition(r))j.isEnabled()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{H.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof T?n.push(s.isMounted()?f.evaluateAll(s):f.scan(s.getTarget())):s instanceof Q&&n.push(f.evaluateText(s))}),t.push(e.show().then(()=>{H.show(e.getTarget()),i||(f.triggerLoadOnShow(e),ee.refreshSubtree(e.getTarget()))})),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 te(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(j.isEnabled()&&J.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),!e.isVisible()||!e.isMounted())return Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${u.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),ee.refreshSubtree(i),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.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 (
|
|
23
|
+
`)}):typeof c=="string"&&o.push({key:l,message:c}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await F.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 F.warnUnvalidatedCustomValidity(e,`${u.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return b.isRectFullyVisible(t.getBoundingClientRect())?(r.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1):(t.focus({preventScroll:!0}),t.scrollIntoView({behavior:"smooth",block:"nearest"}),b.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++b.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==b.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=b.VALIDATION_SCROLL_STABLE_FRAMES&&b.isRectPartlyVisible(a)||performance.now()-r>=b.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top<r&&e.bottom>0&&e.left<t&&e.right>0}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${u.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=J.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&j.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${u.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):Ae().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=J.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(l=>{i&&typeof i=="object"&&l in i&&(o[l]=i[l])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.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=[],s=this.eventType?b.attrName(this.eventType,"bind"):b.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){const h=this.options.bindArg;a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const A=this.resolveCurrentRowItem(o,y),S={...A};if(i&&typeof i=="object"&&!Array.isArray(i)){const P=A[h],D=P!==null&&typeof P=="object"&&!Array.isArray(P)?P:{};S[h]=this.mergeAppendBindingData(o,i,D)}else S[h]=i;return this.reconcileRowUserEdits(o,S)}});return}const c={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const h=c[d],y=h&&typeof h=="object"&&!Array.isArray(h)?h:{};c[d]=this.mergeAppendBindingData(o,i,y)}else c[d]=i;n.push(O.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,c),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:h=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,h):h,A=this.mergeAppendBindingData(o,i,y),S=this.options.bindMerge?{...y,...A}:A;return this.reconcileRowUserEdits(o,S)}});return}const c=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...c}:c;n.push(O.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(l=>{H.bindComplete(l.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&O.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=F.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${u.prefix}form-arg`);if(s){const a=String(s),o=t[a],l=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:se(l,n)}}return se(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&O.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:se(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of F.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=F.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],l=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:se(l,a)}}return i}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=b.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:l=>this.applyCopyToRowItem(s,l,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(O.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=F.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:se(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?ve(this.options.copySourceFragment):{...this.options.copySourceFragment.getRawBindingData()??{}}:this.options.formFragment?ve(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getRawBindingData()??{}}:{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=F.getValues(r);Object.assign(e,i),F.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=b.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 e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,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,baseUrl: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"&&!Pe(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&me(t)){const d=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Lt(t)&&m.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.`):m.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=ft(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const h=new FormData;for(const[y,A]of Object.entries(t))A==null?h.append(y,""):A instanceof Blob?h.append(y,A):Array.isArray(A)?A.forEach(S=>{S instanceof Blob?h.append(y,S):h.append(y,ue(S))}):h.append(y,ue(A));n.body=h}else if(/application\/x-www-form-urlencoded/i.test(d)){const h=new URLSearchParams;for(const[y,A]of Object.entries(t))A!==void 0&&(Array.isArray(A)?A.forEach(S=>h.append(y,ue(S))):h.append(y,ue(A)));n.body=h}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let c;return o&&(c=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:c,transportMode:o?"query-get":"http",signature:Ot(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?ve(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return ve(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=b.attrName(this.eventType,e),i=z.read(t,r);if(i!==null&&i.trim()!==""){const s=z.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=N.get(s);return a instanceof T?a.hasAttribute(`${u.prefix}each`)?a:(m.error("Haori",`Row container must have ${u.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e){const t=e.getRawAttribute(`${u.prefix}each`);if(t===null)return m.error("Haori",`Row container has no ${u.prefix}each expression.`),null;const r=t.trim().split(".");if(!(r.length>0&&r.every(o=>/^[A-Za-z_$][\w$]*$/.test(o))))return m.error("Haori",`Row operations require a plain identifier path for ${u.prefix}each (got: ${t}).`),null;let n=e,s=null;for(;n;){const o=n.getRawBindingData();if(o&&r[0]in o){s=o;break}n=n.getParent()}if(!n||!s)return m.error("Haori",`Binding data owner not found for ${u.prefix}each="${t}".`),null;let a=s;for(const o of r){if(a===null||typeof a!="object"||Array.isArray(a)){a=void 0;break}a=a[o]}return Array.isArray(a)?{owner:n,ownerData:s,array:a,path:r}:(m.error("Haori",`${u.prefix}each="${t}" does not resolve to an array.`),null)}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],l={...n[a]};n[a]=l,n=l}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${u.prefix}each container (${t}).`),{kind:"skip"}):b.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${u.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=b.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const c of i){const d=b.resolveRowArrayIndex(c,a);if(d===null)continue;const h=a[d];if(h===null||typeof h!="object"||Array.isArray(h)){m.warn("Haori",`Row data is not an object; the write was skipped (${c.attributeName}).`);continue}const y=c.apply(h);if(b.isSameRowItem(h,y)){c.syncWhenUnchanged&&r.push(b.syncUnchangedRowValues(c.row,y,c.syncWhenUnchanged));continue}a[d]=y,o=!0}if(!o)return;const l=O.setBindingData(s.owner.getTarget(),b.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(O.isEachUpdateRunning(n)){l.catch(c=>{m.error("Haori","Failed to write row data.",c)});return}r.push(l)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&O.clearUserEditMarks(e),F.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){const r=b.getRowFragments(e.container),i=r.indexOf(e.row);if(i===-1)return m.warn("Haori",`The target row is no longer in the ${u.prefix}each container; the write was skipped (${e.attributeName}).`),null;const n=e.container.getAttribute(`${u.prefix}each-key`),s=e.row.getListKey();if(n&&s!==null){const a=[];t.forEach((c,d)=>{O.createListKey(c,String(n),d)===s&&a.push(d)});const o=r.slice(0,i).filter(c=>c.getListKey()===s).length,l=a[o]??-1;return l===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${s}"); the write was skipped (${e.attributeName}).`),null):l}return i>=t.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${e.attributeName}).`),null):i}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(b.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t)=>{if(t<=0||t>=e.length)return!1;const[r]=e.splice(t,1);return e.splice(t-1,0,r),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t)=>{if(t<0||t>=e.length-1)return!1;const[r]=e.splice(t,1);return e.splice(t+1,0,r),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=b.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${u.prefix}row`):null,a=b.getRowFragments(r),o=s?a.indexOf(s):a.length-1,l=i.array.slice();return t(l,o)?O.setBindingData(i.owner.getTarget(),b.withPathValue(i.ownerData,i.path,l),{kind:"nonSupply",sequence:this.operationSequence}):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 O.setBindingData(a,o,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};b.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,b.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,b.RUNNING_CLICK_TARGETS=new WeakSet,b.validationReportGeneration=0,b.VALIDATION_SCROLL_TIMEOUT_MS=1e3,b.VALIDATION_SCROLL_STABLE_FRAMES=2;let te=b;class Ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ct(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=N.get(e);return r instanceof T?r.hasAttribute(`${u.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof T?t.push(f.evaluateAll(r)):r instanceof Q&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=T.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof T&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.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}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${u.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(f.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof T&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=f.getReactiveFetchState(t),i=te.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 te(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.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`,""),H.importStart(t,n),Ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return V.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${u.prefix}importing`),H.importEnd(t,n,o,s),f.adoptImportedChildren(e);const l=[];return e.getChildren().forEach(c=>{c instanceof T?l.push(f.scan(c.getTarget())):c instanceof Q&&l.push(f.evaluateText(c))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),H.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=N.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){const t=N.get(e);return t?f.initializeElementFragment(t,!1).then(()=>F.restoreInitialValues(e)).then(()=>{ee.applySubtree(e)}):Promise.resolve()}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),ee.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof T?r.push(f.initializeElementFragment(i,t)):i instanceof Q&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.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 f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>f.setAttribute(e.getTarget(),i,n)))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>F.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=N.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let l=null,c=null,d=null;switch(t){case`${u.prefix}bind`:{if(r!==null&&i&&s instanceof T&&s.consumeSelfWrittenBind(r))break;const h=r===null?{}:f.parseDataBind(r);if(i){const y=n??T.nextSequence();return r===null?(o.push(f.setBindingData(e,h,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,h,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(h);break}case`${u.prefix}derive`:c=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${u.prefix}derive-name`)),l=f.evaluateDerive(s,r,s.getRawAttribute(`${u.prefix}derive-name`)),o.push(l.then(()=>{}));break;case`${u.prefix}derive-name`:c=f.createDeriveInputSignature(s,s.getRawAttribute(`${u.prefix}derive`),r),l=f.evaluateDerive(s,s.getRawAttribute(`${u.prefix}derive`),r),o.push(l.then(()=>{}));break;case`${u.prefix}if`:o.push(f.evaluateIf(s));break;case`${u.prefix}each`:o.push(f.evaluateEach(s));break;case`${u.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${u.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${u.prefix}store`:r!==null&&o.push(ge.restore(s));break;case`${u.prefix}validity`:case`${u.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${u.prefix}url-param`:{const h=s.getAttribute(`${u.prefix}url-arg`),y=dt.readParams();h===null&&s.hasAttribute(`${u.prefix}store`)&&m.warn("Haori",`${u.prefix}url-param を ${u.prefix}url-arg なしで ${u.prefix}store と併用すると復元した値が消えます(${u.prefix}url-arg を指定してください)。`);const A={reentrant:!0,kind:"nonSupply",sequence:T.nextSequence()};if(h===null)o.push(f.setBindingData(e,y,A));else{const S=s.getRawBindingData()||{};S[String(h)]=y,o.push(f.setBindingData(e,S,A))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(l!==null)return s.setDeriveInputSignature(c),l.then(h=>{if(h)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=N.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",l=r.sequence??T.nextOperationSequence(),c={sequence:l,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(l);const h=T.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,l);const A=a?f.resolveByPathAuthority(i,y,t,c):t;i.setBindingData(A),a&&(H.bindChange(e,y,A,"manual"),ge.mirror(i));const S=()=>{i.markBindingWorkStart();const P=i.getRawBindingData()??A;let D=a?i.setAttribute(`${u.prefix}bind`,JSON.stringify(P)):Promise.resolve();return e.tagName==="FORM"&&(D=D.then(()=>{if(i.wasResetAfter(h))return;const B=i.getRawBindingData()??A;return F.syncValues(i,F.resolveSyncValues(i,B),!1,c)})),D=D.then(()=>F.syncAncestorArgForms(i,h,c)),D=D.then(()=>f.evaluateAll(i,n)),D=D.then(()=>T.retryUnappliedValueWrites(e,h)),D=D.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),D.then(()=>i.markBindingWorkEnd(),B=>{throw i.markBindingWorkEnd(),B})};return s?S():i.enqueueBindingWork(S)}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const l=t,c=r,d={};let h=Object.keys(l).some(A=>!Object.prototype.hasOwnProperty.call(c,A));const y=new Set([...Object.keys(l),...Object.keys(c)]);for(const A of y){const S=n===""?A:`${n}.${A}`,P=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(l,A)?l[A]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(c,A)?c[A]:f.ABSENT_PATH,i,S);P!==f.ABSENT_PATH&&(d[A]=P),P!==(Object.prototype.hasOwnProperty.call(c,A)?c[A]:f.ABSENT_PATH)&&(h=!0)}return h?d:c}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const l=t,c=r,d=c.map((h,y)=>f.mergePathAuthority(e,l[y],h,i,`${n}[${s[y]}]`));return d.some((h,y)=>h!==c[y])?d:c}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.has(n)?"edit":i.kind,o={sequence:i.sequence,kind:a};return e.canApplyPath(n,o)?(e.markPathApplied(n,o),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,l)=>f.createListKey(o,n,l)),a=r.map((o,l)=>f.createListKey(o,n,l));return s.some((o,l)=>o!==a[l])?null:a}static resolveEachKeyArg(e,t){const r=`${u.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const l=a.getAttribute(`${r}-key`);return l===null?null:l.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${u.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=N.get(e);return r instanceof T?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=N.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const c=l.getTarget(),d=f.resolveElementId(c);return d!==""?`#${d}`:c.tagName.toLowerCase()},s=(l,c,d,h)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(c),kind:d,depth:h})};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 j.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=N.get(e);if(r.isSkipMutationNodes())return;const i=N.get(t.nextSibling),n=N.get(t);if(n){if(n.getParent()===r)return;r.insertBefore(n,i),n instanceof T?f.scan(n.getTarget()):n instanceof Q&&f.evaluateText(n)}}static removeNode(e){const t=N.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=N.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=N.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`),o=n.getRawBindingData();let l;if(a){l={...o??{}};const c=String(a),d=F.resolveAncestorArgOwner(n,c);l[c]=F.mergeCollectedValues((d?d.value:l[c])??null,s)}else l=F.mergeCollectedValues(o,s);i.push(f.setBindingData(n.getTarget(),l,{kind:"nonSupply",sequence:T.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.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,c=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const h=f.createDeriveInputSignature(e,a,o);h===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==h&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(h)})))}return n&&(r=r.then(()=>f.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),c=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const h=[];return e.getChildren().forEach(y=>{if(y instanceof T){if(f.canSkipUnchangedNestedEach(y))return;h.push(f.evaluateAll(y,t))}else y instanceof Q&&h.push(f.evaluateText(y))}),Promise.all(h).then(()=>{})}).then(()=>{c&&d!==null&&e.setDeriveSubtreeSignature(d)}))}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=J.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 f.createBindingSignature(i)===f.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;if(J.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(f.isHiddenIfCondition(r))j.isEnabled()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{H.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof T?n.push(s.isMounted()?f.evaluateAll(s):f.scan(s.getTarget())):s instanceof Q&&n.push(f.evaluateText(s))}),t.push(e.show().then(()=>{H.show(e.getTarget()),i||(f.triggerLoadOnShow(e),ee.refreshSubtree(e.getTarget()))})),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 te(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(j.isEnabled()&&J.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),!e.isVisible()||!e.isMounted())return Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${u.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),ee.refreshSubtree(i),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.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 (
|
|
24
24
|
${r}
|
|
25
25
|
);`)}catch{try{i=new Function(`"use strict";
|
|
26
26
|
${r}
|
|
27
27
|
`)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.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"&&(f.EACH_RENDERED_CHANGE_WARNED.has(r)||(f.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),f.countEachRenderedRows(e)!==0){if(!n){if(f.EACH_RENDERED_CHANGE_FIRED.has(r))return;f.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){m.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=f.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=f.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof T){if(a.hasAttribute(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),f.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 d=N.get(l);d instanceof T&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const c=N.get(l);c instanceof T&&e.getChildren().includes(c)&&(e.removeChild(c),c.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?f.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(f.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${u.prefix}each-before`)&&!r.hasAttribute(`${u.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>f.evaluateAll(r))).then(()=>{})}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:(m.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`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${u.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${u.prefix}each-index`);s&&n.add(String(s));const a=f.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!f.areExpressionsRowLocal(f.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(u.prefix))continue;const a=i.slice(u.prefix.length);if(f.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!f.areExpressionsRowLocal([s],t))return!1;continue}if(!f.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))return!1}let r=t;if(e.hasAttribute(`${u.prefix}each`)){const i=e.getRawAttribute(`${u.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${u.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof T){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof Q){const n=i.getRawText();if(n.includes("{{")&&!f.areExpressionsRowLocal(f.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=J.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}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:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof T?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!0:f.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return f.recordDerivedSubtreeSignatureComputation(e,t),f.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:f.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(f.createDescendantBindingSignature(e,"refresh")),f.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!j.isEnabled()||!e.hasAttribute(`${u.prefix}derive`))return null;const t=f.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:f.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return f.DERIVE_SUBTREE_PROFILES.set(e,r),r}static resolveElementId(e){return e.getAttribute("id")??""}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();const s=f.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${u.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${u.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(c=>c instanceof T).findIndex(c=>c===r);n+=`:nth-child(${l+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${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 Q&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof T?!f.markFreshInitializationSkippable(n):n instanceof Q?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 m.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=t.map((E,v)=>f.createListKey(E,n?String(n):null,v)),o=new Set(a),l=new Map;a.forEach(E=>{l.set(E,(l.get(E)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const c=[];let d=e.getChildren().filter(E=>E instanceof T).filter(E=>!E.hasAttribute(`${u.prefix}each-before`)&&!E.hasAttribute(`${u.prefix}each-after`));const h=d.map(E=>E.getListKey()),y=new Set;d=d.filter((E,v)=>{const R=String(E.getListKey()),k=l.get(R)??0;if(k===0){y.add(E);const x=E.getListKey();return x!==null&&H.rowRemove(E.getTarget(),x,v),c.push(E.remove()),!1}return l.set(R,k-1),!0});const A=d.map(E=>E.getListKey()),S=new Map;d.forEach(E=>{const v=E.getListKey();if(v===null)return;const R=S.get(v);R?R.push(E):S.set(v,[E])});const P=e.getChildElementFragments().filter(E=>!y.has(E)),D=P.filter(E=>E.hasAttribute(`${u.prefix}each-before`)).length;let B=Promise.resolve();return a.forEach((E,v)=>{const R=t[v],k=v;let x;const q=S.get(E)?.shift();if(q){x=q;const G=D+v;B=B.then(()=>f.updateRowFragment(x,R,i,k,s?String(s):null,E).then(_=>f.repositionEachRow(e,x,P,G).then(Z=>{if(Z!==null&&H.rowMove(x.getTarget(),E,Z-D,v),!!_)return f.clearUserEditMarks(x),f.evaluateAll(x).then(()=>f.applyRowFormValues(e,x,R))})))}else{x=r.clone();const G=D+v;B=B.then(()=>f.updateRowFragment(x,R,i,k,s?String(s):null,E).then(()=>{const _=P[G]??null;return e.insertBefore(x,_).then(()=>{P.splice(G,0,x)}).then(()=>f.initializeFreshEachRow(x)).then(()=>f.applyRowFormValues(e,x,R)).then(()=>{H.rowAdd(x.getTarget(),E,k,R)})}))}}),Promise.all(c).then(()=>B).then(()=>{const E=a.filter(G=>G!==null),v=A.filter(G=>G!==null),R=new Set(v),k=E.filter(G=>!R.has(G)),q=h.filter(G=>G!==null).filter(G=>!o.has(G));H.eachUpdate(e.getTarget(),k,q,E)})}static warnDuplicateEachKey(e){!j.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${u.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve(null);r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s).then(()=>n)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${u.prefix}form-list`)||!F.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():F.syncRowValues(t,r)}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;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return m.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=f.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()&&f.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=>f.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)}:${f.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{f.evaluateAll(e)},100)}};f.ATTRIBUTE_ALIAS_SUFFIX="attr-",f.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],f.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],f.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,f.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),f.ROW_LOCAL_STATIC_ATTRIBUTES=new Set(["each-arg","each-key","each-index","each-before","each-after","derive-name","row","form","form-arg","form-list","form-object","form-detach","store","store-params","store-arg","store-type","enhance","enhance-new"]),f.REACTIVE_FETCH_STATES=new WeakMap,f.REACTIVE_IMPORT_STATES=new WeakMap,f.DERIVE_SUBTREE_PROFILES=new WeakMap,f.EACH_UPDATE_STATES=new WeakMap,f.EACH_RENDERED_CHANGE_FIRED=new WeakSet,f.EACH_RENDERED_CHANGE_WARNED=new WeakSet,f.WARNED_DUPLICATE_EACH_KEYS=new Set,f.ABSENT_PATH=Symbol("absent");let O=f;const he=class he{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[he.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=N.get(e);t&&new te(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){m.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(he.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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=N.get(i);n instanceof T&&new te(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){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=N.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof T&&(i.syncValue(),i.markUserEdit(),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=N.get(a);o instanceof T&&(o.syncValue(),o.markUserEdit())}}const n=()=>{new te(i,t,r).run().catch(s=>{m.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}};he.HISTORY_STATE_KEY="__haoriHistoryState__",he.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Be=he;const U=class U{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)&&(U.isHtmlElement(e)&&U.syncElement(e),e.querySelectorAll("*").forEach(t=>{U.syncElement(t)}))}static syncElement(e){const t=U.registrations.get(e),r=N.get(e);if(!r||!U.shouldObserve(r)){t&&(t.observer.disconnect(),U.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=U.resolveRoot(r),n=U.resolveRootMargin(r),s=U.resolveThreshold(r),a=r.hasAttribute(`${u.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&U.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),U.registrations.delete(e));const o=new IntersectionObserver(l=>{const c=U.registrations.get(e);c&&l.forEach(d=>{!d.isIntersecting||c.running||U.isDisabled(c.fragment)||(c.running=!0,new te(c.fragment,"intersect").runWithResult().then(h=>{h&&c.once&&(c.observer.disconnect(),U.registrations.delete(e))}).catch(h=>{m.error("[Haori]","Intersect procedure execution error:",h)}).finally(()=>{const h=U.registrations.get(e);h&&(h.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),U.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(U.isHtmlElement(e)){const t=U.registrations.get(e);t&&(t.observer.disconnect(),U.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=U.registrations.get(t);r&&(r.observer.disconnect(),U.registrations.delete(t))})}static disconnectAll(){U.registrations.forEach(e=>{e.observer.disconnect()}),U.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!U.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=z.query(r,t,document);return U.isHtmlElement(i)?i:(m.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}};U.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),U.registrations=new Map;let ce=U;const w=class w{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);if(!t&&!w.hasPollAttribute(e))return;const r=N.get(e);if(!(r instanceof T)||!w.shouldObserve(r)){t&&w.teardown(e,t);return}const i=w.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}w.teardown(e,t)}w.startPolling(e,r,i)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&w.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&w.teardown(t,r)})}static disconnectAll(){w.registrations.forEach(e=>{w.clearTimers(e)}),w.registrations.clear(),w.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",w.visibilityListener),w.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${u.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${u.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!w.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${u.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
|
|
28
|
-
`)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:w.resolveInterval(t),timeoutMs:w.resolveTimeout(t),errorLimit:w.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};w.registrations.set(e,i),w.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{w.handleTimeout(e)},i.timeoutMs)),w.injectState(i),w.tick(e)}static async tick(e){const t=w.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await w.stop(e,t,"detached");return}const r=w.isHidden(e)||w.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await w.injectState(t)),r){w.schedule(e,t);return}if(w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new te(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(w.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await w.stop(e,t,"error");return}if(await w.restoreStateIfCleared(t),i&&w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}w.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{w.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=w.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&H.pollTimeout(e,t.count,w.elapsed(t)),await w.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,w.clearTimers(t),r==="detached"){w.registrations.delete(e);return}await w.injectState(t),e.isConnected&&H.pollStop(e,r,t.count,w.elapsed(t))}}static teardown(e,t){w.clearTimers(t),w.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(w.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(w.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),w.tick(t))})};w.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=w.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:w.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return O.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:T.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){w.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await w.injectState(e)}static resolveStateFragments(e){const t=`${u.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=z.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof T&&s.push(o)}),s}static resolveInterval(e){const t=`${u.prefix}poll-interval`;if(!e.hasAttribute(t))return w.DEFAULT_INTERVAL_MS;const r=w.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${w.DEFAULT_INTERVAL_MS}ms を使用します。`),w.DEFAULT_INTERVAL_MS):r<w.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${w.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),w.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${u.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${u.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${u.prefix}if-false]`)!==null}static isDisabled(e){const t=`${u.prefix}poll-disabled`;return e.hasAttribute(t)?w.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${u.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):w.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};w.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),w.DEFAULT_INTERVAL_MS=5e3,w.MIN_INTERVAL_MS=100,w.registrations=new Map,w.visibilityListener=null;let de=w;const pt="0.41.0";function Ut(g){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>g()):Promise.resolve().then(g)}const L=class L{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)&&(L.isHtmlElement(e)&&L.syncElement(e),e.querySelectorAll("*").forEach(t=>{L.syncElement(t)}))}static syncElement(e){const t=L.registrations.get(e),r=N.get(e);if(!(r instanceof T)||!L.shouldObserve(r)){t&&(t.observer.disconnect(),L.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=L.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),L.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=L.resolveRoot(r),s=L.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const c=L.registrations.get(e);if(!c)return;let d=!1;l.forEach(h=>{const y=h.target;c.observedRows.has(y)&&(h.isIntersecting?c.visibleRows.has(y)||(c.visibleRows.add(y),d=!0):c.visibleRows.delete(y)&&(d=!0))}),d&&L.scheduleCompute(c)},{root:n,rootMargin:s,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};L.registrations.set(e,o),L.refreshRows(o)}static cleanupTree(e){if(L.isHtmlElement(e)){const t=L.registrations.get(e);t&&(t.observer.disconnect(),L.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=L.registrations.get(t);r&&(r.observer.disconnect(),L.registrations.delete(t))})}static disconnectAll(){L.registrations.forEach(e=>{e.observer.disconnect()}),L.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=z.query(r,t,document);return L.isHtmlElement(i)?i:(m.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===""?L.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof T&&!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=L.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));L.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Ut(()=>{e.scheduled=!1;const t=e.fragment.getTarget();L.registrations.get(t)===e&&L.computeAndPublish(e)}))}static computeAndPublish(e){const t=L.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,L.publish(e,n))}static publish(e,t){const r=L.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);O.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:T.nextSequence()}).catch(o=>{m.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}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let ae=L;const K=class K{static disconnectMutationObservers(){K._mutationObservers.forEach(e=>{e.disconnect()}),K._mutationObservers.length=0}static async init(){if(K._initialized)return;K._initialized=!0,K.disconnectMutationObservers(),T.setPendingMutationFlusher(()=>{K.flushPendingMutations()});const e=new Be;K._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([O.scan(document.head),O.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await V.wait(),document.body.setAttribute("data-haori-ready",""),K.observe(document.head),K.observe(document.body),ce.syncTree(document.body),de.syncTree(document.body),ae.syncTree(document.body)}finally{e.release()}H.ready(pt)}static getDispatcher(){return K._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{K.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),K._mutationObservers.push(t)}static flushPendingMutations(){for(const e of K._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(K.isBindAttributeRecord),i=t.filter(n=>!K.isBindAttributeRecord(n));r.length>0&&K.processMutations(r,T.nextSequence()),i.length>0&&Promise.resolve().then(()=>{K.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${u.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(K.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(pe)&&(r.attributeName==="disabled"||r.attributeName===pe)||r.attributeName&&O.isAliasedAttributeReflection(i,r.attributeName))break;O.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),ce.syncElement(i),de.syncElement(i),ae.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{ce.cleanupTree(i),de.cleanupTree(i),ae.cleanupTree(i),O.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(O.addNode(i.parentElement,i),ce.syncTree(i),de.syncTree(i),ae.syncTree(i))}),r.target instanceof Element&&ae.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?O.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};K._initialized=!1,K._mutationObservers=[],K._dispatcher=null;let Re=K;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Re.init):Re.init();const Vt=()=>ne.waitForRenders(),qt=ne.enhancers;exports.Core=O;exports.Enhance=ee;exports.Env=u;exports.Form=F;exports.Fragment=N;exports.Haori=ne;exports.Log=m;exports.Queue=V;exports.default=ne;exports.enhancers=qt;exports.version=pt;exports.waitForRenders=Vt;
|
|
28
|
+
`)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:w.resolveInterval(t),timeoutMs:w.resolveTimeout(t),errorLimit:w.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};w.registrations.set(e,i),w.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{w.handleTimeout(e)},i.timeoutMs)),w.injectState(i),w.tick(e)}static async tick(e){const t=w.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await w.stop(e,t,"detached");return}const r=w.isHidden(e)||w.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await w.injectState(t)),r){w.schedule(e,t);return}if(w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new te(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(w.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await w.stop(e,t,"error");return}if(await w.restoreStateIfCleared(t),i&&w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}w.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{w.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=w.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&H.pollTimeout(e,t.count,w.elapsed(t)),await w.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,w.clearTimers(t),r==="detached"){w.registrations.delete(e);return}await w.injectState(t),e.isConnected&&H.pollStop(e,r,t.count,w.elapsed(t))}}static teardown(e,t){w.clearTimers(t),w.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(w.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(w.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),w.tick(t))})};w.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=w.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:w.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return O.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:T.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){w.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await w.injectState(e)}static resolveStateFragments(e){const t=`${u.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=z.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof T&&s.push(o)}),s}static resolveInterval(e){const t=`${u.prefix}poll-interval`;if(!e.hasAttribute(t))return w.DEFAULT_INTERVAL_MS;const r=w.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${w.DEFAULT_INTERVAL_MS}ms を使用します。`),w.DEFAULT_INTERVAL_MS):r<w.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${w.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),w.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${u.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${u.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${u.prefix}if-false]`)!==null}static isDisabled(e){const t=`${u.prefix}poll-disabled`;return e.hasAttribute(t)?w.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${u.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):w.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};w.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),w.DEFAULT_INTERVAL_MS=5e3,w.MIN_INTERVAL_MS=100,w.registrations=new Map,w.visibilityListener=null;let de=w;const pt="0.41.1";function Ut(g){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>g()):Promise.resolve().then(g)}const L=class L{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)&&(L.isHtmlElement(e)&&L.syncElement(e),e.querySelectorAll("*").forEach(t=>{L.syncElement(t)}))}static syncElement(e){const t=L.registrations.get(e),r=N.get(e);if(!(r instanceof T)||!L.shouldObserve(r)){t&&(t.observer.disconnect(),L.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=L.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),L.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=L.resolveRoot(r),s=L.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const c=L.registrations.get(e);if(!c)return;let d=!1;l.forEach(h=>{const y=h.target;c.observedRows.has(y)&&(h.isIntersecting?c.visibleRows.has(y)||(c.visibleRows.add(y),d=!0):c.visibleRows.delete(y)&&(d=!0))}),d&&L.scheduleCompute(c)},{root:n,rootMargin:s,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};L.registrations.set(e,o),L.refreshRows(o)}static cleanupTree(e){if(L.isHtmlElement(e)){const t=L.registrations.get(e);t&&(t.observer.disconnect(),L.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=L.registrations.get(t);r&&(r.observer.disconnect(),L.registrations.delete(t))})}static disconnectAll(){L.registrations.forEach(e=>{e.observer.disconnect()}),L.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=z.query(r,t,document);return L.isHtmlElement(i)?i:(m.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===""?L.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof T&&!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=L.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));L.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Ut(()=>{e.scheduled=!1;const t=e.fragment.getTarget();L.registrations.get(t)===e&&L.computeAndPublish(e)}))}static computeAndPublish(e){const t=L.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,L.publish(e,n))}static publish(e,t){const r=L.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);O.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:T.nextSequence()}).catch(o=>{m.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}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let ae=L;const K=class K{static disconnectMutationObservers(){K._mutationObservers.forEach(e=>{e.disconnect()}),K._mutationObservers.length=0}static async init(){if(K._initialized)return;K._initialized=!0,K.disconnectMutationObservers(),T.setPendingMutationFlusher(()=>{K.flushPendingMutations()});const e=new Be;K._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([O.scan(document.head),O.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await V.wait(),document.body.setAttribute("data-haori-ready",""),K.observe(document.head),K.observe(document.body),ce.syncTree(document.body),de.syncTree(document.body),ae.syncTree(document.body)}finally{e.release()}H.ready(pt)}static getDispatcher(){return K._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{K.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),K._mutationObservers.push(t)}static flushPendingMutations(){for(const e of K._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(K.isBindAttributeRecord),i=t.filter(n=>!K.isBindAttributeRecord(n));r.length>0&&K.processMutations(r,T.nextSequence()),i.length>0&&Promise.resolve().then(()=>{K.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${u.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(K.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(pe)&&(r.attributeName==="disabled"||r.attributeName===pe)||r.attributeName&&O.isAliasedAttributeReflection(i,r.attributeName))break;O.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),ce.syncElement(i),de.syncElement(i),ae.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{ce.cleanupTree(i),de.cleanupTree(i),ae.cleanupTree(i),O.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(O.addNode(i.parentElement,i),ce.syncTree(i),de.syncTree(i),ae.syncTree(i))}),r.target instanceof Element&&ae.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?O.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};K._initialized=!1,K._mutationObservers=[],K._dispatcher=null;let Re=K;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Re.init):Re.init();const Vt=()=>ne.waitForRenders(),qt=ne.enhancers;exports.Core=O;exports.Enhance=ee;exports.Env=u;exports.Form=F;exports.Fragment=N;exports.Haori=ne;exports.Log=m;exports.Queue=V;exports.default=ne;exports.enhancers=qt;exports.version=pt;exports.waitForRenders=Vt;
|
|
29
29
|
//# sourceMappingURL=haori.cjs.js.map
|
package/dist/haori.es.js
CHANGED
|
@@ -8492,7 +8492,74 @@ ${R}
|
|
|
8492
8492
|
), !0;
|
|
8493
8493
|
F.applyCustomValidity(e);
|
|
8494
8494
|
const t = this.findFirstInvalid(e);
|
|
8495
|
-
|
|
8495
|
+
if (t === null)
|
|
8496
|
+
return !0;
|
|
8497
|
+
const r = t;
|
|
8498
|
+
return b.isRectFullyVisible(t.getBoundingClientRect()) ? (r.reportValidity(), t.focus(), this.options.scrollOnError && t.scrollIntoView({ behavior: "smooth", block: "nearest" }), !1) : (t.focus({ preventScroll: !0 }), t.scrollIntoView({ behavior: "smooth", block: "nearest" }), b.reportValidityAfterScroll(r), !1);
|
|
8499
|
+
}
|
|
8500
|
+
/**
|
|
8501
|
+
* スクロールが止まってから、対象の入力要素の検証 UI(バブル)を表示します。
|
|
8502
|
+
*
|
|
8503
|
+
* `requestAnimationFrame` ごとに対象要素の位置を測り、位置が変わらないフレームが
|
|
8504
|
+
* 続き、かつ画面内に入ったら表示します。スムーズスクロールの所要時間はブラウザに
|
|
8505
|
+
* よって変わるため、上限(`VALIDATION_SCROLL_TIMEOUT_MS`)を過ぎたら静止を待たずに
|
|
8506
|
+
* 表示します。待機中に別の検証が始まった場合と、対象が DOM から外れた場合は
|
|
8507
|
+
* 表示しません。
|
|
8508
|
+
*
|
|
8509
|
+
* @param target 検証エラーの入力要素
|
|
8510
|
+
*/
|
|
8511
|
+
static reportValidityAfterScroll(e) {
|
|
8512
|
+
const t = ++b.validationReportGeneration, r = performance.now();
|
|
8513
|
+
let i = null, n = 0;
|
|
8514
|
+
const s = () => {
|
|
8515
|
+
if (t !== b.validationReportGeneration || !e.isConnected)
|
|
8516
|
+
return;
|
|
8517
|
+
const a = e.getBoundingClientRect(), o = `${Math.round(a.top)}:${Math.round(a.left)}`;
|
|
8518
|
+
if (n = o === i ? n + 1 : 0, i = o, n >= b.VALIDATION_SCROLL_STABLE_FRAMES && b.isRectPartlyVisible(a) || performance.now() - r >= b.VALIDATION_SCROLL_TIMEOUT_MS) {
|
|
8519
|
+
e.reportValidity();
|
|
8520
|
+
return;
|
|
8521
|
+
}
|
|
8522
|
+
requestAnimationFrame(s);
|
|
8523
|
+
};
|
|
8524
|
+
requestAnimationFrame(s);
|
|
8525
|
+
}
|
|
8526
|
+
/**
|
|
8527
|
+
* ビューポートの大きさを返します。
|
|
8528
|
+
*
|
|
8529
|
+
* @returns ビューポートの幅と高さ
|
|
8530
|
+
*/
|
|
8531
|
+
static getViewportSize() {
|
|
8532
|
+
return {
|
|
8533
|
+
width: window.innerWidth || document.documentElement.clientWidth,
|
|
8534
|
+
height: window.innerHeight || document.documentElement.clientHeight
|
|
8535
|
+
};
|
|
8536
|
+
}
|
|
8537
|
+
/**
|
|
8538
|
+
* 矩形がビューポートに収まっているかを判定します。
|
|
8539
|
+
*
|
|
8540
|
+
* 検証 UI を今すぐ出してよいかの判定に使います。一部でも外に出ていれば、
|
|
8541
|
+
* `reportValidity()` がバブルを見せるためにスクロールする余地が残っているため、
|
|
8542
|
+
* 「収まっている」とは扱いません。
|
|
8543
|
+
*
|
|
8544
|
+
* @param rect 判定する矩形
|
|
8545
|
+
* @returns 全体が画面内にあれば true
|
|
8546
|
+
*/
|
|
8547
|
+
static isRectFullyVisible(e) {
|
|
8548
|
+
const { width: t, height: r } = b.getViewportSize();
|
|
8549
|
+
return e.top >= 0 && e.left >= 0 && e.bottom <= r && e.right <= t;
|
|
8550
|
+
}
|
|
8551
|
+
/**
|
|
8552
|
+
* 矩形がビューポートと重なっているかを判定します。
|
|
8553
|
+
*
|
|
8554
|
+
* スクロールの静止判定に使います。位置が変わらないだけでは、スクロールが始まる
|
|
8555
|
+
* 前の 1 フレームを「静止」と誤認するため、画面内に入ったことも条件にします。
|
|
8556
|
+
*
|
|
8557
|
+
* @param rect 判定する矩形
|
|
8558
|
+
* @returns 一部でも画面内にあれば true
|
|
8559
|
+
*/
|
|
8560
|
+
static isRectPartlyVisible(e) {
|
|
8561
|
+
const { width: t, height: r } = b.getViewportSize();
|
|
8562
|
+
return e.top < r && e.bottom > 0 && e.left < t && e.right > 0;
|
|
8496
8563
|
}
|
|
8497
8564
|
/**
|
|
8498
8565
|
* `data-{event}-if` の実行条件を評価します。
|
|
@@ -9543,7 +9610,7 @@ ${R}
|
|
|
9543
9610
|
);
|
|
9544
9611
|
}
|
|
9545
9612
|
};
|
|
9546
|
-
b.DATA_PLACEHOLDER_REGEX = /\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g, b.SINGLE_PLACEHOLDER_REGEX = /^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/, b.RUNNING_CLICK_TARGETS = /* @__PURE__ */ new WeakSet();
|
|
9613
|
+
b.DATA_PLACEHOLDER_REGEX = /\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g, b.SINGLE_PLACEHOLDER_REGEX = /^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/, b.RUNNING_CLICK_TARGETS = /* @__PURE__ */ new WeakSet(), b.validationReportGeneration = 0, b.VALIDATION_SCROLL_TIMEOUT_MS = 1e3, b.VALIDATION_SCROLL_STABLE_FRAMES = 2;
|
|
9547
9614
|
let ee = b;
|
|
9548
9615
|
class Ot {
|
|
9549
9616
|
/**
|
|
@@ -12622,7 +12689,7 @@ w.CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
|
12622
12689
|
"state"
|
|
12623
12690
|
]), w.DEFAULT_INTERVAL_MS = 5e3, w.MIN_INTERVAL_MS = 100, w.registrations = /* @__PURE__ */ new Map(), w.visibilityListener = null;
|
|
12624
12691
|
let ce = w;
|
|
12625
|
-
const Ht = "0.41.
|
|
12692
|
+
const Ht = "0.41.1";
|
|
12626
12693
|
function Ut(g) {
|
|
12627
12694
|
typeof requestAnimationFrame == "function" ? requestAnimationFrame(() => g()) : Promise.resolve().then(g);
|
|
12628
12695
|
}
|