@shadow-js/web 1.0.4 → 1.0.6

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -1
  3. package/dist/dev/class-style.js +6 -1
  4. package/dist/dev/class-style.js.map +1 -1
  5. package/dist/dev/control-flow/dynamic.js +4 -4
  6. package/dist/dev/control-flow/no-hydration.js +1 -1
  7. package/dist/dev/control-flow/portal.js +1 -1
  8. package/dist/dev/element.js +2 -2
  9. package/dist/dev/extend.js +6 -6
  10. package/dist/dev/head/use-head.js +1 -1
  11. package/dist/dev/head/validate.js +1 -1
  12. package/dist/dev/hydration.js +21 -13
  13. package/dist/dev/hydration.js.map +1 -1
  14. package/dist/dev/index.d.ts +5 -5
  15. package/dist/dev/index.js +6 -6
  16. package/dist/dev/insert.js +12 -1
  17. package/dist/dev/insert.js.map +1 -1
  18. package/dist/dev/jsx/global.d.ts +2 -2
  19. package/dist/dev/jsx/html.d.ts +1 -1
  20. package/dist/dev/jsx/intrinsic.d.ts +1 -1
  21. package/dist/dev/jsx/mathml.d.ts +1 -1
  22. package/dist/dev/jsx/svg.d.ts +1 -1
  23. package/dist/dev/jsx-runtime.d.ts +3 -3
  24. package/dist/dev/render.js +22 -11
  25. package/dist/dev/render.js.map +1 -1
  26. package/dist/dev/select-value.d.ts +3 -1
  27. package/dist/dev/select-value.js +11 -1
  28. package/dist/dev/select-value.js.map +1 -1
  29. package/dist/dev/server/class-style.js +1 -1
  30. package/dist/dev/server/element.js +3 -3
  31. package/dist/dev/server/form-controls.js +1 -1
  32. package/dist/dev/server/hydration-script.js +1 -1
  33. package/dist/dev/server/portals.js +1 -1
  34. package/dist/dev/server/raw-text.js +1 -1
  35. package/dist/dev/server/render.js +2 -2
  36. package/dist/dev/server/stream.js +3 -3
  37. package/dist/dev/spread.js +12 -4
  38. package/dist/dev/spread.js.map +1 -1
  39. package/dist/dev/template.js +3 -3
  40. package/dist/prod/class-style.js +1 -1
  41. package/dist/prod/class-style.js.map +1 -1
  42. package/dist/prod/control-flow/dynamic.js +1 -1
  43. package/dist/prod/control-flow/no-hydration.js +1 -1
  44. package/dist/prod/control-flow/portal.js +1 -1
  45. package/dist/prod/element.js +1 -1
  46. package/dist/prod/events.js +1 -1
  47. package/dist/prod/events.js.map +1 -1
  48. package/dist/prod/extend.js +1 -1
  49. package/dist/prod/head/use-head.js +1 -1
  50. package/dist/prod/head/validate.js +1 -1
  51. package/dist/prod/hydration.js +1 -1
  52. package/dist/prod/hydration.js.map +1 -1
  53. package/dist/prod/index.js +1 -1
  54. package/dist/prod/insert.js +1 -1
  55. package/dist/prod/insert.js.map +1 -1
  56. package/dist/prod/render.js +1 -1
  57. package/dist/prod/render.js.map +1 -1
  58. package/dist/prod/select-value.js +1 -1
  59. package/dist/prod/select-value.js.map +1 -1
  60. package/dist/prod/server/class-style.js +1 -1
  61. package/dist/prod/server/element.js +1 -1
  62. package/dist/prod/server/form-controls.js +2 -2
  63. package/dist/prod/server/hydration-script.js +1 -1
  64. package/dist/prod/server/portals.js +1 -1
  65. package/dist/prod/server/raw-text.js +1 -1
  66. package/dist/prod/server/render.js +1 -1
  67. package/dist/prod/server/stream.js +1 -1
  68. package/dist/prod/spread.js +1 -1
  69. package/dist/prod/spread.js.map +1 -1
  70. package/dist/prod/template.js +1 -1
  71. package/dist/server/class-style.js +1 -1
  72. package/dist/server/class-style.js.map +1 -1
  73. package/dist/server/control-flow/dynamic.js +1 -1
  74. package/dist/server/control-flow/portal.js +1 -1
  75. package/dist/server/control-flow/suspense.js +1 -1
  76. package/dist/server/element.js +1 -1
  77. package/dist/server/events.js +1 -1
  78. package/dist/server/events.js.map +1 -1
  79. package/dist/server/extend.js +1 -1
  80. package/dist/server/head/use-head.js +1 -1
  81. package/dist/server/head/validate.js +1 -1
  82. package/dist/server/hydration.js +1 -1
  83. package/dist/server/hydration.js.map +1 -1
  84. package/dist/server/index.js +1 -1
  85. package/dist/server/insert.js +1 -1
  86. package/dist/server/insert.js.map +1 -1
  87. package/dist/server/render.js +1 -1
  88. package/dist/server/render.js.map +1 -1
  89. package/dist/server/select-value.js +1 -1
  90. package/dist/server/select-value.js.map +1 -1
  91. package/dist/server/server/class-style.js +1 -1
  92. package/dist/server/server/element.js +1 -1
  93. package/dist/server/server/form-controls.js +2 -2
  94. package/dist/server/server/hydration-script.js +1 -1
  95. package/dist/server/server/portals.js +1 -1
  96. package/dist/server/server/raw-text.js +1 -1
  97. package/dist/server/server/render.js +1 -1
  98. package/dist/server/server/stream.js +1 -1
  99. package/dist/server/spread.js +1 -1
  100. package/dist/server/spread.js.map +1 -1
  101. package/dist/server/template.js +1 -1
  102. package/dist/server-dev/class-style.js +6 -1
  103. package/dist/server-dev/class-style.js.map +1 -1
  104. package/dist/server-dev/control-flow/dynamic.js +1 -1
  105. package/dist/server-dev/control-flow/portal.js +1 -1
  106. package/dist/server-dev/control-flow/suspense.js +2 -2
  107. package/dist/server-dev/element.js +1 -1
  108. package/dist/server-dev/extend.js +6 -6
  109. package/dist/server-dev/head/use-head.js +1 -1
  110. package/dist/server-dev/head/validate.js +1 -1
  111. package/dist/server-dev/hydration.js +21 -13
  112. package/dist/server-dev/hydration.js.map +1 -1
  113. package/dist/server-dev/index.js +6 -6
  114. package/dist/server-dev/insert.js +12 -1
  115. package/dist/server-dev/insert.js.map +1 -1
  116. package/dist/server-dev/render.js +22 -11
  117. package/dist/server-dev/render.js.map +1 -1
  118. package/dist/server-dev/select-value.js +11 -1
  119. package/dist/server-dev/select-value.js.map +1 -1
  120. package/dist/server-dev/server/class-style.js +1 -1
  121. package/dist/server-dev/server/element.js +3 -3
  122. package/dist/server-dev/server/form-controls.js +1 -1
  123. package/dist/server-dev/server/hydration-script.js +1 -1
  124. package/dist/server-dev/server/portals.js +1 -1
  125. package/dist/server-dev/server/raw-text.js +1 -1
  126. package/dist/server-dev/server/render.js +2 -2
  127. package/dist/server-dev/server/stream.js +3 -3
  128. package/dist/server-dev/spread.js +12 -4
  129. package/dist/server-dev/spread.js.map +1 -1
  130. package/dist/server-dev/template.js +3 -3
  131. package/package.json +3 -3
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{runWithServerHead as c}from"../head/server-head.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},l={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:l,get children(){return u(S,()=>f({value:i,get children(){return c(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
1
+ import{attachRootErrors as e}from"../control-flow/root-errors.js";import{runWithServerHead as t}from"../head/server-head.js";import{createRootScope as n,resourceKey as r,withScope as i}from"../internal/hydration-scope.js";import{StreamContext as a}from"../internal/stream-context.js";import{MAX_TIMER_MS as o,SsrError as s}from"./errors.js";import{escape as c}from"./escape.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let o={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(o);let s={key:e=>{let t=r(e);return o.requested.add(t),t},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let r=t.then(t=>{h.set(e,t)},()=>void 0);o.inFlight.add(r),r.finally(()=>o.inFlight.delete(r)),n?.deferStream===!0&&o.held.push({key:e,entry:r})},pending:e=>k.get(e)},l={defer:e=>{o.boundaries.push(e)}},d={onCaughtError:e=>{o.answered?v.onCaughtError?.(e):o.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{o.answered?v.onUncaughtError?.(e):o.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),o.html=p(r=>(o.dispose=r,e(d),a({value:l,get children(){return u(S,()=>f({value:s,get children(){return t(v.head,()=>i(n(y),()=>c(_())))}}))}})()())),o},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new s(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,o))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new s(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
2
2
  //# sourceMappingURL=stream.js.map
