haori 0.70.0 → 0.70.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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量なライブラリです。JavaScript をほとんど書かずに、データバインディング、条件分岐、繰り返し処理、フォームの双方向バインディング、サーバー通信などを HTML 属性で宣言できます。
4
4
 
5
- バージョン: 0.70.0
5
+ バージョン: 0.70.1
6
6
 
7
7
  ---
8
8
 
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.70.0
5
+ Version: 0.70.1
6
6
 
7
7
  ---
8
8
 
package/dist/haori.cjs.js CHANGED
@@ -37,5 +37,5 @@ ${i}
37
37
  );`)}catch{try{s=new Function(`"use strict";
38
38
  ${i}
39
39
  `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(s)try{s.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${c.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let s=!1;if(i==="always"?s=!0:i!==""&&i!=="once"&&(d.EACH_RENDERED_CHANGE_WARNED.has(r)||(d.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),d.countEachRenderedRows(e)!==0){if(!s){if(d.EACH_RENDERED_CHANGE_FIRED.has(r))return;d.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(n){m.error("[Haori]",`each-rendered-change dispatch error: ${n}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${c.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),s=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof R){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),n&&d.warnExtraEachChildren(e),!n){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!n){const h=N.get(l);h instanceof R&&(r=h.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const u=N.get(l);u instanceof R&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?d.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}static reevaluateEachRows(e){if(d.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>d.evaluateAll(r,d.collectRowLocalFragments(e,r)))).then(()=>{})}static collectRowLocalFragments(e,t){const r=new Set,i=d.getEachScopeNames(e);if(i===null)return r;const s=n=>{if(d.keepsRowScopeNames(n))for(const a of n.getChildren())a instanceof de?d.areExpressionsRowLocal(d.extractInterpolations(a.getRawText()),i)&&r.add(a):a instanceof R&&(d.isRowLocalSubtree(a,i)?r.add(a):s(a))};return s(t),r}static keepsRowScopeNames(e){return e.getAttributeNames().every(t=>!t.startsWith(c.prefix)||t===`${c.prefix}if`||t===`${c.prefix}row`)}static getEachScopeNames(e){const t=e.getAttribute(`${c.prefix}each-arg`);if(!t)return null;const r=new Set([String(t)]),i=e.getAttribute(`${c.prefix}each-index`);return i&&r.add(String(i)),r}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e)||!d.isRowLocalEachTemplate(e)||d.hasEachFixedChildren(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),s=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=d.getEachScopeNames(e);if(r===null||i===null)return e.setRowLocalTemplate(!1),!1;const s=d.isRowLocalSubtree(r,i);return e.setRowLocalTemplate(s),s}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const s=e.getRawAttribute(i),n=typeof s=="string"?s:"";if(n.includes("{{")){if(!d.areExpressionsRowLocal(d.extractInterpolations(n),t))return!1;continue}if(!i.startsWith(c.prefix))continue;const a=i.slice(c.prefix.length);if(d.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!d.areExpressionsRowLocal([n],t))return!1;continue}if(d.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&d.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${c.prefix}each`)){const i=e.getRawAttribute(`${c.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const s=new Set(t);s.add(i);const n=e.getRawAttribute(`${c.prefix}each-index`);typeof n=="string"&&n!==""&&s.add(n),r=s}for(const i of e.getChildren())if(i instanceof R){if(!d.isRowLocalSubtree(i,r))return!1}else if(i instanceof de){const s=i.getRawText();if(s.includes("{{")&&!d.areExpressionsRowLocal(d.extractInterpolations(s),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const s=re.getFreeIdentifiers(i);if(s.length===0||s.some(n=>!t.has(n)))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(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof R?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshUrlParams(){const e=`${c.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const s=N.peek(i);return s instanceof R?d.setAttribute(i,e,s.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{m.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof R&&t(i)})};t(e)}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!V.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static 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 s=i.tagName.toLowerCase();const n=d.resolveElementId(i).trim();if(n!==""){s+=`#${n}`,t.unshift(s);break}const a=r.getRawAttribute(`${c.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(s+=`[${c.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(u=>u instanceof R).findIndex(u=>u===r);s+=`:nth-child(${l+1})`}t.unshift(s),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof de&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>d.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof R?!d.markFreshInitializationSkippable(s):s instanceof de?s.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${c.prefix}each-key`),n=e.getAttribute(`${c.prefix}each-arg`),a=t.map((F,Z)=>d.createListKey(F,s?String(s):null,Z)),o=new Set(a),l=new Map;a.forEach(F=>{l.set(F,(l.get(F)??0)+1)}),s&&o.size!==a.length&&d.warnDuplicateEachKey(String(s));const u=[];let h=e.getChildren().filter(F=>F instanceof R).filter(F=>!F.hasAttribute(`${c.prefix}each-before`)&&!F.hasAttribute(`${c.prefix}each-after`));const y=h.map(F=>F.getListKey()),b=new Set;h=h.filter((F,Z)=>{const ee=String(F.getListKey()),ae=l.get(ee)??0;if(ae===0){b.add(F);const K=F.getListKey();return K!==null&&O.rowRemove(F.getTarget(),K,Z),u.push(F.remove()),!1}return l.set(ee,ae-1),!0});const E=h.map(F=>F.getListKey()),A=new Map;h.forEach(F=>{const Z=F.getListKey();if(Z===null)return;const ee=A.get(Z);ee?ee.push(F):A.set(Z,[F])});const w=e.getChildElementFragments().filter(F=>!b.has(F)),$=w.filter(F=>F.hasAttribute(`${c.prefix}each-before`)).length;let M=Promise.resolve();const se=[];return a.forEach((F,Z)=>{const ee=t[Z],ae=Z;let K;const oe=A.get(F)?.shift();if(oe){K=oe;const j=$+Z;M=M.then(()=>d.updateRowFragment(K,ee,i,ae,n?String(n):null,F).then(k=>d.repositionEachRow(e,K,w,j).then(B=>{B!==null&&O.rowMove(K.getTarget(),F,B-$,Z),!(!k&&d.isRowLocalEachTemplate(e))&&se.push(d.evaluateAll(K,k?new Set:d.collectRowLocalFragments(e,K)).then(()=>d.applyRowFormValues(e,K,ee)))})))}else{K=r.clone();const j=$+Z;M=M.then(()=>d.updateRowFragment(K,ee,i,ae,n?String(n):null,F).then(()=>{const k=w[j]??null;return e.insertBefore(K,k).then(()=>{w.splice(j,0,K)}).then(()=>d.initializeFreshEachRow(K)).then(()=>d.applyRowFormValues(e,K,ee)).then(()=>{O.rowAdd(K.getTarget(),F,ae,ee)})}))}}),Promise.all(u).then(()=>M).then(()=>Promise.all(se)).then(()=>{const F=a.filter(j=>j!==null),Z=E.filter(j=>j!==null),ee=new Set(Z),ae=F.filter(j=>!ee.has(j)),oe=y.filter(j=>j!==null).filter(j=>!o.has(j));O.eachUpdate(e.getTarget(),ae,oe,F)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof R).filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!V.isEnabled()||d.WARNED_DUPLICATE_EACH_KEYS.has(e)||(d.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${c.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const s=r.indexOf(t);if(s===-1||s===i)return Promise.resolve(null);r.splice(s,1);const n=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,n).then(()=>s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${c.prefix}form-list`)||!D.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():D.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a;if(typeof t=="object"&&t!==null)a=s?{[s]:{...t}}:{...t};else if(s)a={[s]:t};else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=d.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(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(s=>d.createBindingSignature(s,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 s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${d.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.initialValueRestores=new Set,d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),d.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","value-type","store","store-params","store-arg","store-type","enhance","enhance-new"]),d.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),d.managedFetchSequence=0,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap,d.EACH_RENDERED_CHANGE_FIRED=new WeakSet,d.EACH_RENDERED_CHANGE_WARNED=new WeakSet,d.WARNED_DUPLICATE_EACH_KEYS=new Set,d.VALUE_BINDING_ATTRIBUTES=["value","checked"],d.OPTION_BINDING_ATTRIBUTES=["selected"],d.ABSENT_PATH=Symbol("absent");let C=d;const Ee=class Ee{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||D.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>ne.refreshSubtree(r),0)},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;if(!r||r[Ee.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=N.get(e);t&&new he(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("reset",this.onReset),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("reset",this.onReset),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`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(Ee.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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 s=N.get(i);s instanceof R&&this.isFromTarget(s,t)&&new he(s,"on",t).run().catch(n=>{m.error("[Haori]","Procedure execution error:",n)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=z.read(e,r),s=t.target;return i===null||!(s instanceof Node)?!1:z.queryAll(i,r).some(n=>n.contains(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(s=>{s instanceof HTMLElement&&(s.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(s.getAttribute(this.onAttributeName)),s.querySelectorAll(`[${this.onAttributeName}]`).forEach(n=>this.subscribeCustomEvent(n.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=`${c.prefix}input-`;if(!r.getAttributeNames().some(n=>n.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){(t==="change"||t==="input")&&this.markUserEditDuringInit(r,t==="change"),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;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const s=()=>{const n=new he(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){he.recordClickOutcome(e,n);const a=r.target;a instanceof HTMLElement&&a!==e&&he.recordClickOutcome(a,n)}};if(t==="click"&&e.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){if(this.markUserEditDuringInit(e,!1))return;this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=N.get(e);t instanceof R&&t.markUserEdit()}markUserEditDuringInit(e,t){const r=N.peek(e);return r instanceof R?t?(r.markUserEditOnDeferredChange(),Ee.radioGroupMembers(e).forEach(i=>i.markUserEdit()),!0):(r.markUserEdit(),!0):!1}static radioGroupMembers(e){if(!(e instanceof HTMLInputElement)||e.type!=="radio"||!e.name)return[];const t=[];for(const r of Array.from(document.getElementsByName(e.name))){if(r===e||!(r instanceof HTMLInputElement)||r.type!=="radio"||r.form!==e.form)continue;const i=N.get(r);i instanceof R&&t.push(i)}return t}syncUserEdit(e,t){const r=N.get(e);r instanceof R&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),Ee.radioGroupMembers(e).forEach(i=>{i.syncValue(),i.markUserEdit()}))}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`,i=`${c.prefix}click-lock`;let s=e;for(;s;){if(s.getAttributeNames().some(a=>a.startsWith(t)&&a!==r&&a!==i))return s;if(s.hasAttribute(r))return null;s=s.parentElement}return null}};Ee.HISTORY_STATE_KEY="__haoriHistoryState__",Ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let nt=Ee;const q=class q{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)&&(q.isHtmlElement(e)&&q.syncElement(e),e.querySelectorAll("*").forEach(t=>{q.syncElement(t)}))}static syncElement(e){const t=q.registrations.get(e),r=N.get(e);if(!r||!q.shouldObserve(r)){t&&(t.observer.disconnect(),q.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=q.resolveRoot(r),s=q.resolveRootMargin(r),n=q.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===s&&t.threshold===n&&t.once===a){t.fragment=r,q.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),q.registrations.delete(e));const o=new IntersectionObserver(l=>{const u=q.registrations.get(e);u&&l.forEach(h=>{if(u.intersecting=h.isIntersecting,!!h.isIntersecting){if(u.running||q.isDisabled(u.fragment)){u.pending=!0;return}q.runProcedure(e,u)}})},{root:i,rootMargin:s,threshold:n});o.observe(e),q.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:s,threshold:n})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new he(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{m.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=q.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),q.registrations.delete(e);return}q.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||q.isDisabled(t.fragment)||q.runProcedure(e,t)}static cleanupTree(e){if(q.isHtmlElement(e)){const t=q.registrations.get(e);t&&(t.observer.disconnect(),q.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=q.registrations.get(t);r&&(r.observer.disconnect(),q.registrations.delete(t))})}static disconnectAll(){q.registrations.forEach(e=>{e.observer.disconnect()}),q.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!q.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=z.query(r,t,document);return q.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}};q.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),q.registrations=new Map;let Me=q;const S=class S{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(S.isHtmlElement(e)&&S.syncElement(e),e.querySelectorAll("*").forEach(t=>{S.syncElement(t)}))}static syncElement(e){const t=S.registrations.get(e);if(!t&&!S.hasPollAttribute(e))return;const r=N.get(e);if(!(r instanceof R)||!S.shouldObserve(r)){t&&S.teardown(e,t);return}const i=S.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}S.teardown(e,t)}S.startPolling(e,r,i)}static cleanupTree(e){if(S.isHtmlElement(e)){const t=S.registrations.get(e);t&&S.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=S.registrations.get(t);r&&S.teardown(t,r)})}static disconnectAll(){S.registrations.forEach(e=>{S.clearTimers(e)}),S.registrations.clear(),S.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",S.visibilityListener),S.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=`${c.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=`${c.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!S.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
40
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:S.resolveInterval(t),timeoutMs:S.resolveTimeout(t),errorLimit:S.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};S.registrations.set(e,i),S.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{S.handleTimeout(e)},i.timeoutMs)),S.injectState(i),S.tick(e)}static async tick(e){const t=S.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await S.stop(e,t,"detached");return}const r=S.isHidden(e)||S.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await S.injectState(t)),r){S.schedule(e,t);return}if(S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new he(t.fragment,"poll").runWithResult()}catch(s){m.error("[Haori]","Poll procedure execution error:",s)}finally{t.fetching=!1}if(!(S.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await S.stop(e,t,"error");return}if(i&&S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}S.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{S.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=S.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,S.elapsed(t)),await S.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,S.clearTimers(t),r==="detached"){S.registrations.delete(e);return}await S.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,S.elapsed(t))}}static teardown(e,t){S.clearTimers(t),S.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(S.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(S.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),S.tick(t))})};S.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=S.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:S.elapsed(e)};return Promise.all(t.map(i=>{const s=i.getTarget(),n={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(s,n,{reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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 s=z.queryAll(i,t,document);if(s.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const n=[];return s.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof R&&n.push(o)}),n}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return S.DEFAULT_INTERVAL_MS;const r=S.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${S.DEFAULT_INTERVAL_MS}ms を使用します。`),S.DEFAULT_INTERVAL_MS):r<S.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${S.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),S.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=S.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=S.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?S.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.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):S.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}};S.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),S.DEFAULT_INTERVAL_MS=5e3,S.MIN_INTERVAL_MS=100,S.registrations=new Map,S.visibilityListener=null;let $e=S;const er="0.70.0";function Br(p){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p()):Promise.resolve().then(p)}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 R)||!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 s=L.resolveRoot(r),n=L.resolveRootMargin(r);if(t&&t.observer.root===s&&t.observer.rootMargin===n&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let h=!1;l.forEach(y=>{const b=y.target;u.observedRows.has(b)&&(y.isIntersecting?u.visibleRows.has(b)||(u.visibleRows.add(b),h=!0):u.visibleRows.delete(b)&&(h=!0))}),h&&L.scheduleCompute(u)},{root:s,rootMargin:n,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:s,rootMargin:n,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(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=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=`${c.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 R&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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,Br(()=>{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 s;if(i.length===0)s={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);s={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const n=JSON.stringify(s);n!==e.lastSnapshot&&(e.lastSnapshot=n,L.publish(e,s))}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(),s={...r.getRawBindingData()??{}};s[e.varName]={...t};const n=e.fragment.getTarget(),a=i===n?new Set:new Set([e.fragment]);C.setBindingData(i,s,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let Re=L;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers(),R.setPendingMutationFlusher(()=>{H.flushPendingMutations()});const e=new nt;H._dispatcher=e,e.startDeferred(),H._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.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 H.waitInitialIntakes(),await J.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),Me.syncTree(document.body),$e.syncTree(document.body),Re.syncTree(document.body)}finally{H._initialIntakes=null,e.release()}O.ready(er)}static getDispatcher(){return H._dispatcher}static async waitInitialIntakes(){const e=H._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(H._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>H.toCapturedRecord(i));t.disconnect(),H.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!H.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>R.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=R.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{H.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}static flushPendingMutations(){for(const e of H._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(H.isBindAttributeRecord),i=t.filter(s=>!H.isBindAttributeRecord(s));r.length>0&&H.processMutations(r,R.nextSequence()),i.length>0&&Promise.resolve().then(()=>{H.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(H.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(we)&&(r.attributeName==="disabled"||r.attributeName===we))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&R.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const s=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);H._initialIntakes?.push(s),Me.syncElement(i),$e.syncElement(i),Re.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{H.isStaleExternalRemoval(r,i)||(Me.cleanupTree(i),$e.cleanupTree(i),Re.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);H._initialIntakes?.push(s),Me.syncTree(i),$e.syncTree(i),Re.syncTree(i)}),r.target instanceof Element&&Re.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.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)}}};H._initialized=!1,H._mutationObservers=[],H._dispatcher=null,H._initialIntakes=null;let He=H;ne.setMutationCapture(p=>He.captureMutations(p));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Ur=()=>ge.waitForRenders(),Hr=ge.enhancers,Vr=ge.handlers;exports.Core=C;exports.Enhance=ne;exports.Env=c;exports.Form=D;exports.Fragment=N;exports.Haori=ge;exports.Log=m;exports.Queue=J;exports.default=ge;exports.enhancers=Hr;exports.handlers=Vr;exports.version=er;exports.waitForRenders=Ur;
40
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:S.resolveInterval(t),timeoutMs:S.resolveTimeout(t),errorLimit:S.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};S.registrations.set(e,i),S.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{S.handleTimeout(e)},i.timeoutMs)),S.injectState(i),S.tick(e)}static async tick(e){const t=S.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await S.stop(e,t,"detached");return}const r=S.isHidden(e)||S.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await S.injectState(t)),r){S.schedule(e,t);return}if(S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new he(t.fragment,"poll").runWithResult()}catch(s){m.error("[Haori]","Poll procedure execution error:",s)}finally{t.fetching=!1}if(!(S.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await S.stop(e,t,"error");return}if(i&&S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}S.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{S.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=S.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,S.elapsed(t)),await S.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,S.clearTimers(t),r==="detached"){S.registrations.delete(e);return}await S.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,S.elapsed(t))}}static teardown(e,t){S.clearTimers(t),S.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(S.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(S.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),S.tick(t))})};S.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=S.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:S.elapsed(e)};return Promise.all(t.map(i=>{const s=i.getTarget(),n={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(s,n,{reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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 s=z.queryAll(i,t,document);if(s.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const n=[];return s.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof R&&n.push(o)}),n}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return S.DEFAULT_INTERVAL_MS;const r=S.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${S.DEFAULT_INTERVAL_MS}ms を使用します。`),S.DEFAULT_INTERVAL_MS):r<S.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${S.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),S.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=S.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=S.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?S.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.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):S.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}};S.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),S.DEFAULT_INTERVAL_MS=5e3,S.MIN_INTERVAL_MS=100,S.registrations=new Map,S.visibilityListener=null;let $e=S;const er="0.70.1";function Br(p){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p()):Promise.resolve().then(p)}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 R)||!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 s=L.resolveRoot(r),n=L.resolveRootMargin(r);if(t&&t.observer.root===s&&t.observer.rootMargin===n&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let h=!1;l.forEach(y=>{const b=y.target;u.observedRows.has(b)&&(y.isIntersecting?u.visibleRows.has(b)||(u.visibleRows.add(b),h=!0):u.visibleRows.delete(b)&&(h=!0))}),h&&L.scheduleCompute(u)},{root:s,rootMargin:n,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:s,rootMargin:n,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(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=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=`${c.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 R&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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,Br(()=>{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 s;if(i.length===0)s={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);s={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const n=JSON.stringify(s);n!==e.lastSnapshot&&(e.lastSnapshot=n,L.publish(e,s))}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(),s={...r.getRawBindingData()??{}};s[e.varName]={...t};const n=e.fragment.getTarget(),a=i===n?new Set:new Set([e.fragment]);C.setBindingData(i,s,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let Re=L;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers(),R.setPendingMutationFlusher(()=>{H.flushPendingMutations()});const e=new nt;H._dispatcher=e,e.startDeferred(),H._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.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 H.waitInitialIntakes(),await J.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),Me.syncTree(document.body),$e.syncTree(document.body),Re.syncTree(document.body)}finally{H._initialIntakes=null,e.release()}O.ready(er)}static getDispatcher(){return H._dispatcher}static async waitInitialIntakes(){const e=H._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(H._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>H.toCapturedRecord(i));t.disconnect(),H.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!H.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>R.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=R.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{H.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}static flushPendingMutations(){for(const e of H._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(H.isBindAttributeRecord),i=t.filter(s=>!H.isBindAttributeRecord(s));r.length>0&&H.processMutations(r,R.nextSequence()),i.length>0&&Promise.resolve().then(()=>{H.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(H.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(we)&&(r.attributeName==="disabled"||r.attributeName===we))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&R.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const s=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);H._initialIntakes?.push(s),Me.syncElement(i),$e.syncElement(i),Re.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{H.isStaleExternalRemoval(r,i)||(Me.cleanupTree(i),$e.cleanupTree(i),Re.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);H._initialIntakes?.push(s),Me.syncTree(i),$e.syncTree(i),Re.syncTree(i)}),r.target instanceof Element&&Re.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.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)}}};H._initialized=!1,H._mutationObservers=[],H._dispatcher=null,H._initialIntakes=null;let He=H;ne.setMutationCapture(p=>He.captureMutations(p));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Ur=()=>ge.waitForRenders(),Hr=ge.enhancers,Vr=ge.handlers;exports.Core=C;exports.Enhance=ne;exports.Env=c;exports.Form=D;exports.Fragment=N;exports.Haori=ge;exports.Log=m;exports.Queue=J;exports.default=ge;exports.enhancers=Hr;exports.handlers=Vr;exports.version=er;exports.waitForRenders=Ur;
41
41
  //# sourceMappingURL=haori.cjs.js.map
package/dist/haori.es.js CHANGED
@@ -18901,7 +18901,7 @@ S.CONFIG_KEYS = /* @__PURE__ */ new Set([
18901
18901
  "state"
18902
18902
  ]), S.DEFAULT_INTERVAL_MS = 5e3, S.MIN_INTERVAL_MS = 100, S.registrations = /* @__PURE__ */ new Map(), S.visibilityListener = null;
18903
18903
  let $e = S;
18904
- const Or = "0.70.0";
18904
+ const Or = "0.70.1";
18905
18905
  function Br(p) {
18906
18906
  typeof requestAnimationFrame == "function" ? requestAnimationFrame(() => p()) : Promise.resolve().then(p);
18907
18907
  }
@@ -37,5 +37,5 @@ ${i}
37
37
  );`)}catch{try{s=new Function(`"use strict";
38
38
  ${i}
39
39
  `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(s)try{s.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${c.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let s=!1;if(i==="always"?s=!0:i!==""&&i!=="once"&&(d.EACH_RENDERED_CHANGE_WARNED.has(r)||(d.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),d.countEachRenderedRows(e)!==0){if(!s){if(d.EACH_RENDERED_CHANGE_FIRED.has(r))return;d.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(n){m.error("[Haori]",`each-rendered-change dispatch error: ${n}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${c.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),s=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof S){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),n&&d.warnExtraEachChildren(e),!n){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!n){const h=N.get(l);h instanceof S&&(r=h.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const u=N.get(l);u instanceof S&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?d.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}static reevaluateEachRows(e){if(d.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>d.evaluateAll(r,d.collectRowLocalFragments(e,r)))).then(()=>{})}static collectRowLocalFragments(e,t){const r=new Set,i=d.getEachScopeNames(e);if(i===null)return r;const s=n=>{if(d.keepsRowScopeNames(n))for(const a of n.getChildren())a instanceof ue?d.areExpressionsRowLocal(d.extractInterpolations(a.getRawText()),i)&&r.add(a):a instanceof S&&(d.isRowLocalSubtree(a,i)?r.add(a):s(a))};return s(t),r}static keepsRowScopeNames(e){return e.getAttributeNames().every(t=>!t.startsWith(c.prefix)||t===`${c.prefix}if`||t===`${c.prefix}row`)}static getEachScopeNames(e){const t=e.getAttribute(`${c.prefix}each-arg`);if(!t)return null;const r=new Set([String(t)]),i=e.getAttribute(`${c.prefix}each-index`);return i&&r.add(String(i)),r}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e)||!d.isRowLocalEachTemplate(e)||d.hasEachFixedChildren(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),s=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=d.getEachScopeNames(e);if(r===null||i===null)return e.setRowLocalTemplate(!1),!1;const s=d.isRowLocalSubtree(r,i);return e.setRowLocalTemplate(s),s}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const s=e.getRawAttribute(i),n=typeof s=="string"?s:"";if(n.includes("{{")){if(!d.areExpressionsRowLocal(d.extractInterpolations(n),t))return!1;continue}if(!i.startsWith(c.prefix))continue;const a=i.slice(c.prefix.length);if(d.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!d.areExpressionsRowLocal([n],t))return!1;continue}if(d.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&d.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${c.prefix}each`)){const i=e.getRawAttribute(`${c.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const s=new Set(t);s.add(i);const n=e.getRawAttribute(`${c.prefix}each-index`);typeof n=="string"&&n!==""&&s.add(n),r=s}for(const i of e.getChildren())if(i instanceof S){if(!d.isRowLocalSubtree(i,r))return!1}else if(i instanceof ue){const s=i.getRawText();if(s.includes("{{")&&!d.areExpressionsRowLocal(d.extractInterpolations(s),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const s=re.getFreeIdentifiers(i);if(s.length===0||s.some(n=>!t.has(n)))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(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof S?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshUrlParams(){const e=`${c.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const s=N.peek(i);return s instanceof S?d.setAttribute(i,e,s.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{m.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof S&&t(i)})};t(e)}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!B.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static 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 s=i.tagName.toLowerCase();const n=d.resolveElementId(i).trim();if(n!==""){s+=`#${n}`,t.unshift(s);break}const a=r.getRawAttribute(`${c.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(s+=`[${c.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(u=>u instanceof S).findIndex(u=>u===r);s+=`:nth-child(${l+1})`}t.unshift(s),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof ue&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>d.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof S?!d.markFreshInitializationSkippable(s):s instanceof ue?s.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${c.prefix}each-key`),n=e.getAttribute(`${c.prefix}each-arg`),a=t.map((F,Z)=>d.createListKey(F,s?String(s):null,Z)),o=new Set(a),l=new Map;a.forEach(F=>{l.set(F,(l.get(F)??0)+1)}),s&&o.size!==a.length&&d.warnDuplicateEachKey(String(s));const u=[];let h=e.getChildren().filter(F=>F instanceof S).filter(F=>!F.hasAttribute(`${c.prefix}each-before`)&&!F.hasAttribute(`${c.prefix}each-after`));const y=h.map(F=>F.getListKey()),b=new Set;h=h.filter((F,Z)=>{const te=String(F.getListKey()),oe=l.get(te)??0;if(oe===0){b.add(F);const K=F.getListKey();return K!==null&&O.rowRemove(F.getTarget(),K,Z),u.push(F.remove()),!1}return l.set(te,oe-1),!0});const E=h.map(F=>F.getListKey()),A=new Map;h.forEach(F=>{const Z=F.getListKey();if(Z===null)return;const te=A.get(Z);te?te.push(F):A.set(Z,[F])});const w=e.getChildElementFragments().filter(F=>!b.has(F)),$=w.filter(F=>F.hasAttribute(`${c.prefix}each-before`)).length;let M=Promise.resolve();const ne=[];return a.forEach((F,Z)=>{const te=t[Z],oe=Z;let K;const le=A.get(F)?.shift();if(le){K=le;const j=$+Z;M=M.then(()=>d.updateRowFragment(K,te,i,oe,n?String(n):null,F).then(k=>d.repositionEachRow(e,K,w,j).then(H=>{H!==null&&O.rowMove(K.getTarget(),F,H-$,Z),!(!k&&d.isRowLocalEachTemplate(e))&&ne.push(d.evaluateAll(K,k?new Set:d.collectRowLocalFragments(e,K)).then(()=>d.applyRowFormValues(e,K,te)))})))}else{K=r.clone();const j=$+Z;M=M.then(()=>d.updateRowFragment(K,te,i,oe,n?String(n):null,F).then(()=>{const k=w[j]??null;return e.insertBefore(K,k).then(()=>{w.splice(j,0,K)}).then(()=>d.initializeFreshEachRow(K)).then(()=>d.applyRowFormValues(e,K,te)).then(()=>{O.rowAdd(K.getTarget(),F,oe,te)})}))}}),Promise.all(u).then(()=>M).then(()=>Promise.all(ne)).then(()=>{const F=a.filter(j=>j!==null),Z=E.filter(j=>j!==null),te=new Set(Z),oe=F.filter(j=>!te.has(j)),le=y.filter(j=>j!==null).filter(j=>!o.has(j));O.eachUpdate(e.getTarget(),oe,le,F)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof S).filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!B.isEnabled()||d.WARNED_DUPLICATE_EACH_KEYS.has(e)||(d.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${c.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const s=r.indexOf(t);if(s===-1||s===i)return Promise.resolve(null);r.splice(s,1);const n=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,n).then(()=>s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${c.prefix}form-list`)||!D.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():D.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a;if(typeof t=="object"&&t!==null)a=s?{[s]:{...t}}:{...t};else if(s)a={[s]:t};else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=d.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(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(s=>d.createBindingSignature(s,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 s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${d.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.initialValueRestores=new Set,d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),d.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","value-type","store","store-params","store-arg","store-type","enhance","enhance-new"]),d.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),d.managedFetchSequence=0,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap,d.EACH_RENDERED_CHANGE_FIRED=new WeakSet,d.EACH_RENDERED_CHANGE_WARNED=new WeakSet,d.WARNED_DUPLICATE_EACH_KEYS=new Set,d.VALUE_BINDING_ATTRIBUTES=["value","checked"],d.OPTION_BINDING_ATTRIBUTES=["selected"],d.ABSENT_PATH=Symbol("absent");let C=d;const Ae=class Ae{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||D.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>se.refreshSubtree(r),0)},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;if(!r||r[Ae.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=N.get(e);t&&new de(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("reset",this.onReset),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("reset",this.onReset),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`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(Ae.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 s=N.get(i);s instanceof S&&this.isFromTarget(s,t)&&new de(s,"on",t).run().catch(n=>{m.error("[Haori]","Procedure execution error:",n)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=z.read(e,r),s=t.target;return i===null||!(s instanceof Node)?!1:z.queryAll(i,r).some(n=>n.contains(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(s=>{s instanceof HTMLElement&&(s.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(s.getAttribute(this.onAttributeName)),s.querySelectorAll(`[${this.onAttributeName}]`).forEach(n=>this.subscribeCustomEvent(n.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=`${c.prefix}input-`;if(!r.getAttributeNames().some(n=>n.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){(t==="change"||t==="input")&&this.markUserEditDuringInit(r,t==="change"),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;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const s=()=>{const n=new de(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){de.recordClickOutcome(e,n);const a=r.target;a instanceof HTMLElement&&a!==e&&de.recordClickOutcome(a,n)}};if(t==="click"&&e.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){if(this.markUserEditDuringInit(e,!1))return;this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=N.get(e);t instanceof S&&t.markUserEdit()}markUserEditDuringInit(e,t){const r=N.peek(e);return r instanceof S?t?(r.markUserEditOnDeferredChange(),Ae.radioGroupMembers(e).forEach(i=>i.markUserEdit()),!0):(r.markUserEdit(),!0):!1}static radioGroupMembers(e){if(!(e instanceof HTMLInputElement)||e.type!=="radio"||!e.name)return[];const t=[];for(const r of Array.from(document.getElementsByName(e.name))){if(r===e||!(r instanceof HTMLInputElement)||r.type!=="radio"||r.form!==e.form)continue;const i=N.get(r);i instanceof S&&t.push(i)}return t}syncUserEdit(e,t){const r=N.get(e);r instanceof S&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),Ae.radioGroupMembers(e).forEach(i=>{i.syncValue(),i.markUserEdit()}))}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`,i=`${c.prefix}click-lock`;let s=e;for(;s;){if(s.getAttributeNames().some(a=>a.startsWith(t)&&a!==r&&a!==i))return s;if(s.hasAttribute(r))return null;s=s.parentElement}return null}};Ae.HISTORY_STATE_KEY="__haoriHistoryState__",Ae.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let at=Ae;const q=class q{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)&&(q.isHtmlElement(e)&&q.syncElement(e),e.querySelectorAll("*").forEach(t=>{q.syncElement(t)}))}static syncElement(e){const t=q.registrations.get(e),r=N.get(e);if(!r||!q.shouldObserve(r)){t&&(t.observer.disconnect(),q.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=q.resolveRoot(r),s=q.resolveRootMargin(r),n=q.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===s&&t.threshold===n&&t.once===a){t.fragment=r,q.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),q.registrations.delete(e));const o=new IntersectionObserver(l=>{const u=q.registrations.get(e);u&&l.forEach(h=>{if(u.intersecting=h.isIntersecting,!!h.isIntersecting){if(u.running||q.isDisabled(u.fragment)){u.pending=!0;return}q.runProcedure(e,u)}})},{root:i,rootMargin:s,threshold:n});o.observe(e),q.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:s,threshold:n})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new de(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{m.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=q.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),q.registrations.delete(e);return}q.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||q.isDisabled(t.fragment)||q.runProcedure(e,t)}static cleanupTree(e){if(q.isHtmlElement(e)){const t=q.registrations.get(e);t&&(t.observer.disconnect(),q.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=q.registrations.get(t);r&&(r.observer.disconnect(),q.registrations.delete(t))})}static disconnectAll(){q.registrations.forEach(e=>{e.observer.disconnect()}),q.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!q.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=z.query(r,t,document);return q.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}};q.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),q.registrations=new Map;let Ce=q;const R=class R{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(R.isHtmlElement(e)&&R.syncElement(e),e.querySelectorAll("*").forEach(t=>{R.syncElement(t)}))}static syncElement(e){const t=R.registrations.get(e);if(!t&&!R.hasPollAttribute(e))return;const r=N.get(e);if(!(r instanceof S)||!R.shouldObserve(r)){t&&R.teardown(e,t);return}const i=R.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}R.teardown(e,t)}R.startPolling(e,r,i)}static cleanupTree(e){if(R.isHtmlElement(e)){const t=R.registrations.get(e);t&&R.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=R.registrations.get(t);r&&R.teardown(t,r)})}static disconnectAll(){R.registrations.forEach(e=>{R.clearTimers(e)}),R.registrations.clear(),R.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",R.visibilityListener),R.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=`${c.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=`${c.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!R.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
40
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:R.resolveInterval(t),timeoutMs:R.resolveTimeout(t),errorLimit:R.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};R.registrations.set(e,i),R.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{R.handleTimeout(e)},i.timeoutMs)),R.injectState(i),R.tick(e)}static async tick(e){const t=R.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await R.stop(e,t,"detached");return}const r=R.isHidden(e)||R.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await R.injectState(t)),r){R.schedule(e,t);return}if(R.isUntilSatisfied(t.fragment)){await R.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new de(t.fragment,"poll").runWithResult()}catch(s){m.error("[Haori]","Poll procedure execution error:",s)}finally{t.fetching=!1}if(!(R.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await R.stop(e,t,"error");return}if(i&&R.isUntilSatisfied(t.fragment)){await R.stop(e,t,"until");return}R.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{R.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=R.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,R.elapsed(t)),await R.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,R.clearTimers(t),r==="detached"){R.registrations.delete(e);return}await R.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,R.elapsed(t))}}static teardown(e,t){R.clearTimers(t),R.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(R.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(R.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),R.tick(t))})};R.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=R.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:R.elapsed(e)};return Promise.all(t.map(i=>{const s=i.getTarget(),n={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(s,n,{reflectToAttribute:!1,kind:"nonSupply",sequence:S.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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 s=z.queryAll(i,t,document);if(s.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const n=[];return s.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof S&&n.push(o)}),n}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return R.DEFAULT_INTERVAL_MS;const r=R.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${R.DEFAULT_INTERVAL_MS}ms を使用します。`),R.DEFAULT_INTERVAL_MS):r<R.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${R.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),R.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=R.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=R.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?R.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.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):R.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}};R.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),R.DEFAULT_INTERVAL_MS=5e3,R.MIN_INTERVAL_MS=100,R.registrations=new Map,R.visibilityListener=null;let Me=R;const er="0.70.0";function Lr(p){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p()):Promise.resolve().then(p)}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 S)||!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 s=L.resolveRoot(r),n=L.resolveRootMargin(r);if(t&&t.observer.root===s&&t.observer.rootMargin===n&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let h=!1;l.forEach(y=>{const b=y.target;u.observedRows.has(b)&&(y.isIntersecting?u.visibleRows.has(b)||(u.visibleRows.add(b),h=!0):u.visibleRows.delete(b)&&(h=!0))}),h&&L.scheduleCompute(u)},{root:s,rootMargin:n,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:s,rootMargin:n,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(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=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=`${c.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 S&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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,Lr(()=>{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 s;if(i.length===0)s={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);s={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const n=JSON.stringify(s);n!==e.lastSnapshot&&(e.lastSnapshot=n,L.publish(e,s))}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(),s={...r.getRawBindingData()??{}};s[e.varName]={...t};const n=e.fragment.getTarget(),a=i===n?new Set:new Set([e.fragment]);C.setBindingData(i,s,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:S.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let Re=L;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),S.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new at;U._dispatcher=e,e.startDeferred(),U._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.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 U.waitInitialIntakes(),await Y.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ce.syncTree(document.body),Me.syncTree(document.body),Re.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}O.ready(er)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>S.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=S.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(s=>!U.isBindAttributeRecord(s));r.length>0&&U.processMutations(r,S.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(U.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(ve)&&(r.attributeName==="disabled"||r.attributeName===ve))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&S.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const s=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(s),Ce.syncElement(i),Me.syncElement(i),Re.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ce.cleanupTree(i),Me.cleanupTree(i),Re.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);U._initialIntakes?.push(s),Ce.syncTree(i),Me.syncTree(i),Re.syncTree(i)}),r.target instanceof Element&&Re.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.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)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let He=U;se.setMutationCapture(p=>He.captureMutations(p)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Or=()=>fe.waitForRenders(),Br=fe.enhancers,Ur=fe.handlers,Hr=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:se,Env:c,Form:D,Fragment:N,Haori:fe,Log:m,Queue:Y,default:fe,enhancers:Br,handlers:Ur,version:er,waitForRenders:Or},Symbol.toStringTag,{value:"Module"})),ot=fe;for(const[p,e]of Object.entries(Hr))p in ot||Object.defineProperty(ot,p,{value:e,writable:!0,enumerable:!0,configurable:!0});return ot}();
40
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:R.resolveInterval(t),timeoutMs:R.resolveTimeout(t),errorLimit:R.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};R.registrations.set(e,i),R.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{R.handleTimeout(e)},i.timeoutMs)),R.injectState(i),R.tick(e)}static async tick(e){const t=R.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await R.stop(e,t,"detached");return}const r=R.isHidden(e)||R.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await R.injectState(t)),r){R.schedule(e,t);return}if(R.isUntilSatisfied(t.fragment)){await R.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new de(t.fragment,"poll").runWithResult()}catch(s){m.error("[Haori]","Poll procedure execution error:",s)}finally{t.fetching=!1}if(!(R.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await R.stop(e,t,"error");return}if(i&&R.isUntilSatisfied(t.fragment)){await R.stop(e,t,"until");return}R.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{R.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=R.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,R.elapsed(t)),await R.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,R.clearTimers(t),r==="detached"){R.registrations.delete(e);return}await R.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,R.elapsed(t))}}static teardown(e,t){R.clearTimers(t),R.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(R.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(R.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),R.tick(t))})};R.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=R.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:R.elapsed(e)};return Promise.all(t.map(i=>{const s=i.getTarget(),n={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(s,n,{reflectToAttribute:!1,kind:"nonSupply",sequence:S.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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 s=z.queryAll(i,t,document);if(s.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const n=[];return s.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof S&&n.push(o)}),n}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return R.DEFAULT_INTERVAL_MS;const r=R.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${R.DEFAULT_INTERVAL_MS}ms を使用します。`),R.DEFAULT_INTERVAL_MS):r<R.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${R.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),R.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=R.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=R.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?R.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.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):R.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}};R.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),R.DEFAULT_INTERVAL_MS=5e3,R.MIN_INTERVAL_MS=100,R.registrations=new Map,R.visibilityListener=null;let Me=R;const er="0.70.1";function Lr(p){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p()):Promise.resolve().then(p)}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 S)||!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 s=L.resolveRoot(r),n=L.resolveRootMargin(r);if(t&&t.observer.root===s&&t.observer.rootMargin===n&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let h=!1;l.forEach(y=>{const b=y.target;u.observedRows.has(b)&&(y.isIntersecting?u.visibleRows.has(b)||(u.visibleRows.add(b),h=!0):u.visibleRows.delete(b)&&(h=!0))}),h&&L.scheduleCompute(u)},{root:s,rootMargin:n,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:s,rootMargin:n,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(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=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=`${c.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 S&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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,Lr(()=>{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 s;if(i.length===0)s={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);s={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const n=JSON.stringify(s);n!==e.lastSnapshot&&(e.lastSnapshot=n,L.publish(e,s))}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(),s={...r.getRawBindingData()??{}};s[e.varName]={...t};const n=e.fragment.getTarget(),a=i===n?new Set:new Set([e.fragment]);C.setBindingData(i,s,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:S.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let Re=L;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),S.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new at;U._dispatcher=e,e.startDeferred(),U._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.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 U.waitInitialIntakes(),await Y.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ce.syncTree(document.body),Me.syncTree(document.body),Re.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}O.ready(er)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>S.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=S.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(s=>!U.isBindAttributeRecord(s));r.length>0&&U.processMutations(r,S.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(U.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(ve)&&(r.attributeName==="disabled"||r.attributeName===ve))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&S.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const s=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(s),Ce.syncElement(i),Me.syncElement(i),Re.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ce.cleanupTree(i),Me.cleanupTree(i),Re.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);U._initialIntakes?.push(s),Ce.syncTree(i),Me.syncTree(i),Re.syncTree(i)}),r.target instanceof Element&&Re.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.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)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let He=U;se.setMutationCapture(p=>He.captureMutations(p)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Or=()=>fe.waitForRenders(),Br=fe.enhancers,Ur=fe.handlers,Hr=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:se,Env:c,Form:D,Fragment:N,Haori:fe,Log:m,Queue:Y,default:fe,enhancers:Br,handlers:Ur,version:er,waitForRenders:Or},Symbol.toStringTag,{value:"Module"})),ot=fe;for(const[p,e]of Object.entries(Hr))p in ot||Object.defineProperty(ot,p,{value:e,writable:!0,enumerable:!0,configurable:!0});return ot}();
41
41
  //# sourceMappingURL=haori.iife.js.map
