|
| 1 | +import { onCleanup, untrack, type Setter } from "@solidjs/signals"; |
| 2 | +import type { Element as SolidElement } from "../types.js"; |
| 3 | +import type { Component, ComponentProps } from "./component.js"; |
| 4 | +import { $DEVCOMP, IS_DEV } from "./core.js"; |
| 5 | +import { createMemo, createSignal, sharedConfig } from "./hydration.js"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Options for `dynamicComponent` (and for `@solidjs/web`'s `dynamic`, which |
| 9 | + * passes them through to the same core). |
| 10 | + */ |
| 11 | +export interface DynamicOptions { |
| 12 | + /** |
| 13 | + * SSR only: hold the document's first flush until the source settles, so |
| 14 | + * the resolved component renders into the shell instead of streaming in |
| 15 | + * behind its boundary's fallback. Same meaning as `createMemo`'s |
| 16 | + * `deferStream`. Default `false` — a source is data of unknown cost and |
| 17 | + * streams by default. Ignored on the client. |
| 18 | + */ |
| 19 | + deferStream?: boolean; |
| 20 | + /** |
| 21 | + * The source cannot change: call it once, untracked, now, and render the |
| 22 | + * result with no computation per instance. The source must resolve |
| 23 | + * synchronously. |
| 24 | + */ |
| 25 | + static?: boolean; |
| 26 | +} |
| 27 | + |
| 28 | +// The server-component transport's binding contract (`Symbol.for`, so no |
| 29 | +// import ties this entry to the frames transport): a value the transport |
| 30 | +// resolved carries `{ component, address }` — `component` is the MOUNT |
| 31 | +// identity, one per server function; `address` names the call's content |
| 32 | +// store. Same component across resolutions means "same instance, new |
| 33 | +// binding". See frames/src/frame-transport.ts (COMPONENT_BINDING). |
| 34 | +const COMPONENT_BINDING = /*#__PURE__*/ Symbol.for("solid.component-binding"); |
| 35 | +// The box a factory memo holds a thenable source answer in, so the factory |
| 36 | +// stays sync-valued and the per-instance memo is the one that goes async |
| 37 | +// (and, under hydration, adopts the server's record). Module-local. |
| 38 | +const FLIGHT = /*#__PURE__*/ Symbol("solid.dynamic-flight"); |
| 39 | + |
| 40 | +function bindingOf(value: any): { component: Function; address: string } | undefined { |
| 41 | + // Nullish has no properties; every other value boxes. A missing brand is |
| 42 | + // undefined, and a falsy brand is not a binding. |
| 43 | + return value?.[COMPONENT_BINDING] || undefined; |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * How a tag name a source resolved to becomes an element. Renderers pass |
| 48 | + * one (`dynamic` passes `staticElement` / `ssrElement`); `dynamicComponent` |
| 49 | + * passes nothing, and a string then renders nothing. The core never names |
| 50 | + * the element runtime, so a bundle that only uses `dynamicComponent` drops |
| 51 | + * it. |
| 52 | + */ |
| 53 | +type TagArm = (tag: string, props: any) => any; |
| 54 | + |
| 55 | +/** |
| 56 | + * Shared implementation behind `dynamicComponent` and a renderer's `dynamic`. |
| 57 | + * The tag arm is the only DOM/SSR-specific part. Not application API — |
| 58 | + * `@internal`, read back through `solid-js/internal`. |
| 59 | + * |
| 60 | + * @internal |
| 61 | + */ |
| 62 | +export function dynamicCore( |
| 63 | + source: () => any, |
| 64 | + options?: DynamicOptions, |
| 65 | + tagArm?: TagArm |
| 66 | +): Component<any> { |
| 67 | + if (options?.static) return staticDynamic(untrack(source), tagArm); |
| 68 | + // `prev` threads into the resolution so a source switching server-component |
| 69 | + // calls of the same function DELIVERS instead of swapping: the memo keeps |
| 70 | + // its previous value (the mount below never re-renders) and the new call's |
| 71 | + // address flows into the live accessor the instance mounted with — the |
| 72 | + // instance re-binds its frame's pull to the new address's store (warm |
| 73 | + // store re-materializes instantly; an in-flight stream morphs in; keyed |
| 74 | + // slot state survives). Everything else resolves to `next` and swaps. |
| 75 | + // Async resolutions run the delivery in the promise chain — an ownerless |
| 76 | + // microtask, exactly where frame writes already happen — and not in the |
| 77 | + // equals gate: a kept resolution hands the memo `prev`, so the gate never |
| 78 | + // sees the new address at all. |
| 79 | + // Live delivery channels, one per mounted site: this component may be |
| 80 | + // mounted more than once (each mount is its own instance with its own |
| 81 | + // address accessor), and a kept resolution must reach every one. |
| 82 | + const sites = new Set<Setter<string>>(); |
| 83 | + // The latest resolution's address, tracked at THIS level because a kept |
| 84 | + // resolution returns `prev` — a binding whose `.address` is frozen at the |
| 85 | + // first resolution — and `sites` only reaches mounts that exist right now. |
| 86 | + // A site mounting AFTER a delivery (unmount → remount over the same |
| 87 | + // dynamic, the turnkey away/back cycle) must initialize from the latest |
| 88 | + // delivered address, not the kept binding's original one: initializing |
| 89 | + // stale binds the fresh mount to the first call's resident store (the SSR |
| 90 | + // payload) while the refetched response warms a store nothing reads. |
| 91 | + let deliveredAddress: string | undefined; |
| 92 | + const resolveBinding = (next: any, prev: any) => { |
| 93 | + const binding = bindingOf(next); |
| 94 | + if (!binding) return next; |
| 95 | + deliveredAddress = binding.address; |
| 96 | + const prevBinding = bindingOf(prev); |
| 97 | + if (prevBinding && prevBinding.component === binding.component) { |
| 98 | + for (const deliver of sites) deliver(binding.address); |
| 99 | + return prev; |
| 100 | + } |
| 101 | + return next; |
| 102 | + }; |
| 103 | + // The same rule at the memo's gate, for values the compute never sees: an |
| 104 | + // async iterable's yields land straight from the pump (a `live` server |
| 105 | + // component's loop re-yields its binding per connection, and the first |
| 106 | + // connection after hydration resolves the per-address binding where the |
| 107 | + // document adopted the per-function placeholder — two objects, one |
| 108 | + // component, one address). Same component is the same instance: equal, |
| 109 | + // with the incoming address delivered when it is not the one showing. |
| 110 | + // The comparator is `(prev, next)` on every commit path: `prev` is what |
| 111 | + // the memo HOLDS — the first resolution, kept ever since, whose address |
| 112 | + // the deliveries have long moved past — so only `next` says anything |
| 113 | + // about where the instance should be. (Reading "the address that is not |
| 114 | + // the delivered one" as incoming swung a reconnect's re-yield back to |
| 115 | + // the document's call after the source had switched arguments.) With |
| 116 | + // nothing delivered (no site mounted) a differing address is a plain |
| 117 | + // change — nothing is kept, so nothing is lost by swapping. |
| 118 | + const sameInstance = (prev: any, next: any) => { |
| 119 | + if (prev === next) return true; |
| 120 | + const held = bindingOf(prev); |
| 121 | + const incoming = bindingOf(next); |
| 122 | + if (!held || !incoming || held.component !== incoming.component) return false; |
| 123 | + if (held.address === incoming.address) return true; |
| 124 | + if (deliveredAddress === undefined) return false; |
| 125 | + if (incoming.address !== deliveredAddress) { |
| 126 | + deliveredAddress = incoming.address; |
| 127 | + for (const deliver of sites) deliver(incoming.address); |
| 128 | + } |
| 129 | + return true; |
| 130 | + }; |
| 131 | + // Three memos, the same owner shape as the server's `dynamic` so hydration |
| 132 | + // ids agree (the server core has the full account): |
| 133 | + // |
| 134 | + // 1. The FACTORY memo runs the source once for every mount and is sync- |
| 135 | + // valued by construction: a thenable the source returns is boxed |
| 136 | + // (`FLIGHT`), so the factory never goes pending on it. It stays the |
| 137 | + // consumer of an async ITERABLE answer (a `live` server component's |
| 138 | + // loop): the yields land at its gate, `sameInstance` keeps a reconnect's |
| 139 | + // re-yield quiet, and under hydration the frames intercept's local |
| 140 | + // answer (LIVE_LOCAL) and the takeover arming both belong to this node, |
| 141 | + // exactly as before — the record below never sits on it. |
| 142 | + // 2. The per-instance VALUE memo unboxes, and for a thenable becomes the |
| 143 | + // ORDINARY async memo the boundary waits on. Under hydration it is the |
| 144 | + // node the server's record is keyed to (the server's value memo at the |
| 145 | + // same id serialized the landing): it ADOPTS the record — a server |
| 146 | + // component's flight reference resolves to its binding, a tag to its |
| 147 | + // string — and never waits on the client's own re-run of the source, so |
| 148 | + // a hydrating <Loading> sees no pending beat (#3666). The trace run |
| 149 | + // still reads the factory, which is how the instance follows a later |
| 150 | + // source change; the token pins a delivery to this instance's LATEST |
| 151 | + // computation (a superseded source's late resolution must not re-bind |
| 152 | + // the mount to stale content). The thenable is transparent — it |
| 153 | + // transforms the value inside the SAME microtask as the source |
| 154 | + // promise's own handlers. |
| 155 | + // 3. The per-instance RENDER memo applies props. |
| 156 | + const cached = createMemo<any>( |
| 157 | + (prev: any) => { |
| 158 | + const next = source() as any; |
| 159 | + if (!next || typeof next.then !== "function") return resolveBinding(next, prev); |
| 160 | + return { [FLIGHT]: next }; |
| 161 | + }, |
| 162 | + { lazy: true, equals: sameInstance } |
| 163 | + ); |
| 164 | + return props => { |
| 165 | + // Hydration adopts the value memo's record, and its trace run — the one |
| 166 | + // read that subscribes it to the factory — happens under the tracer's |
| 167 | + // mocked globals (fetch, Promise), where the factory's FIRST compute must |
| 168 | + // not run: the source's answer is consumed for real later (the factory is |
| 169 | + // lazy, and a `Promise.resolve()` minted under the mock never settles). |
| 170 | + // Warm the factory here, in the owner's own tick, so the trace finds it |
| 171 | + // computed. A NotReady (an iterable still pending its first yield, a |
| 172 | + // dependency) is the value memo's to see on its own read. |
| 173 | + if (sharedConfig.hydrating) { |
| 174 | + try { |
| 175 | + untrack(cached); |
| 176 | + } catch { |
| 177 | + // The value memo observes the NotReady on its own read. |
| 178 | + } |
| 179 | + } |
| 180 | + let latest = 0; |
| 181 | + const value = createMemo<Function | string | undefined>( |
| 182 | + (prev: any) => { |
| 183 | + const c = cached(); |
| 184 | + if (!c || !c[FLIGHT]) return resolveBinding(c, prev); |
| 185 | + const next: PromiseLike<any> = c[FLIGHT]; |
| 186 | + const token = ++latest; |
| 187 | + // `onFulfilled` may be absent: the hydration tracer observes a |
| 188 | + // compute's thenable with `.then(undefined, noop)`. |
| 189 | + return { |
| 190 | + then: (onFulfilled: any, onRejected: any) => |
| 191 | + next.then((resolved: any) => { |
| 192 | + const landed = token === latest ? resolveBinding(resolved, prev) : resolved; |
| 193 | + return onFulfilled ? onFulfilled(landed) : landed; |
| 194 | + }, onRejected) |
| 195 | + }; |
| 196 | + }, |
| 197 | + { equals: sameInstance } |
| 198 | + ); |
| 199 | + return createMemo(() => { |
| 200 | + const component = value(); |
| 201 | + switch (typeof component) { |
| 202 | + case "function": { |
| 203 | + if (IS_DEV) Object.assign(component, { [$DEVCOMP]: true }); |
| 204 | + const binding = bindingOf(component); |
| 205 | + if (binding) { |
| 206 | + // Mount the per-function component with a LIVE address accessor |
| 207 | + // (the transport's second-argument convention); kept resolutions |
| 208 | + // above deliver into it, and the instance follows — no re-render |
| 209 | + // at this seam. Initialize from the LATEST resolved address: the |
| 210 | + // kept binding's own `.address` is the first resolution's and |
| 211 | + // goes stale the moment a later call is kept-delivered. |
| 212 | + // `ownedWrite`: a delivery is a write from wherever the |
| 213 | + // resolution lands — a promise microtask for an async source, |
| 214 | + // but INSIDE the factory's compute when the source is a memo that |
| 215 | + // already settled the call (the multi-flight `refresh(todos)` |
| 216 | + // shape, and the hydrated document's first refetch), and inside |
| 217 | + // the equals gate for a pump's yield. None of those read the |
| 218 | + // address back, so the owned-scope write guard has nothing to |
| 219 | + // protect here. |
| 220 | + const [address, setAddress] = createSignal((deliveredAddress ??= binding.address), { |
| 221 | + ownedWrite: true |
| 222 | + }); |
| 223 | + sites.add(setAddress); |
| 224 | + onCleanup(() => sites.delete(setAddress)); |
| 225 | + return untrack(() => (binding.component as any)(props, address)); |
| 226 | + } |
| 227 | + return untrack(() => (component as Function)(props)); |
| 228 | + } |
| 229 | + |
| 230 | + case "string": |
| 231 | + // No tag arm (`dynamicComponent`): a string renders nothing, like |
| 232 | + // any other non-component value. `dynamic` passes an arm. |
| 233 | + return tagArm ? tagArm(component, props) : undefined; |
| 234 | + |
| 235 | + default: |
| 236 | + break; |
| 237 | + } |
| 238 | + }) as unknown as SolidElement; |
| 239 | + }; |
| 240 | +} |
| 241 | + |
| 242 | +// `{ static: true }`: the resolved value once, no factory memo, no |
| 243 | +// per-instance memo — the instance IS the element or the component call, |
| 244 | +// owner-free like compiled JSX, so the server's static path (the same rule) |
| 245 | +// produces the same hydration keys. |
| 246 | +function staticDynamic(component: any, tagArm?: TagArm): Component<any> { |
| 247 | + if (IS_DEV && component && typeof component.then === "function") |
| 248 | + throw new Error("dynamic(): a static source must resolve synchronously, not to a promise"); |
| 249 | + if (typeof component === "function") { |
| 250 | + if (IS_DEV) Object.assign(component, { [$DEVCOMP]: true }); |
| 251 | + const binding = bindingOf(component); |
| 252 | + if (binding) { |
| 253 | + // A server-function component: its address is fixed too (the source is |
| 254 | + // never re-resolved), so the live accessor is a constant. |
| 255 | + const address = () => binding.address; |
| 256 | + return props => untrack(() => (binding.component as any)(props, address)); |
| 257 | + } |
| 258 | + return props => untrack(() => component(props)); |
| 259 | + } |
| 260 | + if (typeof component === "string" && tagArm) return props => tagArm(component, props); |
| 261 | + return () => undefined as unknown as SolidElement; |
| 262 | +} |
| 263 | + |
| 264 | +/** |
| 265 | + * `dynamic` for a source that only ever answers with a component — never a |
| 266 | + * tag name. A reactive, optionally async source; a stable `Component` back; |
| 267 | + * `{ static: true }` and `{ deferStream: true }`. The source's type excludes |
| 268 | + * strings, so a tag name is a compile error here — use `@solidjs/web`'s |
| 269 | + * `dynamic` for one. |
| 270 | + * |
| 271 | + * Cost model, which is the reason this exists: `dynamic` must be able to |
| 272 | + * render a tag, so one `dynamic` anywhere on a page retains the element |
| 273 | + * runtime — `createElement`, `spread` and the prop-collection helpers, the |
| 274 | + * SVG/MathML tables — for everyone, whether or not any source ever answers |
| 275 | + * with a string (a bundler cannot know what a source will resolve to). |
| 276 | + * `dynamicComponent` has no tag arm and never references that runtime, so a |
| 277 | + * page whose only dynamic mounts are components pays nothing for it. |
| 278 | + * |
| 279 | + * This is the documented way to mount a server component: a server |
| 280 | + * function's answer is a component reference, and the frames transport |
| 281 | + * resolves every call for the same function to the same mount identity, so |
| 282 | + * a refetch or an argument change is delivered into the mounted instance |
| 283 | + * rather than remounting it. |
| 284 | + * |
| 285 | + * @example |
| 286 | + * ```tsx |
| 287 | + * const Story = dynamicComponent(() => getStory(props.storyId)); |
| 288 | + * return <Story comment={p => <Comment cid={p.cid}>{p.children}</Comment>} />; |
| 289 | + * |
| 290 | + * // A client component chosen by (sync) data — the same thing `dynamic` |
| 291 | + * // does, without retaining the element runtime for the page. |
| 292 | + * const Page = dynamicComponent(() => (page().editable ? Editor : Viewer)); |
| 293 | + * ``` |
| 294 | + */ |
| 295 | +export const dynamicComponent = dynamicCore as { |
| 296 | + <C extends Component<any>>( |
| 297 | + source: () => C | Promise<C> | AsyncIterable<C> | null | undefined | false, |
| 298 | + options?: DynamicOptions |
| 299 | + ): Component<ComponentProps<C>>; |
| 300 | +}; |
0 commit comments