@opentf/afw 0.37.0 → 0.39.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/core/route.d.ts +33 -0
- package/core/route.js +12 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/jsx-runtime.d.ts +22 -1
- package/package.json +5 -1
- package/runtime/dom.js +23 -4
- package/runtime/error-boundary.d.ts +1 -1
- package/runtime/error-boundary.js +11 -1
- package/runtime/head.js +10 -1
- package/runtime/hmr.js +29 -0
- package/runtime/index.d.ts +4 -0
- package/runtime/index.js +5 -0
- package/runtime/lazy.d.ts +8 -0
- package/runtime/lazy.js +135 -0
- package/runtime/pending-scope.d.ts +6 -0
- package/runtime/pending-scope.js +39 -0
- package/runtime/pending.d.ts +31 -0
- package/runtime/pending.js +276 -0
- package/runtime/resource.d.ts +6 -0
- package/runtime/resource.js +65 -5
- package/runtime/route-data.js +33 -1
- package/runtime/route-errors.d.ts +3 -0
- package/runtime/route-errors.js +16 -0
- package/runtime/route-match.js +97 -12
- package/runtime/router.d.ts +44 -3
- package/runtime/router.js +470 -49
- package/runtime/scroll.js +130 -0
- package/runtime/transition-hooks.js +10 -0
- package/runtime/transition.d.ts +43 -0
- package/runtime/transition.js +187 -0
- package/server/api.js +3 -3
- package/server/builtins.js +29 -1
- package/server/index.d.ts +20 -1
- package/server/index.js +3 -2
- package/server/loader.js +73 -7
- package/server/middleware.js +9 -5
- package/server/render.js +85 -16
package/core/route.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** How a route's pages render. */
|
|
2
|
+
export type RenderStrategy =
|
|
3
|
+
/** Rendered on the server for each request; the browser adopts the HTML. */
|
|
4
|
+
| "server"
|
|
5
|
+
/** Built to HTML at build time; the browser adopts it. */
|
|
6
|
+
| "static"
|
|
7
|
+
/** Rendered in the browser. The page module never enters the server bundle. */
|
|
8
|
+
| "client";
|
|
9
|
+
|
|
10
|
+
/** One page's dynamic params: `{ slug: "hello" }`, or an array for a catch-all segment. */
|
|
11
|
+
export type StaticParams = Record<string, string | number | Array<string | number>>;
|
|
12
|
+
|
|
13
|
+
/** A folder's `_config.js`: applies to its pages and every folder below; the nearest one wins. */
|
|
14
|
+
export interface RouteConfig {
|
|
15
|
+
/**
|
|
16
|
+
* How the pages render. Must be a string literal: the build reads it without running
|
|
17
|
+
* the file, since it decides what each bundle contains. Inherited when omitted.
|
|
18
|
+
*/
|
|
19
|
+
render?: RenderStrategy;
|
|
20
|
+
/**
|
|
21
|
+
* `client` routes only: `"server"` (the default) runs the route's loaders on the server
|
|
22
|
+
* and sends their data with the page; `"client"` leaves fetching to the page.
|
|
23
|
+
*/
|
|
24
|
+
data?: "server" | "client";
|
|
25
|
+
/**
|
|
26
|
+
* `static` dynamic routes only: the params of each page to build. Runs at build time.
|
|
27
|
+
* A matching URL that is not listed renders when it is requested.
|
|
28
|
+
*/
|
|
29
|
+
paths?: () => StaticParams[] | Promise<StaticParams[]>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Declare a folder's render policy: `export default defineRoute({ render: "static" })`. */
|
|
33
|
+
export function defineRoute<T extends RouteConfig>(config: T & Record<Exclude<keyof T, keyof RouteConfig>, never>): T;
|
package/core/route.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// `defineRoute` — the default export of a folder's `_config.js`, which sets how the
|
|
2
|
+
// pages in that folder and below it render. It returns its argument: the build reads
|
|
3
|
+
// `render` and `data` from the source (they must be string literals) and runs `paths`
|
|
4
|
+
// at build time inside the server bundle. Neutral core: no runtime or Node imports.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {import("./route.d.ts").RouteConfig} config
|
|
8
|
+
* @returns {import("./route.d.ts").RouteConfig}
|
|
9
|
+
*/
|
|
10
|
+
export function defineRoute(config) {
|
|
11
|
+
return config;
|
|
12
|
+
}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
export * from "./core/signals.js";
|
|
4
4
|
export * from "./core/reactive.js";
|
|
5
5
|
export * from "./core/errors.js";
|
|
6
|
+
export * from "./core/route.js";
|
|
6
7
|
export * from "./runtime/index.js";
|
|
7
8
|
// `Link` is shipped as JSX source and compiled by the consuming app's pipeline
|
|
8
9
|
// (the `.jsx` lands in the module graph and afwc transforms it). Its compiled
|
package/jsx-runtime.d.ts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
/// <reference path="./macros.d.ts" />
|
|
2
|
+
import type { Transition } from "./runtime/transition.js";
|
|
2
3
|
/** Type-only JSX entry for the AFW compiler (`jsx: "preserve"`). */
|
|
3
4
|
export namespace JSX {
|
|
4
5
|
type Element = Node;
|
|
5
6
|
interface ElementChildrenAttribute { children: unknown }
|
|
7
|
+
|
|
8
|
+
/** A lazy component's loader, `() => import("./Chart.jsx")`, used as a JSX tag. */
|
|
9
|
+
type LazyLoader = () => Promise<unknown>;
|
|
10
|
+
type LazyTarget<L> = L extends () => Promise<infer M> ? (M extends { default: infer C } ? C : M) : never;
|
|
11
|
+
type PropsOf<C> = C extends (props: infer P, ...rest: any[]) => unknown ? P
|
|
12
|
+
: C extends new (props: infer P, ...rest: any[]) => unknown ? P
|
|
13
|
+
: {};
|
|
14
|
+
/** What a tag can be: an element name, a component (function or class), or a lazy loader. */
|
|
15
|
+
type ElementType = string | ((props: any, ...rest: any[]) => unknown) | (new (props: any, ...rest: any[]) => unknown) | LazyLoader;
|
|
16
|
+
/** A lazy loader's props are the props of the component it loads. */
|
|
17
|
+
type LibraryManagedAttributes<C, P> = C extends LazyLoader ? PropsOf<LazyTarget<C>> : P;
|
|
6
18
|
interface IntrinsicAttributes { key?: string | number }
|
|
7
19
|
|
|
8
20
|
type Handler<E, T extends Event> = (event: T & { currentTarget: E }) => void;
|
|
@@ -31,7 +43,16 @@ export namespace JSX {
|
|
|
31
43
|
type Properties<E> = {
|
|
32
44
|
[K in keyof E as E[K] extends Function ? never : K extends `on${string}` | keyof Common<E> ? never : K]?: E[K];
|
|
33
45
|
};
|
|
34
|
-
|
|
46
|
+
/**
|
|
47
|
+
* Enter/exit transitions on an element that a conditional or list adds and removes:
|
|
48
|
+
* `transition` for both directions, or `in` / `out` for one each.
|
|
49
|
+
*/
|
|
50
|
+
type Transitions = {
|
|
51
|
+
transition?: Transition | null | false;
|
|
52
|
+
in?: Transition | null | false;
|
|
53
|
+
out?: Transition | null | false;
|
|
54
|
+
};
|
|
55
|
+
type HTML = { [K in keyof HTMLElementTagNameMap]: Properties<HTMLElementTagNameMap[K]> & Common<HTMLElementTagNameMap[K]> & Transitions };
|
|
35
56
|
type SVG = { [K in Exclude<keyof SVGElementTagNameMap, keyof HTML>]: Common<SVGElementTagNameMap[K]> & { [attribute: string]: unknown } };
|
|
36
57
|
type IntrinsicElements = HTML & SVG & {
|
|
37
58
|
[tag: `${string}-${string}`]: Common<HTMLElement> & { [attribute: string]: unknown };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.39.0",
|
|
4
4
|
"description": "The AFW runtime: signals and zero-VDOM DOM bindings, with routing and server rendering.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"types": "./server/adapters/node.d.ts",
|
|
28
28
|
"default": "./server/adapters/node.js"
|
|
29
29
|
},
|
|
30
|
+
"./transition": {
|
|
31
|
+
"types": "./runtime/transition.d.ts",
|
|
32
|
+
"default": "./runtime/transition.js"
|
|
33
|
+
},
|
|
30
34
|
"./hmr": "./runtime/hmr.js",
|
|
31
35
|
"./jsx-runtime": {
|
|
32
36
|
"types": "./jsx-runtime.d.ts"
|
package/runtime/dom.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { DEV, warnOnce } from "../core/dev.js";
|
|
6
6
|
import { effect, scope, signal } from "../core/signals.js";
|
|
7
7
|
import { claimRegionEnd, claimRegionStart, HydrationMismatch, isHydrating } from "./hydrate.js";
|
|
8
|
+
import { transitionHooks as tx } from "./transition-hooks.js";
|
|
8
9
|
|
|
9
10
|
/** Distinguishes items that carry identity (objects) from interchangeable primitives. */
|
|
10
11
|
const hasIdentity = (v) => v !== null && (typeof v === "object" || typeof v === "function");
|
|
@@ -233,6 +234,8 @@ export function setProp(el, name, value) {
|
|
|
233
234
|
// first so the property setter exists; it's a no-op for already-upgraded or non-custom
|
|
234
235
|
// elements. (A client CSR build creates already-upgraded instances, so this never fires
|
|
235
236
|
// there.)
|
|
237
|
+
// A lazy component's placeholder keeps every prop for the component it loads.
|
|
238
|
+
if (el.__afwLazy) return el.__afwLazy.set(name, value);
|
|
236
239
|
if (
|
|
237
240
|
!(name in el) &&
|
|
238
241
|
el.tagName &&
|
|
@@ -255,7 +258,8 @@ export function setProp(el, name, value) {
|
|
|
255
258
|
export function spread(el, obj, asProps) {
|
|
256
259
|
if (!obj) return;
|
|
257
260
|
for (const k in obj) {
|
|
258
|
-
if (asProps) el
|
|
261
|
+
if (asProps && el.__afwLazy) el.__afwLazy.set(k, obj[k]);
|
|
262
|
+
else if (asProps) el[k] = obj[k];
|
|
259
263
|
else setAttr(el, k, obj[k]);
|
|
260
264
|
}
|
|
261
265
|
}
|
|
@@ -417,7 +421,7 @@ function htmlToNodes(html) {
|
|
|
417
421
|
/** Flatten a reactive child value into DOM nodes: nodes pass through, arrays
|
|
418
422
|
* recurse, nullish/booleans render nothing, `{__html}` markers are parsed back into
|
|
419
423
|
* the nodes the server rendered, and primitives become text nodes. */
|
|
420
|
-
function toNodes(value) {
|
|
424
|
+
export function toNodes(value) {
|
|
421
425
|
if (value == null || typeof value === "boolean") return [];
|
|
422
426
|
if (Array.isArray(value)) {
|
|
423
427
|
const out = [];
|
|
@@ -478,6 +482,9 @@ export function hydrateChild(cur, adoptFn, buildFn, depsFn) {
|
|
|
478
482
|
* previous branch's scope is disposed so its bindings' effects don't outlive it. */
|
|
479
483
|
function childEffect(anchor, fn, current, skipFirst, currentScope = null, firstFn = fn) {
|
|
480
484
|
let first = skipFirst;
|
|
485
|
+
// The region's first DOM write; enter transitions skip it unless they opt in.
|
|
486
|
+
// A hydrated region's first write is a later swap, never initial.
|
|
487
|
+
let initial = !skipFirst;
|
|
481
488
|
const disposeEffect = effect(() => {
|
|
482
489
|
// Build in a scope: the branch's nested bindings (text/attr/list effects)
|
|
483
490
|
// belong to this run and are disposed when the branch is replaced.
|
|
@@ -493,10 +500,14 @@ function childEffect(anchor, fn, current, skipFirst, currentScope = null, firstF
|
|
|
493
500
|
}
|
|
494
501
|
const next = built.result;
|
|
495
502
|
const host = anchor.parentNode;
|
|
503
|
+
// A node with an exit transition stays in place, inert, and removes itself
|
|
504
|
+
// when its animation ends (`tx.leave` returns true).
|
|
496
505
|
for (const n of current) {
|
|
497
|
-
if (n.parentNode === host) host.removeChild(n);
|
|
506
|
+
if (n.parentNode === host && !(tx.leave && tx.leave(n))) host.removeChild(n);
|
|
498
507
|
}
|
|
499
508
|
if (host) for (const n of next) host.insertBefore(n, anchor);
|
|
509
|
+
if (tx.enter && host) for (const n of next) tx.enter(n, initial);
|
|
510
|
+
initial = false;
|
|
500
511
|
if (currentScope) currentScope.dispose();
|
|
501
512
|
currentScope = built;
|
|
502
513
|
current = next;
|
|
@@ -566,6 +577,9 @@ function reconcileList(anchor, sourceFn, renderItem, keyFn, cache, prevKeys) {
|
|
|
566
577
|
// reorder can be spotted by identity.
|
|
567
578
|
const id = DEV && !keyFn ? listId++ : -1;
|
|
568
579
|
let prevItems = [];
|
|
580
|
+
// The first run renders the list's initial items; enter transitions skip them
|
|
581
|
+
// unless they opt in. A hydrated list adopts its first items, so none are new.
|
|
582
|
+
let initial = true;
|
|
569
583
|
const disposeEffect = effect(() => {
|
|
570
584
|
const data = sourceFn();
|
|
571
585
|
const items = Array.isArray(data) ? data : [];
|
|
@@ -609,7 +623,8 @@ function reconcileList(anchor, sourceFn, renderItem, keyFn, cache, prevKeys) {
|
|
|
609
623
|
// Remove nodes whose keys disappeared, and dispose their bindings.
|
|
610
624
|
for (const entry of cache.values()) {
|
|
611
625
|
if (entry.dispose) entry.dispose();
|
|
612
|
-
|
|
626
|
+
const node = entry.node;
|
|
627
|
+
if (node.parentNode && !(tx.leave && tx.leave(node))) node.parentNode.removeChild(node);
|
|
613
628
|
}
|
|
614
629
|
cache = next;
|
|
615
630
|
prevKeys = newKeys;
|
|
@@ -628,6 +643,10 @@ function reconcileList(anchor, sourceFn, renderItem, keyFn, cache, prevKeys) {
|
|
|
628
643
|
const ref = i + 1 < nodes.length ? nodes[i + 1] : anchor;
|
|
629
644
|
if (nodes[i].nextSibling !== ref) host.insertBefore(nodes[i], ref);
|
|
630
645
|
}
|
|
646
|
+
if (tx.enter) {
|
|
647
|
+
for (let i = 0; i < nodes.length; i++) if (prevIndex[i] === -1) tx.enter(nodes[i], initial);
|
|
648
|
+
}
|
|
649
|
+
initial = false;
|
|
631
650
|
});
|
|
632
651
|
return () => {
|
|
633
652
|
disposeEffect();
|
|
@@ -10,7 +10,7 @@ export class ErrorBoundaryElement extends HTMLElement {
|
|
|
10
10
|
connectedCallback(): void;
|
|
11
11
|
_mounted: boolean | undefined;
|
|
12
12
|
_blueprint: ChildNode[] | undefined;
|
|
13
|
-
catch(error: any): void;
|
|
13
|
+
catch(error: any, context?: { retry?: () => unknown }): void;
|
|
14
14
|
_failed: boolean | undefined;
|
|
15
15
|
reset(): void;
|
|
16
16
|
#private;
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
// effect/event errors still go to global reporting (as with React boundaries).
|
|
16
16
|
|
|
17
17
|
import { reportError } from "../core/errors.js";
|
|
18
|
+
import { routeErrorHandler } from "./route-errors.js";
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* Report a caught render/mount error and route it to the nearest enclosing
|
|
@@ -32,6 +33,8 @@ export function handleError(el, error, context = {}) {
|
|
|
32
33
|
const portal = node.closest ? node.closest("[data-afw-portal]") : null;
|
|
33
34
|
node = portal ? portal.__portalHost : null;
|
|
34
35
|
}
|
|
36
|
+
// No boundary: the router's `error.jsx` is the boundary of last resort.
|
|
37
|
+
routeErrorHandler()?.(el, error, context);
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
// A self-contained fallback (inline-styled so it reads fine without any app CSS).
|
|
@@ -78,7 +81,11 @@ export class ErrorBoundaryElement extends HTMLElement {
|
|
|
78
81
|
|
|
79
82
|
// Invoked by handleError when a descendant throws during render/mount. Deferred
|
|
80
83
|
// to a microtask so we never mutate the tree mid-connectedCallback (re-entrancy).
|
|
81
|
-
|
|
84
|
+
// `context.retry` (a failed `<Pending>` resource) is called on reset, after the
|
|
85
|
+
// subtree is back: a resource created outside the boundary is not rebuilt with it,
|
|
86
|
+
// so it has to be refetched explicitly.
|
|
87
|
+
catch(error, context = {}) {
|
|
88
|
+
if (typeof context.retry === "function") (this._retries ??= []).push(context.retry);
|
|
82
89
|
if (this._failed) return; // first error wins; ignore the cascade
|
|
83
90
|
this._failed = true;
|
|
84
91
|
queueMicrotask(() => this.#renderFallback(error));
|
|
@@ -111,6 +118,9 @@ export class ErrorBoundaryElement extends HTMLElement {
|
|
|
111
118
|
// now reading whatever props it currently holds — it may throw again
|
|
112
119
|
// (→ catch) or render cleanly if the cause is gone.
|
|
113
120
|
this.replaceChildren(...this._blueprint);
|
|
121
|
+
const retries = this._retries ?? [];
|
|
122
|
+
this._retries = [];
|
|
123
|
+
for (const retry of retries) retry();
|
|
114
124
|
});
|
|
115
125
|
}
|
|
116
126
|
}
|
package/runtime/head.js
CHANGED
|
@@ -9,7 +9,16 @@ export function prepareRouteHead(hydrate) {
|
|
|
9
9
|
if (canonical) {
|
|
10
10
|
try { baseUrl = new URL(canonical, window.location.href).origin; } catch {}
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
// The title to show for a page without one: the shell's. On a server-rendered page the
|
|
13
|
+
// shell's title is the unmanaged `<title>`, or — when the page had its own — the
|
|
14
|
+
// `afw-shell-title` the server kept; a client-rendered load reads the shell directly.
|
|
15
|
+
if (hydrate) {
|
|
16
|
+
const kept = document.head.querySelector('meta[name="afw-shell-title"]')?.getAttribute("content");
|
|
17
|
+
const shell = document.head.querySelector("title:not([data-afw-head])")?.textContent;
|
|
18
|
+
fallbackTitle = kept ?? shell ?? "";
|
|
19
|
+
} else {
|
|
20
|
+
fallbackTitle = document.title;
|
|
21
|
+
}
|
|
13
22
|
}
|
|
14
23
|
|
|
15
24
|
/** Replace route SEO while preserving styles, executable scripts and viewport. */
|
package/runtime/hmr.js
CHANGED
|
@@ -80,6 +80,8 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
|
|
|
80
80
|
};
|
|
81
81
|
return entry;
|
|
82
82
|
});
|
|
83
|
+
// For `registerHotHydrate`: the adopt factory marks its view with this record's `view`.
|
|
84
|
+
hot.data.afwRoute = record;
|
|
83
85
|
const updated = record.factory !== factory || record.shape !== shape;
|
|
84
86
|
record.factory = factory;
|
|
85
87
|
record.shape = shape;
|
|
@@ -93,6 +95,33 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
|
|
|
93
95
|
return record.view;
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
/**
|
|
99
|
+
* A development page's `hydrateAt`, registered for the route refresh. The adopt walk runs
|
|
100
|
+
* inside fresh refresh slots (its `$state` reads `hotRouteState`), and the adopted view is
|
|
101
|
+
* marked like a view `registerHotRoute` built, so an edit after hydration refreshes it with
|
|
102
|
+
* its state kept. `shape` is the same state shape `registerHotRoute` was given.
|
|
103
|
+
*/
|
|
104
|
+
export function registerHotHydrate(hot, adopt, shape = "") {
|
|
105
|
+
if (!hot) return adopt;
|
|
106
|
+
return (cursor, ...args) => {
|
|
107
|
+
const slots = new Map();
|
|
108
|
+
const outer = routeSlots;
|
|
109
|
+
routeSlots = slots;
|
|
110
|
+
let node;
|
|
111
|
+
try {
|
|
112
|
+
node = adopt(cursor, ...args);
|
|
113
|
+
} finally {
|
|
114
|
+
routeSlots = outer;
|
|
115
|
+
}
|
|
116
|
+
const record = hot.data.afwRoute;
|
|
117
|
+
if (record && node) {
|
|
118
|
+
node.__afwHotFactory = record.view;
|
|
119
|
+
node.__afwHotSlots = { shape, slots };
|
|
120
|
+
}
|
|
121
|
+
return node;
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
96
125
|
export function hotState(host, key, create) {
|
|
97
126
|
// A new element built by a refresh picks up the state of the one it replaces.
|
|
98
127
|
if (!host.__afwHotCarried) {
|
package/runtime/index.d.ts
CHANGED
|
@@ -10,7 +10,11 @@ export { invalidate } from "./invalidate.js";
|
|
|
10
10
|
export { ServerFunctionError, serverFunction } from "./server-function.js";
|
|
11
11
|
export * from "./context.js";
|
|
12
12
|
export * from "./error-boundary.js";
|
|
13
|
+
export * from "./pending.js";
|
|
14
|
+
export { enterPending, exitPending } from "./pending-scope.js";
|
|
13
15
|
export * from "./portal.js";
|
|
14
16
|
export * from "./raw-html.js";
|
|
15
17
|
export * from "./code-block.js";
|
|
16
18
|
export * from "./clipboard.js";
|
|
19
|
+
export { setTransition } from "./transition.js";
|
|
20
|
+
export { lazyComponent, type Lazy } from "./lazy.js";
|
package/runtime/index.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// force the registration side effect to be retained.
|
|
5
5
|
import "./context.js";
|
|
6
6
|
import "./error-boundary.js";
|
|
7
|
+
import "./pending.js";
|
|
7
8
|
import "./portal.js";
|
|
8
9
|
import "./raw-html.js";
|
|
9
10
|
import "./code-block.js";
|
|
@@ -20,7 +21,11 @@ export { invalidate } from "./invalidate.js";
|
|
|
20
21
|
export { ServerFunctionError, serverFunction } from "./server-function.js";
|
|
21
22
|
export * from "./context.js";
|
|
22
23
|
export * from "./error-boundary.js";
|
|
24
|
+
export * from "./pending.js";
|
|
25
|
+
export { enterPending, exitPending } from "./pending-scope.js";
|
|
23
26
|
export * from "./portal.js";
|
|
24
27
|
export * from "./raw-html.js";
|
|
25
28
|
export * from "./code-block.js";
|
|
26
29
|
export * from "./clipboard.js";
|
|
30
|
+
export { setTransition } from "./transition.js";
|
|
31
|
+
export { lazyComponent } from "./lazy.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A lazy component's loader: `const Chart: Lazy<typeof ChartComponent> = () => import("./Chart.jsx")`.
|
|
3
|
+
* The annotation is optional: TypeScript infers the loader's type, and JSX takes the
|
|
4
|
+
* props from the component it loads. Calling it preloads the component.
|
|
5
|
+
*/
|
|
6
|
+
export type Lazy<C> = () => Promise<{ default: C } | C>;
|
|
7
|
+
/** Compiler-emitted: the loader, callable to preload, with the placeholder's `tag`. */
|
|
8
|
+
export function lazyComponent<L extends () => Promise<unknown>>(loader: L, tag: string): L & { readonly tag: string };
|
package/runtime/lazy.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Lazy components: `const Chart = () => import("./Chart.jsx")` at module level, used
|
|
2
|
+
// as `<Chart …/>`. The compiler rewrites the declaration to
|
|
3
|
+
// `lazyComponent(<the same loader>, "<stable tag>")`, so the bundler still splits
|
|
4
|
+
// `Chart.jsx` into its own chunk and `<Chart>` compiles like any component (by `.tag`).
|
|
5
|
+
//
|
|
6
|
+
// The tag is a placeholder element. It keeps the props and children it is given, loads
|
|
7
|
+
// the chunk when it first connects (one download for every instance), then creates the
|
|
8
|
+
// real component, hands it the props and children, and forwards later prop updates and
|
|
9
|
+
// the component's `$expose`d methods. While it loads it counts as loading for the
|
|
10
|
+
// nearest <Pending>; a failed download goes where other errors go. It renders only in
|
|
11
|
+
// the browser: the server sends the empty placeholder (server/builtins.js).
|
|
12
|
+
|
|
13
|
+
import { signal } from "../core/signals.js";
|
|
14
|
+
import { setProp } from "./dom.js";
|
|
15
|
+
import { handleError } from "./error-boundary.js";
|
|
16
|
+
import { hydrationProps } from "./hydrate.js";
|
|
17
|
+
import { closestPending } from "./pending-scope.js";
|
|
18
|
+
|
|
19
|
+
/** The component a loader resolved to: a module's default export, or the component itself. */
|
|
20
|
+
function componentOf(loaded) {
|
|
21
|
+
if (loaded && typeof loaded.tag === "string") return loaded;
|
|
22
|
+
const component = loaded?.default;
|
|
23
|
+
if (component && typeof component.tag === "string") return component;
|
|
24
|
+
throw new TypeError("a lazy component's import() must resolve to a module whose default export is a component, or to a component (.then((m) => m.Name))");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Compiler-emitted. Returns the loader, callable to preload (`Chart()`), with the
|
|
29
|
+
* placeholder's `tag` (registered on first read, like a compiled component's).
|
|
30
|
+
*/
|
|
31
|
+
export function lazyComponent(loader, tag) {
|
|
32
|
+
let pending = null;
|
|
33
|
+
let component = null;
|
|
34
|
+
const load = () =>
|
|
35
|
+
(pending ??= Promise.resolve()
|
|
36
|
+
.then(loader)
|
|
37
|
+
.then((loaded) => (component = componentOf(loaded))));
|
|
38
|
+
|
|
39
|
+
class LazyElement extends HTMLElement {
|
|
40
|
+
#props = new Map();
|
|
41
|
+
#inner = null;
|
|
42
|
+
#loading = signal(true);
|
|
43
|
+
#loaded = signal(false);
|
|
44
|
+
#boundary = null;
|
|
45
|
+
#handle = {
|
|
46
|
+
loading: () => this.#loading.value,
|
|
47
|
+
settled: () => this.#loaded.value,
|
|
48
|
+
// A failed import() is cached by the browser for the page's life: retry reloads it.
|
|
49
|
+
refetch: () => globalThis.location?.reload(),
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
#read = false;
|
|
53
|
+
|
|
54
|
+
constructor() {
|
|
55
|
+
super();
|
|
56
|
+
// Compiler-emitted props reach a lazy host here (setProp / spread), not as attributes.
|
|
57
|
+
this.__afwLazy = { set: (name, value) => this.#set(name, value) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
#set(name, value) {
|
|
61
|
+
this.#props.set(name, value);
|
|
62
|
+
if (this.#inner) setProp(this.#inner, name, value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
connectedCallback() {
|
|
66
|
+
if (!this.shadowRoot) {
|
|
67
|
+
// Shows nothing until the component arrives (the children stay in the light DOM).
|
|
68
|
+
const root = this.attachShadow({ mode: "open" });
|
|
69
|
+
const style = document.createElement("style");
|
|
70
|
+
style.textContent = ":host{display:contents}";
|
|
71
|
+
root.append(style);
|
|
72
|
+
}
|
|
73
|
+
if (this.#inner) return;
|
|
74
|
+
// Props the server rendered this placeholder with (the hydration payload). Read on
|
|
75
|
+
// connect, not in the constructor: a parser-created element gets its attributes
|
|
76
|
+
// after construction. Props set since then win.
|
|
77
|
+
if (!this.#read) {
|
|
78
|
+
this.#read = true;
|
|
79
|
+
const props = hydrationProps(this);
|
|
80
|
+
if (props) for (const key in props) if (!this.#props.has(key)) this.#props.set(key, props[key]);
|
|
81
|
+
}
|
|
82
|
+
if (!this.#boundary) {
|
|
83
|
+
this.#boundary = closestPending(this);
|
|
84
|
+
this.#boundary?.__track(this.#handle);
|
|
85
|
+
}
|
|
86
|
+
load().then(() => this.#mount(), (error) => this.#fail(error));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
disconnectedCallback() {
|
|
90
|
+
queueMicrotask(() => {
|
|
91
|
+
if (this.isConnected || !this.#boundary) return;
|
|
92
|
+
this.#boundary.__untrack(this.#handle);
|
|
93
|
+
this.#boundary = null;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
#mount() {
|
|
98
|
+
if (this.#inner || !this.isConnected) return;
|
|
99
|
+
const inner = document.createElement(component.tag);
|
|
100
|
+
for (const [name, value] of this.#props) setProp(inner, name, value);
|
|
101
|
+
// `on*` callback props are assigned to a component directly (`el.onpicked = fn`):
|
|
102
|
+
// on this placeholder they are own properties, or — for a name the DOM already
|
|
103
|
+
// has, like `onchange` — its built-in handler property. Hand both over.
|
|
104
|
+
for (const key in this) {
|
|
105
|
+
if (/^on[A-Za-z]/.test(key) && typeof this[key] === "function") {
|
|
106
|
+
setProp(inner, key, this[key]);
|
|
107
|
+
this[key] = null; // the component owns it now; don't also fire on the placeholder
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
inner.append(...this.childNodes);
|
|
111
|
+
this.#inner = inner;
|
|
112
|
+
this.append(inner); // connects it: its body runs and its `$expose` methods land
|
|
113
|
+
this.shadowRoot.append(document.createElement("slot"));
|
|
114
|
+
// A parent's ref points at this placeholder: forward the exposed methods.
|
|
115
|
+
for (const key of Object.keys(inner)) {
|
|
116
|
+
if (typeof inner[key] === "function" && !(key in this)) this[key] = (...args) => inner[key](...args);
|
|
117
|
+
}
|
|
118
|
+
this.#loading.value = false;
|
|
119
|
+
this.#loaded.value = true;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
#fail(error) {
|
|
123
|
+
this.#loading.value = false;
|
|
124
|
+
if (this.#boundary) this.#boundary.__fail(error, this.#handle);
|
|
125
|
+
else handleError(this, error, { phase: "lazy", retry: this.#handle.refetch });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const define = () => {
|
|
130
|
+
if (typeof customElements !== "undefined" && !customElements.get(tag)) customElements.define(tag, LazyElement);
|
|
131
|
+
};
|
|
132
|
+
const lazy = () => load();
|
|
133
|
+
Object.defineProperty(lazy, "tag", { get: () => (define(), tag) });
|
|
134
|
+
return lazy;
|
|
135
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Compiler-emitted around the build of a `<Pending>`'s children. */
|
|
2
|
+
export function enterPending(el: Element): void;
|
|
3
|
+
/** Compiler-emitted after the build of a `<Pending>`'s children. */
|
|
4
|
+
export function exitPending(): void;
|
|
5
|
+
export function buildingPending(): Element | null;
|
|
6
|
+
export function closestPending(node: Node): Element | null;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// How a resource finds the `<Pending>` boundaries that wait on it (pending.js).
|
|
2
|
+
// Kept apart from the element so resource.js stays small.
|
|
3
|
+
//
|
|
4
|
+
// - A resource created in a component under a boundary: the component's host is
|
|
5
|
+
// connected by then, so the boundary is its nearest `afw-internal-pending`
|
|
6
|
+
// ancestor (hopping across portals, like context).
|
|
7
|
+
// - A resource read while a boundary's children are being built (a page resource
|
|
8
|
+
// passed down as props): the compiler brackets that build with
|
|
9
|
+
// `enterPending` / `exitPending`, and the read registers with that boundary.
|
|
10
|
+
|
|
11
|
+
const building = [];
|
|
12
|
+
|
|
13
|
+
/** Compiler-emitted around the build of a `<Pending>`'s children. */
|
|
14
|
+
export function enterPending(el) {
|
|
15
|
+
building.push(el);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Compiler-emitted (in a `finally`) after the build of a `<Pending>`'s children. */
|
|
19
|
+
export function exitPending() {
|
|
20
|
+
const el = building.pop();
|
|
21
|
+
el?.__built?.();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The boundary whose children are being built right now, or null. */
|
|
25
|
+
export function buildingPending() {
|
|
26
|
+
return building.length ? building[building.length - 1] : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The nearest `<Pending>` around `node`, across portals, or null. */
|
|
30
|
+
export function closestPending(node) {
|
|
31
|
+
let el = node;
|
|
32
|
+
while (el && el.closest) {
|
|
33
|
+
const boundary = el.closest("afw-internal-pending");
|
|
34
|
+
if (boundary) return boundary;
|
|
35
|
+
const portal = el.closest("[data-afw-portal]");
|
|
36
|
+
el = portal ? portal.__portalHost : null;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export class PendingElement extends HTMLElement {
|
|
2
|
+
fallback: unknown;
|
|
3
|
+
refreshing: unknown;
|
|
4
|
+
refetch: "keep" | "fallback";
|
|
5
|
+
error: ((error: unknown, retry: () => void) => unknown) | null;
|
|
6
|
+
delay: number;
|
|
7
|
+
__track(handle: unknown): void;
|
|
8
|
+
__untrack(handle: unknown): void;
|
|
9
|
+
__built(): void;
|
|
10
|
+
__fail(error: unknown, handle: unknown): void;
|
|
11
|
+
}
|
|
12
|
+
/** JSX props consumed by the compiler-generated custom-element host. */
|
|
13
|
+
export const Pending: {
|
|
14
|
+
new(props: {
|
|
15
|
+
/** Shown until every resource inside has loaded once. */
|
|
16
|
+
fallback?: unknown;
|
|
17
|
+
/** Shown beside the content while a resource inside refetches. */
|
|
18
|
+
refreshing?: unknown;
|
|
19
|
+
/** `"keep"` (default): the content stays during a refetch. `"fallback"`: show the fallback again. */
|
|
20
|
+
refetch?: "keep" | "fallback";
|
|
21
|
+
/**
|
|
22
|
+
* Show a failed first load here: `(error, retry) => view`. `retry` refetches what failed.
|
|
23
|
+
* Without it, the failure goes to the nearest `<ErrorBoundary>` or `error.jsx`.
|
|
24
|
+
*/
|
|
25
|
+
error?: (error: unknown, retry: () => void) => unknown;
|
|
26
|
+
/** Milliseconds to wait before showing `fallback` or `refreshing`; a faster load shows neither. Default 0. */
|
|
27
|
+
delay?: number;
|
|
28
|
+
children?: unknown;
|
|
29
|
+
}): PendingElement;
|
|
30
|
+
prototype: PendingElement;
|
|
31
|
+
};
|