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 →
- MediaQueryWhether a CSS media query matches, kept in your Model.
PrefersDarkandPrefersReducedMotionare presets.bundle - BreakpointsThe window’s width and the named breakpoint it falls in, from a table you pass.bundle
- platformFromUAThe platform read from a user-agent string passed in, so a test pins it;
isBrowserandisServersay where the code runs.function
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 →
- OnlineWhether the browser reports a network connection.bundle
- websocketA WebSocket as a bundle: its status, the last error, and each message received or sent.bundle factory
- sseA server-sent events connection as a bundle: its status, the last error, and each message received.bundle factory
- broadcastMessagesMessages other tabs post on a named channel, as an entry;
postBroadcastis the Command that posts one.entry - SharedHostOne host for every tab: a SharedWorker serving a conversation per opening, or the page itself where there is no SharedWorker.function
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 →
- TimerA count of ticks at an interval, started and stopped by Messages.bundle
- IntervalTicks stamped with Effect’s clock, for a view that shows a clock or an elapsed time.bundle
- ticksA clock your Model drives: whether it runs and how fast are read from your Model, so no second running flag exists.entry
- debounceA value that settles after it stops changing for a delay, then reports once.bundle factory
- ThrottleLets an attempt through at most once per interval and reports when it did.bundle
- formatRelativeTimeRelative time as a function: picks the unit and leaves the wording to
Intl.RelativeTimeFormat.function
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 →
- PaginationThe current page, the page size and the total, with the steps between pages.bundle
- HistoryAn undo stack: past, present and future values, with push, undo, redo and a capacity.bundle factory
- LocaleThe reader’s locale, set by a Message.bundle
- SelectionSetWhich ids are selected: select, deselect, toggle, replace all, clear.bundle
- VirtualThe scroll, row heights and layout of a virtualized list, so the Model knows which rows to draw.bundle
- BoxBoxes that move and resize as pure functions: constraints, aspect ratio, a grid and keyboard steps.function
- rangeA numeric range as an array,
range(1, 4)is[1, 2, 3]: the pagination companion.function
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 →
- TweenA value moving from one number to another over a fixed time.bundle
- SpringA value that settles on a target by stiffness and damping.bundle
- PresenceShow and hide with a leave phase, so content can animate out before it is removed.bundle
- MotionWhether motion should be reduced, a service read when a transition starts; absent, motion is full.service
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.
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 →
- GeolocationThe device’s position: its status, the coordinates, and a denial the view can say.bundle
- mediaDevicesThe cameras and microphones present, refreshed when they change.bundle factory
- mediaStreamA live camera or microphone stream: started, stopped, denied or ended.bundle factory
- permissionsThe state of named permissions, watched as the browser changes them.bundle factory
- enterFullscreenFullscreen as Commands, with
fullscreenChangesreporting what the document says.Command
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 →
- VisibilityWhether the page is visible.bundle
- WindowSizeThe window’s width and height.bundle
- IdleWhether the reader has been inactive for a timeout.bundle
- InputModalityWhether the page is being driven by keyboard, mouse or touch.bundle
- keyboardEventsKey presses and releases, reported to your Message; the parent keeps whatever key state it wants.entry
- pointerEventsPointer moves, reported as positions.entry
- scrollEventsThe window’s scroll position, as it changes.entry
- activeElementEventsThe focused element’s tag and id, as focus moves.entry
- matchHotkeyMatches a key press against a hotkey pattern;
formatHotkeyandariaKeyshortcutswrite it for display and for assistive technology.function
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 →
- ResizeAn element’s content box size, reported as it changes.Mount
- IntersectionWhether an element crosses the viewport, and how much of it shows.Mount
- MutationChanges to an element’s subtree: nodes added or removed, attributes changed.Mount
- BoundsAn element’s rectangle, the current one first.Mount
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.
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.
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.
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 →
- copyTextCopies text to the clipboard, and
readTextreads it; each answers with a Message.Command - shareOpens the Web Share sheet; a dismissal is its own outcome, not a failure.Command
- loadScriptAppends a script to the head unless it is there, once per URL.Command
- decodeImageFetches and decodes an image before it is shown, so a switch never passes through a blank.Command
- AutofocusFocuses its element when it is drawn.Mount
- InputMaskFormats typed text by a pattern, reporting the masked value and the raw one.Mount
- KeepInViewScrolls what newly matches a selector, such as the row just selected, into view the least amount that shows it.Mount
- MeasureWrites where marked elements are to custom properties, with no Message and no Model, for a view to draw over them.Mount
- TrackBoxFollows one element by id and writes its box to custom properties.Mount
- FluidHoverWrites a moving highlight’s place to custom properties on its container, for a stylesheet to draw.Mount
- ScrollBarsOverlay scroll bars: marks the bars beside a scroller and writes their custom properties.Mount
- ScrollSettleHears a scroller come to rest and reports which item starts nearest its start: a snapping carousel reads it as the slide shown.Mount
- KeyboardInsetWrites how much of the layout viewport the on-screen keyboard covers to
--fk-keyboard-inset.Mount - FocusScopeContains focus within an element, and restores it on the way out.Mount
- FocusReturnReturns focus, when an overlay closes, to what had it before the overlay took it.Mount
- FocusRecoveryWhere focus goes, tried in order, when the part that had it is gone.Mount
- FollowTabStopKeeps focus inside a container of roving tab stops on its stop when a transition moves or removes it.Mount
- ScrollLockLocks the page’s scroll under an overlay;
HideOutsidehides the rest of the page from assistive technology.Mount - PointerPositionA pointer’s press, move and release as places in the element’s padding box, with pressure.Mount
- PointerDragA drag over marked items, reporting the zone of the item it is over.Mount
- DragPreviewShows a drag’s preview in the top layer, on an element with
popover="manual".Mount - MoveMoves a draggable element, reporting where it started, went and ended.Mount
- TargetsReports which marked descendant the pointer hovers or presses.Mount
- MarqueeA lasso over marked descendants, reporting the rectangle and what it touches.Mount
- SwipeA swipe on its element: where it started, and where it ended with the release velocity.Mount
- EditableTextText edited in place, reporting each edit, a commit and a cancel.Mount
- keepScrollKeeps the window’s scroll across an application’s own navigations.function
- pointedLinksThe address of the link a reader means to follow, once a pointer or focus has rested on it, for a preload.function
- visibleLinksThe address of each same-origin link that scrolls into view, for a preload; opt-in.function
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, () => ''),
],
),
})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 →
- PressPointer and keyboard activation of one element as one fact.bundle
- LongPressHolding an element down for a threshold is one fact.bundle
- RepeatA held stepper: one step on press, then another every interval while held.bundle
- SelectionWhich ids are selected, in single, multiple or range mode, and the anchor a range extends from.bundle
- RovingTabindexOne tab stop for a set of items: arrows move focus between them.bundle
- ListNavigationKeyboard navigation of a list: a roving tab stop, type to find, and PageUp and PageDown.bundle
- GridNavigationArrow keys over items laid out in rows of a number of columns.bundle
- SpatialNavigationArrow keys over freely placed items: each arrow moves to the nearest one that way.bundle
- TreeNavigationKeyboard navigation of a tree after the WAI-ARIA tree pattern: one tab stop, rows shown or folded.bundle
- TypeaheadPrintable keys build a query that a timer clears, and the query picks the item to move to.bundle
- ReorderMoving an item to another place in a list or tree, by keyboard and by pointer.bundle
- InlineEditEditing a value where it is shown: Enter or F2 starts, Enter saves, Escape puts it back.bundle
- SwipeActionsSwipe-to-reveal actions behind a row, with a way in that needs no pointer.bundle
- LiveAnnouncePolite and assertive announcements for assistive technology, debounced so a burst reads once.bundle
- DismissLayerDismissable layers: Escape closes the topmost, and a press outside closes the layers it is outside of.bundle
- PresenceDraws a phase the Model already holds: a leaving row is inert for the whole exit.Behavior
- FocusVisibleMarks the target while the page is driven by keyboard, so a stylesheet can show a ring only then.Behavior
- FocusScopeContains focus within a container slot.Behavior
- FocusRecoveryMarks an owner slot and its parts, and recovers focus when a part goes.Behavior
- LayersThe scroll lock and the hidden-outside set, wired as Behaviors to a container slot.Behavior
- MoveA draggable slot, mapping its drag facts into the view’s Messages.Behavior
- PointerDragA container slot whose marked items can be dragged over each other.Behavior
- MarqueeA lasso over the container’s marked descendants.Behavior
- TargetsReports which descendant of a container slot is hovered or pressed.Behavior
- EditableTextText edited in place, wired to a container slot.Behavior
- BundleBehaviorThe mixin half of a Bundle: a Behavior whose slots are wired to the Bundle’s Messages.Behavior
- OverlayOne overlay policy, modal or non-modal, instead of nine subtly different overlays.Behavior
- PlacingKeeps a floating panel inside the viewport: shifts it from an edge and flips it above its trigger.function
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.
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'}.`,
],
),
})