@shadow-js/web 1.0.2 → 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 +14 -0
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +10 -5
- package/dist/dev/class-style.js +47 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +2 -2
- 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 +15 -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 +5 -2
- package/dist/dev/element.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 +11 -0
- package/dist/dev/insert.js +50 -33
- 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.js +0 -1
- 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/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +22 -12
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +4 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/server/attributes.js +1 -31
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +5 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/index.js +1 -1
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/render.js +1 -1
- package/dist/dev/server/stream.js +1 -1
- package/dist/dev/server.js +1 -1
- package/dist/dev/spread.js +49 -27
- 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/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/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/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/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/render.js +1 -1
- package/dist/prod/server/stream.js +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.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.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/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/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/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/render.js +1 -1
- package/dist/server/server/stream.js +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.map +1 -1
- package/dist/server-dev/class-style.js +47 -47
- package/dist/server-dev/class-style.js.map +1 -1
- 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 +15 -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.map +1 -1
- package/dist/server-dev/extend.js +2 -2
- package/dist/server-dev/insert.js +50 -33
- 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 +0 -1
- 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/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +22 -12
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/attributes.js +1 -31
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +5 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/index.js +1 -1
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/render.js +1 -1
- package/dist/server-dev/server/stream.js +1 -1
- package/dist/server-dev/server.js +1 -1
- package/dist/server-dev/spread.js +35 -26
- 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 +3 -3
|
@@ -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 // 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":";;;;;;;;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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,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;GA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AO;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,OA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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,7 +92,9 @@ 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"];
|
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\";\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 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":"
|
|
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"}
|
package/dist/dev/extend.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isUnsafeUrlAttribute } from "./attributes.js";
|
|
2
2
|
import { element } from "./element.js";
|
|
3
|
-
import { Region, bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
3
|
+
import { Region, bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
|
|
4
4
|
import { claimElement, claimPortal, isClaiming, takeRegion, withoutClaiming } from "./internal/claim.js";
|
|
5
5
|
import { WebWarningCode, warnOnce } from "./internal/diagnostics.js";
|
|
6
6
|
import { Claims, claims } from "./internal/hydration-hooks.js";
|
|
@@ -9,4 +9,4 @@ import { HTML_NS, MATHML_NS, SVG_NS } from "./internal/names.js";
|
|
|
9
9
|
import { PortalContext, PortalSink } from "./internal/portal-context.js";
|
|
10
10
|
import { reconcileNodes } from "./internal/reconcile.js";
|
|
11
11
|
import { StreamBoundary, StreamContext, StreamSink } from "./internal/stream-context.js";
|
|
12
|
-
export { type Claims, HTML_NS, type HydrationScope, MATHML_NS, PortalContext, type PortalSink, type Region, SVG_NS, type StreamBoundary, StreamContext, type StreamSink, type WebWarningCode, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
|
12
|
+
export { type Claims, HTML_NS, type HydrationScope, MATHML_NS, PortalContext, type PortalSink, type Region, SVG_NS, type StreamBoundary, StreamContext, type StreamSink, type WebWarningCode, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, moveRegion, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
package/dist/dev/extend.js
CHANGED
|
@@ -5,8 +5,8 @@ import { childScope, createRootScope, currentScope, enterComponent, nextKey, res
|
|
|
5
5
|
import { claimElement, claimPortal, isClaiming, takeRegion, withoutClaiming } from "./internal/claim.js";
|
|
6
6
|
import { claims } from "./internal/hydration-hooks.js";
|
|
7
7
|
import { reconcileNodes } from "./internal/reconcile.js";
|
|
8
|
-
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
8
|
+
import { bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
|
|
9
9
|
import { element } from "./element.js";
|
|
10
10
|
import { PortalContext } from "./internal/portal-context.js";
|
|
11
11
|
import { StreamContext } from "./internal/stream-context.js";
|
|
12
|
-
export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
|
12
|
+
export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, moveRegion, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
package/dist/dev/insert.d.ts
CHANGED
|
@@ -40,6 +40,17 @@ export declare function createRegion(parent: Node, anchorNode: Node | null, init
|
|
|
40
40
|
* @internal
|
|
41
41
|
*/
|
|
42
42
|
export declare function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown;
|
|
43
|
+
/**
|
|
44
|
+
* Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts
|
|
45
|
+
* each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so
|
|
46
|
+
* what it shows is not built again. Only for a region without an anchor.
|
|
47
|
+
* @param region The region to move.
|
|
48
|
+
* @param parent The node that receives the region's nodes.
|
|
49
|
+
* @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).
|
|
50
|
+
* @since 1.0.3
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
export declare function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void;
|
|
43
54
|
/**
|
|
44
55
|
* Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not
|
|
45
56
|
* touched.
|
package/dist/dev/insert.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
+
import { leaves } from "./internal/accessor.js";
|
|
1
2
|
import { checkClaimedText } from "./internal/claim.js";
|
|
2
3
|
import { claims } from "./internal/hydration-hooks.js";
|
|
3
4
|
import { reconcileNodes } from "./internal/reconcile.js";
|
|
4
|
-
import { useRenderEffect } from "@shadow-js/core";
|
|
5
|
+
import { onCleanup, useRenderEffect } from "@shadow-js/core";
|
|
5
6
|
import { addCleanup, createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
|
|
6
7
|
// src/insert.ts
|
|
7
|
-
/** Longest chain of accessors a single value may hold (a function returning a function ...). */
|
|
8
|
-
const MAX_ACCESSOR_DEPTH = 1e4;
|
|
9
8
|
/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */
|
|
10
9
|
const tails = /* @__PURE__ */ new WeakMap();
|
|
11
10
|
/** The document a node belongs to (a Document is its own document). */
|
|
@@ -34,39 +33,23 @@ function pruneTexts(region, keep) {
|
|
|
34
33
|
} else if (!keep.includes(texts)) region.texts = null;
|
|
35
34
|
}
|
|
36
35
|
/**
|
|
36
|
+
* The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect
|
|
37
|
+
* that runs again flattens the same fragment value once more: it must still give those nodes.
|
|
38
|
+
*/
|
|
39
|
+
const fragmentChildren = /* @__PURE__ */ new WeakMap();
|
|
40
|
+
/**
|
|
37
41
|
* Flattens a value into parts without recursion. Functions are called (and their results unwrapped)
|
|
38
42
|
* through `call`, which runs inside the render effect that owns the value, so reads are tracked.
|
|
39
43
|
*/
|
|
40
|
-
function flatten(root, call
|
|
44
|
+
function flatten(root, call) {
|
|
41
45
|
const parts = [];
|
|
42
|
-
const
|
|
43
|
-
const cursors = [0];
|
|
44
|
-
const active = /* @__PURE__ */ new Set();
|
|
45
|
-
while (frames.length > 0) {
|
|
46
|
-
const top = frames.length - 1;
|
|
47
|
-
const frame = frames[top];
|
|
48
|
-
const cursor = cursors[top] ?? 0;
|
|
49
|
-
if (frame === void 0 || cursor >= frame.length) {
|
|
50
|
-
const done = frames.pop();
|
|
51
|
-
if (done !== void 0) active.delete(done);
|
|
52
|
-
cursors.pop();
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
cursors[top] = cursor + 1;
|
|
56
|
-
let item = frame[cursor];
|
|
57
|
-
for (let depth = 0; typeof item === "function"; depth += 1) {
|
|
58
|
-
if (depth >= MAX_ACCESSOR_DEPTH) throw new TypeError("insert(): accessor chain is too deep.");
|
|
59
|
-
item = call(item);
|
|
60
|
-
}
|
|
46
|
+
for (const item of leaves(root, "insert(): a value contains itself.", call)) {
|
|
61
47
|
if (item === null || item === void 0 || typeof item === "boolean") continue;
|
|
62
|
-
if (item instanceof DocumentFragment)
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
frames.push(item);
|
|
68
|
-
cursors.push(0);
|
|
69
|
-
} else parts.push(String(item));
|
|
48
|
+
if (item instanceof DocumentFragment) {
|
|
49
|
+
const kids = fragmentChildren.get(item) ?? [...item.childNodes];
|
|
50
|
+
fragmentChildren.set(item, kids);
|
|
51
|
+
for (const child of kids) parts.push(child);
|
|
52
|
+
} else parts.push(item instanceof Node ? item : String(item));
|
|
70
53
|
}
|
|
71
54
|
return parts;
|
|
72
55
|
}
|
|
@@ -122,6 +105,21 @@ function endOf(region, last) {
|
|
|
122
105
|
if (marker.parentNode !== region.parent) return null;
|
|
123
106
|
return marker.nextSibling;
|
|
124
107
|
}
|
|
108
|
+
/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */
|
|
109
|
+
const commitWatchers = /* @__PURE__ */ new WeakMap();
|
|
110
|
+
/**
|
|
111
|
+
* Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the
|
|
112
|
+
* parent holds (a name on the first element of a content region) can follow a change of content.
|
|
113
|
+
* The watch ends with the owner that is current when this is called.
|
|
114
|
+
* @internal
|
|
115
|
+
*/
|
|
116
|
+
function watchCommits(parent, run) {
|
|
117
|
+
const set = commitWatchers.get(parent) ?? /* @__PURE__ */ new Set();
|
|
118
|
+
commitWatchers.set(parent, set.add(run));
|
|
119
|
+
onCleanup(() => {
|
|
120
|
+
set.delete(run);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
125
123
|
/** Makes the DOM show `next` for this region. */
|
|
126
124
|
function reconcileRegion(region, next) {
|
|
127
125
|
const parent = region.parent;
|
|
@@ -132,6 +130,9 @@ function reconcileRegion(region, next) {
|
|
|
132
130
|
reconcileNodes(parent, attached, next, end);
|
|
133
131
|
region.nodes = next;
|
|
134
132
|
pruneTexts(region, next);
|
|
133
|
+
commitWatchers.get(parent)?.forEach((run) => {
|
|
134
|
+
run();
|
|
135
|
+
});
|
|
135
136
|
}
|
|
136
137
|
/** Applies a flattened value to a region. */
|
|
137
138
|
function commit(region, parts) {
|
|
@@ -223,7 +224,7 @@ function containsFunction(root) {
|
|
|
223
224
|
const stack = [root];
|
|
224
225
|
const seen = /* @__PURE__ */ new Set([root]);
|
|
225
226
|
while (stack.length > 0) {
|
|
226
|
-
const frame = stack.pop()
|
|
227
|
+
const frame = stack.pop();
|
|
227
228
|
for (const item of frame) {
|
|
228
229
|
if (typeof item === "function") return true;
|
|
229
230
|
if (Array.isArray(item) && !seen.has(item)) {
|
|
@@ -301,6 +302,22 @@ function bindRegion(region, value, ordered) {
|
|
|
301
302
|
return latest;
|
|
302
303
|
}
|
|
303
304
|
/**
|
|
305
|
+
* Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts
|
|
306
|
+
* each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so
|
|
307
|
+
* what it shows is not built again. Only for a region without an anchor.
|
|
308
|
+
* @param region The region to move.
|
|
309
|
+
* @param parent The node that receives the region's nodes.
|
|
310
|
+
* @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).
|
|
311
|
+
* @since 1.0.3
|
|
312
|
+
* @internal
|
|
313
|
+
*/
|
|
314
|
+
function moveRegion(region, parent, move) {
|
|
315
|
+
const attached = region.nodes.filter((node) => node.parentNode === region.parent);
|
|
316
|
+
for (const node of attached) move(node);
|
|
317
|
+
region.parent = parent;
|
|
318
|
+
region.marker = attached[0]?.previousSibling ?? parent.lastChild;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
304
321
|
* Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not
|
|
305
322
|
* touched.
|
|
306
323
|
* @internal
|
|
@@ -373,6 +390,6 @@ function insert(parent, value, anchorNode, initial) {
|
|
|
373
390
|
const resolvedAnchor = anchorNode ?? null;
|
|
374
391
|
return bindRegion(createRegion(parent, resolvedAnchor, initial === void 0 ? claims.current.takeRegion(parent, resolvedAnchor) : initial), value, resolvedAnchor === null);
|
|
375
392
|
}
|
|
376
|
-
export { anchor, bindRegion, createRegion, insert, removeRegion };
|
|
393
|
+
export { anchor, bindRegion, createRegion, insert, moveRegion, removeRegion, watchCommits };
|
|
377
394
|
|
|
378
395
|
//# sourceMappingURL=insert.js.map
|
package/dist/dev/insert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call: (fn: () => unknown) => unknown = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() ?? [];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;AAkBA,MAAM,qBAAqB;;AA+B3B,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,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AIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
|
|
1
|
+
{"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n for (const node of attached) move(node);\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;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,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/internal/accessor.ts
|
|
2
|
+
/** Longest chain of accessors a single value may hold (a function returning a function ...). */
|
|
3
|
+
const MAX_ACCESSOR_DEPTH = 1e4;
|
|
4
|
+
/**
|
|
5
|
+
* Calls `value` while it is a function, so an accessor that returns an accessor is followed to the
|
|
6
|
+
* value at its end. `call` runs each function (default: a plain call); `insert` passes one that
|
|
7
|
+
* memoizes. Class and style values use the default, inside the effect that applies them, so the
|
|
8
|
+
* signals an accessor reads are tracked by it.
|
|
9
|
+
* @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
function unwrap(value, call = (fn) => fn()) {
|
|
13
|
+
for (let depth = 0; typeof value === "function"; depth += 1) {
|
|
14
|
+
if (depth >= MAX_ACCESSOR_DEPTH) throw new TypeError("An accessor returns accessors more than 10,000 levels deep.");
|
|
15
|
+
value = call(value);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is
|
|
21
|
+
* the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.
|
|
22
|
+
* `insert` and the class writer share it.
|
|
23
|
+
* @param root The value; an array is entered, any other value is a leaf.
|
|
24
|
+
* @param cycle The message of the `TypeError` thrown when an array contains itself.
|
|
25
|
+
* @param call Passed to {@link unwrap}.
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
function leaves(root, cycle, call) {
|
|
29
|
+
const found = [];
|
|
30
|
+
const frames = [[root]];
|
|
31
|
+
const cursors = [0];
|
|
32
|
+
const active = /* @__PURE__ */ new Set();
|
|
33
|
+
while (frames.length > 0) {
|
|
34
|
+
const top = frames.length - 1;
|
|
35
|
+
const frame = frames[top];
|
|
36
|
+
const cursor = cursors[top];
|
|
37
|
+
if (cursor >= frame.length) {
|
|
38
|
+
active.delete(frames.pop());
|
|
39
|
+
cursors.pop();
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
cursors[top] = cursor + 1;
|
|
43
|
+
const item = unwrap(frame[cursor], call);
|
|
44
|
+
if (!Array.isArray(item)) found.push(item);
|
|
45
|
+
else if (active.has(item)) throw new TypeError(cycle);
|
|
46
|
+
else {
|
|
47
|
+
active.add(item);
|
|
48
|
+
frames.push(item);
|
|
49
|
+
cursors.push(0);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return found;
|
|
53
|
+
}
|
|
54
|
+
export { leaves, unwrap };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=accessor.js.map
|