Primitives. Behaviour with no markup of its own.

A primitive here is headless state and behaviour for a Foldkit application: a media query, a timer, a roving tab stop, an undo stack. It keeps its fact in your Model, reports changes as Messages, and draws nothing, so your view draws it. A component in foldkit-mixins-ui is one of these dressed in markup and a recipe; reach for a primitive when the markup is yours. Read the guide for the model, or pick a family below.

Media

What the browser says about its surroundings: a media query, the viewport, the platform. foldkit-primitives/media guide →

Examples

PrefersDark

The site places PrefersDark once in its Model; the view reads model.dark.matches. Change your system’s scheme and the line follows.

Your system asks for a light color scheme.

export const prefersDarkExample = (model: Model, _slots: Slots, h: H): Html =>
  h.p([], [`Your system asks for a ${model.dark.matches ? 'dark' : 'light'} color scheme.`])

Breakpoints

Breakpoints reports the window’s width and the named breakpoint it falls in, from a table you pass. Resize the window.

0 pixels wide: phone.

import { Breakpoints } from 'foldkit-primitives/media'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// Mobile-first thresholds: the name is the largest whose width is at or below the window's.
export default primitiveExample({
  title: 'Breakpoints',
  text: '`Breakpoints` reports the window’s width and the named breakpoint it falls in, from a table you pass. Resize the window.',
  state: Breakpoints.with({ breakpoints: { phone: 0, tablet: 640, desktop: 1024 } }),
  view: ({ model, h }) =>
    h.p(
      [],
      [`${Math.round(model.width)} pixels wide: ${model.breakpoint ?? 'below every breakpoint'}.`],
    ),
})

MediaQuery

MediaQuery keeps whether a query matches, corrected as the browser changes it. This one asks for a pointer that can hover, which a phone has not.

You are on a touch screen.

import { MediaQuery } from 'foldkit-primitives/media'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// Any query the browser understands: the bundle keeps whether it matches now.
export default primitiveExample({
  title: 'MediaQuery',
  text: '`MediaQuery` keeps whether a query matches, corrected as the browser changes it. This one asks for a pointer that can hover, which a phone has not.',
  state: MediaQuery.with({ query: '(hover: hover) and (pointer: fine)' }),
  view: ({ model, h }) =>
    h.p([], [model.matches ? 'You have a mouse or trackpad.' : 'You are on a touch screen.']),
})

platformFromUA

platformFromUA names the platform from a user-agent string passed in. A test pins the answer by passing the string; the view calls it with a fixed one.

  • mac from “Mozilla/5.0 (Macintosh; Inte…”
  • android from “Mozilla/5.0 (Linux; Android …”
  • windows from “Mozilla/5.0 (Windows NT 10.0…”
import { platformFromUA } from 'foldkit-primitives/media'
import { primitiveExample, stateless } from '../../../gallery/primitiveExample.js'

// Pure: pass a user-agent string and a test pins the answer; the view reads where it runs.
export default primitiveExample({
  title: 'platformFromUA',
  text: '`platformFromUA` names the platform from a user-agent string passed in. A test pins the answer by passing the string; the view calls it with a fixed one.',
  state: stateless,
  view: ({ h }) =>
    h.ul(
      [],
      [
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)',
        'Mozilla/5.0 (Linux; Android 14; Pixel 8)',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
      ].map(agent => h.li([], [`${platformFromUA(agent)} from “${agent.slice(0, 28)}…”`])),
    ),
})

Network

What the network reported last: online or not, a socket, an event stream, a post from another tab. foldkit-primitives/net guide →

Examples

Online

Online keeps online in the Model, from the window’s online and offline events. Switch your network off and on to watch it.

Online.

export const onlineExample = (model: Model, _slots: Slots, h: H): Html =>
  h.p([], [model.online.online ? 'Online.' : 'Offline: the browser reports no connection.'])

broadcastMessages and postBroadcast

postBroadcast is a Command that posts to a named channel; broadcastMessages is an entry that reports what other tabs post. Press here with this page open in a second tab.

Heard nothing yet.

import { Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { BroadcastMessage, broadcastMessages, postBroadcast } from 'foldkit-primitives/net'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({ heard: Schema.Array(Schema.String) })
const Message = defineMessageUnion({
  Said: { text: Schema.String },
  Received: { data: Schema.Unknown },
  Posted: {},
  BroadcastFailed: { message: Schema.String },
})

// Open this page in a second tab and press: every other tab on the channel hears it, the poster does not.
export default primitiveExample({
  title: 'broadcastMessages and postBroadcast',
  text: '`postBroadcast` is a Command that posts to a named channel; `broadcastMessages` is an entry that reports what other tabs post. Press here with this page open in a second tab.',
  state: {
    Model,
    Message,
    init: () => ({ model: { heard: [] } }),
    update: (model, message) =>
      Message.match(message, {
        Said: ({ text }) => ({ model, commands: [postBroadcast('primitives-example', text)] }),
        Received: ({ data }) => ({ model: { heard: [...model.heard, String(data)].slice(-3) } }),
        Posted: () => ({ model }),
        BroadcastFailed: () => ({ model }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(() => ({
      channel: Subscription.persistentEntry(
        broadcastMessages('primitives-example').pipe(
          Stream.filter(event => event._tag === 'Received'),
          Stream.map(({ data }) => Message.Received({ data })),
        ),
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(onMessage(Message.Said({ text: 'hello from another tab' }))),
          ]),
          ['Say hello to other tabs'],
        ),
        model.heard.length === 0 ? ' Heard nothing yet.' : ` Heard: ${model.heard.join('; ')}.`,
      ],
    ),
})

Time

What the clock said last: a count of ticks, when the last one was, a value that settled after typing stopped. foldkit-primitives/time guide →

Examples

Timer

A Timer placed with { intervalMs: 1000 } starts stopped; Started and Stopped are Messages, and only Ticked advances the count.

0 ticks, one a second.

export const timerExample = (model: Model, slots: Slots, h: H): Html =>
  h.p(
    [],
    [
      `${model.ticks.count} ${model.ticks.count === 1 ? 'tick' : 'ticks'}, one a second. `,
      h.button(
        slots.liveButton.attrs([
          h.Type('button'),
          h.OnClick(
            Message.GotTicksMessage({
              message: model.ticks.running ? TimerMessage.Stopped() : TimerMessage.Started(),
            }),
          ),
        ]),
        [model.ticks.running ? 'Stop' : 'Start'],
      ),
    ],
  )

Debounce

debounce makes a bundle whose Changed Message restarts a timer; only the last value is reported, once, as its OutMessage.

Settled on “”, after the typing stopped.

import { Schema } from 'effect'
import { Bundle } from 'foldkit-bundle'
import { debounce } from 'foldkit-primitives/time'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Typed = debounce({ name: 'Typed', value: Schema.String })

// `Changed` on every keystroke; `Typed.Debounced` leaves the bundle once, 500ms after the last.
const App = Bundle.compose({ settled: Schema.String }).pipe(
  Bundle.withChild('typed', Typed, {
    args: { delayMs: 500 },
    onOut: out => model => ({ model: { ...model, settled: out.value } }),
  }),
)

export default primitiveExample({
  title: 'Debounce',
  text: '`debounce` makes a bundle whose `Changed` Message restarts a timer; only the last value is reported, once, as its OutMessage.',
  state: App.placements.runtime({ Model: App.Model, initial: { settled: '' } }),
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.input(
          slots.liveField.attrs([
            h.Type('text'),
            h.AriaLabel('Search'),
            h.OnInput(value =>
              onMessage(App.Message.GotTypedMessage({ message: Typed.Message.Changed({ value }) })),
            ),
          ]),
        ),
        h.p([], [`Settled on “${model.settled}”, after the typing stopped.`]),
      ],
    ),
})

Interval

Interval stamps each tick with the time. The clock below runs while it is started and stops with the bundle.

Not started.

import { Interval, IntervalMessage } from 'foldkit-primitives/time'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// Each tick carries Effect's clock, so the view shows a time without reading one.
export default primitiveExample({
  title: 'Interval',
  text: '`Interval` stamps each tick with the time. The clock below runs while it is started and stops with the bundle.',
  state: Interval.with({ intervalMs: 1000 }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        model.lastAt === null
          ? 'Not started. '
          : `${new Date(model.lastAt).toISOString().slice(11, 19)} UTC `,
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(
              onMessage(model.running ? IntervalMessage.Stopped() : IntervalMessage.Started()),
            ),
          ]),
          [model.running ? 'Stop' : 'Start'],
        ),
      ],
    ),
})

