@opsydyn/astro-foldkit 0.13.0 → 1.0.0-next.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/README.md CHANGED
@@ -1,834 +1,40 @@
1
- # @opsydyn/astro-foldkit
1
+ # Astro package migration
2
2
 
3
- Astro integration and renderer for [FoldKit](https://foldkit.dev), with
4
- islands that can pre-render, and an opt-in server-rendered page path.
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 choose per island whether and when it ships JavaScript.
7
-
8
- There are two deliberately separate entry paths:
9
-
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
- - `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
-
13
- ## Installation
14
-
15
- For coding agents, the independent
16
- [astro-foldkit skill](https://github.com/opsydyn/fold-kit-experiments/tree/main/skills/astro-foldkit)
17
- includes consumer guidance and a standalone island/SSG example. Install the
18
- complete skill folder through your agent host; it is separate from this npm
19
- package and does not require the Viz skill.
20
-
21
- ```sh
22
- npm install @opsydyn/astro-foldkit
23
- # peer deps
24
- npm install astro foldkit
25
- ```
26
-
27
- ## FoldKit compatibility
28
-
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.
32
- Applications can define interruptible work with
33
- `Command.define(name, { interrupt: true, ... })` inside their own update loop;
34
- this integration continues to own Astro rendering, hydration, and lifecycle
35
- event delivery.
36
-
37
- ## Setup
38
-
39
- Add the integration to `astro.config.ts`:
3
+ `@opsydyn/astro-foldkit` 1.x forwards the integration and component adapter
4
+ from `@opsydyn/astro-effect-ui`. Both import paths use the same renderer.
5
+ This branch uses the `1.0.0-next.0` archives for local qualification.
40
6
 
41
7
  ```ts
42
8
  import { defineConfig } from 'astro/config';
43
- import foldkit from '@opsydyn/astro-foldkit';
44
-
45
- export default defineConfig({
46
- integrations: [foldkit()],
47
- });
48
- ```
49
-
50
- FoldKit generates one public build identity for the coordinated client and server
51
- artifacts. The integration uses that compiled identity by default, including
52
- Astro's prerender and Cloudflare environments. Astro continues to own the HTML
53
- document, assets, and deployment adapter; do not enable the standalone FoldKit
54
- `ssr.build` pipeline inside this integration.
55
-
56
- For separately built artifacts, supply the same deployment-specific
57
- `FOLDKIT_BUILD_ID` environment variable to every build, or configure
58
- `foldkit({ server: { buildId: 'release-unique-deployment-id' } })`. The ID appears
59
- in public HTML, so it must not contain secrets. Do not reuse it across deployments
60
- with different rendering inputs. Blank `server.buildId` options are rejected, and FoldKit
61
- fails closed when neither a compiled identity nor an explicit override is available.
62
-
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.
66
-
67
- ## Defining an app
68
-
69
- Use `lazyApp` to register a FoldKit app for lazy loading. The literal loader keeps each Astro island as an explicit code-splitting boundary; it returns your `main.ts` module, which must export a value that satisfies `AppConfig`. `defineApp` remains available as a backwards-compatible alias.
70
-
71
- ```ts
72
- // src/apps/counter/app.ts
73
- import { lazyApp } from '@opsydyn/astro-foldkit/define-app';
74
-
75
- export default lazyApp(() => import('./main'));
76
- ```
77
-
78
- ```ts
79
- // src/apps/counter/main.ts
80
- import { Schema } from 'effect';
81
- import type { Document, HtmlBuilder } from 'foldkit/html';
82
-
83
- type Message = 'Inc' | 'Dec';
84
-
85
- // `Model` is a runtime Schema, not a plain value: FoldKit reads `Model.ast`
86
- // while the island hydrates. A non-Schema `Model` type-checks, because the
87
- // contract types it as `unknown`, then fails at hydration.
88
- export const Model = Schema.Number;
89
- export type Model = typeof Model.Type;
90
-
91
- export const init = () => ({ model: 0 });
92
- export const update = (model: Model, message: Message) => ({
93
- model: message === 'Inc' ? model + 1 : model - 1,
94
- });
95
- export const view = (model: Model, h: HtmlBuilder<Message>): Document => ({
96
- title: `Counter: ${model}`,
97
- body: h.button([h.OnClick('Inc')], [String(model)]),
98
- });
99
- ```
100
-
101
- A string-union `Message` keeps this example small. Applications with more than a
102
- couple of messages should use `defineMessageUnion` from `foldkit/message`, as
103
- the [astro-foldkit skill](../../skills/astro-foldkit) and the demo apps do.
104
-
105
- Use the app in an Astro page:
106
-
107
- ```astro
108
- ---
109
- import Counter from '../apps/counter/app'
110
- ---
111
- <Counter client:load noMeta />
112
- ```
113
-
114
- `noMeta` keeps the island from writing `document.title` on every render tick,
115
- which is what you want whenever the Astro page owns its own title — in
116
- particular on any page carrying more than one island. Drop it only when this
117
- island is meant to own the page title. See [`noMeta`](#nometa).
118
-
119
- For `lazyApp` / `defineApp`, the server renderer emits a deterministic
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.
130
-
131
- ### Pre-rendered islands (opt-in)
132
-
133
- An island can put its first paint in the HTML:
134
-
135
- ```ts
136
- import { lazyApp } from '@opsydyn/astro-foldkit/define-app';
137
-
138
- export default lazyApp<Props>(() => import('./main'), { prerender: true });
139
- ```
140
-
141
- The server then loads the module and runs `init` and `view` over the props
142
- Astro already serialises, filling the same mount shell instead of leaving it
143
- empty. The markup is static. Nothing hydrates it, and the client replaces it on
144
- boot exactly as it replaces an empty mount; because both sides run the same
145
- pure `init` and `view` over the same props, the replacement is the same markup.
146
-
147
- It carries no hydration stamp and no Flags payload, so any number of
148
- pre-rendered islands may share one document — unlike a `definePage` owner, of
149
- which a document may hold one. No build identity is involved, and no Astro
150
- request context is read.
151
-
152
- Two consequences are worth knowing:
153
-
154
- - `init` and `view` run on the server. An island whose `init` touches a
155
- browser-only resource must leave this off. Opting in and failing fails the
156
- render rather than quietly falling back to the empty mount, because an author
157
- who asked for markup should be told they did not get it.
158
- - `client:visible` only works for an island that opts in. Astro's directive
159
- observes an island's children, because `astro-island` is `display: contents`;
160
- an empty mount measures 0x0 and never intersects, so the island silently
161
- never hydrates. A pre-rendered island has size, and the directive works.
162
-
163
- ### Choosing when JavaScript runs
164
-
165
- Pre-rendering separates two decisions that used to be one: whether an island
166
- appears in the HTML, and whether it ships JavaScript. Make them per island.
167
-
168
- | Island needs | Write | JavaScript at load |
169
- | --------------------------- | ------------------------------------------------- | ---------------------------- |
170
- | To be read, never touched | `prerender: true`, **no directive** | none for this island |
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 |
173
- | Interaction, immediately | `prerender: true`, `client:load` or `client:idle` | the runtime, at load |
174
- | A browser-only `init` | no `prerender`, `client:load` or `client:idle` | the runtime, at load |
175
-
176
- An island with no directive is Astro's ordinary static component: Astro emits
177
- no `<astro-island>` element and no script, so a pre-rendered FoldKit chart with
178
- no directive is complete HTML and nothing else. Most charts in a report are
179
- never interacted with, and this is how they should ship.
180
-
181
- One thing decides how much any of this saves: **the FoldKit runtime is shared,
182
- so one island that hydrates at load pays for all of it.** Making three of four
183
- islands static saves their own chunks and serialised props, not the runtime the
184
- fourth still needs. The large win comes when _nothing_ on the page hydrates at
185
- load. The pattern that gets there is to pre-render everything, leave the
186
- readable islands without a directive, and give the one interactive island
187
- `client:visible` if it sits below the fold.
188
-
189
- Measured on a report page with three charts and a data grid over 7,729 rows:
190
-
191
- | Configuration | JavaScript at load | After scrolling to the grid |
192
- | ------------------------------------------------------------- | -------------------- | --------------------------- |
193
- | Four islands, `client:load` | 377 KB, 17 requests | — |
194
- | Three charts static, grid `client:load` | 351 KB, 8 requests | — |
195
- | Everything pre-rendered, charts static, grid `client:visible` | **0 KB, 0 requests** | 351 KB, 8 requests |
196
-
197
- In the last configuration the whole report, the grid's first page included,
198
- renders before any JavaScript runs. A chart that loses its hover readout by
199
- going static can keep the information as a native SVG `<title>` on each mark,
200
- which the browser shows as a tooltip and which costs no runtime.
201
-
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
263
- without an error, each once per component:
264
-
265
- - an island with **no directive and no `prerender`** renders an empty mount and
266
- ships nothing, so it never displays anything;
267
- - an island with **`client:visible` and no `prerender`** never intersects, for
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.
271
-
272
- FoldKit replaces the inner mount, not the outer `<astro-island>`. The outer
273
- element remains Astro's lifecycle owner, including for empty `client:only`
274
- hosts, where the client renderer creates an inner mount. Nested islands keep
275
- their own mounts.
276
-
277
- The demo app's [`/request-diagnostics`](../../apps/web/src/pages/request-diagnostics.astro) page shows the integration boundary with a practical machine-driven chart workflow. The page uses `@opsydyn/astro-foldkit` for hydration, `@opsydyn/foldkit-viz` for chart primitives, and `foldkit/experimental/machine` in the application update layer.
278
-
279
- The [`/comparison`](../../apps/web/src/pages/comparison.astro) example hosts
280
- dynamic scatter/histogram panels using the same `lazyApp` island contract.
281
- Stable panel IDs, `foldChildAt`, linked selection, measurements and focus policy
282
- belong to the application. Astro provides hydration and lifecycle facts only;
283
- no additional integration API or server-rendering opt-in is required. The promo
284
- hosts the maintained workbench with source inspection and standalone exports.
285
-
286
- ## Server-rendered pages (opt-in)
287
-
288
- Use `definePage` when one FoldKit application owns the document content for an
289
- Astro route. It is intentionally separate from `lazyApp`: existing apps and
290
- charts remain client-only islands unless they are explicitly migrated.
291
-
292
- The page loader has the same literal lazy-module shape as `lazyApp`, but its
293
- Flags factory is synchronous and receives request facts from Astro:
294
-
295
- ```ts
296
- // src/apps/greeting/page.ts
297
- import { definePage } from '@opsydyn/astro-foldkit/define-page';
298
- import { Match, Schema } from 'effect';
299
-
300
- import { Flags, type Locale, type Name } from './model';
301
-
302
- type Props = { readonly name: Name };
303
-
304
- const localeFromUrl = (url: URL): Locale =>
305
- Match.value(url.searchParams.get('locale')).pipe(
306
- Match.when('ar', () => 'ar' as const),
307
- Match.when('en', () => 'en' as const),
308
- Match.orElse(() => 'en' as const),
309
- );
310
-
311
- export default definePage<Props, Flags>(() => import('./main'), {
312
- flags: ({ props, url }) =>
313
- Schema.decodeSync(Flags)({
314
- name: props.name,
315
- locale: localeFromUrl(url),
316
- }),
317
- });
318
- ```
319
-
320
- The loaded `main` module exports the page configuration, including the runtime
321
- `Flags` Schema/value used by FoldKit to validate the serialized handoff:
322
-
323
- ```ts
324
- // src/apps/greeting/main.ts
325
- import { Message } from './message';
326
- import { Flags, init, Model } from './model';
327
- import { update } from './update';
328
- import { view } from './view';
329
-
330
- export { Flags, init, Message, Model, update, view };
331
- ```
332
-
333
- `Flags` must be public JSON-serializable data required to create the first
334
- Model. The factory may derive it from `request`, `url`, `params`, and validated
335
- component `props`, but it must not return secrets, credentials, request bodies,
336
- or runtime objects. It must not run Commands, Subscriptions, remote loads, or
337
- browser-only resources. Server rendering is a deterministic render handoff,
338
- not a server data-loading abstraction.
339
-
340
- ### Request SSR
341
-
342
- Resolve the same page document in the Astro frontmatter so its FoldKit metadata
343
- can reach the outer layout. Keep the resolver import server-only:
344
-
345
- ```astro
346
- ---
347
- export const prerender = false;
348
-
349
- import { Schema } from 'effect';
350
- import { resolvePageDocument } from '@opsydyn/astro-foldkit/server';
351
-
352
- import GreetingPage from '../apps/greeting/page';
353
- import { Name } from '../apps/greeting/model';
354
- import Layout from '../layouts/Layout.astro';
355
-
356
- const name = Schema.decodeSync(Name)(Astro.url.searchParams.get('name') ?? 'astronaut');
357
- const document = await resolvePageDocument(GreetingPage, {
358
- request: Astro.request,
359
- url: Astro.url,
360
- params: Astro.params,
361
- props: { name },
362
- });
363
- ---
364
-
365
- <Layout
366
- title={document.title}
367
- lang={document.lang}
368
- dir={document.dir}
369
- canonical={document.canonical}
370
- ogUrl={document.ogUrl}
371
- >
372
- <GreetingPage client:load name={name} />
373
- </Layout>
374
- ```
375
-
376
- The layout owns the outer `<html>` structure and applies `title`, `lang`,
377
- `dir`, `canonical`, and `ogUrl` from the resolved FoldKit `Document`. The
378
- `client:load` directive is still required for an interactive page: the server
379
- HTML contains one stamped FoldKit root and the browser hydrates that exact root
380
- with the serialized Flags payload.
381
-
382
- ### Canonical metadata
383
-
384
- `definePage` does not infer a canonical URL from `Astro.url`, route parameters,
385
- or the browser location. The page view must return `Document.canonical` when the
386
- application has a canonical identity. Query parameters and alternate
387
- representations remain application-owned. When FoldKit supplies the 0.165
388
- canonical-to-`ogUrl` fallback, the resolver passes it through unchanged.
389
-
390
- ### SSG
391
-
392
- The same page owner can be prerendered when its props and Flags are universal:
393
-
394
- ```astro
395
- ---
396
- export const prerender = true;
397
-
398
- import { Schema } from 'effect';
399
- import { resolvePageDocument } from '@opsydyn/astro-foldkit/server';
400
-
401
- import GreetingPage from '../apps/greeting/page';
402
- import { Name } from '../apps/greeting/model';
403
- import Layout from '../layouts/Layout.astro';
404
-
405
- const name = Schema.decodeSync(Name)('static astronaut');
406
- const document = await resolvePageDocument(GreetingPage, {
407
- request: Astro.request,
408
- url: Astro.url,
409
- params: Astro.params,
410
- props: { name },
411
- });
412
- ---
413
-
414
- <Layout
415
- title={document.title}
416
- lang={document.lang}
417
- dir={document.dir}
418
- canonical={document.canonical}
419
- ogUrl={document.ogUrl}
420
- >
421
- <GreetingPage client:load name={name} />
422
- </Layout>
423
- ```
424
-
425
- An SSG error fails the build. A request-SSR error reaches Astro's error
426
- response. The integration does not replace failed page rendering with the
427
- client-only shell. A document may have only one `definePage` owner; use
428
- `lazyApp` / `defineApp` for additional charts or embedded applications.
9
+ import effectUi from '@opsydyn/astro-effect-ui';
429
10
 
430
- `noMeta` remains an island-only option for `defineApp`. It does not change the
431
- page-owner metadata contract.
432
-
433
- ## Passing props
434
-
435
- `lazyApp` accepts a type parameter for the props your FoldKit app expects. This makes the component callable with typed attributes in `.astro` files.
436
-
437
- ```ts
438
- // src/apps/greeting/app.ts
439
- import { lazyApp } from '@opsydyn/astro-foldkit/define-app';
440
- import type { Name } from './model';
441
-
442
- export default lazyApp<{ name: Name }>(() => import('./main'));
443
- ```
444
-
445
- Props are forwarded from Astro's `<astro-island>` serialisation into your `init` function. Declare `init` to accept `props: unknown` and validate at the boundary with Effect Schema:
446
-
447
- ```ts
448
- // src/apps/greeting/model.ts
449
- import { Schema } from 'effect';
450
-
451
- export const Name = Schema.String.pipe(Schema.brand('Name'));
452
- export type Name = typeof Name.Type;
453
-
454
- const Props = Schema.Struct({ name: Name });
455
-
456
- export const init = (props: unknown): { readonly model: Model } => {
457
- const { name } = Schema.decodeUnknownSync(Props)(props);
458
- return { model: name };
459
- };
460
- ```
461
-
462
- Pass the branded value from the Astro page:
463
-
464
- ```astro
465
- ---
466
- import { Schema } from 'effect'
467
- import GreetingApp from '../apps/greeting/app'
468
- import { Name } from '../apps/greeting/model'
469
-
470
- const name = Schema.decodeSync(Name)(Astro.url.searchParams.get('name') ?? 'World')
471
- ---
472
- <GreetingApp client:load name={name} />
473
- ```
474
-
475
- The TypeScript types flow end-to-end: the `Name` brand is required at the Astro call site, and `Schema.decodeUnknownSync` re-validates the serialised value at the client hydration boundary.
476
-
477
- ## Built-in props
478
-
479
- The renderer intercepts one reserved prop before forwarding anything to your app. It is never seen by `init`, `update`, or `view`.
480
-
481
- ### `noMeta`
482
-
483
- Prevents the FoldKit program from overwriting `document.title`. Use this whenever you embed an app as an island on a page that manages its own title — without it, the island's view tree will update the browser tab title on every render tick.
484
-
485
- ```astro
486
- <DashboardChart client:load noMeta data={chartData} />
487
- ```
488
-
489
- Both `noMeta` and `noMeta={true}` are accepted. The wrapper pins only the
490
- Document `title`; FoldKit still applies `lang` and `dir` from the app's current
491
- Document.
492
-
493
- `noMeta` is declared on the default `EmptyProps`. Supplying your own `Props` to
494
- `lazyApp<Props>` replaces that type, so re-declare the prop to keep the opt-out
495
- available:
496
-
497
- ```ts
498
- // src/apps/chart/app.ts
499
- import { lazyApp } from '@opsydyn/astro-foldkit/define-app';
500
-
501
- import type { ChartProps } from './main';
502
-
503
- type Props = ChartProps & { readonly noMeta?: boolean | '' };
504
-
505
- export default lazyApp<Props>(() => import('./main'));
506
- ```
507
-
508
- Without it, `<Chart client:load noMeta />` fails to type-check with
509
- `Property 'noMeta' does not exist`.
510
-
511
- ## Architecture
512
-
513
- `definePage` owns one server-rendered FoldKit application for a document;
514
- `lazyApp` / `defineApp` owns an independent client island. The integration does
515
- not infer page ownership from ordinary app markers, and adding `definePage`
516
- does not migrate existing chart routes.
517
-
518
- ### Imperative shell, functional core
519
-
520
- The Astro page is the **imperative shell**: it performs side effects (HTTP fetches, query-param reads, URL parsing) and validates raw values into branded types via `Schema.decodeSync`. The shell hands only clean, typed values into the component.
521
-
522
- The FoldKit app is the **functional core**: its `init`, `update`, and `view` functions are pure. They receive already-validated props, run a closed message loop, and produce a view tree — with no side effects outside of declared `Command`s and `Subscription`s.
523
-
524
- ### Data flow
525
-
526
- ```mermaid
527
- flowchart TD
528
- subgraph shell ["Astro SSR (imperative shell)"]
529
- A[fetch / query params] --> B["Schema.decodeSync(Brand)"]
530
- B --> C[branded prop]
531
- end
532
-
533
- subgraph island ["Astro serialisation"]
534
- C --> D["&lt;astro-island props='...'&gt;"]
535
- end
536
-
537
- subgraph hydration ["Client hydration — client.ts"]
538
- D --> E["config.init(props)"]
539
- E --> F["Schema.decodeUnknownSync(Props)"]
540
- F --> G[initial Model]
541
- end
542
-
543
- subgraph core ["FoldKit runtime (functional core)"]
544
- G --> H[update loop]
545
- H --> I[view]
546
- I --> J[DOM patch]
547
- K["Subscription\n(animationFrame, events)"] --> H
548
- end
549
- ```
550
-
551
- The double-decode is intentional: `Schema.decodeSync` at the Astro boundary ensures the page cannot render with invalid data; `Schema.decodeUnknownSync` at the FoldKit boundary re-validates after JSON round-trip through the island serialisation, so the functional core never receives unverified input.
552
-
553
- ## AppConfig
554
-
555
- The module returned by your loader must export:
556
-
557
- | Export | Type | Description |
558
- | :------- | :------------------------------------------------------------------------ | :-------------------------------------------- |
559
- | `Model` | `unknown` | Initial model type marker |
560
- | `init` | `(props: unknown) => { model: Model; commands?: ReadonlyArray<Command> }` | Initial state from props and startup commands |
561
- | `update` | `(model, message) => { model: Model; commands?: ReadonlyArray<Command> }` | Pure state transition |
562
- | `view` | `(model, h: HtmlBuilder<Message>) => Document` | Render with the current render-frame builder |
563
-
564
- For `definePage`, `init` receives the validated `Flags` value rather than raw
565
- Astro props, and the module must additionally export the runtime `Flags`
566
- Schema/value. `defineApp` keeps the existing props-based `init` contract.
567
-
568
- ## Exports
569
-
570
- | Entry point | Description |
571
- | :----------------------------------- | :-------------------------------------------------------- |
572
- | `@opsydyn/astro-foldkit` | Default Astro integration (`foldkit()`) |
573
- | `@opsydyn/astro-foldkit/define-app` | `lazyApp` helper (`defineApp` alias) and `AppConfig` type |
574
- | `@opsydyn/astro-foldkit/define-page` | `definePage`, `PageConfig`, and page Flags context types |
575
- | `@opsydyn/astro-foldkit/server` | Server-only `resolvePageDocument` metadata resolver |
576
-
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`.
580
-
581
- ## Embedding
582
-
583
- `Runtime.embed` gives you a typed handle to the running program so you can clean it up on unmount and push live data in without remounting. This integration uses `embed` internally — the `astro:unmount` event calls `handle.dispose()` to tear down subscriptions and animation-frame loops when Astro navigates away.
584
-
585
- ### Declaring ports
586
-
587
- Ports are typed channels declared in your app's `main.ts`. Pass a `Schema` for each port so values are validated at the boundary.
588
-
589
- ```ts
590
- // src/apps/dashboard/main.ts
591
- import { Port } from 'foldkit';
592
- import { Schema } from 'effect';
593
-
594
- export const ports = {
595
- inbound: {
596
- data: Port.inbound(Schema.Array(DataPointSchema)),
597
- },
598
- outbound: {
599
- selection: Port.outbound(Schema.NullOr(Schema.String)),
600
- },
601
- };
11
+ export default defineConfig({ integrations: [effectUi()] });
602
12
  ```
603
13
 
604
- ### Navigation events
605
-
606
- To receive Astro View Transition lifecycle events, declare an inbound port and a mapper in the app configuration. Astro props remain the input to `init`; navigation events are runtime messages delivered through the configured port.
14
+ Define a component with Effect UI's `Html.component(...)`, then expose it
15
+ to Astro from a normal TypeScript module.
607
16
 
608
17
  ```ts
609
- // src/apps/dashboard/main.ts
610
- import { Schema } from 'effect';
611
- import { Port } from 'foldkit';
612
- import type { NavigationEvent } from '@opsydyn/astro-foldkit';
18
+ import { astroComponent } from '@opsydyn/astro-effect-ui/component';
19
+ import { Counter } from './counter';
613
20
 
614
- export const ports = {
615
- inbound: {
616
- navigation: Port.inbound(Schema.Unknown),
617
- },
618
- };
619
-
620
- export const navigation = {
621
- port: 'navigation',
622
- map: (event: NavigationEvent) => ({
623
- _tag: 'Navigated' as const,
624
- ...event,
625
- }),
626
- };
21
+ export default astroComponent(Counter);
627
22
  ```
628
23
 
629
- The mapper receives this value shape:
630
-
631
- ```ts
632
- type NavigationEvent = {
633
- readonly phase: 'coldLoad' | 'entered' | 'exited' | 'stayed';
634
- readonly path: string;
635
- readonly previousPath: string | null;
636
- };
637
- ```
638
-
639
- The bridge sends `coldLoad` immediately for the first mount of an island identity. A retained island receives `stayed` on `astro:before-swap` when its matching `uid` exists in the incoming document, but does not receive `entered` from the following global `astro:page-load`. A same-identity remount emits `entered` on mount; an active island can also emit `entered` for a later page load when it was not retained. Every mounted island emits `exited` once on `astro:unmount`. Events contain normalized pathnames; route parsing and route-specific message decisions belong in the app mapper. If the configured inbound port is missing, the integration warns once and leaves the FoldKit runtime mounted without forwarding events.
640
-
641
- The integration owns only lifecycle observation and port delivery. The app owns parsing `path` into its route type, mapping the event into a past-tense Message, and deciding whether an `entered` event should run a load or revalidation command. Keep that policy in `update` or a FoldKit `Transition`, so SSR props, navigation facts, and side effects remain separate. When an app uses exited to interrupt work, the interrupt key, state, and outcome policy stay in its update loop; the integration does not cancel or replace commands.
642
-
643
- ### Retained island ownership
644
-
645
- When Astro actually retains the same client-island element during navigation,
646
- the integration preserves its running FoldKit Model and resources. Repeated
647
- hydration of that host shares one initialization, including while its module
648
- is loading; it does not call `init` again or start another runtime. Matching a
649
- `uid` for navigation events alone is not a substitute for retaining the DOM host.
650
-
651
- Props seed `init` once per live runtime. Changes to Astro's serialized props do
652
- not reseed an active retained island; use app-owned inbound ports for live data.
653
- On genuine `astro:unmount`, the integration detaches its navigation bridge and
654
- disposes the runtime. Unmount during module loading prevents a later detached
655
- mount. Module-load or pure `init` failure releases ownership so hydration can
656
- retry; asynchronous runtime startup failures remain FoldKit-owned.
657
-
658
- Remounting the same host starts with fresh props and uses public `Runtime.embed`
659
- sequencing to wait for previous teardown before restarting. The host must still
660
- represent the same app, schemas, ports and update definition. This contract is
661
- for `lazyApp` / `defineApp` islands, not a new retained-navigation guarantee for
662
- `definePage` owners.
663
-
664
- Pass the ports map to `makeApplication` alongside your `init`, `update`, and `view`:
665
-
666
- ```ts
667
- import { Runtime } from 'foldkit';
668
-
669
- const program = Runtime.makeApplication({
670
- Model,
671
- init,
672
- update,
673
- view,
674
- container,
675
- devTools: false,
676
- ports,
677
- });
678
- ```
679
-
680
- ### Live prop updates
681
-
682
- Once embedded, push new data through an inbound port instead of remounting the component. This is particularly useful in Astro View Transition flows where the page shell re-runs but the island should preserve its running state:
683
-
684
- ```ts
685
- const handle = Runtime.embed(program);
686
-
687
- // Called when Astro soft-navigates back to this page with new data
688
- handle.ports.data.send(nextDataPoints);
689
- ```
690
-
691
- ### Outbound subscriptions
692
-
693
- Subscribe to outbound ports to react to events inside the program from the host page. Port names are flat on `handle.ports` regardless of whether they were declared under `inbound` or `outbound`:
694
-
695
- ```ts
696
- const unsubscribe = handle.ports.selection.subscribe((id) => {
697
- // sync selection state to the URL or another island
698
- history.replaceState({}, '', `?selected=${id ?? ''}`);
699
- });
700
-
701
- element.addEventListener(
702
- 'astro:unmount',
703
- () => {
704
- unsubscribe();
705
- handle.dispose();
706
- },
707
- { once: true },
708
- );
709
- ```
710
-
711
- ## Peer dependencies
712
-
713
- | Package | Version |
714
- | :-------- | :-------------------- |
715
- | `astro` | `≥ 5.0` |
716
- | `effect` | `~4.1.0` |
717
- | `foldkit` | `≥ 0.170.0 < 0.171.0` |
718
-
719
- ## Stateflow Observatory example
720
-
721
- The demo route `/stateflow` uses `StateflowPage`, an app-owned `definePage` entry,
722
- to server-render the graph and current state before hydrating with `client:load`
723
- inside the existing Astro layout. Astro supplies the island and lifecycle facts;
724
- the app owns the Machine, typed inbound replay Port, outbound transition telemetry Port,
725
- replay policy, and trace inspector. The graph consumes plain layout records.
726
-
727
- This slice adds no Astro integration API and moves no async work into the
728
- integration. Commands and subscriptions remain app-owned, including telemetry
729
- emission, validation of inbound replay events, and the reduced-motion
730
- `Dom.streamFromMediaQuery` stream in a `Subscription.persistentEntry`. That subscription is the app's
731
- example of FoldKit PR [#1424](https://github.com/foldkit/foldkit/pull/1424): it
732
- records the browser's initial media-query match and subsequent changes, then
733
- lets the Model decide whether visual motion is allowed.
734
-
735
- ## Remote visual loads
736
-
737
- For future remote filter, brush, or zoom loads, construct the refresh step with
738
- an explicit selection snapshot and request ID. `LoadFilteredData` is an
739
- app-owned interruptible Command whose declared args include `selection` and
740
- `requestId`; its `execute` uses those args and returns the ID with its result
741
- Message. Commands do not read the later Model implicitly.
742
-
743
- In this example, `Model.data` is `AsyncData<Data, string>`. `Selection`, `Data`,
744
- `Model`, and `Message` are application types. The app also stores the latest
745
- `selection`, a monotonic `nextRequestId`, `routeActive`, and a discriminated
746
- `request` union: `Idle | Running { requestId } | Cancelling { requestId }`.
747
-
748
- ```ts
749
- import { Option } from 'effect';
750
- import { getData, Idle, revalidateOrLoad, succeed } from 'foldkit/asyncData';
751
- import { refresh } from 'foldkit/update';
752
- import type { Return } from 'foldkit/update';
753
-
754
- import { LoadFilteredData } from './command';
755
- import type { Message } from './message';
756
- import type { Data, Model, Selection } from './model';
757
-
758
- const loadOnFilter = (selection: Selection, requestId: number) =>
759
- refresh<Model, Message, Data, string>({
760
- read: (model) => Option.some(model.data),
761
- revalidate: revalidateOrLoad,
762
- write: (model, data) => ({ ...model, data }),
763
- load: LoadFilteredData({ selection, requestId }),
764
- });
765
-
766
- // Call only when request is Idle and data is not Loading or Refreshing.
767
- const startLatest = (model: Model): Return<Model, Message> => {
768
- const requestId = model.nextRequestId;
769
- const next: Model = {
770
- ...model,
771
- nextRequestId: requestId + 1,
772
- request: { _tag: 'Running', requestId },
773
- };
774
- return loadOnFilter(next.selection, requestId)(next);
775
- };
776
-
777
- // The outcome handler first checks Cancelling and the cancelled request ID.
778
- const afterInterruption = (model: Model): Return<Model, Message> => {
779
- const next: Model = {
780
- ...model,
781
- request: { _tag: 'Idle' },
782
- data: Option.match(getData(model.data), {
783
- onNone: () => Idle(),
784
- onSome: (data) => succeed(data),
785
- }),
786
- };
787
- if (!next.routeActive) return { model: next };
788
- return startLatest(next);
789
- };
790
- ```
791
-
792
- Use this explicit **latest-selection wins** policy in the app's update loop:
793
-
794
- 1. Record every new filter, brush, or zoom selection in `Model.selection`. If
795
- the route is active and `request` is `Idle`, call `startLatest` with that
796
- updated Model. While the route is inactive, only store the selection.
797
- 2. If a request is `Running`, change it to `Cancelling` with the same request
798
- ID and return only its keyed interruption Command. Capture that ID in the
799
- interruption outcome Message. Do not start a replacement in the same batch.
800
- 3. While `Cancelling`, keep replacing `Model.selection` with the latest input;
801
- emit no further load or interruption Commands. Ignore normal result Messages
802
- for this cancelled request, including a result racing with interruption.
803
- 4. For a matching interruption outcome (`Interrupted` or `NotFound`), call
804
- `afterInterruption` using the current Model. An interrupted Command will not
805
- send its original result Message. The helper therefore explicitly clears
806
- pending AsyncData: `Loading` becomes `Idle`, and `Refreshing(data)` becomes
807
- `Success(data)`. It then starts the latest selection with a fresh ID, moving
808
- back to `Loading` or `Refreshing`. Calling `refresh` on the old pending state
809
- would produce no Command because `revalidateOrLoad` returns `None` there.
810
- 5. Accept a normal result only when its ID matches the `Running` request.
811
- Apply `settle(model.data, result)` from `foldkit/asyncData` and set `request`
812
- to `Idle` in the same update. Ignore stale IDs and duplicate outcomes. Cached
813
- data retained during replacement still belongs to the previous selection;
814
- present it as such until the matching replacement result arrives.
815
- 6. On route exit, mark the route inactive and interrupt any `Running` request,
816
- or wait for the existing `Cancelling` outcome. The same outcome handler
817
- clears pending AsyncData but starts no replacement while inactive. Route
818
- entry can call `startLatest` from `Idle`; if still `Cancelling`, wait for its
819
- outcome before loading the latest selection.
820
-
821
- The app owns command keys and correlation, interruption/cancellation policy,
822
- AsyncData, and the Model. `refresh` supplies the revalidation step, not that
823
- replacement policy. The app derives the records supplied to `foldkit-viz`,
824
- whose synchronous functions compute geometry; chart primitives cannot fetch
825
- data or subscribe to events or Ports.
826
-
827
- Use typed Ports only for host input/output: map validated inbound values to app
828
- Messages and emit outbound values through app-owned Commands. Keep internal
829
- state in the Model and internal event flow in Messages and update. Astro mounts
830
- the island and supplies lifecycle facts; it does not own remote visual loads.
24
+ Use the component as a normal Astro import. Astro renders its markup on
25
+ the server. Choose `client:load`, `client:idle`, `client:visible` or
26
+ `client:interaction` when it needs a browser runtime. For browser-only
27
+ components use `client:only="astro-effect-ui"`.
831
28
 
832
- ## License
29
+ | 0.x import or option | 1.x migration |
30
+ | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
31
+ | Default integration from `@opsydyn/astro-foldkit` | Use the default integration from `@opsydyn/astro-effect-ui`. The previous package name also forwards to it. |
32
+ | `/define-app`, `lazyApp`, `defineApp`, or `prerender` option | Move the model, messages and view to `Html.component` and wrap it with `astroComponent` from `/component`. |
33
+ | `/define-page`, Flags, or the `/server` document resolver | Resolve request data, page metadata and layouts in Astro. Pass only public, serializable props into the component. |
34
+ | Build IDs and navigation messages | Use Astro's navigation and the Effect UI island scope. |
35
+ | Slots into an island | Compose the markup in an Astro layout or inside the component tree. |
833
36
 
834
- MIT
37
+ Consumers still running FoldKit can pin the published 0.x integration.
38
+ The standalone renderer's release artifact is staged in
39
+ `packages/astro-effect-ui/dist`. Rehearse both archives together because
40
+ the forwarding archive declares the exact standalone version.