@shadow-js/web 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/dist/dev/attributes.d.ts +10 -3
- package/dist/dev/attributes.js +27 -49
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +15 -6
- package/dist/dev/class-style.js +64 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.d.ts +11 -2
- package/dist/dev/control-flow/dynamic.js +57 -40
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.js +2 -2
- package/dist/dev/control-flow/error-boundary.js.map +1 -1
- package/dist/dev/control-flow/portal.d.ts +2 -2
- package/dist/dev/control-flow/portal.js +17 -13
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/suspense-list.js +2 -2
- package/dist/dev/control-flow/suspense-list.js.map +1 -1
- package/dist/dev/control-flow/suspense.js +2 -2
- package/dist/dev/control-flow/suspense.js.map +1 -1
- package/dist/dev/element.js +6 -3
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +15 -44
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/extend.d.ts +2 -2
- package/dist/dev/extend.js +2 -2
- package/dist/dev/insert.d.ts +26 -5
- package/dist/dev/insert.js +84 -45
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/accessor.js +56 -0
- package/dist/dev/internal/accessor.js.map +1 -0
- package/dist/dev/internal/claim.d.ts +2 -1
- package/dist/dev/internal/claim.js +18 -3
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +2 -2
- package/dist/dev/internal/css-units.js.map +1 -1
- package/dist/dev/internal/diagnostics.d.ts +7 -3
- package/dist/dev/internal/diagnostics.js +14 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +20 -2
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +45 -71
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +7 -12
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +5 -2
- package/dist/dev/jsx/html.d.ts +1 -0
- package/dist/dev/resource-hints.js +4 -2
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.js +5 -15
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -0
- package/dist/dev/server/attributes.js +6 -32
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +10 -7
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +7 -1
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.js +14 -6
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.js +5 -2
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +3 -2
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/raw-text.d.ts +28 -0
- package/dist/dev/server/raw-text.js +66 -0
- package/dist/dev/server/raw-text.js.map +1 -0
- package/dist/dev/server/render.d.ts +2 -1
- package/dist/dev/server/render.js +3 -3
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/stream.d.ts +1 -1
- package/dist/dev/server/stream.js +3 -3
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +2 -1
- package/dist/dev/server.js +3 -2
- package/dist/dev/spread.js +56 -81
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +1 -3
- package/dist/dev/template.js.map +1 -1
- package/dist/dev/view-transition.js +12 -4
- package/dist/dev/view-transition.js.map +1 -1
- 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/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js +1 -1
- package/dist/prod/control-flow/suspense.js.map +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/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js +2 -0
- package/dist/prod/internal/accessor.js.map +1 -0
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/resource-hints.js +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/raw-text.js +2 -0
- package/dist/prod/server/raw-text.js.map +1 -0
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/server.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/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js +1 -1
- package/dist/prod/view-transition.js.map +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/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/control-flow/suspense.js.map +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/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js +2 -0
- package/dist/server/internal/accessor.js.map +1 -0
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/resource-hints.js +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/raw-text.js +2 -0
- package/dist/server/server/raw-text.js.map +1 -0
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/server.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/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/attributes.js +27 -49
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +64 -47
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +22 -10
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +2 -2
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +17 -13
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/suspense-list.js +2 -2
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/control-flow/suspense.js.map +1 -1
- package/dist/server-dev/element.js +3 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +15 -44
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/extend.js +2 -2
- package/dist/server-dev/insert.js +84 -45
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/accessor.js +56 -0
- package/dist/server-dev/internal/accessor.js.map +1 -0
- package/dist/server-dev/internal/claim.js +18 -3
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +2 -2
- package/dist/server-dev/internal/css-units.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +14 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +20 -2
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +45 -71
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +7 -12
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/resource-hints.js +4 -2
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +5 -15
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +6 -32
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +10 -7
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +7 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +14 -6
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +5 -2
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/index.js +3 -2
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/raw-text.js +86 -0
- package/dist/server-dev/server/raw-text.js.map +1 -0
- package/dist/server-dev/server/render.js +3 -3
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/stream.js +3 -3
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +3 -2
- package/dist/server-dev/spread.js +42 -80
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -3
- package/dist/server-dev/template.js.map +1 -1
- package/dist/server-dev/view-transition.js.map +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-transition.js","names":["startViewTransition","doc","flushSync","update","error","failure","callback","types","options","ViewTransition","built","ready","contentValue","untrack","props","start","end","generated","useId","useEffect","element","firstElementBetween","setOrClear","node","value","property"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists
|
|
1
|
+
{"version":3,"file":"view-transition.js","names":["startViewTransition","doc","flushSync","update","error","failure","callback","types","options","ViewTransition","built","ready","contentValue","untrack","props","start","end","generated","useId","useEffect","name","transitionClass","apply","element","firstElementBetween","setOrClear","parent","watchCommits","node","value","property"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":"A,8HAmDA,SAAgBA,EACd,EACA,EACe,CACf,IAAMC,EAAM,OAAO,SAAa,IAAc,IAAA,GAAa,SAC3D,GAAIA,IAAQ,IAAA,IAAa,OAAOA,EAAI,qBAAwB,WAAY,CACtE,GAAI,CACFC,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,OAAO,QAAQ,OAAOA,CAAK,CAC7B,CACA,OAAO,QAAQ,QAAQ,CACzB,CACA,IAAIC,EACEC,MAAuB,CAC3B,GAAI,CACFJ,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,EAAU,CAAE,OAAM,CACpB,CACF,EACMG,EAAQC,GAAS,MAIvB,OAHmBP,EAAI,oBACrBM,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAID,EAAW,CAAE,OAAQA,EAAU,MAAO,CAAC,GAAGC,CAAK,CAAE,CAE/E,CAAC,CAAC,SAAS,SAAW,CACpC,GAAIF,IAAY,IAAA,GAAW,MAAMA,EAAQ,KAC3C,CAAC,CACH,CAsDA,SAAgBI,EAAe,EAA+C,CAG5E,IAAIC,EACAC,EAAQ,GACNC,OACCD,IACH,EAAQ,GACR,EAAQE,MAAcC,EAAM,QAAQ,GAE/BJ,GAEHK,EAAQ,SAAS,eAAe,EAAE,EAClCC,EAAM,SAAS,eAAe,EAAE,EAChCC,EAAYH,EAAM,OAAS,GAAO,MAAMI,EAAM,IAAM,IAAA,GAiB1D,OAbAC,MAAgB,CACd,IAAMC,EAAOH,IAAc,OAAOH,EAAM,MAAS,SAAWA,EAAM,KAAO,IAAA,IACnEO,EAAkBP,EAAM,MACxBQ,MAAoB,CACxB,IAAMC,EAAUC,EAAoBT,EAAOC,CAAG,EAC1CO,IAAY,OAChBE,EAAWF,EAAS,uBAAwBH,CAAI,EAChDK,EAAWF,EAAS,wBAAyBF,CAAe,EAC9D,EACAC,EAAM,EACN,IAAMI,EAASX,EAAM,WACjBW,IAAW,MAAMC,EAAaD,EAAQJ,CAAK,CACjD,CAAC,MACY,CAACP,EAAOH,EAAa,EAAGI,CAAG,CAC1C,CAGA,SAASQ,EAAoB,EAAa,EAA+B,CACvE,IAAK,IAAII,EAAOb,EAAM,YAAaa,IAAS,MAAQA,IAASZ,EAAK,EAAOY,EAAK,YAC5E,GAAIA,EAAK,WAAa,EAAG,OAAOA,EAElC,OAAO,IACT,CAEA,SAASH,EAAW,EAAsB,EAAkB,EAAiC,CACvFI,IAAU,IAAA,IAAaA,IAAU,GAAIN,EAAQ,MAAM,eAAeO,CAAQ,EACzEP,EAAQ,MAAM,YAAYO,EAAUD,CAAK,CAChD,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n
|
|
1
|
+
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return e.replace(/\p{Cc}/gu,``)}function s(e){return i.test(o(e).trim().toLowerCase())}function c(e,t){let r=e.toLowerCase();return n.test(r)?r===`values`?t.split(`;`).some(s):s(t):!1}function l(e,t){return t==null?null:t===!1?r.test(e)?`false`:null:t===!0?r.test(e)?`true`:``:String(t)}function u(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function d(e,t,n,r){let i=n.toLowerCase(),a=l(i,r);a===null?t===null?e.removeAttribute(n):e.removeAttributeNS(t,u(n)):/^on./.test(i)||c(i,a)||(t===null?e.getAttribute(n)!==a&&e.setAttribute(n,a):e.getAttributeNS(t,u(n))!==a&&e.setAttributeNS(t,n,a))}function f(e,t,n){a(t),d(e,null,t,n)}function p(e,t,n,r){a(n),d(e,t===``?null:t,n,r)}function m(e,t,n){a(t),e.toggleAttribute(t,!!n)}export{a as assertAttributeName,c as isUnsafeUrlAttribute,f as setAttribute,p as setAttributeNS,m as setBoolAttribute};
|
|
2
2
|
//# sourceMappingURL=attributes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ENUMERATED_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","isStringValued","lowerName","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeUrlAttribute","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute","present"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"srcdoc\",\n \"poster\",\n \"data\",\n \"values\",\n \"from\",\n \"to\",\n \"by\",\n]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES = new Set([\"draggable\", \"spellcheck\", \"contenteditable\"]);\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their boolean values are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters. Written as a loop so no control character appears in a regex. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `srcdoc`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own.\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.has(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n const present = el.hasAttribute(name);\n if (value) {\n if (!present) el.setAttribute(name, \"\");\n } else if (present) {\n el.removeAttribute(name);\n }\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,kBAAiB,IAAI,IAAI,CAC7B,OACA,MACA,SACA,aACA,aACA,SACA,SACA,OACA,SACA,OACA,KACA,IACF,CAAC,EAGKC,kBAAwB,IAAI,IAAI,CAAC,YAAa,aAAc,iBAAiB,CAAC,EAG9EC,EAAsB,CAAC,cAAe,iBAAkB,WAAW,EAOzE,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAe,EAA4B,CAClD,OACEC,EAAU,WAAW,OAAO,GAC5BA,EAAU,WAAW,OAAO,GAC5BN,EAAsB,IAAIM,CAA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V,CAAI,EAC/Da,EAAG,eAAeD,EAAWJ,EAAUE,CAAS,CAAC,IAAMV,GAChEa,EAAG,eAAeD,EAAWF,EAAWV,CAAI,CAEhD,CAyBA,SAAgBc,EAAa,EAAa,EAAc,EAAsB,CAC5EtB,EAAoBC,CAAI,EACxBkB,EAAOE,EAAI,KAAMpB,EAAMW,CAAK,CAC9B,CAuBA,SAAgBW,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGvB,EAAoBC,CAAI,EACxBkB,EAAOE,EAAID,IAAc,GAAK,KAAOA,EAAWnB,EAAMW,CAAK,CAC7D,CAoBA,SAAgBY,EAAiB,EAAa,EAAc,EAAsB,CAChFxB,EAAoBC,CAAI,EACxB,IAAMwB,EAAUJ,EAAG,aAAapB,CAAI,EAChCW,EACGa,GAASJ,EAAG,aAAapB,EAAM,EAAE,EAC7BwB,GACTJ,EAAG,gBAAgBpB,CAAI,CAE3B,C"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","stripControls","text","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAc,EAAsB,CAC3C,OAAOC,EAAK,QAAQ,WAAY,EAAE,CACpC,CAGA,SAASC,EAAY,EAAwB,CAC3C,OAAON,EAAoB,KAAKI,EAAcG,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,CAC3E,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYP,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKW,CAAS,EAE3BA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CAAM,CACzC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(e){let n=e;for(let r of Object.keys(e))typeof e[r]==`function`&&(n===e&&(n={...e}),n[r]=t(e[r]));return n}function a(n,r){for(let i of e(n,`SHADOW_CLASS_CYCLE`))if(typeof i==`string`)i!==``&&r.push(i);else if(typeof i==`number`)i!==0&&!Number.isNaN(i)&&r.push(String(i));else if(typeof i==`object`&&i){let e=i;for(let n of Object.keys(e))t(e[n])&&n!==``&&r.push(n)}}function o(e){let n=t(e);if(typeof n==`string`)return n;if(n==null||n===!1)return null;let r=[];return a(n,r),r.join(` `)}function s(e,t,n){let r=o(t);r===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==r&&e.setAttribute(`class`,r):e.className!==r&&(e.className=r)}function c(e,t){s(e,t,e.namespaceURI!==r)}function l(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function u(e,t){return Object.hasOwn(e,t)&&!!e[t]}function d(e,t,n){let r=i(t??{}),a=n??{},o=/* @__PURE__ */ new Set([...Object.keys(a),...Object.keys(r)]);for(let t of o){let n=u(r,t);if(n!==u(a,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return r}function f(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function p(e,t,r){let i=f(t);r==null||r===!1?e.style.removeProperty(i):e.style.setProperty(i,n(i,r))}function m(e,n,r){let a=t(n);if(a==null||a===!1)return e.removeAttribute(`style`),a;if(typeof a!=`object`)return e.style.cssText=String(a),a;if(Array.isArray(a)){e.style.cssText=``;for(let n of a){let r=t(n);if(typeof r==`string`)e.style.cssText+=`;${r}`;else if(r!=null&&r!==!1){if(typeof r!=`object`||Array.isArray(r))throw TypeError(`SHADOW_STYLE_ITEM`);m(e,r,{})}}return a}let o=i({...a}),s=l(r)??{};(typeof r==`string`||Array.isArray(r))&&(e.style.cssText=``);let c=/* @__PURE__ */ new Set([...Object.keys(s),...Object.keys(o)]);for(let t of c)Object.is(s[t],o[t])||p(e,t,o[t]);return o}export{s as applyClass,l as asRecord,d as classList,c as className,p as setStyleProperty,m as style,f as toCssProperty};
|
|
2
2
|
//# sourceMappingURL=class-style.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":["collectClasses","frames","root","cursors","active","top","frame","cursor","done","item","parts","record","key","classText","value","applyClass","text","el","svg","className","HTML_NS","asRecord","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n // Explicit frames instead of recursion: array nesting depth is controlled by the user.\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = frame[cursor];\n if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(\n __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\",\n );\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (record[key] && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array).\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness. `undefined` switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next: Record<string, unknown> = value ?? {};\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n const now = Boolean(next[key]);\n const was = Boolean(before[key]);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. `null`, `undefined` and `false` remove the `style` attribute.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n if (value === null || value === undefined || value === false) {\n el.removeAttribute(\"style\");\n return value;\n }\n if (typeof value !== \"object\") {\n el.style.cssText = String(value);\n return value;\n }\n const next = { ...(value as Record<string, unknown>) };\n const before = asRecord(prev) ?? {};\n if (typeof prev === \"string\") el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,qGAIA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAMC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOH,EA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AOA,GAAU,SAEnB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAK,EACxBA,EAET,IAAMS,EAAO,CAAE,GAAIT,CAAkC,EAC/CU,EAASH,EAASI,CAAI,GAAK,CAAC,EAC9B,OAAOA,GAAS,WAAU,EAAG,MAAM,QAAU,IACjD,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMX,KAAOc,EACZ,OAAO,GAAGF,EAAOZ,GAAMW,EAAKX,EAAI,GACpCqB,EAAiBhB,EAAIL,EAAKW,EAAKX,EAAI,EAErC,OAAOW,CACT,C"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":["resolveMap","out","map","key","unwrap","collectClasses","item","leaves","root","parts","record","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved","source"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */\nfunction resolveMap(map: Record<string, unknown>): Record<string, unknown> {\n let out = map;\n for (const key of Object.keys(map)) {\n if (typeof map[key] !== \"function\") continue;\n if (out === map) out = { ...map };\n out[key] = unwrap(map[key]);\n }\n return out;\n}\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next = resolveMap(value ?? {});\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next = resolveMap({ ...(resolved as Record<string, unknown>) });\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAW,EAAuD,CACzE,IAAIC,EAAMC,EACV,IAAK,IAAMC,KAAO,OAAO,KAAKD,CAAG,EAC3B,OAAOA,EAAIC,IAAS,aACpBF,IAAQC,IAAK,EAAM,CAAE,GAAGA,CAAI,GAChC,EAAIC,GAAOC,EAAOF,EAAIC,EAAI,GAE5B,OAAOF,CACT,CAGA,SAASI,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,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,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAEF8B,EAAMpB,EAAIV,EAAM,CAAC,CAAC,CACpB,CACF,CACA,OAAO+B,CACT,CACA,IAAMd,EAAOvB,EAAW,CAAE,GAAIqC,CAAqC,CAAC,EAC9Db,EAASJ,EAASK,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMpB,KAAOuB,EACZ,OAAO,GAAGF,EAAOrB,GAAMoB,EAAKpB,EAAI,GACpC8B,EAAiBjB,EAAIb,EAAKoB,EAAKpB,EAAI,EAErC,OAAOoB,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createComponent as e}from"../component.js";import{ssrElement as
|
|
1
|
+
import{createComponent as e}from"../component.js";import{isTextOnlyElement as t}from"../server/raw-text.js";import{ssrElement as n,ssrRaw as r}from"../server/element.js";import{mergeProps as i,splitProps as a,untrack as o,useMemo as s}from"@shadow-js/core";const c=/^(?!script$)[a-z][a-z0-9-]*$/i;function l(e,i){if(!c.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);return n(e,i,()=>{let{children:n}=i;return n===void 0||t(e)?n:[r(`<!--[-->`),n,r(`<!--]-->`)]},!0)}function u(t,n){if(!t)return null;if(typeof t==`string`)return l(t,n);if(typeof t==`function`)return e(t,n);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function d(e){let[,t]=a(e,[`component`]);return s(()=>{let n=e.component;return o(()=>u(n,t))},{allowWrites:!0})}function f(e,t={}){return d(i({get component(){return e()}},t))}export{d as Dynamic,f as createDynamic};
|
|
2
2
|
//# sourceMappingURL=dynamic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":["TAG_PATTERN","DENIED_TAGS","buildElement","lower","tag","ssrElement","props","children","ssrRaw","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, nextKey, SVG_NS } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { spread } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/** Tag names that take the SVG namespace. Anything else is HTML. */\nconst SVG_TAGS: ReadonlySet<string> = new Set([\n \"svg\",\n \"g\",\n \"path\",\n \"circle\",\n \"ellipse\",\n \"line\",\n \"polygon\",\n \"polyline\",\n \"rect\",\n \"text\",\n \"tspan\",\n \"textpath\",\n \"defs\",\n \"use\",\n \"symbol\",\n \"marker\",\n \"clippath\",\n \"mask\",\n \"pattern\",\n \"lineargradient\",\n \"radialgradient\",\n \"stop\",\n \"filter\",\n]);\n\n/** Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** Tags refused in any letter case: a script would bypass CSP nonces and Trusted Types. */\nconst DENIED_TAGS: ReadonlySet<string> = new Set([\"script\"]);\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n const lower = tag.toLowerCase();\n if (!TAG_PATTERN.test(tag) || DENIED_TAGS.has(lower)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n return children === undefined\n ? undefined\n : [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const svg = SVG_TAGS.has(lower);\n const claimed = claims.current.claimElement(nextKey());\n const el = claimed ?? (svg ? document.createElementNS(SVG_NS, tag) : document.createElement(tag));\n // Attributes through spread; children through insert, which adopts the server's children region.\n spread(el, props, svg, true);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. SVG-only names (`circle`, `path`, `svg`, ...) are created\n * in the SVG namespace.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,uMA4DA,MAAMA,EAAc,qBAGdC,kBAAmC,IAAI,IAAI,CAAC,QAAQ,CAAC,EAQ3D,SAASC,EAAa,EAAa,EAAwB,CACzD,IAAMC,EAAQC,EAAI,YAAY,EAC9B,GAAI,CAACJ,EAAY,KAAKI,CAAG,GAAKH,EAAY,IAAIE,CAAK,EACjD,MAAU,UAAsD,oBAAoB,EAMpF,OAAOE,EACLD,EACAE,MACM,CACJ,GAAM,CAAE,YAAaA,EACrB,OAAOC,IAAa,IAAA,GAChB,IAAA,GACA,CAACC,EAAO,UAAU,EAAGD,EAAUC,EAAO,UAAU,CAAC,CACvD,EACA,EACF,CAUJ,CAMA,SAASC,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOR,EAAaQ,EAAQJ,CAAK,EACjE,GAAI,OAAOI,GAAW,WACpB,OAAOC,EAAgBD,EAAsCJ,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CAqCA,SAAgBM,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWR,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOS,MACU,CACb,IAAML,EAAkBJ,EAAM,UAC9B,OAAOU,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAb,CACF,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":["TAG_PATTERN","buildElement","tag","ssrElement","props","children","isTextOnlyElement","ssrRaw","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,iQAkDA,MAAMA,EAAc,gCA8CpB,SAASC,EAAa,EAAa,EAAwB,CACzD,GAAI,CAACD,EAAY,KAAKE,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAMpF,OAAOC,EACLD,EACAE,MACM,CACJ,GAAM,CAAE,YAAaA,EAGrB,OADIC,IAAa,IAAA,IAAaC,EAAkBJ,CAAG,EAAUG,EACtD,CAACE,EAAO,UAAU,EAAGF,EAAUE,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CAQJ,CAMA,SAASC,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOR,EAAaQ,EAAQL,CAAK,EACjE,GAAI,OAAOK,GAAW,WACpB,OAAOC,EAAgBD,EAAsCL,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBO,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWT,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOU,MACU,CACb,IAAML,EAAkBL,EAAM,UAC9B,OAAOW,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{currentScope as e,withScope as t}from"../internal/hydration-scope.js";import{rootErrorsOf as n}from"./root-errors.js";import{catchError as r,createRoot as i,getOwner as a,onCleanup as o,untrack as s,useMemo as c,useSignal as l}from"@shadow-js/core";import{
|
|
1
|
+
import{currentScope as e,withScope as t}from"../internal/hydration-scope.js";import{rootErrorsOf as n}from"./root-errors.js";import{catchError as r,createRoot as i,getOwner as a,onCleanup as o,untrack as s,useMemo as c,useSignal as l}from"@shadow-js/core";import{SignalNode as u,handleError as d,readSignal as f,writeSignal as p}from"@shadow-js/core/extend";function m(m){let h=new u(void 0,Object.is),g=a(),_=n(g),v=e(),y=v===null?null:{id:v.id,count:v.count,resources:v.resources},b=()=>f(h),x=e=>{p(h,e,{allowInMemo:!0})},[S,C]=l(0,{equals:!1}),w=!0,T=!1,E,D=()=>{w&&(x(void 0),C(e=>e+1))},O=e=>{w&&(_?.onCaughtError?.(e),T?E===void 0&&(E={error:e}):x({error:e}))},k=()=>{let e=E;return E=void 0,e},A=e=>{let t=m.fallback;if(typeof t!=`function`)return t;try{return s(()=>t(e,D))}catch(e){d(e,g);return}},j=()=>{T=!0;try{S();let e=b()??k();if(e!==void 0)return A(e.error);let t=i(e=>({dispose:e,value:r(()=>s(()=>m.children),O)})),n=k();return n===void 0?t.value:(t.dispose(),A(n.error))}finally{i(()=>{o(()=>{T=!0})}),T=!1}},M=c(()=>y===null?j():t({...y},j),{allowWrites:!0});return i(()=>{o(()=>{w=!1})}),M}export{m as ErrorBoundary};
|
|
2
2
|
//# sourceMappingURL=error-boundary.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-boundary.js","names":["ErrorBoundary","failureCell","createSignalNode","parentOwner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createSignalNode, handleError, readSignal, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = createSignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,4WA0FA,SAAgBA,EAAc,EAAmD,CAG/E,IAAMC,EAAcC,EAAsC,IAAA,GAAW,OAAO,EAAE,EAExEC,EAAcC,EAAS,EAEvBC,EAAQC,EAAaH,CAAW,EAEhCI,EAAOC,EAAa,EACpBC,EACJF,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EG,MAAqCC,EAAWV,CAAW,EAC3DW,EAAc,GAAoC,CACtDC,EAAYZ,EAAaa,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAcC,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDC,EAAQ,GAERC,EAAO,GAEPC,EAEEC,MAAoB,CACnBH,IACLN,EAAW,IAAA,EAAS,EACpBI,EAAY,GAAUM,EAAQ,CAAC,EACjC,EAYMC,EAAU,GAAyB,CAClCL,IACLb,GAAO,gBAAgBmB,CAAK,EACxBL,EACEC,IAAY,IAAA,KAAW,EAAU,CAAE,OAAM,GAG/CR,EAAW,CAAE,OAAM,CAAC,EACtB,EAGMa,MAAyC,CAC7C,IAAMC,EAAWN,EAEjB,MADA,GAAU,IAAA,GACHM,CACT,EAEMC,EAAe,GAA4B,CAC/C,IAAMC,EAAWC,EAAM,SACvB,GAAI,OAAOD,GAAa,WAAY,OAAOA,EAC3C,GAAI,CACF,OAAOE,MACJF,EAA4DJ,EAAOH,CAAK,CAC3E,CACF,OAASU,EAAQ,CAGfC,EAAYD,EAAQ5B,CAAW,EAC/B,MACF,CACF,EAGM8B,MAAuB,CAC3B,EAAO,GACP,GAAI,CACFlB,EAAQ,EACR,IAAMmB,EAAUxB,EAAQ,GAAKe,EAAY,EACzC,GAAIS,IAAY,IAAA,GAEd,OAAOP,EAAYO,EAAQ,KAAK,EAIlC,IAAMC,EAAQC,EAAY,IAEjB,CACL,UACA,MAAOC,MAAiBP,MAAcD,EAAM,QAAQ,EAAGN,CAAM,CAC/D,EACD,EACKe,EAAWb,EAAY,EAO7B,OANIa,IAAa,IAAA,GAMVH,EAAM,OALXA,EAAM,QAAQ,EAEPR,EAAYW,EAAS,KAAK,EAIrC,QAAU,CAERF,MAAiB,CACfG,MAAgB,CACd,EAAO,EACT,CAAC,CACH,CAAC,EACD,EAAO,EACT,CAEF,EAIMC,EAAOC,MACJhC,IAAW,KAAOwB,EAAM,EAAIS,EAAU,CAAE,GAAGjC,CAAO,EAAGwB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAG,MAAiB,CACfG,MAAgB,CACd,EAAQ,EAEV,CAAC,CACH,CAAC,EACMC,CACT,C"}
|
|
1
|
+
{"version":3,"file":"error-boundary.js","names":["ErrorBoundary","failureCell","SignalNode","parentOwner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { handleError, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = new SignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,sWA0FA,SAAgBA,EAAc,EAAmD,CAG/E,IAAMC,EAAc,IAAIC,EAAgC,IAAA,GAAW,OAAO,EAAE,EAEtEC,EAAcC,EAAS,EAEvBC,EAAQC,EAAaH,CAAW,EAEhCI,EAAOC,EAAa,EACpBC,EACJF,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EG,MAAqCC,EAAWV,CAAW,EAC3DW,EAAc,GAAoC,CACtDC,EAAYZ,EAAaa,E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G,MAAiB,CACfG,MAAgB,CACd,EAAQ,EAEV,CAAC,CACH,CAAC,EACMC,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,removeRegion as
|
|
1
|
+
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,moveRegion as o,removeRegion as s}from"../insert.js";import{PortalContext as c}from"../internal/portal-context.js";import{createRoot as l,getOwner as u,isServer as d,onCleanup as f,runWithOwner as p,useContext as m,useRenderEffect as h}from"@shadow-js/core";function g(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function _(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function v(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function y(y){let b=t(),x=m(c);if(d||x!==null)return y.useShadow!==!0&&x?.render?.(b,()=>y.children),null;let S=u(),C,w=r.current.claimPortal(b),T=()=>{let e=C;e!==void 0&&(C=void 0,e.stopEffects(),s(e.region))},E=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:p(S,()=>l(t=>{let a=()=>{i(c,()=>y.children)};return s===`plain`?a():s===`claimed`?n(e(b),a):r.current.withoutClaiming(()=>n(e(b),a)),t}))}},D=e=>{let t=C;if(t===void 0){let t=w??[],n=`plain`;w===void 0?b!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,w=void 0;for(let n of t)n.parentNode!==e&&g(e,n);C=E(e,t,n)}else o(t.region,e,t=>g(e,t)),C={host:e,region:t.region,stopEffects:t.stopEffects}};return h(()=>({host:v(y.mount),shadow:y.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){T();for(let e of w??[])e.parentNode?.removeChild(e);w=void 0;return}let n=t?_(e):e;(C===void 0||C.host!==n)&&D(n)}),f(T),null}export{y as Portal};
|
|
2
2
|
//# sourceMappingURL=portal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","renderServerPortal","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","nodes","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\nimport { renderServerPortal } from \"../server/portals\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content, and static nodes keep their identity while they\n * move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) renderServerPortal(key, () => props.children, sink);\n return null;\n }\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n });\n return { host, region, stopEffects };\n };\n\n /** Moves the content to `target`. The nodes move first, then the children are bound again. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n const nodes = previous.region.nodes.filter((node) => node.parentNode === previous.host);\n previous.stopEffects();\n for (const node of nodes) appendMoved(target, node);\n mounted = mountInto(target, nodes, \"plain\");\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,qcAiEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAa,EAA6C,CAGjE,OAFIC,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAO,EAA0B,CAI/C,IAAMC,EAAMC,EAAQ,EAGdC,EAAOC,EAAWC,CAAa,EACrC,GAAIC,GAAYH,IAAS,KAEvB,OADII,EAAM,YAAc,IAAMC,EAAmBP,MAAWM,EAAM,SAAUJ,CAAI,EACzE,KAET,IAAIM,EAGAC,EAA8BC,EAAO,QAAQ,YAAYV,CAAG,EAG1DW,MAAsB,CAC1B,IAAMC,EAAUJ,EACZI,IAAY,IAAA,KAChB,EAAU,IAAA,GACVA,EAAQ,YAAY,EACpBC,EAAaD,EAAQ,MAAM,EAC7B,EAGME,GAAa,EAAY,EAAiB,IAA6B,CAC3E,IAAMC,EAASC,EAAapB,EAAM,KAAMqB,CAAO,EAU/C,MAAO,CAAE,OAAM,SAAQ,YATHC,EAAY,GAAY,CAC1C,IAAMC,MAAmB,CACvBC,EAAWL,MAAcT,EAAM,QAAQ,CACzC,EAIA,OAHIe,IAAS,QAASF,EAAK,EAClBE,IAAS,UAAWC,EAAUC,EAAWvB,CAAG,EAAGmB,CAAI,EACvDT,EAAO,QAAQ,oBAAsBY,EAAUC,EAAWvB,CAAG,EAAGmB,CAAI,CAAC,EACnEK,CACT,CACiC,CAAE,CACrC,EAGMC,EAAU,GAAuB,CACrC,IAAMC,EAAWlB,EACjB,GAAIkB,IAAa,IAAA,GAAW,CAC1B,IAAMT,EAAUR,GAAW,CAAC,EACxBY,EAAkB,QAClBZ,IAAY,IAAA,GACPT,IAAQ,IAAA,IAAaU,EAAO,QAAQ,WAAW,IAAG,EAAO,aADvC,EAAO,UAElC,EAAU,IAAA,GACV,IAAK,IAAMhB,KAAQuB,EACbvB,EAAK,aAAeD,GAAQD,EAAYC,EAAQC,CAAI,EAE1D,EAAUoB,EAAUrB,EAAQwB,EAASI,CAAI,EACzC,MACF,CACA,IAAMM,EAAQD,EAAS,OAAO,MAAM,OAAQ,GAAShC,EAAK,aAAegC,EAAS,IAAI,EACtFA,EAAS,YAAY,EACrB,IAAK,IAAMhC,KAAQiC,EAAOnC,EAAYC,EAAQC,CAAI,EAClD,EAAUoB,EAAUrB,EAAQkC,EAAO,OAAO,CAC5C,EAyBA,OAvBAC,OAIW,CAAE,KAFI/B,EAAaS,EAAM,KAEpB,EAAG,OADAA,EAAM,YAAc,EACb,IAEvB,CAAE,OAAM,YAAa,CACpB,GAAIV,IAAS,KAAM,CACjBe,EAAQ,EAOR,MACF,CACA,IAAMlB,EAAeoC,EAASlC,EAAaC,CAAI,EAAIA,GAC/CY,IAAY,IAAA,IAAaA,EAAQ,OAASf,IAC9CgC,EAAOhC,CAAM,CACf,CACF,EACAqC,EAAUnB,CAAO,EACV,IACT,C"}
|
|
1
|
+
{"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","owner","getOwner","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","runWithOwner","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","moveRegion","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n onCleanup,\n runWithOwner,\n useContext,\n useRenderEffect,\n} from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n moveRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content: the children are built once, and\n * their nodes and effects keep their identity while they move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) sink?.render?.(key, () => props.children);\n return null;\n }\n // The content is built under the portal's own owner, not under the effect that picks the mount:\n // that effect runs again for each new mount and would dispose what it owns.\n const owner = getOwner();\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = runWithOwner(owner, () =>\n createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n }),\n );\n return { host, region, stopEffects };\n };\n\n /** Mounts the content in `target` the first time, and moves it there afterward. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n // The children were built once, under an owner that stays: the nodes and their effects move, so\n // an input keeps what was typed and a component is neither disposed nor set up again.\n moveRegion(previous.region, target, (node) => appendMoved(target, node));\n mounted = { host: target, region: previous.region, stopEffects: previous.stopEffects };\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,2bAyEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAa,EAA6C,CAGjE,OAFIC,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAO,EAA0B,CAI/C,IAAMC,EAAMC,EAAQ,EAGdC,EAAOC,EAAWC,CAAa,EACrC,GAAIC,GAAYH,IAAS,KAEvB,OADII,EAAM,YAAc,IAAMJ,GAAM,SAASF,MAAWM,EAAM,QAAQ,EAC/D,KAIT,IAAMC,EAAQC,EAAS,EACnBC,EAGAC,EAA8BC,EAAO,QAAQ,YAAYX,CAAG,EAG1DY,MAAsB,CAC1B,IAAMC,EAAUJ,EACZI,IAAY,IAAA,KAChB,EAAU,IAAA,GACVA,EAAQ,YAAY,EACpBC,EAAaD,EAAQ,MAAM,EAC7B,EAGME,GAAa,EAAY,EAAiB,IAA6B,CAC3E,IAAMC,EAASC,EAAarB,EAAM,KAAMsB,CAAO,EAY/C,MAAO,CAAE,OAAM,SAAQ,YAXHC,EAAaZ,MAC/Ba,EAAY,GAAY,CACtB,IAAMC,MAAmB,CACvBC,EAAWN,MAAcV,EAAM,QAAQ,CACzC,EAIA,OAHIiB,IAAS,QAASF,EAAK,EAClBE,IAAS,UAAWC,EAAUC,EAAWzB,CAAG,EAAGqB,CAAI,EACvDV,EAAO,QAAQ,oBAAsBa,EAAUC,EAAWzB,CAAG,EAAGqB,CAAI,CAAC,EACnEK,CACT,CAAC,CAE8B,CAAE,CACrC,EAGMC,EAAU,GAAuB,CACrC,IAAMC,EAAWnB,EACjB,GAAImB,IAAa,IAAA,GAAW,CAC1B,IAAMV,EAAUR,GAAW,CAAC,EACxBa,EAAkB,QAClBb,IAAY,IAAA,GACPV,IAAQ,IAAA,IAAaW,EAAO,QAAQ,WAAW,IAAG,EAAO,aADvC,EAAO,UAElC,EAAU,IAAA,GACV,IAAK,IAAMjB,KAAQwB,EACbxB,EAAK,aAAeD,GAAQD,EAAYC,EAAQC,CAAI,EAE1D,EAAUqB,EAAUtB,EAAQyB,EAASK,CAAI,CAE3C,MAGAM,EAAWD,EAAS,OAAQnC,EAAS,GAASD,EAAYC,EAAQC,CAAI,CAAC,EACvE,EAAU,CAAE,KAAMD,EAAQ,OAAQmC,EAAS,OAAQ,YAAaA,EAAS,WAAY,CACvF,EA6BA,OA3BAE,OAIW,CAAE,KAFIjC,EAAaS,EAAM,KAEpB,EAAG,OADAA,EAAM,YAAc,EACb,IAEvB,CAAE,OAAM,YAAa,CACpB,GAAIV,IAAS,KAAM,CACjBgB,EAAQ,EAGR,IAAK,IAAMlB,KAAQgB,GAAW,CAAC,EAAGhB,EAAK,YAAY,YAAYA,CAAI,EACnE,EAAU,IAAA,GAOV,MACF,CACA,IAAMD,EAAesC,EAASpC,EAAaC,CAAI,EAAIA,GAC/Ca,IAAY,IAAA,IAAaA,EAAQ,OAAShB,IAC9CkC,EAAOlC,CAAM,CACf,CACF,EACAuC,EAAUpB,CAAO,EACV,IACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createContext as e,onCleanup as t}from"@shadow-js/core";import{
|
|
1
|
+
import{createContext as e,onCleanup as t}from"@shadow-js/core";import{SignalNode as n,readSignal as r,writeSignal as i}from"@shadow-js/core/extend";const a=/* @__PURE__ */ e(null,{name:`SuspenseList`});function o(e){let o=new n(0,!1),s=[],c=()=>{i(o,0,{allowInMemo:!0})};return a({value:{register(n){let i={ready:n};s.push(i),c(),t(()=>{let e=s.indexOf(i);e!==-1&&s.splice(e,1),c()});let a=()=>(r(o),s.indexOf(i)),l=()=>{let t=a();if(t===-1)return!1;switch(e.revealOrder){case`together`:return s.every(e=>e.ready());case`forwards`:return s.slice(0,t+1).every(e=>e.ready());case`backwards`:return s.slice(t).every(e=>e.ready());default:return n()}};return{reveal:l,showFallback:()=>{if(l())return!1;let t=e.revealOrder;if(t!==`forwards`&&t!==`backwards`)return!0;if(e.tail===`hidden`)return!1;if(e.tail!==`collapsed`)return!0;let n=a(),r=t===`backwards`?[...s].reverse():s,i=t===`backwards`?s.length-1-n:n;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==void 0&&!t.ready())return e===i}return!1}}}},get children(){return e.children}})}export{o as SuspenseList,a as SuspenseListContext};
|
|
2
2
|
//# sourceMappingURL=suspense-list.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suspense-list.js","names":["SuspenseListContext","SuspenseList","changes","
|
|
1
|
+
{"version":3,"file":"suspense-list.js","names":["SuspenseListContext","SuspenseList","changes","SignalNode","slots","touch","writeSignal","entry","onCleanup","index","position","readSignal","reveal","props","slot","ready","order","ordered","wanted","i","candidate"],"sources":["../../../src/control-flow/suspense-list.ts"],"sourcesContent":["import { type Accessor, type Context, createContext, onCleanup, useContext } from \"@shadow-js/core\";\nimport { readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n\n/** What a `<Suspense>` inside a list learns about its place: when to show content and a fallback. @internal */\nexport interface SuspenseListSlot {\n /** True when this boundary may show its content now (it is ready and the order allows it). */\n reveal(): boolean;\n /** True when this boundary should show its fallback while it waits. */\n showFallback(): boolean;\n}\n\n/** Provided by `<SuspenseList>` to the boundaries below it. @internal */\nexport interface SuspenseListState {\n /** Registers a boundary, in creation order; `ready` reports that its own data has loaded. */\n register(ready: () => boolean): SuspenseListSlot;\n}\n\n/** The enclosing list, or null. @internal */\nexport const SuspenseListContext: Context<SuspenseListState | null> =\n /* @__PURE__ */ createContext<SuspenseListState | null>(null, { name: \"SuspenseList\" });\n\n/**\n * Props of {@link SuspenseList}.\n * @since 1.0.0\n */\nexport interface SuspenseListProps {\n /**\n * `\"forwards\"`: boundaries reveal in order, each after the ones before it. `\"backwards\"`: the\n * same from the last one. `\"together\"`: all at once, when the last one is ready. Without it each\n * boundary reveals on its own. Read reactively.\n * @default undefined (each boundary reveals as soon as its own data is ready)\n */\n readonly revealOrder?: \"forwards\" | \"backwards\" | \"together\" | undefined;\n /**\n * What the boundaries that are still waiting show: `\"collapsed\"` only the next fallback in\n * order, `\"hidden\"` none. Applies to `forwards` and `backwards`; the default shows every fallback.\n * @default undefined (every waiting boundary shows its fallback)\n */\n readonly tail?: \"collapsed\" | \"hidden\" | undefined;\n /**\n * The content, with the `<Suspense>` boundaries to coordinate anywhere below it.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Coordinates the `<Suspense>` boundaries below it so a page of independent loads reveals in a\n * calm order instead of popping in at random.\n *\n * @param props See {@link SuspenseListProps}.\n * @returns An accessor of the children, rendered with the list's coordination in context.\n * @example\n * import { Suspense, SuspenseList } from \"@shadow-js/web\";\n *\n * function Skeleton() {\n * return <p>Loading...</p>;\n * }\n *\n * function Profile() {\n * return <p>Profile</p>;\n * }\n *\n * function Feed() {\n * return <p>Feed</p>;\n * }\n *\n * function Page() {\n * return (\n * <SuspenseList revealOrder=\"forwards\" tail=\"collapsed\">\n * <Suspense fallback={<Skeleton />}>\n * <Profile />\n * </Suspense>\n * <Suspense fallback={<Skeleton />}>\n * <Feed />\n * </Suspense>\n * </SuspenseList>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function SuspenseList(props: SuspenseListProps): Accessor<unknown> {\n // The set of boundaries changes as they are created and disposed; `changes` tells readers.\n const changes = new SignalNode<number>(0, false);\n const slots: Array<{ readonly ready: () => boolean }> = [];\n const touch = (): void => {\n writeSignal(changes, 0, { allowInMemo: true });\n };\n\n const state: SuspenseListState = {\n register(ready) {\n const entry = { ready };\n slots.push(entry);\n touch();\n onCleanup(() => {\n const index = slots.indexOf(entry);\n if (index !== -1) slots.splice(index, 1);\n touch();\n });\n const position = (): number => {\n readSignal(changes);\n return slots.indexOf(entry);\n };\n const reveal = (): boolean => {\n const index = position();\n if (index === -1) return false;\n switch (props.revealOrder) {\n case \"together\":\n return slots.every((slot) => slot.ready());\n case \"forwards\":\n return slots.slice(0, index + 1).every((slot) => slot.ready());\n case \"backwards\":\n return slots.slice(index).every((slot) => slot.ready());\n default:\n return ready();\n }\n };\n const showFallback = (): boolean => {\n if (reveal()) return false;\n const order = props.revealOrder;\n const sequential = order === \"forwards\" || order === \"backwards\";\n if (!sequential) return true;\n if (props.tail === \"hidden\") return false;\n if (props.tail !== \"collapsed\") return true;\n // Only the next boundary in order that is not revealed yet shows its fallback.\n const index = position();\n const ordered = order === \"backwards\" ? [...slots].reverse() : slots;\n const wanted = order === \"backwards\" ? slots.length - 1 - index : index;\n for (let i = 0; i < ordered.length; i += 1) {\n const candidate = ordered[i];\n if (candidate !== undefined && !candidate.ready()) return i === wanted;\n }\n return false;\n };\n return { reveal, showFallback };\n },\n };\n\n return SuspenseListContext({\n value: state,\n get children() {\n return props.children;\n },\n }) as Accessor<unknown>;\n}\n\n/** The slot of the nearest list for a boundary created now, or null outside a list. @internal */\nexport function registerInList(ready: () => boolean): SuspenseListSlot | null {\n const list = useContext(SuspenseListContext);\n return list === null ? null : list.register(ready);\n}\n"],"mappings":"A,oJAkBA,MAAaA,EACK,kBAAwC,KAAM,CAAE,KAAM,cAAe,CAAC,EA+DxF,SAAgBC,EAAa,EAA6C,CAExE,IAAMC,EAAU,IAAIC,EAAmB,EAAG,EAAK,EACzCC,EAAkD,CAAC,EACnDC,MAAoB,CACxBC,EAAYJ,EAAS,EAAG,CAAE,YAAa,EAAK,CAAC,CAC/C,EAmDA,OAAOF,EAAoB,CACzB,MAAO,CAjDP,SAAS,EAAO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AAOL,EAAM,QACf,CACF,CAAC,CACH,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{escape as r}from"../server/escape.js";import{ssrRaw as i}from"../server/element.js";import{StreamContext as a}from"../internal/stream-context.js";import{SuspenseContext as o,getOwner as s,runWithOwner as c,useContext as l}from"@shadow-js/core";import{
|
|
1
|
+
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{escape as r}from"../server/escape.js";import{ssrRaw as i}from"../server/element.js";import{StreamContext as a}from"../internal/stream-context.js";import{SuspenseContext as o,getOwner as s,runWithOwner as c,useContext as l}from"@shadow-js/core";import{SignalNode as u,createOwner as d,readSignal as f,transitionHooks as p,writeSignal as m}from"@shadow-js/core/extend";function h(){let e=new u(0,Object.is),t,n=!1,r=t=>{m(e,e.value+t,{allowInMemo:!0})};return{tracker:{increment:()=>r(1),decrement:()=>{r(-1),e.value===0&&t?.release()},hold:()=>n?(t??=p()?.boundaryHold(),t?.engage()===!0):!1},count:()=>f(e),holding:()=>t?.holding()===!0,revealed:()=>{n=!0}}}function g(r){let i=t(),{tracker:a,count:s,holding:l,revealed:u}=h(),f=d();return f.gate=()=>s()>0||!1,_(r,i,s,c(f,()=>n(e(i),()=>o({value:a,get children(){return r.children}}))))}function _(t,u,d,f){let p=e(u===void 0?void 0:`${u}f`);if(d()===0)return f;let m=l(a);if(m===null||u===void 0)return()=>n(p,()=>t.fallback);let g=s(),_={id:u,rebuild:()=>{let i=h(),a=c(g,()=>n(e(u),()=>o({value:i.tracker,get children(){return t.children}})));return i.count()>0?(m.defer(_),null):r(a())}};return m.defer(_),()=>[i(`<!--[b:${u}-->`),n(p,()=>t.fallback),i(`<!--]-->`)]}export{g as Suspense};
|
|
2
2
|
//# sourceMappingURL=suspense.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suspense.js","names":["createTracker","pending","
|
|
1
|
+
{"version":3,"file":"suspense.js","names":["createTracker","pending","SignalNode","hold","shown","adjust","writeSignal","by","transitionHooks","readSignal","Suspense","key","nextKey","boundary","createOwner","count","suspenseOnServer","props","runWithOwner","withScope","childScope","SuspenseContext","tracker","fallbackScope","content","sink","useContext","StreamContext","owner","getOwner","next","rebuilt","escape","ssrRaw"],"sources":["../../../src/control-flow/suspense.ts"],"sourcesContent":["import {\n type Accessor,\n getOwner,\n runWithOwner,\n SuspenseContext,\n type SuspenseTracker,\n useContext,\n useMemo,\n} from \"@shadow-js/core\";\nimport {\n type BoundaryHold,\n createOwner,\n readSignal,\n SignalNode,\n transitionHooks,\n writeSignal,\n} from \"@shadow-js/core/extend\";\nimport { childScope, nextKey, StreamContext, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"../server/escape\";\nimport { registerInList } from \"./suspense-list\";\n\n/**\n * Props of {@link Suspense}.\n * @since 1.0.0\n */\nexport interface SuspenseProps {\n /**\n * Shown while any resource read inside the boundary is loading for the first time.\n * @default undefined (a pending boundary renders nothing)\n */\n fallback?: unknown;\n /**\n * The content. Created once, under the boundary, and kept alive while the fallback is visible.\n * @default undefined (renders nothing)\n */\n children?: unknown;\n}\n\n/** What a boundary tracks: its pending reads, and whether a transition holds its content. */\ninterface Tracking {\n readonly tracker: SuspenseTracker;\n readonly count: () => number;\n /** True while a transition waits for data and the boundary keeps showing its content. */\n readonly holding: () => boolean;\n /** Called when the boundary first shows its content: only then can a transition hold it. */\n readonly revealed: () => void;\n}\n\n/**\n * A counter the resources of one boundary report to (see {@link SuspenseTracker}), and the hold a\n * transition takes on the boundary. A transition that reads pending data while the boundary shows\n * content does not bring the fallback back: its readers keep their previous values, the boundary\n * keeps its content, and the readers run again when the count returns to zero.\n */\nfunction createTracker(): Tracking {\n // Counted with an extension-API cell: a resource may be read (and so hold this boundary) while a\n // memo computes, where a plain write would be rejected.\n const pending = new SignalNode<number>(0, Object.is);\n // The hold a transition takes on this boundary. Only a transition read creates it (core keeps the\n // machinery of holds behind its transition hooks); the boundary's memo reads the count before it\n // reads the hold, so it runs again when the count reaches zero (the release).\n let hold: BoundaryHold | undefined;\n let shown = false;\n const adjust = (by: number): void => {\n writeSignal(pending, pending.value + by, { allowInMemo: true });\n };\n const tracker: SuspenseTracker = {\n increment: () => adjust(1),\n decrement: () => {\n adjust(-1);\n if (pending.value === 0) hold?.release();\n },\n hold: (): boolean => {\n if (!shown) return false;\n hold ??= transitionHooks()?.boundaryHold();\n return hold?.engage() === true;\n },\n };\n return {\n tracker,\n count: () => readSignal(pending),\n holding: () => hold?.holding() === true,\n revealed: () => {\n shown = true;\n },\n };\n}\n\n/**\n * Shows `fallback` while resources read inside it are loading for the first time. The children\n * are created once and stay alive (with their state) while the fallback is visible; the boundary\n * only switches what is displayed. Nested boundaries each track their own resources.\n *\n * On the server a boundary renders its fallback when its data is not ready (`renderToString`), or\n * streams the content later (`renderToStream`). Content and fallback get their own hydration key\n * space, so what a boundary renders never shifts the keys of its siblings.\n *\n * @param props See {@link SuspenseProps}.\n * @returns An accessor of what the boundary shows: the fallback while a resource is pending, the\n * children otherwise.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n * import { Suspense } from \"@shadow-js/web\";\n *\n * function Profile() {\n * const name = useResource(() => Promise.resolve(\"Ada\"));\n * return <p>{name()}</p>;\n * }\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <Profile />\n * </Suspense>\n * );\n * }\n * @see SuspenseList\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function Suspense(props: SuspenseProps): Accessor<unknown> {\n const key = nextKey();\n const { tracker, count, holding, revealed } = createTracker();\n // The content lives under its own owner, whose gate holds back user effects and `onMount` until\n // the boundary has resolved once. Render effects (DOM bindings) are never held.\n // Inside a <SuspenseList> the boundary also waits for its turn to be revealed.\n const slot = __SERVER__ ? null : registerInList(() => count() === 0);\n const boundary = createOwner();\n boundary.gate = () => count() > 0 || (slot !== null && !slot.reveal());\n const content = runWithOwner(boundary, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (__SERVER__) return suspenseOnServer(props, key, count, content as () => unknown);\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n return useMemo<unknown>(\n (previous) => {\n // Read first: the memo depends on the count even while held, so it runs again when the hold ends.\n count();\n // A transition holds the boundary: the content stays as it was (the same value, so no DOM change).\n if (holding() && previous !== undefined) return previous;\n if (slot === null) {\n if (count() > 0) return withScope(fallbackScope, () => props.fallback);\n revealed();\n return (content as () => unknown)();\n }\n if (count() === 0 && slot.reveal()) {\n revealed();\n return (content as () => unknown)();\n }\n return slot.showFallback() ? withScope(fallbackScope, () => props.fallback) : null;\n },\n { allowWrites: true },\n );\n}\n\n/** Server behavior: ready content, a fallback, or a fallback plus a deferred stream chunk. */\nfunction suspenseOnServer(\n props: SuspenseProps,\n key: string | undefined,\n count: () => number,\n content: () => unknown,\n): Accessor<unknown> {\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n if (count() === 0) return content;\n const sink = useContext(StreamContext);\n if (sink === null || key === undefined) {\n return () => withScope(fallbackScope, () => props.fallback);\n }\n const owner = getOwner();\n const boundary = {\n id: key,\n rebuild: (): string | null => {\n const next = createTracker();\n const rebuilt = runWithOwner(owner, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: next.tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (next.count() > 0) {\n sink.defer(boundary);\n return null;\n }\n return escape((rebuilt as () => unknown)());\n },\n };\n sink.defer(boundary);\n // The markers delimit the region the stream later replaces; hydration strips them.\n return () => [\n ssrRaw(`<!--[b:${key}-->`),\n withScope(fallbackScope, () => props.fallback),\n ssrRaw(\"<!--]-->\"),\n ];\n}\n"],"mappings":"A,8cAwDA,SAASA,GAA0B,CAGjC,IAAMC,EAAU,IAAIC,EAAmB,EAAG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AK,QACZ,IAAI,UAAW,CACb,OAAOb,EAAM,QACf,CACF,CAAC,CACH,CACF,EAKA,OAJIa,EAAK,MAAM,EAAI,GACjBL,EAAK,MAAMZ,CAAQ,EACZ,MAEFmB,EAAQD,EAA0B,CAAC,CAC5C,CACF,EAGA,OAFAN,EAAK,MAAMZ,CAAQ,MAEN,CACXoB,EAAO,UAAUtB,EAAI,IAAI,EACzBQ,EAAUI,MAAqBN,EAAM,QAAQ,EAC7CgB,EAAO,UAAU,CACnB,CACF,C"}
|
package/dist/server/element.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ssrElement as
|
|
1
|
+
import{isTextOnlyElement as e}from"./server/raw-text.js";import{ssrElement as t,ssrRaw as n}from"./server/element.js";import"@shadow-js/core";const r=/^[a-z][a-z0-9-]*$/i;function i(i,a){if(!r.test(i)||i.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let o=a;return t(i,a,()=>{let t=o.children;return t===void 0||e(i)?t:[n(`<!--[-->`),t,n(`<!--]-->`)]},!0)}export{i as element};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|