formatRelativeTime

formatRelativeTime(from, to) picks the unit and leaves the wording to Intl.RelativeTimeFormat. Choose how long ago.

It was 2 hours ago.

import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { formatRelativeTime } from 'foldkit-primitives/time'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = defineMessageUnion({ Picked: { minutes: Schema.Number } })

// A function, not a bundle: the Model keeps the date, the view formats it.
export default primitiveExample({
  title: 'formatRelativeTime',
  text: '`formatRelativeTime(from, to)` picks the unit and leaves the wording to `Intl.RelativeTimeFormat`. Choose how long ago.',
  state: {
    Model: Schema.Struct({ minutes: Schema.Number }),
    Message,
    init: () => ({ model: { minutes: 90 } }),
    update: (model, message) =>
      Message.match(message, { Picked: ({ minutes }) => ({ model: { ...model, minutes } }) }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        ...[5, 90, 3000, 60_000].map(minutes =>
          h.button(
            slots.liveButton.attrs([
              h.Type('button'),
              h.AriaPressed(String(model.minutes === minutes)),
              h.OnClick(onMessage(Message.Picked({ minutes }))),
            ]),
            [`${minutes} min`],
          ),
        ),
        ` It was ${formatRelativeTime(new Date(Date.now() - model.minutes * 60_000), new Date())}.`,
      ],
    ),
})

Throttle

Throttle lets an attempt through at most once per interval. Press as fast as you like: the count rises once a second at most.

0 let through.

import { Schema } from 'effect'
import { Bundle } from 'foldkit-bundle'
import { Throttle, ThrottleMessage } from 'foldkit-primitives/time'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `Attempted` asks; the bundle reads Effect's clock and reports `Throttled` only when a
// second has passed since the last one let through.
const App = Bundle.compose({ passed: Schema.Number }).pipe(
  Bundle.withChild('gate', Throttle, {
    args: { intervalMs: 1000 },
    onOut: () => model => ({ model: { ...model, passed: model.passed + 1 } }),
  }),
)

export default primitiveExample({
  title: 'Throttle',
  text: '`Throttle` lets an attempt through at most once per interval. Press as fast as you like: the count rises once a second at most.',
  state: App.placements.runtime({ Model: App.Model, initial: { passed: 0 } }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(
              onMessage(App.Message.GotGateMessage({ message: ThrottleMessage.Attempted() })),
            ),
          ]),
          ['Press quickly'],
        ),
        ` ${model.passed} let through.`,
      ],
    ),
})

State

Application state with nowhere else to live: the page, the undo stack, the locale, a selection, a window of rows. foldkit-primitives/state guide →

Examples

History

An undo stack as a bundle. Each keystroke is a Push in the group typing, so a run of typing is one step to undo.

0 to undo, 0 to redo.

export const historyExample = (model: Model, slots: Slots, h: H): Html =>
  h.div(
    [],
    [
      h.input(
        slots.liveField.attrs([
          h.Type('text'),
          h.AriaLabel('Note'),
          h.Value(model.note.present),
          h.OnInput(value =>
            Message.GotNoteMessage({
              message: NoteHistory.Message.Push({ value, group: 'typing' }),
            }),
          ),
        ]),
      ),
      h.button(
        slots.liveButton.attrs([
          h.Type('button'),
          h.Disabled(model.note.past.length === 0),
          h.OnClick(Message.GotNoteMessage({ message: NoteHistory.Message.Undo() })),
        ]),
        ['Undo'],
      ),
      h.button(
        slots.liveButton.attrs([
          h.Type('button'),
          h.Disabled(model.note.future.length === 0),
          h.OnClick(Message.GotNoteMessage({ message: NoteHistory.Message.Redo() })),
        ]),
        ['Redo'],
      ),
      h.p([], [`${model.note.past.length} to undo, ${model.note.future.length} to redo.`]),
    ],
  )