package/dist/index.d.ts CHANGED
@@ -5238,7 +5238,7 @@ declare interface ValueChangeOrigin {
5238
5238
  * リリース時に `package.json` と揃えて更新します(`tests/version.test.ts` が
5239
5239
  * 一致を検査します)。
5240
5240
  */
5241
- export declare const version = "0.70.0";
5241
+ export declare const version = "0.70.1";
5242
5242
 
5243
5243
  /**
5244
5244
  * すべてのレンダリングタスク(追従投入分を含む)の完了を待ちます。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haori",
3
- "version": "0.70.0",
3
+ "version": "0.70.1",
4
4
  "description": "A lightweight HTML-first UI engine powered by declarative data bindings and expressions.",
5
5
  "scripts": {
6
6
  "dev": "vite",
@@ -12,7 +12,7 @@
12
12
  "test:watch": "vitest",
13
13
  "test:legacy": "vitest run --config vitest.legacy.config.ts",
14
14
  "test:mutation": "stryker run",
15
- "bench": "vitest bench --run",
15
+ "bench": "vitest bench --run --config vitest.legacy.config.ts",
16
16
  "bench:browser": "node bench/run.mjs",
17
17
  "test:e2e": "playwright test",
18
18
  "test:coverage": "vitest run --coverage",
@@ -69,19 +69,19 @@
69
69
  "homepage": "https://github.com/meibinlab/haori-js#readme",
70
70
  "devDependencies": {
71
71
  "@eslint/js": "^9.31.0",
72
- "@playwright/test": "^1.57.0",
72
+ "@playwright/test": "^1.65.0",
73
73
  "@stryker-mutator/core": "^10.0.0",
74
74
  "@stryker-mutator/vitest-runner": "^10.0.0",
75
75
  "@types/node": "^22.7.5",
76
- "@vitest/coverage-v8": "^3.2.7",
76
+ "@vitest/coverage-v8": "^4.1.12",
77
77
  "eslint": "^9.31.0",
78
78
  "http-server": "^14.1.1",
79
- "jsdom": "^26.1.0",
79
+ "jsdom": "^31.0.1",
80
80
  "prettier": "^3.6.2",
81
81
  "typescript": "^5.6.3",
82
82
  "typescript-eslint": "^8.37.0",
83
83
  "vite": "^7.0.4",
84
84
  "vite-plugin-dts": "^4.5.4",
85
- "vitest": "^3.2.4"
85
+ "vitest": "^4.1.12"
86
86
  }
87
87
  }