reactionview 0.4.1 → 0.6.0
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.
- checksums.yaml +4 -4
- data/README.md +22 -39
- data/app/assets/javascripts/reactionview-dev-tools.esm.js +59495 -2633
- data/app/assets/javascripts/reactionview-dev-tools.esm.js.map +1 -1
- data/app/assets/javascripts/reactionview-dev-tools.umd.js +59476 -2617
- data/app/assets/javascripts/reactionview-dev-tools.umd.js.map +1 -1
- data/app/assets/javascripts/reactionview.esm.js +26 -0
- data/app/assets/javascripts/reactionview.esm.js.map +1 -0
- data/lib/generators/reactionview/install_generator.rb +39 -4
- data/lib/reactionview/asset_manifest.rb +1 -1
- data/lib/reactionview/config.rb +99 -4
- data/lib/reactionview/importmap.rb +3 -0
- data/lib/reactionview/instrumentation.rb +143 -0
- data/lib/reactionview/railtie.rb +117 -5
- data/lib/reactionview/slots/dev_compiler.rb +25 -0
- data/lib/reactionview/slots/rendering.rb +157 -0
- data/lib/reactionview/slots/resolver.rb +27 -0
- data/lib/reactionview/slots/state_overrides.rb +68 -0
- data/lib/reactionview/slots.rb +38 -0
- data/lib/reactionview/template/dependencies.rb +90 -0
- data/lib/reactionview/template/handlers/erb.rb +25 -1
- data/lib/reactionview/template/handlers/herb/herb.rb +69 -57
- data/lib/reactionview/template/handlers/herb.rb +188 -13
- data/lib/reactionview/template/local_template.rb +37 -6
- data/lib/reactionview/template/partial_resolver.rb +90 -0
- data/lib/reactionview/version.rb +1 -1
- data/lib/reactionview.rb +13 -0
- data/reactionview.gemspec +3 -2
- metadata +30 -11
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const e=[`mouseenter`,`mouseleave`],t=[`submit`,`button`,`reset`],n=[`meta`,`ctrl`,`alt`,`shift`],r=[`keydown`,`keyup`,`keypress`],i=/^[ -~]$/,a=/^(?:Key([A-Z])|Digit([0-9]))$/,o={form:`submit`,input:`input`,textarea:`input`,select:`change`,details:`toggle`},s={esc:`escape`,return:`enter`,space:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,page_up:`pageup`,page_down:`pagedown`},c={meta:`meta`,cmd:`meta`,ctrl:`ctrl`,alt:`alt`,shift:`shift`};function l(e){return e instanceof HTMLInputElement&&t.includes(e.type)?`click`:o[e.localName]??`click`}function u(e){let[t,n]=e.split(`@`,2),{head:r,filter:i}=f(t),a=r.split(`+`),o=a.pop(),l=null,u=[];for(let e of[...a,...i]){let t=e.toLowerCase(),n=c[t];n?u.push(n):l=s[t]??t}return{type:o,key:l,modifiers:u,global:n===`window`||n===`document`||n===`outside`,outside:n===`outside`}}function d(e){let[t,n]=e.split(`@`,2);if(n!==void 0&&n!==`window`&&n!==`document`&&n!==`outside`)return`names \`@${n}\` as its target. Use \`@window\`, \`@document\` or \`@outside\`, or drop the target to listen on the element.`;let{head:r,filter:i}=f(t),a=r.split(`+`).slice(0,-1).find(e=>!c[e.toLowerCase()]);if(a!==void 0)return`prefixes the event with \`${a}+\`, which is not a modifier. Use \`ctrl\`, \`alt\`, \`shift\`, \`meta\` or \`cmd\`.`;if(i.includes(``))return"has an empty key filter. Name the key after the dot, like `keydown.esc`, or drop the dot.";let o=i.filter(e=>!c[e.toLowerCase()]);return o.length>1?`filters on ${o.length} keys. Name one key per clause, with modifiers joined by \`+\`, like \`keydown.ctrl+k\`.`:o[0]?.includes(`.`)?"joins its filter with `.`. Join modifiers and key with `+`, like `keydown.meta+k`.":null}function f(e){let t=e.indexOf(`.`),n=t===-1?e:e.slice(0,t);return t===-1||!r.includes(n)?{head:e,filter:[]}:{head:n,filter:e.slice(t+1).split(`+`)}}function p(e,t){return e.type!==t.type||(e.key!==null||e.modifiers.length>0)&&!m(e,t)?!1:e.key===null||ee(e.key,t)}function m(e,t){return n.every(n=>!!t[`${n}Key`]===e.modifiers.includes(n))}function ee(e,t){return typeof t.key==`string`?t.key.toLowerCase()===e?!0:t.isComposing||!i.test(e)||i.test(t.key)?!1:typeof t.code==`string`&&te(t.code)===e:!1}function te(e){let[,t,n]=e.match(a)??[];return t?.toLowerCase()??n??null}const h={slot:`data-herb-slot`,name:`data-herb-name`,region:`data-herb-region`,styleScoped:`data-herb-style-scoped`,dependencies:`data-herb-dependencies`,manifests:`data-herb-manifests`,into:`data-herb-into`,action:`data-herb-action`,set:`data-herb-set`,toggle:`data-herb-toggle`,increment:`data-herb-increment`,decrement:`data-herb-decrement`,reset:`data-herb-reset`,by:`data-herb-by`,debounce:`data-herb-debounce`,throttle:`data-herb-throttle`},g={action:{operation:`action`},set:{operation:`set`},toggle:{operation:`toggle`,needs:`boolean`},increment:{operation:`count`,needs:`integer`,step:1},decrement:{operation:`count`,needs:`integer`,step:-1},reset:{operation:`reset`,bare:!0}},_=Object.keys(g),v=_.map(e=>`[${h[e]}]`).join(`, `),ne=_.map(e=>h[e]),re=h.dependencies,y=`template[${re}]`;function ie(e){return oe(e.trim(),` `).filter(e=>e.length>0).map(e=>{let t=e.indexOf(`->`);return t===-1?{event:null,rest:e}:{event:e.slice(0,t),rest:e.slice(t+2)}})}function b(e){let t=e.trim();return t.length>0?[t]:[]}function ae(e){let t=!1;for(let n=0;n<e.length;n+=1)e[n]===`'`&&e[n-1]!==`\\`&&(t=!t);return!t}function oe(e,t){let n=[],r=``,i=!1;for(let a=0;a<e.length;a+=1){let o=e[a];if(o===`'`&&e[a-1]!==`\\`){i=!i,r+=o;continue}if(o===t&&!i){n.push(r),r=``;continue}r+=o}return n.push(r),n}function se(e){return e.length>=2&&e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1).replace(/\\'/g,`'`):e}const ce=`[data-herb-transition]`,le=`data-herb-transition`;let ue=!1;const de=[];function x(e,t=document,n={}){let{force:r=!1,type:i}=typeof n==`boolean`?{force:n}:n;return fe(t,r)?new Promise(n=>{de.push({callback:e,root:t,type:i,done:n}),ue||pe()}):(e(),Promise.resolve())}function fe(e,t){if(typeof document>`u`)return!1;let n=e instanceof Element&&e.matches(`[data-herb-transition]`);if(!t&&!n&&!e.querySelector(`[data-herb-transition]`)||typeof document.startViewTransition!=`function`||document.visibilityState===`hidden`||document.querySelector(`dialog:modal`))return!1;for(let e of document.querySelectorAll(`:popover-open`))for(let t of e.querySelectorAll(`*`))if(t.checkVisibility?.())return!1;return!0}function pe(){let e=de.splice(0);if(e.length===0){ue=!1;return}ue=!0;let t=e.map(e=>e.root),n=[...new Set(e.map(e=>e.type).filter(e=>e!==void 0))],r=document.startViewTransition;if(_e(t,n.length>0),!ge(t)){ve();for(let t of e)t.callback(),t.done();pe();return}let i=document.createElement(`style`);i.textContent=`
|
|
2
|
+
@layer herb-transitions {
|
|
3
|
+
::view-transition-group(*),
|
|
4
|
+
::view-transition-old(*),
|
|
5
|
+
::view-transition-new(*) {
|
|
6
|
+
animation-duration: 150ms;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
@media (prefers-reduced-motion: reduce) {
|
|
11
|
+
::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) {
|
|
12
|
+
animation: none !important;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
::view-transition-old(root) {
|
|
17
|
+
animation: none !important;
|
|
18
|
+
opacity: 0 !important;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
::view-transition-new(root) {
|
|
22
|
+
animation: none !important;
|
|
23
|
+
opacity: 1 !important;
|
|
24
|
+
}
|
|
25
|
+
`;let a=document.querySelector(`meta[name="csp-nonce"]`)?.content;a&&(i.nonce=a),document.head.appendChild(i);let o=()=>{for(let t of e)t.callback(),t.done();_e(t,n.length>0)},s;try{s=me(r,o,n)}catch{i.remove(),ve();for(let t of e)t.callback(),t.done();pe();return}s.ready?.catch(()=>{}),xe(s),be(s),s.finished.finally(()=>{i.remove(),ve(),pe()}).catch(()=>{})}function me(e,t,n){if(n.length===0)return e.call(document,t);try{return e.call(document,{update:t,types:n})}catch{return e.call(document,t)}}function he(e){let t=[];for(let n of e)n instanceof HTMLElement&&n.matches(`[data-herb-transition]`)&&t.push(n),t.push(...n.querySelectorAll(ce));return t}function ge(e){return he(e).some(e=>getComputedStyle(e).viewTransitionName!==`none`)}function _e(e,t=!1){for(let n of e){let e=[...n.querySelectorAll(ce)];n instanceof HTMLElement&&n.matches(`[data-herb-transition]`)&&e.unshift(n);for(let n of e){if(n.style.viewTransitionName)continue;let e=n.getAttribute(le);(e||!t)&&(n.style.viewTransitionName=e?ye(e):`match-element`)}}}function ve(){for(let e of document.querySelectorAll(ce))e.style.viewTransitionName=``}function ye(e){return e.replace(/[^a-zA-Z0-9_-]/g,`-`)}function be(e){let t=()=>{document.visibilityState===`hidden`&&e.skipTransition()};document.addEventListener(`visibilitychange`,t),e.finished.finally(()=>{document.removeEventListener(`visibilitychange`,t)}).catch(()=>{})}function xe(e){let t=t=>{t.newState===`open`&&t.target?.matches?.(`dialog, [popover]`)&&e.skipTransition()};document.addEventListener(`beforetoggle`,t,!0);let n=new MutationObserver(()=>{document.querySelector(`dialog:modal`)&&(e.skipTransition(),n.disconnect())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`open`],subtree:!0}),e.finished.finally(()=>{n.disconnect(),document.removeEventListener(`beforetoggle`,t,!0)}).catch(()=>{})}const Se=/^herb-region:(.*):([0-9a-f]+):(\d+)$/,Ce=/^\/herb-region:(.*)$/,we=/^herb-slot:(\d+)(?::([a-z_]+)(?::([\s\S]*))?)?$/,Te=/^\/herb-slot:(\d+)$/,Ee=/^herb-item:(\d+):([\s\S]*)$/,De=/^\/herb-item:(\d+)$/,Oe=/^herb-branch:(\d+):(\w+)$/,ke=/^herb-seeds:([\s\S]*)$/,Ae=/^\/?herb-(region|slot|item|branch|seeds):/,je=/^(.*):([0-9a-f]+)$/,Me=/^\d+$/,Ne=`item`,Pe=`parts`,Fe=`herb-part`,Ie=`child`,Le=[`child`,`raw_text`,`raw_text_interpolation`],Re=[`attribute_interpolation`,`raw_text_interpolation`];function ze(e){return Ae.test(e)}function S(e){let t=Se.exec(e);if(t)return{kind:`region-open`,file:t[1],version:t[2],occurrence:Number(t[3])};let n=Ce.exec(e);if(n)return{kind:`region-close`,file:n[1]};let r=we.exec(e);if(r){let e={kind:`slot-open`,index:Number(r[1]),type:r[2]??`child`};return r[3]!==void 0&&(e.key=r[3]),e}let i=Te.exec(e);if(i)return{kind:`slot-close`,index:Number(i[1])};let a=Ee.exec(e);if(a)return{kind:`item-open`,index:Number(a[1]),key:a[2]};let o=De.exec(e);if(o)return{kind:`item-close`,index:Number(o[1])};let s=ke.exec(e);return s?{kind:`seeds`,seeds:Ze(s[1])}:C(e)}function Be(e){return Ee.test(e)}function Ve(e){return De.test(e)}function C(e){let t=Oe.exec(e);return t?{kind:`branch`,index:Number(t[1]),branch:t[2]}:null}function w(e){let t=we.exec(e);return t?Number(t[1]):null}function He(e){return Me.test(e)?Number(e):null}function Ue(e,t,n){return`herb-region:${e}:${t}:${n}`}function We(e){return`/herb-region:${e}`}function Ge(e,t){return`herb-item:${e}:${t}`}function Ke(e,t){return`herb-slot:${e}:keyed:${t}`}function qe(e){return`/herb-slot:${e}`}function T(e,t){return`${e}:${t}`}function Je(e){let t=e.indexOf(`:`);if(t===-1)return null;let n=e.slice(0,t),r=e.slice(t+1);if(!Me.test(n))return null;let i=Number(n);return r===`item`?{kind:`item`,index:i}:r===`parts`?{kind:`parts`,index:i}:Me.test(r)?{kind:`branch`,index:i,branch:Number(r)}:null}function E(e){return T(e,Ne)}function Ye(e){return T(e,Pe)}function Xe(e){let t=je.exec(e);return t?{file:t[1],version:t[2]}:null}function Ze(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{}:t}catch{return{}}}const Qe=`Herb Client Runtime`,$e=`herb:dev-tools-start`,et=`turbo:before-render`,D=[];let O=!1,tt=!1;function k(e){let t={origin:Qe,...e},n=it();if(n?.report){D.length>0&&n.report(D.splice(0)),n.report(t);return}if(ut()){let e=console.warn;t.severity===`error`&&(e=console.error);let n=``;t.suggestion&&(n=`. ${t.suggestion}`),e(`[herb] ${t.message}${n}`,t)}D.push(t),D.length>50&&D.shift(),at()}function nt(){let e=it();if(!e?.report||D.length===0)return 0;let t=D.splice(0);return e.report(t),t.length}function rt(){D.length=0,ot()}function it(){if(globalThis.window)return window.HerbDevTools}function at(){typeof document<`u`&&(st(),!O&&(O=!0,document.addEventListener($e,A),window.addEventListener(`load`,A)))}function ot(){ct(),O&&(O=!1,document.removeEventListener($e,A),window.removeEventListener(`load`,A))}function A(){nt()}function st(){if(typeof window>`u`)return;let e=Object.getOwnPropertyDescriptor(window,`HerbDevTools`);if(e?.get||e&&e.value!==void 0&&e.value!==null||e&&e.configurable===!1)return;let t;Object.defineProperty(window,"HerbDevTools",{configurable:!0,enumerable:!0,get:()=>t,set:e=>{t=e,e&&queueMicrotask(nt)}}),tt=!0}function ct(){if(!tt||typeof window>`u`)return;tt=!1;let e=Object.getOwnPropertyDescriptor(window,`HerbDevTools`);e?.get&&e.get()===void 0&&delete window.HerbDevTools}function lt(){if(typeof document>`u`)return()=>{};let e=()=>{D.length=0,(globalThis.window&&window.HerbDevTools)?.clear?.(Qe)};return document.addEventListener(et,e),()=>document.removeEventListener(et,e)}function ut(){return typeof document>`u`?!1:document.querySelector(`meta[name="herb-debug-mode"][content="true"]`)!==null}var dt=class{constructor(e){this.parsed=new WeakMap,this.validated=new WeakSet,this.delegate=e}forget(e){this.parsed.delete(e),this.validated.delete(e)}of(e){let t=this.parsed.get(e);if(t)return t;let n=[];for(let t of _){let r=e.getAttribute(h[t]);if(r!==null)for(let i of ie(r))n.push({action:t,event:i.event??l(e),rest:i.rest})}return this.parsed.set(e,n),n}validate(e){if(!this.validated.has(e)){this.validated.add(e);for(let t of _){let n=h[t],r=e.getAttribute(n);if(r!==null){if(!ae(r)){k({template:this.delegate.templateOf(e),element:e,message:`\`${n}="${r}"\` has an unbalanced quote`,code:`herb-invalid-action`,severity:`error`});continue}for(let n of ie(r))this.validateClause(e,t,n)}}}}validateClause(e,t,n){let r=g[t],i=h[t];if(n.event===``||n.rest.trim()===``&&!r.bare){let t=`nothing after the event`;n.event===``&&(t=`no event before the arrow`),k({template:this.delegate.templateOf(e),element:e,message:`\`${i}\` has a clause with ${t}`,code:`herb-invalid-action`,severity:`error`});return}let a=n.event===null?null:d(n.event);if(a!==null){k({template:this.delegate.templateOf(e),element:e,message:`\`${n.event}\` in \`${i}\` ${a}`,code:`herb-invalid-action`,severity:`error`});return}if(oe(n.rest,`,`).length>1){let t=r.operation===`set`?`assignment`:`name`;k({template:this.delegate.templateOf(e),element:e,message:`\`${i}\` lists several ${t}s in one clause. A clause takes one ${t}, and each clause carries its own event or the element's default.`,code:`herb-invalid-action`,severity:`error`,suggestion:`separate the clauses with spaces, like \`${i}="a b"\``});return}if(r.operation!==`action`){if(r.operation===`set`){this.validateAssignment(e,n.rest);return}for(let t of b(n.rest)){let n=this.delegate.declarationFor(e,t);if(!n)continue;let a=n.declaration.kind;r.needs&&a!==r.needs&&a!==`seeded`&&this.reportKind(n.scope.region.file,i,t,a,r.needs,e)}}}validateAssignment(e,t){let n=t.indexOf(`=`);if(n<1){k({template:this.delegate.templateOf(e),element:e,message:`\`${t.trim()}\` in \`${h.set}\` is not a \`state=value\` pair`,code:`herb-invalid-action`,severity:`error`});return}let r=t.slice(0,n).trim(),i=se(t.slice(n+1).trim()),a=this.delegate.declarationFor(e,r);if(!a||i===`$value`)return;let o=a.declaration.kind;(o===`boolean`&&i!==`true`&&i!==`false`||o===`integer`&&!/^-?\d+$/.test(i))&&k({template:a.scope.region.file,element:e,message:`\`${r}=${i}\` does not parse as a ${o}; \`${r}\` is declared as one`,code:`herb-state-type`,severity:`error`,value:r})}reportKind(e,t,n,r,i,a=null){k({template:e,element:a,message:`\`${t}\` on \`${n}\` can never work, because \`${n}\` is a ${r} and it needs a ${i}`,code:`herb-state-type`,severity:`error`,value:n})}},j=class{constructor(e=[]){this.delegates=new Set,this.observer=null,this.root=null,this.attributeFilter=[...e]}watch(e){let t=e.filter(e=>!this.attributeFilter.includes(e));if(t.length===0)return;this.attributeFilter.push(...t);let n=this.root;this.observer&&n&&(this.deliver(this.observer.takeRecords()),this.root=null,this.observe(n))}add(e){return this.delegates.add(e),()=>this.remove(e)}remove(e){this.delegates.delete(e),this.delegates.size===0&&this.disconnect()}observe(e){this.observer&&this.root===e||(this.observer?.disconnect(),this.root=e,this.observer=new MutationObserver(e=>this.deliver(e)),this.observer.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:this.attributeFilter}))}disconnect(){this.observer?.disconnect(),this.observer=null,this.root=null}deliver(e){let t=[],n=[];for(let r of e)t.push(...r.addedNodes),n.push(...r.removedNodes);let r=t.filter(e=>e.isConnected);if(r.length>0)for(let e of[...this.delegates])e.nodesAdded?.(r);if(n.length>0)for(let e of[...this.delegates])e.nodesRemoved?.(n);for(let t of e)if(t.type===`attributes`&&t.target instanceof Element&&t.attributeName)for(let e of[...this.delegates])e.attributeChanged?.(t.target,t.attributeName)}};function M(e){return e===null?``:e===!0?`true`:e===!1?`false`:String(e)}function ft(e,t){if(t===`boolean`)return e===`true`;if(t===`integer`){let t=e.trim();return/^-?\d+$/.test(t)?Number(t):0}return t===`nil`&&e===``?null:e}function pt(e,t){if(e instanceof HTMLInputElement&&e.type===`checkbox`)return e.checked;let n=e.value;return ft(n,t)}function mt(e,t){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)switch(t){case`boolean`:return typeof e==`boolean`?e:e!==null;case`integer`:return typeof e==`number`?Number.isInteger(e)?e:Math.trunc(e):typeof e==`string`&&/^-?\d+$/.test(e.trim())?Number(e.trim()):void 0;case`string`:case`symbol`:return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):void 0;default:return e}}function ht(e){return e===`integer`?`an Integer`:`a ${e.charAt(0).toUpperCase()+e.slice(1)}`}var gt=class{constructor(e){this.instructions=new dt(this),this.events=new Set,this.globalEvents=new Set,this.direct=new Map,this.elements=null,this.unobserve=null,this.pinned=null,this.listeners=[],this.globalListeners=[],this.timings=new WeakMap,this.state=e}start(e=document,t){this.scan(e),this.unobserve?.(),this.elements=t??new j(ne),this.unobserve=this.elements.add(this);let n=document.documentElement;e instanceof Element&&(n=e),this.elements.observe(n)}nodesAdded(e){for(let t of e)t instanceof Element&&this.scan(t)}attributeChanged(e){this.instructions.forget(e),this.scan(e)}stop(){this.unobserve?.(),this.unobserve=null,this.elements=null;for(let[e,t]of this.listeners)document.removeEventListener(e,t,!0);for(let[e,t]of this.globalListeners)window.removeEventListener(e,t,!0);for(let e of this.direct.values())e();this.listeners=[],this.globalListeners=[],this.events=new Set,this.globalEvents=new Set,this.direct=new Map}scan(t){let n=[];t instanceof Element&&t.matches(v)&&n.push(t),n.push(...t.querySelectorAll(v));for(let t of n){for(let n of this.instructions.of(t)){let r=u(n.event);e.includes(r.type)?this.attach(t,r.type):r.global?this.delegateGlobal(r.type):this.delegate(r.type)}this.instructions.validate(t)}}templateOf(e){return this.state.scopeFor(e)?.region.file??``}delegate(e){if(this.events.has(e))return;this.events.add(e);let t=e=>this.dispatch(e);document.addEventListener(e,t,!0),this.listeners.push([e,t])}delegateGlobal(e){if(this.globalEvents.has(e))return;this.globalEvents.add(e);let t=e=>this.dispatchGlobal(e);window.addEventListener(e,t,!0),this.globalListeners.push([e,t])}dispatchGlobal(e){for(let t of document.querySelectorAll(v))this.run(t,e,!0)}attach(t,n){if(this.direct.has(t))return;let r=e=>{this.run(t,e)};for(let n of e)t.addEventListener(n,r);this.direct.set(t,()=>{for(let n of e)t.removeEventListener(n,r)})}dispatch(e){let t=e.target;if(!(t instanceof Element))return;let n=t.closest(v);for(;n;){if(this.run(n,e))return;n=n.parentElement?.closest(v)??null}}run(e,t,n=!1){let r=!1,i=this.instructions.of(e).filter(i=>{let a=u(i.event);return a.global!==n||!p(a,t)||a.outside&&t.target instanceof Node&&e.contains(t.target)?!1:(r||=a.modifiers.length>0,!0)}),a=i.length>0;r&&t.cancelable&&t.preventDefault(),this.pinned=null,a&&(this.pinned=this.pinScopes(e,i));try{for(let n of i)this.schedule(e,n,t)}finally{this.pinned=null}return a}schedule(e,t,n){let r=`${t.action}:${t.event}:${t.rest}`,i=this.timings.get(e)??new Map,a=i.get(r)??{};this.timings.set(e,i),i.set(r,a);let o=this.timingOf(e,h.throttle);if(o!==null){let r=Date.now();if(a.last!==void 0&&r-a.last<o)return;a.last=r,this.execute(e,t.action,t.rest,n);return}let s=this.timingOf(e,h.debounce);if(s!==null){a.timer!==void 0&&clearTimeout(a.timer),a.timer=setTimeout(()=>{a.timer=void 0;let r=this.pinScopes(e,[t]);this.pinned=r;try{this.execute(e,t.action,t.rest,n)}finally{this.pinned=null}},s);return}this.execute(e,t.action,t.rest,n)}timingOf(e,t){let n=e.getAttribute(t);if(n===null)return null;let r=Number(n);return Number.isFinite(r)&&r>=0?r:null}execute(e,t,n,r){let i=g[t];try{i.operation===`set`?this.set(e,n,r):i.operation===`toggle`?this.toggle(e,n):i.operation===`reset`?this.reset(e,n):i.operation===`action`?this.invoke(e,n):this.count(e,n,i.step??1)}catch(e){if(!(e instanceof TypeError))throw e}}pinScopes(e,t){let n=new Map;for(let r of t)for(let t of b(r.rest))this.pin(n,e,t.split(`=`)[0].trim());return n}pin(e,t,n){if(n===``||e.has(n))return;let r=this.state.scopeFor(t,n);r&&e.set(n,r)}declarationFor(e,t){return this.declaration(e,t)}declaration(e,t){let n=this.pinned?.get(t)??this.state.scopeFor(e,t);if(!n)return this.state.refusedRegion(e)||k({template:this.templateOf(e),element:e,message:`nothing around this element declares the state \`${t}\``,code:`herb-unknown-state`,severity:`error`,value:t}),null;let r=this.state.declaredStates(n).find(e=>e.name===t);return r?{scope:n,declaration:r}:null}apply(e){for(let[t,n]of e)this.state.setState(n,{scope:t})}group(e,t,n,r){let i=e.get(t);if(i){i[n]=r;return}e.set(t,{[n]:r})}set(e,t,n){if(oe(t,`,`).length>1)return;let r=new Map,i=this.pairOf(e,t);if(!i)return;let a=this.declaration(e,i.name);if(!a)return;let o=this.assignedValue(e,i.name,a,i.raw,n);o&&(this.group(r,a.scope,i.name,o.value),this.apply(r))}pairOf(e,t){let n=t.indexOf(`=`);return n<1?(k({template:this.templateOf(e),element:e,message:`\`${t}\` in \`${h.set}\` is not a \`state=value\` pair`,code:`herb-invalid-action`,severity:`error`}),null):{name:t.slice(0,n).trim(),raw:se(t.slice(n+1).trim())}}assignedValue(e,t,n,r,i){let{scope:a,declaration:o}=n,s=o.kind;if(r===`$value`){let e=i.target;return{value:e instanceof Element?pt(e,s):null}}return s===`boolean`&&r!==`true`&&r!==`false`||s===`integer`&&!/^-?\d+$/.test(r)?(k({template:a.region.file,element:e,message:`\`${t}=${r}\` does not parse as a ${s}; \`${t}\` is declared as one`,code:`herb-state-type`,severity:`error`,value:t}),null):{value:ft(r,s)}}toggle(e,t){let n=new Map;for(let r of b(t)){let t=this.declaration(e,r);if(!t)return;let{scope:i,declaration:a}=t;if(a.kind!==`boolean`&&a.kind!==`seeded`){k({template:i.region.file,element:e,message:`\`${h.toggle}\` on \`${r}\` did nothing, because \`${r}\` is a ${a.kind} and toggling needs a boolean`,code:`herb-state-type`,severity:`error`,value:r});return}this.group(n,i,r,this.state.getState(r,{scope:i})!==!0)}this.apply(n)}count(e,t,n){let r=Number(e.getAttribute(h.by)??`1`),i=1;Number.isFinite(r)&&(i=r);let a=n*i;for(let n of b(t)){let t=this.declaration(e,n);if(!t)return;this.state.increment(n,{scope:t.scope,by:a})}}invoke(e,t){for(let n of b(t)){if(n===`$refresh`){this.state.refresh();continue}k({template:this.templateOf(e),element:e,message:n.startsWith(`$`)?`\`${n}\` is not a built-in action`:`\`${n}\` names a user-defined action, and those are not available yet`,code:`herb-invalid-action`,severity:`error`})}}reset(e,t){if(t.trim()===``){let t=this.state.scopeFor(e);if(!t)return;for(let n of this.state.declaredStates(t))this.state.reset(n.name,{scope:this.state.scopeFor(e,n.name)??t});return}for(let n of b(t)){let t=this.declaration(e,n);if(!t)return;this.state.reset(n,{scope:t.scope})}}};const _t=new WeakMap,vt=new WeakMap;function N(e,t=null){if(!t){let t=vt.get(e);return t||(t={region:e,item:null},vt.set(e,t)),t}let n=_t.get(t);return n||(n={region:e,item:t},_t.set(t,n)),n}function yt(e,t){let n=e.get(t.region);n||(n=new Map,e.set(t.region,n));let r=t.item?.key??``,i=n.get(r);return i||(i=new Map,n.set(r,i)),i}function bt(e){return e.item?.collection.index??null}let xt=null;function St(e){return xt=e,()=>{xt===e&&(xt=null)}}function Ct(){xt?.()}const wt=`application/vnd.herb.slots+json`,Tt=`Herb-Schema`,Et=`Herb-Node-Path`,Dt=`Herb-Block`,Ot=`Herb-State`;var kt=class extends Error{constructor(e,t){super(`Herb slots request failed with ${e}`),this.status=e,this.failure=t}};function At(e={}){let t={Accept:wt,...e.headers};return e.schema&&(t[Tt]=`1`),e.nodePath&&(t[Et]=e.nodePath.join(`,`)),e.block!==void 0&&(t[Dt]=String(e.block)),e.state&&Object.keys(e.state).length>0&&(t[Ot]=jt(e.state)),t}function jt(e){return JSON.stringify(e).replace(/[\u007f-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}async function P(e,t={}){let n=new URL(e.toString(),window.location.href),r=(t.method??`GET`).toUpperCase(),i=At(t),a;if(t.body instanceof FormData||t.body instanceof URLSearchParams?a=t.body:t.body&&(a=JSON.stringify(t.body),i[`Content-Type`]??=`application/json`),r!==`GET`&&r!==`HEAD`){let e=Mt();e&&(i[`X-CSRF-Token`]??=e)}n.searchParams.set(`format`,t.format??`slots`);let o=await fetch(n.toString(),{method:r,body:a,headers:i,signal:t.signal});if(!o.ok){let e=await Pt(o);throw t.report!==!1&&k(Nt(o.status,e)),new kt(o.status,e)}return r!==`GET`&&r!==`HEAD`&&t.refresh!==!1&&Ct(),o.status===204?{template:``,version:``,occurrence:0,slots:{}}:await o.json()}function Mt(){return typeof document>`u`?null:document.querySelector(`meta[name="csrf-token"]`)?.content??null}function Nt(e,t){return{template:t?.template??``,message:t?.message??`The application answered ${e}. Check the server log.`,code:t?.class??`RuntimeError`,severity:`error`,origin:`Web Application`,phase:`runtime`,overlay:`dismissible`,...t?.line?{location:{start:{line:t.line,column:1}}}:{},...t?.backtrace?.length?{backtrace:t.backtrace}:{}}}async function Pt(e){try{return(await e.json())?.error??null}catch{return null}}const F=h.slot,Ft=h.name,It=`[${F}]`,Lt=`template[${h.region}]`;function Rt(e){return e.hasAttribute(F)}function zt(e){return e.hasAttribute(Ft)}function Bt(e){return(e.getAttribute(F)?.split(/\s+/).filter(Boolean)??[]).map(e=>{let[t,n,...r]=e.split(`:`),i=null;return r.length>0&&(i=r.join(`:`)),{index:Number(t),type:n??`child`,attribute:i}})}function*I(e){for(let t of e.querySelectorAll(It))for(let e of Bt(t))yield[t,e]}function Vt(e){return Le.includes(e)?`content`:`element`}function*L(e){if(e.nodeType===Node.COMMENT_NODE&&(yield e),e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)return;e.nodeType===Node.ELEMENT_NODE&&(Rt(e)||zt(e))&&(yield e);let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>e.nodeType===Node.COMMENT_NODE?ze(e.data.trim())?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:Rt(e)||zt(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}),n=t.nextNode();for(;n;)yield n,n=t.nextNode()}function R(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT,{acceptNode:e=>w(e.data.trim())===null?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}),n=[],r=t.nextNode();for(;r;)n.push(r),r=t.nextNode();return n}function Ht(e,t){let n=qe(t),r=e.nextSibling;for(;r;){if(r.nodeType===Node.COMMENT_NODE&&r.data.trim()===n)return r;r=r.nextSibling}return null}function Ut(e){if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)return[];let t=[...e.querySelectorAll(Lt)];return e instanceof HTMLTemplateElement&&e.matches(Lt)&&t.unshift(e),t}function Wt(e){if(e.kind===`range`)return H(e);let t=document.createRange();return e.kind===`content`?t.selectNodeContents(e.element):t.selectNode(e.element),t}function z(e){return e.kind===`range`?null:e.element}function B(e){return e.kind===`range`?e.start.parentElement:e.element}function Gt(e){return e.kind===`content`?e.element.innerHTML:e.kind===`element`?e.element.outerHTML:W(H(e))}function Kt(e){return e.kind===`range`?H(e).toString():e.element.textContent??``}function V(e){return e.kind===`range`?e.start.isConnected:e.element.isConnected}function H(e){let t=document.createRange();return t.setStartAfter(e.start),t.setEndBefore(e.end),t}function U(e){let t=document.createRange();return t.setStartBefore(e.start),t.setEndAfter(e.end),t}function W(e){let t=document.createElement(`div`);return t.append(e.cloneContents()),t.innerHTML}function G(e,t){let n=e.start.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING,r=e.end.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING;return!!(n&&r)}function qt(e,t){return e.start.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?!e.end||!!(e.end.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING):!1}function Jt(e,t){return e.ranges.some(e=>qt(e,t))}var Yt=class{constructor(e,t,n={}){this.records=new Map,this.observed=null,this.queue=Promise.resolve(),this.controller=new AbortController,this.minted=0,this.onSubmit=e=>{let t=e.target;t instanceof HTMLFormElement&&t.hasAttribute(h.into)&&(e.preventDefault(),e.stopPropagation(),this.submitForm(t))},this.slots=e,this.state=t,this.options=n}submit(e){let t=e.key??`herb-pending-${this.minted+=1}`,n=this.collection(e.into),r={options:e,key:t,slot:null},i=!1,a=x(()=>{if(i=!0,!n)return;let a=this.slots.addItem(n,t,{values:e.values,text:!0});a&&(this.setStates(n,a,{pending:!0,failed:!1}),r.slot=n)},n&&B(n.anchor)||document);return r.inserted=i?void 0:a,this.records.set(t,r),this.enqueue(r)}retry(e){let t=this.keyOf(e),n=t===null?void 0:this.records.get(t);if(t===null||!n)return this.reportUnsent(`retry`,e,t),null;let r=n.slot?.items.get(t)??null;return n.slot&&r&&this.setStates(n.slot,r,{pending:!0,failed:!1}),this.enqueue(n)}discard(e){let t=this.keyOf(e),n=t===null?void 0:this.records.get(t);return t===null||!n?(this.reportUnsent(`discard`,e,t),!1):(this.records.delete(t),!n.slot||this.slots.dismissItem(n.slot,t))}observe(e=document){typeof document<`u`&&(this.observed?.removeEventListener(`submit`,this.onSubmit,!0),this.observed=e,e.addEventListener(`submit`,this.onSubmit,!0))}unobserve(){this.observed?.removeEventListener(`submit`,this.onSubmit,!0),this.observed=null}submitForm(e){let t=e.getAttribute(h.into),n=this.state.scopeFor(e)?.region;if(t===null||t===``||!n)return null;let r=this.slots.slot(n.file,t,n.occurrence);if(!r||r.type!==`collection`){let e=`\`${h.into}="${t}"\` names nothing in this template.`;return r&&(e=`\`${h.into}="${t}"\` names a ${r.type} slot, and a send needs a collection.`),k({template:n.file,message:e,code:`herb-unknown-collection`,severity:`error`,suggestion:"name a keyed collection, the element carrying `data-herb-name` around the loop",value:t}),null}let i=new FormData(e),a={};for(let[e,t]of i.entries())typeof t==`string`&&(a[Qt(e)]=t);let o=this.submit({url:e.getAttribute(`action`)??e.action,method:(e.getAttribute(`method`)??`post`).toUpperCase(),body:i,into:{file:n.file,name:t,occurrence:n.occurrence},values:a});return e.reset(),this.state.resetBound(e),o}reportUnsent(e,t,n){let r=t instanceof Element?t:null,i=r?this.state.scopeFor(r):null,a=n===null?`names no row this outbox holds`:`names the row \`${n}\`, which this outbox never sent`;k({template:i?.region.file??``,element:r,message:`\`outbox.${e}\` ${a}, so nothing happened.`,code:`herb-unsent-mutation`,severity:`warning`,suggestion:"send the write through `outbox.submit` so the outbox can retry it, or handle the failure where the request was made"})}keyOf(e){return typeof e==`string`?e:this.state.scopeFor(e)?.item?.key??null}abort(){this.controller.abort(),this.controller=new AbortController}enqueue(e){let t=this.queue.then(()=>this.send(e));return this.queue=t.catch(()=>void 0),t}async send(e){e.inserted&&await e.inserted;let{options:t,key:n}=e,r=null;try{r=await this.transport()(this.request(t),this.controller.signal)}catch(t){return this.fail(e),{status:Zt(e.slot,`failed`),key:n,error:t}}return await this.confirm(e,r)}async confirm(e,t){let{options:n,key:r}=e,i=e.slot;if(!t)return this.settle(e),{status:Zt(i,`confirmed`),key:r};let a=r;if(i){let e=(n.confirmKey??this.realKey.bind(this))(t,r);e&&e!==r&&(this.slots.rekeyItem(i,r,e)?a=e:this.slots.removeItem(i,r))}let o=t;i&&(o=this.narrow(t,i));let s;return await x(()=>{s=this.slots.apply(o,{items:`merge`})},e.slot&&B(e.slot.anchor)||document),s.applied===0&&s.deferred.some(e=>e.reason===`stale-version`)?(this.settle(e,a),this.records.delete(r),{status:`stale`,key:a,report:s}):(this.settle(e,a),this.records.delete(r),{status:Zt(i,`confirmed`),key:a,report:s})}settle(e,t){let n=e.slot,r=n?.items.get(t??e.key)??null;n&&r&&this.setStates(n,r,{pending:!1,failed:!1})}fail(e){let t=e.slot,n=t?.items.get(e.key)??null;t&&n&&this.setStates(t,n,{pending:!1,failed:!0})}setStates(e,t,n){let r=this.slots.regionOf(e);if(!r)return;let i=N(r,t),a=Object.fromEntries(Object.entries(n).filter(([e])=>this.state.declares(i,e)));Object.keys(a).length!==0&&this.state.setState(a,{scope:i})}collection(e){let t=e.name??e.index;if(t===void 0)return null;let n=this.slots.slot(e.file,t,e.occurrence??0);return n?.type===`collection`?n:null}realKey(e,t){for(let n of Object.values(e.slots)){if(typeof n!=`object`||!n||!(`items`in n))continue;let r=Object.keys(n.items).filter(e=>e!==t);if(r.length===1)return r[0];r.length>1&&k({template:e.template,message:`A confirm carried ${r.length} rows, so the optimistic row cannot tell which one it became and keeps its temporary key.`,code:`herb-ambiguous-confirm`,severity:`warning`,suggestion:"render only the created row in the confirm response, or pass `confirmKey` to `submit`"})}return null}narrow(e,t){let n=e.slots[t.index];return n===void 0?e:{...e,slots:{[t.index]:n}}}request(e){let t={Accept:`application/vnd.herb.slots+json`,...this.options.headers?.()},n=typeof document>`u`?null:document.querySelector(`meta[name="csrf-token"]`)?.content;return n&&!t[`X-CSRF-Token`]&&(t[`X-CSRF-Token`]=n),{url:e.url,method:(e.method??`post`).toUpperCase(),body:e.body,headers:t}}transport(){return this.options.transport??Xt(this.options.format??`slots`)}};function Xt(e){return async(t,n)=>{let r;return t.body instanceof FormData?r=t.body:t.body&&(r=new URLSearchParams(t.body)),await P(t.url,{method:t.method,body:r,headers:t.headers,format:e,signal:n})}}function Zt(e,t){return e?t:`detached`}function Qt(e){let t=[...e.matchAll(/\[([^\[\]]+)\]/g)];return t.length===0?e:t[t.length-1][1]}function $t(e){return en($.get()?.state,e)}function en(e,t){let n=n=>{let r=e?.scopeFor(t,n);return r?{scope:r}:{}};return{get scope(){return e?.scopeFor(t)??null},get:t=>e?.getState(t,n(t))??null,set:t=>{let r=Object.keys(t)[0];return r?e?.setState(t,n(r))??!1:!1},toggle:t=>e?.toggle(t,n(t))??!1,increment:(t,r)=>e?.increment(t,{...n(t),by:r})??!1,decrement:(t,r)=>e?.decrement(t,{...n(t),by:r})??!1,reset:t=>e?.reset(t,n(t))??!1,on:(t,r)=>e?.on(t,r,n(t))??(()=>{})}}const tn=`turbo:load`;function nn(e){let t=()=>{e.regions().length>0||document.querySelector(v)&&k({template:window.location.href,message:"This page has `data-herb-*` attributes but no slot regions, so nothing on it is interactive.",code:`herb-no-regions`,severity:`warning`,suggestion:"add `<%# herb:slots client %>` to the template that wrote them"})};return t(),typeof document>`u`?()=>{}:(document.addEventListener(tn,t),()=>document.removeEventListener(tn,t))}const rn=`herb:slot-update`,an=`herb:state-change`;var on=class{constructor(e){this.kept=new Map,this.recording=null,this.nextToken=1,this.delegate=e}transaction(e){if(this.recording)return{token:null,result:e()};let t=[];this.recording=t;let n;try{n=e()}finally{this.recording=null}if(t.length===0)return{token:null,result:n};let r=this.nextToken++;if(this.kept.set(r,t),this.kept.size>50){let e=this.kept.keys().next().value;e!==void 0&&this.kept.delete(e)}return{token:r,result:n}}revert(e){let t=this.kept.get(e);if(!t)return!1;this.kept.delete(e);for(let e=t.length-1;e>=0;--e)t[e]();return!0}record(e,t){if(!this.recording)return;let n=t(),r=this.delegate.addressOf(e);this.recording.push(()=>{let e=this.delegate.slotAt(r);e&&n(e)})}};function sn(e){return Array.isArray(e)?e:[e]}function cn(e){return e[e.length-1]}function K(e,t){for(let n=e.length-1;n>=0;--n)if(t(e[n]))return e.splice(n,1)[0];return null}const ln=/[&<>"']/g,un=/&(amp|lt|gt|quot|apos|#39|#x27);/g,dn={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},fn={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,"#39":`'`,"#x27":`'`};function pn(e,t,n=!1,r){for(let r of R(e)){let e=w(r.data.trim());if(e===null)continue;let i=t[e];if(i===void 0||Array.isArray(i))continue;let a=Ht(r,e);if(!a)continue;let o=document.createRange();o.setStartAfter(r),o.setEndBefore(a),o.deleteContents(),o.insertNode(o.createContextualFragment(Dn(i,n)))}for(let[i,a]of I(e)){let e=t[a.index];if(e!==void 0){if(a.attribute!==null){let t=En(a,n?e:Tn(e),r);t!==null&&i.setAttribute(a.attribute,t);continue}if(a.type===`raw_text_interpolation`){let t=xn(r?.(a.index)??null,e);t!==null&&(i.textContent=t);continue}a.type===`child`&&!Array.isArray(e)&&(i.innerHTML=Dn(e,n))}}}function mn(e,t){let n=0,r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;r.nextNode();){let t=r.currentNode;if(t===e)return n>0;let i=t.data.trim();Be(i)?n+=1:Ve(i)&&--n}if(e instanceof Element){let n=e;for(;n&&n!==t;){let e=n;for(;e=e.previousSibling;)if(e.nodeType===Node.COMMENT_NODE){let t=e.data.trim();if(Be(t))return!0;if(Ve(t))break}n=n.parentNode}}return!1}function hn(e){let t={};for(let n of R(e)){let r=w(n.data.trim());if(r===null||mn(n,e))continue;let i=Ht(n,r);if(!i)continue;let a=document.createRange();a.setStartAfter(n),a.setEndBefore(i),t[r]=gn(a.cloneContents())}for(let[n,r]of I(e))r.attribute===null&&r.type===`child`&&(mn(n,e)||(t[r.index]=n.innerHTML));return t}function gn(e){let t=document.createElement(`div`);return t.append(e),t.innerHTML}function _n(e){for(let t of L(e))t.nodeType===Node.COMMENT_NODE&&S(t.data.trim())?.kind===`seeds`&&t.remove()}function vn(e){for(let t of R(e)){if(!e.contains(t))continue;let n=w(t.data.trim());if(n===null)continue;let r=Ht(t,n);if(!r)continue;let i=document.createRange();i.setStartAfter(t),i.setEndBefore(r),i.deleteContents()}for(let[t,n]of I(e)){if(n.attribute!==null){n.type===`boolean_attribute`?t.removeAttribute(n.attribute):t.setAttribute(n.attribute,``);continue}n.type===`child`&&t.replaceChildren()}}function yn(e){let t=new Map;for(let[,n]of I(e))n.attribute!==null&&t.set(n.attribute,n.index);return t}function bn(e){let t=new Map,n=null;for(let r of[...e.content.childNodes]){if(r.nodeType===Node.COMMENT_NODE){let e=C(r.data.trim());e&&(n=document.createDocumentFragment(),t.set(T(e.index,e.branch),n))}n?.append(r)}return t}function xn(e,t){if(!e)return null;let n=sn(t);if(n.length!==e.length-1)return null;let r=e[0];for(let t=1;t<e.length;t+=1)r+=`${n[t-1]}${e[t]}`;return r}function Sn(e){return e.replace(ln,e=>dn[e])}function Cn(e){return e.includes(`&`)?e.replace(un,(e,t)=>fn[t]):e}function wn(e){let t=document.createElement(`template`);t.innerHTML=e;for(let e of[...L(t.content)]){if(e.nodeType===Node.COMMENT_NODE){e.remove();continue}let t=e;t.removeAttribute(F),t.removeAttribute(Ft)}return t.innerHTML}function Tn(e){return Array.isArray(e)?e.map(Cn):Cn(e)}function En(e,t,n){return e.type===`attribute_interpolation`?xn(n?.(e.index)??null,t):Array.isArray(t)?null:t}function Dn(e,t){return t?Sn(e):e}var On=class{constructor(){this.held=new Map}park(e,t,n){let{file:r,version:i}=e,a=this.held.get(r),o={version:i,fragments:new Map};return a&&a.version===i&&(o=a),this.held.set(r,o),!o.fragments.has(t)&&(o.fragments.set(t,n),!0)}push(e,t,n){let{file:r,version:i}=e,a=this.held.get(r),o={version:i,fragments:new Map};a&&a.version===i&&(o=a),this.held.set(r,o),o.fragments.set(t,n)}adopt(e){for(let t of Ut(e)){let e=Xe(t.getAttribute(h.region)??``);if(e){for(let[n,r]of bn(t))this.park(e,n,r);t.remove()}}}parked(e,t){return this.held.get(e)?.fragments.get(t)??null}all(){return[...this.held.values()].flatMap(e=>[...e.fragments.values()])}keys(e){return[...this.held.get(e)?.fragments.keys()??[]]}branches(e,t){return this.keys(e).map(e=>Je(e)).filter(e=>e?.kind===`branch`&&e.index===t).map(e=>e.branch).sort((e,t)=>e-t)}mode(e,t){return t===void 0?this.keys(e).length>0?`client`:`server`:this.branches(e,t).length>0?`client`:`server`}materialize(e,t,n={},r){let i=this.parked(e,t);if(!i)return null;let a=i.cloneNode(!0);return pn(a,n,!1,r),a}blanked(e){return vn(e),e}clear(){this.held=new Map}};const kn=`template[${h.manifests}]`;function An(e,t){let n=[];return e instanceof HTMLTemplateElement&&e.matches(t)&&n.push(e),(e instanceof Element||e instanceof DocumentFragment||e instanceof Document)&&n.push(...e.querySelectorAll(t)),n}function jn(e){let t=e.content.textContent??e.textContent??``;if(!t.trim())return null;try{return JSON.parse(t)}catch{return null}}var Mn=class{constructor(){this.held=new Map,this.byFile=new Map}adopt(e){let t=0;for(let n of An(e,kn)){let e=jn(n);for(let[n,r]of Object.entries(e??{}))this.keep(n,r)&&(t+=1);n.remove()}return t}push(e,t){this.held.set(e,t),this.byFile.set(t.file,t),this.byFile.set(t.identifier,t)}hold(e){let t=0;for(let[n,r]of Object.entries(e))this.keep(n,r)&&(t+=1);return t}get(e,t){return this.held.get(`${e}:${t}`)??null}nameOf(e,t,n){return this.get(e,t)?.names[n]??null}partsOf(e,t,n){return this.get(e,t)?.parts[String(n)]??null}partsForFile(e,t){return this.byFile.get(e)?.parts[String(t)]??null}bindingsOf(e,t,n){return this.get(e,t)?.bindings?.[String(n)]??null}statesOf(e,t){return this.get(e,t)?.states??null}evict(e,t){let n=0;for(let[r,i]of this.held)i.file===e&&i.version!==t&&(this.held.delete(r),n+=1);let r=this.byFile.get(e);if(r&&r.version!==t){let n=[...this.held.values()].find(n=>n.file===e&&n.version===t);n&&(this.byFile.set(e,n),this.byFile.set(n.identifier,n))}return n}clear(){this.held=new Map,this.byFile=new Map}keep(e,t){if(!e||!t||typeof t!=`object`||this.held.has(e))return!1;let n=t;return this.held.set(e,n),this.byFile.set(n.file,n),this.byFile.set(n.identifier,n),!0}};function Nn({template:e,target:t,values:n={},text:r=!1,resolve:i,prepare:a}){let o=e.cloneNode(!0);a?.(o),pn(o,n,r,i);let s=[...o.childNodes];return t.parentNode?.insertBefore(o,t),s}const Pn=/^\d+$/;var Fn=class{constructor(e,t,n,r){this.delegate=e,this.journal=t,this.statics=n,this.manifests=r}reconcile(e,t){let n=this.itemsInDocumentOrder(e).map(e=>e.key),r=new Set(t),i=n.filter(e=>!r.has(e)),a=t.filter(e=>!n.includes(e)),o=t.filter(e=>n.includes(e)),s=n.filter(e=>r.has(e)),c=o.filter((e,t)=>s[t]!==e);return{added:a,removed:i,moved:c,kept:o,unchanged:a.length===0&&i.length===0&&c.length===0}}mergeItems(e,t){let n=t.filter(t=>!e.items.has(t));if(n.length===0)return[];let r=this.rowTemplate(e),i=this.itemsEnd(e);if(!r||!i)return n;for(let t of n)this.buildItem(e,t,r,i);return[]}reconcileItems(e,t,n=`replace`){return this.delegate.building(`client`,()=>{if(n===`merge`)return this.mergeItems(e,t);let r=this.reconcile(e,t);return r.unchanged?[]:this.applyPlan(e,t,r)})}applyPlan(e,t,n){let r=null;n.added.length>0&&(r=this.rowTemplate(e));for(let t of n.removed){let n=e.items.get(t);n&&this.dropItem(e,n)}if(!r)return this.order(e,t.filter(t=>e.items.has(t))),n.added;for(let i of n.added)this.buildItem(e,i,r,this.anchorFor(e,t,i));return this.order(e,t),[]}anchorFor(e,t,n){for(let r of t.slice(t.indexOf(n)+1)){let t=e.items.get(r);if(t)return t.start}return this.itemsEnd(e)}rowTemplate(e){let t=this.statics.parked(e.region.file,E(e.index));if(t)return t;let[n]=this.itemsInDocumentOrder(e);return n?this.rowFragment(n):null}rowFragment(e){let t=document.createRange().createContextualFragment(``);return t.append(U(e).cloneContents()),vn(t),_n(t),t}keepItem(e,t){e.items.size>1||this.statics.park(e.region,E(e.index),this.rowFragment(t))}buildItem(e,t,n,r,i={},a=!1){let o=this.insertionPoint(e,r);if(!o)return;let s=Nn({template:n,target:o,values:i,text:a,resolve:this.partsResolver(e),prepare:n=>this.prepareItem(n,e,t)});this.delegate.scan(s,{region:e.region,slot:e,item:e.item}),this.journal.record(e,()=>e=>{let n=e.items.get(t);n&&this.dropItem(e,n)});let c=e.items.get(t)??null;c&&this.delegate.recordBuilt(e,c),this.delegate.announceItemAdded(e,t,c)}prepareItem(e,t,n){for(let r of L(e)){if(r.nodeType!==Node.COMMENT_NODE)continue;let e=r,i=S(e.data.trim());if(i?.kind===`item-open`&&i.index===t.index){e.data=Ge(t.index,n);break}}for(let t of[...e.childNodes]){if(t.nodeType!==Node.COMMENT_NODE)continue;let e=S(t.data.trim());e?.kind===`branch`&&e.branch===`item`&&t.remove()}}insertionPoint(e,t){if(t)return t;let[n]=this.itemsInDocumentOrder(e);return n?n.start:this.itemsEnd(e)}itemsEnd(e){return e.anchor.kind===`range`?e.anchor.end:null}partsResolver(e){return t=>this.manifests.partsOf(e.region.file,e.region.version,t)}dropItem(e,t){this.journal.record(e,()=>{let n=U(t).cloneContents(),r=this.itemsInDocumentOrder(e),i=r[r.indexOf(t)+1]?.key??null;return e=>{if(e.anchor.kind!==`range`||e.items.has(t.key))return;let r=e.anchor.end;i!==null&&(r=e.items.get(i)?.start??e.anchor.end);let a=n.cloneNode(!0),o=[...a.childNodes];r.parentNode?.insertBefore(a,r),this.delegate.scan(o,{region:e.region,slot:e,item:e.item}),this.delegate.announceItemAdded(e,t.key,e.items.get(t.key)??null)}}),this.keepItem(e,t),this.delegate.announceItemRemoved(e,t.key,t),U(t).deleteContents(),e.items.delete(t.key)}order(e,t){let n=this.itemsEnd(e);if(!n)return;let r=this.itemsInDocumentOrder(e),i=t.map(t=>e.items.get(t)).filter(e=>e!==void 0);if(!(i.length===r.length&&i.every((e,t)=>e===r[t]))){this.journal.record(e,()=>{let e=r.map(e=>e.key);return t=>{this.order(t,e)}}),this.delegate.announceItemsMoving(e,i);for(let e of i)n.parentNode?.insertBefore(U(e).extractContents(),n);this.pruneItems(e),this.delegate.announceItemsMoved(e,i)}}addItem(e,t,n={}){if(e.type!==`collection`)return null;let r=this.itemsEnd(e);if(!r||e.items.has(t))return null;let i=this.rowTemplate(e);if(!i)return null;let a=r;n.before!==void 0&&(a=e.items.get(n.before)?.start??r);let o=this.itemValues(e,i,n.values??{});return this.delegate.building(`client`,()=>{this.buildItem(e,t,i,a,o,n.text===!0)}),e.items.get(t)??null}removeItem(e,t){let n=e.items.get(t);return n?(this.dropItem(e,n),!0):!1}rekeyItem(e,t,n){if(t===n||e.items.has(n))return!1;let r=e.items.get(t);return r?(r.start.data=Ge(e.index,n),r.key=n,e.items.delete(t),e.items.set(n,r),this.journal.record(e,()=>e=>{this.rekeyItem(e,n,t)}),this.delegate.announceItemRekeyed(e,n,t,r),!0):!1}itemValues(e,t,n){let r=yn(t),i={};for(let[t,a]of Object.entries(n)){if(Pn.test(t)){i[Number(t)]=a;continue}let n=this.manifests.nameOf(e.region.file,e.region.version,t)??r.get(t)??null;n!==null&&(i[n]=a)}return i}pruneItems(e){if(e.items.size===0)return;let t=this.itemsInDocumentOrder(e);e.items.clear();for(let n of t){for(let[e,t]of n.slots)V(t.anchor)?this.pruneItems(t):n.slots.delete(e);e.items.set(n.key,n)}}itemsInDocumentOrder(e){return[...e.items.values()].filter(e=>e.start.isConnected).sort((e,t)=>e.start.compareDocumentPosition(t.start)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1)}};function In(e,t){e&&e!==t&&(t.parent=e,e.children.includes(t)||e.children.push(t))}function Ln(e){let t=[],n=[...e.children];for(;n.length>0;){let e=n.shift();t.push(e),n.push(...e.children)}return t}function Rn(e){let t=[],n=e.parent;for(;n;)t.push(n),n=n.parent;return t}function zn(e){return`${e.openRegions.length}:${e.openSlots.length}:${e.openItems.length}`}function Bn(e,t){return e.ranges.find(e=>qt(e,t))??null}var Vn=class{constructor(e,t,n){this.held=[],this.visited=new WeakSet,this.delegate=e,this.statics=t,this.manifests=n}scan(e,t){let n={regions:[],slots:[]},r=sn(e),i=null,a=``;for(let e of r)(!i||zn(i)===a)&&(i=this.seed(t??this.locate(e)??{}),a=zn(i)),this.scanMarkers(e,n,i);for(let e of r)this.manifests.adopt(e),this.statics.adopt(e);return n}locate(e){return this.placements(e)[0]??null}placements(e){let t=[];for(let n of this.held)Jt(n,e)&&t.push(this.placementIn(n,e));return t.sort((t,n)=>{let r=Bn(t.region,e).start,i=Bn(n.region,e).start;return r===i?0:r.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING?1:-1})}seed(e){let t={openRegions:[],openSlots:[],openItems:[]},n=e.region??e.slot?.region??e.item?.collection.region??null;if(n){let r=e.slot?Bn(n,e.slot.anchor.kind===`range`?e.slot.anchor.start:e.slot.anchor.element):n.ranges[0];t.openRegions.push({region:n,range:r??n.ranges[0]})}return e.item&&t.openItems.push({slot:e.item.collection.index,item:e.item}),e.slot&&t.openSlots.push({index:e.slot.index,slot:e.slot}),t}regionsFor(e){return this.held.filter(t=>t.file===e)}regions(){return[...this.held]}files(){return[...new Set(this.held.map(e=>e.file))]}slotsFor(e,t){return this.regionsFor(e).map(e=>e.slots.get(t)).filter(e=>e!==void 0)}region(e,t=0){return this.regionsFor(e).find(e=>e.occurrence===t)??null}slot(e,t,n=0){let r=this.region(e,n);if(!r)return null;let i=this.slotIndex(r,t,null);return i===null?null:r.slots.get(i)??null}itemsFor(e,t,n=0){return this.slot(e,t,n)?.items??new Map}slotInItem(e,t,n,r,i=0){let a=this.region(e,i),o=this.itemsFor(e,t,i).get(n);if(!a||!o)return null;let s=this.slotIndex(a,r,o);return s===null?null:o.slots.get(s)??null}slotIndex(e,t,n){if(typeof t==`number`)return t;let r=this.manifests.nameOf(e.file,e.version,t);if(r!==null)return r;let i=n?.slots??e.slots;for(let e of i.values())if(e.attribute===t)return e.index;return null}regionOf(e){return e.region}slotAt(e){let t=e.region.slots;for(let n of e.path){let e=t.get(n.collection)?.items.get(n.key);if(!e)return null;t=e.slots}return t.get(e.index)??null}owner(e){return e.item?.slots??e.region.slots}prune(){let e=this.held.length;this.held=this.held.filter(e=>this.regionConnected(e));for(let e of this.held)for(let[t,n]of e.slots)this.slotConnected(n)?this.delegate.pruneItems(n):e.slots.delete(t);return e-this.held.length}clear(){this.held=[],this.visited=new WeakSet,this.statics.clear(),this.manifests.clear()}get size(){return this.held.reduce((e,t)=>e+t.slots.size,0)}scanMarkers(e,t,n){for(let r of L(e)){if(r.nodeType===Node.ELEMENT_NODE){let e=r;if(this.visited.has(e))continue;this.visited.add(e),this.anchorSlots(e,t,n);continue}let e=r,i=S(e.data.trim());if(i){if(this.visited.has(e)){this.replay(i,e,n);continue}switch(this.visited.add(e),i.kind){case`region-open`:this.openRegion(i,e,t,n);break;case`region-close`:this.closeRegion(i,e,n);break;case`slot-open`:this.openSlot(i,e,t,n);break;case`slot-close`:this.closeSlot(i,e,n);break;case`item-open`:this.openItem(i,e,n);break;case`item-close`:this.closeItem(i,e,n);break;case`seeds`:this.sowSeeds(i,n);break;case`branch`:this.markBranch(i,n)}}}}replay(e,t,n){switch(e.kind){case`region-open`:{let r=this.held.find(t=>t.file===e.file&&t.occurrence===e.occurrence&&t.version===e.version),i=r?.ranges.find(e=>e.start===t);r&&i&&n.openRegions.push({region:r,range:i});break}case`region-close`:K(n.openRegions,t=>t.region.file===e.file);break;case`slot-open`:{let r=this.holderAt(n)?.slots.get(e.index);if(r&&r.anchor.kind===`range`&&r.anchor.start===t&&(n.openSlots.push({index:r.index,slot:r}),r.type===`keyed`)){let e=r.items.values().next().value;e&&n.openItems.push({slot:r.index,item:e})}break}case`slot-close`:K(n.openSlots,t=>t.index===e.index)?.slot.type===`keyed`&&K(n.openItems,t=>t.slot===e.index);break;case`item-open`:{let r=this.collectionAt(n,e.index)?.items.get(e.key);r&&r.start===t&&n.openItems.push({slot:e.index,item:r});break}case`item-close`:K(n.openItems,t=>t.slot===e.index)}}openRegion(e,t,n,r){let i={start:t,end:null},a=this.held.find(t=>t.file===e.file&&t.occurrence===e.occurrence&&t.version===e.version),o=cn(r.openRegions)?.region??null,s=o?this.slotOpenIn(r,o):null;if(a&&a.ranges.some(e=>e.start.isConnected)){a.ranges.push(i),r.openRegions.push({region:a,range:i}),a.parent===null&&o&&(a.parent=o,a.slot=s?.type===`child`?s:null,a.item=this.itemAt(r,o));return}a&&(this.held=this.held.filter(e=>e!==a));let c={file:e.file,version:e.version,occurrence:e.occurrence,ranges:[i],slots:new Map,parent:o,slot:s?.type===`child`?s:null,item:o?this.itemAt(r,o):null};r.openRegions.push({region:c,range:i}),this.held.push(c),n.regions.push(c)}closeRegion(e,t,n){let r=K(n.openRegions,t=>t.region.file===e.file);r&&(r.range.end=t)}openSlot(e,t,n,r){let i=this.regionAt(r);if(!i)return;let a=this.itemAt(r,i),o=this.slotOpenIn(r,i),s={index:e.index,type:e.type,attribute:null,anchor:{kind:`range`,start:t,end:t},items:new Map,key:e.key??null,branch:null,parent:null,children:[],region:i,item:a,claimed:!1,shown:null,captured:null};if(r.openSlots.push({index:s.index,slot:s}),this.attach(i,s,n,o,a),s.type===`keyed`){let e={key:s.key??``,start:t,end:t,slots:new Map,collection:s};s.items.set(e.key,e),r.openItems.push({slot:s.index,item:e})}}closeSlot(e,t,n){let r=K(n.openSlots,t=>t.index===e.index);if(r?.slot.anchor.kind===`range`&&(r.slot.anchor.end=t),r?.slot.type===`keyed`){let r=K(n.openItems,t=>t.slot===e.index);r&&(r.item.end=t)}}openItem(e,t,n){let r=this.collectionAt(n,e.index);if(!r)return;let i={key:e.key,start:t,end:t,slots:new Map,collection:r};r.items.set(i.key,i),n.openItems.push({slot:e.index,item:i})}closeItem(e,t,n){let r=K(n.openItems,t=>t.slot===e.index);r&&(r.item.end=t)}sowSeeds(e,t){let n=this.holderAt(t);n&&(n.seeds={...n.seeds??{},...e.seeds})}markBranch(e,t){let n=this.regionAt(t),r=He(e.branch);if(r===null||!n)return;let i=t.openSlots.find(t=>t.index===e.index&&t.slot.region===n)?.slot??this.holderAt(t)?.slots.get(e.index);i&&(i.branch=r)}regionAt(e){return cn(e.openRegions)?.region??null}holderAt(e){let t=this.regionAt(e);return t?this.itemAt(e,t)??t:null}collectionAt(e,t){let n=this.regionAt(e);return n?e.openSlots.find(e=>e.index===t&&e.slot.region===n)?.slot||(this.holderAt(e)?.slots.get(t)??null):null}slotOpenIn(e,t){let n=cn(e.openSlots)?.slot??null;return n&&n.region===t?n:null}itemAt(e,t){let n=cn(e.openItems)?.item??null;return n&&n.collection.region===t?n:null}anchorSlots(e,t,n){let r=this.regionAt(n);if(!r)return;let i=this.slotOpenIn(n,r),a=this.itemAt(n,r);for(let n of Bt(e)){let o={index:n.index,type:n.type,attribute:n.attribute,key:null,anchor:{kind:Vt(n.type),element:e},items:new Map,branch:null,parent:null,children:[],region:r,item:a,claimed:!1,shown:null,captured:null};this.attach(r,o,t,i,a)}}attach(e,t,n,r=null,i=null){if(!e)return;let a=i?.slots??e.slots,o=a.get(t.index);if(o){o.anchor=t.anchor,o.type=t.type,In(r,o);return}In(r,t),a.set(t.index,t),n.slots.push(t)}forget(e){let t=this.owner(e);t.get(e.index)===e&&t.delete(e.index),e.parent&&(e.parent.children=e.parent.children.filter(t=>t!==e))}forgetChildren(e){for(let t of Ln(e))this.forget(t);e.children=[]}placementIn(e,t){let n=e.slots,r=null,i=null;for(;;){let a=null,o=null;for(let e of n.values())if(e.anchor.kind===`range`&&G(e.anchor,t)){(!a||a.anchor.kind===`range`&&G(a.anchor,e.anchor.start))&&(a=e);for(let n of e.items.values())G(n,t)&&(!o||G(o,n.start))&&(o=n)}if(a&&(r=a),!o)return{region:e,slot:r,item:i};i=o,n=o.slots}}regionConnected(e){return e.ranges=e.ranges.filter(e=>e.start.isConnected),e.ranges.length>0}slotConnected(e){return V(e.anchor)}};function Hn(e){return typeof e==`object`&&!!e&&`template`in e}function Un(e){let t={};for(let[n,r]of Object.entries(e??{}))typeof r==`string`&&(t[Number(n)]=r);return t}function Wn(e,t,n){let r={applied:0,deferred:[]};return Kn(e,t,r,n),r}function Gn(e){return e.item?.slots??e.region.slots}function Kn(e,t,n,r){let i=e.region(t.template,t.occurrence);if(!i){J(n,t,null,`no-region`);return}if(i.version!==t.version){J(n,t,null,`stale-version`);return}t.seeds&&(i.seeds={...i.seeds??{},...t.seeds}),q(e,t,i.slots,t.slots,n,r)}function q(e,t,n,r,i,a){let o=[];for(let[s,c]of Object.entries(r)){if(Hn(c)){Kn(e,c,i,a);continue}let r=Number(s),l=n.get(r);if(!l){J(i,t,r,`no-slot`);continue}if(l.claimed){if(l.type===`conditional`&&typeof c==`object`&&c&&!Array.isArray(c)&&`branch`in c&&!(`items`in c)&&c.slots){if(Xn(e,t,l,c)&&e.announceBranchMaterial(l),c.branch===l.branch)q(e,t,Gn(l),c.slots,i,a);else if(c.branch!==null){let e=l.shown??new Map;e.set(c.branch,{...e.get(c.branch)??{},...Un(c.slots)}),l.shown=e}}continue}if(l.type===`block`&&l.children.length>0){o.push([l,r,c]);continue}qn(e,t,l,r,c,i,a)}for(let[n,r,s]of o)qn(e,t,n,r,s,i,a)}function qn(e,t,n,r,i,a,o){if(typeof i==`boolean`){e.setBooleanAttribute(n,i)?a.applied+=1:J(a,t,r,`partial-attribute`);return}if(typeof i==`string`||Array.isArray(i)){Yn(e,t,n,r,i,a);return}`items`in i?$n(e,t,n,i,a,o):`key`in i?Jn(e,t,n,i,a,o):Zn(e,t,n,i,a,o)}function Jn(e,t,n,r,i,a){if(r.key!==n.key&&!e.rebuildKeyed(n,r.key,Un(r.slots))){J(i,t,n.index,`keyed`);return}q(e,t,n.items.get(r.key)?.slots??Gn(n),r.slots??{},i,a)}function Yn(e,t,n,r,i,a){if(n.type===`block`&&n.children.length>0){e.covers(n,i)||J(a,t,r,`block`);return}let o=n.attribute?Tn(i):i;if(!e.holds(n,o)){if(n.attribute){if(!e.setAttribute(n,o)){J(a,t,r,`partial-attribute`);return}}else if(n.type===`raw_text_interpolation`){if(!e.setText(n,o)){J(a,t,r,`partial-content`);return}}else{if(Array.isArray(o)){J(a,t,r,`partial-attribute`);return}e.update(n,o)}a.applied+=1}}function Xn(e,t,n,r){return r.branch===null||!r.statics?!1:(e.holdStatics({file:t.template,version:t.version},{[`${n.index}:${r.branch}`]:r.statics}),!0)}function Zn(e,t,n,r,i,a){if(Xn(e,t,n,r),r.branch!==n.branch){if(!e.switchBranch(n,r.branch,Un(r.slots))){k({template:t.template,message:`The payload picked branch ${r.branch} of a conditional this page has no material for, so the branch cannot be shown.`,code:`herb-slots-materialize`,severity:`warning`,suggestion:"Render the page with `herb:slots client` to park every branch, or serve the values from a build that sends the branch statics along."}),J(i,t,n.index,`branch`);return}i.applied+=1}r.slots&&q(e,t,Gn(n),r.slots,i,a)}function Qn(e,t,n,r){r.statics&&e.holdStatics({file:t.template,version:t.version},{[E(n.index)]:r.statics})}function $n(e,t,n,r,i,a){Qn(e,t,n,r);let o=r.order??Object.keys(r.items);for(let t of o)e.keepItem(n,t);let s=e.reconcileItems(n,er(e,n,o,a),a);s.length>0&&J(i,t,n.index,`items`,s);for(let s of o){let o=n.items.get(s);if(!o)continue;let{seeds:c,...l}=r.items[s];c&&(o.seeds={...o.seeds??{},...c}),q(e,t,o.slots,l,i,a)}}function er(e,t,n,r){if(r===`merge`)return n;let i=[...n];for(let r of e.reconcile(t,n).removed){let n=t.items.get(r);n&&(e.isLeaving(n)||e.dismissItem(t,r),e.isLeaving(n)&&i.splice(tr(e,t,i,r),0,r))}return i}function tr(e,t,n,r){let i=e.itemsInOrder(t).map(e=>e.key),a=i.slice(0,i.indexOf(r)).reverse();for(let e of a){let t=n.indexOf(e);if(t!==-1)return t+1}return 0}function J(e,t,n,r,i){let a={file:t.template,occurrence:t.occurrence,index:n,reason:r};if(i){e.deferred.push({...a,keys:i});return}e.deferred.push(a)}var nr=class{constructor(){this.journal=new on(this),this.statics=new On,this.manifests=new Mn,this.index=new Vn(this,this.statics,this.manifests),this.collections=new Fn(this,this.journal,this.statics,this.manifests),this.cause=`client`,this.built=null,this.wrote=!1,this.leaving=new Set,this.delegates=new Set,this.elements=null,this.unobserve=null}claim(e){e.claimed=!0}observe(e=document.documentElement,t){return this.unobserve?.(),this.elements=t??new j,this.unobserve=this.elements.add(this),this.elements.observe(e),this.scan(e)}nodesAdded(e){this.scan(e)}nodesRemoved(){this.prune()}disconnect(){this.unobserve?.(),this.unobserve=null,this.elements=null}adoptManifests(e,t={}){if(!t.replace)return this.manifests.hold(e);let n=0;for(let[t,r]of Object.entries(e))this.manifests.push(t,r),n+=1;return n}statesFor(e,t){return this.manifests.statesOf(e,t)}bindingsFor(e){return!e.parent||!e.slot?null:this.manifests.bindingsOf(e.parent.file,e.parent.version,e.slot.index)}holdStatics(e,t){let n=0;for(let[r,i]of Object.entries(t)){let t=document.createElement(`template`);t.innerHTML=i,this.statics.push(e,r,t.content),n+=1}return n}evictManifests(e,t){return this.manifests.evict(e,t)}rangeOf(e){return`anchor`in e?Wt(e.anchor):H(e)}descendantsOf(e){return Ln(e)}ancestorsOf(e){return Rn(e)}apply(e,t={}){return this.building(`apply`,()=>Wn(this,e,t.items??`replace`))}scan(e,t){return this.index.scan(e,t)}locate(e){return this.index.locate(e)}placements(e){return this.index.placements(e)}regionsFor(e){return this.index.regionsFor(e)}regions(){return this.index.regions()}files(){return this.index.files()}parkedRoots(){let e=this.statics.all();for(let t of this.regions())for(let n of t.slots.values())this.capturedIn(n,e);return e}capturedIn(e,t){for(let n of e.captured?.values()??[])t.push(n);for(let n of e.items.values())for(let e of n.slots.values())this.capturedIn(e,t)}slotsFor(e,t){return this.index.slotsFor(e,t)}region(e,t=0){return this.index.region(e,t)}slot(e,t,n=0){return this.index.slot(e,t,n)}itemsFor(e,t,n=0){return this.index.itemsFor(e,t,n)}slotInItem(e,t,n,r,i=0){return this.index.slotInItem(e,t,n,r,i)}regionOf(e){return this.index.regionOf(e)}slotAt(e){return this.index.slotAt(e)}get size(){return this.index.size}prune(){return this.index.prune()}pruneItems(e){this.collections.pruneItems(e)}clear(){this.index.clear()}subscribe(e){return this.delegates.add(e),()=>{this.delegates.delete(e)}}building(e,t){if(this.built)return t();let n={branches:[],items:[]},r=this.cause;this.built=n,this.cause=e,this.wrote=!1;try{return t()}finally{if(this.built=null,this.cause=r,(n.branches.length>0||n.items.length>0)&&this.announceBuilt(n,e),this.wrote){this.wrote=!1;for(let e of[...this.delegates])e.settled?.()}}}transaction(e){return this.journal.transaction(e)}revert(e){return this.journal.revert(e)}addressOf(e){let t=[],n=e.item;for(;n;)t.unshift({collection:n.collection.index,key:n.key}),n=n.collection.item;return{region:e.region,path:t,index:e.index}}swapBranch(e,t,n){if(this.journal.record(e,()=>{let t=this.current(e),n=e.branch;return e=>{this.update(e,t),e.branch=n}}),this.capture(e),t===null)return this.update(e,``),e.branch=null,!0;let r=this.branchMarkup(e,t,n);return r?(this.writeFragment(e,r),e.branch=t,this.built?.branches.push(e),this.focusAutofocus(e),!0):!1}branchMarkup(e,t,n){let r=e.captured?.get(t);if(r){let i=r.cloneNode(!0);return pn(i,{...e.shown?.get(t)??{},...n},!1,t=>this.manifests.partsForFile(e.region.file,t)),i}return this.materialize(e.region.file,T(e.index,t),{...e.shown?.get(t)??{},...n})}focusAutofocus(e){if(typeof document>`u`||e.anchor.kind!==`range`||!e.anchor.start.isConnected)return;let t=this.rangeOf(e),n=t.commonAncestorContainer,r=(n instanceof Element?n:n.parentElement)?.querySelector(`[autofocus]`);r&&t.intersectsNode(r)&&document.activeElement!==r&&r.focus()}partsFor(e,t){return this.manifests.partsOf(e.file,e.version,t)}rewrite(e,t,n){let r=[...t.childNodes];return e.deleteContents(),e.insertNode(t),this.scan(r,n)}writeFragment(e,t){this.index.forgetChildren(e),this.rewrite(this.rangeOf(e),t,{region:e.region,slot:e,item:e.item}),this.announce(e,`branch`,t=>t.branchSwitched?.(e))}currentText(e){return this.attributeValue(e)??Kt(e.anchor)}setText(e,t){if(e.anchor.kind===`element`)return!1;let n=t;if(e.type===`raw_text_interpolation`){let r=this.interpolate(e,t);if(r===null)return!1;n=r}if(Array.isArray(n)||this.currentText(e)===n)return!1;if(this.journal.record(e,()=>{let t=this.current(e);return e=>{this.update(e,t)}}),this.index.forgetChildren(e),e.anchor.kind===`content`)e.anchor.element.textContent=n;else{let t=document.createDocumentFragment();t.append(document.createTextNode(n)),this.rewrite(this.rangeOf(e),t,{region:e.region,slot:e,item:e.item})}return this.announce(e,`value`,t=>t.valueWritten?.(e)),!0}attributeValue(e){let t=z(e.anchor);return!t||!e.attribute?null:t.getAttribute(e.attribute)??``}current(e){return Gt(e.anchor)}covers(e,t){return!Array.isArray(t)&&wn(this.current(e))===wn(t)}holds(e,t){if(e.type===`attribute_interpolation`){let n=this.interpolate(e,t);return n!==null&&this.attributeValue(e)===n}if(e.type===`raw_text_interpolation`){let n=this.interpolate(e,t);return n!==null&&this.currentText(e)===n}if(Array.isArray(t))return!1;let n=this.attributeValue(e);return n===null?this.current(e)===t:n===t}announce(e,t,n,{key:r=null,item:i=null,previousKey:a=null}={}){let o=e.region??null;this.wrote=!0;for(let e of[...this.delegates])n(e);this.dispatch({file:o?.file??``,occurrence:o?.occurrence??0,index:e.index,operation:t,key:r,previousKey:a,slot:e,item:i,cause:this.cause})}announceBuilt(e,t){let[n]=e.branches.length>0?e.branches:e.items.map(e=>e.slot),r=n?.region??null;for(let t of[...this.delegates])t.built?.(e);this.dispatch({file:r?.file??``,occurrence:r?.occurrence??0,index:n?.index??0,operation:`built`,key:null,previousKey:null,slot:null,item:null,cause:t,built:e})}dispatch(e){typeof document<`u`&&document.dispatchEvent(new CustomEvent(rn,{detail:e}))}update(e,t){if(this.current(e)===t)return{regions:[],slots:[]};if(this.journal.record(e,()=>{let t=this.current(e);return e=>{this.update(e,t)}}),this.index.forgetChildren(e),e.anchor.kind===`element`){let n=this.rangeOf(e).createContextualFragment(t),r=e.anchor.element,i=r.parentNode;return r.replaceWith(n),this.index.forget(e),i?this.scan([...i.childNodes],{region:e.region,slot:e.parent,item:e.item}):this.scan([])}let n=this.rangeOf(e),r=this.rewrite(n,n.createContextualFragment(t),{region:e.region,slot:e,item:e.item});return this.announce(e,`value`,t=>t.valueWritten?.(e)),r}updateItem(e,t,n){let r=e.items.get(t);if(!r)return null;if(W(this.rangeOf(r))===n)return{regions:[],slots:[]};this.journal.record(e,()=>{let e=W(this.rangeOf(r));return n=>{this.updateItem(n,t,e)}});let i=this.rangeOf(r),a=this.rewrite(i,i.createContextualFragment(n),{region:e.region,slot:e,item:r});return this.announce(e,`item-updated`,n=>n.itemUpdated?.(e,t,e.items.get(t)??null),{key:t,item:e.items.get(t)??null}),a}setAttribute(e,t,n=e.attribute){if(!z(e.anchor)||n===null)return!1;let r=t;return e.type===`attribute_interpolation`&&(r=this.interpolate(e,t),r===null)||Array.isArray(r)?!1:this.writeAttribute(e,r,n)}writeAttribute(e,t,n){let r=z(e.anchor);return r?r.getAttribute(n)===t||(this.journal.record(e,()=>{let e=r.getAttribute(n);return t=>{this.writeAttribute(t,e,n)}}),t===null?r.removeAttribute(n):r.setAttribute(n,t),this.announce(e,`attribute`,t=>t.attributeWritten?.(e)),!0):!1}setBooleanAttribute(e,t,n=e.attribute){let r=z(e.anchor);return!r||n===null||e.type!==`boolean_attribute`?!1:r.hasAttribute(n)===t||(this.journal.record(e,()=>{let e=r.hasAttribute(n);return t=>{this.setBooleanAttribute(t,e,n)}}),r.toggleAttribute(n,t),n in r&&(r[n]=t),this.announce(e,`attribute`,t=>t.attributeWritten?.(e)),!0)}interpolate(e,t){return t===null?null:xn(this.partsFor(e.region,e.index),t)}capture(e){if(e.branch===null)return!1;let t=this.rangeOf(e).cloneContents(),n=e.captured??new Map;return n.set(e.branch,t.cloneNode(!0)),e.captured=n,this.remember(e,e.branch,hn(t)),this.statics.park(e.region,T(e.index,e.branch),this.statics.blanked(t))}remember(e,t,n){let r=e.shown??new Map;r.set(t,n),e.shown=r}parked(e,t){return this.statics.parked(e,t)}parkedKeys(e){return this.statics.keys(e)}branchesFor(e,t){return this.statics.branches(e,t)}renderModeFor(e,t){return this.statics.mode(e,t)}materialize(e,t,n={}){return this.statics.materialize(e,t,n,t=>this.manifests.partsForFile(e,t))}holdBranch(e,t){return this.held(n=>n.holdBranch?.(e,t))}holdItem(e,t){return this.held(n=>n.holdItem?.(e,t))}held(e){let t=[];for(let n of[...this.delegates]){let r=e(n);r&&t.push(r)}return t.length===0?null:Promise.allSettled(t).then(()=>void 0)}dismissItem(e,t){let n=e.items.get(t);if(!n)return!1;let r=this.holdItem(e,n);return r?(this.leaving.add(n),r.then(()=>{this.leaving.delete(n)&&e.items.get(t)===n&&this.removeItem(e,t)}),!0):this.removeItem(e,t)}keepItem(e,t){let n=e.items.get(t);n&&this.leaving.delete(n)}isLeaving(e){return this.leaving.has(e)}itemsInOrder(e){return this.collections.itemsInDocumentOrder(e)}announceItemsMoving(e,t){for(let n of[...this.delegates])n.itemsMoving?.(e,t)}announceItemsMoved(e,t){for(let n of[...this.delegates])n.itemsMoved?.(e,t)}switchBranch(e,t,n={}){return t!==e.branch&&this.building(`client`,()=>this.swapBranch(e,t,n))}rebuildKeyed(e,t,n={}){return e.type!==`keyed`||e.anchor.kind!==`range`||t===e.key?!1:this.building(`client`,()=>this.swapKeyed(e,t,n))}swapKeyed(e,t,n){if(e.anchor.kind!==`range`)return!1;let r=this.keyedMarkup(e,n);if(!r)return!1;this.journal.record(e,()=>{let t=this.current(e),n=e.key;return e=>{e.anchor.kind===`range`&&(e.items.clear(),e.items.set(n??``,{key:n??``,start:e.anchor.start,end:e.anchor.end,slots:new Map,collection:e}),e.anchor.start.data=Ke(e.index,n??``)),e.key=n,this.update(e,t)}});let i=e.key,a={key:t,start:e.anchor.start,end:e.anchor.end,slots:new Map,collection:e};return this.index.forgetChildren(e),e.items.clear(),e.items.set(t,a),this.rewrite(this.rangeOf(e),r,{region:e.region,slot:e,item:a}),e.anchor.start.data=Ke(e.index,t),e.key=t,this.focusAutofocus(e),this.announce(e,`keyed`,n=>n.keyedRebuilt?.(e,t,i),{key:t,previousKey:i}),!0}keyedMarkup(e,t){let n=this.materialize(e.region.file,E(e.index),t);if(n){for(let e of[...n.childNodes]){if(e.nodeType!==Node.COMMENT_NODE)continue;let t=C(e.data.trim());t&&t.branch===`item`&&e.remove()}return n}let r=document.createRange().createContextualFragment(``);return r.append(this.rangeOf(e).cloneContents()),vn(r),_n(r),pn(r,t,!1,t=>this.manifests.partsForFile(e.region.file,t)),r}invalidateStale(e,t){let n=e=>{for(let r of e.values()){if(r.shown)for(let e of r.shown.values())for(let n of Object.keys(e))(t.has(Number(n))||this.embedsStale(e[Number(n)],t))&&delete e[Number(n)];if(r.captured)for(let[e,n]of[...r.captured])this.holdsAny(n,t)&&r.captured.delete(e);for(let e of r.items.values())n(e.slots)}};n(e.slots)}embedsStale(e,t){if(typeof e!=`string`)return!1;for(let n of e.matchAll(/<!--\s*herb-slot:(\d+)/g))if(t.has(Number(n[1])))return!0;return!1}holdsAny(e,t){for(let n of R(e)){let e=w(n.data.trim());if(e!==null&&t.has(e))return!0}for(let[,n]of I(e))if(t.has(n.index))return!0;return!1}recordBuilt(e,t){this.built?.items.push({slot:e,item:t})}announceBranchMaterial(e){this.announce(e,`branch-material`,t=>t.branchMaterial?.(e),{})}announceItemAdded(e,t,n){this.announce(e,`item-added`,r=>r.itemAdded?.(e,t,n),{key:t,item:n})}announceItemRemoved(e,t,n){this.announce(e,`item-removed`,r=>r.itemRemoved?.(e,t,n),{key:t,item:n})}announceItemRekeyed(e,t,n,r){this.announce(e,`item-rekeyed`,i=>i.itemRekeyed?.(e,t,n,r),{key:t,item:r,previousKey:n})}reconcile(e,t){return this.collections.reconcile(e,t)}reconcileItems(e,t,n=`replace`){return this.collections.reconcileItems(e,t,n)}addItem(e,t,n={}){return this.collections.addItem(e,t,n)}removeItem(e,t){return this.collections.removeItem(e,t)}rekeyItem(e,t,n){return this.collections.rekeyItem(e,t,n)}};function rr(e){if(!e||!Array.isArray(e))return null;let[t,n,r,i]=e;return n!==null||r||i?null:typeof t==`string`?t:null}function ir(e){if(Array.isArray(e)){let[t,n,r,i]=e;return i===void 0?{branch:r,condition:[t,n]}:{branch:r,condition:[t,n,i]}}if(`condition`in e)return e;let{branch:t,...n}=e;return{branch:t,condition:n}}function Y(e,t){if(!Array.isArray(e))return e.all?e.all.every(e=>Y(e,t)):dr(e).some(e=>Y(e,t));let[n,r,i,a]=e,o=typeof a==`string`?or(a,t(n)):t(n);if(i===`blank`)return cr(o);if(i===`present`)return!cr(o);if(i===`falsy`)return!ar(o);if(r===null)return ar(o);let s=ur(r,t);if(i===void 0||i===`==`)return o===s;if(i===`!=`)return o!==s;if(typeof o!=`number`||typeof s!=`number`)return!1;switch(i){case`>`:return o>s;case`>=`:return o>=s;case`<`:return o<s;case`<=`:return o<=s;default:return!1}}function X(e,t){if(!Array.isArray(e))return dr(e).some(e=>X(e,t));let[n,r]=e;return t.includes(n)?!0:typeof r==`object`&&!!r&&`state`in r&&t.includes(r.state)}function ar(e){return e!==!1&&e!==null}function or(e,t){return e===`to_s`?t===null?``:String(t):e===`length`?typeof t==`string`?[...t].length:0:t}function sr(e,t){if(Array.isArray(e)){let[n,r,i,a]=e;if(typeof a==`string`&&r===null&&!i)return or(a,t(n))}return Y(e,t)}function cr(e){return e===null||e===!1||typeof e==`string`&&/^\s*$/.test(e)}function lr(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t===`nil`)return null;if(/^-?\d+$/.test(t))return Number(t);if(/^:[a-zA-Z_]\w*[?!]?$/.test(t))return t.slice(1);if(/^"(?:[^"\\]|\\.)*"$/.test(t)||/^'(?:[^'\\]|\\.)*'$/.test(t))return t.slice(1,-1).replace(/\\(.)/g,`$1`)}function ur(e,t){if(typeof e==`string`)return lr(e);if(`state`in e){let n=t(e.state);return e.transform?or(e.transform,n):n}return e.value}function dr(e){return e.all??e.any??[]}function Z(e,t,n){return e.declarations.find(e=>e.name===t?n===null?e.scope===`region`:e.scope===n:!1)||(n===null?null:e.declarations.find(e=>e.name===t&&e.scope===`region`)??null)}function fr(e){return e.line===void 0||e.line===null?{}:{location:{start:{line:e.line,column:e.column??0}}}}function pr(e){return e.value===void 0?lr(e.default):e.value}function mr(e){if(typeof e!=`object`||!e)return typeof e==`string`?lr(e):void 0;if(!(`state`in e))return e.value}var hr=class{constructor(e,t){this.store=new Map,this.reported=new WeakMap,this.delegate=e,this.slots=t}held(e,t){return this.store.get(e.region)?.get(e.item?.key??``)?.get(t)}migrateRegion(e,t){let n=this.store.get(e);n&&(this.store.delete(e),this.store.set(t,n));let r=this.reported.get(e);r&&(this.reported.delete(e),this.reported.set(t,r))}forget(e,t){let n=this.store.get(e);if(n)for(let e of n.values())e.delete(t)}migrate(e,t,n){let r=this.store.get(e),i=r?.get(t);r&&i&&(r.delete(t),r.set(n,i))}valueFor(e,t){let n=yt(this.store,t);if(n.has(e))return n.get(e);let r=this.delegate.manifestFor(t.region);if(!r)return;let i=this.firstOf(r,t,e);return i!==void 0&&n.set(e,i),i}firstOf(e,t,n){let r=this.shipped(e,t,n);if(r!==void 0)return r;let i=this.fromValueSlot(e,t,n);if(i!==void 0)return i;let a=this.fromConditional(e,t,n);return a===void 0?this.fromDeclaration(e,t,n):a}fromDeclaration(e,t,n){let r=this.delegate.declarationFor(e,t,n);return r?pr(r):void 0}shipped(e,t,n){let r=this.delegate.declarationFor(e,t,n);if(!r||r.derived||r.count)return;let i=t.item?.seeds?.[n]??t.region.seeds?.[n];if(i===void 0){this.warnUnshipped(t,r,n);return}return this.readShipped(t,r,n,i)}warnUnshipped(e,t,n){(e.item?.seeds??e.region.seeds)&&pr(t)===void 0&&this.warn(e,t,`the server shipped no value for \`${n}\`; its rendered value was not a boolean, number, string, or nil, so the client falls back to what the page shows`,`seed the state with a primitive, since that is all a state can hold`)}readShipped(e,t,n,r){let i=mt(r,t.kind),a=ht(t.kind);if(i===void 0){this.warn(e,t,`the server shipped ${JSON.stringify(r)} for \`${n}\`, which is declared as ${a}, and the client cannot read it as one`,`seed the state with ${a}`);return}return i!==r&&this.warn(e,t,`the server shipped ${JSON.stringify(r)} for \`${n}\`, which is declared as ${a}, so the client coerced it to ${JSON.stringify(i)}`,`seed the state with ${a}`),i}warn(e,t,n,r){let i=this.reported.get(e.region)??new Set,a=`${e.item?.key??``}:${t.name}`;i.has(a)||(i.add(a),this.reported.set(e.region,i),k({template:e.region.file,message:n,code:`herb-state-type`,severity:`warning`,value:t.name,suggestion:r,...fr(t)}))}fromValueSlot(e,t,n){let r=this.delegate.declarationFor(e,t,n);for(let i of e.reads[n]??[])if(!e.computed?.[String(i)])for(let n of this.delegate.scopedSlots(t,i)){if(n.claimed||Re.includes(n.type))continue;let t=z(n.anchor);if(n.type===`boolean_attribute`){let a=e.presence?.[String(i)];if(!a||!Array.isArray(a)||a[1]!==null||!t||!n.attribute)continue;let o=a[2],s=t.hasAttribute(n.attribute);if(o==null)return s;if(r?.kind!==`boolean`)continue;if(o===`falsy`||o===`blank`)return!s;if(o===`truthy`||o===`present`)return s;continue}return ft(this.slots.currentText(n),r?.kind??`string`)}}fromConditional(e,t,n){for(let[r,i]of Object.entries(e.conditionals)){let a=i.arms.map(e=>ir(e));if(a.some(e=>Array.isArray(e.condition)&&e.condition[0]===n))for(let o of this.delegate.scopedSlots(t,Number(r))){let r=a.find(e=>e.branch===o.branch)?.condition,s=Array.isArray(r)&&r[0]===n?r:null;if(s)return s[2]===void 0?this.literalOf(s[1]):void 0;if(o.branch===i.else||o.branch===null)return this.whenNoBranchShowsIt(e,t,n)}}}whenNoBranchShowsIt(e,t,n){return this.delegate.declarationFor(e,t,n)?.kind!==`boolean`&&void 0}literalOf(e){return e===null||mr(e)}},gr=class{constructor(e,t){this.queued=new Set,this.last=new WeakMap,this.delegate=e,this.slots=t}migrateRegion(e,t){let n=this.last.get(e);n&&(this.last.delete(e),this.last.set(t,n)),this.queued.delete(e)&&this.queued.add(t)}declarationsIn(e){return e.declarations.filter(e=>e.count)}countFor(e,t){let n=e.count;if(n==null)return null;let r=pr(e),i=t.region.slots.get(n.collection),a=0;if(typeof r==`number`&&(a=r),!i)return a;let o=i.items,s=0;for(let e of o.values()){let r=N(t.region,e);(n.when===null||n.when===void 0||Y(n.when,e=>this.delegate.valueAt(e,r)))&&(s+=1)}return a+s*(n.by??1)}itemsChanged(e){let t=this.slots.regionOf(e);if(!t)return;let n=this.delegate.manifestFor(t);n&&this.declarationsIn(n).some(t=>t.count?.collection===e.index)&&(this.queued.has(t)||(this.queued.add(t),queueMicrotask(()=>{this.queued.delete(t),this.recount(t)})))}recount(e){let t=this.delegate.manifestFor(e);if(!t)return;let n=N(e),r=[];for(let i of this.declarationsIn(t)){let t=this.last.get(e)?.get(i.name)??null,a=this.delegate.valueAt(i.name,n);a!==t&&r.push({name:i.name,value:a,previous:t})}if(r.length===0)return;let i=this.delegate.derivedDependents(t,n,r.map(e=>e.name)).map(t=>({name:t,previous:this.last.get(e)?.get(t)??null,value:this.delegate.valueAt(t,n)})).filter(e=>e.value!==e.previous),a=this.last.get(e)??new Map;for(let e of[...r,...i])a.set(e.name,e.value);this.last.set(e,a),this.delegate.countsChanged(t,n,[...r,...i])}},_r=class{constructor(e,t,n={}){this.timer=null,this.due=1/0,this.epoch=0,this.controller=null,this.waiting=[],this.slots=e,this.delegate=t,this.options=n}request(e=0){let t=new Promise(e=>this.waiting.push(e)),n=Date.now()+e;return(this.timer===null||n<this.due)&&(this.timer!==null&&clearTimeout(this.timer),this.due=n,this.timer=setTimeout(()=>void this.run(),e)),t}flush(){return this.request(0)}stop(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.due=1/0,this.controller?.abort(),this.settle({applied:0,deferred:0,stale:!0,failed:!1},this.waiting.splice(0))}async run(){this.timer=null,this.due=1/0,this.controller?.abort();let e=new AbortController,t=this.epoch+=1,n=this.waiting.splice(0);this.controller=e;let r;try{r=await this.transport()(this.steering(),e.signal)}catch{let r=t!==this.epoch||e.signal.aborted;this.settle({applied:0,deferred:0,stale:r,failed:!r},n);return}if(t!==this.epoch){this.settle({applied:0,deferred:0,stale:!0,failed:!1},n);return}let i;await x(()=>{i=this.slots.apply(r)}),this.settle({applied:i.applied,deferred:i.deferred.length,stale:!1,failed:!1},n)}settle(e,t){for(let n of t)n(e)}transport(){return this.options.transport?this.options.transport:(e,t)=>P(window.location.href,{format:this.options.format,state:e,signal:t})}steering(){let e={},t=4096;for(let n of this.slots.regions()){let r=this.delegate.manifestFor(n);if(!r||e[n.file])continue;let i={};for(let e of vr(r)){let r=this.delegate.steeringValue(n,e);if(r===void 0)continue;let a=e.length+JSON.stringify(r??null).length+8;a>t||(t-=a,i[e]=r)}Object.keys(i).length>0&&(e[n.file]=i)}return e}};function vr(e){let t=new Set;for(let n of Object.values(e.conditionals??{}))for(let e of n.arms)yr(ir(e).condition,t);for(let n of Object.keys(e.server?.reads??{}))t.add(n);let n=new Set;for(let t of e.declarations)t.scope===`region`&&!t.derived&&!t.count&&n.add(t.name);return new Set([...t].filter(e=>n.has(e)))}function yr(e,t){if(Array.isArray(e)){typeof e[0]==`string`&&t.add(e[0]);let n=e[1];n&&typeof n==`object`&&`state`in n&&typeof n.state==`string`&&t.add(n.state);return}for(let n of br(e))yr(n,t)}function br(e){return e.all??e.any??[]}var xr=class{constructor(e,t){this.showing=new Map,this.armed=new Set,this.observers=new Map,this.polls=new Map,this.slots=e,this.delegate=t}showFallbacks(e,t,n,r=[]){let i=Object.entries(e.fragments??{}).sort(([e],[t])=>Number(e)-Number(t));for(let[e,a]of i)if(a.reads?.some(e=>n.has(e))&&(!a.on||a.on.some(e=>r.includes(e))))for(let n of this.delegate.placedSlots(t,Number(e)))this.present(n.slot,a)}settle(e){if(!e.stale)for(let[t,n]of this.showing){if(n.restoreTimer!==null)continue;if(n.showTimer!==null&&(clearTimeout(n.showTimer),n.showTimer=null),n.shownAt===0||e.failed){this.showing.delete(t);continue}let r=n.shownAt+n.hold-Date.now();if(t.branch===n.fallback){if(!n.deferred){this.showing.delete(t);continue}n.restoreTimer=setTimeout(()=>{this.showing.delete(t),x(()=>this.delegate.resettle(t),B(t.anchor)??document)},Math.max(r,0));continue}if(r<=0){this.showing.delete(t);continue}let i=t.branch;n.restoreTimer=setTimeout(()=>{this.showing.delete(t),t.branch===n.fallback&&x(()=>void this.slots.switchBranch(t,i),B(t.anchor)??document)},r),this.slots.switchBranch(t,n.fallback)&&this.delegate.resettle(t)}}holding(e){return(this.showing.get(e)?.shownAt??0)>0}hydrated(){this.sweep();for(let e of this.slots.regions()){let t=this.delegate.manifestFor(e)?.fragments;if(!t)continue;let n=N(e);for(let[e,r]of Object.entries(t))if(r.mode&&r.state)for(let t of this.delegate.placedSlots(n,Number(e)))this.arm(t.slot,Number(e),r,t.scope)}}disconnect(){for(let e of this.showing.values())e.showTimer!==null&&clearTimeout(e.showTimer),e.restoreTimer!==null&&clearTimeout(e.restoreTimer);this.showing.clear();for(let e of this.observers.values())e.disconnect();this.observers.clear(),this.armed.clear();for(let e of this.polls.values())clearTimeout(e);this.polls.clear()}sweep(){for(let[e,t]of this.polls)V(e.anchor)||(clearTimeout(t),this.polls.delete(e));for(let[e,t]of this.observers)V(e.anchor)||(t.disconnect(),this.observers.delete(e));for(let e of this.armed)V(e.anchor)||this.armed.delete(e)}present(e,t){let n=this.showing.get(e);if(n){n.restoreTimer!==null&&(clearTimeout(n.restoreTimer),n.restoreTimer=null);return}let r={fallback:t.fallback,hold:t.hold??300,deferred:!!t.mode,shownAt:0,showTimer:null,restoreTimer:null};this.showing.set(e,r);let i=t.delay??150;if(i<=0||e.branch===null||e.branch===r.fallback||this.blank(e,t)){this.swapToFallback(e,r);return}r.showTimer=setTimeout(()=>{r.showTimer=null,this.swapToFallback(e,r)},i)}blank(e,t){let n=t.reads??[];if(n.length===0)return!1;let r=this.slots.descendantsOf(e);return!n.some(e=>{let t=r.find(t=>t.index===e);return t?this.slots.currentText(t).trim()!==``:!1})}swapToFallback(e,t){t.shownAt=Date.now(),t.deferred&&this.slots.claim(e),e.branch!==t.fallback&&this.slots.switchBranch(e,t.fallback)&&this.delegate.resettle(e)}arm(e,t,n,r){if(this.armed.has(e))return;if(this.armed.add(e),e.branch!==n.fallback){this.armPoll(e,t,n,r);return}if(n.mode===`async`||typeof IntersectionObserver>`u`){this.trigger(e,t,n,r);return}let i=this.sentinelFor(e);if(!i){this.trigger(e,t,n,r);return}let a=new IntersectionObserver(i=>{i.some(e=>e.isIntersecting)&&(a.disconnect(),this.observers.delete(e),this.trigger(e,t,n,r))});a.observe(i),this.observers.set(e,a)}trigger(e,t,n,r){this.present(e,n),this.delegate.writeInternal(n.state,r),this.delegate.requestBlock(r.region,t).then(i=>{this.settle(i),this.armPoll(e,t,n,r)})}armPoll(e,t,n,r){let i=n.poll??0;if(i<=0||this.polls.has(e))return;let a=()=>{this.polls.set(e,setTimeout(()=>{if(!V(e.anchor)){this.polls.delete(e),this.armed.delete(e);return}if(document.hidden){a();return}this.delegate.requestBlock(r.region,t).then(t=>{this.settle(t),this.polls.has(e)&&a()})},i))};a()}sentinelFor(e){let t=e.anchor;if(t.kind===`range`){let e=t.start.nextSibling;for(;e&&e!==t.end;){if(e instanceof Element)return e;e=e.nextSibling}}return B(t)}};const Q={applied:0,deferred:[],written:0,restored:0,stale:!1,failed:!1};var Sr=class{constructor(e,t){this.values=new Map,this.dependencies=new Map,this.params=new Map,this.sequence=new Map,this.pending=new Map,this.restores=[],this.previous=new Map,this.waiting=[],this.timer=null,this.controller=null,this.slots=e,this.options=t}get(e){return this.values.get(e)}all(){return Object.fromEntries(this.values)}names(){return[...this.dependencies.keys()]}slotsFor(e){return this.dependencies.get(this.stateName(e))??[]}adopt(e){for(let[t,n]of Object.entries(e.state??{}))this.dependencies.set(t,n);for(let[t,n]of Object.entries(e.params??{}))this.params.set(t,n)}known(e){return this.params.has(e)||this.dependencies.has(e)}set(e,t){let n=e;typeof e==`string`&&(n={[e]:t??``});let r=Object.keys(n);for(let[e,t]of Object.entries(n))this.pending.set(e,t),this.sequence.set(e,(this.sequence.get(e)??0)+1),this.previous.has(e)||this.previous.set(e,this.values.get(e)),this.values.set(e,t);return this.restores.push(...this.slots.building(`client`,()=>this.optimistic(r))),this.options.debounce<=0?this.flush():(this.timer&&clearTimeout(this.timer),new Promise(e=>{this.waiting.push(e),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.debounce)}))}async flush(){let e=this.pending,t=this.restores,n=this.previous,r=this.waiting;if(this.pending=new Map,this.restores=[],this.previous=new Map,this.waiting=[],e.size===0)return this.settle(Q,r);let i=[...e.keys()],a=new Map(i.map(e=>[e,this.sequence.get(e)??0]));this.controller?.abort();let o=new AbortController;this.controller=o;let s=null;try{s=await this.options.transport({state:this.all(),changed:i},o.signal)}catch{if(o.signal.aborted||this.superseded(a))return this.settle({...Q,written:t.length,stale:!0},r);this.slots.building(`client`,()=>this.restore(t));for(let[e,t]of n)t===void 0?this.values.delete(e):this.values.set(e,t);return this.settle({...Q,written:t.length,restored:t.length,failed:!0},r)}if(this.superseded(a))return this.settle({...Q,written:t.length,stale:!0},r);let c={applied:0,deferred:[]};if(s){let e=s;await x(()=>{c=this.slots.apply(e)})}return this.settle({...c,written:t.length,restored:0,stale:!1,failed:!1},r)}settle(e,t){for(let n of t)n(e);return e}superseded(e){for(let[t,n]of e)if((this.sequence.get(t)??0)!==n)return!0;return!1}optimistic(e){let t=[];for(let n of e){let e=this.values.get(n)??``;for(let r of this.dependencies.get(this.stateName(n))??[])for(let n of this.resolve(r)){let r=this.slots.currentText(n);this.writeSlot(n,e)&&t.push({slot:n,value:r})}}return t}restore(e){for(let t of[...e].reverse())this.writeSlot(t.slot,t.value)}resolve(e){let t=[];for(let n of this.slots.regionsFor(e.file)){if(n.version!==e.version)continue;let r=n.slots.get(e.index);r&&t.push(r)}return t}async fetch(e,t){let n=new URL(window.location.href);for(let[t,r]of Object.entries(e.state))n.searchParams.set(t,r);return await P(n,{format:this.options.format,signal:t})}stateName(e){return this.params.get(e)??e}writeSlot(e,t){return z(e.anchor)&&e.attribute?this.slots.setAttribute(e,t):this.slots.setText(e,t)}};const Cr=[`input`,`textarea`,`select`],wr=[`input`,`textarea`,`select`,`option`],Tr=[`value`,`checked`,`selected`];function Er(e){if(e.type===`attribute_interpolation`||e.type===`raw_text_interpolation`)return!1;let t=z(e.anchor);return t?e.attribute?Tr.includes(e.attribute)&&wr.includes(t.localName):t.localName===`textarea`:!1}var Dr=class{constructor(e){this.onInput=e=>{let t=e.target;t instanceof Element&&this.sync(t)},this.onReset=e=>{let t=e.target;t instanceof HTMLFormElement&&setTimeout(()=>{for(let e of t.elements)this.sync(e)},0)},this.delegate=e}observe(){document.addEventListener(`input`,this.onInput),document.addEventListener(`change`,this.onInput),document.addEventListener(`reset`,this.onReset)}disconnect(){document.removeEventListener(`input`,this.onInput),document.removeEventListener(`change`,this.onInput),document.removeEventListener(`reset`,this.onReset)}sync(e){let t=this.nameOf(e);if(!t)return;let n=pt(e,this.delegate.declarationFor(t.manifest,t.scope,t.name)?.kind??`string`);this.delegate.setState({[t.name]:n},{scope:t.scope})}resetForm(e){for(let t of e.elements){let e=this.nameOf(t);e&&this.delegate.reset(e.name,{scope:e.scope})}}nameOf(e){if(!Cr.includes(e.localName))return null;let t=this.delegate.scopeFor(e);if(!t)return null;let n=this.delegate.manifestFor(t.region);if(!n)return null;let r=n.bound;for(let[i,a]of Object.entries(r??n.reads??{}))for(let o of a)for(let a of this.delegate.scopedSlots(t,o))if(z(a.anchor)===e&&(r||Er(a))&&(r||a.type!==`boolean_attribute`||rr(n.presence?.[String(o)])===i))return{name:i,scope:t,manifest:n};return null}slotWritten(e){let t=z(e.anchor);if(!t||e.attribute!==`value`||!Cr.includes(t.localName))return;let n=t.getAttribute(`value`)??``;t.value!==n&&(t.value=n)}},Or=class{constructor(e,t={}){this.declared=new Map,this.scoped=new Map,this.bound=new Dr(this),this.elements=null,this.unobserveElements=null,this.unsubscribe=null,this.disarmMutationRefresh=null,this.options={transport:t.transport??((e,t)=>this.server.fetch(e,t)),debounce:t.debounce??0,format:t.format??`slots`,refetch:t.refetch??`auto`,refetchDebounce:t.refetchDebounce??150,refetchTransport:t.refetchTransport},this.slots=e,this.seeds=new hr(this,e),this.counts=new gr(this,e),this.server=new Sr(e,this.options),this.refetch=new _r(e,{manifestFor:e=>this.manifestFor(e),steeringValue:(e,t)=>this.valueAt(t,N(e))},{transport:this.options.refetchTransport,format:this.options.format}),this.fragments=new xr(e,{manifestFor:e=>this.manifestFor(e),placedSlots:(e,t)=>this.placedSlots(e,t),writeInternal:(e,t)=>void this.setState({[e]:!0},{scope:t}),requestBlock:(e,t)=>this.fetchBlock(e,t),resettle:e=>this.settleBranch(e)}),this.disarmMutationRefresh=St(()=>this.refreshAfterMutation()),this.unsubscribe=e.subscribe(this)}refresh(){return this.refetch.flush()}refreshAfterMutation(){if(this.options.refetch!==`off`)for(let e of this.slots.regions()){let t=this.manifestFor(e)?.server;if(t&&(Object.keys(t.reads??{}).length>0||Object.keys(t.branches??{}).length>0)){this.refetch.request(0);return}}}set(e,t){return this.server.set(e,t)}built(e){this.settle(e),this.fragments.hydrated()}branchMaterial(e){this.settleBranch(e)}itemAdded(e){this.counts.itemsChanged(e)}keyedRebuilt(e,t){let n=e.items.get(t);n&&this.settleItem(e,n)}itemRemoved(e){this.counts.itemsChanged(e)}get(e){return this.server.get(e)}all(){return this.server.all()}names(){return this.server.names()}slotsFor(e){return this.server.slotsFor(e)}migrateRegion(e,t,n={}){let r=this.scoped.get(e);r&&(this.scoped.delete(e),this.scoped.set(t,r)),this.seeds.migrateRegion(e,t),this.counts.migrateRegion(e,t);for(let e of n.except??[]){if(r)for(let t of r.values())t.delete(e);this.seeds.forget(t,e)}}resettle(e){let t=this.manifestFor(e);if(t)for(let n of Object.values(t.reads))for(let t of n){let n=e.slots.get(t);n&&this.slots.claim(n)}for(let t of e.slots.values()){this.settleBranch(t);for(let e of t.items.values())this.settleItem(t,e)}}settle(e){for(let t of e.branches)this.settleBranch(t);for(let{slot:t,item:n}of e.items)this.settleItem(t,n)}adopt(e=document){let t=[...e.querySelectorAll(y)];for(let e of t)this.merge(e.content.textContent??e.textContent??``),e.remove();return t.length>0&&this.fragments.hydrated(),t.length}observe(e=document.documentElement,t){typeof document<`u`&&(this.unsubscribe??=this.slots.subscribe(this),this.bound.observe(),this.unobserveElements?.(),this.elements=t??new j,this.unobserveElements=this.elements.add(this),this.elements.observe(e))}nodesAdded(e){for(let t of e)if(t instanceof Element&&(t.matches(y)||t.querySelector(y))){this.adopt();return}}disconnect(){this.unobserveElements?.(),this.unobserveElements=null,this.elements=null,this.unsubscribe?.(),this.unsubscribe=null,this.disarmMutationRefresh?.(),this.disarmMutationRefresh=null,this.refetch.stop(),this.fragments.disconnect(),typeof document<`u`&&this.bound.disconnect()}write(e,t){return z(e.anchor)&&e.attribute?this.slots.setAttribute(e,t):this.slots.setText(e,t)}merge(e){if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}this.server.adopt(t);for(let[e,n]of Object.entries(t.states??{}))this.declared.set(e,n)}refusedRegion(e){for(let t of this.slots.placements(e))if(!this.manifestFor(t.region))return t.region;return null}manifestFor(e){let t=this.slots.statesFor(e.file,e.version)??this.declared.get(e.file);return!t||t.version!==e.version?null:t}scopeFor(e,t){if(!(e instanceof Element)){if(!t||!e.item)return e;let n=this.manifestFor(e.region);if(!n)return e;let r=e.item.collection.index,i=null;return r!==null&&(i=Z(n,t,r)),i!==null&&i.scope===r||Z(n,t,null)===null?e:{region:e.region,item:null}}let n=new Map(this.slots.placements(e).map(e=>[e.region,e])),r=this.slots.regions().filter(e=>n.has(e)),i=r.some(e=>this.slots.bindingsFor(e)!==null)?[...r].reverse():r;for(let e of i){let r=n.get(e);if(!r)continue;let i=this.manifestFor(e);if(!i)continue;let a=r.item;for(;a;){if(!t||Z(i,t,a.collection.index)!==null)return N(e,a);a=a.collection.item}if(!t||Z(i,t,null)!==null)return N(e)}return null}declaredStates(e){let t=this.manifestFor(e.region);if(!t)return[];let n=bt(e);return t.declarations.filter(e=>e.scope===`region`||n!==null&&e.scope===n)}getState(e,t={}){let n=this.scope(t.scope,e);return n?this.valueAt(e,n):null}setState(e,t={}){return this.slots.building(`client`,()=>this.writeState(e,t))}writeState(e,t){let n=Object.keys(e);if(n.length===0)return!1;let r=this.scope(t.scope,n[0]);if(!r)return this.reportUnknown(n[0],null),!1;let i=this.manifestFor(r.region);if(!i)return k({template:r.region.file,message:`the page was rendered by a different version of \`${r.region.file}\`, so its states cannot be resolved`,code:`herb-stale-version`,severity:`warning`,suggestion:`reload the page`}),!1;let a=new Map,o={};for(let t of n){let n=this.resolveState(this.scopeFor(r,t)??r,t);if(n.scope.region===r.region){o[t]=e[t];continue}let i=a.get(n.scope)??{};i[n.name]=e[t],a.set(n.scope,i)}let s=!0;for(let[e,t]of a)s=this.setState(t,{scope:e})&&s;let c=Object.keys(o);if(c.length===0)return s;let l=new Map,u=new Map,d=new Map;for(let e of c){let t=this.scopeFor(r,e)??r,n=this.declaration(i,t,e);if(n===null)return this.reportUnknown(e,r),!1;if(n.derived)return k({template:r.region.file,message:`\`${e}\` is derived from \`${n.default}\`, so it cannot be written. Write the states it reads.`,code:`herb-state-derived`,severity:`error`,value:e}),!1;if(n.count)return k({template:r.region.file,message:`\`${e}\` is counted from the template's loop, so it cannot be written. Write the item states its condition reads.`,code:`herb-state-counted`,severity:`error`,value:e}),!1;d.set(t,[...d.get(t)??[],e]),u.set(e,t),l.set(e,this.valueAt(e,t))}let f=new Map;for(let[e,t]of d)f.set(e,this.derivedDependents(i,e,t).map(t=>({name:t,previous:this.valueAt(t,e)})));let p=N(r.region),m=this.counts.declarationsIn(i).map(e=>({name:e.name,previous:this.valueAt(e.name,p)})),ee=this.derivedDependents(i,p,m.map(e=>e.name)).map(e=>({name:e,previous:this.valueAt(e,p)})),te=this.snapshotBound([...d.keys(),p]);for(let[e,t]of Object.entries(o)){let n=u.get(e)??r;this.store(n,e,t),this.writeValueSlots(i,n,e,t)}let h=new Map;for(let[e,t]of d){let n=[];h.set(e,n);for(let t of f.get(e)??[]){let r=this.valueAt(t.name,e);r!==t.previous&&(n.push(t.name),this.writeValueSlots(i,e,t.name,r))}let r=[...t,...n];this.invalidateStaleReads(i,e,r),this.writeConditionals(i,e,r),this.writePresence(i,e,r),this.writeComputed(i,e,r)}let g=[];for(let e of[...m,...ee]){let t=this.valueAt(e.name,p);t!==e.previous&&(g.push(e.name),this.writeValueSlots(i,p,e.name,t))}g.length>0&&(this.invalidateStaleReads(i,p,g),this.writeConditionals(i,p,g),this.writePresence(i,p,g),this.writeComputed(i,p,g));for(let[e,t]of Object.entries(o))this.announceState(u.get(e)??r,e,t,l.get(e)??null);for(let[e,t]of f)for(let n of t){let t=this.valueAt(n.name,e);t!==n.previous&&this.announceState(e,n.name,t,n.previous)}for(let e of[...m,...ee]){let t=this.valueAt(e.name,p);t!==e.previous&&this.announceState(p,e.name,t,e.previous)}let _=c.filter(e=>this.valueAt(e,u.get(e)??r)!==(l.get(e)??null));for(let[e,t]of d)this.propagateToBound(e,[...t,...h.get(e)??[]],te);return g.length>0&&this.propagateToBound(p,g,te),_.length>0&&this.requestReadRefetch(i,p,_),s}resolveState(e,t){let n=this.scopeFor(e,t)??e,r=t;for(let e=0;e<8&&n.item===null;e+=1){let e=n.region,t=e.parent,i=this.slots.bindingsFor(e)?.states[r];if(!t||!i||!this.manifestFor(t))break;let a=N(t,e.item);n=this.scopeFor(a,i)??a,r=i}return{scope:n,name:r}}boundChildren(e){let t=[];for(let n of this.slots.regions()){if(n.parent!==e.region||e.item!==null&&n.item!==e.item)continue;let r=this.slots.bindingsFor(n);r&&t.push({region:n,binding:r})}return t}snapshotBound(e){let t=new Map,n=e=>{for(let{region:r,binding:i}of this.boundChildren(e)){if(t.has(r))continue;let e=this.manifestFor(r);if(!e)continue;let a=N(r),o=Object.keys(i.states),s=new Map;for(let t of[...o,...this.derivedDependents(e,a,o)])s.set(t,this.valueAt(t,a));t.set(r,s),n(a)}};for(let t of e)n(t);return t}propagateToBound(e,t,n){for(let{region:r,binding:i}of this.boundChildren(e)){let e=Object.entries(i.states).filter(([,e])=>t.includes(e)).map(([e])=>e);if(e.length===0)continue;let a=this.manifestFor(r);if(!a)continue;let o=N(r),s=n.get(r)??new Map,c=[];for(let t of e)this.writeValueSlots(a,o,t,this.valueAt(t,o));for(let t of this.derivedDependents(a,o,e)){let e=this.valueAt(t,o);e!==s.get(t)&&(c.push(t),this.writeValueSlots(a,o,t,e))}let l=[...e,...c];this.invalidateStaleReads(a,o,l),this.writeConditionals(a,o,l),this.writePresence(a,o,l),this.writeComputed(a,o,l);for(let e of l)this.announceState(o,e,this.valueAt(e,o),s.get(e)??null);this.propagateToBound(o,l,n),this.requestReadRefetch(a,o,l)}}async fetchBlock(e,t){let n=this.blockSteering(e),r={template:e.file,index:t},i;try{i=this.options.refetchTransport?await this.options.refetchTransport(n,new AbortController().signal,r):await P(window.location.href,{format:this.options.format,state:n,block:t})}catch{return{applied:0,deferred:0,stale:!1,failed:!0}}if(!i)return{applied:0,deferred:0,stale:!1,failed:!0};let a,o=e.slots.get(t);return await x(()=>{a=this.slots.apply(i)},o&&B(o.anchor)||document),{applied:a.applied,deferred:a.deferred.length,stale:!1,failed:!1}}blockSteering(e){let t=this.manifestFor(e);if(!t)return{};let n={};for(let r of vr(t)){let t=this.valueAt(r,N(e));t!==void 0&&(n[r]=t)}return Object.keys(n).length>0?{[e.file]:n}:{}}invalidateStaleReads(e,t,n){let r=e.server?.reads??{},i=new Set(n.flatMap(e=>(r[e]??[]).map(e=>e.index)));i.size>0&&this.slots.invalidateStale(t.region,i)}requestReadRefetch(e,t,n){if(this.options.refetch!==`auto`)return;let r=e.server?.reads??{},i=new Set(n.flatMap(e=>(r[e]??[]).map(e=>e.index))),a=e.server?.branches??{};for(let[n,r]of Object.entries(a)){let a=e.conditionals[n];if(!a)continue;let o=this.placedSlots(t,Number(n));if(!(o.length===0||o.some(e=>this.targetBranch(a,e.scope)===0)))for(let e of r)i.delete(e.index)}i.size!==0&&(this.fragments.showFallbacks(e,t,i,n),this.refetch.request(this.options.refetchDebounce).then(e=>this.fragments.settle(e)))}toggle(e,t={}){this.requireKind(e,t,`boolean`,`toggle`);let n=this.getState(e,t);return this.setState({[e]:n!==!0},t)}increment(e,t={}){this.requireKind(e,t,`integer`,`increment`);let n=this.getState(e,t),r=0;return typeof n==`number`&&(r=n),this.setState({[e]:r+(t.by??1)},t)}decrement(e,t={}){return this.increment(e,{...t,by:-(t.by??1)})}reset(e,t={}){let n=this.scope(t.scope,e);if(!n)return!1;let r=this.seeds.held(n,e);return this.setState({[e]:r??this.defaultOf(e,n)},t)}on(e,t,n={}){let r=null;n.scope&&(r=this.scope(n.scope,e));let i=n=>{let i=n.detail;i.name===e&&(!r||i.file===r.region.file&&i.occurrence===r.region.occurrence&&(r.item?.key??null)===i.key)&&t(i.value,i.previous)};return document.addEventListener(an,i),()=>document.removeEventListener(an,i)}reportUnknown(e,t){let n=[];t&&(n=this.declaredStates(t).map(e=>e.name));let r=`no scope on this page declares it`;n.length>0&&(r=`the states in scope are ${n.join(`, `)}`),k({template:t?.region.file??this.slots.regions()[0]?.file??``,message:`nothing here declares the state \`${e}\`; ${r}`,code:`herb-unknown-state`,severity:`error`,value:e})}scope(e,t){if(e)return this.scopeFor(e,t);for(let e of this.slots.regions()){let n=this.manifestFor(e);if(n&&Z(n,t,null)!==null)return N(e)}for(let e of this.slots.regions())if(this.declared.has(e.file)&&!this.manifestFor(e))return N(e);return null}declarationFor(e,t,n){return this.declaration(e,t,n)}declaration(e,t,n){return Z(e,n,bt(t))}requireKind(e,t,n,r){let i=this.scope(t.scope,e);if(!i)return;let a=this.declarationIn(i,e);if(a&&a.kind!==n&&a.kind!==`seeded`){let t=`use set with a ${n} value`;throw n===`boolean`&&(t=`set a value instead, or declare a boolean flag`),k({template:i.region.file,message:`${r} on \`${e}\` did nothing, because \`${e}\` is a ${a.kind} and ${r} needs a ${n}`,code:`herb-state-type`,severity:`error`,value:e,suggestion:t,...fr(a)}),TypeError(`${r} needs a ${n} state, and \`${e}\` is declared as ${a.kind}`)}}valueAt(e,t){let{scope:n,name:r}=this.resolveState(t,e),i=this.declarationIn(n,r);if(i?.count)return this.counts.countFor(i,n);if(i?.derived)return this.deriveValue(i,n);let a=this.scoped.get(n.region)?.get(n.item?.key??``)?.get(r);if(a!==void 0)return a;let o=this.seeds.valueFor(r,n);return o===void 0?this.defaultOf(r,n):o}deriveValue(e,t){let n=e.derived;return n==null?null:e.kind!==`boolean`&&Array.isArray(n)&&n.length===2&&n[1]===null?this.valueAt(n[0],t):sr(n,e=>this.valueAt(e,t))}derivedDependents(e,t,n){let r=bt(t),i=new Set(n),a=[];for(let t of e.declarations){if(!t.derived)continue;let e=t.scope===`region`;r!==null&&(e=t.scope===r),e&&X(t.derived,[...i])&&(a.push(t.name),i.add(t.name))}return a}defaultOf(e,t){let n=this.declarationIn(t,e);if(!n)return null;let r=pr(n);return r===void 0?null:r}declares(e,t){let n=this.resolveState(e,t);return this.declarationIn(n.scope,n.name)!==null}declarationIn(e,t){let n=this.manifestFor(e.region);return n?this.declaration(n,e,t):null}store(e,t,n){this.seeds.valueFor(t,e),yt(this.scoped,e).set(t,n)}departing(e,t){for(let n=e.slot.parent;n;n=n.parent){let r=t.conditionals[String(n.index)];if(r&&n.branch!==null&&this.targetBranch(r,e.scope)!==n.branch){if(this.fragments.holding(n))continue;return!0}}return!1}writeValueSlots(e,t,n,r){let i=e.computed??{};for(let a of e.reads[n]??[])if(!i[String(a)])for(let i of this.placedSlots(t,a)){if(i.slot.type===`boolean_attribute`||this.departing(i,e))continue;let a=i.scope===t?r:this.valueAt(n,i.scope);this.write(i.slot,M(a)),this.slots.claim(i.slot)}}writePresence(e,t,n){for(let[r,i]of Object.entries(e.presence??{}))if(X(i,n))for(let n of this.placedSlots(t,Number(r))){if(this.departing(n,e))continue;let t=Y(i,e=>this.valueAt(e,n.scope));this.slots.setBooleanAttribute(n.slot,t),this.slots.claim(n.slot)}}writeComputed(e,t,n){for(let[r,i]of Object.entries(e.computed??{}))if(X(i,n))for(let n of this.placedSlots(t,Number(r)))this.departing(n,e)||(this.write(n.slot,M(sr(i,e=>this.valueAt(e,n.scope)))),this.slots.claim(n.slot))}writeConditionals(e,t,n){for(let[r,i]of Object.entries(e.conditionals))if(i.arms.some(e=>X(ir(e).condition,n)))for(let e of this.placedSlots(t,Number(r))){let n=e.slot;if(this.fragments.holding(n))continue;let r=this.targetBranch(i,e.scope);if(this.slots.claim(n),n.branch===r)continue;let a=this.slots.holdBranch(n,r);if(a){a.then(()=>{let r=this.targetBranch(i,e.scope);n.branch!==r&&V(n.anchor)&&this.switchTo(n,r,t.region.file)});continue}this.switchTo(n,r,t.region.file)}}switchTo(e,t,n){let r=B(e.anchor);if(r?.querySelector(`[data-herb-transition]`)){x(()=>{!this.slots.switchBranch(e,t)&&e.branch!==t&&this.options.refetch!==`off`&&this.refetch.request(this.options.refetchDebounce).then(e=>this.fragments.settle(e))},r);return}if(!(this.slots.switchBranch(e,t)||e.branch===t)){if(this.options.refetch!==`off`){this.refetch.request(this.options.refetchDebounce).then(e=>this.fragments.settle(e));return}k({template:n,element:r,message:`branch ${t??`else`} of slot ${e.index} was never parked, so it cannot be shown`,code:`herb-no-parked-branch`,severity:`warning`,suggestion:"the template renders in server mode; compile it with `herb:slots client`, or leave `refetch` on to pull the branch from the server"})}}targetBranch(e,t){let n=e=>this.valueAt(e,t);for(let t of e.arms){let e=ir(t);if(Y(e.condition,n))return e.branch}return e.else}resetBound(e){this.bound.resetForm(e)}attributeWritten(e){this.bound.slotWritten(e)}countsChanged(e,t,n){for(let r of n)this.writeValueSlots(e,t,r.name,r.value);let r=n.map(e=>e.name);this.writeConditionals(e,t,r),this.writePresence(e,t,r),this.writeComputed(e,t,r);for(let e of n)this.announceState(t,e.name,e.value,e.previous)}scopedSlots(e,t){return this.placedSlots(e,t).map(e=>e.slot)}placedSlots(e,t){if(e.item){let n=e.item.slots.get(t);return n?[{slot:n,scope:e}]:[]}let n=e.region.slots.get(t);if(n)return[{slot:n,scope:e}];let r=[];for(let n of e.region.slots.values())if(n.type===`collection`)for(let i of n.items.values()){let n=i.slots.get(t);n&&r.push({slot:n,scope:{region:e.region,item:i}})}return r}announceState(e,t,n,r){typeof document<`u`&&document.dispatchEvent(new CustomEvent(an,{detail:{name:t,value:n,previous:r,file:e.region.file,occurrence:e.region.occurrence,key:e.item?.key??null}}))}itemRekeyed(e,t,n){let r=this.slots.regionOf(e);if(!r)return;let i=this.scoped.get(r),a=i?.get(n);i&&a&&(i.delete(n),i.set(t,a)),this.seeds.migrate(r,n,t)}settleBranch(e){let t=this.slots.regionOf(e);if(!t)return;let n=this.manifestFor(t);if(!n)return;let r=N(t,e.item);for(let[e,t]of Object.entries(n.reads)){if(t.length===0)continue;let i=this.scopeFor(r,e)??r,a=this.getState(e,{scope:i});a!==void 0&&this.writeValueSlots(n,i,e,a)}let i=n.declarations.map(e=>e.name);this.writePresence(n,r,i),this.writeComputed(n,r,i),this.writeConditionals(n,r,i),this.requestBranchRefetch(n,e)}requestBranchRefetch(e,t){if(this.options.refetch!==`auto`||t.branch===null)return;let n=e.server?.branches?.[String(t.index)]??[];if(n.length===0)return;let r=t.shown?.get(t.branch)??{},i=this.slots.descendantsOf(t);n.some(e=>{if(e.index in r)return!1;let t=i.find(t=>t.index===e.index);return t!==void 0&&!t.claimed&&this.slots.currentText(t)===``})&&this.refetch.request(0)}settleItem(e,t){let n=this.slots.regionOf(e);if(!n)return;let r=this.manifestFor(n);if(!r)return;let i=N(n,t);for(let[e,n]of Object.entries(r.reads)){let a=this.scopeFor(i,e)??i,o=this.getState(e,{scope:a});if(o===void 0)continue;let s=M(o);for(let e of n){let n=t.slots.get(e);n&&n.type!==`boolean_attribute`&&!r.computed?.[String(e)]&&(this.write(n,s),this.slots.claim(n))}}for(let[e,n]of Object.entries(r.presence??{})){let r=t.slots.get(Number(e));r&&(this.slots.setBooleanAttribute(r,Y(n,e=>this.valueAt(e,i))),this.slots.claim(r))}for(let[e,n]of Object.entries(r.computed??{})){let r=t.slots.get(Number(e));r&&(this.write(r,M(sr(n,e=>this.valueAt(e,i)))),this.slots.claim(r))}}},kr=class{constructor(e,t){this.definitions=new Map,this.contexts=new WeakMap,this.rects=new Map,this.fresh=[],this.root=null,this.elements=null,this.unobserve=null,this.unsubscribe=null,this.slots=e,this.contextFor=t}define(e,t){let n={attribute:e,behavior:t,connected:new Set,touched:new Set,named:new WeakSet},r=this.definitions.get(e)??new Set;return r.add(n),this.definitions.set(e,r),this.elements?.watch([e]),this.root&&this.connectIn([this.root],n),()=>this.undefine(n)}observe(e=document.documentElement,t){this.unobserve?.(),this.root=e,this.elements=t??new j,this.unobserve=this.elements.add(this),this.unsubscribe??=this.slots.subscribe(this),this.elements.watch([...this.definitions.keys()]),this.elements.observe(e);for(let t of this.all())this.connectIn([e],t)}disconnect(){this.unobserve?.(),this.unobserve=null,this.unsubscribe?.(),this.unsubscribe=null,this.elements=null,this.root=null,this.fresh=[];for(let e of this.all())for(let t of[...e.connected])this.disconnectElement(e,t)}nodesAdded(e){for(let t of this.all())this.connectIn(e,t);this.fresh=[]}nodesRemoved(){for(let e of this.all())for(let t of[...e.connected])t.isConnected||this.disconnectElement(e,t)}attributeChanged(e,t){let n=this.definitions.get(t);if(!n)return;let r=e.getAttribute(t);for(let t of n)r===null?t.connected.has(e)&&this.disconnectElement(t,e):t.connected.has(e)?(this.guarded(t,e,()=>t.behavior.valueChanged?.(e,r,this.context(e))),this.name(t,e)):this.connectElement(t,e)}built(e){for(let t of e.branches)this.fresh.push(this.slots.rangeOf(t));for(let{item:t}of e.items)this.fresh.push(this.slots.rangeOf(t))}holdBranch(e){return this.holdWithin(this.slots.rangeOf(e))}holdItem(e,t){return this.holdWithin(this.slots.rangeOf(t))}valueWritten(e){this.written(e)}attributeWritten(e){this.written(e)}itemsMoving(e,t){let n=t.map(e=>this.slots.rangeOf(e));for(let e of this.all())if(e.behavior.moved)for(let t of e.connected)n.some(e=>e.intersectsNode(t))&&this.rects.set(t,t.getBoundingClientRect())}itemsMoved(){let e=[...this.rects];this.rects.clear();for(let t of this.all())if(t.behavior.moved)for(let[n,r]of e){if(!t.connected.has(n))continue;let e=n.getBoundingClientRect();(r.top!==e.top||r.left!==e.left||r.width!==e.width||r.height!==e.height)&&(t.touched.add(n),this.guarded(t,n,()=>t.behavior.moved?.(n,{from:r,to:e},this.context(n))))}}settled(){for(let e of this.all()){let t=[...e.touched];e.touched.clear();for(let n of t)e.connected.has(n)&&this.guarded(e,n,()=>e.behavior.settled?.(n,this.context(n)))}}written(e){let t=z(e.anchor),n=t?null:this.slots.rangeOf(e);for(let r of this.all())if(r.behavior.updated)for(let i of r.connected)(t?i.contains(t):n.intersectsNode(i))&&(r.touched.add(i),this.guarded(r,i,()=>r.behavior.updated?.(i,e,this.context(i))))}holdWithin(e){let t=[];for(let n of this.all())if(n.behavior.leave)for(let r of n.connected)e.intersectsNode(r)&&this.guarded(n,r,()=>{let e=n.behavior.leave?.(r,this.context(r));e&&t.push(e)});if(t.length>0)return Promise.allSettled(t).then(()=>void 0)}undefine(e){let t=this.definitions.get(e.attribute);if(t?.delete(e)){t.size===0&&this.definitions.delete(e.attribute);for(let t of[...e.connected])this.disconnectElement(e,t)}}all(){return[...this.definitions.values()].flatMap(e=>[...e])}connectIn(e,t){let n=`[${CSS.escape(t.attribute)}]`;for(let r of e)if(r instanceof Element&&r.hasAttribute(t.attribute)&&this.connectElement(t,r),r instanceof Element||r instanceof Document||r instanceof DocumentFragment)for(let e of r.querySelectorAll(n))this.connectElement(t,e)}connectElement(e,t){e.connected.has(t)||(e.connected.add(t),this.guarded(e,t,()=>e.behavior.connect?.(t,this.context(t))),this.name(e,t),e.behavior.enter&&this.fresh.some(e=>e.intersectsNode(t))&&this.guarded(e,t,()=>e.behavior.enter?.(t,this.context(t))))}disconnectElement(e,t){e.connected.delete(t)&&(e.touched.delete(t),this.rects.delete(t),this.guarded(e,t,()=>e.behavior.disconnect?.(t,this.context(t))))}name(e,t){if(!e.behavior.transition)return;let n;this.guarded(e,t,()=>{n=e.behavior.transition?.(t,this.context(t))}),typeof n==`string`&&n!==``?(t.setAttribute(le,n),e.named.add(t)):e.named.has(t)&&(t.removeAttribute(le),e.named.delete(t))}context(e){let t=this.contexts.get(e);return t||(t=this.contextFor(e),this.contexts.set(e,t)),t}guarded(e,t,n){try{n()}catch(n){k({template:``,element:t,message:`the behavior for \`${e.attribute}\` threw ${n instanceof Error?n.message:String(n)}`,code:`herb-behavior-error`,severity:`error`,value:e.attribute})}}};const Ar=Symbol(`Runtime.start`);let jr=null;var $=class e{constructor(e,t={}){if(this.elements=null,this.stopClearing=null,this.stopWatchingCoverage=null,e!==Ar)throw TypeError(`Runtime is created by Runtime.start()`);this.slots=new nr,this.state=new Or(this.slots,t.state),this.outbox=new Yt(this.slots,this.state,t.outbox),this.actions=new gt(this.state),this.behaviors=new kr(this.slots,e=>({state:en(this.state,e),slots:this.slots,outbox:this.outbox}))}static start(t={}){let n=e.get();if(n)return n;let r=new e(Ar,t);t.manifests&&r.slots.adoptManifests(t.manifests);let i=new j(ne),a=document.documentElement;r.elements=i,r.slots.observe(a,i),r.state.adopt(),r.state.observe(a,i),r.actions.start(document,i),r.behaviors.observe(a,i),r.outbox.observe(),r.stopClearing=lt(),r.stopWatchingCoverage=nn(r.slots),jr=r;try{window.HerbRuntime=r}catch{}return r}static get(){return jr}refresh(){return this.state.refresh()}stop(){if(this.slots.disconnect(),this.state.disconnect(),this.outbox.unobserve(),this.outbox.abort(),this.actions.stop(),this.behaviors.disconnect(),this.elements?.disconnect(),this.elements=null,this.stopClearing?.(),this.stopClearing=null,this.stopWatchingCoverage?.(),this.stopWatchingCoverage=null,jr===this){jr=null;try{window.HerbRuntime===this&&delete window.HerbRuntime}catch{}}}};typeof document<`u`&&queueMicrotask(()=>{!$.get()&&!window.HerbRuntime&&$.start({state:{debounce:150}})});function Mr(e){let t=$t(e.element),n=t.scope,r=[];e.state=t,e.outbox=$.get()?.outbox,e.slots=$.get()?.slots;let i=[];n&&(i=Nr(n));for(let n of i){let i=e[`${n}Changed`];typeof i==`function`&&r.push(t.on(n,(t,n)=>i.call(e,t,n)))}let a=e.disconnect?.bind(e);return e.disconnect=()=>{for(let e of r)e();a?.()},t}function Nr(e){let t=$.get();return t?t.state.declaredStates(e).map(e=>e.name):[]}export{ne as ACTION_ATTRIBUTES,_ as ACTION_NAMES,g as ACTION_SCHEMA,v as ACTION_SELECTOR,F as ANCHOR_ATTRIBUTE,It as ANCHOR_SELECTOR,gt as Actions,Dt as BLOCK_HEADER,kr as Behaviors,Le as CONTENT_SLOT_TYPES,Ie as DEFAULT_SLOT_TYPE,re as DEPENDENCIES_ATTRIBUTE,y as DEPENDENCIES_SELECTOR,$e as DEV_TOOLS_START_EVENT,j as ElementObserver,h as HERB_ATTRIBUTES,Re as INTERPOLATED_SLOT_TYPES,Ne as ITEM_STATICS,Mn as Manifests,Ft as NAME_ATTRIBUTE,Et as NODE_PATH_HEADER,Yt as Outbox,Pe as PARTS_STATICS,Fe as PART_MARKER,Qe as RUNTIME_ORIGIN,$ as Runtime,Tt as SCHEMA_HEADER,wt as SLOTS_MIME_TYPE,rn as SLOT_EVENT,an as STATE_EVENT,Ot as STATE_HEADER,Lt as STATICS_SELECTOR,nr as Slots,kt as SlotsRequestError,Or as State,Cr as VALUE_ELEMENTS,Bt as anchorEntries,Vt as anchorKind,Rt as anchored,I as anchoredSlots,Er as bindable,T as branchKey,C as branchOf,lt as clearOnNavigation,Ht as closingFor,V as connected,Gt as currentHTML,Kt as currentText,z as elementOf,nt as flushReports,B as hostOf,W as htmlOf,H as innerRange,Ve as isItemClose,Be as isItemOpen,ze as isMarker,Ge as itemMarker,E as itemStaticsKey,Ke as keyedSlotMarker,L as markers,zt as named,He as numericBranch,U as outerRange,S as parseMarker,Ze as parseSeeds,Xe as parseStaticsIdentity,Je as parseStaticsKey,Ye as partsKey,Wt as rangeOf,We as regionCloseMarker,Ue as regionOpenMarker,k as report,rt as resetReport,en as scopedState,qe as slotCloseMarker,w as slotOpenIndex,R as slotOpeners,At as slotsHeaders,P as slotsRequest,$t as stateFor,Ut as staticsElements,Mr as useState,G as withinBounds,Jt as withinRegion,qt as withinRegionRange};
|
|
26
|
+
//# sourceMappingURL=reactionview.esm.js.map
|