Locale

Locale is the reader’s locale in the Model, set by a Message. It starts from navigator.language in the browser.

November 18, 2026, 1,234,567.5

import { Locale, LocaleMessage } from 'foldkit-primitives/state'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const LOCALES = ['en-US', 'de-DE', 'ja-JP']

// The Model holds a locale tag; every formatter in the view reads it from there.
export default primitiveExample({
  title: 'Locale',
  text: '`Locale` is the reader’s locale in the Model, set by a Message. It starts from `navigator.language` in the browser.',
  state: Locale.with({ default: 'en-US' }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        ...LOCALES.map(locale =>
          h.button(
            slots.liveButton.attrs([
              h.Type('button'),
              h.AriaPressed(String(model.locale === locale)),
              h.OnClick(onMessage(LocaleMessage.SetLocale({ locale }))),
            ]),
            [locale],
          ),
        ),
        ` ${new Date(Date.UTC(2026, 10, 18)).toLocaleDateString(model.locale, { timeZone: 'UTC', dateStyle: 'long' })}, ${(1234567.5).toLocaleString(model.locale)}`,
      ],
    ),
})

Pagination

Pagination holds the page, the page size and the total, and clamps every step into range. offset and pageCount read it.

Rows 1 to 10, page 1 of 10

import { Pagination, PaginationMessage, offset, pageCount } from 'foldkit-primitives/state'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// The bundle owns the page and the steps between pages; the rows are the application's.
export default primitiveExample({
  title: 'Pagination',
  text: '`Pagination` holds the page, the page size and the total, and clamps every step into range. `offset` and `pageCount` read it.',
  state: Pagination.with({ perPage: 10, total: 95 }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.Disabled(model.page === 1),
            h.OnClick(onMessage(PaginationMessage.PrevPage())),
          ]),
          ['Previous'],
        ),
        ` Rows ${offset(model) + 1} to ${Math.min(offset(model) + model.perPage, model.total ?? 0)}, page ${model.page} of ${pageCount(model)} `,
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.Disabled(model.page === pageCount(model)),
            h.OnClick(onMessage(PaginationMessage.NextPage())),
          ]),
          ['Next'],
        ),
      ],
    ),
})

SelectionSet

SelectionSet keeps the ids chosen. Toggle flips one, ReplaceAll and Clear change them together.

0 chosen.

import { SelectionSet, SelectionSetMessage, isSelected } from 'foldkit-primitives/state'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const FRUIT = ['Apple', 'Pear', 'Plum']

// Which ids are chosen is the bundle's; what a choice looks like is the view's.
export default primitiveExample({
  title: 'SelectionSet',
  text: '`SelectionSet` keeps the ids chosen. `Toggle` flips one, `ReplaceAll` and `Clear` change them together.',
  state: SelectionSet,
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        ...FRUIT.map(id =>
          h.button(
            slots.liveButton.attrs([
              h.Type('button'),
              h.AriaPressed(String(isSelected(model, id))),
              h.OnClick(onMessage(SelectionSetMessage.Toggle({ id }))),
            ]),
            [id],
          ),
        ),
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(onMessage(SelectionSetMessage.Clear())),
          ]),
          ['Clear'],
        ),
        ` ${model.selected.length} chosen.`,
      ],
    ),
})

Motion

Where an animation is, as a number in the Model: a tween, a spring, a mount that leaves before it is removed. foldkit-primitives/motion guide →

Examples

Tween

A number animated from 0 to 100 over 1.5 seconds on Effect’s clock. The view only reads model.fade.value; under reduced motion it jumps to the end.

export const tweenExample = (model: Model, slots: Slots, h: H): Html =>
  h.div(
    [],
    [
      h.div(slots.liveBar.attrs([h.Style({ '--filled': `${model.fade.value}%` })]), []),
      h.button(
        slots.liveButton.attrs([
          h.Type('button'),
          h.OnClick(Message.GotFadeMessage({ message: TweenMessage.Started() })),
        ]),
        [model.fade.running ? 'Running' : 'Run'],
      ),
    ],
  )

Presence

Presence shows and hides with a leave phase: after Hide the phase is hiding for the duration, then hidden. The box fades in that gap and is removed after it.

import { Presence, PresenceMessage, isVisible } from 'foldkit-primitives/motion'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `hiding` keeps the node drawn for `durationMs`, so a transition can run before it is removed.
export default primitiveExample({
  title: 'Presence',
  text: '`Presence` shows and hides with a leave phase: after `Hide` the phase is `hiding` for the duration, then `hidden`. The box fades in that gap and is removed after it.',
  state: Presence.with({ durationMs: 300 }),
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(
              onMessage(model.phase === 'shown' ? PresenceMessage.Hide() : PresenceMessage.Show()),
            ),
          ]),
          [model.phase === 'shown' ? 'Hide' : 'Show'],
        ),
        ...(isVisible(model)
          ? [
              h.div(
                slots.liveBox.attrs([
                  h.Style({
                    opacity: model.phase === 'hiding' ? '0' : '1',
                    transition: 'opacity 300ms',
                  }),
                ]),
                [`Phase: ${model.phase}.`],
              ),
            ]
          : []),
      ],
    ),
})

Spring

Spring settles a number on its target by stiffness and damping, so it can overshoot where a Tween cannot. The view reads value.

0
import { Spring, SpringMessage } from 'foldkit-primitives/motion'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// A target by stiffness and damping, stepped every 16ms on Effect's clock while running.
export default primitiveExample({
  title: 'Spring',
  text: '`Spring` settles a number on its target by stiffness and damping, so it can overshoot where a `Tween` cannot. The view reads `value`.',
  state: Spring.with({ from: 0, to: 100, stiffness: 120, damping: 8 }),
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.div(
          slots.liveBar.attrs([
            h.Style({ '--filled': `${Math.max(0, Math.min(100, model.value))}%` }),
          ]),
          [],
        ),
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(SpringMessage.Started()))]),
          [model.running ? 'Running' : 'Release'],
        ),
        ` ${Math.round(model.value)}`,
      ],
    ),
})

