@opentf/afw 0.32.0 → 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 +93 -36
- package/core/metadata.js +2 -0
- package/package.json +11 -5
- package/runtime/hmr.js +36 -7
- package/runtime/hydrate.d.ts +6 -0
- package/runtime/hydrate.js +48 -0
- package/runtime/mount.js +3 -0
- package/runtime/router.d.ts +3 -0
- package/runtime/router.js +53 -11
- package/server/index.d.ts +4 -0
- package/server/index.js +1 -1
- package/server/render.js +3 -0
- package/server/ssg-runtime.js +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Open Tech Foundation and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,26 +1,98 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
1
3
|
# @opentf/afw
|
|
2
4
|
|
|
3
|
-
The
|
|
4
|
-
|
|
5
|
+
***The AFW runtime: signals and zero-VDOM DOM bindings***
|
|
6
|
+
|
|
7
|
+
[Docs](https://afw.opentechf.org/docs) | [Reactivity](https://afw.opentechf.org/docs/core-concepts/reactivity) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
|
|
8
|
+
|
|
9
|
+
</div>
|
|
10
|
+
|
|
11
|
+
<div align="right">
|
|
12
|
+
|
|
13
|
+
*An [Open Tech Foundation](https://opentechf.org/) project*
|
|
14
|
+
|
|
15
|
+
</div>
|
|
16
|
+
|
|
17
|
+
> You write `.jsx` components; the AFW compiler lowers them to plain DOM code that
|
|
18
|
+
> imports its helpers from this package. Each component becomes a self-registering
|
|
19
|
+
> Custom Element, and each `{expression}` becomes one binding to one signal.
|
|
20
|
+
|
|
21
|
+
```jsx
|
|
22
|
+
import { onMount } from "@opentf/afw";
|
|
5
23
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`bindText`, `bindList`, …) from this package. Components compile to self-registering
|
|
9
|
-
`web-*` Custom Elements.
|
|
24
|
+
export default function Clock() {
|
|
25
|
+
let now = $state(null);
|
|
10
26
|
|
|
11
|
-
|
|
27
|
+
onMount(() => {
|
|
28
|
+
now = new Date();
|
|
29
|
+
const id = setInterval(() => (now = new Date()), 1000);
|
|
30
|
+
return () => clearInterval(id);
|
|
31
|
+
});
|
|
12
32
|
|
|
13
|
-
|
|
33
|
+
return <time>{now ? now.toLocaleTimeString() : "Loading clock…"}</time>;
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Every second, one text node changes; nothing else on the page is touched.
|
|
38
|
+
Returning a function from `onMount` registers its cleanup.
|
|
39
|
+
|
|
40
|
+
> [!NOTE]
|
|
41
|
+
> **Alpha.** The API can change between minor versions; see the
|
|
42
|
+
> [changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw/CHANGELOG.md).
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```sh
|
|
14
47
|
pnpm add @opentf/afw
|
|
48
|
+
pnpm add -D @opentf/esdev-plugin-afw
|
|
15
49
|
```
|
|
16
50
|
|
|
17
|
-
|
|
18
|
-
|
|
51
|
+
Components compile through [`@opentf/esdev-plugin-afw`](https://www.npmjs.com/package/@opentf/esdev-plugin-afw)
|
|
52
|
+
on [esdev](https://esrun.opentechf.org/esdev) 0.17 or newer. To start from a
|
|
53
|
+
working app instead, run `esdev create my-app --template=spa`.
|
|
54
|
+
|
|
55
|
+
## What's inside
|
|
56
|
+
|
|
57
|
+
| Area | Contents |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| **Reactivity** | A signal / computed / effect core, written from scratch |
|
|
60
|
+
| **DOM bindings** | `bindText`, `bindAttr`, `bindList`, `bindChild`, `setProp`, `spread`, `clsx`: the targets the compiler emits |
|
|
61
|
+
| **Components** | `Context`, `Portal`, `ErrorBoundary`, event dispatch with `emit` |
|
|
62
|
+
| **Routing** | `mountApp`, the reactive `router`, `<Link>`, guards, loaders, locale prefixes |
|
|
63
|
+
| **Server** | DOM-free SSR/SSG rendering, API routes, middleware, cookies, a Node adapter |
|
|
64
|
+
|
|
65
|
+
## Macros and hooks
|
|
66
|
+
|
|
67
|
+
Written in your components and resolved by the compiler; nothing to import for the
|
|
68
|
+
`$` macros.
|
|
69
|
+
|
|
70
|
+
| Macro / hook | Purpose |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `$state(value)` | Reactive local state; assign to it like a variable |
|
|
73
|
+
| `$derived(expr)` | A value recomputed when its inputs change |
|
|
74
|
+
| `$effect(fn)` | Run side effects when their inputs change |
|
|
75
|
+
| `$ref()` | A reference to a rendered element or component |
|
|
76
|
+
| `$context(Context)` | Read the nearest provided context value |
|
|
77
|
+
| `$expose({ … })` | Methods a parent can call through a ref |
|
|
78
|
+
| `onMount`, `onCleanup` | Lifecycle of the component's host element |
|
|
79
|
+
| `onResize`, `onVisibilityChange`, `onMediaQuery` | Observers that clean up with the component |
|
|
80
|
+
|
|
81
|
+
## Entry points
|
|
82
|
+
|
|
83
|
+
| Import | Contents |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `@opentf/afw` | Runtime, reactivity and `Link`: what compiled components import |
|
|
86
|
+
| `@opentf/afw/signals` | The reactivity core on its own |
|
|
87
|
+
| `@opentf/afw/runtime` | DOM helpers, `Context`, `Portal`, `ErrorBoundary` |
|
|
88
|
+
| `@opentf/afw/server` | DOM-free rendering, route registration, API and middleware helpers |
|
|
89
|
+
| `@opentf/afw/server/adapters/node` | `toNodeListener` for `node:http` servers |
|
|
90
|
+
| `@opentf/afw/jsx-runtime` | JSX type definitions for TypeScript |
|
|
19
91
|
|
|
20
92
|
## TypeScript
|
|
21
93
|
|
|
22
|
-
|
|
23
|
-
|
|
94
|
+
Declarations ship with the package. Keep JSX for the AFW compiler and point
|
|
95
|
+
`jsxImportSource` at this package:
|
|
24
96
|
|
|
25
97
|
```json
|
|
26
98
|
{
|
|
@@ -35,33 +107,18 @@ JSX for the AFW compiler and select the framework's type entry:
|
|
|
35
107
|
}
|
|
36
108
|
```
|
|
37
109
|
|
|
38
|
-
`esdev create my-app --language=ts`
|
|
39
|
-
declarations.
|
|
40
|
-
still runs through `@opentf/esdev-plugin-afw`. Compiler helper signatures remain
|
|
41
|
-
permissive; signals and lifecycle callbacks carry their value and event types.
|
|
42
|
-
|
|
43
|
-
## What's inside
|
|
44
|
-
|
|
45
|
-
- **Reactivity** — a from-scratch `signal` / `computed` / `effect` core.
|
|
46
|
-
- **DOM runtime** — fine-grained bindings (`bindText`, `bindAttr`, `bindList`,
|
|
47
|
-
`bindChild`, `setProp`, `spread`, `clsx`) the compiler targets, plus `Context`,
|
|
48
|
-
`Portal`, `ErrorBoundary`, and event dispatch (`emit`).
|
|
49
|
-
- **Compiler macros** — authored in your components, resolved at compile time:
|
|
50
|
-
`$state`, `$derived`, `$ref`, `$context`, `$effect`, `$expose`, and the
|
|
51
|
-
`onMount` / `onCleanup` / `onResize` / `onVisibilityChange` / `onMediaQuery`
|
|
52
|
-
lifecycle hooks.
|
|
53
|
-
- **`<Link>`** — client-side navigation, shipped as JSX source and compiled by your
|
|
54
|
-
app's pipeline.
|
|
110
|
+
`esdev create my-app --language=ts` generates this configuration together with the
|
|
111
|
+
macro declarations.
|
|
55
112
|
|
|
56
|
-
##
|
|
113
|
+
## Documentation
|
|
57
114
|
|
|
58
|
-
|
|
|
115
|
+
| Topic | Link |
|
|
59
116
|
| --- | --- |
|
|
60
|
-
|
|
|
61
|
-
|
|
|
62
|
-
|
|
|
63
|
-
|
|
|
117
|
+
| Components and JSX | [Core concepts](https://afw.opentechf.org/docs/core-concepts/components) |
|
|
118
|
+
| Reactivity | [Signals, derived values and effects](https://afw.opentechf.org/docs/core-concepts/reactivity) |
|
|
119
|
+
| Routing | [Pages, layouts, guards and API routes](https://afw.opentechf.org/docs/routing/pages-and-layouts) |
|
|
120
|
+
| Deployment | [Static generation, hydration and servers](https://afw.opentechf.org/docs/deployment) |
|
|
64
121
|
|
|
65
122
|
## License
|
|
66
123
|
|
|
67
|
-
MIT
|
|
124
|
+
MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
|
package/core/metadata.js
CHANGED
|
@@ -134,6 +134,8 @@ export function renderHead(meta = {}, { path = "/", baseUrl = "", managed = fals
|
|
|
134
134
|
push(metaTag("property", "og:url", og.url ? absUrl(baseUrl, og.url) : canonical));
|
|
135
135
|
push(metaTag("property", "og:image", ogImage));
|
|
136
136
|
push(metaTag("property", "og:site_name", og.siteName));
|
|
137
|
+
push(metaTag("property", "og:locale", og.locale));
|
|
138
|
+
for (const alt of [].concat(og.alternateLocale ?? [])) push(metaTag("property", "og:locale:alternate", alt));
|
|
137
139
|
|
|
138
140
|
// Twitter Card (falls back to Open Graph / top-level values).
|
|
139
141
|
const tw = isPlainObject(meta.twitter) ? meta.twitter : {};
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The
|
|
3
|
+
"version": "0.33.0",
|
|
4
|
+
"description": "The AFW runtime: signals and zero-VDOM DOM bindings, with routing and server rendering.",
|
|
5
5
|
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"build": "cp ../../LICENSE LICENSE"
|
|
8
|
+
},
|
|
6
9
|
"exports": {
|
|
7
10
|
".": {
|
|
8
11
|
"types": "./index.d.ts",
|
|
@@ -40,11 +43,14 @@
|
|
|
40
43
|
"!**/*.test.js"
|
|
41
44
|
],
|
|
42
45
|
"keywords": [
|
|
46
|
+
"afw",
|
|
43
47
|
"opentf",
|
|
44
|
-
"web-components",
|
|
45
48
|
"signals",
|
|
46
49
|
"reactivity",
|
|
47
|
-
"
|
|
50
|
+
"web-components",
|
|
51
|
+
"custom-elements",
|
|
52
|
+
"jsx",
|
|
53
|
+
"ssr",
|
|
48
54
|
"ssg"
|
|
49
55
|
],
|
|
50
56
|
"repository": {
|
|
@@ -52,7 +58,7 @@
|
|
|
52
58
|
"url": "https://github.com/Open-Tech-Foundation/afw.git",
|
|
53
59
|
"directory": "packages/afw"
|
|
54
60
|
},
|
|
55
|
-
"homepage": "https://
|
|
61
|
+
"homepage": "https://afw.opentechf.org",
|
|
56
62
|
"bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
|
|
57
63
|
"license": "MIT",
|
|
58
64
|
"publishConfig": {
|
package/runtime/hmr.js
CHANGED
|
@@ -19,12 +19,19 @@ export function hotRouteState(key, create) {
|
|
|
19
19
|
return routeSlots.get(key);
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* `exports` is the source of the page's exports other than its view and the route data the
|
|
24
|
+
* router re-reads (see the compiler's `hot_exports_shape`). Importers hold the old values,
|
|
25
|
+
* so a change there reloads; an edit to the view, its metadata or its headings refreshes.
|
|
26
|
+
*/
|
|
27
|
+
export function registerHotRoute(hot, factory, shape = "", exports = "", data = {}) {
|
|
23
28
|
if (!hot) return factory;
|
|
24
|
-
if (
|
|
25
|
-
|
|
29
|
+
if (hot.data.afwRouteBoundary && hot.data.afwExports !== exports) {
|
|
30
|
+
hot.data.afwExports = exports;
|
|
31
|
+
hot.invalidate();
|
|
26
32
|
return factory;
|
|
27
33
|
}
|
|
34
|
+
hot.data.afwExports = exports;
|
|
28
35
|
hot.data.afwRouteBoundary = true;
|
|
29
36
|
const record = hot.keep("afw-route", () => {
|
|
30
37
|
const entry = { factory, shape };
|
|
@@ -61,9 +68,12 @@ export function registerHotRoute(hot, factory, safe, shape = "") {
|
|
|
61
68
|
const updated = record.factory !== factory || record.shape !== shape;
|
|
62
69
|
record.factory = factory;
|
|
63
70
|
record.shape = shape;
|
|
71
|
+
// `data`: this update's `metadata`/`generateMetadata`/`toc`, which the router's import of
|
|
72
|
+
// the route (the original module) would not see.
|
|
73
|
+
record.data = data;
|
|
64
74
|
hot.accept();
|
|
65
75
|
if (updated) queueMicrotask(() => {
|
|
66
|
-
if (!hot.data.afwInvalidated) void refreshHotRoute(record.view);
|
|
76
|
+
if (!hot.data.afwInvalidated) void refreshHotRoute(record.view, record.data);
|
|
67
77
|
});
|
|
68
78
|
return record.view;
|
|
69
79
|
}
|
|
@@ -111,16 +121,35 @@ function refresh(record, hosts) {
|
|
|
111
121
|
}
|
|
112
122
|
}
|
|
113
123
|
|
|
114
|
-
|
|
124
|
+
/**
|
|
125
|
+
* `exports` is the source of the module's exports other than its components: importers
|
|
126
|
+
* hold the old values, so a change there reloads, while an edit to the components alone
|
|
127
|
+
* refreshes them in place. Each entry's shape covers what a refresh can't carry over
|
|
128
|
+
* (props, state declarations, the exposed method names).
|
|
129
|
+
*/
|
|
130
|
+
/**
|
|
131
|
+
* `$expose` in a development build: publish `api` on the host like `Object.assign`, after
|
|
132
|
+
* removing whatever the previous version of the component exposed there. A refresh
|
|
133
|
+
* re-runs the component on the same host, so a renamed or removed method would otherwise
|
|
134
|
+
* linger beside its replacement.
|
|
135
|
+
*/
|
|
136
|
+
export function hotExpose(host, api) {
|
|
137
|
+
for (const key of host.__afwExposed ?? []) if (!(key in api)) delete host[key];
|
|
138
|
+
Object.assign(host, api);
|
|
139
|
+
host.__afwExposed = Object.keys(api);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function registerHotModule(hot, entries, accept = true, exports = "") {
|
|
115
143
|
const signature = entries.map(([component, shape]) => [component.tag, shape]);
|
|
116
144
|
const previous = hot?.data.afwSignature;
|
|
117
|
-
if (previous && (
|
|
145
|
+
if (previous && (JSON.stringify(previous) !== JSON.stringify(signature) || hot.data.afwExports !== exports)) {
|
|
118
146
|
hot.data.afwInvalidated = true;
|
|
119
147
|
hot.invalidate();
|
|
120
148
|
return;
|
|
121
149
|
}
|
|
122
150
|
if (hot) {
|
|
123
151
|
hot.data.afwSignature = signature;
|
|
152
|
+
hot.data.afwExports = exports;
|
|
124
153
|
hot.data.afwInvalidated = false;
|
|
125
154
|
}
|
|
126
155
|
const changed = [];
|
|
@@ -166,5 +195,5 @@ export function registerHotModule(hot, entries, safe, accept = true) {
|
|
|
166
195
|
}));
|
|
167
196
|
jobs.sort((a, b) => a.depth - b.depth);
|
|
168
197
|
for (const { record, host } of jobs) refresh(record, [host]);
|
|
169
|
-
if (
|
|
198
|
+
if (accept) hot?.accept();
|
|
170
199
|
}
|
package/runtime/hydrate.d.ts
CHANGED
|
@@ -171,3 +171,9 @@ export const SLOT_END: "c]";
|
|
|
171
171
|
export class HydrationMismatch extends Error {
|
|
172
172
|
constructor(message: any);
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Adopt a `<p>` holding a component, past its `<!--p]-->` end marker: kept as served when
|
|
176
|
+
* the parser left it intact, rebuilt with `build()` when a block element in a component
|
|
177
|
+
* made the parser close it early. Compiler-emitted.
|
|
178
|
+
*/
|
|
179
|
+
export function hydrateParagraph(cur: any, adopt: (el: any) => void, build: () => any): any;
|
package/runtime/hydrate.js
CHANGED
|
@@ -285,6 +285,54 @@ export function claimElement(cur, tag) {
|
|
|
285
285
|
return el;
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
+
/**
|
|
289
|
+
* Adopt a `<p>` holding a component (a *recoverable region*), advancing the cursor past
|
|
290
|
+
* its `<!--p]-->` end marker. The compiler cannot see a component's markup, and a block
|
|
291
|
+
* element in it (`<div>`) makes the HTML parser close the `<p>` early, moving the rest of
|
|
292
|
+
* the paragraph out after it. So:
|
|
293
|
+
*
|
|
294
|
+
* - intact (the component rendered inline markup, the common case): `adopt(el)` wires the
|
|
295
|
+
* served paragraph and the marker follows it directly. Nothing is rebuilt.
|
|
296
|
+
* - restructured: `adopt` throws {@link HydrationMismatch}, or nodes the parser moved out
|
|
297
|
+
* sit between the `<p>` and its marker. Everything from the `<p>` up to the marker is
|
|
298
|
+
* removed and `build()` puts a fresh paragraph in its place. One paragraph is rebuilt,
|
|
299
|
+
* not the whole view. (The build warned about it: see `ssgParagraph`.)
|
|
300
|
+
*
|
|
301
|
+
* Comments are never moved by the parser, so the marker always ends the region. Without
|
|
302
|
+
* one there is no boundary to recover inside, and the mismatch propagates as before.
|
|
303
|
+
*/
|
|
304
|
+
export function hydrateParagraph(cur, adopt, build) {
|
|
305
|
+
const el = claimElement(cur, "p");
|
|
306
|
+
let intact = true;
|
|
307
|
+
try {
|
|
308
|
+
adopt(el);
|
|
309
|
+
} catch (e) {
|
|
310
|
+
if (!(e instanceof HydrationMismatch)) throw e;
|
|
311
|
+
intact = false;
|
|
312
|
+
}
|
|
313
|
+
let end = el.nextSibling;
|
|
314
|
+
if (intact && isParagraphEnd(end)) {
|
|
315
|
+
cur.node = end.nextSibling;
|
|
316
|
+
return el;
|
|
317
|
+
}
|
|
318
|
+
while (end && !isParagraphEnd(end)) end = end.nextSibling;
|
|
319
|
+
if (!end) throw new HydrationMismatch("expected a <!--p]--> paragraph end marker");
|
|
320
|
+
const parent = end.parentNode;
|
|
321
|
+
for (let n = el; n !== end; ) {
|
|
322
|
+
const next = n.nextSibling;
|
|
323
|
+
parent.removeChild(n);
|
|
324
|
+
n = next;
|
|
325
|
+
}
|
|
326
|
+
// A build, not an adoption: the components in the fresh paragraph must build their
|
|
327
|
+
// own markup rather than look for server nodes that were just removed.
|
|
328
|
+
const fresh = runBuild(build);
|
|
329
|
+
parent.insertBefore(fresh, end);
|
|
330
|
+
cur.node = end.nextSibling;
|
|
331
|
+
return fresh;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const isParagraphEnd = (n) => n?.nodeType === 8 && n.data === "p]";
|
|
335
|
+
|
|
288
336
|
/**
|
|
289
337
|
* Claim a dynamic text hole delimited by `<!--$-->…<!--/-->`, returning the text node
|
|
290
338
|
* to bind onto (created empty when the server rendered no value), and advance the
|
package/runtime/mount.js
CHANGED
|
@@ -26,6 +26,9 @@ export function buildScopedView(view) {
|
|
|
26
26
|
try {
|
|
27
27
|
const lc = (node.__lifecycle ??= { mounts: [], cleanups: [] });
|
|
28
28
|
lc.cleanups.push(owned.dispose);
|
|
29
|
+
// A fragment root (an MDX page, a `<>…</>` view) is empty once inserted. Keep the
|
|
30
|
+
// nodes it held, so the router can still find the view to replace or re-parent.
|
|
31
|
+
if (node.nodeType === 11) node.__afwNodes = Array.from(node.childNodes);
|
|
29
32
|
return node;
|
|
30
33
|
} catch (error) {
|
|
31
34
|
try { owned.dispose(); } catch (cleanupError) { console.error(cleanupError); }
|
package/runtime/router.d.ts
CHANGED
|
@@ -80,6 +80,7 @@ export function resolveModule(entry: any): Promise<any>;
|
|
|
80
80
|
* so a page reading `router.pathname`/`params`/`query` resolves to the route being
|
|
81
81
|
* pre-rendered. The client uses `navigate` instead.
|
|
82
82
|
*/
|
|
83
|
+
export function setRouteToc(pageModule: any): void;
|
|
83
84
|
export function setRouteState({ pathname, search, params, locale, data }?: {
|
|
84
85
|
locale?: string | null;
|
|
85
86
|
data?: unknown;
|
|
@@ -141,6 +142,8 @@ export namespace router {
|
|
|
141
142
|
const params: any;
|
|
142
143
|
const locale: any;
|
|
143
144
|
const data: any;
|
|
145
|
+
/** The current page's headings (MDX `export const toc`), or `[]`. */
|
|
146
|
+
const toc: { depth: number; id: string; text: string }[];
|
|
144
147
|
function push(path: any): Promise<void>;
|
|
145
148
|
function replace(path: any): Promise<void>;
|
|
146
149
|
}
|
package/runtime/router.js
CHANGED
|
@@ -40,6 +40,7 @@ const state = {
|
|
|
40
40
|
params: signal({}),
|
|
41
41
|
locale: signal(null),
|
|
42
42
|
data: signal(undefined),
|
|
43
|
+
toc: signal([]),
|
|
43
44
|
};
|
|
44
45
|
|
|
45
46
|
export const routes = { pages: {}, layouts: {}, notFound: null, loaderRoutes: new Set() };
|
|
@@ -154,6 +155,10 @@ export const router = {
|
|
|
154
155
|
get data() {
|
|
155
156
|
return routeValue("data");
|
|
156
157
|
},
|
|
158
|
+
/** The current page's headings (`export const toc`, emitted for MDX), or `[]`. */
|
|
159
|
+
get toc() {
|
|
160
|
+
return routeValue("toc");
|
|
161
|
+
},
|
|
157
162
|
push: (path) => navigate(path),
|
|
158
163
|
replace: (path) => navigate(path, true),
|
|
159
164
|
};
|
|
@@ -267,6 +272,7 @@ export async function buildRouteNode(match, query = {}) {
|
|
|
267
272
|
const modules = [...layoutModules, pageModule].map(namespace);
|
|
268
273
|
const pageFactory = pageModule?.default ?? pageModule;
|
|
269
274
|
const layoutFactories = layoutModules.map(module => module?.default ?? module);
|
|
275
|
+
setRouteToc(pageModule);
|
|
270
276
|
let node = buildScopedView(() => pageFactory(props));
|
|
271
277
|
const nodes = [node];
|
|
272
278
|
try {
|
|
@@ -298,6 +304,7 @@ export async function hydrateRouteNode(match, query, rootEl) {
|
|
|
298
304
|
// checked after they all land rather than short-circuiting on the page: bailing
|
|
299
305
|
// early would only skip imports the CSR fallback below is about to need anyway.
|
|
300
306
|
const [pageMod, ...layoutMods] = await resolveAll([match.entry, ...chain], resolveModule);
|
|
307
|
+
setRouteToc(pageMod);
|
|
301
308
|
if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
|
|
302
309
|
// The whole chain must be adoptable — one non-adoptable layout means a clean CSR build.
|
|
303
310
|
if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) return null;
|
|
@@ -339,6 +346,18 @@ export async function resolveModule(entry) {
|
|
|
339
346
|
* so a page reading `router.pathname`/`params`/`query` resolves to the route being
|
|
340
347
|
* pre-rendered. The client uses `navigate` instead.
|
|
341
348
|
*/
|
|
349
|
+
/**
|
|
350
|
+
* Publish the page module's `toc` export as `router.toc`. Called once the page module is
|
|
351
|
+
* resolved and before any factory runs, so a layout's `<Toc>` renders the same outline on
|
|
352
|
+
* the server, at hydration and after a client navigation.
|
|
353
|
+
*/
|
|
354
|
+
export function setRouteToc(pageModule) {
|
|
355
|
+
const toc = Array.isArray(pageModule?.toc) ? pageModule.toc : [];
|
|
356
|
+
const route = getRenderContext()?.route;
|
|
357
|
+
if (route) route.toc = toc;
|
|
358
|
+
else state.toc.value = toc;
|
|
359
|
+
}
|
|
360
|
+
|
|
342
361
|
export function setRouteState({ pathname = "/", search = "", params = {}, locale, data } = {}) {
|
|
343
362
|
const route = getRenderContext()?.route;
|
|
344
363
|
if (route) {
|
|
@@ -646,7 +665,20 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
|
|
|
646
665
|
// the declarations still match (see `registerHotRoute`), outer layouts keep their
|
|
647
666
|
// nodes and state, and an edited layout receives the existing inner route view as
|
|
648
667
|
// `children`, so the page and its components move into it without remounting.
|
|
649
|
-
|
|
668
|
+
// The nodes a route view occupies in the document: the element itself, or the nodes a
|
|
669
|
+
// fragment root held (see `buildScopedView`).
|
|
670
|
+
const viewNodes = (node) => (node?.nodeType === 11 ? node.__afwNodes ?? [] : node ? [node] : []);
|
|
671
|
+
|
|
672
|
+
// A route view to pass on as a layout's `children`: a fragment root is empty once
|
|
673
|
+
// inserted, so it is refilled with the nodes it held.
|
|
674
|
+
function asChildren(node) {
|
|
675
|
+
if (node?.nodeType !== 11) return node;
|
|
676
|
+
const frag = document.createDocumentFragment();
|
|
677
|
+
frag.append(...viewNodes(node));
|
|
678
|
+
return frag;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export async function refreshHotRoute(factory, data = null) {
|
|
650
682
|
const index = currentNodes.findIndex(node => node.__afwHotFactory === factory);
|
|
651
683
|
if (!rootEl || index < 0) return;
|
|
652
684
|
const seq = navSeq;
|
|
@@ -656,8 +688,9 @@ export async function refreshHotRoute(factory) {
|
|
|
656
688
|
if (!match) return;
|
|
657
689
|
const query = Object.fromEntries(state.searchParams.value);
|
|
658
690
|
const inner = index > 0 ? currentNodes[index - 1] : null;
|
|
659
|
-
const
|
|
660
|
-
const
|
|
691
|
+
const innerFirst = viewNodes(inner)[0];
|
|
692
|
+
const innerParent = innerFirst?.parentNode;
|
|
693
|
+
const innerNext = viewNodes(inner).at(-1)?.nextSibling;
|
|
661
694
|
let node;
|
|
662
695
|
try {
|
|
663
696
|
const [pageModule, ...layoutModules] = await resolveAll(
|
|
@@ -668,24 +701,33 @@ export async function refreshHotRoute(factory) {
|
|
|
668
701
|
const focusedId = rootEl.contains(document.activeElement) ? document.activeElement.id : null;
|
|
669
702
|
const scroll = [window.scrollX, window.scrollY];
|
|
670
703
|
const props = { params: match.params, query };
|
|
671
|
-
if (inner) props.children = inner;
|
|
704
|
+
if (inner) props.children = asChildren(inner);
|
|
705
|
+
// `data` is the edited module's route data; the modules imported above are the
|
|
706
|
+
// originals. currentNodes runs page → innermost layout → root, the chain root first.
|
|
707
|
+
const namespace = module => typeof module === "function" ? { default: module } : module;
|
|
708
|
+
const fresh = module => (data ? { ...namespace(module), ...data } : namespace(module));
|
|
709
|
+
const page = index === 0 ? fresh(pageModule) : namespace(pageModule);
|
|
710
|
+
const layouts = layoutModules.map((module, i) => (index === layoutModules.length - i ? fresh(module) : namespace(module)));
|
|
711
|
+
// An edited page may have new headings: publish them before the view rebuilds.
|
|
712
|
+
setRouteToc(page);
|
|
672
713
|
node = buildScopedView(() => factory(props, previous));
|
|
673
|
-
previous
|
|
714
|
+
const old = viewNodes(previous);
|
|
715
|
+
if (old.length === 0) throw new Error("the refreshed view has no nodes in the document to replace");
|
|
716
|
+
old[0].parentNode.insertBefore(node, old[0]);
|
|
717
|
+
for (const n of old) n.remove();
|
|
674
718
|
runCleanup(previous);
|
|
675
719
|
currentNodes = currentNodes.map((current, i) => (i === index ? node : current));
|
|
676
720
|
runMount(node);
|
|
677
|
-
const
|
|
678
|
-
const metadata = await resolveMetadataModules(
|
|
679
|
-
[...layoutModules, pageModule].map(namespace),
|
|
680
|
-
{ params: match.params, query },
|
|
681
|
-
);
|
|
721
|
+
const metadata = await resolveMetadataModules([...layouts, page], { params: match.params, query });
|
|
682
722
|
if (seq === navSeq) updateRouteHead(metadata, state.pathname.value);
|
|
683
723
|
if (focusedId) document.getElementById(focusedId)?.focus({ preventScroll: true });
|
|
684
724
|
window.scrollTo(...scroll);
|
|
685
725
|
clearError({ phase: "route" });
|
|
686
726
|
} catch (error) {
|
|
687
727
|
// A failed layout build may already hold the inner view; put it back.
|
|
688
|
-
if (
|
|
728
|
+
if (innerParent && innerFirst.parentNode !== innerParent) {
|
|
729
|
+
for (const n of viewNodes(inner)) innerParent.insertBefore(n, innerNext ?? null);
|
|
730
|
+
}
|
|
689
731
|
if (node && !node.isConnected) runCleanup(node);
|
|
690
732
|
reportError(error, { phase: "route", path: state.pathname.value });
|
|
691
733
|
}
|
package/server/index.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ export const router: {
|
|
|
37
37
|
readonly params: RouteParams;
|
|
38
38
|
readonly locale: string | null;
|
|
39
39
|
readonly data: unknown;
|
|
40
|
+
/** The current page's headings (MDX `export const toc`), or `[]`. */
|
|
41
|
+
readonly toc: { depth: number; id: string; text: string }[];
|
|
40
42
|
};
|
|
41
43
|
export function matchRoute(pathname: string): { entry: unknown; params: RouteParams; route: string } | null;
|
|
42
44
|
export function configureI18n(config: { locales: string[]; defaultLocale?: string } | null): void;
|
|
@@ -45,6 +47,8 @@ export function resolveLocale(pathname: string): { locale: string | null; path:
|
|
|
45
47
|
export function localizePath(pathname: string, locale?: string | null): string;
|
|
46
48
|
/** Set the current request's locale during server rendering. */
|
|
47
49
|
export function setLocale(locale: string | null): void;
|
|
50
|
+
/** Publish a page module's `toc` export as `router.toc`. */
|
|
51
|
+
export function setRouteToc(pageModule: { toc?: unknown } | null | undefined): void;
|
|
48
52
|
/** Set the current request's route state directly. */
|
|
49
53
|
export function setRouteState(state?: {
|
|
50
54
|
pathname?: string;
|
package/server/index.js
CHANGED
|
@@ -20,7 +20,7 @@ export * from "./render.js";
|
|
|
20
20
|
export {
|
|
21
21
|
registerRoutes, router, matchRoute, configureI18n, i18nLocales,
|
|
22
22
|
resolveLocale, localizePath, shouldInterceptNav,
|
|
23
|
-
setLocale, setRouteState, navigate,
|
|
23
|
+
setLocale, setRouteState, setRouteToc, navigate,
|
|
24
24
|
} from "../runtime/router.js";
|
|
25
25
|
export { isHydrating } from "../runtime/hydrate.js";
|
|
26
26
|
export { emit } from "../runtime/events.js";
|
package/server/render.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
resolveModule,
|
|
14
14
|
routes,
|
|
15
15
|
setRouteState,
|
|
16
|
+
setRouteToc,
|
|
16
17
|
} from "../runtime/router.js";
|
|
17
18
|
import { resolveMetadata } from "./head.js";
|
|
18
19
|
import { beginHydrationCollect, endHydrationCollect } from "./ssg-runtime.js";
|
|
@@ -60,6 +61,8 @@ async function renderInContext(pathname, params, search, data) {
|
|
|
60
61
|
);
|
|
61
62
|
const page = pageModule?.default ?? pageModule;
|
|
62
63
|
const layouts = layoutModules.map(module => module?.default ?? module);
|
|
64
|
+
// Before any factory runs, so a layout's `<Toc>` serves the page's outline.
|
|
65
|
+
setRouteToc(pageModule);
|
|
63
66
|
|
|
64
67
|
// Each context owns its hydration ids, including when another render is nested.
|
|
65
68
|
let html, hydration;
|
package/server/ssg-runtime.js
CHANGED
|
@@ -161,6 +161,64 @@ export function attr(name, value) {
|
|
|
161
161
|
return ` ${name}="${escapeAttr(String(value))}"`;
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
/**
|
|
165
|
+
* The dynamic attributes of an element that carries a spread (`<div {...rest} class="x">`).
|
|
166
|
+
* `entries` lists, in source order, `[name, value]` pairs for named attributes and plain
|
|
167
|
+
* objects for spreads. A later entry overrides an earlier one with the same name, which is
|
|
168
|
+
* the order the client's `spread`/`setAttribute` calls apply them in. A served tag can't
|
|
169
|
+
* repeat an attribute (the parser keeps the first one), so the merge has to happen here.
|
|
170
|
+
* Event handlers and functions have no HTML form and are left to the client.
|
|
171
|
+
*/
|
|
172
|
+
export function ssgAttrs(entries) {
|
|
173
|
+
const merged = new Map();
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
if (Array.isArray(entry)) merged.set(entry[0], entry[1]);
|
|
176
|
+
else if (entry && typeof entry === "object") {
|
|
177
|
+
for (const k in entry) merged.set(k, entry[k]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
let s = "";
|
|
181
|
+
for (const [name, value] of merged) {
|
|
182
|
+
if (name === "ref" || name === "children" || typeof value === "function") continue;
|
|
183
|
+
s += attr(name, value);
|
|
184
|
+
}
|
|
185
|
+
return s;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Tags that close an open `<p>` (the HTML parser's "close a p element" list). Mirrors
|
|
189
|
+
// `CLOSES_P` in the compiler's static_tree.rs.
|
|
190
|
+
const CLOSES_P = /<(address|article|aside|blockquote|center|details|dialog|dir|div|dl|dd|dt|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|li|listing|main|menu|nav|ol|p|plaintext|pre|search|section|summary|table|ul|xmp)[\s/>]/i;
|
|
191
|
+
const warnedParagraphs = new Set();
|
|
192
|
+
|
|
193
|
+
/** The first tag in a paragraph's inner HTML that would close the `<p>`, or null. */
|
|
194
|
+
export function paragraphBlockTag(html) {
|
|
195
|
+
const m = CLOSES_P.exec(html);
|
|
196
|
+
return m ? m[1].toLowerCase() : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The inner HTML of a `<p>` holding components (`names`, e.g. "<Badge>"), returned
|
|
201
|
+
* unchanged. If a component's markup put a block element in it, the browser will close
|
|
202
|
+
* the paragraph early and hydration rebuilds it (`hydrateParagraph`), so say so once per
|
|
203
|
+
* page and paragraph, with the fix.
|
|
204
|
+
*/
|
|
205
|
+
export function ssgParagraph(html, names) {
|
|
206
|
+
const tag = paragraphBlockTag(html);
|
|
207
|
+
if (tag) {
|
|
208
|
+
const page = getRenderContext()?.route?.pathname ?? "";
|
|
209
|
+
const key = `${page}\0${names}\0${tag}`;
|
|
210
|
+
if (!warnedParagraphs.has(key)) {
|
|
211
|
+
warnedParagraphs.add(key);
|
|
212
|
+
console.warn(
|
|
213
|
+
`⚠ ${names} renders a <${tag}> inside a paragraph${page ? ` on ${page}` : ""}. ` +
|
|
214
|
+
"The browser moves it out of the <p>, so that paragraph is rebuilt on load. " +
|
|
215
|
+
"Put the component on its own line, or render inline markup (<span>) from it.",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return html;
|
|
220
|
+
}
|
|
221
|
+
|
|
164
222
|
/**
|
|
165
223
|
* A dynamic hole's value → HTML: trusted `{__html}` raw, else escaped text. An
|
|
166
224
|
* array (`{[<a/>, <b/>]}` or `{[1, 2, 3]}`) renders each item concatenated with no
|