@opsydyn/astro-foldkit 0.11.0 → 0.13.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/CHANGELOG.md CHANGED
@@ -1,17 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.13.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.12.0...astro-foldkit-v0.13.0) (2026-11-13)
4
+
5
+ ### Features
6
+
7
+ - **astro-foldkit:** preload the chunk chain of islands that boot at load ([6d7eaef](https://github.com/opsydyn/fold-kit-experiments/commit/6d7eaefadfac9c05347184ee954d4cacdb3ea04c))
8
+
9
+ ## [0.12.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.11.0...astro-foldkit-v0.12.0) (2026-11-12)
10
+
11
+ ### Features
12
+
13
+ - **astro-foldkit:** add a client:interaction directive that replays early input ([9e2afa8](https://github.com/opsydyn/fold-kit-experiments/commit/9e2afa848cefa0accb1cc58767b1389c652239df))
14
+ - **astro-foldkit:** add a client:interaction directive that replays early input ([0ddee8a](https://github.com/opsydyn/fold-kit-experiments/commit/0ddee8a79f8b84ea4fdfb097524faa873830da2f))
15
+
16
+ ### Bug Fixes
17
+
18
+ - **astro-foldkit:** pre-bundle island dependencies before the first request ([13c8a73](https://github.com/opsydyn/fold-kit-experiments/commit/13c8a73c46b4458d4513a10e26fc4780e05e2838))
19
+ - **astro-foldkit:** pre-bundle island dependencies before the first request ([a5b52c1](https://github.com/opsydyn/fold-kit-experiments/commit/a5b52c18e2207af6d71e2e4c58032ec720b2172e))
20
+
3
21
  ## [0.11.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.10.0...astro-foldkit-v0.11.0) (2026-11-12)
4
22
 
5
23
  ### Features
6
24
 
7
- - **astro-foldkit:** warn about islands that fail silently ([166dc12](https://github.com/opsydyn/fold-kit-experiments/commit/166dc12f752ccb1ec499a18196b40600d0d481dd))
8
25
  - **astro-foldkit:** warn about islands that fail silently ([232e940](https://github.com/opsydyn/fold-kit-experiments/commit/232e94023d5181e049d6d964a93220d364d06fff))
9
26
 
10
27
  ## [0.10.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.9.3...astro-foldkit-v0.10.0) (2026-11-11)
11
28
 
12
29
  ### Features
13
30
 
14
- - **astro-foldkit:** let an island pre-render its first paint ([46011d0](https://github.com/opsydyn/fold-kit-experiments/commit/46011d037531541d405a86b1d4079114fe547476))
15
31
  - **astro-foldkit:** let an island pre-render its first paint ([ae06ae9](https://github.com/opsydyn/fold-kit-experiments/commit/ae06ae9df22a8cbf094cfe3a9a28ef48da5cf51d))
16
32
 
17
33
  ## [0.9.3](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.9.2...astro-foldkit-v0.9.3) (2026-10-29)
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @opsydyn/astro-foldkit
2
2
 
3
3
  Astro integration and renderer for [FoldKit](https://foldkit.dev), with
4
- client-only islands and an opt-in server-rendered page path.
4
+ islands that can pre-render, and an opt-in server-rendered page path.
5
5
 
6
- FoldKit is an Elm Architecture runtime built on [Effect](https://effect.website). This package registers FoldKit as an Astro renderer so you can drop any FoldKit app into a `.astro` page as a component and hydrate it with `client:load`.
6
+ FoldKit is an Elm Architecture runtime built on [Effect](https://effect.website). This package registers FoldKit as an Astro renderer so you can drop any FoldKit app into a `.astro` page as a component, and choose per island whether and when it ships JavaScript.
7
7
 
8
8
  There are two deliberately separate entry paths:
9
9
 
10
- - `lazyApp` / `defineApp` keeps the existing client-only island contract. Astro receives a deterministic mount shell and FoldKit starts in the browser.
10
+ - `lazyApp` / `defineApp` registers an island. By default Astro receives a deterministic empty mount shell and FoldKit starts in the browser. With `{ prerender: true }` the island's first render is in the HTML, so it can ship with no directive and no JavaScript, or hydrate later with `client:visible` or this package's `client:interaction`. See [Choosing when JavaScript runs](#choosing-when-javascript-runs).
11
11
  - `definePage` opts one FoldKit application into SSG or request SSR. The server emits FoldKit HTML and public Flags, and `client:load` hydrates that exact DOM.
12
12
 
13
13
  ## Installation
@@ -26,8 +26,9 @@ npm install astro foldkit
26
26
 
27
27
  ## FoldKit compatibility
28
28
 
29
- `@opsydyn/astro-foldkit` targets FoldKit `0.167.x` to `0.169.x`, stable Effect
30
- `4.0.0`, and the matching `@foldkit/vite-plugin` `0.28.x` line.
29
+ `@opsydyn/astro-foldkit` targets FoldKit `0.170.x`, Effect `4.1.x`, and the
30
+ matching `@foldkit/vite-plugin` `0.29.x` line. An application on an older FoldKit
31
+ needs an older release of this integration.
31
32
  Applications can define interruptible work with
32
33
  `Command.define(name, { interrupt: true, ... })` inside their own update loop;
33
34
  this integration continues to own Astro rendering, hydration, and lifecycle
@@ -59,8 +60,9 @@ in public HTML, so it must not contain secrets. Do not reuse it across deploymen
59
60
  with different rendering inputs. Blank `server.buildId` options are rejected, and FoldKit
60
61
  fails closed when neither a compiled identity nor an explicit override is available.
61
62
 
62
- See the [0.167 migration guide](../../docs/migrations/foldkit-0.167.md) for the
63
- subscription API changes and package compatibility checks.
63
+ See the [FoldKit 0.170 release notes](../../docs/releases/foldkit-0.170.md) for
64
+ the move to Effect 4.1, and the [0.167 migration guide](../../docs/migrations/foldkit-0.167.md)
65
+ for the earlier subscription API changes.
64
66
 
65
67
  ## Defining an app
66
68
 
@@ -115,10 +117,16 @@ particular on any page carrying more than one island. Drop it only when this
115
117
  island is meant to own the page title. See [`noMeta`](#nometa).
116
118
 
117
119
  For `lazyApp` / `defineApp`, the server renderer emits a deterministic
118
- `<div data-foldkit-island="true"></div>` mount shell. It does not load or
119
- execute the FoldKit application during SSR; the application is loaded and
120
- embedded only by the client renderer. Astro still owns the outer island
121
- serialisation and client directive behavior.
120
+ `<div data-foldkit-island="true"></div>` mount shell. Unless the island opts
121
+ into [pre-rendering](#pre-rendered-islands-opt-in), it does not load or execute
122
+ the FoldKit application during SSR; the application is loaded and embedded only
123
+ by the client renderer. Astro still owns the outer island serialisation and
124
+ client directive behavior.
125
+
126
+ In development the integration also adds every module that imports
127
+ `define-app` or `define-page` to Vite's dependency scan, so an island's
128
+ dependencies are bundled when the dev server starts rather than on the first
129
+ request that loads it.
122
130
 
123
131
  ### Pre-rendered islands (opt-in)
124
132
 
@@ -161,6 +169,7 @@ appears in the HTML, and whether it ships JavaScript. Make them per island.
161
169
  | --------------------------- | ------------------------------------------------- | ---------------------------- |
162
170
  | To be read, never touched | `prerender: true`, **no directive** | none for this island |
163
171
  | Interaction, below the fold | `prerender: true`, `client:visible` | none until it is scrolled to |
172
+ | Interaction, by a few | `prerender: true`, `client:interaction` | none until it is touched |
164
173
  | Interaction, immediately | `prerender: true`, `client:load` or `client:idle` | the runtime, at load |
165
174
  | A browser-only `init` | no `prerender`, `client:load` or `client:idle` | the runtime, at load |
166
175
 
@@ -190,13 +199,75 @@ renders before any JavaScript runs. A chart that loses its hover readout by
190
199
  going static can keep the information as a native SVG `<title>` on each mark,
191
200
  which the browser shows as a tooltip and which costs no runtime.
192
201
 
193
- The renderer warns at build and dev time about the two arrangements that fail
202
+ #### Module preloads for islands that boot at load
203
+
204
+ An island's JavaScript arrives as a chain: Astro's bootstrap fetches the
205
+ renderer and the component module, the component's `load` imports the
206
+ application, and each chunk reveals its own imports only once it arrives.
207
+ Astro emits no preload hints for island chunks, so every link costs a round
208
+ trip.
209
+
210
+ For each pre-rendered page, the build adds a `<link rel="modulepreload">` at
211
+ the end of `<head>` for every chunk a `client:load` or `client:only` FoldKit
212
+ island needs to boot, so the browser fetches the chain in parallel. The links
213
+ follow the stylesheets, so they do not compete with render-blocking CSS. What
214
+ the application imports lazily stays lazy, and islands that defer their
215
+ download (`client:visible`, `client:idle`, `client:interaction`,
216
+ `client:media`) are left alone, as are other renderers' islands. Nothing needs
217
+ configuring.
218
+
219
+ On a server-rendered report page whose owner hydrates with `client:load`, at
220
+ 150 ms per request, this cut the time to hydration from 1,140 ms to 510 ms, five
221
+ sequential round trips down to two, with first paint unchanged.
222
+
223
+ Pages rendered on request are not on disk at build time and keep the chain.
224
+
225
+ #### `client:interaction`
226
+
227
+ The integration adds a `client:interaction` directive. It hydrates a
228
+ pre-rendered island on the reader's first pointer press, focus or key press
229
+ inside it, and replays what they did before it booted:
230
+
231
+ ```astro
232
+ <Counter client:interaction />
233
+ <Counter client:interaction={{ hover: true }} />
234
+ ```
235
+
236
+ FoldKit renders an island fresh rather than adopting the pre-rendered markup,
237
+ so without help the click that started the download would be lost, and text
238
+ typed into the static markup would disappear in the swap. The directive records
239
+ clicks, field edits and focus inside the island, in order, and replays them
240
+ onto the matching elements of the first client render: a field edit arrives as
241
+ `input` and `change` events, a click as a click, and focus and the caret are
242
+ restored. Elements are matched by position, which holds because server and
243
+ client run the same pure `init` and `view`. A step whose element has changed,
244
+ or is now disabled, is skipped. A run of edits to one field replays as its
245
+ final value. With `{ hover: true }` a mouse pointer over the island also starts
246
+ the download, which usually finishes before the click.
247
+
248
+ The pre-rendered markup never reacts, so replay is faithful only up to the
249
+ first point where the application would have changed the DOM. Typing into a
250
+ field, pressing a button that clears it, then typing again replays the button
251
+ press correctly but leaves the field holding everything typed.
252
+
253
+ Choose it over `client:visible` only when most readers who see the island never
254
+ use it, and its controls work in the pre-rendered markup. Every interaction
255
+ waits for the download first. On the report page above, under Slow 4G and a
256
+ 4× CPU slowdown on a phone viewport, the grid's search was usable 1.65 s after
257
+ the tap with `client:interaction`, against immediately with `client:visible`,
258
+ which had already spent 172 KB while the reader scrolled. That grid also keeps
259
+ its controls disabled until its rows arrive, so the reader's first tap does
260
+ nothing but start the download: `client:visible` is the better choice there.
261
+
262
+ The renderer warns at build and dev time about the arrangements that misbehave
194
263
  without an error, each once per component:
195
264
 
196
265
  - an island with **no directive and no `prerender`** renders an empty mount and
197
266
  ships nothing, so it never displays anything;
198
267
  - an island with **`client:visible` and no `prerender`** never intersects, for
199
- the reason above, so it never hydrates.
268
+ the reason above, so it never hydrates;
269
+ - an island with **`client:interaction` and no `prerender`** has no markup to
270
+ interact with, so it hydrates at once, as `client:load` would.
200
271
 
201
272
  FoldKit replaces the inner mount, not the outer `<astro-island>`. The outer
202
273
  element remains Astro's lifecycle owner, including for empty `client:only`
@@ -503,7 +574,9 @@ Schema/value. `defineApp` keeps the existing props-based `init` contract.
503
574
  | `@opsydyn/astro-foldkit/define-page` | `definePage`, `PageConfig`, and page Flags context types |
504
575
  | `@opsydyn/astro-foldkit/server` | Server-only `resolvePageDocument` metadata resolver |
505
576
 
506
- The root entry point also exports the `NavigationConfig`, `NavigationEvent`, and `NavigationPhase` types.
577
+ The root entry point also exports the `InteractionOptions`, `NavigationConfig`,
578
+ `NavigationEvent`, and `NavigationPhase` types, and declares the
579
+ `client:interaction` directive on Astro's `AstroClientDirectives`.
507
580
 
508
581
  ## Embedding
509
582
 
@@ -640,7 +713,8 @@ element.addEventListener(
640
713
  | Package | Version |
641
714
  | :-------- | :-------------------- |
642
715
  | `astro` | `≥ 5.0` |
643
- | `foldkit` | `≥ 0.167.0 < 0.170.0` |
716
+ | `effect` | `~4.1.0` |
717
+ | `foldkit` | `≥ 0.170.0 < 0.171.0` |
644
718
 
645
719
  ## Stateflow Observatory example
646
720
 
@@ -0,0 +1,90 @@
1
+ //#region src/directive-interaction.d.ts
2
+ /**
3
+ * `client:interaction`: hydrate a pre-rendered FoldKit island on the reader's
4
+ * first sign of intent rather than at load or on sight, and replay what they
5
+ * did before it booted.
6
+ *
7
+ * FoldKit's `embed` renders fresh: it replaces the pre-rendered markup instead
8
+ * of adopting it. A click that triggers the download would otherwise be lost,
9
+ * and anything typed or focused before the swap would vanish with the old DOM.
10
+ * So the directive records clicks, edited form values and focus inside the
11
+ * island while the application loads, and replays them onto the matching
12
+ * elements of the first client render. The match is by position: server and
13
+ * client run the same pure `init` and `view` over the same props, so the two
14
+ * trees have the same shape.
15
+ *
16
+ * Astro bundles this module on its own into an inline script, so it imports
17
+ * nothing.
18
+ */
19
+ /** Options for `client:interaction`. */
20
+ type InteractionOptions = Readonly<{
21
+ /**
22
+ * Also hydrate when a mouse pointer moves over the island. Hover usually
23
+ * comes well before a click, so the application is often ready by then, at
24
+ * the cost of loading for readers who only pass over it.
25
+ */
26
+ hover?: boolean;
27
+ }>;
28
+ type TreeNode = {
29
+ readonly tagName: string;
30
+ readonly parentElement: TreeNode | null;
31
+ readonly children: ArrayLike<TreeNode>;
32
+ };
33
+ /** Where an element sits under a root: the child index at each level. */
34
+ type Position = Readonly<{
35
+ path: ReadonlyArray<number>;
36
+ tagName: string;
37
+ }>;
38
+ declare const positionOf: (root: TreeNode, target: TreeNode) => Position | undefined;
39
+ /** The element at `position` under `root`, if it is still the same kind of element. */
40
+ declare const resolvePosition: (root: TreeNode, position: Position) => TreeNode | undefined;
41
+ /** One thing the reader did before the application booted. */
42
+ type Step = Readonly<{
43
+ kind: 'click';
44
+ position: Position;
45
+ }> | Readonly<{
46
+ kind: 'value';
47
+ position: Position;
48
+ value: string;
49
+ }>;
50
+ /** What the reader did inside the island before the application booted, in order. */
51
+ type Recording = Readonly<{
52
+ steps: ReadonlyArray<Step>;
53
+ focus: Readonly<{
54
+ position: Position;
55
+ selection?: readonly [number, number] | undefined;
56
+ }> | undefined;
57
+ }>;
58
+ /**
59
+ * Adds a step, folding a run of edits to one field into its latest value: the
60
+ * application needs where the reader got to, not every keystroke.
61
+ */
62
+ declare const appendStep: (steps: ReadonlyArray<Step>, step: Step) => ReadonlyArray<Step>;
63
+ /**
64
+ * Replays a recording onto the freshly rendered application under `root`, in
65
+ * the order the reader acted, then restores focus. A value reaches the
66
+ * application as `input` and `change` events, as typing would.
67
+ *
68
+ * Steps whose element no longer matches, or is disabled, are skipped: a
69
+ * control the application has not enabled must not receive input the reader
70
+ * could not have given it. The pre-rendered markup never reacted to the
71
+ * reader, so a field the application would have changed between two edits
72
+ * holds the reader's text as typed into the static field.
73
+ */
74
+ declare const replay: (root: TreeNode, recording: Recording) => void;
75
+ /**
76
+ * The application root that replaced `oldRoot`. FoldKit renders its root in
77
+ * place of the mount element; should it ever render inside the mount instead,
78
+ * the mount is still in its slot and the root is its first child.
79
+ */
80
+ declare const currentRoot: <Node extends TreeNode>(slot: Readonly<{
81
+ parent: Node;
82
+ index: number;
83
+ mount: Node;
84
+ }>) => Node | undefined;
85
+ type DirectiveLoad = () => Promise<() => Promise<void>>;
86
+ declare const interactionDirective: (load: DirectiveLoad, options: {
87
+ readonly value: unknown;
88
+ }, el: HTMLElement) => void;
89
+ //#endregion
90
+ export { InteractionOptions, Position, Recording, Step, TreeNode, appendStep, currentRoot, interactionDirective as default, positionOf, replay, resolvePosition };
@@ -0,0 +1,197 @@
1
+ //#region src/directive-interaction.ts
2
+ const positionOf = (root, target) => {
3
+ const path = [];
4
+ let node = target;
5
+ while (node !== root) {
6
+ const parent = node.parentElement;
7
+ if (parent === null) return void 0;
8
+ path.unshift(Array.prototype.indexOf.call(parent.children, node));
9
+ node = parent;
10
+ }
11
+ return {
12
+ path,
13
+ tagName: target.tagName
14
+ };
15
+ };
16
+ /** The element at `position` under `root`, if it is still the same kind of element. */
17
+ const resolvePosition = (root, position) => {
18
+ let node = root;
19
+ for (const index of position.path) {
20
+ node = node.children[index];
21
+ if (node === void 0) return void 0;
22
+ }
23
+ return node.tagName === position.tagName ? node : void 0;
24
+ };
25
+ const samePosition = (a, b) => a.tagName === b.tagName && a.path.length === b.path.length && a.path.every((index, level) => index === b.path[level]);
26
+ /**
27
+ * Adds a step, folding a run of edits to one field into its latest value: the
28
+ * application needs where the reader got to, not every keystroke.
29
+ */
30
+ const appendStep = (steps, step) => {
31
+ const last = steps.at(-1);
32
+ return step.kind === "value" && last?.kind === "value" && samePosition(last.position, step.position) ? [...steps.slice(0, -1), step] : [...steps, step];
33
+ };
34
+ const dispatch = (target, type) => {
35
+ target.dispatchEvent(new Event(type, { bubbles: true }));
36
+ };
37
+ const replayStep = (root, step) => {
38
+ const target = resolvePosition(root, step.position);
39
+ if (target === void 0 || target.disabled === true) return;
40
+ if (step.kind === "click") return target.click();
41
+ if (target.value === step.value) return;
42
+ target.value = step.value;
43
+ dispatch(target, "input");
44
+ dispatch(target, "change");
45
+ };
46
+ /**
47
+ * Replays a recording onto the freshly rendered application under `root`, in
48
+ * the order the reader acted, then restores focus. A value reaches the
49
+ * application as `input` and `change` events, as typing would.
50
+ *
51
+ * Steps whose element no longer matches, or is disabled, are skipped: a
52
+ * control the application has not enabled must not receive input the reader
53
+ * could not have given it. The pre-rendered markup never reacted to the
54
+ * reader, so a field the application would have changed between two edits
55
+ * holds the reader's text as typed into the static field.
56
+ */
57
+ const replay = (root, recording) => {
58
+ for (const step of recording.steps) replayStep(root, step);
59
+ if (recording.focus === void 0) return;
60
+ const target = resolvePosition(root, recording.focus.position);
61
+ if (target === void 0 || target.disabled === true) return;
62
+ target.focus({ preventScroll: true });
63
+ const selection = recording.focus.selection;
64
+ if (selection !== void 0) target.setSelectionRange?.(selection[0], selection[1]);
65
+ };
66
+ const triggers = [
67
+ "pointerdown",
68
+ "focusin",
69
+ "keydown"
70
+ ];
71
+ const recorded = [
72
+ "click",
73
+ "focusin",
74
+ "focusout",
75
+ "input",
76
+ "change",
77
+ "submit"
78
+ ];
79
+ /** Fields whose state a click changes, so replaying the click carries it. */
80
+ const checkable = new Set(["checkbox", "radio"]);
81
+ /** The control a click on `target` will be forwarded to, when it is inside a label for another element. */
82
+ const labelledControl = (target) => {
83
+ const control = target.closest("label")?.control ?? null;
84
+ return control === null || control === target || control.contains(target) ? null : control;
85
+ };
86
+ /** The caret or selection of a text field, if it has one. */
87
+ const selectionOf = (element) => {
88
+ if (!(element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)) return void 0;
89
+ const { selectionStart, selectionEnd } = element;
90
+ return selectionStart === null || selectionEnd === null ? void 0 : [selectionStart, selectionEnd];
91
+ };
92
+ /**
93
+ * The application root that replaced `oldRoot`. FoldKit renders its root in
94
+ * place of the mount element; should it ever render inside the mount instead,
95
+ * the mount is still in its slot and the root is its first child.
96
+ */
97
+ const currentRoot = (slot) => {
98
+ const occupant = slot.parent.children[slot.index];
99
+ return occupant === slot.mount ? slot.mount.children[0] : occupant;
100
+ };
101
+ /** Resolves once `oldRoot` has left the document, which is when the client render replaced it. */
102
+ const replacement = (el, oldRoot) => new Promise((resolve) => {
103
+ if (!oldRoot.isConnected) return resolve();
104
+ const observer = new MutationObserver(() => {
105
+ if (oldRoot.isConnected) return;
106
+ observer.disconnect();
107
+ resolve();
108
+ });
109
+ observer.observe(el, {
110
+ childList: true,
111
+ subtree: true
112
+ });
113
+ });
114
+ const interactionDirective = (load, options, el) => {
115
+ const { value } = options;
116
+ const hover = value instanceof Object && "hover" in value && value.hover === true;
117
+ const mount = el.querySelector("[data-foldkit-island]");
118
+ const oldRoot = mount?.firstElementChild ?? null;
119
+ const parent = mount?.parentElement ?? null;
120
+ if (mount === null || oldRoot === null || parent === null) {
121
+ load().then((hydrate) => hydrate());
122
+ return;
123
+ }
124
+ const slot = {
125
+ parent,
126
+ index: Array.prototype.indexOf.call(parent.children, mount),
127
+ mount
128
+ };
129
+ let steps = [];
130
+ let focused;
131
+ let started = false;
132
+ const record = (event) => {
133
+ const target = event.target;
134
+ if (!(target instanceof Element)) return;
135
+ const position = positionOf(oldRoot, target);
136
+ if (position === void 0) return;
137
+ switch (event.type) {
138
+ case "click":
139
+ if (target.closest("a[href]") !== null) return;
140
+ if (labelledControl(target) !== null) return;
141
+ steps = appendStep(steps, {
142
+ kind: "click",
143
+ position
144
+ });
145
+ return;
146
+ case "focusin":
147
+ focused = {
148
+ element: target,
149
+ position
150
+ };
151
+ return;
152
+ case "focusout":
153
+ setTimeout(() => {
154
+ if (focused?.element === target && target.isConnected) focused = void 0;
155
+ });
156
+ return;
157
+ case "submit":
158
+ event.preventDefault();
159
+ return;
160
+ default: if (target instanceof HTMLInputElement && !checkable.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) steps = appendStep(steps, {
161
+ kind: "value",
162
+ position,
163
+ value: target.value
164
+ });
165
+ }
166
+ };
167
+ const stopRecording = () => {
168
+ for (const type of recorded) el.removeEventListener(type, record, true);
169
+ };
170
+ const replayRecording = () => {
171
+ const recording = {
172
+ steps,
173
+ focus: focused === void 0 || focused.element.isConnected ? void 0 : {
174
+ position: focused.position,
175
+ selection: selectionOf(focused.element)
176
+ }
177
+ };
178
+ const root = currentRoot(slot);
179
+ if (root !== void 0) replay(root, recording);
180
+ };
181
+ const hydrateAndReplay = () => {
182
+ const swapped = replacement(el, oldRoot);
183
+ return load().then((hydrate) => hydrate()).then(() => swapped).finally(stopRecording).then(replayRecording);
184
+ };
185
+ const start = (event) => {
186
+ if (event.type === "pointerover" && event.pointerType !== "mouse") return;
187
+ if (started) return;
188
+ started = true;
189
+ for (const type of [...triggers, "pointerover"]) el.removeEventListener(type, start, true);
190
+ hydrateAndReplay();
191
+ };
192
+ for (const type of recorded) el.addEventListener(type, record, true);
193
+ for (const type of triggers) el.addEventListener(type, start, true);
194
+ if (hover) el.addEventListener("pointerover", start, true);
195
+ };
196
+ //#endregion
197
+ export { appendStep, currentRoot, interactionDirective as default, positionOf, replay, resolvePosition };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,18 @@
1
1
  import { n as NavigationEvent, r as NavigationPhase, t as NavigationConfig } from "./navigation-Cy2lnE4G.mjs";
2
+ import { InteractionOptions } from "./directive-interaction.mjs";
2
3
  import { AstroIntegration } from "astro";
3
4
 
4
5
  //#region src/index.d.ts
6
+ declare module 'astro' {
7
+ interface AstroClientDirectives {
8
+ /**
9
+ * Hydrate a pre-rendered FoldKit island on the reader's first pointer press,
10
+ * focus or key press inside it, replaying clicks, typed values and focus
11
+ * that happened before it booted. Requires `lazyApp(load, { prerender: true })`.
12
+ */
13
+ 'client:interaction'?: InteractionOptions | boolean;
14
+ }
15
+ }
5
16
  type FoldkitIntegrationOptions = Readonly<{
6
17
  server?: Readonly<{
7
18
  buildId: string;
@@ -9,4 +20,4 @@ type FoldkitIntegrationOptions = Readonly<{
9
20
  }>;
10
21
  declare function foldkit(options?: FoldkitIntegrationOptions): AstroIntegration;
11
22
  //#endregion
12
- export { FoldkitIntegrationOptions, type NavigationConfig, type NavigationEvent, type NavigationPhase, foldkit as default };
23
+ export { FoldkitIntegrationOptions, type InteractionOptions, type NavigationConfig, type NavigationEvent, type NavigationPhase, foldkit as default };
package/dist/index.mjs CHANGED
@@ -1,19 +1,189 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { foldkit as foldkit$1 } from "@foldkit/vite-plugin";
3
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { join, relative, sep } from "node:path";
5
+ import { readFile, readdir, writeFile } from "node:fs/promises";
6
+ //#region src/island-scan.ts
7
+ const scannable = /\.[cm]?[jt]s$/;
8
+ const declaration = /\.d\.[cm]?ts$/;
9
+ const definesFoldkitEntry = /@opsydyn\/astro-foldkit\/define-(?:app|page)['"]/;
10
+ const globSyntax = /[()[\]{}*?!+@]/g;
11
+ const listFiles = (directory) => existsSync(directory) ? readdirSync(directory, {
12
+ recursive: true,
13
+ encoding: "utf8"
14
+ }) : [];
15
+ const isCandidate = (path) => scannable.test(path) && !declaration.test(path) && !path.split(sep).includes("node_modules");
16
+ const toEntryPattern = (root, file) => relative(root, file).split(sep).join("/").replace(globSyntax, "\\$&");
17
+ /** Root-relative glob patterns, escaped, for the source modules that define FoldKit islands or pages. */
18
+ const findIslandEntries = (root, srcDir) => listFiles(srcDir).filter(isCandidate).map((path) => join(srcDir, path)).filter((file) => definesFoldkitEntry.test(readFileSync(file, "utf8"))).map((file) => toEntryPattern(root, file));
19
+ const islandScanPlugin = (root, srcDir) => ({
20
+ name: "astro-foldkit:island-scan",
21
+ configEnvironment: (name) => {
22
+ if (name !== "client") return void 0;
23
+ const entries = findIslandEntries(root, srcDir);
24
+ return entries.length === 0 ? void 0 : { optimizeDeps: { entries } };
25
+ }
26
+ });
27
+ //#endregion
28
+ //#region src/preload.ts
29
+ /**
30
+ * Module preloads for FoldKit islands that boot at load.
31
+ *
32
+ * An island's JavaScript arrives as a chain: Astro's bootstrap fetches the
33
+ * renderer and the component module, the component's `load` imports the
34
+ * application, and each of those reveals its own imports only once it has
35
+ * arrived. Astro emits no preload hints for island chunks, so every link of
36
+ * the chain costs a round trip. For an island that boots at load, the whole
37
+ * chain is known at build time; listing it in the head lets the browser fetch
38
+ * it in parallel.
39
+ *
40
+ * Islands that defer their download (`client:visible`, `client:idle`,
41
+ * `client:interaction`, `client:media`) are left alone: preloading them would
42
+ * spend the bandwidth they were chosen to save.
43
+ */
44
+ /** Directives that boot an island as soon as the page loads. */
45
+ const eagerDirectives = new Set(["load", "only"]);
46
+ /**
47
+ * The chunks an island needs to boot: the renderer, the component module, the
48
+ * application its `load` imports, and everything those import statically.
49
+ * What the application imports lazily stays lazy.
50
+ */
51
+ const islandPreloads = (graph, rendererFile, componentFile) => {
52
+ const files = /* @__PURE__ */ new Set();
53
+ const visit = (file) => {
54
+ if (files.has(file)) return;
55
+ const node = graph.get(file);
56
+ if (node === void 0) return;
57
+ files.add(file);
58
+ for (const imported of node.imports) visit(imported);
59
+ };
60
+ visit(rendererFile);
61
+ visit(componentFile);
62
+ for (const loaded of graph.get(componentFile)?.dynamicImports ?? []) visit(loaded);
63
+ return [...files];
64
+ };
65
+ const islandTag = /<astro-island\b[^>]*>/g;
66
+ const attribute = /\s([\w:-]+)="([^"]*)"/g;
67
+ const attributesOf = (tag) => new Map([...tag.matchAll(attribute)].map((match) => [match[1] ?? "", match[2] ?? ""]));
68
+ const splitQuery = (url) => {
69
+ const index = url.indexOf("?");
70
+ return index === -1 ? [url, ""] : [url.slice(0, index), url.slice(index)];
71
+ };
72
+ const rendererUrl = (url, graph) => {
73
+ const [path, query] = splitQuery(url);
74
+ for (const [file, node] of graph) if (node.foldkitRenderer && path.endsWith(`/${file}`)) return {
75
+ prefix: path.slice(0, -file.length),
76
+ file,
77
+ query
78
+ };
79
+ };
80
+ const componentFile = (url, renderer, graph) => {
81
+ const [path] = splitQuery(url);
82
+ if (!path.startsWith(renderer.prefix)) return void 0;
83
+ const file = path.slice(renderer.prefix.length);
84
+ return graph.has(file) ? file : void 0;
85
+ };
86
+ /**
87
+ * Adds `modulepreload` links for each FoldKit island on the page that boots at
88
+ * load, at the end of the head so they follow the stylesheets: placed before
89
+ * them, they compete with render-blocking CSS and delay first paint.
90
+ *
91
+ * Returns the page unchanged when it has no such island.
92
+ */
93
+ const addIslandPreloads = (html, graph) => {
94
+ const hrefs = /* @__PURE__ */ new Set();
95
+ for (const [tag] of html.matchAll(islandTag)) {
96
+ const attributes = attributesOf(tag);
97
+ if (!eagerDirectives.has(attributes.get("client") ?? "")) continue;
98
+ const renderer = rendererUrl(attributes.get("renderer-url") ?? "", graph);
99
+ if (renderer === void 0) continue;
100
+ const component = componentFile(attributes.get("component-url") ?? "", renderer, graph);
101
+ if (component === void 0) continue;
102
+ for (const file of islandPreloads(graph, renderer.file, component)) hrefs.add(`${renderer.prefix}${file}${renderer.query}`);
103
+ }
104
+ const links = [...hrefs].filter((href) => !html.includes(`rel="modulepreload" href="${href}"`)).map((href) => `<link rel="modulepreload" href="${href}">`).join("");
105
+ const head = html.indexOf("</head>");
106
+ return links === "" || head === -1 ? html : html.slice(0, head) + links + html.slice(head);
107
+ };
108
+ const normalizeId = (id) => id.replaceAll("\\", "/");
109
+ const chunkGraphOf = (bundle, rendererEntry) => {
110
+ const entry = normalizeId(rendererEntry);
111
+ const graph = /* @__PURE__ */ new Map();
112
+ for (const output of Object.values(bundle)) {
113
+ if (output.type !== "chunk") continue;
114
+ graph.set(output.fileName, {
115
+ imports: output.imports,
116
+ dynamicImports: output.dynamicImports,
117
+ foldkitRenderer: output.facadeModuleId !== null && normalizeId(output.facadeModuleId) === entry
118
+ });
119
+ }
120
+ return graph;
121
+ };
122
+ /** Records the client bundle's chunk graph for {@link writeIslandPreloads}. */
123
+ const preloadPlugin = (rendererEntry, record) => ({
124
+ name: "astro-foldkit:preload",
125
+ apply: "build",
126
+ generateBundle(_options, bundle) {
127
+ if (this.environment?.config.consumer !== "client") return;
128
+ record(chunkGraphOf(bundle, rendererEntry));
129
+ }
130
+ });
131
+ const htmlFiles = async (directory) => (await readdir(directory, {
132
+ recursive: true,
133
+ encoding: "utf8"
134
+ })).filter((path) => path.endsWith(".html")).map((path) => join(directory, path));
135
+ /**
136
+ * Rewrites the pre-rendered pages under `directory` that boot a FoldKit island
137
+ * at load. Pages rendered on request are not on disk and keep the chain.
138
+ *
139
+ * @returns the number of pages rewritten.
140
+ */
141
+ const writeIslandPreloads = async (directory, graph) => {
142
+ let rewritten = 0;
143
+ for (const file of await htmlFiles(directory)) {
144
+ const html = await readFile(file, "utf8");
145
+ if (!html.includes("<astro-island")) continue;
146
+ const updated = addIslandPreloads(html, graph);
147
+ if (updated === html) continue;
148
+ await writeFile(file, updated);
149
+ rewritten += 1;
150
+ }
151
+ return rewritten;
152
+ };
153
+ //#endregion
3
154
  //#region src/index.ts
4
155
  function foldkit(options = {}) {
5
156
  const configuredBuildId = options.server?.buildId;
6
157
  if (configuredBuildId !== void 0 && configuredBuildId.trim() === "") throw new Error("foldkit({ server: { buildId } }) requires a non-empty server.buildId.");
158
+ const rendererEntry = fileURLToPath(new URL("./client.mjs", import.meta.url));
159
+ let clientGraph;
7
160
  return {
8
161
  name: "astro-foldkit",
9
- hooks: { "astro:config:setup": ({ addRenderer, updateConfig }) => {
10
- addRenderer({
11
- name: "astro-foldkit",
12
- clientEntrypoint: fileURLToPath(new URL("./client.mjs", import.meta.url)),
13
- serverEntrypoint: fileURLToPath(new URL("./server.mjs", import.meta.url))
14
- });
15
- updateConfig({ vite: { plugins: [foldkit$1(options.server)] } });
16
- } }
162
+ hooks: {
163
+ "astro:config:setup": ({ config, addClientDirective, addRenderer, updateConfig }) => {
164
+ addRenderer({
165
+ name: "astro-foldkit",
166
+ clientEntrypoint: rendererEntry,
167
+ serverEntrypoint: fileURLToPath(new URL("./server.mjs", import.meta.url))
168
+ });
169
+ addClientDirective({
170
+ name: "interaction",
171
+ entrypoint: fileURLToPath(new URL("./directive-interaction.mjs", import.meta.url))
172
+ });
173
+ updateConfig({ vite: { plugins: [
174
+ foldkit$1(options.server),
175
+ islandScanPlugin(fileURLToPath(config.root), fileURLToPath(config.srcDir)),
176
+ preloadPlugin(rendererEntry, (graph) => {
177
+ clientGraph = graph;
178
+ })
179
+ ] } });
180
+ },
181
+ "astro:build:done": async ({ dir, logger }) => {
182
+ if (clientGraph === void 0) return;
183
+ const rewritten = await writeIslandPreloads(fileURLToPath(dir), clientGraph);
184
+ if (rewritten > 0) logger.info(`Added module preloads for FoldKit islands to ${rewritten} page${rewritten === 1 ? "" : "s"}.`);
185
+ }
186
+ }
17
187
  };
18
188
  }
19
189
  //#endregion
package/dist/server.mjs CHANGED
@@ -52,8 +52,8 @@ const warnOnce = (key, message) => {
52
52
  console.warn(message);
53
53
  };
54
54
  /**
55
- * Names the two ways an island that is not pre-rendered fails without an
56
- * error, both of which leave it as the empty mount shell forever.
55
+ * Names the ways an island that is not pre-rendered silently misbehaves. Two
56
+ * leave it as the empty mount shell forever.
57
57
  *
58
58
  * With no client directive, nothing ever replaces the shell, so the island
59
59
  * renders nothing and ships nothing. With `client:visible`, Astro observes the
@@ -61,12 +61,16 @@ const warnOnce = (key, message) => {
61
61
  * mount measures 0x0, a zero-area target never intersects, and the island never
62
62
  * hydrates. Other directives fire whatever the island's size.
63
63
  *
64
+ * `client:interaction` on a shell does not fail, but it cannot do its job: it
65
+ * waits for input on markup the shell does not have, so it hydrates at once.
66
+ *
64
67
  * Both warn rather than fail: the shell is still valid output, and a warning
65
68
  * should never be what breaks a build.
66
69
  */
67
70
  const diagnoseShellIsland = (metadata) => {
68
71
  const name = metadata?.displayName ?? "A FoldKit island";
69
72
  if (metadata?.hydrate === void 0) warnOnce(`${name}:no-directive`, `[astro-foldkit] ${name} has no client directive and is not pre-rendered, so it renders an empty mount and ships no JavaScript: it will never display anything. Pass { prerender: true } to lazyApp to render it as static HTML, or add a client directive.`);
73
+ else if (metadata.hydrate === "interaction") warnOnce(`${name}:interaction`, `[astro-foldkit] ${name} uses client:interaction but is not pre-rendered. It waits for the reader to interact with the island's markup, and an empty FoldKit mount has none, so it hydrates at once, as client:load would. Pass { prerender: true } to lazyApp, or use client:load or client:idle.`);
70
74
  else if (metadata.hydrate === "visible") warnOnce(`${name}:visible`, `[astro-foldkit] ${name} uses client:visible but is not pre-rendered. Astro observes an island's children, and an empty FoldKit mount measures 0x0, so it never intersects and the island never hydrates. Pass { prerender: true } to lazyApp, or use client:load or client:idle.`);
71
75
  };
72
76
  async function check(component) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsydyn/astro-foldkit",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Astro integration and renderer for FoldKit.",
5
5
  "keywords": [
6
6
  "astro",