Device

What the hardware reported last: a position, cameras, a live stream, a permission, fullscreen. foldkit-primitives/device guide →

Examples

enterFullscreen and fullscreenChanges

enterFullscreen and exitFullscreen are Commands; fullscreenChanges reports what the document says, including a reader pressing Escape. A browser that refuses answers Failed.

import { Option, Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { enterFullscreen, exitFullscreen, fullscreenChanges } from 'foldkit-primitives/device'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({
  active: Schema.Boolean,
  failure: Schema.OptionFromNullOr(Schema.String),
})
const Message = defineMessageUnion({
  Toggled: {},
  Changed: { active: Schema.Boolean },
  Entered: {},
  Exited: {},
  Failed: { message: Schema.String },
})

export default primitiveExample({
  title: 'enterFullscreen and fullscreenChanges',
  text: '`enterFullscreen` and `exitFullscreen` are Commands; `fullscreenChanges` reports what the document says, including a reader pressing Escape. A browser that refuses answers `Failed`.',
  state: {
    Model,
    Message,
    init: () => ({ model: { active: false, failure: Option.none() } }),
    update: (model, message) =>
      Message.match(message, {
        Toggled: () => ({
          model,
          commands: [model.active ? exitFullscreen() : enterFullscreen(document.documentElement)],
        }),
        Changed: ({ active }) => ({ model: { ...model, active } }),
        Entered: () => ({ model: { ...model, failure: Option.none() } }),
        Exited: () => ({ model }),
        Failed: ({ message }) => ({ model: { ...model, failure: Option.some(message) } }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(() => ({
      changes: Subscription.persistentEntry(
        fullscreenChanges().pipe(
          Stream.filter(event => event._tag === 'Changed'),
          Stream.map(({ active }) => Message.Changed({ active })),
        ),
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(Message.Toggled()))]),
          [model.active ? 'Leave fullscreen' : 'Go fullscreen'],
        ),
        Option.match(model.failure, {
          onNone: () => '',
          onSome: message => ` Not possible here: ${message}.`,
        }),
      ],
    ),
})

Geolocation

Geolocation watches the device position while placed. Here it is placed behind a press, so the browser asks only then; a denial is its own status.

import { Option, Schema } from 'effect'
import { Bundle } from 'foldkit-bundle'
import { Geolocation } from 'foldkit-primitives/device'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `when` gates the placement's watch: nothing asks the browser for a position until the press.
const App = Bundle.compose({ asked: Schema.Boolean }).pipe(
  Bundle.withMessages({ Asked: {} }),
  Bundle.withChild('here', Geolocation, { when: model => model.asked }),
)

export default primitiveExample({
  title: 'Geolocation',
  text: '`Geolocation` watches the device position while placed. Here it is placed behind a press, so the browser asks only then; a denial is its own status.',
  state: App.placements.runtime({
    Model: App.Model,
    initial: { asked: false },
    update: App.placements.update(model => ({ model: { ...model, asked: true } })),
  }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        model.asked
          ? model.here.status === 'denied'
            ? 'Permission was denied. Allow it in the site settings to try again.'
            : Option.match(model.here.coords, {
                onNone: () => 'Asking for a position…',
                onSome: ({ latitude, longitude }) =>
                  `Near ${latitude.toFixed(1)}, ${longitude.toFixed(1)}.`,
              })
          : h.button(
              slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(App.Message.Asked()))]),
              ['Where am I?'],
            ),
      ],
    ),
})

mediaDevices

mediaDevices lists the cameras and microphones present and rescans when one is plugged in or out. Listing asks for no permission, so labels stay empty until the page has used a device.

Not scanned yet.

import { mediaDevices, MediaDevicesMessage } from 'foldkit-primitives/device'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Devices = mediaDevices({ name: 'Devices' })

// `init` scans at once; a served page cannot run a Command, so the scan is a press instead.
export default primitiveExample({
  title: 'mediaDevices',
  text: '`mediaDevices` lists the cameras and microphones present and rescans when one is plugged in or out. Listing asks for no permission, so labels stay empty until the page has used a device.',
  state: {
    Model: Devices.Model,
    Message: Devices.Message,
    init: () => ({ model: Devices.init().model }),
    update: (model, message) => Devices.update(model, message),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(onMessage(MediaDevicesMessage.Scan())),
          ]),
          ['Look for devices'],
        ),
        model.status === 'ready'
          ? ` ${model.devices.filter(device => device.kind === 'videoinput').length} cameras, ${model.devices.filter(device => device.kind === 'audioinput').length} microphones.`
          : model.status === 'denied'
            ? ' The browser refused to list devices.'
            : ' Not scanned yet.',
      ],
    ),
})

Events

Window-level events: visibility, size, idleness, input modality, keys, pointer, scroll and focus. foldkit-primitives/events guide →

Examples

WindowSize

WindowSize keeps the window’s width and height in the Model. Resize the window to watch it.

The window is 0 by 0 pixels.

export const windowSizeExample = (model: Model, _slots: Slots, h: H): Html =>
  h.p([], [`The window is ${model.windowSize.width} by ${model.windowSize.height} pixels.`])

activeElementEvents

activeElementEvents reports each element focus lands on. Listen, then Tab through this page.

Nothing focused yet.

