@opsydyn/astro-effect-ui
v1.0.0-next.4
Published
Render Effect UI components in Astro: on the server, as islands, or both.
Maintainers
Readme
@opsydyn/astro-effect-ui
Render Effect UI components in Astro: on the server, as islands that hydrate on a schedule you choose, or in the browser only.
Astro owns the page: its markup, request data, metadata and navigation. An Effect UI component owns its model, messages, view and update. This package is the renderer between the two.
Which package: this one, or @opsydyn/astro-foldkit?
Use this one. @opsydyn/astro-effect-ui holds the renderer, the hydration code and
the whole API on this page.
@opsydyn/astro-foldkit is the
name the integration was first published under, when it rendered FoldKit apps. From 1.x
it contains no renderer of its own: it re-exports the integration, astroComponent and
defineIslands from this package, at one exact version, so a project that already
installs the old name keeps working.
| | @opsydyn/astro-effect-ui | @opsydyn/astro-foldkit |
| ---------------------------- | -------------------------------------- | -------------------------------------------- |
| What it is | The renderer | The earlier name, forwarding to the renderer |
| Start a new project with it | Yes | No |
| Integration, /component | Yes | Yes, re-exported |
| /runtime (defineIslands) | Yes | Yes, re-exported from 1.2.0 |
| Versions | 1.0.0-next.*, on next and latest | 1.x forwards; 0.x is the FoldKit runtime |
Install
npm install @opsydyn/astro-effect-ui@next [email protected] https://pkg.pr.new/Effect-TS/ui/@effect/ui@6679263astro, effect and @effect/ui are peer dependencies. Your components are written
with Effect and Effect UI, so your project chooses the copy and there is only one.
| Peer | Range | Note |
| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| astro | >=5.0.0 <8 | Each release is built and checked against Astro 5, 6 and 7. |
| effect | ~4.1.0 | |
| @effect/ui | * | Effect UI has no npm releases yet, only snapshots installed by URL, which no range can name. 6679263 is the one this release was tested with. |
Node 22 or later.
Quick start
Register the integration:
// astro.config.ts
import { defineConfig } from 'astro/config';
import effectUi from '@opsydyn/astro-effect-ui';
export default defineConfig({ integrations: [effectUi()] });Write a component with Effect UI:
// src/counter/main.ts
import { UiSchema } from '@effect/ui';
import { Html } from '@effect/ui/html';
import { Schema } from 'effect';
const Message = UiSchema.TaggedEnum({ Incremented: {} });
export const Counter = Html.component({
name: 'Counter',
props: Schema.Struct({ start: Schema.Int }),
model: Schema.Int,
message: Message,
}).make({
init: ({ props }) => props.start,
update: ({ model }) => model + 1,
view: (h, count) => h.button.on('click', Message.Incremented()).children(`Count: ${count}`),
});Hand it to Astro from a TypeScript module:
// src/counter/app.ts
import { astroComponent } from '@opsydyn/astro-effect-ui/component';
import { Counter } from './main';
export default astroComponent(Counter);Use it like any Astro component. Its props are typed from the component's schema:
---
import Counter from '../counter/app';
---
<Counter client:interaction start={3} />Choosing when an island hydrates
Astro renders the component's markup on the server whichever you choose. The directive decides when, or whether, it gets a browser runtime.
| Directive | The component becomes interactive |
| ------------------------------- | --------------------------------------------------------------- |
| none | Never. Static markup, and no JavaScript for it. |
| client:load | As the page loads. |
| client:idle | When the browser is next idle. |
| client:visible | When it scrolls into view. |
| client:media="(query)" | When the media query matches. |
| client:interaction | When a reader first presses, focuses or types in it. See below. |
| client:only="astro-effect-ui" | In the browser only. Nothing is rendered on the server. |
astro-effect-ui is the renderer's name, which client:only needs.
client:interaction
This directive comes with the integration. An island stays as the server rendered it, with none of its code loaded, until someone uses it.
<Chart client:interaction />
<Chart client:interaction={{ hover: true, preload: 'visible' }} />| Option | Type | Default | Effect |
| --------- | --------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| hover | boolean | false | A mouse pointer entering the island hydrates it too. Suits a chart or a card that only shows something on hover. Touch and pen do not count: they press. |
| preload | 'idle' \| 'visible' | none | Fetch the island's code ahead of the first interaction. Nothing hydrates early. |
What starts hydration, inside the island:
| Event | When |
| -------------------------- | --------------------------------------------- |
| pointerdown | Always |
| focusin | Always, so keyboard users reach it by tabbing |
| keydown | Always |
| pointerover from a mouse | Only with hover: true |
- Input made while the island loads is kept. A click is held and replayed. A mouse
resting on the island is replayed as
mouseenter, once for each element under it, outermost first. Keys pressed in that moment are not replayed. - Links and native controls are left alone. A click on a link, a label, a checkbox or a radio button does what the browser does, while the island hydrates behind it.
preload: 'idle'waits forrequestIdleCallback, or 200 ms where the browser has none.preload: 'visible'fetches when the island comes within 200 px of the viewport.preloadcosts the download.idleon every island of a long page fetches all of them. On a 100 ms, 5 Mbit/s connection a first hover answered in about 950 ms without it and about 30 ms with it.- Code that does not arrive is asked for again on the next interaction, three times in all. See When something fails.
astro checkknows the attribute. The integration declares its type.
API
The package has three entry points. Everything each one exports is listed here.
| Entry point | Exports |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| @opsydyn/astro-effect-ui | effectUi (default), EffectUiOptions |
| @opsydyn/astro-effect-ui/component | astroComponent, AstroComponent, Accepted, IslandProps, IslandRendererError, IslandComponent, asIslandComponent, toAstro |
| @opsydyn/astro-effect-ui/runtime | defineIslands, ServerRuntime, ClientRuntime, IslandFailure, IslandFallback, AnyServerRuntime, AnyClientRuntime |
@opsydyn/astro-effect-ui
effectUi(options?): default export
function effectUi(options?: EffectUiOptions): AstroIntegration;Returns the Astro integration. It does four things:
- registers the renderer, named
astro-effect-ui; - registers the
client:interactiondirective and declares its type forastro check; - sets up Vite (see Vite);
- for each runtime module you name, writes an entry file into Astro's generated-code directory that makes the renderer with it.
EffectUiOptions
type EffectUiOptions = {
readonly interaction?: boolean;
readonly runtime?: { readonly server?: string; readonly client?: string };
};| Option | Type | Default | Meaning |
| ---------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| interaction | boolean | true | false registers neither the client:interaction directive nor its type. |
| runtime.server | string | none | Path from the project root to a module that default-exports a server runtime. See Services. |
| runtime.client | string | none | The same for the browser. |
@opsydyn/astro-effect-ui/component
astroComponent(component)
function astroComponent<C extends Component.Any>(component: C & Accepted<C>): AstroComponent<C>;Takes an Effect UI component and returns what Astro imports. The result takes the component's props, typed from its props schema. Astro serialises an island's props to send them to the browser, so they must be serialisable.
It accepts only a component that needs no services beyond the HTML host. For one that
issues a Command.Service, or needs any other service, the call is a type error whose
one property names what is missing. For a component that needs DeleteTodo, the
argument would have to be:
{ readonly 'astroComponent: no island runtime provides': DeleteTodo }Use the astroComponent that defineIslands returns
instead.
AstroComponent<C>
type AstroComponent<C> = (props: Component.Props<C>) => void;What astroComponent returns for component C: to Astro, a component taking its props.
Accepted<C, Provided = never>
The check astroComponent applies to its argument. It is unknown, which changes
nothing, when the HTML host and the services Provided cover what C requires.
Otherwise it is an object type with the one property shown above. Requirements typed as
any are let through, since nothing can be read from them.
IslandProps
type IslandProps = object;The props an island may take.
IslandRendererError
class IslandRendererError extends Data.TaggedError('IslandRendererError')<{
readonly message: string;
readonly cause?: unknown;
}> {}What the renderer fails with. Errors lists the messages.
IslandComponent, asIslandComponent(value), toAstro(component)
type IslandComponent = Component.Members<
string,
IslandProps,
unknown,
never,
never,
Html.Host,
Html.Elements
>;
function asIslandComponent(value: Component.Any): IslandComponent;
function toAstro<C>(component: Component.Any): AstroComponent<C>;The renderer's own entry points use these, and an app has no need to.
IslandComponent is a component as the renderer runs it. asIslandComponent narrows
a value to one, failing with IslandRendererError when it is not an Effect UI
component. toAstro is astroComponent without the services check.
@opsydyn/astro-effect-ui/runtime
defineIslands<Services>()
function defineIslands<Services = never>(): {
astroComponent: <C extends Component.Any>(
component: C & Accepted<C, Services>,
) => AstroComponent<C>;
serverRuntime: (runtime: ServerRuntime<Services>) => ServerRuntime<Services>;
clientRuntime: (runtime: ClientRuntime<Services>) => ClientRuntime<Services>;
};Names the services an app's islands may use, once, and returns three functions typed by them.
| Returned | Use |
| --------------------------- | --------------------------------------------------------------------------------------------------------- |
| astroComponent(component) | As above, but accepts a component whose needs Services cover. |
| serverRuntime(runtime) | Describes what every server render shares. Default-export the result from the runtime.server module. |
| clientRuntime(runtime) | Describes what every island on a page shares. Default-export the result from the runtime.client module. |
serverRuntime and clientRuntime return their argument unchanged. They exist to
check it against Services.
ServerRuntime<Services = never>
| Field | Type | Meaning |
| -------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| layer | Layer.Layer<Services, unknown> | Provides the services. Required as soon as Services names one, optional otherwise. Built once, on the first render. |
| budget | Duration.Input | How long a render waits for Layers and queries. Effect UI's default is 500 ms. |
ClientRuntime<Services = never>
| Field | Type | Meaning |
| ---------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| layer | Layer.Layer<Services, unknown> | Provides the services. Required as soon as Services names one, optional otherwise. Built once, when the first island on a page starts. |
| fallback | IslandFallback | The view shown in place of an island that failed. Without it the island keeps its earlier markup. |
| onError | (failure: IslandFailure) => Effect.Effect<void, never, Services> | Runs in the page's runtime when an island fails, as well as the effect-ui:error event. |
IslandFailure
type IslandFailure = Readonly<{ error: unknown; phase: 'activate' | 'run' }>;An island whose component failed: activate if it never came alive, run if it failed
later. It is what onError receives and the detail of effect-ui:error.
IslandFallback
type IslandFallback = NonNullable<BrowserHost.MountOptions<Html.Elements>['fallback']>;A fallback view, as Effect UI's BrowserHost.mount takes it: (result, h) => view,
where result.cause is why the root failed.
AnyServerRuntime, AnyClientRuntime
A runtime whatever its services, as the renderer receives it. They type the default
export of a runtime module once serverRuntime or clientRuntime has checked it.
What the server renders
| The component has | Output |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No client directive | Its markup, with nothing around it and no script. |
| A client directive | Its markup inside <div data-effect-ui-root>, followed by its state in <script type="application/json" data-effect-ui-state>. Hydration adopts both. |
| client:only | Nothing from the component. Astro shows any slot="fallback" content until the browser builds it. |
Only a component's body markup is used. Astro owns the document <head>, so set
titles and metadata in Astro.
In the browser
| When | What the renderer does |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| The directive fires | Adopts the server's markup and state, or builds the component under client:only. |
| Astro unmounts the island (astro:unmount, as on a client-side navigation) | Closes the component's runtime: its scope, subscriptions and resources. |
| A kept island's props change | Rebuilds the component. See Kept islands. |
| The component fails | See When something fails. |
Events, attributes and spans
| Name | Kind | Meaning |
| -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------- |
| effect-ui:error | Event on a failed island | Bubbles and crosses shadow roots. detail is an IslandFailure. |
| astro:hydration-error | Event | Raised by Astro 7 when hydration rejects, and by client:interaction on every Astro version. |
| data-effect-ui-failed | Attribute on a failed island | For a style or a test to find. Removed if the island is rebuilt. |
| data-effect-ui-root | Attribute | The element holding a hydrating component's markup. Written and read by the renderer. |
| data-effect-ui-state | Attribute | The script holding its serialised state. Written and read by the renderer. |
| astro-effect-ui.render | Span | Around each server render, with a component attribute. |
| astro-effect-ui.activate | Span | Around each island start in the browser, with the same attribute. |
Errors
Each is an IslandRendererError.
| Message | When |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Expected an Effect UI component. | Something other than an Effect UI component reached the renderer. |
| <Name> has no slot named "<slot>". It declares: <names>. | Astro passed content for a slot the component does not declare. |
| <Name> rendered nothing on the server and has no client directive. | A prerendered page: the build fails. On a page rendered for a request the same text is logged, prefixed [astro-effect-ui], and the page is still answered. |
| <Name> failed on the server at <paths> and has no client directive. | A child failed on the server, so its fallback is all the page would ever show. Treated like the row above: a build fails, a request logs it. |
| Missing Effect UI hydration markup or state. | An island was asked to hydrate without the root or state the server writes. |
| The <Name> island failed. | The component failed while running. cause holds why. |
Slots
An Effect UI component declares the places a parent can fill, and its view places them. Astro is that parent:
export const Card = Html.component({
name: 'Card',
props: Schema.Struct({ title: Schema.String }),
model: Schema.String,
message: Schema.Never,
slots: ['default', 'footer'],
}).make({
init: ({ props }) => props.title,
update: ({ model }) => model,
view: (h, title) =>
h.section.children(h.h2(title), h.slots.default, h.footer.children(h.slots.footer)),
});<Card client:load title="Welcome">
<p>Rendered by Astro.</p>
<small slot="footer">And so is this.</small>
</Card>- The content is Astro's markup, and may hold other islands.
- Hydration keeps the server's nodes. A slot the view removes and places again gets the same nodes back, so an island inside it keeps running.
- A static component gets the content with nothing around it.
- An undeclared slot is an error that names the slots the component does declare.
- Empty content is not a slot. A slot Astro passes with only whitespace is left out.
slot="fallback"stays Astro's. Underclient:onlyit is what shows until the component is built, and it is never passed to the component.
Services and the island runtime
Name the app's services once, and use the wrapper that knows them:
// src/islands.ts
import { defineIslands } from '@opsydyn/astro-effect-ui/runtime';
export const islands = defineIslands<DeleteTodo | Flags>();// src/effect-ui.client.ts: everything the islands of a page share
export default islands.clientRuntime({
layer: Layer.merge(DeleteTodo.layer, Flags.layer),
fallback: (_failure, h) => h.p.class('island-failed').children('This part could not load.'),
onError: (failure) => reportToTelemetry(failure),
});// src/effect-ui.server.ts: everything a server render shares
export default islands.serverRuntime({
layer: Layer.merge(DeleteTodo.layer, Flags.layer),
budget: '200 millis',
});// astro.config.ts
effectUi({
runtime: { server: './src/effect-ui.server.ts', client: './src/effect-ui.client.ts' },
});Then islands.astroComponent(TodoList) accepts a component whose needs those services
cover.
- One runtime on each side. The client layer is built once, when the first island on a page starts, and every island runs in it. The server layer is built once for the process, or for the isolate on Cloudflare Workers.
- Request data goes in props. The server layer outlives a request, so it must not hold request data. An island also runs again in the browser, where no request exists.
- Two modules, so server code stays on the server. A server layer often imports code that must never reach the browser. Either module may be left out.
- Tracing and logging use Effect's own channels. Renders and activations run inside the spans listed above, and the renderer's log lines go through Effect's logger, so a tracer or a logger in the layer sees them.
- Requirements typed as
anyare let through, since nothing can be read from them.
When something fails
A page keeps working when one island does not.
- The code does not arrive.
client:interactionleaves the island as the server rendered it and asks again on the next interaction, three times in all. Clicks held during a failed attempt are dropped. After the third attempt the island is plain markup. - The component fails, while it hydrates or at any time later. Its runtime is
closed and the island shows the server's markup again, or its fallback content
under
client:only. It no longer responds. With afallbackin the client runtime that view is shown in its place instead. The island getsdata-effect-ui-failed, raiseseffect-ui:error, and the runtime'sonErrorruns. A component that fails to hydrate is not retried. - Hydration fails under any directive. The renderer rejects, so Astro reports it
as it does for every framework:
astro:hydration-errorfrom Astro 7, a console error before that. - A component renders nothing on the server. With a client directive the browser
builds it. With none, nothing ever would, so a prerendered page fails the build and
a page rendered for a request is still answered, with an error logged through
Effect's logger that starts
[astro-effect-ui].
document.addEventListener('effect-ui:error', (event) => report(event.detail.error));Kept islands
A root's props are fixed once it starts. When an island kept across a navigation with
transition:persist is given different props, the component is rebuilt with them and
its Model starts over. Add transition:persist-props to keep the island as it is.
Vite
The integration prebundles effect, @effect/ui and @effect/ui/html, so the dev
server does not discover them on the first island and reload the page. It also resolves
effect and @effect/ui once, so the renderer and your components share one copy. An
app needs neither setting in its own config.
Why it works this way
The decisions behind this page are recorded in the repository:
Working on this package
bun run --filter @opsydyn/astro-effect-ui build
bun run --filter @opsydyn/astro-effect-ui test
bun run --filter @opsydyn/astro-effect-ui size:check
bun run ci:astro-compat- The build stages the npm package in
dist/, with this README. The workspace manifest is private; the staged one is what gets published. - The size check holds the renderer's browser code and the inlined directive to
etc/bundle-budget.json. - The compatibility check packs this package and the forwarding one, then builds isolated Astro 5, 6 and 7 projects from its fixture, which covers slots, a runtime module on each side, and the prerender flag.
- Publishing goes through the
effect-ui-nexttrain, described in the migration record.