@@ -1,2 +1,2 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";const S=/^(?:__proto__|constructor|prototype)$/;function C(e){let t=e.unref;t!==void 0&&(e.unref=void 0,b(t))}function w(c,l,u,d,f){if(l===`ref`){if(C(d),typeof u==`function`){let e=u,t=b(()=>e(c));typeof t==`function`&&(d.unref=t)}}else if(l===`autoFocus`)d.focused||(d.focused=!0,r(c,u));else if(l===`class`||l===`className`)i(c,u,f);else if(l===`style`)d.styled=s(c,u,d.styled);else if(l===`classList`)d.listed=o(c,a(u),d.listed);else if(l.length>2&&l.startsWith(`on`)){d.unbind.get(l)?.(),d.unbind.delete(l);let e=m(l,c.localName,c.getAttribute(`type`)?.toLowerCase()??null),t=e.passive&&typeof u==`function`?{handleEvent:u,passive:!0}:u,n=g(c,e.type,t,!0,e.capture);n!==void 0&&d.unbind.set(l,n)}else if(l===`innerHTML`||l===`dangerouslySetInnerHTML`)c.innerHTML=_(l===`innerHTML`?u:typeof u==`object`&&u?Reflect.get(u,`__html`):void 0);else if(l===`textContent`)c.textContent=_(u);else if(!f&&(l===`value`||l===`defaultValue`)&&c instanceof HTMLSelectElement)v(c,u);else if(!f&&T.test(l)&&l in c)D(c,l,u,f)&&Reflect.set(c,l,E.test(l)?u??``:!!u),l===`value`&&c instanceof HTMLInputElement&&(c.defaultValue=_(u));else if(l.startsWith(`prop:`))Reflect.set(c,l.slice(5),u);else if(l.startsWith(`attr:`))e(c,l.slice(5),u);else if(l.startsWith(`bool:`))n(c,l.slice(5),u);else{let r=p(l,f);h(r,u)?n(c,r,u):r.startsWith(`xlink:`)?t(c,`http://www.w3.org/1999/xlink`,r,u):e(c,r,u)}}const T=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,E=/^(?:value|defaultValue)$/;function D(e,t,n,r){if(r||!T.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return E.test(t)?i!==_(n):i!==!!n}function O(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=A();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),k(e,n,a)}M(e,i,n,a)}function k(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function A(){return{values:/* @__PURE__ */ new Map,unbind:/* @__PURE__ */ new Map}}function j(e,t,n){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let r=A();k(e,n,r),M(e,()=>typeof t==`function`?t():t,n,r)}function M(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbind.values())e();r.unbind.clear(),C(r)}),x(()=>{let e=t(),n=[];if(typeof e!=`object`||!e)return n;let r,a=!1;for(let t of Object.keys(e))S.test(t.slice(t.indexOf(`:`)+1))||f.test(t)||(t===`children`?i&&(r=Reflect.get(e,t),a=!0):n.push([t,Reflect.get(e,t)]));return a&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n},t=>{let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(r.values.has(a)&&Object.is(r.values.get(a),o)&&!D(e,a,o,n))&&(r.values.set(a,o),w(e,a,o,r,n));for(let t of[...r.values.keys()])i.has(t)||(r.values.delete(t),w(e,t,void 0,r,n))})}export{O as spread,j as spreadProps};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{bindEvent as c}from"./events.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{claims as f}from"./internal/hydration-hooks.js";import{IGNORED_KEYS as p,attributeName as m,eventPlan as h,isFlagAttribute as g}from"./internal/react-names.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";const S=/^(?:__proto__|constructor|prototype)$/;function C(e){let t=e.unref;t!==void 0&&(e.unref=void 0,b(t))}function w(l,u,d,f,p){if(u===`ref`){if(C(f),typeof d==`function`){let e=d,t=b(()=>e(l));typeof t==`function`&&(f.unref=t)}}else if(u===`autoFocus`)f.focused||(f.focused=!0,r(l,d));else if(u===`class`||u===`className`)i(l,d,p);else if(u===`style`)f.styled=s(l,d,f.styled);else if(u===`classList`)f.listed=o(l,a(d),f.listed);else if(u.length>2&&u.startsWith(`on`)){f.unbind.get(u)?.(),f.unbind.delete(u);let e=h(u,l.localName,l.getAttribute(`type`)?.toLowerCase()??null),t=e.passive&&typeof d==`function`?{handleEvent:d,passive:!0}:d,n=c(l,e.type,t,!0,e.capture);n!==void 0&&f.unbind.set(u,n)}else if(u===`innerHTML`||u===`dangerouslySetInnerHTML`)l.innerHTML=_(u===`innerHTML`?d:typeof d==`object`&&d?Reflect.get(d,`__html`):void 0);else if(u===`textContent`)l.textContent=_(d);else if(!p&&(u===`value`||u===`defaultValue`)&&l instanceof HTMLSelectElement)v(l,d);else if(!p&&T.test(u)&&u in l&&!D(l,u))O(l,u,d,p)&&Reflect.set(l,u,E.test(u)?d??``:!!d),u===`value`&&l instanceof HTMLInputElement&&(l.defaultValue=_(d));else if(u.startsWith(`prop:`))Reflect.set(l,u.slice(5),d);else if(u.startsWith(`attr:`))e(l,u.slice(5),d);else if(u.startsWith(`bool:`))n(l,u.slice(5),d);else{let r=m(u,p);g(r,d)?n(l,r,d):r.startsWith(`xlink:`)?t(l,`http://www.w3.org/1999/xlink`,r,d):e(l,r,d)}}const T=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,E=/^(?:value|defaultValue)$/;function D(e,t){return t===`value`&&(e.localName===`progress`||e.localName===`meter`||e.localName===`li`)}function O(e,t,n,r){if(r||!T.test(t)||!(t in e)||D(e,t))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return E.test(t)?i!==_(n):i!==!!n}function k(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=j();if(!r&&e.localName!==`textarea`){let t=f.current.isClaiming()?f.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),A(e,n,a)}N(e,i,n,a)}function A(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function j(){return{values:/* @__PURE__ */ new Map,unbind:/* @__PURE__ */ new Map}}function M(e,t,n){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let r=j();A(e,n,r),N(e,()=>typeof t==`function`?t():t,n,r)}function N(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbind.values())e();r.unbind.clear(),C(r)}),x(()=>{let e=t(),n=[];if(typeof e!=`object`||!e)return n;let r,a=!1;for(let t of Object.keys(e))S.test(t.slice(t.indexOf(`:`)+1))||p.test(t)||(t===`children`?i&&(r=Reflect.get(e,t),a=!0):n.push([t,Reflect.get(e,t)]));return a&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n},t=>{let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),r.values.has(a)&&Object.is(r.values.get(a),o)&&!O(e,a,o,n)||(r.values.set(a,o),w(e,a,o,r,n));for(let t of[...r.values.keys()])i.has(t)||(r.values.delete(t),w(e,t,void 0,r,n))})}export{k as spread,M as spreadProps};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","spreadProps","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EAAIF,EAAOK,CAAG,OAG3B,GAAIN,IAAQ,QACV,EAAM,OAASO,EAAMJ,EAAgC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AG,EAC9B,EAAW,IAIf6C,EAAQ,KAAK,CAAC7C,EAAK,QAAQ,IAAI4B,EAAO5B,CAAG,CAAC,CAAC,GAG7C,OADI8C,GAAY,CAACD,EAAQ,MAAM,CAAC7C,KAASA,IAAQ,OAAO,GAAG6C,EAAQ,KAAK,CAAC,QAAS5C,CAAK,CAAC,EACjF4C,CACT,EAGC,GAAY,CACX,IAAMG,kBAAU,IAAI,IACpB,IAAK,GAAM,CAAChD,EAAKC,KAAU4C,EACzBG,EAAQ,IAAIhD,CAAG,EAEb,IAAM,OAAO,IAAIA,CAAG,GACpB,OAAO,GAAGH,EAAM,OAAO,IAAIG,CAAG,EAAGC,CAAK,GACtC,CAACiB,EAAYf,EAAIH,EAAKC,EAAOqC,CAAK,KAGpCzC,EAAM,OAAO,IAAIG,EAAKC,CAAK,EAC3BF,EAASI,EAAIH,EAAKC,EAAOJ,EAAOyC,CAAK,GAEvC,IAAK,IAAMtC,IAAO,CAAC,GAAGH,EAAM,OAAO,KAAK,CAAC,EACnCmD,EAAQ,IAAIhD,CAAG,IACnBH,EAAM,OAAO,OAAOG,CAAG,EAGvBD,EAASI,EAAIH,EAAK,IAAA,GAAWH,EAAOyC,CAAK,EAE7C,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","isMeasure","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","spreadProps","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and\n * writes `value=\"0\"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as\n * an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.\n */\nfunction isMeasure(el: Element, key: string): boolean {\n // The tag, not `instanceof`: a class of this window is not the class of an iframe's element, and a minimal DOM may\n // not define `HTMLMeterElement` at all.\n return (\n key === \"value\" &&\n (el.localName === \"progress\" || el.localName === \"meter\" || el.localName === \"li\")\n );\n}\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EA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CA,EAA6C,OAAOiB,EACxD,IAAI7C,EACA8C,EAAW,GACf,IAAK,IAAM/C,KAAO,OAAO,KAAK6B,CAAK,EAC7BnC,EAAgB,KAAKM,EAAI,MAAMA,EAAI,QAAQ,GAAG,EAAI,CAAC,CAAC,GAAKgD,EAAa,KAAKhD,CAAG,IAE9EA,IAAQ,WAGN2C,IACF,EAAQ,QAAQ,IAAId,EAAO7B,CAAG,EAC9B,EAAW,IAIf8C,EAAQ,KAAK,CAAC9C,EAAK,QAAQ,IAAI6B,EAAO7B,CAAG,CAAC,CAAC,GAG7C,OADI+C,GAAY,CAACD,EAAQ,MAAM,CAAC9C,KAASA,IAAQ,OAAO,GAAG8C,EAAQ,KAAK,CAAC,QAAS7C,CAAK,CAAC,EACjF6C,CACT,EAGC,GAAY,CACX,IAAMG,kBAAU,IAAI,IACpB,IAAK,GAAM,CAACjD,EAAKC,KAAU6C,EACzBG,EAAQ,IAAIjD,CAAG,EAEbH,EAAM,OAAO,IAAIG,CAAG,GACpB,OAAO,GAAGH,EAAM,OAAO,IAAIG,CAAG,EAAGC,CAAK,GACtC,CAACkB,EAAYhB,EAAIH,EAAKC,EAAOsC,CAAK,IAGpC1C,EAAM,OAAO,IAAIG,EAAKC,CAAK,EAC3BF,EAASI,EAAIH,EAAKC,EAAOJ,EAAO0C,CAAK,GAEvC,IAAK,IAAMvC,IAAO,CAAC,GAAGH,EAAM,OAAO,KAAK,CAAC,EACnCoD,EAAQ,IAAIjD,CAAG,IACnBH,EAAM,OAAO,OAAOG,CAAG,EAGvBD,EAASI,EAAIH,EAAK,IAAA,GAAWH,EAAO0C,CAAK,EAE7C,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
1
+ import{claims as e}from"./internal/hydration-hooks.js";import{nextKey as t}from"./internal/hydration-scope.js";import{MATHML_NS as n}from"./internal/names.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(e,t){let i=document.createElement(`template`),a=t&1?`svg`:t&2?`math`:null;if(a===null)return i.innerHTML=e,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${e}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,n).childNodes):Array.from(o.childNodes):[]}function a(n,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=e.current.claimElement(t());if(a!==null)return a;let c=o??=i(n,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
2
2
  //# sourceMappingURL=template.js.map
@@ -1,2 +1,2 @@
1
- import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(n,r){for(let i of e(n,`SHADOW_CLASS_CYCLE`))if(typeof i==`string`)i!==``&&r.push(i);else if(typeof i==`number`)i!==0&&!Number.isNaN(i)&&r.push(String(i));else if(typeof i==`object`&&i){let e=i;for(let n of Object.keys(e))t(e[n])&&n!==``&&r.push(n)}}function a(e){let n=t(e);if(typeof n==`string`)return n;if(n==null||n===!1)return null;let r=[];return i(n,r),r.join(` `)}function o(e,t,n){let r=a(t);r===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==r&&e.setAttribute(`class`,r):e.className!==r&&(e.className=r)}function s(e,t){o(e,t,e.namespaceURI!==r)}function c(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function l(e,t){return Object.hasOwn(e,t)&&!!e[t]}function u(e,n,r){let i=n??{},a=i;for(let e of Object.keys(i))typeof i[e]==`function`&&(a===i&&(a={...i}),a[e]=t(i[e]));let o=r??{},s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s){let n=l(a,t);if(n!==l(o,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return a}function d(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function f(e,t,r){let i=d(t);r==null||r===!1?e.style.removeProperty(i):e.style.setProperty(i,n(i,r))}function p(e,n,r){let i=t(n);if(i==null||i===!1)return e.removeAttribute(`style`),i;if(typeof i!=`object`)return e.style.cssText=String(i),i;if(Array.isArray(i)){e.style.cssText=``;for(let n of i){let r=t(n);if(typeof r==`string`)e.style.cssText+=`;${r}`;else if(r!=null&&r!==!1){if(typeof r!=`object`||Array.isArray(r))throw TypeError(`SHADOW_STYLE_ITEM`);p(e,r,{})}}return i}let a={...i};for(let e of Object.keys(a))a[e]=t(a[e]);let o=c(r)??{};(typeof r==`string`||Array.isArray(r))&&(e.style.cssText=``);let s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s)Object.is(o[t],a[t])||f(e,t,a[t]);return a}export{o as applyClass,c as asRecord,u as classList,s as className,f as setStyleProperty,p as style,d as toCssProperty};
1
+ import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(n,r){for(let i of e(n,`SHADOW_CLASS_CYCLE`))if(typeof i==`string`)i!==``&&r.push(i);else if(typeof i==`number`)i!==0&&!Number.isNaN(i)&&r.push(String(i));else if(typeof i==`object`&&i){let e=i;for(let n of Object.keys(e))t(e[n])&&n!==``&&r.push(n)}}function a(e){let n=t(e);if(typeof n==`string`)return n;if(n==null||n===!1)return null;let r=[];return i(n,r),r.join(` `)}function o(e,t,n){let r=a(t);r===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==r&&e.setAttribute(`class`,r):e.className!==r&&(e.className=r)}function s(e,t){o(e,t,e.namespaceURI!==r)}function c(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function l(e,t){return Object.hasOwn(e,t)&&!!e[t]}function u(e,n,r){let i=n??{},a=i;for(let e of Object.keys(i))typeof i[e]==`function`&&(a===i&&(a={...i}),a[e]=t(i[e]));let o=r??{},s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s){let n=l(a,t);if(n!==l(o,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return a}function d(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function f(e,t,r){let i=d(t);r==null||r===!1?e.style.removeProperty(i):e.style.setProperty(i,n(i,r))}function p(e,n,r){let i=t(n);if(i==null||i===!1)return e.removeAttribute(`style`),i;if(typeof i!=`object`)return e.style.cssText=String(i),i;if(Array.isArray(i)){e.style.cssText=``;for(let n of i){let r=t(n);if(typeof r==`string`)e.style.cssText+=`;${r}`;else if(r!=null&&r!==!1){if(typeof r!=`object`||Array.isArray(r))throw TypeError(`SHADOW_STYLE_ITEM`);let n={};for(let e of Object.keys(r)){let i=t(r[e]);i!=null&&i!==!1&&(n[e]=i)}p(e,n,{})}}return i}let a={...i};for(let e of Object.keys(a))a[e]=t(a[e]);let o=c(r)??{};(typeof r==`string`||Array.isArray(r))&&(e.style.cssText=``);let s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s)Object.is(o[t],a[t])||f(e,t,a[t]);return a}export{o as applyClass,c as asRecord,u as classList,s as className,f as setStyleProperty,p as style,d as toCssProperty};
2
2
  //# sourceMappingURL=class-style.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,KAAKH,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGG,EAAM,KAAK,OAAOH,CAAI,CA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IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAEFkC,EAAMtB,EAAIZ,EAAM,CAAC,CAAC,CACpB,CACF,CACA,OAAOmC,CACT,CACA,IAAMd,EAAgC,CAAE,GAAIc,CAAqC,EACjF,IAAK,IAAM9B,KAAO,OAAO,KAAKgB,CAAI,EAAG,EAAKhB,GAAOC,EAAOe,EAAKhB,EAAI,EACjE,IAAMiB,EAASN,EAASO,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EACZ,OAAO,GAAGF,EAAOjB,GAAMgB,EAAKhB,EAAI,GACpC0B,EAAiBnB,EAAIP,EAAKgB,EAAKhB,EAAI,EAErC,OAAOgB,CACT,C"}
1
+ {"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved","declared","part"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n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,SAEtB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAQ,EAC3BA,EAET,GAAI,MAAM,QAAQA,CAAQ,EAAG,CAG3B,EAAG,MAAM,QAAU,GACnB,IAAK,IAAMf,KAAUe,EAAU,CAC7B,IAAMnC,EAAOM,EAAOc,CAAM,EAC1B,GAAI,OAAOpB,GAAS,SAClB,EAAG,MAAM,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAIF,IAAMoC,EAAoC,CAAC,EAC3C,IAAK,IAAM/B,KAAO,OAAO,KAAKL,CAAI,EAAG,CACnC,IAAMqC,EAAO/B,EAAQN,EAAiCK,EAAI,EACtDgC,GAAS,MAA8BA,IAAS,KAAO,EAAShC,GAAOgC,EAC7E,CACAH,EAAMtB,EAAIwB,EAAU,CAAC,CAAC,CACxB,CACF,CACA,OAAOD,CACT,CACA,IAAMd,EAAgC,CAAE,GAAIc,CAAqC,EACjF,IAAK,IAAM9B,KAAO,OAAO,KAAKgB,CAAI,EAAG,EAAKhB,GAAOC,EAAOe,EAAKhB,EAAI,EACjE,IAAMiB,EAASN,EAASO,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EACZ,OAAO,GAAGF,EAAOjB,GAAMgB,EAAKhB,EAAI,GACpC0B,EAAiBnB,EAAIP,EAAKgB,EAAKhB,EAAI,EAErC,OAAOgB,CACT,C"}
@@ -1,2 +1,2 @@
1
- import{createComponent as e}from"../component.js";import{isTextOnlyElement as t}from"../server/raw-text.js";import{ssrElement as n,ssrRaw as r}from"../server/element.js";import{mergeProps as i,splitProps as a,untrack as o,useMemo as s}from"@shadow-js/core";const c=/^(?!script$)[a-z][a-z0-9-]*$/i;function l(e,i){if(!c.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);return n(e,i,()=>{let{children:n}=i;return n===void 0||t(e)?n:[r(`<!--[-->`),n,r(`<!--]-->`)]},!0)}function u(t,n){if(!t)return null;if(typeof t==`string`)return l(t,n);if(typeof t==`function`)return e(t,n);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function d(e){let[,t]=a(e,[`component`]);return s(()=>{let n=e.component;return o(()=>u(n,t))},{allowWrites:!0})}function f(e,t={}){return d(i({get component(){return e()}},t))}export{d as Dynamic,f as createDynamic};
1
+ import{createComponent as e}from"../component.js";import{ssrElement as t,ssrRaw as n}from"../server/element.js";import{isTextOnlyElement as r}from"../server/raw-text.js";import{mergeProps as i,splitProps as a,untrack as o,useMemo as s}from"@shadow-js/core";const c=/^(?!script$)[a-z][a-z0-9-]*$/i;function l(e,i){if(!c.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);return t(e,i,()=>{let{children:t}=i;return t===void 0||r(e)?t:[n(`<!--[-->`),t,n(`<!--]-->`)]},!0)}function u(t,n){if(!t)return null;if(typeof t==`string`)return l(t,n);if(typeof t==`function`)return e(t,n);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function d(e){let[,t]=a(e,[`component`]);return s(()=>{let n=e.component;return o(()=>u(n,t))},{allowWrites:!0})}function f(e,t={}){return d(i({get component(){return e()}},t))}export{d as Dynamic,f as createDynamic};
2
2
  //# sourceMappingURL=dynamic.js.map
@@ -1,2 +1,2 @@
1
- import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,moveRegion as o,removeRegion as s}from"../insert.js";import{PortalContext as c}from"../internal/portal-context.js";import{createRoot as l,getOwner as u,isServer as d,onCleanup as f,runWithOwner as p,useContext as m,useRenderEffect as h}from"@shadow-js/core";function g(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function _(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function v(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function y(y){let b=t(),x=m(c);if(d||x!==null)return y.useShadow!==!0&&x?.render?.(b,()=>y.children),null;let S=u(),C,w=r.current.claimPortal(b),T=()=>{let e=C;e!==void 0&&(C=void 0,e.stopEffects(),s(e.region))},E=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:p(S,()=>l(t=>{let a=()=>{i(c,()=>y.children)};return s===`plain`?a():s===`claimed`?n(e(b),a):r.current.withoutClaiming(()=>n(e(b),a)),t}))}},D=e=>{let t=C;if(t===void 0){let t=w??[],n=`plain`;w===void 0?b!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,w=void 0;for(let n of t)n.parentNode!==e&&g(e,n);C=E(e,t,n)}else o(t.region,e,t=>g(e,t)),C={host:e,region:t.region,stopEffects:t.stopEffects}};return h(()=>({host:v(y.mount),shadow:y.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){T();for(let e of w??[])e.parentNode?.removeChild(e);w=void 0;return}let n=t?_(e):e;(C===void 0||C.host!==n)&&D(n)}),f(T),null}export{y as Portal};
1
+ import{bindRegion as e,createRegion as t,moveRegion as n,removeRegion as r}from"../insert.js";import{childScope as i,nextKey as a,withScope as o}from"../internal/hydration-scope.js";import{claims as s}from"../internal/hydration-hooks.js";import{PortalContext as c}from"../internal/portal-context.js";import{createRoot as l,getOwner as u,isServer as d,onCleanup as f,runWithOwner as p,useContext as m,useRenderEffect as h}from"@shadow-js/core";function g(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function _(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function v(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function y(y){let b=a(),x=m(c);if(d||x!==null)return y.useShadow!==!0&&x?.render?.(b,()=>y.children),null;let S=u(),C,w=s.current.claimPortal(b),T=()=>{let e=C;e!==void 0&&(C=void 0,e.stopEffects(),r(e.region))},E=(n,r,a)=>{let c=t(n,null,r);return{host:n,region:c,stopEffects:p(S,()=>l(t=>{let n=()=>{e(c,()=>y.children)};return a===`plain`?n():a===`claimed`?o(i(b),n):s.current.withoutClaiming(()=>o(i(b),n)),t}))}},D=e=>{let t=C;if(t===void 0){let t=w??[],n=`plain`;w===void 0?b!==void 0&&s.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,w=void 0;for(let n of t)n.parentNode!==e&&g(e,n);C=E(e,t,n)}else n(t.region,e,t=>g(e,t)),C={host:e,region:t.region,stopEffects:t.stopEffects}};return h(()=>({host:v(y.mount),shadow:y.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){T();for(let e of w??[])e.parentNode?.removeChild(e);w=void 0;return}let n=t?_(e):e;(C===void 0||C.host!==n)&&D(n)}),f(T),null}export{y as Portal};
2
2
  //# sourceMappingURL=portal.js.map
@@ -1,2 +1,2 @@
1
- import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{escape as r}from"../server/escape.js";import{ssrRaw as i}from"../server/element.js";import{StreamContext as a}from"../internal/stream-context.js";import{SuspenseContext as o,getOwner as s,runWithOwner as c,useContext as l}from"@shadow-js/core";import{SignalNode as u,createOwner as d,readSignal as f,transitionHooks as p,writeSignal as m}from"@shadow-js/core/extend";function h(){let e=new u(0,Object.is),t,n=!1,r=t=>{m(e,e.value+t,{allowInMemo:!0})};return{tracker:{increment:()=>r(1),decrement:()=>{r(-1),e.value===0&&t?.release()},hold:()=>n?(t??=p()?.boundaryHold(),t?.engage()===!0):!1},count:()=>f(e),holding:()=>t?.holding()===!0,revealed:()=>{n=!0}}}function g(r){let i=t(),{tracker:a,count:s,holding:l,revealed:u}=h(),f=d();return f.gate=()=>s()>0||!1,_(r,i,s,c(f,()=>n(e(i),()=>o({value:a,get children(){return r.children}}))))}function _(t,u,d,f){let p=e(u===void 0?void 0:`${u}f`);if(d()===0)return f;let m=l(a);if(m===null||u===void 0)return()=>n(p,()=>t.fallback);let g=s(),_={id:u,rebuild:()=>{let i=h(),a=c(g,()=>n(e(u),()=>o({value:i.tracker,get children(){return t.children}})));return i.count()>0?(m.defer(_),null):r(a())}};return m.defer(_),()=>[i(`<!--[b:${u}-->`),n(p,()=>t.fallback),i(`<!--]-->`)]}export{g as Suspense};
1
+ import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{StreamContext as r}from"../internal/stream-context.js";import{ssrRaw as i}from"../server/element.js";import{escape as a}from"../server/escape.js";import{SuspenseContext as o,getOwner as s,runWithOwner as c,useContext as l}from"@shadow-js/core";import{SignalNode as u,createOwner as d,readSignal as f,transitionHooks as p,writeSignal as m}from"@shadow-js/core/extend";function h(){let e=new u(0,Object.is),t,n=!1,r=t=>{m(e,e.value+t,{allowInMemo:!0})};return{tracker:{increment:()=>r(1),decrement:()=>{r(-1),e.value===0&&t?.release()},hold:()=>n?(t??=p()?.boundaryHold(),t?.engage()===!0):!1},count:()=>f(e),holding:()=>t?.holding()===!0,revealed:()=>{n=!0}}}function g(r){let i=t(),{tracker:a,count:s,holding:l,revealed:u}=h(),f=d();return f.gate=()=>s()>0||!1,_(r,i,s,c(f,()=>n(e(i),()=>o({value:a,get children(){return r.children}}))))}function _(t,u,d,f){let p=e(u===void 0?void 0:`${u}f`);if(d()===0)return f;let m=l(r);if(m===null||u===void 0)return()=>n(p,()=>t.fallback);let g=s(),_={id:u,rebuild:()=>{let r=h(),i=c(g,()=>n(e(u),()=>o({value:r.tracker,get children(){return t.children}})));return r.count()>0?(m.defer(_),null):a(i())}};return m.defer(_),()=>[i(`<!--[b:${u}-->`),n(p,()=>t.fallback),i(`<!--]-->`)]}export{g as Suspense};
2
2
  //# sourceMappingURL=suspense.js.map
@@ -1,2 +1,2 @@
1
- import{isTextOnlyElement as e}from"./server/raw-text.js";import{ssrElement as t,ssrRaw as n}from"./server/element.js";import"@shadow-js/core";const r=/^[a-z][a-z0-9-]*$/i;function i(i,a){if(!r.test(i)||i.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let o=a;return t(i,a,()=>{let t=o.children;return t===void 0||e(i)?t:[n(`<!--[-->`),t,n(`<!--]-->`)]},!0)}export{i as element};
1
+ import{ssrElement as e,ssrRaw as t}from"./server/element.js";import{isTextOnlyElement as n}from"./server/raw-text.js";import"@shadow-js/core";const r=/^[a-z][a-z0-9-]*$/i;function i(i,a){if(!r.test(i)||i.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let o=a;return e(i,a,()=>{let e=o.children;return e===void 0||n(i)?e:[t(`<!--[-->`),e,t(`<!--]-->`)]},!0)}export{i as element};
2
2
  //# sourceMappingURL=element.js.map
@@ -1,2 +1,2 @@
1
- import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(t){e(()=>{let e=`$$${t.type}`,n=`${e}Data`,i=[];for(let a of t.composedPath()){if(t.cancelBubble)break;let o=Reflect.get(a,e);if(typeof o!=`function`)continue;let s=Reflect.get(a,n);try{Object.defineProperty(t,"currentTarget",{configurable:!0,get:()=>a}),r(()=>o.call(a,...s===void 0?[t]:[s,t]))}catch(e){i.push(e)}finally{Reflect.deleteProperty(t,`currentTarget`)}}let[a]=i;if(i.length===1)throw a;if(i.length>1)throw AggregateError(i,`SHADOW_EVENT_ERRORS`)})}function s(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function c(t,n,i,a){let o=t=>{e(()=>r(()=>i(t)))};return t.addEventListener(n,o,a),()=>{t.removeEventListener(n,o,a)}}function l(e,t,n,r){let{once:i,passive:a,signal:o}=n;return c(e,t,e=>n.handleEvent(e),{capture:n.capture===!0||r,once:i,passive:a,signal:o})}function u(...e){return function(t){for(let n of e)n.call(this,t)}}function d(e,t){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n)),!n.has(e)&&(n.add(e),t.addEventListener(e,o))}function f(e,t=globalThis.document){for(let n of e)d(n,t)}function p(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,o);a.delete(e)}}function m(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function h(e,t,n,r,a=!1){if(n==null||n===!1)return;if(s(n))return l(e,t,n,a);let o=n,u,f=!1;if(Array.isArray(n)&&typeof n[0]==`function`)o=n[0],u=n[1],f=!0;else if(typeof n!=`function`)throw TypeError(`SHADOW_EVENT_HANDLER`);let p=`$$${t}`;if(r&&(!f||u!==void 0)&&!a&&i.test(t)&&Reflect.get(e,p)===void 0){d(t,m(e));let n=`${p}Data`;return Reflect.set(e,p,o),f?Reflect.set(e,n,u):Reflect.deleteProperty(e,n),()=>{Reflect.get(e,p)===o&&(Reflect.deleteProperty(e,p),Reflect.deleteProperty(e,n))}}return c(e,t,t=>o.call(e,...f?[u,t]:[t]),a)}function g(e,r,i,a,o){let s=h(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{g as addEventListener,h as bindEvent,u as chainEvents,p as clearDelegatedEvents,f as delegateEvents};
1
+ import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(t){e(()=>{let e=`$$${t.type}`,n=`${e}Data`,i=[];for(let a of t.composedPath()){if(t.cancelBubble)break;let o=Reflect.get(a,e);if(typeof o!=`function`)continue;let s=Reflect.get(a,n);try{Object.defineProperty(t,"currentTarget",{configurable:!0,get:()=>a}),r(()=>o.call(a,...s===void 0?[t]:[s,t]))}catch(e){i.push(e)}finally{Reflect.deleteProperty(t,`currentTarget`)}}let[a]=i;if(i.length===1)throw a;if(i.length>1)throw AggregateError(i,`SHADOW_EVENT_ERRORS`)})}function s(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function c(t,n,i,a){let o=t=>{e(()=>r(()=>i(t)))};return t.addEventListener(n,o,a),()=>{t.removeEventListener(n,o,a)}}function l(e,t,n,r){let{once:i,passive:a,signal:o}=n;return c(e,t,e=>n.handleEvent(e),{capture:n.capture===!0||r,once:i,passive:a,signal:o})}function u(...e){return function(t){for(let n of e)n.call(this,t)}}function d(e,t){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n)),n.has(e)||(n.add(e),t.addEventListener(e,o))}function f(e,t=globalThis.document){for(let n of e)d(n,t)}function p(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,o);a.delete(e)}}function m(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function h(e,t,n,r,a=!1){if(n==null||n===!1)return;if(s(n))return l(e,t,n,a);let o=n,u,f=!1;if(Array.isArray(n)&&typeof n[0]==`function`)o=n[0],u=n[1],f=!0;else if(typeof n!=`function`)throw TypeError(`SHADOW_EVENT_HANDLER`);let p=`$$${t}`;if(r&&(!f||u!==void 0)&&!a&&i.test(t)&&Reflect.get(e,p)===void 0){d(t,m(e));let n=`${p}Data`;return Reflect.set(e,p,o),f?Reflect.set(e,n,u):Reflect.deleteProperty(e,n),()=>{Reflect.get(e,p)===o&&(Reflect.deleteProperty(e,p),Reflect.deleteProperty(e,n))}}return c(e,t,t=>o.call(e,...f?[u,t]:[t]),a)}function g(e,r,i,a,o){let s=h(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{g as addEventListener,h as bindEvent,u as chainEvents,p as clearDelegatedEvents,f as delegateEvents};
2
2
  //# sourceMappingURL=events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","dispatchDelegated","batch","key","event","dataKey","errors","node","fn","data","untrack","error","first","isListenerObject","handler","listen","listener","run","el","name","options","bindListenerObject","object","capture","chainEvents","handlers","installDelegate","known","target","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","tuple","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n });\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n for (const name of names) installDelegate(name, target);\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n }\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAkB,EAAoB,CAG7CC,MAAY,CACV,IAAMC,EAAM,KAAKC,EAAM,OACjBC,EAAU,GAAGF,EAAI,MACjBG,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMI,EAAK,QAAQ,IAAID,EAAMJ,CAAG,EAChC,GAAI,OAAOK,GAAO,WAAY,SAC9B,IAAMC,EAAO,QAAQ,IAAIF,EAAMF,CAAO,EACtC,GAAI,CACF,OAAO,eAAeD,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWG,CAA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O,MAC1B,CACP,QAAQ,IAAIa,EAAIkB,CAAI,IAAM5B,IAC5B,QAAQ,eAAeU,EAAIkB,CAAI,EAC/B,QAAQ,eAAelB,EAAIb,CAAO,EAEtC,CACF,CACA,OAAOU,EAAOG,EAAIC,EAAO,GAAUX,EAAG,KAAKU,EAAI,GAAIiB,EAAQ,CAAC1B,EAAML,CAAK,EAAI,CAACA,CAAK,CAAE,EAAGmB,CAAO,CAC/F,CA6BA,SAAgBe,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASL,EAAUhB,EAAIC,EAAML,EAASuB,IAAa,GAAMd,IAAY,EAAI,EAE3EgB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
1
+ {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","dispatchDelegated","batch","key","event","dataKey","errors","node","fn","data","untrack","error","first","isListenerObject","handler","listen","listener","run","el","name","options","bindListenerObject","object","capture","chainEvents","handlers","installDelegate","known","target","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","tuple","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n });\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n for (const name of names) installDelegate(name, target);\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n }\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAkB,EAAoB,CAG7CC,MAAY,CACV,IAAMC,EAAM,KAAKC,EAAM,OACjBC,EAAU,GAAGF,EAAI,MACjBG,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMI,EAAK,QAAQ,IAAID,EAAMJ,CAAG,EAChC,GAAI,OAAOK,GAAO,WAAY,SAC9B,IAAMC,EAAO,QAAQ,IAAIF,EAAMF,CAAO,EACtC,GAAI,CACF,OAAO,eAAeD,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWG,CAAK,CAAC,EACrFG,MACGF,EAAe,KAAKD,EAAM,GAAIE,IAAS,IAAA,GAAY,CAACL,CAAK,EAAI,CAACK,EAAML,CAAK,CAAE,CAC9E,CACF,OAASO,EAAO,CACdL,EAAO,KAAKK,CAAK,CACnB,QAAU,CACR,QAAQ,eAAeP,EAAO,eAAe,CAC/C,CACF,CACA,GAAM,CAACQ,GAASN,EAChB,GAAIA,EAAO,SAAW,EAAG,MAAMM,EAC/B,GAAIN,EAAO,OAAS,EAClB,MAAU,eACRA,EAC4C,qBAC9C,CACJ,CAAC,CACH,CAWA,SAASO,EAAiB,EAA6C,CACrE,OACE,OAAOC,GAAY,YACnBA,GACA,OAAQA,EAAsC,aAAgB,UAElE,CAGA,SAASC,EACP,EACA,EACA,EACA,EACY,CACZ,IAAMC,EAAY,GAAuB,CACvCd,MAAYQ,MAAcO,EAAIb,CAAK,CAAC,CAAC,CACvC,EAEA,OADAc,EAAG,iBAAiBC,EAAMH,EAAUI,CAAO,MAC9B,CACXF,EAAG,oBAAoBC,EAAMH,EAAUI,CAAO,CAChD,CACF,CAGA,SAASC,EACP,EACA,EACA,EACA,EACY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I,MAAM,QAAQrB,CAAO,GAAK,OAAOA,EAAQ,IAAO,WAClD,EAAKA,EAAQ,GACb,EAAOA,EAAQ,GACf,EAAQ,QACH,GAAI,OAAOA,GAAY,WAC5B,MAAU,UAGJ,sBACN,EAIF,IAAMsB,EAAO,KAAKjB,IAGlB,GACEkB,IACC,CAACF,GAAS1B,IAAS,IAAA,KACpB,CAACc,GACDxB,EAAiB,KAAKoB,CAAI,GAC1B,QAAQ,IAAID,EAAIkB,CAAI,IAAM,IAAA,GAC1B,CACAV,EAAgBP,EAAMa,EAAmBd,CAAE,CAAC,EAC5C,IAAMb,EAAU,GAAG+B,EAAK,MAIxB,OAHA,QAAQ,IAAIlB,EAAIkB,EAAM5B,CAAE,EACpB2B,EAAO,QAAQ,IAAIjB,EAAIb,EAASI,CAAI,EACnC,QAAQ,eAAeS,EAAIb,CAAO,MAC1B,CACP,QAAQ,IAAIa,EAAIkB,CAAI,IAAM5B,IAC5B,QAAQ,eAAeU,EAAIkB,CAAI,EAC/B,QAAQ,eAAelB,EAAIb,CAAO,EAEtC,CACF,CACA,OAAOU,EAAOG,EAAIC,EAAO,GAAUX,EAAG,KAAKU,EAAI,GAAIiB,EAAQ,CAAC1B,EAAML,CAAK,EAAI,CAACA,CAAK,CAAE,EAAGmB,CAAO,CAC/F,CA6BA,SAAgBe,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASL,EAAUhB,EAAIC,EAAML,EAASuB,IAAa,GAAMd,IAAY,EAAI,EAE3EgB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
@@ -1 +1 @@
1
- import{warnOnce as e}from"./internal/diagnostics.js";import{isUnsafeUrlAttribute as t}from"./attributes.js";import{HTML_NS as n,MATHML_NS as r,SVG_NS as i}from"./internal/names.js";import{childScope as a,createRootScope as o,currentScope as s,enterComponent as c,nextKey as l,resourceKey as u,withScope as d}from"./internal/hydration-scope.js";import{claimElement as f,claimPortal as p,isClaiming as m,takeRegion as h,withoutClaiming as g}from"./internal/claim.js";import{claims as _}from"./internal/hydration-hooks.js";import{reconcileNodes as v}from"./internal/reconcile.js";import{bindRegion as y,createRegion as b,moveRegion as x,removeRegion as S}from"./insert.js";import{element as C}from"./element.js";import{PortalContext as w}from"./internal/portal-context.js";import{StreamContext as T}from"./internal/stream-context.js";export{n as HTML_NS,r as MATHML_NS,w as PortalContext,i as SVG_NS,T as StreamContext,y as bindRegion,a as childScope,f as claimElement,p as claimPortal,_ as claims,b as createRegion,o as createRootScope,s as currentScope,C as element,c as enterComponent,m as isClaiming,t as isUnsafeUrlAttribute,x as moveRegion,l as nextKey,v as reconcileNodes,S as removeRegion,u as resourceKey,h as takeRegion,e as warnOnce,d as withScope,g as withoutClaiming};
1
+ import{isUnsafeUrlAttribute as e}from"./attributes.js";import{element as t}from"./element.js";import{bindRegion as n,createRegion as r,moveRegion as i,removeRegion as a}from"./insert.js";import{claimElement as o,claimPortal as s,isClaiming as c,takeRegion as l,withoutClaiming as u}from"./internal/claim.js";import{warnOnce as d}from"./internal/diagnostics.js";import{claims as f}from"./internal/hydration-hooks.js";import{childScope as p,createRootScope as m,currentScope as h,enterComponent as g,nextKey as _,resourceKey as v,withScope as y}from"./internal/hydration-scope.js";import{HTML_NS as b,MATHML_NS as x,SVG_NS as S}from"./internal/names.js";import{PortalContext as C}from"./internal/portal-context.js";import{reconcileNodes as w}from"./internal/reconcile.js";import{StreamContext as T}from"./internal/stream-context.js";export{b as HTML_NS,x as MATHML_NS,C as PortalContext,S as SVG_NS,T as StreamContext,n as bindRegion,p as childScope,o as claimElement,s as claimPortal,f as claims,r as createRegion,m as createRootScope,h as currentScope,t as element,g as enterComponent,c as isClaiming,e as isUnsafeUrlAttribute,i as moveRegion,_ as nextKey,w as reconcileNodes,a as removeRegion,v as resourceKey,l as takeRegion,d as warnOnce,y as withScope,u as withoutClaiming};
@@ -1,2 +1,2 @@
1
- import{createHeadRegistry as e}from"./registry.js";import{normalizeTags as t}from"./validate.js";import{ServerHeadContext as n}from"./server-head.js";import{createDomHeadSink as r}from"./sink.js";import{createRoot as i,getOwner as a,isServer as o,untrack as s,useContext as c,useEffect as l,useRenderEffect as u,useSignal as d}from"@shadow-js/core";const f=/* @__PURE__ */ new WeakMap;function p(t){return i(()=>{let[n,i]=d(0),a=e(()=>{i(e=>e+1)}),o=r(t);return l(()=>(n(),a.winners()),e=>{o(e)}),a},{detached:!0})}function m(e){let t=f.get(e);if(t!==void 0)return t;let n=p(e);return f.set(e,n),n}function h(e){if(o){let r=a()===null?null:c(n);r!==null&&r.add(t(s(()=>typeof e==`function`?e():e)));return}if(a()===null)return;let r=m(document);u(()=>t(typeof e==`function`?e():e),e=>r.add(e))}export{h as useHead};
1
+ import{createHeadRegistry as e}from"./registry.js";import{ServerHeadContext as t}from"./server-head.js";import{createDomHeadSink as n}from"./sink.js";import{normalizeTags as r}from"./validate.js";import{createRoot as i,getOwner as a,isServer as o,untrack as s,useContext as c,useEffect as l,useRenderEffect as u,useSignal as d}from"@shadow-js/core";const f=/* @__PURE__ */ new WeakMap;function p(t){return i(()=>{let[r,i]=d(0),a=e(()=>{i(e=>e+1)}),o=n(t);return l(()=>(r(),a.winners()),e=>{o(e)}),a},{detached:!0})}function m(e){let t=f.get(e);if(t!==void 0)return t;let n=p(e);return f.set(e,n),n}function h(e){if(o){let n=a()===null?null:c(t);n!==null&&n.add(r(s(()=>typeof e==`function`?e():e)));return}if(a()===null)return;let n=m(document);u(()=>r(typeof e==`function`?e():e),e=>n.add(e))}export{h as useHead};
2
2
  //# sourceMappingURL=use-head.js.map
@@ -1,2 +1,2 @@
1
- import"../internal/diagnostics.js";import{isUnsafeUrlAttribute as e}from"../attributes.js";const t=`data-shadow-head`,n=`data-shadow-key`,r=/* @__PURE__ */ new Set([`title`,`meta`,`link`,`style`,`base`]),i=/^[a-zA-Z_][a-zA-Z0-9_:.-]*$/,a=/* @__PURE__ */ new Set([t,n]),o=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),s=[`name`,`property`,`http-equiv`,`charset`],c=/* @__PURE__ */ new Set([`og:image`,`og:video`,`og:audio`,`og:locale:alternate`,`og:email`,`og:phone_number`,`og:fax_number`,`article:tag`,`article:author`,`book:author`,`book:tag`,`music:album`,`music:song`,`music:musician`,`music:creator`,`video:actor`,`video:director`,`video:writer`,`video:tag`,`fb:admins`,`twitter:image`]),l=/* @__PURE__ */ new Set([`alternate`,`author`,`archives`,`assets`,`bookmarks`,`me`,`apple-touch-startup-image`]),u=/* @__PURE__ */ new Set([`preload`,`modulepreload`,`prefetch`,`preconnect`,`dns-prefetch`,`stylesheet`]);function d(e){return r.has(e)}function f(e){return e.map(e=>`${e.length}:${e}`).join(``)}function p(e){if(e!=null&&e!==!1){if(e===!0)return``;if(typeof e==`string`)return e;if(typeof e==`number`)return String(e);throw TypeError(`SHADOW_HEAD_ATTRIBUTE_VALUE`)}}function m(t,n){if(n==null)return/* @__PURE__ */ new Map;if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_HEAD_PROPS`);let r=/* @__PURE__ */ new Map;for(let s of Object.keys(n)){if(!i.test(s))throw TypeError(`SHADOW_HEAD_ATTRIBUTE_NAME`);let c=s.toLowerCase();if(c.startsWith(`on`))throw TypeError(`SHADOW_HEAD_EVENT_ATTRIBUTE`);if(a.has(c))throw TypeError(`SHADOW_HEAD_RESERVED`);if(o.has(c))continue;let l=p(Reflect.get(n,s));l!==void 0&&(e(c,l)?`${c}${t}`:r.set(c,l))}return r}function h(e,t){if(t!=null){if(e!==`title`&&e!==`style`)throw TypeError(`SHADOW_HEAD_NO_CHILDREN`);if(typeof t!=`string`)throw TypeError(`SHADOW_HEAD_TEXT`);return t}}function g(e,t){if(t!=null){if(e!==`style`)throw TypeError(`SHADOW_HEAD_STYLE_KEY`);if(typeof t!=`string`||t===``)throw TypeError(`SHADOW_HEAD_KEY`);return t}}function _(e){if(e===void 0)return;let t=e.toLowerCase().split(/\s+/).filter(e=>e!==``);if(t.length!==0)return t.sort().join(` `)}function v(e){let t=e.get(`media`)??``;for(let n of s){let r=e.get(n);if(r!==void 0)return n===`charset`?f([`meta`,n]):c.has(r)?f([`meta`,n,r,t,e.get(`content`)??``]):f([`meta`,n,r,t])}}function y(e){let t=_(e.get(`rel`));if(t!==void 0){if(t.split(` `).some(e=>e===`icon`||e.endsWith(`-icon`)))return f([`link`,`icon`,t,e.get(`sizes`)??``,e.get(`type`)??``]);if(t===`canonical`)return f([`link`,`canonical`]);if(u.has(t))return f([`link`,`resource`,t,e.get(`href`)??``,e.get(`as`)??``]);if(l.has(t))return f([`link`,`multi`,t,e.get(`href`)??``,e.get(`hreflang`)??``,e.get(`media`)??``,e.get(`type`)??``])}}function b(e,t,n){return e===`title`?f([`title`]):e===`base`?f([`base`]):e===`style`?n===void 0?void 0:f([`style`,n]):e===`meta`?v(t):y(t)}function x(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`SHADOW_HEAD_TAG`);let t=Reflect.get(e,`tag`);if(typeof t!=`string`||!d(t))throw TypeError(`SHADOW_HEAD_TAG_NAME`);let n=m(t,Reflect.get(e,`props`)),r=h(t,Reflect.get(e,`children`)),i=g(t,Reflect.get(e,`key`));return{tag:t,attributes:[...n],text:r,key:i,identity:b(t,n,i)}}function S(e){return e==null||e===!1?[]:Array.isArray(e)?e.map(e=>x(e)):[x(e)]}function C(e){let t=e.localName;if(!d(t))return;let n=/* @__PURE__ */ new Map;for(let t of Array.from(e.attributes))t.name!==`data-shadow-head`&&t.name!==`data-shadow-key`&&n.set(t.name.toLowerCase(),t.value);return b(t,n,e.getAttribute(`data-shadow-key`)??void 0)}export{n as HEAD_KEY,t as HEAD_MARKER,b as identityOf,C as identityOfElement,d as isHeadTagName,x as normalizeTag,S as normalizeTags};
1
+ import{isUnsafeUrlAttribute as e}from"../attributes.js";import"../internal/diagnostics.js";const t=`data-shadow-head`,n=`data-shadow-key`,r=/* @__PURE__ */ new Set([`title`,`meta`,`link`,`style`,`base`]),i=/^[a-zA-Z_][a-zA-Z0-9_:.-]*$/,a=/* @__PURE__ */ new Set([t,n]),o=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),s=[`name`,`property`,`http-equiv`,`charset`],c=/* @__PURE__ */ new Set([`og:image`,`og:video`,`og:audio`,`og:locale:alternate`,`og:email`,`og:phone_number`,`og:fax_number`,`article:tag`,`article:author`,`book:author`,`book:tag`,`music:album`,`music:song`,`music:musician`,`music:creator`,`video:actor`,`video:director`,`video:writer`,`video:tag`,`fb:admins`,`twitter:image`]),l=/* @__PURE__ */ new Set([`alternate`,`author`,`archives`,`assets`,`bookmarks`,`me`,`apple-touch-startup-image`]),u=/* @__PURE__ */ new Set([`preload`,`modulepreload`,`prefetch`,`preconnect`,`dns-prefetch`,`stylesheet`]);function d(e){return r.has(e)}function f(e){return e.map(e=>`${e.length}:${e}`).join(``)}function p(e){if(e!=null&&e!==!1){if(e===!0)return``;if(typeof e==`string`)return e;if(typeof e==`number`)return String(e);throw TypeError(`SHADOW_HEAD_ATTRIBUTE_VALUE`)}}function m(t,n){if(n==null)return/* @__PURE__ */ new Map;if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_HEAD_PROPS`);let r=/* @__PURE__ */ new Map;for(let s of Object.keys(n)){if(!i.test(s))throw TypeError(`SHADOW_HEAD_ATTRIBUTE_NAME`);let c=s.toLowerCase();if(c.startsWith(`on`))throw TypeError(`SHADOW_HEAD_EVENT_ATTRIBUTE`);if(a.has(c))throw TypeError(`SHADOW_HEAD_RESERVED`);if(o.has(c))continue;let l=p(Reflect.get(n,s));l!==void 0&&(e(c,l)?`${c}${t}`:r.set(c,l))}return r}function h(e,t){if(t!=null){if(e!==`title`&&e!==`style`)throw TypeError(`SHADOW_HEAD_NO_CHILDREN`);if(typeof t!=`string`)throw TypeError(`SHADOW_HEAD_TEXT`);return t}}function g(e,t){if(t!=null){if(e!==`style`)throw TypeError(`SHADOW_HEAD_STYLE_KEY`);if(typeof t!=`string`||t===``)throw TypeError(`SHADOW_HEAD_KEY`);return t}}function _(e){if(e===void 0)return;let t=e.toLowerCase().split(/\s+/).filter(e=>e!==``);if(t.length!==0)return t.sort().join(` `)}function v(e){let t=e.get(`media`)??``;for(let n of s){let r=e.get(n);if(r!==void 0)return n===`charset`?f([`meta`,n]):c.has(r)?f([`meta`,n,r,t,e.get(`content`)??``]):f([`meta`,n,r,t])}}function y(e){let t=_(e.get(`rel`));if(t!==void 0){if(t.split(` `).some(e=>e===`icon`||e.endsWith(`-icon`)))return f([`link`,`icon`,t,e.get(`sizes`)??``,e.get(`type`)??``]);if(t===`canonical`)return f([`link`,`canonical`]);if(u.has(t))return f([`link`,`resource`,t,e.get(`href`)??``,e.get(`as`)??``]);if(l.has(t))return f([`link`,`multi`,t,e.get(`href`)??``,e.get(`hreflang`)??``,e.get(`media`)??``,e.get(`type`)??``])}}function b(e,t,n){return e===`title`?f([`title`]):e===`base`?f([`base`]):e===`style`?n===void 0?void 0:f([`style`,n]):e===`meta`?v(t):y(t)}function x(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`SHADOW_HEAD_TAG`);let t=Reflect.get(e,`tag`);if(typeof t!=`string`||!d(t))throw TypeError(`SHADOW_HEAD_TAG_NAME`);let n=m(t,Reflect.get(e,`props`)),r=h(t,Reflect.get(e,`children`)),i=g(t,Reflect.get(e,`key`));return{tag:t,attributes:[...n],text:r,key:i,identity:b(t,n,i)}}function S(e){return e==null||e===!1?[]:Array.isArray(e)?e.map(e=>x(e)):[x(e)]}function C(e){let t=e.localName;if(!d(t))return;let n=/* @__PURE__ */ new Map;for(let t of Array.from(e.attributes))t.name!==`data-shadow-head`&&t.name!==`data-shadow-key`&&n.set(t.name.toLowerCase(),t.value);return b(t,n,e.getAttribute(`data-shadow-key`)??void 0)}export{n as HEAD_KEY,t as HEAD_MARKER,b as identityOf,C as identityOfElement,d as isHeadTagName,x as normalizeTag,S as normalizeTags};
2
2
  //# sourceMappingURL=validate.js.map
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"./internal/hydration-scope.js";import{beginClaiming as r,claimElement as i,claimPortal as a,endClaiming as o,isClaiming as s,liftedRegions as c,releaseUnclaimedPortals as l,takeRegion as u,withoutClaiming as d}from"./internal/claim.js";import{claims as f}from"./internal/hydration-hooks.js";import{bindRegion as p,createRegion as m,removeRegion as h}from"./insert.js";import{attachRootErrors as g}from"./control-flow/root-errors.js";import{replayEarlyEvents as _}from"./internal/early-events.js";import{ResourceCacheContext as v,batch as y,createRoot as b,flushSync as x,runWithOwner as S,untrack as C}from"@shadow-js/core";import{withHydration as w}from"@shadow-js/core/extend";function T(e){let n=/* @__PURE__ */ new Set;return{key:t,read(t){if(!n.has(t)&&Object.hasOwn(e,t))return n.add(t),{value:e[t]}},track(){}}}function E(e){let t=e instanceof Document?e:e.ownerDocument;if(t===null)return;t.body!==null&&l(t.body);let n=t.createTreeWalker(e,NodeFilter.SHOW_COMMENT),r=[];for(;n.nextNode();){let e=n.currentNode;(e.data===`[`||e.data===`]`)&&r.push(e)}for(let e of r)e.remove()}function D(t,l,D={}){if(s())throw Error(`SHADOW_HYDRATE_RUNNING`);let O=/* @__PURE__ */ new Map,k=l instanceof Element?[l]:[];for(let e of[...k,...Array.from(l.querySelectorAll(`[data-hk]`))]){let t=e.getAttribute(`data-hk`);t!==null&&O.set(t,e)}r(O,D.onRecoverableError);let A={claimElement:i,takeRegion:u,liftedRegions:c,claimPortal:a,isClaiming:s,withoutClaiming:d},j=f.current;f.current=A;let M=T(D.data??{}),N=m(l,null,Array.from(l.childNodes)),P;try{P=w(()=>y(()=>n(e(D.renderId),()=>S(D.owner??null,()=>b(e=>(g(D),v({value:M,get children(){return p(N,C(t)),null}}),e)))))),x()}finally{o(),f.current=j}_(),E(l);let F=!1;return()=>{F||(F=!0,P(),h(N))}}export{D as hydrate};
1
+ import{attachRootErrors as e}from"./control-flow/root-errors.js";import{bindRegion as t,createRegion as n,removeRegion as r}from"./insert.js";import{beginClaiming as i,claimElement as a,claimPortal as o,endClaiming as s,isClaiming as c,liftedRegions as l,releaseUnclaimedPortals as u,takeRegion as d,withoutClaiming as f}from"./internal/claim.js";import{replayEarlyEvents as p}from"./internal/early-events.js";import{claims as m}from"./internal/hydration-hooks.js";import{createRootScope as h,resourceKey as g,withScope as _}from"./internal/hydration-scope.js";import{ResourceCacheContext as v,batch as y,createRoot as b,flushSync as x,runWithOwner as S,untrack as C}from"@shadow-js/core";import{withHydration as w}from"@shadow-js/core/extend";function T(e){let t=/* @__PURE__ */ new Set;return{key:g,read(n){if(!t.has(n)&&Object.hasOwn(e,n))return t.add(n),{value:e[n]}},track(){}}}function E(e){let t=e instanceof Document?e:e.ownerDocument;if(t===null)return;t.body!==null&&u(t.body);let n=t.createTreeWalker(e,NodeFilter.SHOW_COMMENT),r=[];for(;n.nextNode();){let e=n.currentNode;(e.data===`[`||e.data===`]`)&&r.push(e)}for(let e of r)e.remove()}function D(u,g,D={}){if(c())throw Error(`SHADOW_HYDRATE_RUNNING`);let O=/* @__PURE__ */ new Map,k=g instanceof Element?[g]:[];for(let e of[...k,...Array.from(g.querySelectorAll(`[data-hk]`))]){let t=e.getAttribute(`data-hk`);t!==null&&O.set(t,e)}i(O,D.onRecoverableError);let A={claimElement:a,takeRegion:d,liftedRegions:l,claimPortal:o,isClaiming:c,withoutClaiming:f},j=m.current;m.current=A;let M=T(D.data??{}),N=n(g,null,Array.from(g.childNodes)),P,F=!1,I=()=>{F||(F=!0,P?.(),r(N))};try{w(()=>y(()=>_(h(D.renderId),()=>S(D.owner??null,()=>b(n=>{P=n,e(D),v({value:M,get children(){return t(N,C(u)),null}})}))))),x()}catch(e){try{P?.()}catch(t){throw AggregateError([e,t],`SHADOW_HYDRATE_ERRORS`)}throw e}finally{s(),m.current=j}return p(),E(g),I}export{D as hydrate};
2
2
  //# sourceMappingURL=hydration.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","dispose","flushSync","endClaiming","replayEarlyEvents","disposed","removeRegion"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: () => void;\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n stop = withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n return dispose;\n }),\n ),\n ),\n ),\n );\n flushSync();\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n stop();\n removeRegion(region);\n };\n}\n"],"mappings":"A,wuBAsDA,SAASA,EAAU,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IAAKC,EACL,KAAK,EAAK,CACR,GAAI,GAAK,IAAIC,CAAG,GAAM,OAAO,OAAOC,EAAMD,CAAG,EAE7C,OADAF,EAAK,IAAIE,CAAG,EACL,CAAE,MAAOC,EAAKD,EAAK,CAC5B,EACA,OAAQ,CAER,CACF,CACF,CAMA,SAASE,EAAe,EAAuB,CAC7C,IAAMC,EAAMC,aAAqB,SA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ACH,CACF,CACF,CACF,EACAC,EAAU,CACZ,QAAU,CACRC,EAAY,EACZ,EAAO,QAAUnB,CACnB,CACAoB,EAAkB,EAClBnC,EAAeE,CAAS,EACxB,IAAIkC,EAAW,GACf,UAAa,CACPA,IACJ,EAAW,GACXhB,EAAK,EACLiB,EAAanB,CAAM,EACrB,CACF,C"}
1
+ {"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","disposed","teardown","removeRegion","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","dispose","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","flushSync","error","cleanupError","endClaiming","replayEarlyEvents"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":"A,wuBAsDA,SAASA,EAAU,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IAAKC,EACL,KAAK,EAAK,CACR,GAAI,GAAK,IAAIC,CAAG,GAAM,OAAO,OAAOC,EAAMD,CAAG,EAE7C,OADAF,EAAK,IAAIE,CAAG,EACL,CAAE,MAAOC,EAAKD,EAAK,CAC5B,EACA,OAAQ,CAER,CACF,CACF,CAMA,SAASE,EAAe,EAAuB,CAC7C,IAAMC,EAAMC,aAAqB,SAAWA,EAAYA,EAAU,cAClE,GAAID,IAAQ,KAAM,OACdA,EAAI,OAAS,MAAME,EAAwBF,EAAI,IAAI,EACvD,IAAMG,EAASH,EAAI,iBAAiBC,EAAW,WAAW,YAAY,EAChEG,EAAmB,CAAC,EAC1B,KAAOD,EAAO,SAAS,GAAG,CACxB,IAAME,EAAUF,EAAO,aACnBE,EAAQ,OAAS,KAAOA,EAAQ,OAAS,MAAKD,EAAM,KAAKC,CAAO,CACtE,CACA,IAAK,IAAMA,KAAWD,EAAOC,EAAQ,OAAO,CAC9C,CAgCA,SAAgBC,EACd,EACA,EACA,EAA0B,CAAC,EACf,CACZ,GAAIC,EAAW,EACb,MAAU,MACsD,wBAChE,EACF,IAAMC,kBAAW,IAAI,IACfC,EAAmBR,aAAqB,QAAU,CAACA,CAAS,EAAI,CAAC,EACvE,IAAK,IAAMS,IAAW,CAAC,GAAGD,EAAO,GAAG,MAAM,KAAKR,EAAU,iBAAiB,WAAW,CAAC,CAAC,EAAG,CACxF,IAAMJ,EAAMa,EAAQ,aAAa,SAAS,EACtCb,IAAQ,MAAMW,EAAS,IAAIX,EAAKa,CAAO,CAC7C,CACAC,EAAcH,EAAUI,EAAQ,kBAAkB,EAElD,IAAMC,EAAqB,CACzB,eACA,aACA,gBACA,cACA,aACA,iBACF,EACMC,EAAiBC,EAAO,QAC9B,EAAO,QAAUF,EACjB,IAAMG,EAAQtB,EAAUkB,EAAQ,MAAQ,CAAC,CAAC,EACpCK,EAASC,EAAajB,EAAW,KAAM,MAAM,KAAKA,EAAU,UAAU,CAAC,EACzEkB,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaL,CAAM,EACrB,EACA,GAAI,CAMFM,MACEC,MACEC,EAAUC,EAAgBd,EAAQ,QAAQ,MACxCe,EAAaf,EAAQ,OAAS,SAC5BgB,EAAY,GAAY,CACtB,EAAOC,EACPC,EAAiBlB,CAAO,EACxBmB,EAAqB,CACnB,MAAOf,EACP,IAAI,UAAW,CAEb,OADAgB,EAAWf,EAAQgB,EAAQC,CAAI,CAAC,EACzB,IACT,CACF,CAAC,CACH,CAAC,CACH,CACF,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFjB,IAAO,CACT,OAASkB,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACoC,uBAC1D,CACF,CACA,MAAMD,CACR,QAAU,CACRE,EAAY,EACZ,EAAO,QAAUxB,CACnB,CAGA,OAFAyB,EAAkB,EAClBxC,EAAeE,CAAS,EACjBoB,CACT,C"}
@@ -1 +1 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{classList as i,className as a,setStyleProperty as o,style as s}from"./class-style.js";import{createComponent as c}from"./component.js";import{Activity as l}from"./control-flow/activity.js";import{Show as u}from"./control-flow/show.js";import{ClientOnly as d}from"./control-flow/client-only.js";import{anchor as f,insert as p}from"./insert.js";import{element as m}from"./element.js";import{addEventListener as h,chainEvents as g,clearDelegatedEvents as _,delegateEvents as v}from"./events.js";import{setSelectValue as y}from"./select-value.js";import{spread as b}from"./spread.js";import{Dynamic as x,createDynamic as S}from"./control-flow/dynamic.js";import{ErrorBoundary as C}from"./control-flow/error-boundary.js";import{For as w}from"./control-flow/for.js";import{Fragment as T}from"./control-flow/fragment.js";import{Index as E}from"./control-flow/index-list.js";import{lazy as D}from"./control-flow/lazy.js";import{NoHydration as O}from"./control-flow/no-hydration.js";import{Portal as k}from"./control-flow/portal.js";import{SuspenseList as A}from"./control-flow/suspense-list.js";import{Suspense as j}from"./control-flow/suspense.js";import{Match as M,Switch as N}from"./control-flow/switch.js";import{derived as P}from"./derived.js";import{useHead as F}from"./head/use-head.js";import{Base as I,Link as L,Meta as R,Style as z,Title as B}from"./head/components.js";import{hydrate as V}from"./hydration.js";import{effect as H,memo as U,refTo as W,use as G}from"./reactive.js";import{render as K}from"./render.js";import{preconnect as q,prefetchDNS as J,preinit as Y,preinitModule as X,preload as Z,preloadModule as Q}from"./resource-hints.js";import{template as $}from"./template.js";import{ViewTransition as ee,startViewTransition as te}from"./view-transition.js";import{isDev as ne,isServer as re,mergeProps as ie}from"@shadow-js/core";export{l as Activity,I as Base,d as ClientOnly,x as Dynamic,C as ErrorBoundary,w as For,T as Fragment,E as Index,L as Link,M as Match,R as Meta,O as NoHydration,k as Portal,u as Show,z as Style,j as Suspense,A as SuspenseList,N as Switch,B as Title,ee as ViewTransition,h as addEventListener,f as anchor,r as autoFocus,g as chainEvents,i as classList,a as className,_ as clearDelegatedEvents,c as createComponent,S as createDynamic,v as delegateEvents,P as derived,H as effect,m as element,V as hydrate,p as insert,ne as isDev,re as isServer,D as lazy,U as memo,ie as mergeProps,q as preconnect,J as prefetchDNS,Y as preinit,X as preinitModule,Z as preload,Q as preloadModule,W as refTo,K as render,e as setAttribute,t as setAttributeNS,n as setBoolAttribute,y as setSelectValue,o as setStyleProperty,b as spread,te as startViewTransition,s as style,$ as template,G as use,F as useHead};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{classList as i,className as a,setStyleProperty as o,style as s}from"./class-style.js";import{createComponent as c}from"./component.js";import{Activity as l}from"./control-flow/activity.js";import{Show as u}from"./control-flow/show.js";import{ClientOnly as d}from"./control-flow/client-only.js";import{derived as f}from"./derived.js";import{element as p}from"./element.js";import{addEventListener as m,chainEvents as h,clearDelegatedEvents as g,delegateEvents as _}from"./events.js";import{hydrate as v}from"./hydration.js";import{anchor as y,insert as b}from"./insert.js";import{Dynamic as x,createDynamic as S}from"./control-flow/dynamic.js";import{ErrorBoundary as C}from"./control-flow/error-boundary.js";import{For as w}from"./control-flow/for.js";import{Fragment as T}from"./control-flow/fragment.js";import{Index as E}from"./control-flow/index-list.js";import{lazy as D}from"./control-flow/lazy.js";import{NoHydration as O}from"./control-flow/no-hydration.js";import{Portal as k}from"./control-flow/portal.js";import{SuspenseList as A}from"./control-flow/suspense-list.js";import{Suspense as j}from"./control-flow/suspense.js";import{Match as M,Switch as N}from"./control-flow/switch.js";import{effect as P,memo as F,refTo as I,use as L}from"./reactive.js";import{useHead as R}from"./head/use-head.js";import{Base as z,Link as B,Meta as V,Style as H,Title as U}from"./head/components.js";import{render as W}from"./render.js";import{preconnect as G,prefetchDNS as K,preinit as q,preinitModule as J,preload as Y,preloadModule as X}from"./resource-hints.js";import{setSelectValue as Z}from"./select-value.js";import{spread as Q}from"./spread.js";import{template as $}from"./template.js";import{ViewTransition as ee,startViewTransition as te}from"./view-transition.js";import{isDev as ne,isServer as re,mergeProps as ie}from"@shadow-js/core";export{l as Activity,z as Base,d as ClientOnly,x as Dynamic,C as ErrorBoundary,w as For,T as Fragment,E as Index,B as Link,M as Match,V as Meta,O as NoHydration,k as Portal,u as Show,H as Style,j as Suspense,A as SuspenseList,N as Switch,U as Title,ee as ViewTransition,m as addEventListener,y as anchor,r as autoFocus,h as chainEvents,i as classList,a as className,g as clearDelegatedEvents,c as createComponent,S as createDynamic,_ as delegateEvents,f as derived,P as effect,p as element,v as hydrate,b as insert,ne as isDev,re as isServer,D as lazy,F as memo,ie as mergeProps,G as preconnect,K as prefetchDNS,q as preinit,J as preinitModule,Y as preload,X as preloadModule,I as refTo,W as render,e as setAttribute,t as setAttributeNS,n as setBoolAttribute,Z as setSelectValue,o as setStyleProperty,Q as spread,te as startViewTransition,s as style,$ as template,L as use,R as useHead};
@@ -1,2 +1,2 @@
1
- import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{keepFocus as n,reconcileNodes as r}from"./internal/reconcile.js";import{onCleanup as i,useRenderEffect as a}from"@shadow-js/core";import{addCleanup as o,createComputation as s,currentOwner as c,disposeOwner as l,readComputation as u}from"@shadow-js/core/extend";const d=/* @__PURE__ */ new WeakMap;function f(e){return e instanceof Document?e:e.ownerDocument??document}function p(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function m(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function h(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}const g=/* @__PURE__ */ new WeakMap;function _(t,n){let r=[];for(let i of e(t,`SHADOW_INSERT_CYCLE`,n))if(i!=null&&typeof i!=`boolean`){if(i instanceof DocumentFragment){let e=g.get(i)??[...i.childNodes];g.set(i,e);for(let t of e)r.push(t)}else r.push(i instanceof Node?i:String(i))}return r}function v(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!p(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function y(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&p(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=v(e);let t=o.get(n)?.pop();t===void 0&&(t=f(e.parent).createTextNode(n),m(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function b(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}const x=/* @__PURE__ */ new WeakMap;function S(e,t){let n=x.get(e)??/* @__PURE__ */ new Set;x.set(e,n.add(t)),i(()=>{n.delete(t)})}function C(e,t){let n=y(e,t),i=e.parent,a=e.nodes.filter(e=>e.parentNode===i),o=a[0],s=b(e,a.at(-1));n.length===0&&o!==void 0&&(e.marker=o.previousSibling),r(i,a,n,s),e.nodes=n,h(e,n),x.get(i)?.forEach(e=>{e()})}function w(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&p(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=f(e.parent).createTextNode(r);m(e,t),e.parent.insertBefore(t,b(e,void 0)),e.nodes=[t];return}}C(e,_(t))}function T(e,t,n){let r=[];if(n!==void 0){let t=/* @__PURE__ */ new Set;for(let i of _(n))typeof i==`string`||t.has(i)||i.parentNode!==e||(t.add(i),r.push(i))}let i={parent:e,anchor:t,marker:r.length>0?r[0].previousSibling:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&m(i,e);return i}function E(e){let t=e.parent,n=d.get(t);e.owner=c(),d.set(t,e);let r=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||b(n,n.nodes.at(-1))!==r)return;let i=j(t,r);n.anchor=e.marker=i,n.owner&&o(n.owner,()=>i.remove())}function D(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop();for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function O(e,t,n){if(!D(t))return w(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&E(e),a(typeof t==`function`?t:()=>t,t=>{if(r=t,D(t)){let n=c(),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,o=e=>{i.add(e);let t=r.get(e);return t===void 0&&(t=s({kind:`memo`,fn:()=>e(),allowWrites:!0,owner:n}),r.set(e,t)),u(t)};a(()=>{i=/* @__PURE__ */ new Set;let e=_(t,o);for(let[e,t]of r)i.has(e)||(r.delete(e),l(t));return e},t=>{C(e,t)})}else w(e,t)}),r}function k(e,t,r){let i=e.nodes.filter(t=>t.parentNode===e.parent);n(e.parent,()=>{for(let e of i)r(e)}),e.parent=t,e.marker=i[0]?.previousSibling??t.lastChild}function A(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function j(e,t){let n=f(e).createTextNode(``);return e.insertBefore(n,t),n}function M(e,n,r,i){let a=r??null;return O(T(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{j as anchor,O as bindRegion,T as createRegion,M as insert,k as moveRegion,A as removeRegion,S as watchCommits};
1
+ import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{keepFocus as n,reconcileNodes as r}from"./internal/reconcile.js";import{onCleanup as i,useRenderEffect as a}from"@shadow-js/core";import{addCleanup as o,createComputation as s,currentOwner as c,disposeOwner as l,readComputation as u}from"@shadow-js/core/extend";const d=/* @__PURE__ */ new WeakMap;function f(e){return e instanceof Document?e:e.ownerDocument??document}function p(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function m(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function h(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}const g=/* @__PURE__ */ new WeakMap;function _(t,n){let r=[];for(let i of e(t,`SHADOW_INSERT_CYCLE`,n))if(i!=null&&typeof i!=`boolean`){if(i instanceof DocumentFragment){let e=g.get(i)??[...i.childNodes];g.set(i,e);for(let t of e)r.push(t)}else r.push(i instanceof Node?i:String(i))}return r}function v(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!p(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function y(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&p(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=v(e);let t=o.get(n)?.pop();t===void 0&&(t=f(e.parent).createTextNode(n),m(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function b(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}const x=/* @__PURE__ */ new WeakMap;function S(e,t){let n=x.get(e)??/* @__PURE__ */ new Set;x.set(e,n.add(t)),i(()=>{n.delete(t)})}function C(e,t){x.set(e,(x.get(e)??/* @__PURE__ */ new Set).add(t))}function w(e,t){let n=y(e,t),i=e.parent,a=e.nodes.filter(e=>e.parentNode===i),o=a[0],s=b(e,a.at(-1));n.length===0&&o!==void 0&&(e.marker=o.previousSibling),r(i,a,n,s),e.nodes=n,h(e,n),x.get(i)?.forEach(e=>{e()}),i.nodeName===`OPTGROUP`&&i.parentNode!==null&&x.get(i.parentNode)?.forEach(e=>{e()})}function T(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&p(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=f(e.parent).createTextNode(r);m(e,t),e.parent.insertBefore(t,b(e,void 0)),e.nodes=[t];return}}w(e,_(t))}function E(e,t,n){let r=[];if(n!==void 0){let t=/* @__PURE__ */ new Set;for(let i of _(n))typeof i==`string`||t.has(i)||i.parentNode!==e||(t.add(i),r.push(i))}let i={parent:e,anchor:t,marker:r.length>0?r[0].previousSibling:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&m(i,e);return i}function D(e){let t=e.parent,n=d.get(t);e.owner=c(),d.set(t,e);let r=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||b(n,n.nodes.at(-1))!==r)return;let i=M(t,r);n.anchor=e.marker=i,n.owner&&o(n.owner,()=>i.remove())}function O(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop();for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function k(e,t,n){if(!O(t))return T(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&D(e),a(typeof t==`function`?t:()=>t,t=>{if(r=t,O(t)){let n=c(),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,o=e=>{i.add(e);let t=r.get(e);return t===void 0&&(t=s({kind:`memo`,fn:()=>e(),allowWrites:!0,owner:n}),r.set(e,t)),u(t)};a(()=>{i=/* @__PURE__ */ new Set;let e=_(t,o);for(let[e,t]of r)i.has(e)||(r.delete(e),l(t));return e},t=>{w(e,t)})}else T(e,t)}),r}function A(e,t,r){let i=e.nodes.filter(t=>t.parentNode===e.parent);n(e.parent,()=>{for(let e of i)r(e)}),e.parent=t,e.marker=i[0]?.previousSibling??t.lastChild}function j(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function M(e,t){let n=f(e).createTextNode(``);return e.insertBefore(n,t),n}function N(e,n,r,i){let a=r??null;return k(E(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{M as anchor,k as bindRegion,E as createRegion,N as insert,C as keepWatchingCommits,A as moveRegion,j as removeRegion,S as watchCommits};
2
2
  //# sourceMappingURL=insert.js.map