import { Option, Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { activeElementEvents } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({
  listening: Schema.Boolean,
  focused: Schema.OptionFromNullOr(Schema.String),
})
const Message = defineMessageUnion({
  Listened: { on: Schema.Boolean },
  Focused: { tag: Schema.String },
})

export default primitiveExample({
  title: 'activeElementEvents',
  text: '`activeElementEvents` reports each element focus lands on. Listen, then Tab through this page.',
  state: {
    Model,
    Message,
    init: () => ({ model: { listening: false, focused: Option.none() } }),
    update: (model, message) =>
      Message.match(message, {
        Listened: ({ on }) => ({ model: { ...model, listening: on } }),
        Focused: ({ tag }) => ({ model: { ...model, focused: Option.some(tag) } }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(entry => ({
      focus: entry(
        { listening: Schema.Boolean },
        {
          modelToDependencies: model => ({ listening: model.listening }),
          dependenciesToStream: ({ listening }) =>
            listening
              ? activeElementEvents().pipe(Stream.map(({ tag }) => Message.Focused({ tag })))
              : Stream.empty,
        },
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.AriaPressed(String(model.listening)),
            h.OnClick(onMessage(Message.Listened({ on: !model.listening }))),
          ]),
          [model.listening ? 'Stop' : 'Watch focus'],
        ),
        Option.match(model.focused, {
          onNone: () => ' Nothing focused yet.',
          onSome: tag => ` Focus is on a ${tag.toLowerCase()}.`,
        }),
      ],
    ),
})

Idle

Idle keeps whether the reader has been inactive for a timeout. Leave the page alone for five seconds, then move the pointer.

Active: five seconds from idle.

import { Idle } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// Mouse, keys, presses and scrolls count as activity; five quiet seconds is idle.
export default primitiveExample({
  title: 'Idle',
  text: '`Idle` keeps whether the reader has been inactive for a timeout. Leave the page alone for five seconds, then move the pointer.',
  state: Idle.with({ timeoutMs: 5000 }),
  view: ({ model, h }) =>
    h.p([], [model.idle ? 'Idle: nothing for five seconds.' : 'Active: five seconds from idle.']),
})

InputModality

InputModality keeps whether the page is being driven by keyboard or pointer. Press a key, then press the page.

No input yet.

import { InputModality } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// What the last input was, so a view can show focus rings for keys and none for presses.
export default primitiveExample({
  title: 'InputModality',
  text: '`InputModality` keeps whether the page is being driven by keyboard or pointer. Press a key, then press the page.',
  state: InputModality,
  view: ({ model, h }) =>
    h.p(
      [],
      [
        model.modality === 'unknown'
          ? 'No input yet.'
          : `The last input was ${model.modality === 'keyboard' ? 'a key' : 'a press'}.`,
      ],
    ),
})

keyboardEvents and matchHotkey

keyboardEvents is a stream of presses, lifted into a Subscription that runs while you listen; matchHotkey tests each against a pattern. Listen, then press Control or Command with S.

Saved 0 times.

import { Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { keyboardEvents, matchHotkey } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({ listening: Schema.Boolean, saved: Schema.Number })
const Message = defineMessageUnion({ Listened: { on: Schema.Boolean }, Saved: {} })

// The listener exists only while `listening`: the Subscription's dependency is the flag.
export default primitiveExample({
  title: 'keyboardEvents and matchHotkey',
  text: '`keyboardEvents` is a stream of presses, lifted into a Subscription that runs while you listen; `matchHotkey` tests each against a pattern. Listen, then press Control or Command with S.',
  state: {
    Model,
    Message,
    init: () => ({ model: { listening: false, saved: 0 } }),
    update: (model, message) =>
      Message.match(message, {
        Listened: ({ on }) => ({ model: { ...model, listening: on } }),
        Saved: () => ({ model: { ...model, saved: model.saved + 1 } }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(entry => ({
      keys: entry(
        { listening: Schema.Boolean },
        {
          modelToDependencies: model => ({ listening: model.listening }),
          dependenciesToStream: ({ listening }) =>
            listening
              ? keyboardEvents({ preventDefault: press => matchHotkey('mod+s', press) }).pipe(
                  Stream.filter(event => event._tag === 'Pressed' && matchHotkey('mod+s', event)),
                  Stream.map(() => Message.Saved()),
                )
              : Stream.empty,
        },
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.AriaPressed(String(model.listening)),
            h.OnClick(onMessage(Message.Listened({ on: !model.listening }))),
          ]),
          [model.listening ? 'Stop listening' : 'Listen to keys'],
        ),
        ` Saved ${model.saved} times.`,
      ],
    ),
})

pointerEvents

pointerEvents reports each move of the pointer. The stream is lifted into a Subscription that runs only while you listen.

0, 0

import { Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { pointerEvents } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({ listening: Schema.Boolean, x: Schema.Number, y: Schema.Number })
const Message = defineMessageUnion({
  Listened: { on: Schema.Boolean },
  Moved: { x: Schema.Number, y: Schema.Number },
})

export default primitiveExample({
  title: 'pointerEvents',
  text: '`pointerEvents` reports each move of the pointer. The stream is lifted into a Subscription that runs only while you listen.',
  state: {
    Model,
    Message,
    init: () => ({ model: { listening: false, x: 0, y: 0 } }),
    update: (model, message) =>
      Message.match(message, {
        Listened: ({ on }) => ({ model: { ...model, listening: on } }),
        Moved: ({ x, y }) => ({ model: { ...model, x, y } }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(entry => ({
      moves: entry(
        { listening: Schema.Boolean },
        {
          modelToDependencies: model => ({ listening: model.listening }),
          dependenciesToStream: ({ listening }) =>
            listening
              ? pointerEvents().pipe(Stream.map(({ x, y }) => Message.Moved({ x, y })))
              : Stream.empty,
        },
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.AriaPressed(String(model.listening)),
            h.OnClick(onMessage(Message.Listened({ on: !model.listening }))),
          ]),
          [model.listening ? 'Stop' : 'Follow the pointer'],
        ),
        ` ${Math.round(model.x)}, ${Math.round(model.y)}`,
      ],
    ),
})

scrollEvents

scrollEvents reports the window’s scroll position as it changes. The stream is lifted into a Subscription that runs only while you listen.

0, 0

import { Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { scrollEvents } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Model = Schema.Struct({ listening: Schema.Boolean, x: Schema.Number, y: Schema.Number })
const Message = defineMessageUnion({
  Listened: { on: Schema.Boolean },
  Scrolled: { x: Schema.Number, y: Schema.Number },
})

export default primitiveExample({
  title: 'scrollEvents',
  text: '`scrollEvents` reports the window’s scroll position as it changes. The stream is lifted into a Subscription that runs only while you listen.',
  state: {
    Model,
    Message,
    init: () => ({ model: { listening: false, x: 0, y: 0 } }),
    update: (model, message) =>
      Message.match(message, {
        Listened: ({ on }) => ({ model: { ...model, listening: on } }),
        Scrolled: ({ x, y }) => ({ model: { ...model, x, y } }),
      }),
    subscriptions: Subscription.make<typeof Model.Type, typeof Message.Type>()(entry => ({
      moves: entry(
        { listening: Schema.Boolean },
        {
          modelToDependencies: model => ({ listening: model.listening }),
          dependenciesToStream: ({ listening }) =>
            listening
              ? scrollEvents().pipe(Stream.map(({ x, y }) => Message.Scrolled({ x, y })))
              : Stream.empty,
        },
      ),
    })),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.AriaPressed(String(model.listening)),
            h.OnClick(onMessage(Message.Listened({ on: !model.listening }))),
          ]),
          [model.listening ? 'Stop' : 'Follow the scroll'],
        ),
        ` ${Math.round(model.x)}, ${Math.round(model.y)}`,
      ],
    ),
})

Visibility

Visibility keeps whether the page is visible. Switch to another tab and back: a page can pause work while it is hidden.

This tab is in front.

import { Visibility } from 'foldkit-primitives/events'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `Changed` arrives on `visibilitychange`: the Model knows when the tab was left.
export default primitiveExample({
  title: 'Visibility',
  text: '`Visibility` keeps whether the page is visible. Switch to another tab and back: a page can pause work while it is hidden.',
  state: Visibility,
  view: ({ model, h }) =>
    h.p([], [model.visible ? 'This tab is in front.' : 'This tab is hidden.']),
})

Observers

Element-scoped observation as Mounts: attach one with h.OnMount on the element it watches. foldkit-primitives/observers guide →

Examples

Resize

Resize() is a Mount: attached with h.OnMount to one element, it sends Resized with the content box as the element changes size. The box below can be resized by its corner.

Its content box is 0 by 0 pixels. Drag its corner.
export const resizeExample = (model: Model, slots: Slots, h: H): Html =>
  h.div(slots.liveBox.attrs([h.OnMount(Resize())]), [
    `Its content box is ${Math.round(model.observed.width)} by ${Math.round(model.observed.height)} pixels. Drag its corner.`,
  ])

Bounds

Bounds() is a Mount that reports an element’s rectangle, the current one first, and again when it resizes or the page scrolls. Scroll and watch y.

At 0, 0 in the window, 0 wide.
import { Schema } from 'effect'
import * as Mount from 'foldkit/mount'
import { Bounds, Measured } from 'foldkit-primitives/observers'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// The rectangle is re-measured as the box resizes and as the page scrolls, so its `y` moves.
export default primitiveExample({
  title: 'Bounds',
  text: '`Bounds()` is a Mount that reports an element’s rectangle, the current one first, and again when it resizes or the page scrolls. Scroll and watch `y`.',
  state: {
    Model: Schema.Struct({ x: Schema.Number, y: Schema.Number, width: Schema.Number }),
    Message: Measured,
    init: () => ({ model: { x: 0, y: 0, width: 0 } }),
    update: (_, { x, y, width }) => ({ model: { x, y, width } }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.div(slots.liveBox.attrs([h.OnMount(Mount.mapMessage(Bounds(), onMessage))]), [
      `At ${Math.round(model.x)}, ${Math.round(model.y)} in the window, ${Math.round(model.width)} wide.`,
    ]),
})

Intersection

Intersection() is a Mount on the element it watches. Scroll this page until the box below crosses the window’s edge.

Out of view.
import { Schema } from 'effect'
import * as Mount from 'foldkit/mount'
import { Intersection, IntersectionChanged } from 'foldkit-primitives/observers'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// The Mount's own Message is the example's: `isIntersecting` and `ratio`, as the observer says them.
export default primitiveExample({
  title: 'Intersection',
  text: '`Intersection()` is a Mount on the element it watches. Scroll this page until the box below crosses the window’s edge.',
  state: {
    Model: Schema.Struct({ shown: Schema.Boolean, ratio: Schema.Number }),
    Message: IntersectionChanged,
    init: () => ({ model: { shown: false, ratio: 0 } }),
    update: (model, { isIntersecting, ratio }) => ({ model: { shown: isIntersecting, ratio } }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.div(slots.liveBox.attrs([h.OnMount(Mount.mapMessage(Intersection(), onMessage))]), [
      model.shown ? `In view, ${Math.round(model.ratio * 100)} percent of it.` : 'Out of view.',
    ]),
})

Mutation

Mutation() reports changes to the subtree of the element it is on, with the names of the nodes added. Add an item: the observer, not the button, counts it.

  • Item 1

The observer has seen 0 nodes added.

import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Mount from 'foldkit/mount'
import { Mutation } from 'foldkit-primitives/observers'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = defineMessageUnion({ Added: {}, Observed: { added: Schema.Array(Schema.String) } })

// The button only adds an item to the Model; the count of changes is the observer's.
export default primitiveExample({
  title: 'Mutation',
  text: '`Mutation()` reports changes to the subtree of the element it is on, with the names of the nodes added. Add an item: the observer, not the button, counts it.',
  state: {
    Model: Schema.Struct({ items: Schema.Number, seen: Schema.Number }),
    Message,
    init: () => ({ model: { items: 1, seen: 0 } }),
    update: (model, message) =>
      Message.match(message, {
        Added: () => ({ model: { ...model, items: model.items + 1 } }),
        Observed: ({ added }) => ({ model: { ...model, seen: model.seen + added.length } }),
      }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(Message.Added()))]),
          ['Add an item'],
        ),
        h.ul(
          [
            h.OnMount(
              Mount.mapMessage(Mutation(), ({ added }) => onMessage(Message.Observed({ added }))),
            ),
          ],
          Array.from({ length: model.items }, (_, at) => h.li([], [`Item ${at + 1}`])),
        ),
        h.p([], [`The observer has seen ${model.seen} nodes added.`]),
      ],
    ),
})

DOM

Element Mounts that act while attached, and one-shot Commands that run once and report back. foldkit-primitives/dom guide →

Examples

Autofocus

Autofocus() is a Mount: attached with h.OnMount, it focuses its element as it is drawn and sends Focused. Show the field and type at once.

export const autofocusExample = (model: Model, slots: Slots, h: H): Html =>
  h.div(
    [],
    [
      h.button(
        slots.liveButton.attrs([
          h.Type('button'),
          h.AriaExpanded(model.switched),
          h.OnClick(Message.ToggledSwitch({ on: !model.switched })),
        ]),
        [model.switched ? 'Hide the field' : 'Show a field'],
      ),
      ...(model.switched
        ? [
            h.input(
              slots.liveField.attrs([h.Type('text'), h.AriaLabel('Name'), h.OnMount(Autofocus())]),
            ),
          ]
        : []),
    ],
  )

copyText

copyText is a Command, returned from update; the clipboard is not application state, so the answer is a Message and nothing is stored. Press, then paste somewhere.

import { Option, Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { copyText } from 'foldkit-primitives/dom'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `Copied` and `CopyFailed` are the Command's own Messages, named alike here so it needs no mapping.
const Message = defineMessageUnion({
  Pressed: {},
  Copied: {},
  CopyFailed: { message: Schema.String },
})

export default primitiveExample({
  title: 'copyText',
  text: '`copyText` is a Command, returned from `update`; the clipboard is not application state, so the answer is a Message and nothing is stored. Press, then paste somewhere.',
  state: {
    Model: Schema.Struct({ answer: Schema.OptionFromNullOr(Schema.String) }),
    Message,
    init: () => ({ model: { answer: Option.none() } }),
    update: (model, message) =>
      Message.match(message, {
        Pressed: () => ({ model, commands: [copyText('foldkit-primitives')] }),
        Copied: () => ({ model: { answer: Option.some('Copied.') } }),
        CopyFailed: ({ message }) => ({
          model: { answer: Option.some(`Not copied: ${message}.`) },
        }),
      }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(Message.Pressed()))]),
          ['Copy “foldkit-primitives”'],
        ),
        Option.getOrElse(model.answer, () => ''),
      ],
    ),
})

InputMask

InputMask is a Mount with a pattern: # takes a digit, anything else is written in once typing reaches it. Type a phone number.

Shown “”, typed 0 digits.

import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Mount from 'foldkit/mount'
import { InputMask } from 'foldkit-primitives/dom'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = defineMessageUnion({ Typed: { value: Schema.String, raw: Schema.String } })

// The Mount rewrites the field and keeps the caret; the Model keeps what it reported.
export default primitiveExample({
  title: 'InputMask',
  text: '`InputMask` is a Mount with a pattern: `#` takes a digit, anything else is written in once typing reaches it. Type a phone number.',
  state: {
    Model: Schema.Struct({ value: Schema.String, raw: Schema.String }),
    Message,
    init: () => ({ model: { value: '', raw: '' } }),
    update: (_, message) =>
      Message.match(message, { Typed: ({ value, raw }) => ({ model: { value, raw } }) }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.input(
          slots.liveField.attrs([
            h.Type('text'),
            h.AriaLabel('Phone'),
            h.Attribute('inputmode', 'numeric'),
            h.OnMount(
              Mount.mapMessage(InputMask({ pattern: '(###) ###-####' }), ({ value, raw }) =>
                onMessage(Message.Typed({ value, raw })),
              ),
            ),
          ]),
        ),
        h.p([], [`Shown “${model.value}”, typed ${model.raw.length} digits.`]),
      ],
    ),
})

loadScript

loadScript is a Command that adds a script tag once per address and answers when it has run. Press twice: the second answer comes from the first tag.

Answered 0 times.

import { Option, Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { loadScript } from 'foldkit-primitives/dom'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = defineMessageUnion({
  Pressed: {},
  Loaded: {},
  LoadFailed: { message: Schema.String },
})

// A data: URL stands in for a library's address; a second press shares the first's tag.
const SRC = 'data:text/javascript,void 0'

export default primitiveExample({
  title: 'loadScript',
  text: '`loadScript` is a Command that adds a script tag once per address and answers when it has run. Press twice: the second answer comes from the first tag.',
  state: {
    Model: Schema.Struct({ loads: Schema.Number, failure: Schema.OptionFromNullOr(Schema.String) }),
    Message,
    init: () => ({ model: { loads: 0, failure: Option.none() } }),
    update: (model, message) =>
      Message.match(message, {
        Pressed: () => ({ model, commands: [loadScript(SRC)] }),
        Loaded: () => ({ model: { loads: model.loads + 1, failure: Option.none() } }),
        LoadFailed: ({ message }) => ({ model: { ...model, failure: Option.some(message) } }),
      }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(Message.Pressed()))]),
          ['Load the script'],
        ),
        ` Answered ${model.loads} times.`,
        Option.getOrElse(model.failure, () => ''),
      ],
    ),
})

share

share opens the platform’s share sheet. Dismissing it is its own Message, not a failure; a browser without one answers ShareFailed.

import { Option, Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { share } from 'foldkit-primitives/dom'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = defineMessageUnion({
  Pressed: {},
  Shared: {},
  Dismissed: {},
  ShareFailed: { message: Schema.String },
})

// Where the platform has no share sheet the Command answers `ShareFailed`, and the view says so.
export default primitiveExample({
  title: 'share',
  text: '`share` opens the platform’s share sheet. Dismissing it is its own Message, not a failure; a browser without one answers `ShareFailed`.',
  state: {
    Model: Schema.Struct({ answer: Schema.OptionFromNullOr(Schema.String) }),
    Message,
    init: () => ({ model: { answer: Option.none() } }),
    update: (model, message) =>
      Message.match(message, {
        Pressed: () => ({
          model,
          commands: [share({ title: 'Foldkit Plus', url: 'https://foldkit-plus.pages.dev/' })],
        }),
        Shared: () => ({ model: { answer: Option.some('Shared.') } }),
        Dismissed: () => ({ model: { answer: Option.some('Dismissed.') } }),
        ShareFailed: ({ message }) => ({
          model: { answer: Option.some(`Cannot share here: ${message}.`) },
        }),
      }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([h.Type('button'), h.OnClick(onMessage(Message.Pressed()))]),
          ['Share this site'],
        ),
        Option.getOrElse(model.answer, () => ''),
      ],
    ),
})

Interaction

Keyboard, pointer and focus patterns whose state a view’s slots must reflect: a Bundle for the state and a Behavior for the slots. foldkit-primitives/interaction guide →

Examples

LiveAnnounce

LiveAnnounce holds the text of a polite and an assertive live region. A burst of announcements reads once, the last; the same text twice is made to read again. Press quickly.

import { LiveAnnounce } from 'foldkit-primitives/interaction'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// The regions are drawn in the page's first view and hidden by a rule; here they are visible, so you can read what a screen reader is told.
export default primitiveExample({
  title: 'LiveAnnounce',
  text: '`LiveAnnounce` holds the text of a polite and an assertive live region. A burst of announcements reads once, the last; the same text twice is made to read again. Press quickly.',
  state: LiveAnnounce.bundle.with({ debounceMs: 250, clearAfterMs: 4000 }),
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(
              onMessage(
                LiveAnnounce.Message.Announced({ message: 'Saved.', politeness: 'polite' }),
              ),
            ),
          ]),
          ['Announce “Saved.”'],
        ),
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(
              onMessage(
                LiveAnnounce.Message.Announced({
                  message: 'Connection lost.',
                  politeness: 'assertive',
                }),
              ),
            ),
          ]),
          ['Announce an alert'],
        ),
        LiveAnnounce.view(model, h),
      ],
    ),
})

