haori 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/haori.cjs.js +7 -7
- package/dist/haori.cjs.js.map +1 -1
- package/dist/haori.es.js +448 -402
- package/dist/haori.es.js.map +1 -1
- package/dist/haori.iife.js +7 -7
- package/dist/haori.iife.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/package.json +1 -1
- package/dist/src/form.d.ts.map +1 -1
- package/dist/src/form.js +3 -0
- package/dist/src/form.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/procedure.d.ts +16 -0
- package/dist/src/procedure.d.ts.map +1 -1
- package/dist/src/procedure.js +68 -8
- package/dist/src/procedure.js.map +1 -1
- package/dist/tests/form.test.js +27 -0
- package/dist/tests/form.test.js.map +1 -1
- package/dist/tests/procedure-action-operations.test.js +148 -3
- package/dist/tests/procedure-action-operations.test.js.map +1 -1
- package/package.json +1 -1
package/dist/haori.iife.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var Haori=function(
|
|
1
|
+
var Haori=function(M){"use strict";const B=class B{static isEnabled(){return B.devMode}static enable(){B.devMode=!0}static disable(){B.devMode=!1}static set(t){B.devMode=t}};B.devMode=!1;let C=B;const W="embedded";function _(F){return F==="embedded"||F==="demo"}function rt(F){return F===null?null:_(F)?F:W}const k=class k{static get runtime(){return k._runtime}static setRuntime(t){k._runtime=_(t)?t:W}static detect(){try{const t=document.currentScript||document.querySelector('script[src*="haori"]');if(t instanceof HTMLScriptElement){const r=t.getAttribute("data-prefix")||k._prefix;k._prefix=r.endsWith("-")?r:r+"-";const i=rt(t.getAttribute("data-runtime"));i!==null&&(k._runtime=i)}if(t instanceof HTMLScriptElement&&t.hasAttribute(`${k._prefix}dev`)){C.set(!0);return}const e=window.location.hostname;if(e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"||e.endsWith(".local")){C.set(!0);return}C.set(!1)}catch{}}static get prefix(){return k._prefix}};k._prefix="data-",k._runtime=W;let l=k;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class h{static info(t,...e){C.isEnabled()&&console.log&&console.log(t,...e)}static warn(t,...e){C.isEnabled()&&console.warn&&console.warn(t,...e)}static error(t,...e){console.error(t,...e)}}class it{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(t,e=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:t,timestamp:performance.now(),promise:s,resolve:r,reject:i};return e?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const t=performance.now();for(;this.queue.length>0;){const e=this.queue.shift();if(!e)return;try{const r=await e.task();e.resolve(r)}catch(r){e.reject(r),h.error("[Haori]",`Task ${e.timestamp} failed:`,r)}if(performance.now()-t>this.MAX_BUDGET)break}}catch(t){h.error("[Haori]","Error processing queue:",t)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const t=this.queue.map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}}const Q=class Q{static enqueue(t,e=!1){return this.ASYNC_QUEUE.enqueue(t,e)}static wait(){return this.ASYNC_QUEUE.wait()}};Q.ASYNC_QUEUE=new it;let P=Q;class q{static get runtime(){return l.runtime}static setRuntime(t){l.setRuntime(t)}static dialog(t){return P.enqueue(()=>{window.alert(t)},!0)}static async toast(t,e){const r=document.createElement("div");r.className=`haori-toast haori-toast-${e}`,r.textContent=t,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live","polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(t){return P.enqueue(()=>window.confirm(t),!0)}static openDialog(t){return P.enqueue(()=>{t instanceof HTMLDialogElement?t.showModal():h.error("[Haori]","Element is not a dialog: ",t)},!0)}static closeDialog(t){return P.enqueue(()=>{t instanceof HTMLDialogElement?t.close():h.error("[Haori]","Element is not a dialog: ",t)},!0)}static addErrorMessage(t,e){return P.enqueue(()=>{if(t instanceof HTMLFormElement){t.setAttribute("data-message",e);return}if(t.parentElement){t.parentElement.setAttribute("data-message",e);return}t.setAttribute("data-message",e)},!0)}static clearMessages(t){return P.enqueue(()=>{t.removeAttribute("data-message"),t.querySelectorAll("[data-message]").forEach(e=>{e.removeAttribute("data-message")})},!0)}}const st=["addErrorMessage","clearMessages"];function tt(){const t=globalThis.window?.Haori;return st.every(r=>typeof t?.[r]=="function")?t:q}class g{static getValues(t){const e={};return g.getPartValues(t,e)}static getPartValues(t,e){const r=t.getAttribute("name"),i=t.getAttribute(`${l.prefix}form-object`),s=t.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(e[String(r)])?e[String(r)].push(t.getValue()):e[String(r)]=[t.getValue()]:e[String(r)]=t.getValue(),i&&h.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of t.getChildElementFragments())g.getPartValues(n,e)}else if(i){const n={};for(const a of t.getChildElementFragments())g.getPartValues(a,n);Object.keys(n).length>0&&(e[String(i)]=n),s&&h.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of t.getChildElementFragments()){const o={};g.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(e[String(s)]=n)}else for(const n of t.getChildElementFragments())g.getPartValues(n,e);return e}static setValues(t,e,r=!1){return g.setPartValues(t,e,null,r,!0)}static syncValues(t,e,r=!1){return g.setPartValues(t,e,null,r,!1)}static applyFragmentValue(t,e,r){return r?t.setValue(e):t.syncBindingValue(e)}static setPartValues(t,e,r=null,i=!1,s=!0){const n=[],a=t.getAttribute("name"),o=t.getAttribute(`${l.prefix}form-object`),d=t.getAttribute(`${l.prefix}form-list`),y=t.getAttribute(`${l.prefix}form-detach`);if(a){if(!y||i){const b=e[String(a)];d&&Array.isArray(b)&&r!==null?n.push(g.applyFragmentValue(t,b[r]??null,s)):typeof b>"u"||(typeof b=="string"||typeof b=="number"||typeof b=="boolean"||b===null?n.push(g.applyFragmentValue(t,b,s)):n.push(g.applyFragmentValue(t,String(b),s)))}}else if(o){const b=e[String(o)];if(b&&typeof b=="object")for(const A of t.getChildElementFragments())n.push(g.setPartValues(A,b,null,i,s))}else if(d){const b=e[String(d)];if(Array.isArray(b)){const A=t.getChildElementFragments();for(let S=0;S<A.length;S++){const c=A[S];b.length>S?n.push(g.setPartValues(c,b[S],S,i,s)):n.push(g.setPartValues(c,{},S,i,s))}}}else for(const b of t.getChildElementFragments())n.push(g.setPartValues(b,e,null,i,s));return Promise.all(n).then(()=>{})}static async reset(t){g.clearValues(t),await Promise.all([g.clearMessages(t),g.clearEachClones(t)]),await P.enqueue(()=>{const e=t.getTarget();if(e instanceof HTMLFormElement)e.reset();else{const r=e.parentElement;if(r){const i=e.nextElementSibling,s=document.createElement("form");s.appendChild(e),s.reset(),r.insertBefore(e,i)}}}),await R.evaluateAll(t)}static clearEachClones(t){const e=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&e.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(t);for(const s of t.getChildElementFragments())i(s);return Promise.all(e).then(()=>{})}static clearValues(t){t.clearValue();for(const e of t.getChildElementFragments())g.clearValues(e)}static clearMessages(t){return tt().clearMessages(t.getTarget())}static addErrorMessage(t,e,r){const i=[],s=tt(),n=g.findFragmentsByKey(t,e);return n.forEach(a=>{i.push(s.addErrorMessage(a.getTarget(),r))}),n.length===0&&i.push(s.addErrorMessage(t.getTarget(),r)),Promise.all(i).then(()=>{})}static findFragmentsByKey(t,e){return g.findFragmentByKeyParts(t,e.split("."))}static findFragmentByKeyParts(t,e){const r=[],i=e[0];if(e.length==1&&t.getAttribute("name")===i&&r.push(t),t.hasAttribute(`${l.prefix}form-object`))e.length>1&&t.getAttribute(`${l.prefix}form-object`)===i&&t.getChildElementFragments().forEach(n=>{r.push(...g.findFragmentByKeyParts(n,e.slice(1)))});else if(t.hasAttribute(`${l.prefix}form-list`)){if(e.length>1){const s=t.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const d=i.substring(n+1,a),y=Number(d);if(isNaN(y))h.error("Haori",`Invalid index: ${i}`);else{const b=t.getChildElementFragments().filter(A=>A.hasAttribute(`${l.prefix}row`));y<b.length&&r.push(...g.findFragmentByKeyParts(b[y],e.slice(1)))}}}}}else t.getChildElementFragments().forEach(s=>{r.push(...g.findFragmentByKeyParts(s,e))});return r}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const r=t.getParent();return r?this.getFormFragment(r):null}}const x=class x{static getForbiddenBindingValues(){const t=globalThis,e=[t,t.window,t.document,t.navigator,t.history,t.localStorage,t.sessionStorage,t.fetch,t.Function,t.setTimeout,t.setInterval,t.requestAnimationFrame,t.alert,t.confirm,t.prompt];return t.window?.location&&e.push(t.window.location),e.filter(r=>r!=null)}static buildAssignments(t){const e=new Set(t);return this.FORBIDDEN_NAMES.filter(r=>!e.has(r)).map(r=>`const ${r} = undefined`).join(`;
|
|
2
2
|
`)}static evaluate(t,e={}){if(t.trim()==="")return h.warn("[Haori]",t,"Expression is empty"),null;if(this.containsDangerousPatterns(t))return h.warn("[Haori]",t,"Expression contains dangerous patterns"),null;if(this.containsForbiddenKeys(e))return h.warn("[Haori]",e,"Binded values contain forbidden keys"),null;if(this.containsForbiddenBindingValues(e))return h.warn("[Haori]",e,"Binded values contain forbidden values"),null;const r=Object.keys(e).filter(n=>!this.FORBIDDEN_BINDING_NAMES.has(n)).sort(),i=`${t}:${r.join(",")}`;let s=this.EXPRESSION_CACHE.get(i);if(!s){const n=this.buildAssignments(r),a=n?`"use strict";
|
|
3
3
|
${n};
|
|
4
4
|
return (${t});`:`"use strict";
|
|
5
5
|
return (${t});`;try{s=new Function(...r,a),this.EXPRESSION_CACHE.set(i,s)}catch(o){return h.error("[Haori]","Failed to compile expression:",t,o),null}}try{const n=[],a=this.wrapBoundValues(e);return r.forEach(o=>{n.push(a[o])}),this.withBlockedPropertyAccess(()=>s(...n))}catch(n){return h.error("[Haori]","Expression evaluation error:",t,n),n instanceof ReferenceError?void 0:null}}static containsDangerousPatterns(t){return this.hasAllowedSyntax(t)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(t)):!0}static hasAllowedSyntax(t){const e=this.tokenizeExpression(t);if(e===null||e.length===0)return!1;const r=[];let i=null;for(let s=0;s<e.length;s++){const n=e[s],a=e[s+1]||null,o=r[r.length-1]||null;if(n.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(n.value)||this.STRICT_FORBIDDEN_NAMES.includes(n.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value))||o==="member"&&n.value!=="]"&&n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value))||n.value==="."&&a?.type!=="identifier"||n.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(n.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const d=this.startsMemberAccess(i)?"member":"array";r.push(d);break}case"]":{if(r.pop()===void 0)return!1;break}}i=n}return r.length===0}static tokenizeExpression(t){const e=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<t.length;){const n=t[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(t[s+1]==="/"||t[s+1]==="*"))return null;if(n==='"'||n==="'"){const o=this.readStringToken(t,s);if(o===null)return null;e.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>t.startsWith(o,s));if(a){e.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(t,s);e.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(t,s);e.push(o.token),s=o.nextIndex;continue}if(i.has(n)){e.push({type:"operator",value:n,position:s}),s+=1;continue}return null}return e}static readStringToken(t,e){const r=t[e];let i=e+1;for(;i<t.length;){const s=t[i];if(s==="\\"){i+=2;continue}if(s===r)return{token:{type:"string",value:t.slice(e,i+1),position:e},nextIndex:i+1};i+=1}return null}static readNumberToken(t,e){let r=e;for(;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;if(t[r]===".")for(r+=1;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;return{token:{type:"number",value:t.slice(e,r),position:e},nextIndex:r}}static readIdentifierToken(t,e){let r=e;for(;r<t.length&&/[A-Za-z0-9_$]/.test(t[r]);)r+=1;return{token:{type:"identifier",value:t.slice(e,r),position:e},nextIndex:r}}static startsMemberAccess(t){return t===null?!1:t.type==="identifier"||t.type==="number"?!0:t.value===")"||t.value==="]"||t.value==="?."}static decodeStringLiteral(t){return t.slice(1,-1).replace(/\\u([0-9a-fA-F]{4})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(e,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
6
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(t){const e=new WeakMap,r={};return Object.entries(t).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,e)}),r}static wrapBoundValue(t,e){if(!this.shouldWrapValue(t))return t;const r=t,i=e.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const d=Reflect.get(n,a,o);return typeof a=="symbol"?d:this.wrapBoundValue(d,e)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const d=Reflect.apply(n,a,o);return this.isIteratorLike(d)?d:this.wrapBoundValue(d,e)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),e)});return e.set(r,s),s}static shouldWrapValue(t){if(typeof t=="function")return!0;if(t===null||typeof t!="object")return!1;if(Array.isArray(t))return!0;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}static withBlockedPropertyAccess(t){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return t()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(t){return t===null||typeof t!="object"?!1:typeof t.next=="function"}static containsForbiddenKeys(t){if(!t||typeof t!="object")return!1;for(const e of Object.keys(t))if(this.FORBIDDEN_BINDING_NAMES.has(e))return!0;return!1}static containsForbiddenBindingValues(t,e=new WeakSet){if(!t||typeof t!="object"||e.has(t))return!1;if(e.add(t),this.getForbiddenBindingValues().some(r=>r===t))return!0;for(const r of Object.values(t)){if(typeof r=="function"){if(this.getForbiddenBindingValues().some(i=>i===r))return!0;continue}if(this.containsForbiddenBindingValues(r,e))return!0}return!1}};M.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],M.STRICT_FORBIDDEN_NAMES=["eval","arguments"],M.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),M.FORBIDDEN_BINDING_NAMES=new Set([...M.FORBIDDEN_NAMES.filter(t=>!M.REBINDABLE_FORBIDDEN_NAMES.has(t)),"constructor","__proto__","prototype",...M.STRICT_FORBIDDEN_NAMES]),M.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),M.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),M.EXPRESSION_CACHE=new Map;let L=M;const $=class ${constructor(t){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=t,$.FRAGMENT_CACHE.set(t,this)}static get(t){if(t==null)return null;if($.FRAGMENT_CACHE.has(t))return $.FRAGMENT_CACHE.get(t);let e;switch(t.nodeType){case Node.ELEMENT_NODE:e=new x(t);break;case Node.TEXT_NODE:e=new j(t);break;case Node.COMMENT_NODE:e=new z(t);break;default:return h.warn("[Haori]","Unsupported node type:",t.nodeType),null}return e}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return F.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode===t.getTarget()&&t.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{t.skipMutationNodes=e})}else{const t=this.target.parentNode;if(t)return F.enqueue(()=>{this.target.parentNode===t&&t.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return F.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode!==t.getTarget()&&t.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{t.skipMutationNodes=e})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(t){this.mounted=t}remove(t=!0){return this.parent&&this.parent.removeChild(this),$.FRAGMENT_CACHE.delete(this.target),t?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(t){this.parent=t}};$.FRAGMENT_CACHE=new WeakMap;let w=$;class x extends w{constructor(t){super(t),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingDataCache=null,this.visible=!0,this.display=null,this.template=null,this.listKey=null,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),t.getAttributeNames().forEach(e=>{const r=t.getAttribute(e);if(r!==null&&!this.attributeMap.has(e)){const i=new G(e,r);this.attributeMap.set(e,i)}}),t.childNodes.forEach(e=>{const r=w.get(e);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(t=>t instanceof x)}pushChild(t){this.children.push(t),t.setParent(this)}removeChild(t){const e=this.children.indexOf(t);if(e<0){h.warn("[Haori]","Child fragment not found.",t);return}this.children.splice(e,1),t.setParent(null)}clone(){const t=new x(this.target.cloneNode(!1));return this.attributeMap.forEach((e,r)=>{t.attributeMap.set(r,e)}),this.children.forEach(e=>{const r=e.clone();t.getTarget().appendChild(r.getTarget()),t.pushChild(r)}),t.mounted=!1,t.bindingData=this.bindingData,t.clearBindingDataCache(),t.visible=this.visible,t.display=this.display,t.template=this.template,t}remove(t=!0){const e=[];return this.children.forEach(r=>{e.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.template&&(e.push(this.template.remove(!1)),this.template=null),e.push(super.remove(t)),Promise.all(e).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getRawBindingData(){return this.bindingData}setBindingData(t){this.bindingData=t,this.clearBindingDataCache()}setParent(t){this.parent!==t&&(this.parent=t,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.children.forEach(t=>{t instanceof x&&t.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(t){this.template=t}setListKey(t){this.listKey=t}getListKey(){return this.listKey}setValue(t){return this.applyValue(t,!0)}syncBindingValue(t){return this.applyValue(t,!1)}applyValue(t,e){if(this.skipChangeValue||this.value===t)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=t===!0||t==="true":i==="false"?n=t===!1:n=i===String(t),this.value=s?n:n?t:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,F.enqueue(()=>{r.checked=n,e&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=t,this.skipChangeValue=!0,F.enqueue(()=>{r.value=t===null?"":String(t),e&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})):(h.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}syncValue(){const t=this.getTarget();if(t instanceof HTMLInputElement)if(t.type==="checkbox"||t.type==="radio"){const e=t.type==="checkbox"&&t.value==="true";if(t.checked){const r=t.value;e?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=t.value;e?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=t.value;else t instanceof HTMLTextAreaElement?this.value=t.value:t instanceof HTMLSelectElement&&(this.value=t.value)}setAttribute(t,e){if(this.skipMutationAttributes)return Promise.resolve();if(e===null)return this.removeAttribute(t);const r=new G(t,e);this.attributeMap.set(t,r),this.skipMutationAttributes=!0;const i=this.getTarget(),s=r.isForceEvaluation()?e:this.getAttribute(t);return F.enqueue(()=>{if(s===null||s===!1)i.removeAttribute(t);else{const n=String(s);i.getAttribute(t)!==n&&i.setAttribute(t,n),t==="value"&&(i instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&(this.value=n,i.value!==n&&(i.value=n))}}).finally(()=>{this.skipMutationAttributes=!1})}removeAttribute(t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const e=this.getTarget();return F.enqueue(()=>{e.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(t){const e=this.attributeMap.get(t);if(e===void 0)return null;const r=e.evaluate(this.getBindingData());return r.length===1?r[0]:H.joinEvaluateResults(r)}getRawAttribute(t){const e=this.attributeMap.get(t);return e===void 0?null:e.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(t){return this.attributeMap.has(t)}resolveInsertionPointFromDom(t,e){const r=t.getTarget();if(r.parentNode!==this.target)return null;const i=e?r.nextSibling:r;let s=e?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(t,e,r){if(this.skipMutationNodes)return Promise.resolve();if(t===this)return h.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(t))return h.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=t.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(t),e!==null&&(o=this.children.indexOf(e)));const d=t.getParent();d!==null&&d.removeChild(t);let y=r===void 0?e?.getTarget()||null:r;if(e===null)this.children.push(t);else{let v;if(n?a!==-1&&a<o?v=o-1:v=o:v=this.children.indexOf(e),v===-1){const f=this.resolveInsertionPointFromDom(e,!1);f===null?(h.warn("[Haori]","Reference child not found in children.",e),this.children.push(t)):(this.children.splice(f.index,0,t),y=f.referenceNode)}else this.children.splice(v,0,t)}t.setParent(this),t.setMounted(this.mounted);const b=this.skipMutationNodes;return this.skipMutationNodes=!0,F.enqueue(()=>{this.target.insertBefore(t.getTarget(),y)}).finally(()=>{this.skipMutationNodes=b})}insertAfter(t,e){if(e==null)return this.insertBefore(t,null);const r=this.children.indexOf(e);if(r===-1){const i=this.resolveInsertionPointFromDom(e,!0);return i===null?(h.warn("[Haori]","Reference child not found in children.",e),this.insertBefore(t,null)):this.insertBefore(t,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(t,this.children[r+1]||null)}getPrevious(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<=0?null:e[r-1]}getNext(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<0||r+1>=e.length?null:e[r+1]}isVisible(){return this.visible}hide(){return this.visible=!1,this.display=this.getTarget().style.display,this.getTarget().style.display="none",this.getTarget().setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){return this.getTarget().style.display=this.display??"",this.getTarget().removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(t){if(this.hasAttribute(t))return this;const e=this.getParent();return e===null?null:e.closestByAttribute(t)}}class j extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||"",this.contents=new H(this.text)}clone(){const t=new j(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t.contents=this.contents,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,this.contents=new H(t),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):F.enqueue(()=>{this.skipMutation=!0,this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=this.contents.evaluate(this.parent.getBindingData())[0]:this.contents.isEvaluate?this.target.textContent=H.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData())):this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1})}}class z extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||""}clone(){const t=new z(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,F.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const J=class J{constructor(t){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=t;const e=[...t.matchAll(J.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of e){n.index>r&&this.contents.push({text:t.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<t.length&&this.contents.push({text:t.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(t){return t===null||t.length===0?"":t.map(e=>e==null||e===!1||Number.isNaN(e)?"":typeof e!="string"?String(e):e).join("")}getValue(){return this.value}checkRawExpressions(){for(let t=0;t<this.contents.length;t++)this.contents[t].type===2&&this.contents.length>1&&(h.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[t].type=1)}evaluate(t){if(!this.isEvaluate&&!this.isRawEvaluate)return this.contents.map(r=>r.text);const e=[];return this.contents.forEach(r=>{try{if(r.type===1||r.type===2){const i=L.evaluate(r.text,t);e.push(i)}else e.push(r.text)}catch(i){h.error("[Haori]",`Error evaluating text expression: ${r.text}`,i),e.push("")}}),e}};J.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let H=J;const X=class X extends H{constructor(t,e){super(e),this.forceEvaluation=X.FORCE_EVALUATION_ATTRIBUTES.includes(t)}isForceEvaluation(){return this.forceEvaluation}evaluate(t){if(!this.isEvaluate&&!this.forceEvaluation)return this.contents.map(r=>r.text);const e=[];return this.contents.forEach(r=>{try{if(this.forceEvaluation&&r.type===0||r.type===1||r.type===2){const i=L.evaluate(r.text,t);e.push(i)}else e.push(r.text)}catch(i){h.error("[Haori]",`Error evaluating attribute expression: ${r.text}`,i),e.push("")}}),this.forceEvaluation&&e.length>1?(h.error("[Haori]","each or if expressions must have a single content.",e),[e[0]]):e}};X.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each"];let G=X;class T{static dispatch(t,e,r,i){const s=new CustomEvent(`haori:${e}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return t.dispatchEvent(s)}static ready(t){T.dispatch(document,"ready",{version:t})}static render(t){T.dispatch(t,"render",{target:t})}static importStart(t,e){T.dispatch(t,"importstart",{url:e,startedAt:performance.now()})}static importEnd(t,e,r,i){T.dispatch(t,"importend",{url:e,bytes:r,durationMs:performance.now()-i})}static importError(t,e,r){T.dispatch(t,"importerror",{url:e,error:r})}static bindChange(t,e,r,i="other"){const s=[],n=new Set(Object.keys(e||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const d of o){const y=e?.[d],b=r[d];y!==b&&s.push(d)}T.dispatch(t,"bindchange",{previous:e||{},next:r,changedKeys:s,reason:i})}static eachUpdate(t,e,r,i){T.dispatch(t,"eachupdate",{added:e,removed:r,order:i,total:i.length})}static rowAdd(t,e,r,i){T.dispatch(t,"rowadd",{key:e,index:r,item:i})}static rowRemove(t,e,r){T.dispatch(t,"rowremove",{key:e,index:r})}static rowMove(t,e,r,i){T.dispatch(t,"rowmove",{key:e,from:r,to:i})}static show(t){T.dispatch(t,"show",{visible:!0})}static hide(t){T.dispatch(t,"hide",{visible:!1})}static fetchStart(t,e,r,i,s){T.dispatch(t,"fetchstart",{url:e,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(t,e,r,i){T.dispatch(t,"fetchend",{url:e,status:r,durationMs:performance.now()-i})}static fetchError(t,e,r,i,s){T.dispatch(t,"fetcherror",{url:e,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const st=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"];function Q(){const t=globalThis.window?.Haori;return st.every(r=>typeof t?.[r]=="function")?t:q}const nt=new Set(["GET","HEAD","OPTIONS"]);function at(S){return nt.has(S.toUpperCase())}function ot(S,t){for(const[e,r]of Object.entries(t))r!==void 0&&(r===null?S.append(e,""):Array.isArray(r)?r.forEach(i=>{S.append(e,String(i))}):typeof r=="object"||typeof r=="function"?S.append(e,JSON.stringify(r)):S.append(e,String(r)))}function lt(S,t){const e=new URL(S,window.location.href),r=new URLSearchParams(e.search);return ot(r,t),e.search=r.toString(),e.toString()}const c=class c{static attrName(t,e,r=!1){return t?`${l.prefix}${t}-${e}`:r?`${l.prefix}fetch-${e}`:`${l.prefix}${e}`}static resolveDataParamString(t,e){return t.replace(c.DATA_PLACEHOLDER_REGEX,(r,i,s)=>{const n=L.evaluate(i??s??"",e);return n==null||Number.isNaN(n)?"":encodeURIComponent(typeof n=="object"?JSON.stringify(n):String(n))})}static isJsonStringContext(t,e){let r=!1,i=!1;for(let s=0;s<e;s+=1){const n=t[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(t){if(t===void 0||Number.isNaN(t))return"null";try{return JSON.stringify(t)??JSON.stringify(String(t))}catch{return JSON.stringify(String(t))}}static stringifyJsonTemplateStringContent(t){if(t==null||Number.isNaN(t))return"";const e=typeof t=="object"?c.stringifyJsonTemplateValue(t):String(t);return JSON.stringify(e).slice(1,-1)}static resolveDataJsonString(t,e){return t.replace(c.DATA_PLACEHOLDER_REGEX,(r,i,s,n)=>{const a=L.evaluate(i??s??"",e);return c.isJsonStringContext(t,n)?c.stringifyJsonTemplateStringContent(a):c.stringifyJsonTemplateValue(a)})}static resolveDataAttribute(t,e){const r=t.getRawAttribute(e),i=t.getAttribute(e);if(i&&typeof i=="object"&&!Array.isArray(i))return i;if(typeof i!="string"||r===null)return null;const s=r.trim();return c.SINGLE_PLACEHOLDER_REGEX.test(s)?R.parseDataBind(i):s.startsWith("{")||s.startsWith("[")?R.parseDataBind(c.resolveDataJsonString(r,t.getBindingData())):R.parseDataBind(c.resolveDataParamString(r,t.getBindingData()))}static buildOptions(t,e){const r={targetFragment:t};if(e){if(t.hasAttribute(c.attrName(e,"validate"))&&(r.valid=!0),t.hasAttribute(c.attrName(e,"confirm"))&&(r.confirmMessage=t.getAttribute(c.attrName(e,"confirm"))),t.hasAttribute(c.attrName(e,"data"))&&(r.data=c.resolveDataAttribute(t,c.attrName(e,"data"))),t.hasAttribute(c.attrName(e,"form"))){const f=t.getRawAttribute(c.attrName(e,"form"));if(f){const u=document.body.querySelector(f);u!==null?r.formFragment=m.getFormFragment(w.get(u)):h.error("Haori",`Form element not found: ${f} (${c.attrName(e,"form")})`)}else r.formFragment=m.getFormFragment(t)}else e==="change"&&(r.formFragment=m.getFormFragment(t));if(t.hasAttribute(`${l.prefix}${e}-before-run`)){const f=t.getRawAttribute(`${l.prefix}${e}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
6
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(t){const e=new WeakMap,r={};return Object.entries(t).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,e)}),r}static wrapBoundValue(t,e){if(!this.shouldWrapValue(t))return t;const r=t,i=e.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const d=Reflect.get(n,a,o);return typeof a=="symbol"?d:this.wrapBoundValue(d,e)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const d=Reflect.apply(n,a,o);return this.isIteratorLike(d)?d:this.wrapBoundValue(d,e)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),e)});return e.set(r,s),s}static shouldWrapValue(t){if(typeof t=="function")return!0;if(t===null||typeof t!="object")return!1;if(Array.isArray(t))return!0;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}static withBlockedPropertyAccess(t){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return t()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(t){return t===null||typeof t!="object"?!1:typeof t.next=="function"}static containsForbiddenKeys(t){if(!t||typeof t!="object")return!1;for(const e of Object.keys(t))if(this.FORBIDDEN_BINDING_NAMES.has(e))return!0;return!1}static containsForbiddenBindingValues(t,e=new WeakSet){if(!t||typeof t!="object"||e.has(t))return!1;if(e.add(t),this.getForbiddenBindingValues().some(r=>r===t))return!0;for(const r of Object.values(t)){if(typeof r=="function"){if(this.getForbiddenBindingValues().some(i=>i===r))return!0;continue}if(this.containsForbiddenBindingValues(r,e))return!0}return!1}};x.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],x.STRICT_FORBIDDEN_NAMES=["eval","arguments"],x.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),x.FORBIDDEN_BINDING_NAMES=new Set([...x.FORBIDDEN_NAMES.filter(t=>!x.REBINDABLE_FORBIDDEN_NAMES.has(t)),"constructor","__proto__","prototype",...x.STRICT_FORBIDDEN_NAMES]),x.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),x.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),x.EXPRESSION_CACHE=new Map;let L=x;const I=class I{constructor(t){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=t,I.FRAGMENT_CACHE.set(t,this)}static get(t){if(t==null)return null;if(I.FRAGMENT_CACHE.has(t))return I.FRAGMENT_CACHE.get(t);let e;switch(t.nodeType){case Node.ELEMENT_NODE:e=new D(t);break;case Node.TEXT_NODE:e=new j(t);break;case Node.COMMENT_NODE:e=new Y(t);break;default:return h.warn("[Haori]","Unsupported node type:",t.nodeType),null}return e}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return P.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode===t.getTarget()&&t.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{t.skipMutationNodes=e})}else{const t=this.target.parentNode;if(t)return P.enqueue(()=>{this.target.parentNode===t&&t.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return P.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode!==t.getTarget()&&t.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{t.skipMutationNodes=e})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(t){this.mounted=t}remove(t=!0){return this.parent&&this.parent.removeChild(this),I.FRAGMENT_CACHE.delete(this.target),t?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(t){this.parent=t}};I.FRAGMENT_CACHE=new WeakMap;let w=I;class D extends w{constructor(t){super(t),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingDataCache=null,this.visible=!0,this.display=null,this.template=null,this.listKey=null,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),t.getAttributeNames().forEach(e=>{const r=t.getAttribute(e);if(r!==null&&!this.attributeMap.has(e)){const i=new G(e,r);this.attributeMap.set(e,i)}}),t.childNodes.forEach(e=>{const r=w.get(e);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(t=>t instanceof D)}pushChild(t){this.children.push(t),t.setParent(this)}removeChild(t){const e=this.children.indexOf(t);if(e<0){h.warn("[Haori]","Child fragment not found.",t);return}this.children.splice(e,1),t.setParent(null)}clone(){const t=new D(this.target.cloneNode(!1));return this.attributeMap.forEach((e,r)=>{t.attributeMap.set(r,e)}),this.children.forEach(e=>{const r=e.clone();t.getTarget().appendChild(r.getTarget()),t.pushChild(r)}),t.mounted=!1,t.bindingData=this.bindingData,t.clearBindingDataCache(),t.visible=this.visible,t.display=this.display,t.template=this.template,t}remove(t=!0){const e=[];return this.children.forEach(r=>{e.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.template&&(e.push(this.template.remove(!1)),this.template=null),e.push(super.remove(t)),Promise.all(e).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getRawBindingData(){return this.bindingData}setBindingData(t){this.bindingData=t,this.clearBindingDataCache()}setParent(t){this.parent!==t&&(this.parent=t,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.children.forEach(t=>{t instanceof D&&t.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(t){this.template=t}setListKey(t){this.listKey=t}getListKey(){return this.listKey}setValue(t){return this.applyValue(t,!0)}syncBindingValue(t){return this.applyValue(t,!1)}applyValue(t,e){if(this.skipChangeValue||this.value===t)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=t===!0||t==="true":i==="false"?n=t===!1:n=i===String(t),this.value=s?n:n?t:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=n,e&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=t,this.skipChangeValue=!0,P.enqueue(()=>{r.value=t===null?"":String(t),e&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})):(h.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}syncValue(){const t=this.getTarget();if(t instanceof HTMLInputElement)if(t.type==="checkbox"||t.type==="radio"){const e=t.type==="checkbox"&&t.value==="true";if(t.checked){const r=t.value;e?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=t.value;e?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=t.value;else t instanceof HTMLTextAreaElement?this.value=t.value:t instanceof HTMLSelectElement&&(this.value=t.value)}setAttribute(t,e){if(this.skipMutationAttributes)return Promise.resolve();if(e===null)return this.removeAttribute(t);const r=new G(t,e);this.attributeMap.set(t,r),this.skipMutationAttributes=!0;const i=this.getTarget(),s=r.isForceEvaluation()?e:this.getAttribute(t);return P.enqueue(()=>{if(s===null||s===!1)i.removeAttribute(t);else{const n=String(s);i.getAttribute(t)!==n&&i.setAttribute(t,n),t==="value"&&(i instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&(this.value=n,i.value!==n&&(i.value=n))}}).finally(()=>{this.skipMutationAttributes=!1})}removeAttribute(t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const e=this.getTarget();return P.enqueue(()=>{e.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(t){const e=this.attributeMap.get(t);if(e===void 0)return null;const r=e.evaluate(this.getBindingData());return r.length===1?r[0]:H.joinEvaluateResults(r)}getRawAttribute(t){const e=this.attributeMap.get(t);return e===void 0?null:e.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(t){return this.attributeMap.has(t)}resolveInsertionPointFromDom(t,e){const r=t.getTarget();if(r.parentNode!==this.target)return null;const i=e?r.nextSibling:r;let s=e?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(t,e,r){if(this.skipMutationNodes)return Promise.resolve();if(t===this)return h.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(t))return h.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=t.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(t),e!==null&&(o=this.children.indexOf(e)));const d=t.getParent();d!==null&&d.removeChild(t);let y=r===void 0?e?.getTarget()||null:r;if(e===null)this.children.push(t);else{let A;if(n?a!==-1&&a<o?A=o-1:A=o:A=this.children.indexOf(e),A===-1){const S=this.resolveInsertionPointFromDom(e,!1);S===null?(h.warn("[Haori]","Reference child not found in children.",e),this.children.push(t)):(this.children.splice(S.index,0,t),y=S.referenceNode)}else this.children.splice(A,0,t)}t.setParent(this),t.setMounted(this.mounted);const b=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(t.getTarget(),y)}).finally(()=>{this.skipMutationNodes=b})}insertAfter(t,e){if(e==null)return this.insertBefore(t,null);const r=this.children.indexOf(e);if(r===-1){const i=this.resolveInsertionPointFromDom(e,!0);return i===null?(h.warn("[Haori]","Reference child not found in children.",e),this.insertBefore(t,null)):this.insertBefore(t,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(t,this.children[r+1]||null)}getPrevious(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<=0?null:e[r-1]}getNext(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<0||r+1>=e.length?null:e[r+1]}isVisible(){return this.visible}hide(){return this.visible=!1,this.display=this.getTarget().style.display,this.getTarget().style.display="none",this.getTarget().setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){return this.getTarget().style.display=this.display??"",this.getTarget().removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(t){if(this.hasAttribute(t))return this;const e=this.getParent();return e===null?null:e.closestByAttribute(t)}}class j extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||"",this.contents=new H(this.text)}clone(){const t=new j(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t.contents=this.contents,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,this.contents=new H(t),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0,this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=this.contents.evaluate(this.parent.getBindingData())[0]:this.contents.isEvaluate?this.target.textContent=H.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData())):this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1})}}class Y extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||""}clone(){const t=new Y(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const J=class J{constructor(t){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=t;const e=[...t.matchAll(J.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of e){n.index>r&&this.contents.push({text:t.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<t.length&&this.contents.push({text:t.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(t){return t===null||t.length===0?"":t.map(e=>e==null||e===!1||Number.isNaN(e)?"":typeof e!="string"?String(e):e).join("")}getValue(){return this.value}checkRawExpressions(){for(let t=0;t<this.contents.length;t++)this.contents[t].type===2&&this.contents.length>1&&(h.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[t].type=1)}evaluate(t){if(!this.isEvaluate&&!this.isRawEvaluate)return this.contents.map(r=>r.text);const e=[];return this.contents.forEach(r=>{try{if(r.type===1||r.type===2){const i=L.evaluate(r.text,t);e.push(i)}else e.push(r.text)}catch(i){h.error("[Haori]",`Error evaluating text expression: ${r.text}`,i),e.push("")}}),e}};J.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let H=J;const X=class X extends H{constructor(t,e){super(e),this.forceEvaluation=X.FORCE_EVALUATION_ATTRIBUTES.includes(t)}isForceEvaluation(){return this.forceEvaluation}evaluate(t){if(!this.isEvaluate&&!this.forceEvaluation)return this.contents.map(r=>r.text);const e=[];return this.contents.forEach(r=>{try{if(this.forceEvaluation&&r.type===0||r.type===1||r.type===2){const i=L.evaluate(r.text,t);e.push(i)}else e.push(r.text)}catch(i){h.error("[Haori]",`Error evaluating attribute expression: ${r.text}`,i),e.push("")}}),this.forceEvaluation&&e.length>1?(h.error("[Haori]","each or if expressions must have a single content.",e),[e[0]]):e}};X.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each"];let G=X;class T{static dispatch(t,e,r,i){const s=new CustomEvent(`haori:${e}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return t.dispatchEvent(s)}static ready(t){T.dispatch(document,"ready",{version:t})}static render(t){T.dispatch(t,"render",{target:t})}static importStart(t,e){T.dispatch(t,"importstart",{url:e,startedAt:performance.now()})}static importEnd(t,e,r,i){T.dispatch(t,"importend",{url:e,bytes:r,durationMs:performance.now()-i})}static importError(t,e,r){T.dispatch(t,"importerror",{url:e,error:r})}static bindChange(t,e,r,i="other"){const s=[],n=new Set(Object.keys(e||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const d of o){const y=e?.[d],b=r[d];y!==b&&s.push(d)}T.dispatch(t,"bindchange",{previous:e||{},next:r,changedKeys:s,reason:i})}static eachUpdate(t,e,r,i){T.dispatch(t,"eachupdate",{added:e,removed:r,order:i,total:i.length})}static rowAdd(t,e,r,i){T.dispatch(t,"rowadd",{key:e,index:r,item:i})}static rowRemove(t,e,r){T.dispatch(t,"rowremove",{key:e,index:r})}static rowMove(t,e,r,i){T.dispatch(t,"rowmove",{key:e,from:r,to:i})}static show(t){T.dispatch(t,"show",{visible:!0})}static hide(t){T.dispatch(t,"hide",{visible:!1})}static fetchStart(t,e,r,i,s){T.dispatch(t,"fetchstart",{url:e,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(t,e,r,i){T.dispatch(t,"fetchend",{url:e,status:r,durationMs:performance.now()-i})}static fetchError(t,e,r,i,s){T.dispatch(t,"fetcherror",{url:e,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const nt=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"];function z(){const t=globalThis.window?.Haori;return nt.every(r=>typeof t?.[r]=="function")?t:q}const at=new Set(["GET","HEAD","OPTIONS"]);function ot(F){return at.has(F.toUpperCase())}function lt(F,t){for(const[e,r]of Object.entries(t))r!==void 0&&(r===null?F.append(e,""):Array.isArray(r)?r.forEach(i=>{F.append(e,String(i))}):typeof r=="object"||typeof r=="function"?F.append(e,JSON.stringify(r)):F.append(e,String(r)))}function ct(F,t){const e=new URL(F,window.location.href),r=new URLSearchParams(e.search);return lt(r,t),e.search=r.toString(),e.toString()}const u=class u{static attrName(t,e,r=!1){return t?`${l.prefix}${t}-${e}`:r?`${l.prefix}fetch-${e}`:`${l.prefix}${e}`}static resolveDataParamString(t,e){return t.replace(u.DATA_PLACEHOLDER_REGEX,(r,i,s)=>{const n=L.evaluate(i??s??"",e);return n==null||Number.isNaN(n)?"":encodeURIComponent(typeof n=="object"?JSON.stringify(n):String(n))})}static isJsonStringContext(t,e){let r=!1,i=!1;for(let s=0;s<e;s+=1){const n=t[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(t){if(t===void 0||Number.isNaN(t))return"null";try{return JSON.stringify(t)??JSON.stringify(String(t))}catch{return JSON.stringify(String(t))}}static stringifyJsonTemplateStringContent(t){if(t==null||Number.isNaN(t))return"";const e=typeof t=="object"?u.stringifyJsonTemplateValue(t):String(t);return JSON.stringify(e).slice(1,-1)}static resolveDataJsonString(t,e){return t.replace(u.DATA_PLACEHOLDER_REGEX,(r,i,s,n)=>{const a=L.evaluate(i??s??"",e);return u.isJsonStringContext(t,n)?u.stringifyJsonTemplateStringContent(a):u.stringifyJsonTemplateValue(a)})}static resolveDataAttribute(t,e){const r=t.getRawAttribute(e),i=t.getAttribute(e);if(i&&typeof i=="object"&&!Array.isArray(i))return i;if(typeof i!="string"||r===null)return null;const s=r.trim();return u.SINGLE_PLACEHOLDER_REGEX.test(s)?R.parseDataBind(i):s.startsWith("{")||s.startsWith("[")?R.parseDataBind(u.resolveDataJsonString(r,t.getBindingData())):R.parseDataBind(u.resolveDataParamString(r,t.getBindingData()))}static buildOptions(t,e){const r={targetFragment:t};if(e){if(t.hasAttribute(u.attrName(e,"validate"))&&(r.valid=!0),t.hasAttribute(u.attrName(e,"confirm"))&&(r.confirmMessage=t.getAttribute(u.attrName(e,"confirm"))),t.hasAttribute(u.attrName(e,"data"))&&(r.data=u.resolveDataAttribute(t,u.attrName(e,"data"))),t.hasAttribute(u.attrName(e,"form"))){const c=t.getRawAttribute(u.attrName(e,"form"));if(c){const f=document.body.querySelector(c);f!==null?r.formFragment=g.getFormFragment(w.get(f)):h.error("Haori",`Form element not found: ${c} (${u.attrName(e,"form")})`)}else r.formFragment=g.getFormFragment(t)}else e==="change"&&(r.formFragment=g.getFormFragment(t));if(t.hasAttribute(`${l.prefix}${e}-before-run`)){const c=t.getRawAttribute(`${l.prefix}${e}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
7
7
|
"use strict";
|
|
8
|
-
${
|
|
9
|
-
`)}catch(
|
|
8
|
+
${c}
|
|
9
|
+
`)}catch(f){h.error("Haori",`Invalid before script: ${f}`)}}}const i=u.attrName(e,"fetch"),s=t.hasAttribute(i);s&&(r.fetchUrl=t.getAttribute(i));const n={};if(e){const c=u.attrName(e,"fetch-method");t.hasAttribute(c)&&(n.method=t.getAttribute(c))}else{const c=u.attrName(null,"method",!0);t.hasAttribute(c)&&(n.method=t.getAttribute(c))}if(e){const c=u.attrName(e,"fetch-headers");if(t.hasAttribute(c)){const f=t.getRawAttribute(c);try{n.headers=R.parseDataBind(f)}catch(p){h.error("Haori",`Invalid fetch headers: ${p}`)}}}else{const c=u.attrName(null,"headers",!0);if(t.hasAttribute(c)){const f=t.getRawAttribute(c);try{n.headers=R.parseDataBind(f)}catch(p){h.error("Haori",`Invalid fetch headers: ${p}`)}}}if(e){const c=u.attrName(e,"fetch-content-type");if(t.hasAttribute(c))n.headers={...n.headers,"Content-Type":t.getAttribute(c)};else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let f=!1;n.headers&&typeof n.headers=="object"&&(f="Content-Type"in n.headers),f||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const c=u.attrName(null,"content-type",!0);if(t.hasAttribute(c))n.headers={...n.headers,"Content-Type":t.getAttribute(c)};else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let f=!1;n.headers&&typeof n.headers=="object"&&(f="Content-Type"in n.headers),f||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(n).length>0&&(r.fetchOptions=n);const a=e?u.attrName(e,"bind"):u.attrName(null,"bind",!0);if(t.hasAttribute(a)){const c=t.getRawAttribute(a);if(c){const f=document.body.querySelectorAll(c);f.length>0?(r.bindFragments=[],f.forEach(p=>{const E=w.get(p);E&&r.bindFragments.push(E)})):h.error("Haori",`Bind element not found: ${c} (${a})`)}}const o=u.attrName(e,"bind-arg"),d=u.attrName(null,"arg",!0),y=u.attrName(null,"bind-arg",!0);e?t.hasAttribute(o)&&(r.bindArg=t.getRawAttribute(o)):t.hasAttribute(d)?r.bindArg=t.getRawAttribute(d):t.hasAttribute(y)&&(r.bindArg=t.getRawAttribute(y));const b=e?u.attrName(e,"bind-params"):u.attrName(null,"bind-params",!0);if(t.hasAttribute(b)){const c=t.getRawAttribute(b);r.bindParams=c.split("&").map(f=>f.trim())}const A=e?u.attrName(e,"bind-append"):u.attrName(null,"bind-append",!0);if(t.hasAttribute(A)){const c=t.getRawAttribute(A);r.bindAppendParams=c.split("&").map(f=>f.trim()).filter(Boolean)}const S=e?u.attrName(e,"copy-params"):null;if(S&&t.hasAttribute(S)){const c=t.getRawAttribute(S);r.copyParams=c.split("&").map(f=>f.trim()).filter(Boolean)}if(e){if(t.hasAttribute(u.attrName(e,"adjust"))){const f=t.getRawAttribute(u.attrName(e,"adjust"));if(f){const p=document.body.querySelectorAll(f);p.length>0?(r.adjustFragments=[],p.forEach(E=>{const v=w.get(E);v&&r.adjustFragments.push(v)})):h.error("Haori",`Adjust element not found: ${f} (${u.attrName(e,"adjust")})`)}if(t.hasAttribute(u.attrName(e,"adjust-value"))){const p=t.getRawAttribute(u.attrName(e,"adjust-value")),E=Number(p);isNaN(E)||(r.adjustValue=E)}}if(t.hasAttribute(u.attrName(e,"row-add"))&&(r.rowAdd=!0),t.hasAttribute(u.attrName(e,"row-remove"))&&(r.rowRemove=!0),t.hasAttribute(u.attrName(e,"row-prev"))&&(r.rowMovePrev=!0),t.hasAttribute(u.attrName(e,"row-next"))&&(r.rowMoveNext=!0),t.hasAttribute(`${l.prefix}${e}-after-run`)){const f=t.getRawAttribute(`${l.prefix}${e}-after-run`);try{r.afterCallback=new Function("response",`
|
|
10
10
|
"use strict";
|
|
11
|
-
${
|
|
12
|
-
`)}catch(
|
|
11
|
+
${f}
|
|
12
|
+
`)}catch(p){h.error("Haori",`Invalid after script: ${p}`)}}if(t.hasAttribute(u.attrName(e,"dialog"))&&(r.dialogMessage=t.getAttribute(u.attrName(e,"dialog"))),t.hasAttribute(u.attrName(e,"toast"))&&(r.toastMessage=t.getAttribute(u.attrName(e,"toast"))),t.hasAttribute(u.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(u.attrName(e,"redirect"))),t.hasAttribute(u.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(u.attrName(e,"history"))),t.hasAttribute(u.attrName(e,"history-data"))&&(r.historyData=u.resolveDataAttribute(t,u.attrName(e,"history-data"))),t.hasAttribute(u.attrName(e,"history-form"))){const f=t.getRawAttribute(u.attrName(e,"history-form"));if(f){const p=document.body.querySelector(f);p!==null?r.historyFormFragment=g.getFormFragment(w.get(p)):h.error("Haori",`Form element not found: ${f} (${u.attrName(e,"history-form")})`)}else r.historyFormFragment=g.getFormFragment(t)}["reset","refetch","click","copy","open","close"].forEach(f=>{const p=u.attrName(e,f);if(!t.hasAttribute(p))return;const E=t.getRawAttribute(p),v=[];if(E?(document.body.querySelectorAll(E).forEach(Z=>{const et=w.get(Z);et&&v.push(et)}),v.length===0&&h.error("Haori",`Element not found: ${E} (${p})`)):v.push(t),v.length>0)switch(f){case"reset":r.resetFragments=v;break;case"refetch":r.refetchFragments=v;break;case"click":r.clickFragments=v;break;case"copy":r.copyFragments=v;break;case"open":r.openFragments=v;break;case"close":r.closeFragments=v;break}})}if(!e&&(t.hasAttribute(u.attrName(null,"data",!0))&&(r.data=u.resolveDataAttribute(t,u.attrName(null,"data",!0))),t.hasAttribute(u.attrName(null,"form",!0)))){const c=t.getRawAttribute(u.attrName(null,"form",!0));if(c){const f=document.body.querySelector(c);f!==null?r.formFragment=g.getFormFragment(w.get(f)):h.error("Haori",`Form element not found: ${c} (${u.attrName(null,"fetch-form",!0)})`)}else r.formFragment=g.getFormFragment(t)}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t]),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}constructor(t,e=null){u.isElementFragment(t)?this.options=u.buildOptions(t,e):this.options=t}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1||!await this.confirm())return!1;let e=this.options.fetchUrl,r=this.options.fetchOptions;if(this.options.beforeCallback){const o=this.options.beforeCallback(e||null,r||null);if(o!=null){if(o===!1||typeof o=="object"&&o.stop)return!1;typeof o=="object"&&(e="fetchUrl"in o?o.fetchUrl:e,r="fetchOptions"in o?o.fetchOptions:r)}}const i={};if(this.options.formFragment){const o=g.getValues(this.options.formFragment);Object.assign(i,o)}this.options.data&&typeof this.options.data=="object"&&Object.assign(i,this.options.data);const s=Object.keys(i).length>0;if(e){const o={...r||{}},d=new Headers(o.headers||void 0),y=(o.method||"GET").toUpperCase(),b=l.runtime==="demo"&&!ot(y),A=b?"GET":y;if(o.method=A,A==="GET"||A==="HEAD"||A==="OPTIONS")s&&(e=ct(e,i));else if(s){const c=d.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){d.delete("Content-Type");const f=new FormData;for(const[p,E]of Object.entries(i))E==null?f.append(p,""):E instanceof Blob?f.append(p,E):Array.isArray(E)?E.forEach(v=>f.append(p,String(v))):typeof E=="object"?f.append(p,JSON.stringify(E)):f.append(p,String(E));o.body=f}else if(/application\/x-www-form-urlencoded/i.test(c)){const f=new URLSearchParams;for(const[p,E]of Object.entries(i))E!==void 0&&(E===null?f.append(p,""):Array.isArray(E)?E.forEach(v=>f.append(p,String(v))):typeof E=="object"?f.append(p,JSON.stringify(E)):f.append(p,String(E)));o.body=f}else d.set("Content-Type","application/json"),o.body=JSON.stringify(i)}o.headers=d;let S;if(b&&(S=e&&new URL(e,window.location.href).search||void 0,d.delete("Content-Type"),h.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:y,effectiveMethod:A,transportMode:"query-get",url:e,payload:s?i:void 0,queryString:S})),this.options.targetFragment&&e){const c=performance.now(),f={runtime:l.runtime,requestedMethod:y,effectiveMethod:A,transportMode:b?"query-get":"http",...b?{queryString:S}:{}};return T.fetchStart(this.options.targetFragment.getTarget(),e,o,s?i:void 0,f),fetch(e,o).then(p=>this.handleFetchResult(p,e||void 0,c)).catch(p=>{throw e&&T.fetchError(this.options.targetFragment.getTarget(),e,p),p})}return fetch(e,o).then(c=>this.handleFetchResult(c,e||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&s){const o=this.options.formFragment,d=o.getTarget();d.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const y=o.getBindingData();Object.assign(y,i),await R.setBindingData(d,y)}const n=s?i:{},a=new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(a)}async handleFetchResult(t,e,r){const i=z();if(!t.ok)return this.options.targetFragment&&e&&T.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t),!1;if(this.options.targetFragment&&e&&r&&T.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const s=[];s.push(this.bindResult(t)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>g.reset(a))),await this.copy();const n=[];return this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new u(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0&&this.options.clickFragments.forEach(a=>{const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}),this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.openDialog(o)):h.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):h.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,"info"),this.pushHistory(),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.options.historyData!==void 0&&this.options.historyData!==null,r=this.options.historyFormFragment!==void 0&&this.options.historyFormFragment!==null;if(!(!t&&!e&&!r))try{const i=t?this.options.historyUrl:window.location.pathname,s=new URL(i,window.location.href);if(s.origin!==window.location.origin){const a="history.pushState: cross-origin URL is not allowed: "+s.toString();h.error("Haori",a);return}const n=a=>{for(const[o,d]of Object.entries(a))d!=null&&(Array.isArray(d)?d.forEach(y=>s.searchParams.append(o,String(y))):typeof d=="object"?s.searchParams.set(o,JSON.stringify(d)):s.searchParams.set(o,String(d)))};e&&n(this.options.historyData),r&&n(g.getValues(this.options.historyFormFragment)),history.pushState({},"",s.toString())}catch(i){h.error("Haori",`history.pushState failed: ${i}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=g.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async s=>{const n=e?e.getTarget():document.body;await z().addErrorMessage(n,s)};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const s=await t.json(),n=[];if(s&&typeof s=="object"){if(typeof s.message=="string"&&n.push({message:s.message}),Array.isArray(s.messages))for(const a of s.messages)typeof a=="string"&&n.push({message:a});if(s.errors&&typeof s.errors=="object")for(const[a,o]of Object.entries(s.errors))Array.isArray(o)?n.push({key:a,message:o.join(`
|
|
13
13
|
`)}):typeof o=="string"?n.push({key:a,message:o}):o!=null&&n.push({key:a,message:String(o)});if(n.length===0)for(const[a,o]of Object.entries(s))a==="message"||a==="messages"||a==="errors"||(Array.isArray(o)?n.push({key:a,message:o.join(`
|
|
14
|
-
`)}):typeof o=="string"&&n.push({key:a,message:o}))}if(n.length===0)return await r(`${t.status} ${t.statusText}`),!1;for(const a of n)a.key&&e?await m.addErrorMessage(e,a.key,a.message):await r(a.message);return!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return!1}validate(t){if(this.options.valid!==!0)return!0;const e=t.getTarget();let r=this.validateOne(t);return r||e.focus(),t.getChildElementFragments().reverse().forEach(i=>{r&&=this.validate(i)}),r}validateOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.reportValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):Q().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n=s.getBindingData(),a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],d=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,d)}else n[a]=r;i.push(R.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return h.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r);i.push(R.setBindingData(s.getTarget(),n))})}return Promise.all(i).then(()=>{})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let s=Number(i);isNaN(s)&&(s=0),s+=t,e.push(r.setValue(String(s)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return h.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(h.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(R.evaluateAll(r)),e.push(m.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};c.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,c.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/;let V=c;class ut{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,s)=>{t[s]=i}),t}}class ct{static async load(t,e){let r;try{r=await fetch(t,e)}catch(s){throw h.error("[Haori]","Failed to fetch import source:",t,s),new Error(`Failed to fetch: ${t}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw h.error("[Haori]","Import HTTP error:",t,s),new Error(`Failed to load ${t}: ${s}`)}let i;try{i=await r.text()}catch(s){throw h.error("[Haori]","Failed to read response text:",t,s),new Error(`Failed to read response from: ${t}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(h.warn("[Haori]","No body found in imported document:",t),i)}catch(s){return h.error("[Haori]","Failed to parse imported HTML:",t,s),i}}}const p=class p{static isDeferredAttributeName(t){return p.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return p.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!p.isEvaluateAllExcludedAttributeName(t)&&p.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);p.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>t.setAttribute(r,i)))}return e.then(()=>{})}static scan(t){const e=w.get(t);if(!e)return Promise.resolve();t.parentNode&&(w.get(t.parentNode)?.isMounted()||document.body.contains(t)?e.setMounted(!0):e.setMounted(!1));const r=[],i=new Set;for(const s of p.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+s;e.hasAttribute(n)&&(r.push(p.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),i.add(n))}for(const s of e.getAttributeNames()){if(i.has(s)||p.isDeferredAttributeName(s))continue;const n=e.getRawAttribute(s);n!==null&&r.push(p.setAttribute(e.getTarget(),s,n))}for(const s of p.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+s;e.hasAttribute(n)&&(r.push(p.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),i.add(n))}return e.getChildren().forEach(s=>{s instanceof x?r.push(p.scan(s.getTarget())):s instanceof j&&r.push(p.evaluateText(s))}),Promise.all(r).then(()=>{})}static setAttribute(t,e,r){const i=w.get(t),s=[];switch(e){case`${l.prefix}bind`:{r===null?(i.clearBindingDataCache(),i.setBindingData({})):i.setBindingData(p.parseDataBind(r));break}case`${l.prefix}if`:s.push(p.evaluateIf(i));break;case`${l.prefix}each`:s.push(p.evaluateEach(i));break;case`${l.prefix}fetch`:s.push(new V(i,null).run().then(()=>{}));break;case`${l.prefix}import`:{if(typeof r=="string"){const n=i.getTarget(),a=performance.now();T.importStart(n,r),s.push(ct.load(r).then(o=>{const d=new TextEncoder().encode(o).length;return F.enqueue(()=>{n.innerHTML=o}).then(()=>{T.importEnd(n,r,d,a)})}).catch(o=>{T.importError(n,r,o),h.error("[Haori]","Failed to import HTML:",r,o)}))}break}case`${l.prefix}url-param`:{const n=i.getAttribute(`${l.prefix}url-arg`),a=ut.readParams();if(n===null)p.setBindingData(t,a);else{const o=i.getRawBindingData()||{};o[String(n)]=a,p.setBindingData(t,o)}break}}return r===null?s.push(i.removeAttribute(e)):s.push(i.setAttribute(e,r)),Promise.all(s).then(()=>{})}static setBindingData(t,e){const r=w.get(t),i=r.getRawBindingData();r.setBindingData(e);const s=[];if(s.push(r.setAttribute(`${l.prefix}bind`,JSON.stringify(e))),t.tagName==="FORM"){const n=r.getAttribute(`${l.prefix}form-arg`),a=n&&e[String(n)]&&typeof e[String(n)]=="object"&&!Array.isArray(e[String(n)])?e[String(n)]:n?{}:e;s.push(m.syncValues(r,a))}return s.push(p.evaluateAll(r)),T.bindChange(t,i,e,"manual"),Promise.all(s).then(()=>{})}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return h.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,s]of e.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(t,e){const r=w.get(t);if(r.isSkipMutationNodes())return;const i=w.get(e.nextSibling),s=w.get(e);s&&(r.insertBefore(s,i),s instanceof x?p.scan(s.getTarget()):s instanceof j&&p.evaluateText(s))}static removeNode(t){const e=w.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=w.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=w.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const s=p.getFormFragment(r);if(s){const n=m.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(p.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?p.getFormFragment(e):null}static evaluateAll(t){const e=[];return e.push(p.reevaluateInterpolatedAttributes(t)),t.hasAttribute(`${l.prefix}if`)&&e.push(p.evaluateIf(t)),t.hasAttribute(`${l.prefix}each`)&&e.push(p.evaluateEach(t)),t.getChildren().forEach(r=>{r instanceof x?e.push(p.evaluateAll(r)):r instanceof j&&e.push(p.evaluateText(r))}),Promise.all(e).then(()=>{})}static evaluateText(t){return t.evaluate()}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);return r===!1||r===void 0||r===null||Number.isNaN(r)?t.isVisible()&&e.push(t.hide().then(()=>{T.hide(t.getTarget())})):t.isVisible()||(e.push(t.show().then(()=>{T.show(t.getTarget())})),e.push(p.evaluateAll(t))),Promise.all(e).then(()=>{})}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();let e=t.getTemplate();if(e===null){let i=!1;t.getChildren().forEach(n=>{if(!i&&n instanceof x){if(n.hasAttribute(`${l.prefix}each-before`)||n.hasAttribute(`${l.prefix}each-after`))return;e=n.clone(),t.setTemplate(e),i=!0,t.removeChild(n);const a=n.getTarget();a.parentNode&&a.parentNode.removeChild(a),n.setMounted(!1)}});const s=t.getAttribute(`${l.prefix}each`);return Array.isArray(s)?this.updateDiff(t,s):(h.error("[Haori]","Invalid each attribute:",s),Promise.reject(new Error("Invalid each attribute.")))}const r=t.getAttribute(`${l.prefix}each`);return Array.isArray(r)?this.updateDiff(t,r):(h.error("[Haori]","Invalid each attribute:",r),Promise.reject(new Error("Invalid each attribute.")))}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return h.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=t.getAttribute(`${l.prefix}each-key`),n=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((u,g)=>{const E=p.createListKey(u,s?String(s):null,g);o.push(E),a.set(E,{item:u,itemIndex:g})});const d=[];let y=t.getChildren().filter(u=>u instanceof x).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`));y=y.filter(u=>o.indexOf(String(u.getListKey()))===-1?(d.push(u.remove()),!1):!0);const b=y.map(u=>u.getListKey()),v=t.getChildren().filter(u=>u instanceof x).filter(u=>u.hasAttribute(`${l.prefix}each-before`)).length;let f=Promise.resolve();return o.forEach((u,g)=>{const E=b.indexOf(u),{item:A,itemIndex:P}=a.get(u);let O;if(E!==-1)O=y[E],f=f.then(()=>p.updateRowFragment(O,A,i,P,n?String(n):null,u).then(()=>p.evaluateAll(O)));else{O=r.clone();const W=v+g;f=f.then(()=>p.updateRowFragment(O,A,i,P,n?String(n):null,u).then(()=>t.insertBefore(O,t.getChildren()[W]||null).then(()=>p.evaluateAll(O))))}}),Promise.all(d).then(()=>f).then(()=>{const u=o.filter(P=>P!==null),g=b.filter(P=>P!==null),E=u.filter(P=>!g.includes(P)),A=g.filter(P=>!u.includes(P));T.eachUpdate(t.getTarget(),E,A,u)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const s=t[e];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,s,n){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:e},r&&(a[r]=i);else return h.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve();return t.setListKey(n),t.setBindingData(a),t.setAttribute(`${l.prefix}row`,n)}};p.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","if","each"],p.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch","url-param"],p.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","if","each","fetch","import","url-param"],p.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/;let R=p;class ht{constructor(t=document){this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=w.get(e);r&&new V(r,"load").run()},this.root=t}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0})}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad)}delegate(t,e){const r=this.getElementFromTarget(t.target);if(!r)return;const i=w.get(r);i&&(e==="change"&&i instanceof x&&i.syncValue(),new V(i,e).run().catch(s=>{h.error("[Haori]","Procedure execution error:",s)}))}getElementFromTarget(t){return t?t instanceof HTMLElement?t:t instanceof Node?t.parentElement:null:null}}const N=class N{static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(t instanceof HTMLElement&&N.syncElement(t),t.querySelectorAll("*").forEach(e=>{N.syncElement(e)}))}static syncElement(t){const e=N.registrations.get(t),r=w.get(t);if(!r||!N.shouldObserve(r)){e&&(e.observer.disconnect(),N.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=N.resolveRoot(r),s=N.resolveRootMargin(r),n=N.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===s&&N.sameThreshold(e.observer.thresholds,n)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),N.registrations.delete(t));const o=new IntersectionObserver(d=>{const y=N.registrations.get(t);y&&d.forEach(b=>{!b.isIntersecting||y.running||N.isDisabled(y.fragment)||(y.running=!0,new V(y.fragment,"intersect").runWithResult().then(v=>{v&&y.once&&(y.observer.disconnect(),N.registrations.delete(t))}).catch(v=>{h.error("[Haori]","Intersect procedure execution error:",v)}).finally(()=>{const v=N.registrations.get(t);v&&(v.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(t),N.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(t instanceof HTMLElement){const e=N.registrations.get(t);e&&(e.observer.disconnect(),N.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=N.registrations.get(e);r&&(r.observer.disconnect(),N.registrations.delete(e))})}static disconnectAll(){N.registrations.forEach(t=>{t.observer.disconnect()}),N.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!N.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return i instanceof HTMLElement?i:(h.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(t,e){return t.length===1&&t[0]===e}};N.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),N.registrations=new Map;let U=N;const B=class B{static async init(){if(B._initialized)return;B._initialized=!0;const t=await Promise.allSettled([R.scan(document.head),R.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&h.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&h.error("[Haori]","Failed to build body fragment:",r.reason),B.observe(document.head),B.observe(document.body),new ht().start(),U.syncTree(document.body)}static observe(t){new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{h.info("[Haori]","Attribute changed:",i.target,i.attributeName);const s=i.target;R.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName)),U.syncElement(s);break}case"childList":{h.info("[Haori]","Child list changed:",Array.from(i.removedNodes).map(s=>s.nodeName),Array.from(i.addedNodes).map(s=>s.nodeName)),Array.from(i.removedNodes).forEach(s=>{U.cleanupTree(s),R.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof HTMLElement&&(R.addNode(s.parentElement,s),U.syncTree(s))});break}case"characterData":{h.info("[Haori]","Character data changed:",i.target,i.target.textContent),i.target instanceof Text||i.target instanceof Comment?R.changeText(i.target,i.target.textContent):h.warn("[Haori]","Unsupported character data type:",i.target);break}default:h.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){h.error("[Haori]","Error processing mutation:",s)}}).observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),h.info("[Haori]","Observer initialized for",t)}};B._initialized=!1;let K=B;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",K.init):K.init();const ft="0.4.2";return D.Core=R,D.Env=l,D.Form=m,D.Fragment=w,D.Haori=q,D.Log=h,D.Queue=F,D.default=q,D.version=ft,Object.defineProperties(D,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),D}({});
|
|
14
|
+
`)}):typeof o=="string"&&n.push({key:a,message:o}))}if(n.length===0)return await r(`${t.status} ${t.statusText}`),!1;for(const a of n)a.key&&e?await g.addErrorMessage(e,a.key,a.message):await r(a.message);return!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return!1}validate(t){if(this.options.valid!==!0)return!0;const e=t.getTarget();let r=this.validateOne(t);return r||e.focus(),t.getChildElementFragments().reverse().forEach(i=>{r&&=this.validate(i)}),r}validateOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.reportValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):z().confirm(t)}bindResult(t){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(t.headers.get("Content-Type")?.includes("application/json")?t.json():t.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n=s.getBindingData(),a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],d=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,d)}else n[a]=r;i.push(R.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return h.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r);i.push(R.setBindingData(s.getTarget(),n))})}return Promise.all(i).then(()=>{})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...e};return R.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.formFragment?g.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e={};return this.options.copyParams.forEach(r=>{r in t&&(e[r]=t[r])}),e}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let s=Number(i);isNaN(s)&&(s=0),s+=t,e.push(r.setValue(String(s)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return h.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(h.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(R.evaluateAll(r)),e.push(g.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};u.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,u.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/;let V=u;class ut{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,s)=>{t[s]=i}),t}}class ht{static async load(t,e){let r;try{r=await fetch(t,e)}catch(s){throw h.error("[Haori]","Failed to fetch import source:",t,s),new Error(`Failed to fetch: ${t}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw h.error("[Haori]","Import HTTP error:",t,s),new Error(`Failed to load ${t}: ${s}`)}let i;try{i=await r.text()}catch(s){throw h.error("[Haori]","Failed to read response text:",t,s),new Error(`Failed to read response from: ${t}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(h.warn("[Haori]","No body found in imported document:",t),i)}catch(s){return h.error("[Haori]","Failed to parse imported HTML:",t,s),i}}}const m=class m{static isDeferredAttributeName(t){return m.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return m.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!m.isEvaluateAllExcludedAttributeName(t)&&m.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);m.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>t.setAttribute(r,i)))}return e.then(()=>{})}static scan(t){const e=w.get(t);if(!e)return Promise.resolve();t.parentNode&&(w.get(t.parentNode)?.isMounted()||document.body.contains(t)?e.setMounted(!0):e.setMounted(!1));const r=[],i=new Set;for(const s of m.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+s;e.hasAttribute(n)&&(r.push(m.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),i.add(n))}for(const s of e.getAttributeNames()){if(i.has(s)||m.isDeferredAttributeName(s))continue;const n=e.getRawAttribute(s);n!==null&&r.push(m.setAttribute(e.getTarget(),s,n))}for(const s of m.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+s;e.hasAttribute(n)&&(r.push(m.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),i.add(n))}return e.getChildren().forEach(s=>{s instanceof D?r.push(m.scan(s.getTarget())):s instanceof j&&r.push(m.evaluateText(s))}),Promise.all(r).then(()=>{})}static setAttribute(t,e,r){const i=w.get(t),s=[];switch(e){case`${l.prefix}bind`:{r===null?(i.clearBindingDataCache(),i.setBindingData({})):i.setBindingData(m.parseDataBind(r));break}case`${l.prefix}if`:s.push(m.evaluateIf(i));break;case`${l.prefix}each`:s.push(m.evaluateEach(i));break;case`${l.prefix}fetch`:s.push(new V(i,null).run().then(()=>{}));break;case`${l.prefix}import`:{if(typeof r=="string"){const n=i.getTarget(),a=performance.now();T.importStart(n,r),s.push(ht.load(r).then(o=>{const d=new TextEncoder().encode(o).length;return P.enqueue(()=>{n.innerHTML=o}).then(()=>{T.importEnd(n,r,d,a)})}).catch(o=>{T.importError(n,r,o),h.error("[Haori]","Failed to import HTML:",r,o)}))}break}case`${l.prefix}url-param`:{const n=i.getAttribute(`${l.prefix}url-arg`),a=ut.readParams();if(n===null)m.setBindingData(t,a);else{const o=i.getRawBindingData()||{};o[String(n)]=a,m.setBindingData(t,o)}break}}return r===null?s.push(i.removeAttribute(e)):s.push(i.setAttribute(e,r)),Promise.all(s).then(()=>{})}static setBindingData(t,e){const r=w.get(t),i=r.getRawBindingData();r.setBindingData(e);const s=[];if(s.push(r.setAttribute(`${l.prefix}bind`,JSON.stringify(e))),t.tagName==="FORM"){const n=r.getAttribute(`${l.prefix}form-arg`),a=n&&e[String(n)]&&typeof e[String(n)]=="object"&&!Array.isArray(e[String(n)])?e[String(n)]:n?{}:e;s.push(g.syncValues(r,a))}return s.push(m.evaluateAll(r)),T.bindChange(t,i,e,"manual"),Promise.all(s).then(()=>{})}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return h.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,s]of e.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(t,e){const r=w.get(t);if(r.isSkipMutationNodes())return;const i=w.get(e.nextSibling),s=w.get(e);s&&(r.insertBefore(s,i),s instanceof D?m.scan(s.getTarget()):s instanceof j&&m.evaluateText(s))}static removeNode(t){const e=w.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=w.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=w.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const s=m.getFormFragment(r);if(s){const n=g.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(m.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?m.getFormFragment(e):null}static evaluateAll(t){const e=[];return e.push(m.reevaluateInterpolatedAttributes(t)),t.hasAttribute(`${l.prefix}if`)&&e.push(m.evaluateIf(t)),t.hasAttribute(`${l.prefix}each`)&&e.push(m.evaluateEach(t)),t.getChildren().forEach(r=>{r instanceof D?e.push(m.evaluateAll(r)):r instanceof j&&e.push(m.evaluateText(r))}),Promise.all(e).then(()=>{})}static evaluateText(t){return t.evaluate()}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);return r===!1||r===void 0||r===null||Number.isNaN(r)?t.isVisible()&&e.push(t.hide().then(()=>{T.hide(t.getTarget())})):t.isVisible()||(e.push(t.show().then(()=>{T.show(t.getTarget())})),e.push(m.evaluateAll(t))),Promise.all(e).then(()=>{})}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();let e=t.getTemplate();if(e===null){let i=!1;t.getChildren().forEach(n=>{if(!i&&n instanceof D){if(n.hasAttribute(`${l.prefix}each-before`)||n.hasAttribute(`${l.prefix}each-after`))return;e=n.clone(),t.setTemplate(e),i=!0,t.removeChild(n);const a=n.getTarget();a.parentNode&&a.parentNode.removeChild(a),n.setMounted(!1)}});const s=t.getAttribute(`${l.prefix}each`);return Array.isArray(s)?this.updateDiff(t,s):(h.error("[Haori]","Invalid each attribute:",s),Promise.reject(new Error("Invalid each attribute.")))}const r=t.getAttribute(`${l.prefix}each`);return Array.isArray(r)?this.updateDiff(t,r):(h.error("[Haori]","Invalid each attribute:",r),Promise.reject(new Error("Invalid each attribute.")))}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return h.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=t.getAttribute(`${l.prefix}each-key`),n=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((c,f)=>{const p=m.createListKey(c,s?String(s):null,f);o.push(p),a.set(p,{item:c,itemIndex:f})});const d=[];let y=t.getChildren().filter(c=>c instanceof D).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`));y=y.filter(c=>o.indexOf(String(c.getListKey()))===-1?(d.push(c.remove()),!1):!0);const b=y.map(c=>c.getListKey()),A=t.getChildren().filter(c=>c instanceof D).filter(c=>c.hasAttribute(`${l.prefix}each-before`)).length;let S=Promise.resolve();return o.forEach((c,f)=>{const p=b.indexOf(c),{item:E,itemIndex:v}=a.get(c);let O;if(p!==-1)O=y[p],S=S.then(()=>m.updateRowFragment(O,E,i,v,n?String(n):null,c).then(()=>m.evaluateAll(O)));else{O=r.clone();const Z=A+f;S=S.then(()=>m.updateRowFragment(O,E,i,v,n?String(n):null,c).then(()=>t.insertBefore(O,t.getChildren()[Z]||null).then(()=>m.evaluateAll(O))))}}),Promise.all(d).then(()=>S).then(()=>{const c=o.filter(v=>v!==null),f=b.filter(v=>v!==null),p=c.filter(v=>!f.includes(v)),E=f.filter(v=>!c.includes(v));T.eachUpdate(t.getTarget(),p,E,c)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const s=t[e];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,s,n){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:e},r&&(a[r]=i);else return h.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve();return t.setListKey(n),t.setBindingData(a),t.setAttribute(`${l.prefix}row`,n)}};m.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","if","each"],m.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch","url-param"],m.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","if","each","fetch","import","url-param"],m.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/;let R=m;class ft{constructor(t=document){this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=w.get(e);r&&new V(r,"load").run()},this.root=t}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0})}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad)}delegate(t,e){const r=this.getElementFromTarget(t.target);if(!r)return;const i=w.get(r);i&&(e==="change"&&i instanceof D&&i.syncValue(),new V(i,e).run().catch(s=>{h.error("[Haori]","Procedure execution error:",s)}))}getElementFromTarget(t){return t?t instanceof HTMLElement?t:t instanceof Node?t.parentElement:null:null}}const N=class N{static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(t instanceof HTMLElement&&N.syncElement(t),t.querySelectorAll("*").forEach(e=>{N.syncElement(e)}))}static syncElement(t){const e=N.registrations.get(t),r=w.get(t);if(!r||!N.shouldObserve(r)){e&&(e.observer.disconnect(),N.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=N.resolveRoot(r),s=N.resolveRootMargin(r),n=N.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===s&&N.sameThreshold(e.observer.thresholds,n)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),N.registrations.delete(t));const o=new IntersectionObserver(d=>{const y=N.registrations.get(t);y&&d.forEach(b=>{!b.isIntersecting||y.running||N.isDisabled(y.fragment)||(y.running=!0,new V(y.fragment,"intersect").runWithResult().then(A=>{A&&y.once&&(y.observer.disconnect(),N.registrations.delete(t))}).catch(A=>{h.error("[Haori]","Intersect procedure execution error:",A)}).finally(()=>{const A=N.registrations.get(t);A&&(A.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(t),N.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(t instanceof HTMLElement){const e=N.registrations.get(t);e&&(e.observer.disconnect(),N.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=N.registrations.get(e);r&&(r.observer.disconnect(),N.registrations.delete(e))})}static disconnectAll(){N.registrations.forEach(t=>{t.observer.disconnect()}),N.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!N.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return i instanceof HTMLElement?i:(h.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(t,e){return t.length===1&&t[0]===e}};N.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),N.registrations=new Map;let U=N;const $=class ${static async init(){if($._initialized)return;$._initialized=!0;const t=await Promise.allSettled([R.scan(document.head),R.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&h.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&h.error("[Haori]","Failed to build body fragment:",r.reason),$.observe(document.head),$.observe(document.body),new ft().start(),U.syncTree(document.body)}static observe(t){new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{h.info("[Haori]","Attribute changed:",i.target,i.attributeName);const s=i.target;R.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName)),U.syncElement(s);break}case"childList":{h.info("[Haori]","Child list changed:",Array.from(i.removedNodes).map(s=>s.nodeName),Array.from(i.addedNodes).map(s=>s.nodeName)),Array.from(i.removedNodes).forEach(s=>{U.cleanupTree(s),R.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof HTMLElement&&(R.addNode(s.parentElement,s),U.syncTree(s))});break}case"characterData":{h.info("[Haori]","Character data changed:",i.target,i.target.textContent),i.target instanceof Text||i.target instanceof Comment?R.changeText(i.target,i.target.textContent):h.warn("[Haori]","Unsupported character data type:",i.target);break}default:h.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){h.error("[Haori]","Error processing mutation:",s)}}).observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),h.info("[Haori]","Observer initialized for",t)}};$._initialized=!1;let K=$;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",K.init):K.init();const dt="0.4.3";return M.Core=R,M.Env=l,M.Form=g,M.Fragment=w,M.Haori=q,M.Log=h,M.Queue=P,M.default=q,M.version=dt,Object.defineProperties(M,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),M}({});
|
|
15
15
|
//# sourceMappingURL=haori.iife.js.map
|