@shadow-js/web 1.0.4 → 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 +8 -0
- package/README.md +1 -1
- package/dist/dev/class-style.js +6 -1
- 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 +2 -2
- 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/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 +12 -4
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +3 -3
- 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/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/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/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/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/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/class-style.js +6 -1
- 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/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/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 +12 -4
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +3 -3
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { createRootScope, resourceKey, withScope } from "./internal/hydration-scope.js";
|
|
2
|
-
import { beginClaiming, claimElement, claimPortal, endClaiming, isClaiming, liftedRegions, releaseUnclaimedPortals, takeRegion, withoutClaiming } from "./internal/claim.js";
|
|
3
|
-
import { claims } from "./internal/hydration-hooks.js";
|
|
4
|
-
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
5
1
|
import { attachRootErrors } from "./control-flow/root-errors.js";
|
|
2
|
+
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
3
|
+
import { beginClaiming, claimElement, claimPortal, endClaiming, isClaiming, liftedRegions, releaseUnclaimedPortals, takeRegion, withoutClaiming } from "./internal/claim.js";
|
|
6
4
|
import { replayEarlyEvents } from "./internal/early-events.js";
|
|
5
|
+
import { claims } from "./internal/hydration-hooks.js";
|
|
6
|
+
import { createRootScope, resourceKey, withScope } from "./internal/hydration-scope.js";
|
|
7
7
|
import { ResourceCacheContext, batch, createRoot, flushSync, runWithOwner, untrack } from "@shadow-js/core";
|
|
8
8
|
import { withHydration } from "@shadow-js/core/extend";
|
|
9
9
|
// src/hydration.ts
|
|
@@ -87,8 +87,16 @@ function hydrate(code, container, options = {}) {
|
|
|
87
87
|
const cache = dataCache(options.data ?? {});
|
|
88
88
|
const region = createRegion(container, null, Array.from(container.childNodes));
|
|
89
89
|
let stop;
|
|
90
|
+
let disposed = false;
|
|
91
|
+
const teardown = () => {
|
|
92
|
+
if (disposed) return;
|
|
93
|
+
disposed = true;
|
|
94
|
+
stop?.();
|
|
95
|
+
removeRegion(region);
|
|
96
|
+
};
|
|
90
97
|
try {
|
|
91
|
-
|
|
98
|
+
withHydration(() => batch(() => withScope(createRootScope(options.renderId), () => runWithOwner(options.owner ?? null, () => createRoot((dispose) => {
|
|
99
|
+
stop = dispose;
|
|
92
100
|
attachRootErrors(options);
|
|
93
101
|
ResourceCacheContext({
|
|
94
102
|
value: cache,
|
|
@@ -97,22 +105,22 @@ function hydrate(code, container, options = {}) {
|
|
|
97
105
|
return null;
|
|
98
106
|
}
|
|
99
107
|
});
|
|
100
|
-
return dispose;
|
|
101
108
|
})))));
|
|
102
109
|
flushSync();
|
|
110
|
+
} catch (error) {
|
|
111
|
+
try {
|
|
112
|
+
stop?.();
|
|
113
|
+
} catch (cleanupError) {
|
|
114
|
+
throw new AggregateError([error, cleanupError], "hydrate() failed and so did its teardown.");
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
103
117
|
} finally {
|
|
104
118
|
endClaiming();
|
|
105
119
|
claims.current = previousClaims;
|
|
106
120
|
}
|
|
107
121
|
replayEarlyEvents();
|
|
108
122
|
stripLeftovers(container);
|
|
109
|
-
|
|
110
|
-
return () => {
|
|
111
|
-
if (disposed) return;
|
|
112
|
-
disposed = true;
|
|
113
|
-
stop();
|
|
114
|
-
removeRegion(region);
|
|
115
|
-
};
|
|
123
|
+
return teardown;
|
|
116
124
|
}
|
|
117
125
|
export { hydrate };
|
|
118
126
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration.js","names":[],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: () => void;\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n
|
|
1
|
+
{"version":3,"file":"hydration.js","names":[],"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":";;;;;;;;;AAsDA,SAAS,UAAU,MAA8C;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO;EACL,KAAK;EACL,KAAK,KAAK;GACR,IAAI,KAAK,IAAI,GAAG,KAAK,CAAC,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAA;GACvD,KAAK,IAAI,GAAG;GACZ,OAAO,EAAE,OAAO,KAAK,KAAK;EAC5B;EACA,QAAQ,CAER;CACF;AACF;;;;;AAMA,SAAS,eAAe,WAAuB;CAC7C,MAAM,MAAM,qBAAqB,WAAW,YAAY,UAAU;CAClE,IAAI,QAAQ,MAAM;CAClB,IAAI,IAAI,SAAS,MAAM,wBAAwB,IAAI,IAAI;CACvD,MAAM,SAAS,IAAI,iBAAiB,WAAW,WAAW,YAAY;CACtE,MAAM,QAAmB,CAAC;CAC1B,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,UAAU,OAAO;EACvB,IAAI,QAAQ,SAAS,OAAO,QAAQ,SAAS,KAAK,MAAM,KAAK,OAAO;CACtE;CACA,KAAK,MAAM,WAAW,OAAO,QAAQ,OAAO;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,QACd,MACA,WACA,UAA0B,CAAC,GACf;CACZ,IAAI,WAAW,GACb,MAAM,IAAI,MACE,iDACZ;CACF,MAAM,2BAAW,IAAI,IAAqB;CAC1C,MAAM,QAAmB,qBAAqB,UAAU,CAAC,SAAS,IAAI,CAAC;CACvE,KAAK,MAAM,WAAW,CAAC,GAAG,OAAO,GAAG,MAAM,KAAK,UAAU,iBAAiB,WAAW,CAAC,CAAC,GAAG;EACxF,MAAM,MAAM,QAAQ,aAAa,SAAS;EAC1C,IAAI,QAAQ,MAAM,SAAS,IAAI,KAAK,OAAO;CAC7C;CACA,cAAc,UAAU,QAAQ,kBAAkB;CAElD,MAAM,aAAqB;EACzB;EACA;EACA;EACA;EACA;EACA;CACF;CACA,MAAM,iBAAiB,OAAO;CAC9B,OAAO,UAAU;CACjB,MAAM,QAAQ,UAAU,QAAQ,QAAQ,CAAC,CAAC;CAC1C,MAAM,SAAS,aAAa,WAAW,MAAM,MAAM,KAAK,UAAU,UAAU,CAAC;CAC7E,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,iBAAuB;EAC3B,IAAI,UAAU;EACd,WAAW;EACX,OAAO;EACP,aAAa,MAAM;CACrB;CACA,IAAI;EAMF,oBACE,YACE,UAAU,gBAAgB,QAAQ,QAAQ,SACxC,aAAa,QAAQ,SAAS,YAC5B,YAAY,YAAY;GACtB,OAAO;GACP,iBAAiB,OAAO;GACxB,qBAAqB;IACnB,OAAO;IACP,IAAI,WAAW;KACb,WAAW,QAAQ,QAAQ,IAAI,CAAC;KAChC,OAAO;IACT;GACF,CAAC;EACH,CAAC,CACH,CACF,CACF,CACF;EACA,UAAU;CACZ,SAAS,OAAO;EAGd,IAAI;GACF,OAAO;EACT,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,OAAO,YAAY,GACV,2CACZ;EACF;EACA,MAAM;CACR,UAAU;EACR,YAAY;EACZ,OAAO,UAAU;CACnB;CACA,kBAAkB;CAClB,eAAe,SAAS;CACxB,OAAO;AACT"}
|
package/dist/server-dev/index.js
CHANGED
|
@@ -5,11 +5,11 @@ import { createComponent } from "./component.js";
|
|
|
5
5
|
import { Activity } from "./control-flow/activity.js";
|
|
6
6
|
import { Show } from "./control-flow/show.js";
|
|
7
7
|
import { ClientOnly } from "./control-flow/client-only.js";
|
|
8
|
-
import {
|
|
8
|
+
import { derived } from "./derived.js";
|
|
9
9
|
import { element } from "./element.js";
|
|
10
10
|
import { addEventListener, chainEvents, clearDelegatedEvents, delegateEvents } from "./events.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
11
|
+
import { hydrate } from "./hydration.js";
|
|
12
|
+
import { anchor, insert } from "./insert.js";
|
|
13
13
|
import { Dynamic, createDynamic } from "./control-flow/dynamic.js";
|
|
14
14
|
import { ErrorBoundary } from "./control-flow/error-boundary.js";
|
|
15
15
|
import { For } from "./control-flow/for.js";
|
|
@@ -21,13 +21,13 @@ import { Portal } from "./control-flow/portal.js";
|
|
|
21
21
|
import { SuspenseList } from "./control-flow/suspense-list.js";
|
|
22
22
|
import { Suspense } from "./control-flow/suspense.js";
|
|
23
23
|
import { Match, Switch } from "./control-flow/switch.js";
|
|
24
|
-
import {
|
|
24
|
+
import { effect, memo, refTo, use } from "./reactive.js";
|
|
25
25
|
import { useHead } from "./head/use-head.js";
|
|
26
26
|
import { Base, Link, Meta, Style, Title } from "./head/components.js";
|
|
27
|
-
import { hydrate } from "./hydration.js";
|
|
28
|
-
import { effect, memo, refTo, use } from "./reactive.js";
|
|
29
27
|
import { render } from "./render.js";
|
|
30
28
|
import { preconnect, prefetchDNS, preinit, preinitModule, preload, preloadModule } from "./resource-hints.js";
|
|
29
|
+
import { setSelectValue } from "./select-value.js";
|
|
30
|
+
import { spread } from "./spread.js";
|
|
31
31
|
import { template } from "./template.js";
|
|
32
32
|
import { ViewTransition, startViewTransition } from "./view-transition.js";
|
|
33
33
|
import { isDev, isServer, mergeProps } from "@shadow-js/core";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { withScope } from "./internal/hydration-scope.js";
|
|
2
|
-
import { claims } from "./internal/hydration-hooks.js";
|
|
3
|
-
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
4
1
|
import { attachRootErrors } from "./control-flow/root-errors.js";
|
|
2
|
+
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
3
|
+
import { claims } from "./internal/hydration-hooks.js";
|
|
4
|
+
import { withScope } from "./internal/hydration-scope.js";
|
|
5
5
|
import { batch, createRoot, flushSync, untrack } from "@shadow-js/core";
|
|
6
6
|
// src/render.ts
|
|
7
7
|
/**
|
|
@@ -32,19 +32,30 @@ import { batch, createRoot, flushSync, untrack } from "@shadow-js/core";
|
|
|
32
32
|
*/
|
|
33
33
|
function render(code, container, options) {
|
|
34
34
|
const region = createRegion(container, null, void 0);
|
|
35
|
-
|
|
36
|
-
if (options !== void 0) attachRootErrors(options);
|
|
37
|
-
bindRegion(region, untrack(code));
|
|
38
|
-
return dispose;
|
|
39
|
-
}))));
|
|
40
|
-
flushSync();
|
|
35
|
+
let stop;
|
|
41
36
|
let disposed = false;
|
|
42
|
-
|
|
37
|
+
const teardown = () => {
|
|
43
38
|
if (disposed) return;
|
|
44
39
|
disposed = true;
|
|
45
|
-
stop();
|
|
40
|
+
stop?.();
|
|
46
41
|
removeRegion(region);
|
|
47
42
|
};
|
|
43
|
+
try {
|
|
44
|
+
claims.current.withoutClaiming(() => withScope(null, () => batch(() => createRoot((dispose) => {
|
|
45
|
+
stop = dispose;
|
|
46
|
+
if (options !== void 0) attachRootErrors(options);
|
|
47
|
+
bindRegion(region, untrack(code));
|
|
48
|
+
}))));
|
|
49
|
+
flushSync();
|
|
50
|
+
} catch (error) {
|
|
51
|
+
try {
|
|
52
|
+
teardown();
|
|
53
|
+
} catch (cleanupError) {
|
|
54
|
+
throw new AggregateError([error, cleanupError], "render() failed and so did its teardown.");
|
|
55
|
+
}
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
return teardown;
|
|
48
59
|
}
|
|
49
60
|
export { render };
|
|
50
61
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":[],"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 // 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
|
|
1
|
+
{"version":3,"file":"render.js","names":[],"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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,OACd,MACA,WACA,SACY;CACZ,MAAM,SAAS,aAAa,WAAW,MAAM,KAAA,CAAS;CACtD,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,iBAAuB;EAC3B,IAAI,UAAU;EACd,WAAW;EACX,OAAO;EACP,aAAa,MAAM;CACrB;CAKA,IAAI;EACF,OAAO,QAAQ,sBACb,UAAU,YACR,YACE,YAAY,YAAY;GACtB,OAAO;GAEP,IAAI,YAAY,KAAA,GAAW,iBAAiB,OAAO;GAEnD,WAAW,QAAQ,QAAQ,IAAI,CAAC;EAClC,CAAC,CACH,CACF,CACF;EACA,UAAU;CACZ,SAAS,OAAO;EAGd,IAAI;GACF,SAAS;EACX,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,OAAO,YAAY,GACV,0CACZ;EACF;EACA,MAAM;CACR;CACA,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { cssValueText } from "../internal/css-units.js";
|
|
2
2
|
import { invalid } from "./errors.js";
|
|
3
|
-
import { isSsrNode } from "./node.js";
|
|
4
3
|
import { escapeHtml, resolveValue } from "./escape.js";
|
|
4
|
+
import { isSsrNode } from "./node.js";
|
|
5
5
|
// src/server/class-style.ts
|
|
6
6
|
/** A CSS property name: a custom property, or a lower-case name with an optional vendor dash. */
|
|
7
7
|
const CSS_PROPERTY = /^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { nextKey } from "../internal/hydration-scope.js";
|
|
2
2
|
import { IGNORED_KEYS, attributeName, isFlagAttribute } from "../internal/react-names.js";
|
|
3
|
-
import { invalid } from "./errors.js";
|
|
4
|
-
import { SsrNode, isSsrNode } from "./node.js";
|
|
5
|
-
import { escape, escapeHtml, resolveValue } from "./escape.js";
|
|
6
3
|
import { isEventName, ssrAttribute } from "./attributes.js";
|
|
7
4
|
import { classText, ssrStyle, styleText } from "./class-style.js";
|
|
5
|
+
import { invalid } from "./errors.js";
|
|
6
|
+
import { escape, escapeHtml, resolveValue } from "./escape.js";
|
|
8
7
|
import { keepLeadingNewline, markSelectedOptions, textareaContent } from "./form-controls.js";
|
|
8
|
+
import { SsrNode, isSsrNode } from "./node.js";
|
|
9
9
|
import { rawElementContent } from "./raw-text.js";
|
|
10
10
|
// src/server/element.ts
|
|
11
11
|
/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { invalid } from "./errors.js";
|
|
2
|
-
import { SsrNode } from "./node.js";
|
|
3
2
|
import { escape, escapeHtml, resolveValue } from "./escape.js";
|
|
3
|
+
import { SsrNode } from "./node.js";
|
|
4
4
|
// src/server/form-controls.ts
|
|
5
5
|
/**
|
|
6
6
|
* Server markup for the controls whose state is not an attribute. A browser ignores `value` on a
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { childScope, withScope } from "../internal/hydration-scope.js";
|
|
2
|
+
import { PortalContext } from "../internal/portal-context.js";
|
|
2
3
|
import { SsrError } from "./errors.js";
|
|
3
4
|
import { escape } from "./escape.js";
|
|
4
|
-
import { PortalContext } from "../internal/portal-context.js";
|
|
5
5
|
/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */
|
|
6
6
|
var PortalCollector = class {
|
|
7
7
|
entries = /* @__PURE__ */ new Map();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { invalid } from "./errors.js";
|
|
2
|
-
import { SsrNode, isSsrNode } from "./node.js";
|
|
3
2
|
import { render, resolveValue } from "./escape.js";
|
|
3
|
+
import { SsrNode, isSsrNode } from "./node.js";
|
|
4
4
|
// src/server/raw-text.ts
|
|
5
5
|
/**
|
|
6
6
|
* Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
2
|
+
import { runWithServerHead } from "../head/server-head.js";
|
|
1
3
|
import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
|
|
2
4
|
import { MAX_TIMER_MS, SsrError } from "./errors.js";
|
|
3
5
|
import { escape } from "./escape.js";
|
|
4
|
-
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
5
|
-
import { runWithServerHead } from "../head/server-head.js";
|
|
6
6
|
import { portalCollectorFor, withPortalSink } from "./portals.js";
|
|
7
7
|
import { ResourceCacheContext, createRoot } from "@shadow-js/core";
|
|
8
8
|
// src/server/render.ts
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
2
|
+
import { runWithServerHead } from "../head/server-head.js";
|
|
1
3
|
import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
|
|
4
|
+
import { StreamContext } from "../internal/stream-context.js";
|
|
2
5
|
import { MAX_TIMER_MS, SsrError } from "./errors.js";
|
|
3
6
|
import { escape } from "./escape.js";
|
|
4
|
-
import { StreamContext } from "../internal/stream-context.js";
|
|
5
|
-
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
6
|
-
import { runWithServerHead } from "../head/server-head.js";
|
|
7
7
|
import { portalCollectorFor, withPortalSink } from "./portals.js";
|
|
8
8
|
import { serialize } from "./serialize.js";
|
|
9
9
|
import { ResourceCacheContext, createRoot, untrack } from "@shadow-js/core";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { setAttribute, setAttributeNS, setBoolAttribute } from "./attributes.js";
|
|
2
2
|
import { autoFocus } from "./autofocus.js";
|
|
3
3
|
import { applyClass, asRecord, classList, style } from "./class-style.js";
|
|
4
|
-
import {
|
|
4
|
+
import { bindEvent } from "./events.js";
|
|
5
5
|
import { bindRegion, createRegion, watchCommits } from "./insert.js";
|
|
6
|
+
import { claims } from "./internal/hydration-hooks.js";
|
|
6
7
|
import { IGNORED_KEYS, attributeName, eventPlan, isFlagAttribute } from "./internal/react-names.js";
|
|
7
|
-
import { bindEvent } from "./events.js";
|
|
8
8
|
import { plainText, setSelectValue } from "./select-value.js";
|
|
9
9
|
import { onCleanup, untrack, useRenderEffect } from "@shadow-js/core";
|
|
10
10
|
// src/spread.ts
|
|
@@ -73,7 +73,7 @@ function applyKey(el, key, value, state, svg) {
|
|
|
73
73
|
setSelectValue(el, value);
|
|
74
74
|
return;
|
|
75
75
|
}
|
|
76
|
-
if (!svg && LIVE_PROPERTIES.test(key) && key in el) {
|
|
76
|
+
if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {
|
|
77
77
|
liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.test(key) ? value ?? "" : Boolean(value));
|
|
78
78
|
if (key === "value" && el instanceof HTMLInputElement) el.defaultValue = plainText(value);
|
|
79
79
|
return;
|
|
@@ -93,11 +93,19 @@ const LIVE_PROPERTIES = /^(?:value|checked|selected|muted|indeterminate|defaultV
|
|
|
93
93
|
/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */
|
|
94
94
|
const STRING_PROPERTIES = /^(?:value|defaultValue)$/;
|
|
95
95
|
/**
|
|
96
|
+
* True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and
|
|
97
|
+
* writes `value="0"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as
|
|
98
|
+
* an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.
|
|
99
|
+
*/
|
|
100
|
+
function isMeasure(el, key) {
|
|
101
|
+
return key === "value" && (el.localName === "progress" || el.localName === "meter" || el.localName === "li");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
96
104
|
* True when a live property (typed value, toggled box) no longer matches the value last applied, so
|
|
97
105
|
* an unchanged prop is written again and the element follows the data.
|
|
98
106
|
*/
|
|
99
107
|
function liveDiffers(el, key, value, svg) {
|
|
100
|
-
if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;
|
|
108
|
+
if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;
|
|
101
109
|
if (key === "value" && el instanceof HTMLSelectElement) return true;
|
|
102
110
|
const live = Reflect.get(el, key);
|
|
103
111
|
return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,MAAM,kBAAkB;;AAexB,SAAS,cAAc,OAA0B;CAC/C,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GAAW;CAC3B,MAAM,QAAQ,KAAA;CACd,QAAQ,OAAO;AACjB;;AAGA,SAAS,SACP,IACA,KACA,OACA,OACA,KACM;CACN,IAAI,QAAQ,OAAO;EAEjB,cAAc,KAAK;EACnB,IAAI,OAAO,UAAU,YAAY;GAC/B,MAAM,UAAU;GAChB,MAAM,UAAU,cAAc,QAAQ,EAAE,CAAC;GACzC,IAAI,OAAO,YAAY,YAAY,MAAM,QAAQ;EACnD;EACA;CACF;CACA,IAAI,QAAQ,aAAa;EACvB,IAAI,CAAC,MAAM,SAAS;GAClB,MAAM,UAAU;GAChB,UAAU,IAAI,KAAK;EACrB;EACA;CACF;CACA,IAAI,QAAQ,WAAW,QAAQ,aAAa;EAC1C,WAAW,IAAI,OAAO,GAAG;EACzB;CACF;CACA,IAAI,QAAQ,SAAS;EACnB,MAAM,SAAS,MAAM,IAAgC,OAAO,MAAM,MAAM;EACxE;CACF;CACA,IAAI,QAAQ,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,IAAI,IAAY;EAChC,KAAK,MAAM,CAAC,KAAK,UAAU,SAAS;GAClC,QAAQ,IAAI,GAAG;GACf,IACE,MAAM,OAAO,IAAI,GAAG,KACpB,OAAO,GAAG,MAAM,OAAO,IAAI,GAAG,GAAG,KAAK,KACtC,CAAC,YAAY,IAAI,KAAK,OAAO,KAAK,GAElC;GACF,MAAM,OAAO,IAAI,KAAK,KAAK;GAC3B,SAAS,IAAI,KAAK,OAAO,OAAO,KAAK;EACvC;EACA,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,KAAK,CAAC,GAAG;GAC1C,IAAI,QAAQ,IAAI,GAAG,GAAG;GACtB,MAAM,OAAO,OAAO,GAAG;GAGvB,SAAS,IAAI,KAAK,KAAA,GAAW,OAAO,KAAK;EAC3C;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and\n * writes `value=\"0\"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as\n * an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.\n */\nfunction isMeasure(el: Element, key: string): boolean {\n // The tag, not `instanceof`: a class of this window is not the class of an iframe's element, and a minimal DOM may\n // not define `HTMLMeterElement` at all.\n return (\n key === \"value\" &&\n (el.localName === \"progress\" || el.localName === \"meter\" || el.localName === \"li\")\n );\n}\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,MAAM,kBAAkB;;AAexB,SAAS,cAAc,OAA0B;CAC/C,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GAAW;CAC3B,MAAM,QAAQ,KAAA;CACd,QAAQ,OAAO;AACjB;;AAGA,SAAS,SACP,IACA,KACA,OACA,OACA,KACM;CACN,IAAI,QAAQ,OAAO;EAEjB,cAAc,KAAK;EACnB,IAAI,OAAO,UAAU,YAAY;GAC/B,MAAM,UAAU;GAChB,MAAM,UAAU,cAAc,QAAQ,EAAE,CAAC;GACzC,IAAI,OAAO,YAAY,YAAY,MAAM,QAAQ;EACnD;EACA;CACF;CACA,IAAI,QAAQ,aAAa;EACvB,IAAI,CAAC,MAAM,SAAS;GAClB,MAAM,UAAU;GAChB,UAAU,IAAI,KAAK;EACrB;EACA;CACF;CACA,IAAI,QAAQ,WAAW,QAAQ,aAAa;EAC1C,WAAW,IAAI,OAAO,GAAG;EACzB;CACF;CACA,IAAI,QAAQ,SAAS;EACnB,MAAM,SAAS,MAAM,IAAgC,OAAO,MAAM,MAAM;EACxE;CACF;CACA,IAAI,QAAQ,aAAa;EACvB,MAAM,SAAS,UAAU,IAAI,SAAS,KAAK,GAAG,MAAM,MAAM;EAC1D;CACF;CACA,IAAI,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI,GAAG;EAC1C,MAAM,OAAO,IAAI,GAAG,CAAC,GAAG;EACxB,MAAM,OAAO,OAAO,GAAG;EAEvB,MAAM,OAAO,UAAU,KAAK,GAAG,WAAW,GAAG,aAAa,MAAM,CAAC,EAAE,YAAY,KAAK,IAAI;EACxF,MAAM,UACJ,KAAK,WAAW,OAAO,UAAU,aAAa;GAAE,aAAa;GAAO,SAAS;EAAK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O,KAAK,GAElC;GACF,MAAM,OAAO,IAAI,KAAK,KAAK;GAC3B,SAAS,IAAI,KAAK,OAAO,OAAO,KAAK;EACvC;EACA,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,KAAK,CAAC,GAAG;GAC1C,IAAI,QAAQ,IAAI,GAAG,GAAG;GACtB,MAAM,OAAO,OAAO,GAAG;GAGvB,SAAS,IAAI,KAAK,KAAA,GAAW,OAAO,KAAK;EAC3C;CACF,CACF;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { warnOnce } from "./internal/diagnostics.js";
|
|
2
|
-
import { MATHML_NS } from "./internal/names.js";
|
|
3
|
-
import { nextKey } from "./internal/hydration-scope.js";
|
|
4
1
|
import { checkClaimedTag } from "./internal/claim.js";
|
|
2
|
+
import { warnOnce } from "./internal/diagnostics.js";
|
|
5
3
|
import { claims } from "./internal/hydration-hooks.js";
|
|
4
|
+
import { nextKey } from "./internal/hydration-scope.js";
|
|
5
|
+
import { MATHML_NS } from "./internal/names.js";
|
|
6
6
|
// src/template.ts
|
|
7
7
|
/** One start tag: its name, then its attribute text (group 1). */
|
|
8
8
|
const START_TAG = /<[a-zA-Z][^\s/>]*((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shadow-js/web",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "A DOM renderer with no virtual DOM, plus control flow, server rendering and hydration",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -109,7 +109,7 @@
|
|
|
109
109
|
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test-types.json"
|
|
110
110
|
},
|
|
111
111
|
"peerDependencies": {
|
|
112
|
-
"@shadow-js/core": "^1.0.
|
|
112
|
+
"@shadow-js/core": "^1.0.5"
|
|
113
113
|
},
|
|
114
114
|
"devDependencies": {
|
|
115
115
|
"@biomejs/biome": "2.5.15",
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"@types/node": "^24.0.0",
|
|
119
119
|
"esbuild": "0.27.0",
|
|
120
120
|
"fast-check": "^4.10.2",
|
|
121
|
-
"happy-dom": "
|
|
121
|
+
"happy-dom": "21.0.4",
|
|
122
122
|
"tsdown": "0.23.0",
|
|
123
123
|
"typescript": "7.0.2",
|
|
124
124
|
"vitest": "5.0.3"
|