Move

Move is a Mount that reports a pointer drag as MoveStarted, Moved with the distance from the press, and MoveEnded. Escape ends it as not completed, and the box goes back.

Drag me sideways
import { Match, Schema } from 'effect'
import * as Mount from 'foldkit/mount'
import { Move } from 'foldkit-primitives/interaction'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const Message = Schema.Union([Move.MoveStarted, Move.Moved, Move.MoveEnded])
const Model = Schema.Struct({ x: Schema.Number, dx: Schema.Number, dragging: Schema.Boolean })
const within = (x: number) => Math.max(0, Math.min(120, x))

// Deltas are from where the press began, so the Model keeps the resting position and the drag apart.
export default primitiveExample({
  title: 'Move',
  text: '`Move` is a Mount that reports a pointer drag as `MoveStarted`, `Moved` with the distance from the press, and `MoveEnded`. Escape ends it as not completed, and the box goes back.',
  state: {
    Model,
    Message,
    init: () => ({ model: { x: 0, dx: 0, dragging: false } }),
    update: (model, message) =>
      Match.valueTags(message, {
        MoveStarted: () => ({ model: { ...model, dragging: true } }),
        Moved: ({ deltaX }) => ({ model: { ...model, dx: deltaX } }),
        MoveEnded: ({ completed }) => ({
          model: { x: completed ? within(model.x + model.dx) : model.x, dx: 0, dragging: false },
        }),
      }),
  },
  view: ({ model, onMessage, slots, h }) =>
    h.div(
      slots.liveBox.attrs([
        h.Style({
          touchAction: 'none',
          cursor: 'grab',
          // physical: the box follows the pointer's x, which is the screen's
          transform: `translateX(${within(model.x + model.dx)}px)`,
        }),
        h.OnMount(Mount.mapMessage(Move.mount(), onMessage)),
      ]),
      [model.dragging ? 'Moving…' : 'Drag me sideways'],
    ),
})

