SSR / foldkit-ssr

Resumable pages: answering before the runtime boots

A resumable page waits to boot Foldkit's runtime until idle or first user interaction, capturing clicks and typing from encoded element markers and replaying them in order once the runtime starts:

  1. On the server, Resume.builder(h) encodes each handler's Message onto the element as a marker attribute and stores its schema binding in the envelope.
  2. In the browser, events on marked elements queue their Messages and trigger runtime boot.
  3. SSR.hydrate adopts the server DOM from the resumed Model, then runs queued Messages through update in order before any live events.
ts
const view = (model: Model, h: HtmlBuilder<Message>) => {
  const rh = Resume.builder(h)
  return {
    title: 'Post',
    body: rh.main(
      [],
      [
        rh.button([rh.OnClick(Message.Liked({ id: model.post.id }))], ['Like']),
        rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft)]),
        rh.input([rh.OnChange(Message.Renamed, { id: model.post.id })]),
        rh.div([rh.OnKeyDown(Message.Pressed)], []),
      ],
    ),
  }
}

OnInput, OnChange, OnKeyDown, and OnKeyUp accept a Message constructor directly when one string field (or key + modifiers) remains open for the event to fill. Closure handlers and fields with placeholder checks (such as Schema.isMinLength(1)) boot immediately when triggered and appear in result.unnamed. Inside a Surface view, use Resume.view:

ts
const LikeView = Surface.rootView(
  Like,
  undefined,
  Resume.view((like, rh) => rh.button([rh.OnClick(Message.Liked({ id: like.id }))], ['Like'])),
)

Set start on your plan to 'on-interaction' or 'idle' (default 'now'):

ts
const Post = SSR.plan(App, {
  id: 'post',
  state: Projection.pick(App.model.post),
  surfaces: [PostActionsAt],
  start: 'on-interaction',
})

What a resumable page must declare

  • Allowed messages on Surfaces: Every rh binding's Message must appear in an active Surface's messages array (UndeclaredSurfaces or Uncovered otherwise).
  • deferrable Subscriptions and Managed Resources: Any Subscription or Managed Resource active at boot on a deferred plan must be listed in deferrable (EagerStartRequired otherwise; Remote.resume(Data) declares its own entries automatically). Pass subscriptions and managedResources to SSR.render so the check sees them.
  • rh.KeepTyped() on deferred inputs: Inputs with named OnInput or OnChange handlers on a deferred plan must include rh.KeepTyped() (UnkeptField otherwise).
ts
const DeferredPost = SSR.plan(App, {
  id: 'post',
  state: Projection.pick(App.model.post),
  parts: [Remote.resume(Data)],
  start: 'idle',
  deferrable: ['tick'],
})

Bundles whose code loads on demand

List lazy foldkit-bundle modules (via Bundle.lazy) in your config's lazy option so both server render and browser boot load the chunks before adopting:

ts
const config = {
  Model,
  init: () => placements.init({ title: 'Uploads', upload }),
  update: placements.update(),
  view: (model: Model, h: HtmlBuilder<Message>) => {
    const rh = Resume.builder(h)
    return { title: model.title, body: rh.main([], [PlacedUpload.view(model, rh)]) }
  },
  container: null,
  subscriptions: placements.subscriptions(),
  lazy: [Upload],
}

For route-split apps, pass lazy: model => Routing.codeFor(model.route) and include the fields lazy reads in state (LazyDependsOnUnsentState otherwise). Inside a placement, list the parent wrapper Message on the plan's Surface.

Typing before the script arrives

Adding rh.KeepTyped() preserves text typed (or browser-restored) into an input, textarea, select, checkbox, or radio before hydration finishes:

ts
rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft), rh.KeepTyped()])
  1. While scripts load, the DOM element holds the typed value (requiring no inline script or CSP nonce).
  2. At SSR.hydrate, changed fields emit their OnInput (or OnChange / OnClick for radios and checkboxes) Message at the front of the boot queue.
  3. The first render adopts the served DOM, restores the typed value and caret position in the same task, and reduces the queued Message.

Only rh-built inputs with a named Message member accept rh.KeepTyped() (UnkeepableField otherwise). Any active IME composition ends on the first render while keeping its text.

The runtime on intent: foldkit-ssr/loader

Even with start: 'on-interaction', importing SSR.hydrate evaluates your app bundle at load time. Use the ~2 KB foldkit-ssr/loader entry script so the main bundle loads only when start triggers:

ts
// src/client/loader.ts
import { load } from 'foldkit-ssr/loader'

load({ runtime: () => import('./entry.js') }) // entry.ts calls SSR.hydrate

load reads start from the envelope: 'now' imports immediately; 'idle' waits for browser idle; 'on-interaction' waits for pointer, focus, key, or scroll intent on a marked element. Marked events are held (up to 3 seconds via UNTIL_LIMIT_MS) and passed to SSR.hydrate so they run once. Pair with runtimeChunk from foldkit-ssr/vite to emit <link rel="modulepreload"> for the deferred bundle:

ts
plugins: [foldkit({ ssr: { clientEntry: '/src/client/loader.ts' } }), runtimeChunk({ entry: '/src/client/entry.ts' })]