@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,53 +1,61 @@
|
|
|
1
|
-
import "../internal/
|
|
1
|
+
import { warnOnce } from "../internal/diagnostics.js";
|
|
2
|
+
import { MATHML_NS, SVG_NS } from "../internal/names.js";
|
|
2
3
|
import { nextKey } from "../internal/hydration-scope.js";
|
|
3
4
|
import { createComponent } from "../component.js";
|
|
4
5
|
import { claims } from "../internal/hydration-hooks.js";
|
|
5
6
|
import { bindRegion, createRegion } from "../insert.js";
|
|
6
|
-
import {
|
|
7
|
+
import { spreadProps } from "../spread.js";
|
|
7
8
|
import { mergeProps, splitProps, untrack, useMemo } from "@shadow-js/core";
|
|
8
9
|
// src/control-flow/dynamic.ts
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
"
|
|
30
|
-
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
10
|
+
/**
|
|
11
|
+
* The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern
|
|
12
|
+
* rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,
|
|
13
|
+
* which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never
|
|
14
|
+
* asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).
|
|
15
|
+
*/
|
|
16
|
+
const SVG_PATTERN = /^(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,})$/;
|
|
17
|
+
/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */
|
|
18
|
+
const MATHML_TAGS = /^(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)?)$/;
|
|
19
|
+
/**
|
|
20
|
+
* Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in
|
|
21
|
+
* any letter case: it would bypass CSP nonces and Trusted Types.
|
|
22
|
+
*/
|
|
23
|
+
const TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;
|
|
24
|
+
/**
|
|
25
|
+
* Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace
|
|
26
|
+
* is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path="url(#...)"`, CSS and
|
|
27
|
+
* `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.
|
|
28
|
+
*/
|
|
29
|
+
function warnSvgCase(tag, lower) {
|
|
30
|
+
const canonical = "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".split(" ").find((name) => name.toLowerCase() === lower);
|
|
31
|
+
if (canonical === void 0 || canonical === tag) return;
|
|
32
|
+
warnOnce("DYNAMIC_SVG_CASE", `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}".`, lower);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an
|
|
36
|
+
* HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a
|
|
37
|
+
* custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is
|
|
38
|
+
* matched against the SVG names, and it keeps the spelling the caller wrote.
|
|
39
|
+
*/
|
|
40
|
+
function createTagged(tag) {
|
|
41
|
+
const lower = tag.toLowerCase();
|
|
42
|
+
if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);
|
|
43
|
+
const el = document.createElement(tag);
|
|
44
|
+
if (el.constructor !== HTMLUnknownElement && lower !== "image" || !SVG_PATTERN.test(lower)) return el;
|
|
45
|
+
warnSvgCase(tag, lower);
|
|
46
|
+
return document.createElementNS(SVG_NS, tag);
|
|
47
|
+
}
|
|
39
48
|
/**
|
|
40
49
|
* Creates an element for a validated tag name and applies the props to it, children included.
|
|
41
|
-
* The namespace comes from the tag: SVG-only names get the SVG namespace,
|
|
50
|
+
* The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the
|
|
51
|
+
* MathML namespace, the rest are HTML.
|
|
42
52
|
* On the server it renders the element as markup (with the hydration key and the children region
|
|
43
53
|
* the client adopts); while hydrating it claims that element instead of creating one.
|
|
44
54
|
*/
|
|
45
55
|
function buildElement(tag, props) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const el = claims.current.claimElement(nextKey()) ?? (svg ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag));
|
|
50
|
-
spread(el, props, svg, true);
|
|
56
|
+
if (!TAG_PATTERN.test(tag)) throw new TypeError("ShadowJS Dynamic: invalid tag");
|
|
57
|
+
const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);
|
|
58
|
+
spreadProps(el, props, el.namespaceURI === SVG_NS);
|
|
51
59
|
const region = createRegion(el, null, claims.current.takeRegion(el, null));
|
|
52
60
|
bindRegion(region, () => props.children);
|
|
53
61
|
return el;
|
|
@@ -70,8 +78,17 @@ function buildTarget(target, props) {
|
|
|
70
78
|
* `component` renders nothing.
|
|
71
79
|
*
|
|
72
80
|
* Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so
|
|
73
|
-
* data-driven tags cannot inject markup.
|
|
74
|
-
* in
|
|
81
|
+
* data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,
|
|
82
|
+
* `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not
|
|
83
|
+
* know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter
|
|
84
|
+
* primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a
|
|
85
|
+
* name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.
|
|
86
|
+
* The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG
|
|
87
|
+
* needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG
|
|
88
|
+
* spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.
|
|
89
|
+
* MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML
|
|
90
|
+
* namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent
|
|
91
|
+
* the element will be inserted into.
|
|
75
92
|
*
|
|
76
93
|
* @param props `component` and the props of what it renders.
|
|
77
94
|
* @returns An accessor of the rendered output, to be inserted by the caller.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":[],"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":";;;;;;;;;AAiCA,MAAM,2BAAgC,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,cAAc;;AAGpB,MAAM,8BAAmC,IAAI,IAAI,CAAC,QAAQ,CAAC;;;;;;;AAQ3D,SAAS,aAAa,KAAa,OAAwB;CACzD,MAAM,QAAQ,IAAI,YAAY;CAC9B,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,YAAY,IAAI,KAAK,GACjD,MAAM,IAAI,UAAoB,+BAAsD;CAkBtF,MAAM,MAAM,SAAS,IAAI,KAAK;CAE9B,MAAM,KADU,OAAO,QAAQ,aAAa,QAAQ,CACnC,MAAM,MAAM,SAAS,gBAAA,8BAAwB,GAAG,IAAI,SAAS,cAAc,GAAG;CAE/F,OAAO,IAAI,OAAO,KAAK,IAAI;CAC3B,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO,QAAQ,WAAW,IAAI,IAAI,CAAC;CACzE,WAAW,cAAe,MAAiC,QAAQ;CACnE,OAAO;AACT;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":[],"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":";;;;;;;;;;;;;;;AAuCA,MAAM,cACJ;;AAGF,MAAM,cACJ;;;;;AAMF,MAAM,cAAc;;;;;;AAOpB,SAAS,YAAY,KAAa,OAAqB;CACrD,MAAM,YACJ,+YACG,MAAM,GAAG,CAAC,CACV,MAAM,SAAS,KAAK,YAAY,MAAM,KAAK;CAChD,IAAI,cAAc,KAAA,KAAa,cAAc,KAAK;CAClD,SACE,oBACA,oCAAoC,IAAI,iDAAiD,UAAU,qCAAqC,IAAI,2CAA2C,UAAU,KACjM,KACF;AACF;;;;;;;AAQA,SAAS,aAAa,KAAsB;CAC1C,MAAM,QAAQ,IAAI,YAAY;CAC9B,IAAI,YAAY,KAAK,KAAK,GAAG,OAAO,SAAS,gBAAgB,WAAW,KAAK;CAC7E,MAAM,KAAK,SAAS,cAAc,GAAG;CAGrC,IAAK,GAAG,gBAAgB,sBAAsB,UAAU,WAAY,CAAC,YAAY,KAAK,KAAK,GACzF,OAAO;CAEI,YAAY,KAAK,KAAK;CACnC,OAAO,SAAS,gBAAgB,QAAQ,GAAG;AAC7C;;;;;;;;AASA,SAAS,aAAa,KAAa,OAAwB;CACzD,IAAI,CAAC,YAAY,KAAK,GAAG,GACvB,MAAM,IAAI,UAAoB,+BAAsD;CAkBtF,MAAM,KAAK,OAAO,QAAQ,aAAa,QAAQ,CAAC,KAAK,aAAa,GAAG;CAErE,YAAY,IAAI,OAAO,GAAG,iBAAiB,MAAM;CACjD,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO,QAAQ,WAAW,IAAI,IAAI,CAAC;CACzE,WAAW,cAAe,MAAiC,QAAQ;CACnE,OAAO;AACT;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
@@ -2,10 +2,10 @@ import { currentScope, withScope } from "../internal/hydration-scope.js";
|
|
|
2
2
|
import { attachHotModules, createHotLink } from "./hot-link.js";
|
|
3
3
|
import { rootErrorsOf } from "./root-errors.js";
|
|
4
4
|
import { catchError, createRoot, getOwner, onCleanup, untrack, useMemo, useSignal } from "@shadow-js/core";
|
|
5
|
-
import {
|
|
5
|
+
import { SignalNode, handleError, readSignal, writeSignal } from "@shadow-js/core/extend";
|
|
6
6
|
// src/control-flow/error-boundary.ts
|
|
7
7
|
function ErrorBoundary(props) {
|
|
8
|
-
const failureCell =
|
|
8
|
+
const failureCell = new SignalNode(void 0, Object.is);
|
|
9
9
|
/** Where an error of this boundary's own fallback goes: the boundary that encloses it. */
|
|
10
10
|
const parentOwner = getOwner();
|
|
11
11
|
const roots = rootErrorsOf(parentOwner);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-boundary.js","names":[],"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":";;;;;;AA0FA,SAAgB,cAAc,OAAmD;CAG/E,MAAM,cAAc,iBAAsC,KAAA,GAAW,OAAO,EAAE;;CAE9E,MAAM,cAAc,SAAS;CAE7B,MAAM,QAAQ,aAAa,WAAW;;CAEtC,MAAM,OAAO,aAAa;CAC1B,MAAM,SACJ,SAAS,OAAO,OAAO;EAAE,IAAI,KAAK;EAAI,OAAO,KAAK;EAAO,WAAW,KAAK;CAAU;CACrF,MAAM,gBAAqC,WAAW,WAAW;CACjE,MAAM,cAAc,SAAoC;EACtD,YAAY,aAAa,MAAM,EAAE,aAAa,KAAK,CAAC;CACtD;;CAEA,MAAM,CAAC,SAAS,cAAc,UAAU,GAAG,EAAE,QAAQ,MAAM,CAAC;;CAE5D,IAAI,QAAQ;;CAEZ,IAAI,OAAO;;CAEX,IAAI;CAEJ,MAAM,cAAoB;EACxB,IAAI,CAAC,OAAO;EACZ,WAAW,KAAA,CAAS;EACpB,YAAY,UAAU,QAAQ,CAAC;CACjC;;;;;CAMA,MAAM,MACF,oBAAoB;EAClB,MAAM;CACR,CAAC;CAGL,MAAM,UAAU,UAAyB;EACvC,IAAI,CAAC,OAAO;EACZ,OAAO,gBAAgB,KAAK;EAC5B,IAAI,MAAM;GACR,IAAI,YAAY,KAAA,GAAW,UAAU,EAAE,MAAM;GAC7C;EACF;EACA,WAAW,EAAE,MAAM,CAAC;CACtB;;CAGA,MAAM,oBAAyC;EAC7C,MAAM,WAAW;EACjB,UAAU,KAAA;EACV,OAAO;CACT;CAEA,MAAM,eAAe,UAA4B;EAC/C,MAAM,WAAW,MAAM;EACvB,IAAI,OAAO,aAAa,YAAY,OAAO;EAC3C,IAAI;GACF,OAAO,cACJ,SAA4D,OAAO,KAAK,CAC3E;EACF,SAAS,QAAQ;GAGf,YAAY,QAAQ,WAAW;GAC/B;EACF;CACF;;CAGA,MAAM,cAAuB;EAC3B,OAAO;EACP,IAAI;GACF,QAAQ;GACR,MAAM,UAAU,QAAQ,KAAK,YAAY;GACzC,IAAI,YAAY,KAAA,GAAW;IACzB,KAAK,IAAI;IACT,OAAO,YAAY,QAAQ,KAAK;GAClC;GAEA,KAAK,QAAQ,MAAM;GACnB,MAAM,QAAQ,YAAY,YAAY;IACpC,IAAI,QAAQ,KAAA,GAAW,iBAAiB,IAAI,OAAO;IACnD,OAAO;KACL;KACA,OAAO,iBAAiB,cAAc,MAAM,QAAQ,GAAG,MAAM;IAC/D;GACF,CAAC;GACD,MAAM,WAAW,YAAY;GAC7B,IAAI,aAAa,KAAA,GAAW;IAC1B,MAAM,QAAQ;IACd,KAAK,IAAI;IACT,OAAO,YAAY,SAAS,KAAK;GACnC;GACA,KAAK,OAAO;GACZ,OAAO,MAAM;EACf,UAAU;GAER,iBAAiB;IACf,gBAAgB;KACd,OAAO;IACT,CAAC;GACH,CAAC;GACD,OAAO;EACT;CAEF;CAIA,MAAM,OAAO,cACJ,WAAW,OAAO,MAAM,IAAI,UAAU,EAAE,GAAG,OAAO,GAAG,KAAK,GACjE,EAAE,aAAa,KAAK,CACtB;CAGA,iBAAiB;EACf,gBAAgB;GACd,QAAQ;GACR,KAAK,OAAO;EACd,CAAC;CACH,CAAC;CACD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"error-boundary.js","names":[],"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":";;;;;;AA0FA,SAAgB,cAAc,OAAmD;CAG/E,MAAM,cAAc,IAAI,WAAgC,KAAA,GAAW,OAAO,EAAE;;CAE5E,MAAM,cAAc,SAAS;CAE7B,MAAM,QAAQ,aAAa,WAAW;;CAEtC,MAAM,OAAO,aAAa;CAC1B,MAAM,SACJ,SAAS,OAAO,OAAO;EAAE,IAAI,KAAK;EAAI,OAAO,KAAK;EAAO,WAAW,KAAK;CAAU;CACrF,MAAM,gBAAqC,WAAW,WAAW;CACjE,MAAM,cAAc,SAAoC;EACtD,YAAY,aAAa,MAAM,EAAE,aAAa,KAAK,CAAC;CACtD;;CAEA,MAAM,CAAC,SAAS,cAAc,UAAU,GAAG,EAAE,QAAQ,MAAM,CAAC;;CAE5D,IAAI,QAAQ;;CAEZ,IAAI,OAAO;;CAEX,IAAI;CAEJ,MAAM,cAAoB;EACxB,IAAI,CAAC,OAAO;EACZ,WAAW,KAAA,CAAS;EACpB,YAAY,UAAU,QAAQ,CAAC;CACjC;;;;;CAMA,MAAM,MACF,oBAAoB;EAClB,MAAM;CACR,CAAC;CAGL,MAAM,UAAU,UAAyB;EACvC,IAAI,CAAC,OAAO;EACZ,OAAO,gBAAgB,KAAK;EAC5B,IAAI,MAAM;GACR,IAAI,YAAY,KAAA,GAAW,UAAU,EAAE,MAAM;GAC7C;EACF;EACA,WAAW,EAAE,MAAM,CAAC;CACtB;;CAGA,MAAM,oBAAyC;EAC7C,MAAM,WAAW;EACjB,UAAU,KAAA;EACV,OAAO;CACT;CAEA,MAAM,eAAe,UAA4B;EAC/C,MAAM,WAAW,MAAM;EACvB,IAAI,OAAO,aAAa,YAAY,OAAO;EAC3C,IAAI;GACF,OAAO,cACJ,SAA4D,OAAO,KAAK,CAC3E;EACF,SAAS,QAAQ;GAGf,YAAY,QAAQ,WAAW;GAC/B;EACF;CACF;;CAGA,MAAM,cAAuB;EAC3B,OAAO;EACP,IAAI;GACF,QAAQ;GACR,MAAM,UAAU,QAAQ,KAAK,YAAY;GACzC,IAAI,YAAY,KAAA,GAAW;IACzB,KAAK,IAAI;IACT,OAAO,YAAY,QAAQ,KAAK;GAClC;GAEA,KAAK,QAAQ,MAAM;GACnB,MAAM,QAAQ,YAAY,YAAY;IACpC,IAAI,QAAQ,KAAA,GAAW,iBAAiB,IAAI,OAAO;IACnD,OAAO;KACL;KACA,OAAO,iBAAiB,cAAc,MAAM,QAAQ,GAAG,MAAM;IAC/D;GACF,CAAC;GACD,MAAM,WAAW,YAAY;GAC7B,IAAI,aAAa,KAAA,GAAW;IAC1B,MAAM,QAAQ;IACd,KAAK,IAAI;IACT,OAAO,YAAY,SAAS,KAAK;GACnC;GACA,KAAK,OAAO;GACZ,OAAO,MAAM;EACf,UAAU;GAER,iBAAiB;IACf,gBAAgB;KACd,OAAO;IACT,CAAC;GACH,CAAC;GACD,OAAO;EACT;CAEF;CAIA,MAAM,OAAO,cACJ,WAAW,OAAO,MAAM,IAAI,UAAU,EAAE,GAAG,OAAO,GAAG,KAAK,GACjE,EAAE,aAAa,KAAK,CACtB;CAGA,iBAAiB;EACf,gBAAgB;GACd,QAAQ;GACR,KAAK,OAAO;EACd,CAAC;CACH,CAAC;CACD,OAAO;AACT"}
|
|
@@ -32,8 +32,8 @@ export interface PortalProps {
|
|
|
32
32
|
* Renders `children` into another part of the document, without a wrapper: the content nodes are
|
|
33
33
|
* inserted directly into the mount element (or its shadow root). Nothing is left at the call site.
|
|
34
34
|
* Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the
|
|
35
|
-
* mount stay. A reactive `mount` moves the content
|
|
36
|
-
* move.
|
|
35
|
+
* mount stay. A reactive `mount` moves the content: the children are built once, and
|
|
36
|
+
* their nodes and effects keep their identity while they move.
|
|
37
37
|
*
|
|
38
38
|
* On the server the content is rendered into the render's `portals` collector (see
|
|
39
39
|
* `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { childScope, nextKey, withScope } from "../internal/hydration-scope.js";
|
|
2
2
|
import { claims } from "../internal/hydration-hooks.js";
|
|
3
|
-
import { bindRegion, createRegion, removeRegion } from "../insert.js";
|
|
3
|
+
import { bindRegion, createRegion, moveRegion, removeRegion } from "../insert.js";
|
|
4
4
|
import { PortalContext } from "../internal/portal-context.js";
|
|
5
|
-
import {
|
|
6
|
-
import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from "@shadow-js/core";
|
|
5
|
+
import { createRoot, getOwner, isServer, onCleanup, runWithOwner, useContext, useRenderEffect } from "@shadow-js/core";
|
|
7
6
|
// src/control-flow/portal.ts
|
|
8
7
|
/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */
|
|
9
8
|
function appendMoved(target, node) {
|
|
@@ -23,8 +22,8 @@ function resolveMount(mount) {
|
|
|
23
22
|
* Renders `children` into another part of the document, without a wrapper: the content nodes are
|
|
24
23
|
* inserted directly into the mount element (or its shadow root). Nothing is left at the call site.
|
|
25
24
|
* Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the
|
|
26
|
-
* mount stay. A reactive `mount` moves the content
|
|
27
|
-
* move.
|
|
25
|
+
* mount stay. A reactive `mount` moves the content: the children are built once, and
|
|
26
|
+
* their nodes and effects keep their identity while they move.
|
|
28
27
|
*
|
|
29
28
|
* On the server the content is rendered into the render's `portals` collector (see
|
|
30
29
|
* `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates
|
|
@@ -58,9 +57,10 @@ function Portal(props) {
|
|
|
58
57
|
const key = nextKey();
|
|
59
58
|
const sink = useContext(PortalContext);
|
|
60
59
|
if (isServer || sink !== null) {
|
|
61
|
-
if (props.useShadow !== true)
|
|
60
|
+
if (props.useShadow !== true) sink?.render?.(key, () => props.children);
|
|
62
61
|
return null;
|
|
63
62
|
}
|
|
63
|
+
const owner = getOwner();
|
|
64
64
|
let mounted;
|
|
65
65
|
let warned = false;
|
|
66
66
|
let adopted = claims.current.claimPortal(key);
|
|
@@ -78,7 +78,7 @@ function Portal(props) {
|
|
|
78
78
|
return {
|
|
79
79
|
host,
|
|
80
80
|
region,
|
|
81
|
-
stopEffects: createRoot((dispose) => {
|
|
81
|
+
stopEffects: runWithOwner(owner, () => createRoot((dispose) => {
|
|
82
82
|
const bind = () => {
|
|
83
83
|
bindRegion(region, () => props.children);
|
|
84
84
|
};
|
|
@@ -86,10 +86,10 @@ function Portal(props) {
|
|
|
86
86
|
else if (mode === "claimed") withScope(childScope(key), bind);
|
|
87
87
|
else claims.current.withoutClaiming(() => withScope(childScope(key), bind));
|
|
88
88
|
return dispose;
|
|
89
|
-
})
|
|
89
|
+
}))
|
|
90
90
|
};
|
|
91
91
|
};
|
|
92
|
-
/**
|
|
92
|
+
/** Mounts the content in `target` the first time, and moves it there afterward. */
|
|
93
93
|
const moveTo = (target) => {
|
|
94
94
|
const previous = mounted;
|
|
95
95
|
if (previous === void 0) {
|
|
@@ -102,10 +102,12 @@ function Portal(props) {
|
|
|
102
102
|
mounted = mountInto(target, initial, mode);
|
|
103
103
|
return;
|
|
104
104
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
105
|
+
moveRegion(previous.region, target, (node) => appendMoved(target, node));
|
|
106
|
+
mounted = {
|
|
107
|
+
host: target,
|
|
108
|
+
region: previous.region,
|
|
109
|
+
stopEffects: previous.stopEffects
|
|
110
|
+
};
|
|
109
111
|
};
|
|
110
112
|
useRenderEffect(() => {
|
|
111
113
|
return {
|
|
@@ -115,6 +117,8 @@ function Portal(props) {
|
|
|
115
117
|
}, ({ host, shadow }) => {
|
|
116
118
|
if (host === null) {
|
|
117
119
|
unmount();
|
|
120
|
+
for (const node of adopted ?? []) node.parentNode?.removeChild(node);
|
|
121
|
+
adopted = void 0;
|
|
118
122
|
if (!warned) {
|
|
119
123
|
warned = true;
|
|
120
124
|
console.warn("[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"portal.js","names":[],"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":";;;;;;;;AAiEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,YACzD,OAAwB,WAAW,MAAM,IAAI;MAE7C,OAAO,YAAY,IAAI;AAE3B;;AAGA,SAAS,aAAa,MAA2B;CAC/C,OAAO,KAAK,cAAc,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC9D;;AAGA,SAAS,aAAa,OAA6C;CACjE,IAAI,UAAU,KAAA,GAAW,OAAO,SAAS;CAEzC,QADc,OAAO,UAAU,aAAa,MAAM,IAAI,UACtC;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,OAAO,OAA0B;CAI/C,MAAM,MAAM,QAAQ;CAGpB,MAAM,OAAO,WAAW,aAAa;CACrC,IAAI,YAAY,SAAS,MAAM;EAC7B,IAAI,MAAM,cAAc,MAAM,mBAAmB,WAAW,MAAM,UAAU,IAAI;EAChF,OAAO;CACT;CACA,IAAI;CACJ,IAAI,SAAS;CAEb,IAAI,UAA8B,OAAO,QAAQ,YAAY,GAAG;;CAGhE,MAAM,gBAAsB;EAC1B,MAAM,UAAU;EAChB,IAAI,YAAY,KAAA,GAAW;EAC3B,UAAU,KAAA;EACV,QAAQ,YAAY;EACpB,aAAa,QAAQ,MAAM;CAC7B;;CAGA,MAAM,aAAa,MAAY,SAAiB,SAA6B;EAC3E,MAAM,SAAS,aAAa,MAAM,MAAM,OAAO;EAU/C,OAAO;GAAE;GAAM;GAAQ,aATH,YAAY,YAAY;IAC1C,MAAM,aAAmB;KACvB,WAAW,cAAc,MAAM,QAAQ;IACzC;IACA,IAAI,SAAS,SAAS,KAAK;SACtB,IAAI,SAAS,WAAW,UAAU,WAAW,GAAG,GAAG,IAAI;SACvD,OAAO,QAAQ,sBAAsB,UAAU,WAAW,GAAG,GAAG,IAAI,CAAC;IAC1E,OAAO;GACT,CACiC;EAAE;CACrC;;CAGA,MAAM,UAAU,WAAuB;EACrC,MAAM,WAAW;EACjB,IAAI,aAAa,KAAA,GAAW;GAC1B,MAAM,UAAU,WAAW,CAAC;GAC5B,IAAI,OAAkB;GACtB,IAAI,YAAY,KAAA,GAAW,OAAO;QAC7B,IAAI,QAAQ,KAAA,KAAa,OAAO,QAAQ,WAAW,GAAG,OAAO;GAClE,UAAU,KAAA;GACV,KAAK,MAAM,QAAQ,SACjB,IAAI,KAAK,eAAe,QAAQ,YAAY,QAAQ,IAAI;GAE1D,UAAU,UAAU,QAAQ,SAAS,IAAI;GACzC;EACF;EACA,MAAM,QAAQ,SAAS,OAAO,MAAM,QAAQ,SAAS,KAAK,eAAe,SAAS,IAAI;EACtF,SAAS,YAAY;EACrB,KAAK,MAAM,QAAQ,OAAO,YAAY,QAAQ,IAAI;EAClD,UAAU,UAAU,QAAQ,OAAO,OAAO;CAC5C;CAEA,sBACQ;EAGJ,OAAO;GAAE,MAFI,aAAa,MAAM,KAEpB;GAAG,QADA,MAAM,cAAc;EACb;CACxB,IACC,EAAE,MAAM,aAAa;EACpB,IAAI,SAAS,MAAM;GACjB,QAAQ;GACR,IAAe,CAAC,QAAQ;IACtB,SAAS;IACT,QAAQ,KACN,kFACF;GACF;GACA;EACF;EACA,MAAM,SAAe,SAAS,aAAa,IAAI,IAAI;EACnD,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,QAAQ;EACtD,OAAO,MAAM;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"portal.js","names":[],"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":";;;;;;;AAyEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,YACzD,OAAwB,WAAW,MAAM,IAAI;MAE7C,OAAO,YAAY,IAAI;AAE3B;;AAGA,SAAS,aAAa,MAA2B;CAC/C,OAAO,KAAK,cAAc,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC9D;;AAGA,SAAS,aAAa,OAA6C;CACjE,IAAI,UAAU,KAAA,GAAW,OAAO,SAAS;CAEzC,QADc,OAAO,UAAU,aAAa,MAAM,IAAI,UACtC;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,OAAO,OAA0B;CAI/C,MAAM,MAAM,QAAQ;CAGpB,MAAM,OAAO,WAAW,aAAa;CACrC,IAAI,YAAY,SAAS,MAAM;EAC7B,IAAI,MAAM,cAAc,MAAM,MAAM,SAAS,WAAW,MAAM,QAAQ;EACtE,OAAO;CACT;CAGA,MAAM,QAAQ,SAAS;CACvB,IAAI;CACJ,IAAI,SAAS;CAEb,IAAI,UAA8B,OAAO,QAAQ,YAAY,GAAG;;CAGhE,MAAM,gBAAsB;EAC1B,MAAM,UAAU;EAChB,IAAI,YAAY,KAAA,GAAW;EAC3B,UAAU,KAAA;EACV,QAAQ,YAAY;EACpB,aAAa,QAAQ,MAAM;CAC7B;;CAGA,MAAM,aAAa,MAAY,SAAiB,SAA6B;EAC3E,MAAM,SAAS,aAAa,MAAM,MAAM,OAAO;EAY/C,OAAO;GAAE;GAAM;GAAQ,aAXH,aAAa,aAC/B,YAAY,YAAY;IACtB,MAAM,aAAmB;KACvB,WAAW,cAAc,MAAM,QAAQ;IACzC;IACA,IAAI,SAAS,SAAS,KAAK;SACtB,IAAI,SAAS,WAAW,UAAU,WAAW,GAAG,GAAG,IAAI;SACvD,OAAO,QAAQ,sBAAsB,UAAU,WAAW,GAAG,GAAG,IAAI,CAAC;IAC1E,OAAO;GACT,CAAC,CAE8B;EAAE;CACrC;;CAGA,MAAM,UAAU,WAAuB;EACrC,MAAM,WAAW;EACjB,IAAI,aAAa,KAAA,GAAW;GAC1B,MAAM,UAAU,WAAW,CAAC;GAC5B,IAAI,OAAkB;GACtB,IAAI,YAAY,KAAA,GAAW,OAAO;QAC7B,IAAI,QAAQ,KAAA,KAAa,OAAO,QAAQ,WAAW,GAAG,OAAO;GAClE,UAAU,KAAA;GACV,KAAK,MAAM,QAAQ,SACjB,IAAI,KAAK,eAAe,QAAQ,YAAY,QAAQ,IAAI;GAE1D,UAAU,UAAU,QAAQ,SAAS,IAAI;GACzC;EACF;EAGA,WAAW,SAAS,QAAQ,SAAS,SAAS,YAAY,QAAQ,IAAI,CAAC;EACvE,UAAU;GAAE,MAAM;GAAQ,QAAQ,SAAS;GAAQ,aAAa,SAAS;EAAY;CACvF;CAEA,sBACQ;EAGJ,OAAO;GAAE,MAFI,aAAa,MAAM,KAEpB;GAAG,QADA,MAAM,cAAc;EACb;CACxB,IACC,EAAE,MAAM,aAAa;EACpB,IAAI,SAAS,MAAM;GACjB,QAAQ;GAGR,KAAK,MAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,YAAY,YAAY,IAAI;GACnE,UAAU,KAAA;GACV,IAAe,CAAC,QAAQ;IACtB,SAAS;IACT,QAAQ,KACN,kFACF;GACF;GACA;EACF;EACA,MAAM,SAAe,SAAS,aAAa,IAAI,IAAI;EACnD,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,QAAQ;EACtD,OAAO,MAAM;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createContext, onCleanup, useContext } from "@shadow-js/core";
|
|
2
|
-
import {
|
|
2
|
+
import { SignalNode, readSignal, writeSignal } from "@shadow-js/core/extend";
|
|
3
3
|
// src/control-flow/suspense-list.ts
|
|
4
4
|
/** The enclosing list, or null. @internal */
|
|
5
5
|
const SuspenseListContext = /* @__PURE__ */ createContext(null, { name: "SuspenseList" });
|
|
@@ -40,7 +40,7 @@ const SuspenseListContext = /* @__PURE__ */ createContext(null, { name: "Suspens
|
|
|
40
40
|
* @since 1.0.0
|
|
41
41
|
*/
|
|
42
42
|
function SuspenseList(props) {
|
|
43
|
-
const changes =
|
|
43
|
+
const changes = new SignalNode(0, false);
|
|
44
44
|
const slots = [];
|
|
45
45
|
const touch = () => {
|
|
46
46
|
writeSignal(changes, 0, { allowInMemo: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suspense-list.js","names":[],"sources":["../../../src/control-flow/suspense-list.ts"],"sourcesContent":["import { type Accessor, type Context, createContext, onCleanup, useContext } from \"@shadow-js/core\";\nimport {
|
|
1
|
+
{"version":3,"file":"suspense-list.js","names":[],"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":";;;;AAkBA,MAAa,sBACK,8BAAwC,MAAM,EAAE,MAAM,eAAe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DxF,SAAgB,aAAa,OAA6C;CAExE,MAAM,UAAU,IAAI,WAAmB,GAAG,KAAK;CAC/C,MAAM,QAAkD,CAAC;CACzD,MAAM,cAAoB;EACxB,YAAY,SAAS,GAAG,EAAE,aAAa,KAAK,CAAC;CAC/C;CAmDA,OAAO,oBAAoB;EACzB,OAAO,EAjDP,SAAS,OAAO;GACd,MAAM,QAAQ,EAAE,MAAM;GACtB,MAAM,KAAK,KAAK;GAChB,MAAM;GACN,gBAAgB;IACd,MAAM,QAAQ,MAAM,QAAQ,KAAK;IACjC,IAAI,UAAU,IAAI,MAAM,OAAO,OAAO,CAAC;IACvC,MAAM;GACR,CAAC;GACD,MAAM,iBAAyB;IAC7B,WAAW,OAAO;IAClB,OAAO,MAAM,QAAQ,KAAK;GAC5B;GACA,MAAM,eAAwB;IAC5B,MAAM,QAAQ,SAAS;IACvB,IAAI,UAAU,IAAI,OAAO;IACzB,QAAQ,MAAM,aAAd;KACE,KAAK,YACH,OAAO,MAAM,OAAO,SAAS,KAAK,MAAM,CAAC;KAC3C,KAAK,YACH,OAAO,MAAM,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,OAAO,SAAS,KAAK,MAAM,CAAC;KAC/D,KAAK,aACH,OAAO,MAAM,MAAM,KAAK,CAAC,CAAC,OAAO,SAAS,KAAK,MAAM,CAAC;KACxD,SACE,OAAO,MAAM;IACjB;GACF;GACA,MAAM,qBAA8B;IAClC,IAAI,OAAO,GAAG,OAAO;IACrB,MAAM,QAAQ,MAAM;IAEpB,IAAI,EADe,UAAU,cAAc,UAAU,cACpC,OAAO;IACxB,IAAI,MAAM,SAAS,UAAU,OAAO;IACpC,IAAI,MAAM,SAAS,aAAa,OAAO;IAEvC,MAAM,QAAQ,SAAS;IACvB,MAAM,UAAU,UAAU,cAAc,CAAC,GAAG,KAAK,CAAC,CAAC,QAAQ,IAAI;IAC/D,MAAM,SAAS,UAAU,cAAc,MAAM,SAAS,IAAI,QAAQ;IAClE,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,GAAG;KAC1C,MAAM,YAAY,QAAQ;KAC1B,IAAI,cAAc,KAAA,KAAa,CAAC,UAAU,MAAM,GAAG,OAAO,MAAM;IAClE;IACA,OAAO;GACT;GACA,OAAO;IAAE;IAAQ;GAAa;EAChC,EAIW;EACX,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CAAC;AACH;;AAGA,SAAgB,eAAe,OAA+C;CAC5E,MAAM,OAAO,WAAW,mBAAmB;CAC3C,OAAO,SAAS,OAAO,OAAO,KAAK,SAAS,KAAK;AACnD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { childScope, nextKey, withScope } from "../internal/hydration-scope.js";
|
|
2
2
|
import { registerInList } from "./suspense-list.js";
|
|
3
3
|
import { SuspenseContext, runWithOwner, useMemo } from "@shadow-js/core";
|
|
4
|
-
import {
|
|
4
|
+
import { SignalNode, createOwner, readSignal, transitionHooks, writeSignal } from "@shadow-js/core/extend";
|
|
5
5
|
// src/control-flow/suspense.ts
|
|
6
6
|
/**
|
|
7
7
|
* A counter the resources of one boundary report to (see {@link SuspenseTracker}), and the hold a
|
|
@@ -10,7 +10,7 @@ import { createOwner, createSignalNode, readSignal, transitionHooks, writeSignal
|
|
|
10
10
|
* keeps its content, and the readers run again when the count returns to zero.
|
|
11
11
|
*/
|
|
12
12
|
function createTracker() {
|
|
13
|
-
const pending =
|
|
13
|
+
const pending = new SignalNode(0, Object.is);
|
|
14
14
|
let hold;
|
|
15
15
|
let shown = false;
|
|
16
16
|
const adjust = (by) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suspense.js","names":[],"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
|
|
1
|
+
{"version":3,"file":"suspense.js","names":[],"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":";;;;;;;;;;;AAwDA,SAAS,gBAA0B;CAGjC,MAAM,UAAU,IAAI,WAAmB,GAAG,OAAO,EAAE;CAInD,IAAI;CACJ,IAAI,QAAQ;CACZ,MAAM,UAAU,OAAqB;EACnC,YAAY,SAAS,QAAQ,QAAQ,IAAI,EAAE,aAAa,KAAK,CAAC;CAChE;CAaA,OAAO;EACL,SAAA;GAZA,iBAAiB,OAAO,CAAC;GACzB,iBAAiB;IACf,OAAO,EAAE;IACT,IAAI,QAAQ,UAAU,GAAG,MAAM,QAAQ;GACzC;GACA,YAAqB;IACnB,IAAI,CAAC,OAAO,OAAO;IACnB,SAAS,gBAAgB,CAAC,EAAE,aAAa;IACzC,OAAO,MAAM,OAAO,MAAM;GAC5B;EAGM;EACN,aAAa,WAAW,OAAO;EAC/B,eAAe,MAAM,QAAQ,MAAM;EACnC,gBAAgB;GACd,QAAQ;EACV;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,SAAS,OAAyC;CAChE,MAAM,MAAM,QAAQ;CACpB,MAAM,EAAE,SAAS,OAAO,SAAS,aAAa,cAAc;CAI5D,MAAM,OAA2B,qBAAqB,MAAM,MAAM,CAAC;CACnE,MAAM,WAAW,YAAY;CAC7B,SAAS,aAAa,MAAM,IAAI,KAAM,SAAS,QAAQ,CAAC,KAAK,OAAO;CACpE,MAAM,UAAU,aAAa,gBAC3B,UAAU,WAAW,GAAG,SACtB,gBAAgB;EACd,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CAAC,CACH,CACF;CAEA,MAAM,gBAAgB,WAAW,QAAQ,KAAA,IAAY,KAAA,IAAY,GAAG,IAAI,EAAE;CAC1E,OAAO,SACJ,aAAa;EAEZ,MAAM;EAEN,IAAI,QAAQ,KAAK,aAAa,KAAA,GAAW,OAAO;EAChD,IAAI,SAAS,MAAM;GACjB,IAAI,MAAM,IAAI,GAAG,OAAO,UAAU,qBAAqB,MAAM,QAAQ;GACrE,SAAS;GACT,OAAQ,QAA0B;EACpC;EACA,IAAI,MAAM,MAAM,KAAK,KAAK,OAAO,GAAG;GAClC,SAAS;GACT,OAAQ,QAA0B;EACpC;EACA,OAAO,KAAK,aAAa,IAAI,UAAU,qBAAqB,MAAM,QAAQ,IAAI;CAChF,GACA,EAAE,aAAa,KAAK,CACtB;AACF"}
|
package/dist/dev/element.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { setAttribute } from "./attributes.js";
|
|
1
|
+
import { setAttribute, setBoolAttribute } from "./attributes.js";
|
|
2
2
|
import { style } from "./class-style.js";
|
|
3
3
|
import { nextKey } from "./internal/hydration-scope.js";
|
|
4
4
|
import { checkClaimedTag } from "./internal/claim.js";
|
|
5
5
|
import { claims } from "./internal/hydration-hooks.js";
|
|
6
6
|
import { insert } from "./insert.js";
|
|
7
|
+
import { isFlagAttribute } from "./internal/react-names.js";
|
|
7
8
|
import { batch, untrack, useRenderEffect } from "@shadow-js/core";
|
|
8
9
|
// src/element.ts
|
|
9
10
|
/**
|
|
@@ -91,11 +92,13 @@ function element(tag, props) {
|
|
|
91
92
|
applied = style(el, value, applied);
|
|
92
93
|
});
|
|
93
94
|
} else useRenderEffect(() => read[key], (value) => {
|
|
94
|
-
|
|
95
|
+
const name = key.toLowerCase();
|
|
96
|
+
if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);
|
|
97
|
+
else setAttribute(el, key, value);
|
|
95
98
|
});
|
|
96
99
|
}
|
|
97
100
|
const ref = read["ref"];
|
|
98
|
-
if (typeof ref === "function") ref(el);
|
|
101
|
+
if (typeof ref === "function") untrack(() => ref(el));
|
|
99
102
|
insert(el, () => read["children"]);
|
|
100
103
|
return el;
|
|
101
104
|
}
|
package/dist/dev/element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n
|
|
1
|
+
{"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setBoolAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { isFlagAttribute } from \"./internal/react-names\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\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 claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n const event = eventNameOf(key);\n if (event !== undefined) {\n bindListener(el, event, read[key]);\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n // The server writes a boolean attribute by truthiness; the client does the same. A name\n // that is a flag has no React spelling, so lower case is its attribute name.\n const name = key.toLowerCase();\n if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);\n else setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,MAAM,cAAc;;AAGpB,SAAS,YAAY,KAAiC;CACpD,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI,KAAK,SAAS,KAAK,IAAI,OAAO,CAAC,CAAC,IACxE,IAAI,MAAM,CAAC,CAAC,CAAC,YAAY,IACzB,KAAA;AACN;;;;;;AAOA,SAAS,aAAa,IAAa,MAAc,SAAwB;CACvE,IAAI;CACJ,IAAI,OAAO,YAAY,YACrB,QAAQ,UAA0B,QAAQ,KAAK,IAAI,KAAK;MACnD,IAAI,MAAM,QAAQ,OAAO,GAAG;EACjC,MAAM,CAAC,IAAI,QAAQ;EACnB,IAAI,OAAO,OAAO,YAAY,QAAQ,UAA0B,GAAG,KAAK,IAAI,MAAM,KAAK;CACzF;CACA,IAAI,SAAS,KAAA,GAAW;CACxB,MAAM,MAAM;CACZ,GAAG,iBAAiB,OAAO,UAAuB;EAChD,YAAY,cAAc,IAAI,KAAK,CAAC,CAAC;CACvC,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAeb,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;CACrD,IAAI,YAAY,QAAA,MAAiB,gBAAgB,SAAS,GAAG;CAC7D,MAAM,KAAK,WAAW,SAAS,cAAc,GAAG;CAChD,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;EACpC,IAAI,QAAQ,cAAc,QAAQ,OAAO;EACzC,MAAM,QAAQ,YAAY,GAAG;EAC7B,IAAI,UAAU,KAAA,GACZ,aAAa,IAAI,OAAO,KAAK,IAAI;OAC5B,IAAI,QAAQ,SAAS;GAE1B,IAAI;GACJ,sBACQ,KAAK,OACV,UAAU;IACT,UAAU,MAAM,IAAmB,OAAO,OAAO;GACnD,CACF;EACF,OACE,sBACQ,KAAK,OACV,UAAU;GAGT,MAAM,OAAO,IAAI,YAAY;GAC7B,IAAI,gBAAgB,MAAM,KAAK,GAAG,iBAAiB,IAAI,MAAM,KAAK;QAC7D,aAAa,IAAI,KAAK,KAAK;EAClC,CACF;CAEJ;CACA,MAAM,MAAM,KAAK;CACjB,IAAI,OAAO,QAAQ,YAAY,cAAc,IAAI,EAAE,CAAC;CACpD,OAAO,UAAU,KAAK,WAAW;CACjC,OAAO;AACT"}
|