Press

Press is a press as one fact: a mouse, a finger, Enter, Space or a screen reader’s click all end in one Pressed, and a touch’s ghost click is not counted twice. Try each.

Pressed 0 times.

import { Schema } from 'effect'
import * as Mount from 'foldkit/mount'
import { Bundle } from 'foldkit-bundle'
import { Press } from 'foldkit-primitives/interaction'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

// `events()` reports the element's pointer, key and click facts; the bundle turns them into one `Pressed`.
const App = Bundle.compose({ presses: Schema.Number }).pipe(
  Bundle.withChild('press', Press.bundle, {
    args: { clickSuppressionMs: 400 },
    onOut: () => model => ({ model: { ...model, presses: model.presses + 1 } }),
  }),
)

export default primitiveExample({
  title: 'Press',
  text: '`Press` is a press as one fact: a mouse, a finger, Enter, Space or a screen reader’s click all end in one `Pressed`, and a touch’s ghost click is not counted twice. Try each.',
  state: App.placements.runtime({ Model: App.Model, initial: { presses: 0 } }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.DataAttribute('pressed', String(model.press.pressed)),
            h.OnMount(
              Mount.mapMessage(Press.events(), message =>
                onMessage(App.Message.GotPressMessage({ message })),
              ),
            ),
          ]),
          [model.press.pressed ? 'Held' : 'Press me'],
        ),
        ` Pressed ${model.presses} times.`,
      ],
    ),
})

