@shadow-js/web 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +2 -3
- package/dist/dev/attributes.js +1 -5
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.js +15 -13
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +4 -4
- package/dist/dev/control-flow/no-hydration.js +1 -1
- package/dist/dev/control-flow/portal.js +1 -1
- package/dist/dev/element.js +10 -27
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +64 -80
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/extend.js +6 -6
- package/dist/dev/head/use-head.js +1 -1
- package/dist/dev/head/validate.js +1 -1
- package/dist/dev/hydration.js +21 -13
- package/dist/dev/hydration.js.map +1 -1
- package/dist/dev/index.d.ts +5 -5
- package/dist/dev/index.js +6 -6
- package/dist/dev/insert.js +50 -68
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +2 -1
- package/dist/dev/internal/reconcile.js +19 -2
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +2 -2
- package/dist/dev/jsx/html.d.ts +1 -1
- package/dist/dev/jsx/intrinsic.d.ts +1 -1
- package/dist/dev/jsx/mathml.d.ts +1 -1
- package/dist/dev/jsx/svg.d.ts +1 -1
- package/dist/dev/jsx-runtime.d.ts +3 -3
- package/dist/dev/render.js +22 -11
- package/dist/dev/render.js.map +1 -1
- package/dist/dev/server/class-style.js +1 -1
- package/dist/dev/server/element.js +3 -3
- package/dist/dev/server/form-controls.js +1 -1
- package/dist/dev/server/hydration-script.js +1 -1
- package/dist/dev/server/portals.js +1 -1
- package/dist/dev/server/raw-text.js +1 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/stream.js +3 -3
- package/dist/dev/spread.js +59 -84
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +3 -3
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/no-hydration.js +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/head/use-head.js +1 -1
- package/dist/prod/head/validate.js +1 -1
- package/dist/prod/hydration.js +1 -1
- package/dist/prod/hydration.js.map +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/render.js +1 -1
- package/dist/prod/render.js.map +1 -1
- package/dist/prod/server/class-style.js +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/hydration-script.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/raw-text.js +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/head/use-head.js +1 -1
- package/dist/server/head/validate.js +1 -1
- package/dist/server/hydration.js +1 -1
- package/dist/server/hydration.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/render.js +1 -1
- package/dist/server/render.js.map +1 -1
- package/dist/server/server/class-style.js +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/hydration-script.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/raw-text.js +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server-dev/attributes.js +1 -5
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +15 -13
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +1 -1
- package/dist/server-dev/control-flow/portal.js +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/element.js +1 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +64 -80
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/extend.js +6 -6
- package/dist/server-dev/head/use-head.js +1 -1
- package/dist/server-dev/head/validate.js +1 -1
- package/dist/server-dev/hydration.js +21 -13
- package/dist/server-dev/hydration.js.map +1 -1
- package/dist/server-dev/index.js +6 -6
- package/dist/server-dev/insert.js +50 -68
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +19 -2
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/render.js +22 -11
- package/dist/server-dev/render.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -1
- package/dist/server-dev/server/element.js +3 -3
- package/dist/server-dev/server/form-controls.js +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -1
- package/dist/server-dev/server/portals.js +1 -1
- package/dist/server-dev/server/raw-text.js +1 -1
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/stream.js +3 -3
- package/dist/server-dev/spread.js +59 -84
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +3 -3
- package/package.json +3 -3
|
@@ -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","
|
|
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,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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{
|
|
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};
|
package/dist/server/insert.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{reconcileNodes as
|
|
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};
|
|
2
2
|
//# sourceMappingURL=insert.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","reconcileRegion","attached","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","createCallCache","memos","touched","fn","createComputation","readComputation","disposeOwner","bindRegion","value","latest","ordered","useRenderEffect","cache","moveRegion","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n for (const node of attached) move(node);\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,qWA+CA,MAAMA,kB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,IAAA,GAAY+B,EAAO,QAAQ,WAAW9C,EAAQ6C,CAAc,EAAI9B,CAEvD,EAAGoB,EAAOU,IAAmB,IAAI,CAC1D,C"}
|
|
1
|
+
{"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":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=null&&n.activeElement!==r&&r.focus({preventScroll:!0})}function t(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function n(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t],a=0,o=r.length;for(;a<o;){let t=a+o>>1;e[r[t]]<n?a=t+1:o=t}i[t]=r[a-1]??-1,r[a]=t}let a=r.at(-1)??-1;for(;a!==-1;)n[e[a]-t]=1,a=i[a]}function r(e,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let n=c;n<l;n+=1)t(e,r[n]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let n=c;n<l;n+=1){let i=r[n],a=f.get(i);a===void 0?t(e,i):p.push(a)}if(p.length===0){for(let t of i.slice(c,u))e.insertBefore(t,d);return}let m=new Uint8Array(u-c);n(p,c,m);let h=typeof e.moveBefore==`function`,g=e.getRootNode(),_=h?null:g.activeElement,v=d;for(let t=u-1;t>=c;--t){let n=i[t];m[t-c]!==1&&(h&&n.parentNode===e?e.moveBefore(n,v):e.insertBefore(n,v)),v=n}_!=null&&g.activeElement!==_&&_.focus({preventScroll:!0})}export{e as keepFocus,r as reconcileNodes};
|
|
2
2
|
//# sourceMappingURL=reconcile.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":["removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":["keepFocus","root","at","active","run","removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":"AAYA,SAAgBA,EAAU,EAAU,EAAuB,CACzD,IAAMC,EAAOC,EAAG,YAAY,EACtBC,EAASF,EAAK,cACpBG,EAAI,EACAD,GAAU,MAAQF,EAAK,gBAAkBE,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,CAGA,SAASE,EAAW,EAAc,EAA8B,CAC1DC,IAAS,IAAA,IAAaA,EAAK,aAAeC,GAAQA,EAAO,YAAYD,CAAI,CAC/E,CAOA,SAASE,EAAsB,EAA2B,EAAgB,EAAyB,CAEjG,IAAMC,EAAkB,CAAC,EACnBC,EAAqBC,EAAO,QAAU,EAAE,EAC9C,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAME,EAAQF,EAAOC,GACjBE,EAAM,EACNC,EAAON,EAAM,OACjB,KAAOK,EAAMC,GAAM,CACjB,IAAMC,EAAUF,EAAMC,GAAS,EACjBJ,EAAOF,EAAMO,IACfH,EAAO,EAAMG,EAAS,EAC7B,EAAOA,CACd,CAEA,EAASJ,GAASH,EAAMK,EAAM,IAAM,GACpC,EAAMA,GAAOF,CACf,CACA,IAAIK,EAASR,EAAM,GAAG,EAAE,GAAK,GAC7B,KAAOQ,IAAW,IAChB,EAAON,EAAOM,GAAqBC,GAAU,EAC7C,EAASR,EAASO,EAEtB,CAuCA,SAAgBE,EACd,EACA,EACA,EACA,EACM,CACN,IAAMC,EAAaC,EAAK,OAClBC,EAAaC,EAAK,OAEpBC,EAAO,EACX,KAAOA,EAAOJ,GAAcI,EAAOF,GAAcD,EAAKG,KAAUD,EAAKC,IAAO,GAAQ,EACpF,IAAIC,EAAWL,EACXM,EAAWJ,EACf,KAAOG,EAAWD,GAAQE,EAAWF,GAAQH,EAAKI,EAAW,KAAOF,EAAKG,EAAW,IAClF,IACA,I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H,GAAU,MAAQF,EAAK,gBAAkBE,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,C"}
|
package/dist/server/render.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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{claims as i}from"./internal/hydration-hooks.js";import{withScope as a}from"./internal/hydration-scope.js";import{batch as o,createRoot as s,flushSync as c,untrack as l}from"@shadow-js/core";function u(u,d,f){let p=n(d,null,void 0),m,h=!1,g=()=>{h||(h=!0,m?.(),r(p))};try{i.current.withoutClaiming(()=>a(null,()=>o(()=>s(n=>{m=n,f!==void 0&&e(f),t(p,l(u))})))),c()}catch(e){try{g()}catch(t){throw AggregateError([e,t],`SHADOW_RENDER_ERRORS`)}throw e}return g}export{u as render};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","claims","withScope","batch","createRoot","options","attachRootErrors","bindRegion","untrack","code","
|
|
1
|
+
{"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","disposed","teardown","removeRegion","claims","withScope","batch","createRoot","dispose","options","attachRootErrors","bindRegion","untrack","code","flushSync","error","cleanupError"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\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 // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n try {\n claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n stop = dispose;\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n }),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a render that throws (an effect of the first flush failed),\n // so the root must not stay alive with its DOM and effects.\n try {\n teardown();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"render() failed and so did its teardown.\" : \"SHADOW_RENDER_ERRORS\",\n );\n }\n throw error;\n }\n return teardown;\n}\n"],"mappings":"A,mVAsCA,SAAgBA,EACd,EACA,EACA,EACY,CACZ,IAAMC,EAASC,EAAaC,EAAW,KAAM,IAAA,EAAS,EAClDC,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaN,CAAM,EACrB,EAKA,GAAI,CACFO,EAAO,QAAQ,oBACbC,EAAU,SACRC,MACEC,EAAY,GAAY,CACtB,EAAOC,EAEHC,IAAY,IAAA,IAAWC,EAAiBD,CAAO,EAEnDE,EAAWd,EAAQe,EAAQC,CAAI,CAAC,CAClC,CAAC,CACH,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFb,EAAS,CACX,OAASc,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACmC,sBACzD,CACF,CACA,MAAMD,CACR,CACA,OAAOb,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{
|
|
1
|
+
import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{escapeHtml as n,resolveValue as r}from"./escape.js";import{isSsrNode as i}from"./node.js";const a=/^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;function o(e,n){let i=[[e]],a=[0],o=/* @__PURE__ */ new Set;for(;i.length>0;){let e=i.length-1,s=i[e],c=a[e]??0;if(s===void 0||c>=s.length){let e=i.pop();e!==void 0&&o.delete(e),a.pop();continue}a[e]=c+1;let l=r(s[c]);if(Array.isArray(l)){if(o.has(l))throw TypeError(`A class array contains itself.`);o.add(l),i.push(l),a.push(0)}else if(typeof l==`string`)l!==``&&n.push(l);else if(typeof l==`number`)l!==0&&!Number.isNaN(l)&&n.push(String(l));else if(typeof l==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a class name.`);else if(typeof l==`object`&&l){let e=l;for(let t of Object.keys(e))t!==``&&r(e[t])&&n.push(t)}}}function s(e){let t=r(e);if(typeof t==`string`)return t;if(t==null||t===!1)return``;let n=[];return o(t,n),n.join(` `)}function c(e){let t=s(e);return t===``?``:` class="${n(t)}"`}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(e){let t=``,n=0,r=!1;for(let i of e)if(r)r=!1;else if(i===`\\`)r=!0;else if(t!==``)i===t&&(t=``);else if(i===`"`||i===`'`)t=i;else if(i===`(`)n+=1;else if(i===`)`)n=Math.max(0,n-1);else if((i===`;`||i===`{`||i===`}`)&&n===0)return!1;return t===``&&n===0&&!r}function d(n,o){let s=r(n);if(s!=null&&s!==!1){if(typeof s==`string`)s!==``&&o.push(s);else{if(typeof s!=`object`||i(s))throw t(`UNRECOGNIZED_INSERT_VALUE`,`A style must be a string, an object or an array of them.`);if(Array.isArray(s))for(let e of s){let t=r(e);if(Array.isArray(t))throw TypeError(`ssrStyle(): a style array may not contain another array.`);d(t,o)}else for(let n of Object.keys(s)){let i=l(n);if(!a.test(i))throw t(`INVALID_STYLE_PROPERTY`,`"${n}" is not a valid CSS property name.`);let c=r(Reflect.get(s,n));if(c==null||c===!1)continue;if(typeof c==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a style value.`);let d=e(i,c);u(d)&&o.push(`${i}:${d}`)}}}}function f(e){let t=[];return d(e,t),t.join(`;`)}function p(e){let t=f(e);return t===``?``:` style="${n(t)}"`}export{s as classText,o as collectClasses,u as isSafeCssValue,c as ssrClass,p as ssrStyle,f as styleText,l as toCssProperty};
|
|
2
2
|
//# sourceMappingURL=class-style.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{
|
|
1
|
+
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{isEventName as i,ssrAttribute as a}from"./attributes.js";import{classText as o,ssrStyle as s,styleText as c}from"./class-style.js";import{invalid as l}from"./errors.js";import{escape as u,escapeHtml as d,resolveValue as f}from"./escape.js";import{keepLeadingNewline as p,markSelectedOptions as m,textareaContent as h}from"./form-controls.js";import{SsrNode as g,isSsrNode as _}from"./node.js";import{rawElementContent as v}from"./raw-text.js";const y=/^[A-Za-z][A-Za-z0-9-]*$/,b=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function S(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function C(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(_(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new g(n)}function w(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new g(e)}function T(){let t=e();return t===void 0?``:` data-hk="${d(t)}"`}function E(e,_,C=void 0,w=!1,E=!1){if(typeof e!=`string`||!y.test(e))throw l(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let A=e.toLowerCase(),j=A===`select`,M=A===`textarea`,N={},P=!1,F=!1,I=w?T():``,L=[],R=``,z;if(typeof _==`object`&&_)for(let e of Object.keys(_)){if(x.has(e)||t.test(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||i(e)||w&&e===`data-hk`)continue;let s=f(Reflect.get(_,e));if(e===`class`||e===`className`){let e=o(s);e!==``&&L.push(e)}else if(e===`classList`)O(s,L);else if(e===`style`)R=c(s);else if(e===`innerHTML`)z=k(s);else if(e===`dangerouslySetInnerHTML`)z=k(f(S(s)));else if((j||M)&&e===`value`)N.value=s,P=!0;else if((j||M)&&e===`defaultValue`)N.fallback=s,F=!0;else if(e.startsWith(`attr:`))I+=a(e.slice(5),s);else if(e.startsWith(`bool:`))I+=a(e.slice(5),s,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(_,t)||(I+=a(t,s,t===`checked`))}else{let t=n(e,E);I+=a(t,s,r(t,s))}}if(L.length>0&&(I+=` class="${d(L.join(` `))}"`),R!==``&&(I+=s(R)),b.has(A))return new g(`<${e}${I}>`);let B=!E&&(A===`script`||A===`style`),V=C===void 0?D(_):C,H=z===void 0?B?v(A,V):u(V):z;if(z===void 0&&(P||F)){let e=P?N.value:N.fallback;H=M?h(e):m(e,H)}else(M||A===`pre`||A===`listing`)&&z===void 0&&(H=p(H));return new g(`<${e}${I}>${H}</${e}>`)}function D(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function O(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&f(Reflect.get(e,n))&&t.push(n)}function k(e){if(e==null)return``;if(_(e))return e.t;if(typeof e==`symbol`)throw l(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{C as ssr,E as ssrElement,T as ssrHydrationKey,w as ssrRaw};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{
|
|
2
|
-
`||t===`\r`?`\n${e}`:e}function c(e){return new
|
|
1
|
+
import{invalid as e}from"./errors.js";import{escape as t,escapeHtml as n,resolveValue as r}from"./escape.js";import{SsrNode as i}from"./node.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){return s(n(a(r(e))))}function s(e){let t=e.charAt(0);return t===`
|
|
2
|
+
`||t===`\r`?`\n${e}`:e}function c(e){return new i(o(e))}function l(e){let t=r(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=r(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const u=/[ \t\n\f\r]+/g,d=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,f={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},p=/<!--[\s\S]*?-->|<[^>]*>/g;function m(e){return e.replace(d,(e,t,n,r)=>{if(r!==void 0)return f[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function h(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function g(e,t,n){n.lastIndex=t;let r=n.exec(e);return m(e.slice(t,r===null?e.length:r.index).replace(p,``)).replace(u,` `).trim()}function _(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=h(e,l);if(u===-1)break;let d=e.slice(l,u),f,p=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(p=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=m(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??g(e,u+1,s));if(v&&(a=!0),v&&p===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&p!==-1&&(n+=e.slice(r,l+p),r=l+_);i=u}return r===0?e:n+e.slice(r)}function v(e,n){return new i(y(e,t(n)))}function y(e,t){return _(t,l(e))}export{s as keepLeadingNewline,y as markSelectedOptions,v as ssrSelectValue,c as ssrTextArea,o as textareaContent};
|
|
3
3
|
//# sourceMappingURL=form-controls.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{DEFAULT_EARLY_EVENTS as e,captureScriptBody as t}from"../internal/early-events.js";import{ssrRaw as n}from"./element.js";const r=/^[A-Za-z0-9+/=_-]+$/;function i(n={}){let i=n.nonce,a=i!==void 0&&r.test(i)?` nonce="${i}"`:``,o=n.eventNames??e;return`<script${a}>${t(o)}<\/script>`}function a(e={}){return n(i(e))}export{a as HydrationScript,i as generateHydrationScript};
|
|
2
2
|
//# sourceMappingURL=hydration-script.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{
|
|
1
|
+
import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{PortalContext as n}from"../internal/portal-context.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new r(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,r,a){if(a===null||n===void 0)return;let o=t(e(n),()=>i(r()));a.add(n,o)}function u(e,t){return n({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
|
|
2
2
|
//# sourceMappingURL=portals.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{
|
|
1
|
+
import{invalid as e}from"./errors.js";import{render as t,resolveValue as n}from"./escape.js";import{SsrNode as r,isSsrNode as i}from"./node.js";const a=/* @__PURE__ */ new Set([`script`,`style`,`title`,`textarea`]);function o(e){return a.has(e.toLowerCase())}const s=/* @__PURE__ */ new Set([`script`,`style`]),c={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function l(e,t){return t.replace(c[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function u(e,n){return l(e.toLowerCase()===`script`?`script`:`style`,t(n,e=>e))}function d(e,t){let r=n(t);return i(r)?r.t:u(e,r)}function f(t,n){if(typeof t!=`string`||!s.has(t.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new r(u(t,n))}export{o as isTextOnlyElement,d as rawElementContent,u as rawTextContent,f as ssrRawText};
|
|
2
2
|
//# sourceMappingURL=raw-text.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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{MAX_TIMER_MS as a,SsrError as o}from"./errors.js";import{escape as s}from"./escape.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(r,a,o,c,d,f){return e(f),l(d,()=>u({value:o,get children(){return t(c,()=>i(n(a),()=>s(r())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,t,n,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let t=r(e);return s.add(t),t},read:e=>n.has(e)?{value:n.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(n=>(i?.clear(),a?.clear(),{html:h(e,t,p,i,a,u),requested:s,tracked:c,errors:l,dispose:n}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new o(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,i,a,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,i,a,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new o(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:r,maxPasses:i}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new o(`SSR_TIMEOUT`,`The render did not finish within ${r} ms.`))},Math.min(r,a))});try{let r=c(t?.portals);return await Promise.race([S(e,n,i,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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
|
package/dist/server/spread.js
CHANGED
|
@@ -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{
|
|
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)}M(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,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};
|
|
2
2
|
//# sourceMappingURL=spread.js.map
|