@opentf/afw 0.0.0-stage → 0.33.0
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/LICENSE +21 -0
- package/README.md +123 -2
- package/components/Link.d.ts +12 -0
- package/components/Link.jsx +54 -0
- package/core/context.d.ts +7 -0
- package/core/context.js +60 -0
- package/core/dev.js +27 -0
- package/core/errors.d.ts +14 -0
- package/core/errors.js +48 -0
- package/core/html.js +10 -0
- package/core/metadata.js +186 -0
- package/core/reactive.d.ts +5 -0
- package/core/reactive.js +190 -0
- package/core/render-context.js +11 -0
- package/core/signals.d.ts +8 -0
- package/core/signals.js +264 -0
- package/index.d.ts +5 -0
- package/index.js +13 -0
- package/jsx-runtime.d.ts +37 -0
- package/package.json +66 -4
- package/runtime/clipboard.d.ts +7 -0
- package/runtime/clipboard.js +47 -0
- package/runtime/code-block.d.ts +14 -0
- package/runtime/code-block.js +76 -0
- package/runtime/context.browser.js +163 -0
- package/runtime/context.d.ts +13 -0
- package/runtime/context.js +44 -0
- package/runtime/dom.browser.js +423 -0
- package/runtime/dom.d.ts +142 -0
- package/runtime/dom.js +670 -0
- package/runtime/error-boundary.browser.js +140 -0
- package/runtime/error-boundary.d.ts +19 -0
- package/runtime/error-boundary.js +123 -0
- package/runtime/events.browser.js +29 -0
- package/runtime/events.d.ts +1 -0
- package/runtime/events.js +17 -0
- package/runtime/head.js +29 -0
- package/runtime/hmr.js +199 -0
- package/runtime/hydrate.browser.js +144 -0
- package/runtime/hydrate.d.ts +179 -0
- package/runtime/hydrate.js +584 -0
- package/runtime/index.d.ts +14 -0
- package/runtime/index.js +24 -0
- package/runtime/lifecycle.d.ts +6 -0
- package/runtime/lifecycle.js +14 -0
- package/runtime/mount.d.ts +20 -0
- package/runtime/mount.js +88 -0
- package/runtime/portal.browser.js +85 -0
- package/runtime/portal.d.ts +12 -0
- package/runtime/portal.js +74 -0
- package/runtime/raw-html.d.ts +11 -0
- package/runtime/raw-html.js +55 -0
- package/runtime/resource.d.ts +9 -0
- package/runtime/resource.js +139 -0
- package/runtime/route-data.d.ts +15 -0
- package/runtime/route-data.js +64 -0
- package/runtime/router.d.ts +149 -0
- package/runtime/router.js +807 -0
- package/server/adapters/node.d.ts +28 -0
- package/server/adapters/node.js +74 -0
- package/server/api.d.ts +175 -0
- package/server/api.js +233 -0
- package/server/builtins.js +42 -0
- package/server/cookies.d.ts +44 -0
- package/server/cookies.js +122 -0
- package/server/head.js +9 -0
- package/server/index.d.ts +155 -0
- package/server/index.js +31 -0
- package/server/loader.js +201 -0
- package/server/middleware.js +119 -0
- package/server/render-context.js +30 -0
- package/server/render.js +175 -0
- package/server/ssg-runtime.js +297 -0
package/runtime/dom.js
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
// Zero-VDOM DOM operations. CSR codegen emits calls into these helpers; they
|
|
2
|
+
// also back runtime-driven updates (reactive text/attributes). No virtual DOM,
|
|
3
|
+
// no diffing — just direct, fine-grained DOM writes wired to signals.
|
|
4
|
+
|
|
5
|
+
import { DEV, warnOnce } from "../core/dev.js";
|
|
6
|
+
import { effect, scope, signal } from "../core/signals.js";
|
|
7
|
+
import { claimRegionEnd, claimRegionStart, HydrationMismatch, isHydrating } from "./hydrate.js";
|
|
8
|
+
|
|
9
|
+
/** Distinguishes items that carry identity (objects) from interchangeable primitives. */
|
|
10
|
+
const hasIdentity = (v) => v !== null && (typeof v === "object" || typeof v === "function");
|
|
11
|
+
|
|
12
|
+
/** Counts lists so each keyless one warns at most once (see {@link warnKeylessDrift}). */
|
|
13
|
+
let listId = 0;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Dev-only guard for the index-key fallback (SPEC §5.4.4: "if `key` is missing,
|
|
17
|
+
* `_mapped` falls back to the array index").
|
|
18
|
+
*
|
|
19
|
+
* Index keying matches items by position, so it is only safe while positions are
|
|
20
|
+
* stable. Splice an item out of the middle and every later item shifts up a slot:
|
|
21
|
+
* the reconciler re-points each surviving node at its *neighbour's* data and
|
|
22
|
+
* removes the node at the tail — so the DOM node destroyed is the last one, not
|
|
23
|
+
* the spliced one. Bindings re-render, which hides this for text-only rows, but a
|
|
24
|
+
* row's node identity is its state: focus, scroll offset, uncontrolled input
|
|
25
|
+
* values, media playback, and any custom element's internals all follow the node
|
|
26
|
+
* and so land on the wrong item.
|
|
27
|
+
*
|
|
28
|
+
* Rather than warn on every keyless list (noise: `["a","b"].map(...)` is fine
|
|
29
|
+
* index-keyed forever), warn only once identity has *demonstrably* drifted — an
|
|
30
|
+
* item object that was at one index is now at another. That is exactly the
|
|
31
|
+
* reconcile where the fallback is about to do the wrong thing.
|
|
32
|
+
*/
|
|
33
|
+
function warnKeylessDrift(id, prevItems, items) {
|
|
34
|
+
const prevIndexOf = new Map();
|
|
35
|
+
for (let i = 0; i < prevItems.length; i++) {
|
|
36
|
+
if (hasIdentity(prevItems[i])) prevIndexOf.set(prevItems[i], i);
|
|
37
|
+
}
|
|
38
|
+
for (let i = 0; i < items.length; i++) {
|
|
39
|
+
const at = prevIndexOf.get(items[i]);
|
|
40
|
+
if (at === undefined || at === i) continue;
|
|
41
|
+
warnOnce(
|
|
42
|
+
`keyless-list:${id}`,
|
|
43
|
+
`A list rendered without \`key\` reordered: an item moved from index ${at} to ${i}.\n` +
|
|
44
|
+
`Without a key, items are matched by position, so the DOM nodes stay put and only their ` +
|
|
45
|
+
`data is re-pointed — per-node state (focus, scroll, inputs, component internals) now ` +
|
|
46
|
+
`belongs to the wrong item, and the node removed is the last one rather than the one you ` +
|
|
47
|
+
`removed.\nFix: give the item a stable key, e.g. \`items.map((item) => <li key={item.id}>…</li>)\`.`,
|
|
48
|
+
);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Attribute names that must be assigned as JS properties (not setAttribute) for
|
|
54
|
+
// correct behavior. Mirrors the set the old runtime relied on (core/constants).
|
|
55
|
+
const AS_PROPERTY = new Set([
|
|
56
|
+
"value",
|
|
57
|
+
"checked",
|
|
58
|
+
"selected",
|
|
59
|
+
"disabled",
|
|
60
|
+
"readOnly",
|
|
61
|
+
"className",
|
|
62
|
+
"htmlFor",
|
|
63
|
+
"indeterminate",
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
// Enumerated attributes: their value is a keyword string ("true"/"false"), not a
|
|
67
|
+
// boolean-attribute presence toggle. `draggable={true}` must become
|
|
68
|
+
// draggable="true" — draggable="" reads back as the default (false). ARIA states
|
|
69
|
+
// behave the same (aria-*="true"/"false").
|
|
70
|
+
const ENUMERATED = new Set(["draggable", "spellcheck", "contenteditable"]);
|
|
71
|
+
|
|
72
|
+
// CSS properties whose numeric values are unitless; every other numeric value
|
|
73
|
+
// gets "px" appended (matching React/JSX conventions, so `style={{ width: 8 }}`
|
|
74
|
+
// means 8px). Mirrors React's CSSProperty unitless list.
|
|
75
|
+
const UNITLESS = new Set([
|
|
76
|
+
"animationIterationCount", "aspectRatio", "borderImageOutset", "borderImageSlice",
|
|
77
|
+
"borderImageWidth", "boxFlex", "boxFlexGroup", "boxOrdinalGroup", "columnCount",
|
|
78
|
+
"columns", "flex", "flexGrow", "flexShrink", "flexOrder", "gridArea", "gridRow",
|
|
79
|
+
"gridRowEnd", "gridRowStart", "gridColumn", "gridColumnEnd", "gridColumnStart",
|
|
80
|
+
"fontWeight", "lineClamp", "lineHeight", "opacity", "order", "orphans", "tabSize",
|
|
81
|
+
"widows", "zIndex", "zoom", "fillOpacity", "floodOpacity", "stopOpacity",
|
|
82
|
+
"strokeDasharray", "strokeDashoffset", "strokeMiterlimit", "strokeOpacity",
|
|
83
|
+
"strokeWidth",
|
|
84
|
+
]);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Apply a `style` object to an element. Numbers get "px" appended unless the
|
|
88
|
+
* property is unitless; CSS custom properties (`--foo`) go through setProperty;
|
|
89
|
+
* nullish values clear the property. A string value is treated as raw cssText.
|
|
90
|
+
*/
|
|
91
|
+
export function applyStyle(el, value) {
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
el.style.cssText = value;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
for (const key in value) {
|
|
97
|
+
const v = value[key];
|
|
98
|
+
if (key.startsWith("--")) {
|
|
99
|
+
el.style.setProperty(key, v == null ? "" : String(v));
|
|
100
|
+
} else if (v == null) {
|
|
101
|
+
el.style[key] = "";
|
|
102
|
+
} else {
|
|
103
|
+
el.style[key] = typeof v === "number" && !UNITLESS.has(key) ? `${v}px` : v;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Render a reactive value to its text form: null/undefined/false → "". */
|
|
109
|
+
export function toText(value) {
|
|
110
|
+
return value == null || value === false ? "" : String(value);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Compile a static subtree once, then stamp copies of it.
|
|
115
|
+
*
|
|
116
|
+
* CSR codegen hoists one `const t = template("<p …>…</p>")` per distinct static
|
|
117
|
+
* subtree in a module and calls `t()` where it would otherwise have emitted a
|
|
118
|
+
* `createElement` + `setAttribute` + `appendChild` for every node. Parsing happens
|
|
119
|
+
* on the first call and `cloneNode(true)` — a single engine-side copy — on every
|
|
120
|
+
* call, including the first.
|
|
121
|
+
*
|
|
122
|
+
* The parse is deferred rather than done at module scope so importing a compiled
|
|
123
|
+
* module never touches `document`: the hydrate bundle is a browser artifact, but
|
|
124
|
+
* module evaluation order is not something a runtime helper should depend on.
|
|
125
|
+
*
|
|
126
|
+
* The compiler only emits this for markup it has proven the HTML parser rebuilds
|
|
127
|
+
* exactly as `createElement` would (`codegen::static_tree::template_html`) — a
|
|
128
|
+
* template is *not* a general-purpose `innerHTML`, and passing it author markup
|
|
129
|
+
* would reintroduce every reparenting rule that analysis exists to avoid.
|
|
130
|
+
*/
|
|
131
|
+
export function template(html) {
|
|
132
|
+
let node;
|
|
133
|
+
return () => {
|
|
134
|
+
if (node === undefined) {
|
|
135
|
+
const el = document.createElement("template");
|
|
136
|
+
el.innerHTML = html;
|
|
137
|
+
node = el.content.firstChild;
|
|
138
|
+
}
|
|
139
|
+
return node.cloneNode(true);
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Sentinel for "nothing written yet" — distinct from any real attribute value. */
|
|
144
|
+
const UNSET = Symbol("unset");
|
|
145
|
+
|
|
146
|
+
/** A value safe to compare by identity for write elision (no internal mutation). */
|
|
147
|
+
const isPrimitive = (v) =>
|
|
148
|
+
v === null || (typeof v !== "object" && typeof v !== "function");
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* clsx-style class normalization. Falsy entries are skipped; strings/numbers are
|
|
152
|
+
* kept; arrays recurse; objects contribute the keys whose values are truthy. Lets
|
|
153
|
+
* JSX write `class={["btn", active && "on", { lg: size === "lg" }]}`.
|
|
154
|
+
*/
|
|
155
|
+
export function clsx(value) {
|
|
156
|
+
if (!value) return "";
|
|
157
|
+
if (typeof value === "string") return value;
|
|
158
|
+
if (typeof value === "number") return String(value);
|
|
159
|
+
if (Array.isArray(value)) {
|
|
160
|
+
const parts = [];
|
|
161
|
+
for (const v of value) {
|
|
162
|
+
const s = clsx(v);
|
|
163
|
+
if (s) parts.push(s);
|
|
164
|
+
}
|
|
165
|
+
return parts.join(" ");
|
|
166
|
+
}
|
|
167
|
+
if (typeof value === "object") {
|
|
168
|
+
const parts = [];
|
|
169
|
+
for (const k in value) if (value[k]) parts.push(k);
|
|
170
|
+
return parts.join(" ");
|
|
171
|
+
}
|
|
172
|
+
return "";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Apply a single static prop/attribute. Handles `style` objects, `on*` event
|
|
177
|
+
* handlers, property-backed attributes, and boolean/nullish removal; everything
|
|
178
|
+
* else falls back to `setAttribute`.
|
|
179
|
+
*/
|
|
180
|
+
export function setAttr(el, name, value) {
|
|
181
|
+
if (name === "style" && value && (typeof value === "object" || typeof value === "string")) {
|
|
182
|
+
applyStyle(el, value);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (name === "class" && value && typeof value === "object") {
|
|
186
|
+
const c = clsx(value); // array/object form → a normalized class string
|
|
187
|
+
if (c) el.setAttribute("class", c);
|
|
188
|
+
else el.removeAttribute("class");
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (name.startsWith("on") && typeof value === "function") {
|
|
192
|
+
el[name.toLowerCase()] = value;
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (AS_PROPERTY.has(name)) {
|
|
196
|
+
el[name] = value;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (ENUMERATED.has(name) || name.startsWith("aria-")) {
|
|
200
|
+
if (value == null) el.removeAttribute(name);
|
|
201
|
+
else el.setAttribute(name, value === true ? "true" : value === false ? "false" : String(value));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (value == null || value === false) {
|
|
205
|
+
el.removeAttribute(name);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (value === true) {
|
|
209
|
+
el.setAttribute(name, "");
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
el.setAttribute(name, String(value));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Apply a named prop to a *child component* element. Set it as a property when the
|
|
217
|
+
* element exposes one (custom-element prop setters, `value`, `checked`, …) so rich
|
|
218
|
+
* values (objects, signals) reach the component's setter; otherwise fall back to an
|
|
219
|
+
* attribute so plain ones (`class`, `data-*`, `aria-*`) still land correctly. This
|
|
220
|
+
* mirrors how JSX libraries target custom elements. If the element is not yet
|
|
221
|
+
* upgraded `name in el` is false, so the value lands as an attribute and the
|
|
222
|
+
* component picks it up from `getAttribute` when it upgrades.
|
|
223
|
+
*/
|
|
224
|
+
export function setProp(el, name, value) {
|
|
225
|
+
// A component prop must land as a *property* (carrying the rich value), never a
|
|
226
|
+
// stringified attribute. A server-parsed custom element that a parent's adopt walk
|
|
227
|
+
// reaches while it is still inert — its own `customElements.define`-driven upgrade
|
|
228
|
+
// hasn't run yet (synchronous upgrades fire in document order, so a parent upgrades
|
|
229
|
+
// and runs this before its later-in-DOM children) — has no accessors, so `name in el`
|
|
230
|
+
// is false. Falling back to `setAttr` would stringify an object to "[object Object]"
|
|
231
|
+
// and, via `attributeChangedCallback`, clobber the child's payload-hydrated signal —
|
|
232
|
+
// flipping conditional branches and desyncing the adopt walk. Force the pending upgrade
|
|
233
|
+
// first so the property setter exists; it's a no-op for already-upgraded or non-custom
|
|
234
|
+
// elements. (A client CSR build creates already-upgraded instances, so this never fires
|
|
235
|
+
// there.)
|
|
236
|
+
if (
|
|
237
|
+
!(name in el) &&
|
|
238
|
+
el.tagName &&
|
|
239
|
+
el.tagName.includes("-") &&
|
|
240
|
+
typeof customElements !== "undefined" &&
|
|
241
|
+
customElements.get(el.tagName.toLowerCase())
|
|
242
|
+
) {
|
|
243
|
+
customElements.upgrade(el);
|
|
244
|
+
}
|
|
245
|
+
if (name in el) el[name] = value;
|
|
246
|
+
else setAttr(el, name, value);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Apply every own enumerable key of `obj` to `el` (`<div {...obj}/>`, SPEC §5.5).
|
|
251
|
+
* `asProps` sets element properties (for components) instead of attributes (for
|
|
252
|
+
* host elements). Keys are applied in object order; the caller wraps this in an
|
|
253
|
+
* effect so a reactive source re-applies.
|
|
254
|
+
*/
|
|
255
|
+
export function spread(el, obj, asProps) {
|
|
256
|
+
if (!obj) return;
|
|
257
|
+
for (const k in obj) {
|
|
258
|
+
if (asProps) el[k] = obj[k];
|
|
259
|
+
else setAttr(el, k, obj[k]);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Wire a text node to a reactive expression. Primitive values update the text in
|
|
265
|
+
* place; a DOM node (or array of them) — e.g. JSX stored as a value, `{iconMap[k]}`
|
|
266
|
+
* — is inserted before the text node, which stays as a stable anchor. Returns the
|
|
267
|
+
* effect disposer so the caller (component lifecycle) can stop updates.
|
|
268
|
+
*/
|
|
269
|
+
export function bindText(node, fn) {
|
|
270
|
+
let inserted = [];
|
|
271
|
+
let lastText; // undefined sentinel — toText() never returns undefined
|
|
272
|
+
let lastNodeValue; // the node/array/marker currently rendered, for the re-run check
|
|
273
|
+
// Hydration: server content left in a node-valued hole (see `claimText`). `adoptable`
|
|
274
|
+
// marks `inserted` as untouched server nodes a hydratable value may still adopt.
|
|
275
|
+
let serverNodes = node.__afwServerNodes ?? null;
|
|
276
|
+
if (serverNodes) delete node.__afwServerNodes;
|
|
277
|
+
let adoptable = false;
|
|
278
|
+
const removeInserted = () => {
|
|
279
|
+
for (const n of inserted) if (n.parentNode) n.parentNode.removeChild(n);
|
|
280
|
+
inserted = [];
|
|
281
|
+
};
|
|
282
|
+
return effect(() => {
|
|
283
|
+
const value = fn();
|
|
284
|
+
|
|
285
|
+
if (serverNodes) {
|
|
286
|
+
const server = serverNodes;
|
|
287
|
+
serverNodes = null;
|
|
288
|
+
inserted = server;
|
|
289
|
+
adoptable = true;
|
|
290
|
+
// The server's `{ __html }` stand-in describes exactly these nodes: keep them.
|
|
291
|
+
if (isHtmlMarker(value)) {
|
|
292
|
+
lastText = undefined;
|
|
293
|
+
lastNodeValue = value;
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// A hydratable JSX value adopts the server nodes still in place instead of
|
|
298
|
+
// rebuilding them — on the first run, or when the parent supplies it after the
|
|
299
|
+
// child already kept the server's stand-in.
|
|
300
|
+
if (adoptable && isHydratable(value) && isHydrating()) {
|
|
301
|
+
adoptable = false;
|
|
302
|
+
try {
|
|
303
|
+
const adopted = value.adopt({ node: inserted[0] ?? null }, inserted);
|
|
304
|
+
inserted = adopted == null ? [] : Array.isArray(adopted) ? adopted : [adopted];
|
|
305
|
+
lastText = undefined;
|
|
306
|
+
lastNodeValue = value;
|
|
307
|
+
return;
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (!(error instanceof HydrationMismatch)) throw error;
|
|
310
|
+
// Fall through: rebuild below, which removes the server nodes first.
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
adoptable = false;
|
|
314
|
+
|
|
315
|
+
// A server `{__html}` marker (see `isHtmlMarker`) renders as the nodes it describes —
|
|
316
|
+
// and it is immutable, so re-running with the same marker keeps what is already there
|
|
317
|
+
// instead of re-parsing it (which would tear down and re-upgrade any island inside).
|
|
318
|
+
if (isHtmlMarker(value) && value === lastNodeValue) return;
|
|
319
|
+
|
|
320
|
+
// Primitive text: the common case. Skip the write when the rendered string
|
|
321
|
+
// is unchanged (a shared dependency can re-run this effect with the same
|
|
322
|
+
// result), so unchanged text nodes don't churn.
|
|
323
|
+
if (!(value instanceof Node) && !Array.isArray(value) && !isHtmlMarker(value) && !isHydratable(value)) {
|
|
324
|
+
const text = toText(value);
|
|
325
|
+
if (text === lastText) return;
|
|
326
|
+
lastText = text;
|
|
327
|
+
lastNodeValue = undefined;
|
|
328
|
+
removeInserted();
|
|
329
|
+
node.data = text;
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Node / array / marker value (e.g. JSX stored as a value): insert before the stable
|
|
334
|
+
// text anchor. Reset the text memo so a later primitive value re-applies.
|
|
335
|
+
lastText = undefined;
|
|
336
|
+
lastNodeValue = value;
|
|
337
|
+
removeInserted();
|
|
338
|
+
node.data = "";
|
|
339
|
+
const parent = node.parentNode;
|
|
340
|
+
if (parent) {
|
|
341
|
+
for (const n of toNodes(value)) {
|
|
342
|
+
parent.insertBefore(n, node);
|
|
343
|
+
inserted.push(n);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Wire an element attribute/prop to a reactive expression. Returns the disposer.
|
|
351
|
+
*
|
|
352
|
+
* No-op writes are elided for primitive values: when the expression recomputes
|
|
353
|
+
* to the same primitive it last wrote, the DOM write is skipped. This matters
|
|
354
|
+
* when many elements share one dependency — e.g. a keyed list where every row's
|
|
355
|
+
* `class={selected === row.id ? "danger" : ""}` subscribes to a single
|
|
356
|
+
* `selected` signal. Changing it re-runs every row's effect, but only the two
|
|
357
|
+
* rows whose class actually changes should touch the DOM; the rest would
|
|
358
|
+
* otherwise call `setAttribute` with an unchanged value and trigger needless
|
|
359
|
+
* style invalidation. Object values (style/class objects, spreads) may have
|
|
360
|
+
* mutated internally, so they are always re-applied.
|
|
361
|
+
*/
|
|
362
|
+
export function bindAttr(el, name, fn) {
|
|
363
|
+
let last = UNSET;
|
|
364
|
+
return effect(() => {
|
|
365
|
+
const value = fn();
|
|
366
|
+
if (isPrimitive(value) && Object.is(value, last)) return;
|
|
367
|
+
last = value;
|
|
368
|
+
setAttr(el, name, value);
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Is this the server's stand-in for a JSX value — `{ __html }`?
|
|
374
|
+
*
|
|
375
|
+
* A JSX value the server can't hand over as a DOM node (a component prop whose value is
|
|
376
|
+
* an element, `<Tabs tabs={[{ content: <CodeBlock/> }]} />`, or JSX embedded in a list's
|
|
377
|
+
* data) is rendered to its HTML and crosses to the client inside the hydration payload as
|
|
378
|
+
* this marker — `ssgText` splices it raw on the server, and the client has to do the same
|
|
379
|
+
* or it would stringify to `[object Object]` in the middle of the page.
|
|
380
|
+
*/
|
|
381
|
+
const isHtmlMarker = (v) => v !== null && typeof v === "object" && typeof v.__html === "string";
|
|
382
|
+
|
|
383
|
+
/** Parse a trusted server-rendered HTML string into the nodes it describes. */
|
|
384
|
+
const HYDRATABLE = Symbol.for("afw.hydratable");
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* A JSX value from the hydrate build: `build()` creates fresh nodes (client render),
|
|
388
|
+
* `adopt(cursor)` claims the server-rendered nodes in place and wires their bindings.
|
|
389
|
+
* A hole that receives one during hydration adopts; any other time it builds.
|
|
390
|
+
*/
|
|
391
|
+
export function hydratableNode(build, adopt) {
|
|
392
|
+
return Object.freeze({ [HYDRATABLE]: true, build, adopt });
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* A component's light-DOM children read as a value (`content: props.children`) during
|
|
397
|
+
* hydration. The server rendered them inside the receiving hole, so `adopt` keeps
|
|
398
|
+
* whatever nodes it is handed there, and `build` returns those same nodes for a later
|
|
399
|
+
* render. Before adoption there is nothing to show.
|
|
400
|
+
*/
|
|
401
|
+
export function adoptedChildren() {
|
|
402
|
+
let kept = [];
|
|
403
|
+
return hydratableNode(() => kept, (_cursor, nodes) => (kept = nodes));
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Is this a {@link hydratableNode} value? */
|
|
407
|
+
export function isHydratable(value) {
|
|
408
|
+
return value != null && typeof value === "object" && value[HYDRATABLE] === true;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function htmlToNodes(html) {
|
|
412
|
+
const tpl = document.createElement("template");
|
|
413
|
+
tpl.innerHTML = html;
|
|
414
|
+
return [...tpl.content.childNodes];
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Flatten a reactive child value into DOM nodes: nodes pass through, arrays
|
|
418
|
+
* recurse, nullish/booleans render nothing, `{__html}` markers are parsed back into
|
|
419
|
+
* the nodes the server rendered, and primitives become text nodes. */
|
|
420
|
+
function toNodes(value) {
|
|
421
|
+
if (value == null || typeof value === "boolean") return [];
|
|
422
|
+
if (Array.isArray(value)) {
|
|
423
|
+
const out = [];
|
|
424
|
+
for (const v of value) for (const n of toNodes(v)) out.push(n);
|
|
425
|
+
return out;
|
|
426
|
+
}
|
|
427
|
+
if (value instanceof Node) return [value];
|
|
428
|
+
if (isHtmlMarker(value)) return htmlToNodes(value.__html);
|
|
429
|
+
if (isHydratable(value)) return toNodes(value.build());
|
|
430
|
+
return [document.createTextNode(String(value))];
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Wire a dynamic child region (conditional/element-valued holes like
|
|
435
|
+
* `{cond && <p/>}` or `{cond ? <a/> : <b/>}`) to a reactive expression. The
|
|
436
|
+
* region is delimited by `anchor` (a comment); on every change the previous
|
|
437
|
+
* nodes are replaced with the new ones, inserted just before the anchor.
|
|
438
|
+
* Returns the effect disposer.
|
|
439
|
+
*/
|
|
440
|
+
export function bindChild(anchor, fn) {
|
|
441
|
+
return childEffect(anchor, fn, [], false);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Hydrate a server-rendered conditional / dynamic-node region (docs/HYDRATION.md §3.1,
|
|
446
|
+
* 2.1b). The cursor `cur` is at the `<!--[-->` marker; between it and `<!--]-->` sits the
|
|
447
|
+
* one branch the server rendered (or nothing). `adoptFn(cur)` evaluates the same branch
|
|
448
|
+
* expression with *adopt* calls — only the taken branch's builder runs, claiming its nodes
|
|
449
|
+
* off the shared cursor — so the adopted nodes become the region's initial content with no
|
|
450
|
+
* rebuild. `buildFn()` is the CSR version (build calls) the effect swaps to when a later
|
|
451
|
+
* reactive change selects a different branch. The closing `<!--]-->` is the swap anchor.
|
|
452
|
+
* Returns the effect disposer.
|
|
453
|
+
*
|
|
454
|
+
* `depsFn()` is the same branch expression with **every branch replaced by `null`**. The
|
|
455
|
+
* region effect has to run something on first paint to subscribe to the deps it should react
|
|
456
|
+
* to — the *condition* — but running the real `buildFn` there constructs a whole subtree only
|
|
457
|
+
* to discard it, and when a branch re-slots the component's `{children}`, `appendChild`
|
|
458
|
+
* **moves** those live server nodes into the throwaway tree, silently emptying the slot (the
|
|
459
|
+
* `<Card>` → `<Link>{children}</Link>` shape lost its children this way). Evaluating the
|
|
460
|
+
* condition with null branches subscribes to exactly the same reads without building anything;
|
|
461
|
+
* reactivity *inside* a branch is wired by that branch's own bindText/bindAttr effects, so it
|
|
462
|
+
* is not a dependency of this region. Older codegen passes no `depsFn` — fall back to `buildFn`.
|
|
463
|
+
*/
|
|
464
|
+
export function hydrateChild(cur, adoptFn, buildFn, depsFn) {
|
|
465
|
+
claimRegionStart(cur);
|
|
466
|
+
// Adopt inside a scope so the adopted branch owns its bindings' effects; the
|
|
467
|
+
// region disposes it when a reactive change swaps the branch out.
|
|
468
|
+
const adoptedScope = scope(() => toNodes(adoptFn(cur)));
|
|
469
|
+
const anchor = claimRegionEnd(cur);
|
|
470
|
+
// Seed with the adopted nodes and skip the first effect run's DOM write: the branch is
|
|
471
|
+
// already in place; from the second run on it swaps normally.
|
|
472
|
+
return childEffect(anchor, buildFn, adoptedScope.result, true, adoptedScope, depsFn || buildFn);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** The child-region effect shared by {@link bindChild} (empty seed, no skip) and
|
|
476
|
+
* {@link hydrateChild} (seeded with adopted nodes, first DOM write skipped). On each run
|
|
477
|
+
* the previous nodes are replaced with the new ones, inserted before `anchor`; the
|
|
478
|
+
* previous branch's scope is disposed so its bindings' effects don't outlive it. */
|
|
479
|
+
function childEffect(anchor, fn, current, skipFirst, currentScope = null, firstFn = fn) {
|
|
480
|
+
let first = skipFirst;
|
|
481
|
+
const disposeEffect = effect(() => {
|
|
482
|
+
// Build in a scope: the branch's nested bindings (text/attr/list effects)
|
|
483
|
+
// belong to this run and are disposed when the branch is replaced.
|
|
484
|
+
// On a hydration first run this evaluates `firstFn` — the condition with null
|
|
485
|
+
// branches — which subscribes the region without constructing (or stealing) DOM.
|
|
486
|
+
const built = scope(() => toNodes((first ? firstFn : fn)()));
|
|
487
|
+
if (first) {
|
|
488
|
+
first = false;
|
|
489
|
+
// Hydration first run subscribes the region effect only; anything the discarded
|
|
490
|
+
// run did create must not stay live alongside the adopted branch.
|
|
491
|
+
built.dispose();
|
|
492
|
+
return; // keep the adopted DOM on first paint
|
|
493
|
+
}
|
|
494
|
+
const next = built.result;
|
|
495
|
+
const host = anchor.parentNode;
|
|
496
|
+
for (const n of current) {
|
|
497
|
+
if (n.parentNode === host) host.removeChild(n);
|
|
498
|
+
}
|
|
499
|
+
if (host) for (const n of next) host.insertBefore(n, anchor);
|
|
500
|
+
if (currentScope) currentScope.dispose();
|
|
501
|
+
currentScope = built;
|
|
502
|
+
current = next;
|
|
503
|
+
});
|
|
504
|
+
return () => {
|
|
505
|
+
disposeEffect();
|
|
506
|
+
if (currentScope) currentScope.dispose();
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Render a keyed list (`array.map(...)`, SPEC §5.4.4) into `parent`, reconciling
|
|
512
|
+
* by key on every change to `sourceFn`'s dependencies.
|
|
513
|
+
*
|
|
514
|
+
* - `sourceFn()` returns the current array (plain data).
|
|
515
|
+
* - `renderItem(itemSignal, index)` builds a node for a new item; the item's
|
|
516
|
+
* value is a signal so per-item bindings update fine-grained on data changes.
|
|
517
|
+
* - `keyFn(item, index)` returns a stable key; falls back to `index` when omitted.
|
|
518
|
+
*
|
|
519
|
+
* Returns the effect disposer (stops reconciliation; used by component cleanup).
|
|
520
|
+
*/
|
|
521
|
+
export function bindList(parent, sourceFn, renderItem, keyFn) {
|
|
522
|
+
const anchor = document.createComment("");
|
|
523
|
+
parent.appendChild(anchor);
|
|
524
|
+
return reconcileList(anchor, sourceFn, renderItem, keyFn, new Map(), []);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Hydrate a server-rendered list region (docs/HYDRATION.md §3.1/2.1). The cursor `cur` is
|
|
529
|
+
* positioned at the `<!--[-->` marker; the region holds one root node per item, then
|
|
530
|
+
* `<!--]-->`. Adopts each item's server node via `adoptItem(cur, itemSignal, index)`
|
|
531
|
+
* (claiming off the shared cursor, which advances to the next item), seeds the reconcile
|
|
532
|
+
* cache with the adopted `{sig, node}` pairs, then wires the *same* keyed-reconcile effect
|
|
533
|
+
* `bindList` uses — so a later data change builds/moves/removes with no first-paint flash.
|
|
534
|
+
* The closing `<!--]-->` becomes the reconcile anchor. Returns the effect disposer.
|
|
535
|
+
*/
|
|
536
|
+
export function hydrateList(cur, sourceFn, adoptItem, renderItem, keyFn) {
|
|
537
|
+
claimRegionStart(cur);
|
|
538
|
+
const data = sourceFn();
|
|
539
|
+
const items = Array.isArray(data) ? data : [];
|
|
540
|
+
const cache = new Map();
|
|
541
|
+
const prevKeys = [];
|
|
542
|
+
for (let index = 0; index < items.length; index++) {
|
|
543
|
+
const item = items[index];
|
|
544
|
+
const key = keyFn ? keyFn(item, index) : index;
|
|
545
|
+
const sig = signal(item);
|
|
546
|
+
// Adopt inside a scope so the item owns its bindings' effects; eviction
|
|
547
|
+
// disposes them (same ownership as CSR-built items in reconcileList).
|
|
548
|
+
const s = scope(() => adoptItem(cur, sig, index)); // claims one item subtree off `cur`
|
|
549
|
+
cache.set(key, { sig, node: s.result, dispose: s.dispose });
|
|
550
|
+
prevKeys.push(key);
|
|
551
|
+
}
|
|
552
|
+
const anchor = claimRegionEnd(cur);
|
|
553
|
+
// The seeded effect's first run re-reads the same data: every key hits the cache, so it
|
|
554
|
+
// subscribes for future updates without mutating the already-correct adopted DOM.
|
|
555
|
+
return reconcileList(anchor, sourceFn, renderItem, keyFn, cache, prevKeys);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* The keyed-reconcile effect shared by {@link bindList} (empty seed) and
|
|
560
|
+
* {@link hydrateList} (seeded from adopted nodes). `anchor` is the trailing comment new
|
|
561
|
+
* items are inserted before; `cache` (key → `{sig, node}`) and `prevKeys` (keys in DOM
|
|
562
|
+
* order) carry reconciliation state across runs. Returns the effect disposer.
|
|
563
|
+
*/
|
|
564
|
+
function reconcileList(anchor, sourceFn, renderItem, keyFn, cache, prevKeys) {
|
|
565
|
+
// Dev-only state for the keyless-drift guard: the previous run's items, so a
|
|
566
|
+
// reorder can be spotted by identity.
|
|
567
|
+
const id = DEV && !keyFn ? listId++ : -1;
|
|
568
|
+
let prevItems = [];
|
|
569
|
+
const disposeEffect = effect(() => {
|
|
570
|
+
const data = sourceFn();
|
|
571
|
+
const items = Array.isArray(data) ? data : [];
|
|
572
|
+
if (DEV && !keyFn) {
|
|
573
|
+
warnKeylessDrift(id, prevItems, items);
|
|
574
|
+
prevItems = items;
|
|
575
|
+
}
|
|
576
|
+
const next = new Map();
|
|
577
|
+
const nodes = new Array(items.length);
|
|
578
|
+
const newKeys = new Array(items.length);
|
|
579
|
+
// For each new position, the node's index in the *previous* order, or -1 if
|
|
580
|
+
// it is newly created. Drives the LIS-based minimal move below.
|
|
581
|
+
const prevIndex = new Array(items.length);
|
|
582
|
+
|
|
583
|
+
const prevPos = new Map();
|
|
584
|
+
for (let i = 0; i < prevKeys.length; i++) prevPos.set(prevKeys[i], i);
|
|
585
|
+
|
|
586
|
+
for (let index = 0; index < items.length; index++) {
|
|
587
|
+
const item = items[index];
|
|
588
|
+
const key = keyFn ? keyFn(item, index) : index;
|
|
589
|
+
let entry = cache.get(key);
|
|
590
|
+
if (entry) {
|
|
591
|
+
cache.delete(key);
|
|
592
|
+
entry.sig.value = item; // fine-grained per-item update (no-op if unchanged)
|
|
593
|
+
prevIndex[index] = prevPos.has(key) ? prevPos.get(key) : -1;
|
|
594
|
+
} else {
|
|
595
|
+
const sig = signal(item);
|
|
596
|
+
// Build inside a scope: the item owns its bindings' effects, so
|
|
597
|
+
// evicting it detaches them from shared signals (e.g. a selection
|
|
598
|
+
// signal every row's class reads). Without this every discarded row
|
|
599
|
+
// leaves a zombie effect that all later writes keep re-running.
|
|
600
|
+
const s = scope(() => renderItem(sig, index));
|
|
601
|
+
entry = { sig, node: s.result, dispose: s.dispose };
|
|
602
|
+
prevIndex[index] = -1;
|
|
603
|
+
}
|
|
604
|
+
next.set(key, entry);
|
|
605
|
+
newKeys[index] = key;
|
|
606
|
+
nodes[index] = entry.node;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// Remove nodes whose keys disappeared, and dispose their bindings.
|
|
610
|
+
for (const entry of cache.values()) {
|
|
611
|
+
if (entry.dispose) entry.dispose();
|
|
612
|
+
if (entry.node.parentNode) entry.node.parentNode.removeChild(entry.node);
|
|
613
|
+
}
|
|
614
|
+
cache = next;
|
|
615
|
+
prevKeys = newKeys;
|
|
616
|
+
|
|
617
|
+
// Minimal-move placement. Nodes whose previous indices form the longest
|
|
618
|
+
// increasing subsequence are already in relative order and stay put; only
|
|
619
|
+
// the rest (and newly created nodes) are inserted. A 2-row swap moves 2
|
|
620
|
+
// nodes, not the ~n nodes a naive "fix every wrong nextSibling" pass would
|
|
621
|
+
// cascade into. Walk back to front so each insertion's reference node is
|
|
622
|
+
// already in its final position.
|
|
623
|
+
const keep = longestIncreasingRun(prevIndex);
|
|
624
|
+
const host = anchor.parentNode;
|
|
625
|
+
if (!host) return; // anchor detached (list torn down) — nothing to place
|
|
626
|
+
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
627
|
+
if (keep.has(i)) continue;
|
|
628
|
+
const ref = i + 1 < nodes.length ? nodes[i + 1] : anchor;
|
|
629
|
+
if (nodes[i].nextSibling !== ref) host.insertBefore(nodes[i], ref);
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
return () => {
|
|
633
|
+
disposeEffect();
|
|
634
|
+
for (const entry of cache.values()) {
|
|
635
|
+
if (entry.dispose) entry.dispose();
|
|
636
|
+
}
|
|
637
|
+
cache.clear();
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Indices `i` of `seq` whose values form a longest strictly-increasing
|
|
643
|
+
* subsequence (patience sorting, O(n log n)). Entries equal to -1 (new nodes)
|
|
644
|
+
* are excluded — they always need insertion. Returned as a Set for O(1) lookup
|
|
645
|
+
* during placement; these are the nodes that can stay where they are.
|
|
646
|
+
*/
|
|
647
|
+
function longestIncreasingRun(seq) {
|
|
648
|
+
const piles = []; // piles[k] = index of the smallest tail of a length-(k+1) run
|
|
649
|
+
const prev = new Array(seq.length).fill(-1);
|
|
650
|
+
for (let i = 0; i < seq.length; i++) {
|
|
651
|
+
const v = seq[i];
|
|
652
|
+
if (v < 0) continue; // new node — never part of the stable run
|
|
653
|
+
let lo = 0;
|
|
654
|
+
let hi = piles.length;
|
|
655
|
+
while (lo < hi) {
|
|
656
|
+
const mid = (lo + hi) >> 1;
|
|
657
|
+
if (seq[piles[mid]] < v) lo = mid + 1;
|
|
658
|
+
else hi = mid;
|
|
659
|
+
}
|
|
660
|
+
if (lo > 0) prev[i] = piles[lo - 1];
|
|
661
|
+
piles[lo] = i;
|
|
662
|
+
}
|
|
663
|
+
const keep = new Set();
|
|
664
|
+
let k = piles.length ? piles[piles.length - 1] : -1;
|
|
665
|
+
while (k >= 0) {
|
|
666
|
+
keep.add(k);
|
|
667
|
+
k = prev[k];
|
|
668
|
+
}
|
|
669
|
+
return keep;
|
|
670
|
+
}
|