Selection

Selection keeps the selected ids, an anchor and the last range. Activated toggles one in multiple mode; Ranged extends from the anchor through the order you pass.

Nothing selected.

import { Selection } from 'foldkit-primitives/interaction'
import { primitiveExample } from '../../../gallery/primitiveExample.js'

const FRUIT = ['Apple', 'Pear', 'Plum', 'Quince']

// Plain activation toggles in `multiple` mode; `Ranged` (a Shift press) selects from the anchor.
export default primitiveExample({
  title: 'Selection',
  text: '`Selection` keeps the selected ids, an anchor and the last range. `Activated` toggles one in `multiple` mode; `Ranged` extends from the anchor through the order you pass.',
  state: Selection.bundle.with({ mode: 'multiple', allowEmpty: true }),
  view: ({ model, onMessage, slots, h }) =>
    h.p(
      [],
      [
        ...FRUIT.map(id =>
          h.button(
            slots.liveButton.attrs([
              h.Type('button'),
              h.AriaPressed(String(model.selected.includes(id))),
              h.OnClick(onMessage(Selection.Message.Activated({ id }))),
            ]),
            [id],
          ),
        ),
        h.button(
          slots.liveButton.attrs([
            h.Type('button'),
            h.OnClick(onMessage(Selection.Message.Ranged({ id: 'Quince', order: FRUIT }))),
          ]),
          ['Anchor to Quince'],
        ),
        ` ${model.selected.join(', ') || 'Nothing selected'}.`,
      ],
    ),
})