foldkit-primitives 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,80 +1,40 @@
1
1
  # `foldkit-primitives`
2
2
 
3
- Ready-made [`foldkit-bundle`](../bundle) primitives: media queries, breakpoints,
4
- presence, timers, intervals, debounce, tweens, springs, pagination, history,
5
- locales, selections, ranges, geolocation, cameras, permissions, sockets,
6
- broadcasts, observers, and clipboard. Most are ordinary bundles — Model,
7
- Message, init, update, and Subscriptions collected in one value — published
8
- under a tree-shakeable subpath, so an application pays only for the primitives
9
- it places. The exceptions keep their own form: entries are Subscription
10
- streams mapped to the parent's Message (keyboard, pointer, scroll); Mounts
11
- are element-scoped observation attached with `h.OnMount` (`Resize`,
12
- `Autofocus`); Commands are one-shot (`copyText`, `share`); pure helpers are
13
- functions (`range`, `formatRelativeTime`).
3
+ Ready-made pieces of browser, clock, device, and interaction state for a
4
+ Foldkit application: a media query, a timer, a socket, an undo stack, a roving
5
+ tab stop, a resize observer, a clipboard write. Each comes in the shape Foldkit
6
+ already has, so adding one adds no store, no hook, and no second reducer. The
7
+ fact lives in your Model, arrives as a Message, and replays like everything
8
+ else.
14
9
 
15
10
  ```ts
16
11
  import { MediaQuery } from 'foldkit-primitives/media'
17
12
  ```
18
13
 
19
- ## Which state belongs here?
14
+ > **The browser reports; the Model owns.** A primitive observes something and
15
+ > hands your `update` a Message. What your application keeps, and what it does
16
+ > about it, stays yours.
20
17
 
21
- A primitive belongs here when it is **reused across applications** and
22
- **stateful**: something observes it, something reacts to it, and replay sees
23
- the same transitions. That is exactly the bundle shape, which is why this
24
- package depends on `foldkit-bundle` and nothing else (besides peers). The one
25
- exception is `interaction`, whose Bundles ship with a `foldkit-mixins` Behavior
26
- that wires them to a view's slots; `foldkit-mixins` is an optional peer that
27
- only that subpath needs.
18
+ ## Which form a primitive takes
28
19
 
29
- | Kind | Form | Example |
30
- | --- | --- | --- |
31
- | Stateful + effectful | bundle | MediaQuery, Timer, WebSocket, Pagination |
32
- | Interaction state a view's slots must reflect | bundle + Behavior | RovingTabindex, Typeahead, ListNavigation, GridNavigation, Press |
33
- | Keyed collections of stateful items | bundle per key | uploads, sockets, timers (later) |
34
- | Stream source with a stored fact | bundle with one boolean/scalar slice | Online, Visibility, WindowSize |
35
- | Stream source only | Subscription entry, not a bundle | keyboard, pointer, scroll, broadcast |
36
- | Element-scoped observation | Mount, not a bundle | Resize, Intersection, Mutation, Autofocus |
37
- | One-shot actions | Command, not a bundle | clipboard copy, share, script load |
38
- | Derived data | pure function, not a bundle | range, relative time, platform |
39
-
40
- Choose by what you need to own. State that outlives the moment — a match,
41
- a count, a page, a position — wants a bundle: the Model keeps it, replay
42
- sees it. A stream you only react to wants an entry: map it into the
43
- parent's Message and keep nothing. Work bound to one element wants a
44
- Mount. Work that runs once and reports back wants a Command. A value
45
- computed from data you already have wants a pure function. When in doubt,
46
- start with the lighter form; promote to a bundle the day the state needs
47
- a name in the Model.
48
-
49
- A bundle holds no state and performs no I/O by itself. The parent Model owns
50
- the placed slice; the browser (or server, or clock) only reports facts as
51
- Messages. The same rule as everywhere else: observation is not ownership.
52
-
53
- A Message that changes nothing (a repeated resize, `Started` while running,
54
- a total that is already held) returns the Model it was given, and a
55
- placement then returns the parent unchanged. Foldkit renders only when the
56
- root Model changes identity, so such a Message renders nothing, and a
57
- `createLazy` view over a placed slice is skipped while the slice is the same.
58
-
59
- Solid developers will notice missing plumbing: there is no event bus
60
- because Messages are the bus, no memo because derivations are pure reads
61
- over the Model, and no reactive map or store because the Model holds plain
62
- data (Effect collections where mutation matters). None of it is missing by
63
- accident — one state machine leaves nowhere for a second one to live.
64
-
65
- ## The mental model
66
-
67
- ```text
68
- browser / clock / server ──facts as Messages──▶ update ──▶ Model slice
69
- ▲
70
- The parent Model owns the recorded fact; subscriptions report environment changes.
71
- ```
20
+ Every primitive is one of five things, chosen by what it has to own:
21
+
22
+ | It needs to own | Form | Joins the application by | Examples |
23
+ | --- | --- | --- | --- |
24
+ | A fact that outlives the moment: a match, a count, a page, a position | **bundle** | placing it in the parent, as a field and a wrapper Message | `MediaQuery`, `Timer`, `Pagination`, `websocket` |
25
+ | Interaction state a view's slots must reflect | **bundle + Behavior** | placing it, then attaching its Behavior to the view's slots | `RovingTabindex`, `Press`, `DismissLayer` |
26
+ | Nothing: a stream you react to | **entry** | lifting it into your Subscriptions, mapped to your Message | `keyboardEvents`, `ticks`, `broadcastMessages` |
27
+ | Nothing: observation bound to one element | **Mount** | attaching it in the view with `h.OnMount` | `Resize`, `Autofocus`, `KeepInView` |
28
+ | Nothing: work done once that reports back | **Command** | returning it from `update` | `copyText`, `share`, `enterFullscreen` |
29
+ | Nothing: a value computed from what you have | **function** | calling it | `range`, `matchHotkey`, `formatRelativeTime` |
30
+
31
+ The lighter form wins when in doubt. Promote to a bundle the day the state
32
+ needs a name in the Model.
72
33
 
73
- Initialization creates the Model slice; subscriptions observe ongoing facts and
74
- report Messages; `update` stores them. Defaults differ by primitive:
75
- MediaQuery starts at `false`, while Online, Visibility, and Locale read an
76
- available platform value during initialization. Missing browser APIs have
77
- primitive-specific fallbacks; do not infer readiness from an SSR default.
34
+ The one dependency is [`foldkit-bundle`](../bundle), whose placement
35
+ mechanism every bundle here uses. `interaction` additionally needs
36
+ [`foldkit-mixins`](../mixins), an optional peer, because its Behaviors write to
37
+ a view's slots.
78
38
 
79
39
  ## Install
80
40
 
@@ -82,32 +42,14 @@ primitive-specific fallbacks; do not infer readiness from an SSR default.
82
42
  pnpm add foldkit-primitives foldkit-bundle effect foldkit
83
43
  ```
84
44
 
85
- `effect` and `foldkit` are peer dependencies. Import per subpath —
86
- `foldkit-primitives/media`, `foldkit-primitives/net`, `foldkit-primitives/time`,
87
- `foldkit-primitives/state`, `foldkit-primitives/motion`, `foldkit-primitives/device`,
88
- `foldkit-primitives/events`, `foldkit-primitives/observers`, `foldkit-primitives/dom` —
89
- so bundlers drop the primitives you never import.
90
-
91
- ## Map of the package
92
-
93
- Each subpath is one concern, one import:
94
-
95
- - `media` — environment facts: MediaQuery (+presets), Breakpoints, platform
96
- - `net` — remote facts: Online, WebSocket, SSE, BroadcastChannel
97
- - `time` — clock facts: Timer, Interval, Debounce, Throttle, relative time
98
- - `state` — owned UI state: Pagination, History, Locale, SelectionSet, Virtual, range
99
- - `motion` — animation state: Tween, Spring, Presence
100
- - `interaction` — a Bundle (or Mount) and its `foldkit-mixins` Behavior: RovingTabindex, Typeahead, ListNavigation, GridNavigation, TreeNavigation, FocusScope, Press, LongPress, Move, Targets, PointerDrag, EditableText, FocusVisible, DismissLayer, ScrollLock, HideOutside, Selection, LiveAnnounce
101
- - `device` — hardware: Geolocation, MediaDevices, MediaStream, Permissions, Fullscreen
102
- - `events` — raw browser events: Visibility, WindowSize, Idle, InputModality, keyboard, pointer, scroll, focus
103
- - `observers` — element Mounts: Resize, Intersection, Mutation, Bounds
104
- - `dom` — element Mounts and one-shot Commands: Autofocus, FocusScope, KeepInView, Measure, Move, Targets, PointerDrag, EditableText, ScrollLock, HideOutside, InputMask, clipboard, share, script loading
45
+ `effect` and `foldkit` are peer dependencies. Import by subpath (`/media`,
46
+ `/net`, `/time`, `/state`, `/motion`, `/interaction`, `/device`, `/events`,
47
+ `/observers`, `/dom`) so a bundler drops what you never import.
105
48
 
106
49
  ## Sixty seconds: follow the color scheme
107
50
 
108
- **Place it in a parent.** `Bundle.compose` states the parent's own field and
109
- Message, and places the primitive under `dark`, with the wrapper Message
110
- `GotDarkMessage` by Foldkit's `Got<Field>Message` convention:
51
+ A bundle is placed in a parent, which gains a field for its state and a
52
+ wrapper Message for its transitions:
111
53
 
112
54
  ```ts
113
55
  import { Schema } from 'effect'
@@ -121,11 +63,7 @@ const Page = Bundle.compose({ theme: Schema.String }).pipe(
121
63
  )
122
64
  type Model = typeof Page.Model.Type
123
65
  type Message = typeof Page.Message.Type
124
- ```
125
-
126
- **Run it.** The parent's assembly derives the update and the Subscriptions:
127
66
 
128
- ```ts
129
67
  const { placements } = Page
130
68
 
131
69
  const config = placements.complete({
@@ -137,848 +75,142 @@ const config = placements.complete({
137
75
  })
138
76
  ```
139
77
 
140
- `update` routes `GotDarkMessage` to the bundle; `subscriptions` runs the
141
- `matchMedia` stream; `initial` starts `matches` at `false` and the stream
142
- corrects it on subscribe. None of these calls perform I/O: `compose` states
143
- the parent, `withChild` places the primitive with its config, and the
144
- assembly derives the folding and the streams. The browser is touched only
145
- when the runtime subscribes. The Solid equivalent this replaces:
146
-
147
- ```ts
148
- // solid-primitives: const dark = createMediaQuery('(prefers-color-scheme: dark)')
149
- // Here the fact lives in the Model: replay, DevTools, and time travel see it.
150
- ```
151
-
152
- ## Composing placements
153
-
154
- One assembly holds every placement: spread its update, init,
155
- subscriptions, and resources once per application, as above. Two
156
- placements of one bundle observe twice — share the field instead, so one
157
- stream feeds every reader. One assembly holds one socket, stream, or
158
- watch: resource tags are per module, and `assemble` refuses the second.
159
- Bundles whose settled value is the whole point (`Debounce`, `Throttle`)
160
- surface it as an OutMessage the placement handles with `onOut`, so the
161
- signal can never be dropped by omission. Entries lift with
162
- `Subscription.persistent`, mapping into the parent's Message; Mounts
163
- attach in views with `h.OnMount`.
164
-
165
- ## Media: `foldkit-primitives/media`
166
-
167
- > Reference: [`./media/README.md`](./media/README.md)
78
+ What each line does, and does not do:
168
79
 
169
- `MediaQuery` follows one CSS media query. Model `{ matches: boolean }`,
170
- one Message `Changed { matches }`, args `{ query: string }`. The stream emits
171
- the current value on subscribe, then every change; without `matchMedia` it is
172
- empty and the slice keeps its initial `false`.
80
+ - **`Bundle.compose(...).pipe(withChild('dark', MediaQuery, …))`** states the
81
+ parent: its own field `theme`, its own Message `ThemeSet`, and `MediaQuery`
82
+ under `dark`. The Model is `{ theme, dark: { matches } }`; the Message union
83
+ gains `GotDarkMessage`. Nothing runs.
84
+ - **`placements.initial({ theme: 'light' })`** gives the fields no placement
85
+ owns; `dark` starts at `{ matches: false }`.
86
+ - **`placements.update(own)`** routes `GotDarkMessage` to the bundle and
87
+ everything else to your own update.
88
+ - **`placements.subscriptions()`** is the `matchMedia` stream, lifted. The
89
+ browser is touched only when the runtime subscribes, which then corrects
90
+ `matches` at once.
91
+ - **`config`** is an ordinary Foldkit application config. Hand it to the
92
+ runtime.
173
93
 
174
- Bound presets place with no args:
94
+ The Solid line this replaces is `createMediaQuery('(prefers-color-scheme: dark)')`.
95
+ The difference is where the answer lives: in the Model, where replay,
96
+ DevTools, an agent, and a server render all see it.
175
97
 
176
- ```ts
177
- import { PrefersDark, PrefersReducedMotion } from 'foldkit-primitives/media'
178
-
179
- const Page = Bundle.compose({ theme: Schema.String }).pipe(Bundle.withChild('dark', PrefersDark))
180
- ```
98
+ ## The other three ways in
181
99
 
182
- `Breakpoints` derives names from one `resize` listener: args
183
- `{ breakpoints }` map names to mobile-first min-widths (finite — anything
184
- else is rejected at placement), Model
185
- `{ width, breakpoint }`, one Message `Changed { width }`. The breakpoint is
186
- the largest name at or below the width (ties break alphabetically); SSR
187
- starts at width 0 with `null`. Placing both `Breakpoints` and `WindowSize`
188
- doubles resize listeners — pick the one the view reads.
189
-
190
- `platformFromUA(ua, hints?)` reads `mac | windows | linux | android | ios | unknown`
191
- from a passed user-agent string (mobile checks first: Android contains
192
- "Linux", iPhones mention "Mac"); Client Hints `platform` wins when
193
- recognized, and a multi-touch Mac UA reads as iOS. `isBrowser()`/`isServer()` split SSR from
194
- client for init defaults.
195
-
196
- ## Net: `foldkit-primitives/net`
197
-
198
- > Reference: [`./net/README.md`](./net/README.md)
199
-
200
- `Online` keeps `online: boolean` in the Model, read from `navigator.onLine`
201
- at startup and kept current by the window's `online`/`offline` events. One
202
- Message `Changed { online }`, no args, no OutMessage. Without a window the
203
- stream is empty and the slice stays at its default, so SSR renders online.
204
-
205
- `sse({ name, createSource? })` is the one-directional sibling: the Model
206
- holds `{ url, status, lastError }`, the resource owns the EventSource, and a
207
- subscription streams its messages. No `send` — the server speaks, the Model
208
- listens. A `Failed` records the error but stays `connecting`: the browser
209
- reconnects dropped streams itself. Event payloads are always text per the
210
- SSE spec.
211
-
212
- `websocket({ name, createSocket? })` makes a duplex socket bundle: the Model
213
- holds `{ url, status, lastError }` with `status` moving
214
- closed → connecting → open. The resource owns the socket (one assembly holds
215
- one); `send` is a placed helper whose command writes through the resource tag
216
- and yields `Sent { data }` on dispatch, carrying what was sent, and
217
- `SendFailed` when no connection is open — a closed socket's `send` is a
218
- silent no-op per spec, so the bundle checks first. Args `{ url,
219
- connectTimeoutMs? }`: with a timeout, a socket still connecting when it runs
220
- out is closed and reported as `TimedOut` (status closed, `lastError` set);
221
- without one, an attempt waits as long as the browser does.
222
- Incoming `Received` notifies without storing: project the payload into your
223
- own field to keep it. `createSocket` defaults to the platform WebSocket, read
224
- lazily so tests substitute a double; the socket service rides the assembly
225
- into the application's resources, as `RemoteClient` does for Remote.
226
-
227
- `broadcastMessages(name)` is the entry form for cross-tab traffic: posts from
228
- other instances arrive as `Received { data }` (notify without storing, like
229
- SSE). No bundle — the channel owns no state, so the parent maps `Received`
230
- into its own Message and keeps what it stores. `postBroadcast(name, data)` is
231
- the one-shot Command, yielding `Posted` or `BroadcastFailed`. A post never
232
- echoes to its own channel, per spec; without the API the entry is empty and
233
- the Command fails, instead of throwing.
234
-
235
- ## Time: `foldkit-primitives/time`
236
-
237
- > Reference: [`./time/README.md`](./time/README.md)
238
-
239
- `Timer` counts ticks while running. Model `{ count, running }`, Messages
240
- `Started`/`Stopped`/`Ticked`, args `{ intervalMs }` (positive and finite —
241
- anything else is rejected at placement). The tick stream runs on
242
- Effect's clock, so tests advance it with TestClock instead of waiting; while
243
- stopped the stream is empty. The first tick comes one interval after
244
- `Started`. Restarting keeps the count; only `Ticked` advances it.
245
-
246
- `Interval` is the wall-clock sibling: Model `{ running, lastAt }`,
247
- `Ticked { at }` stamped from Effect's clock. `Timer` counts ticks,
248
- `Interval` records when — views render clocks and elapsed times from
249
- `lastAt`. Same args, same TestClock story, same silence while stopped.
250
-
251
- Both own their `running` flag, at an interval fixed where they are placed.
252
- When the parent's Model already decides whether the clock runs and how fast
253
- (a game's phase and its score), a second flag would be a second owner of that
254
- fact. `ticks` is the entry for that case: `intervalMs` reads the interval from
255
- the Model, `None` while stopped, and `onTick` makes the parent's Message with
256
- the tick's time:
100
+ **An entry**, lifted into your Subscriptions and mapped to your Message. The
101
+ parent keeps whatever it wants of the stream:
257
102
 
258
103
  ```ts
259
- import { Option } from 'effect'
104
+ import { Stream } from 'effect'
260
105
  import * as Subscription from 'foldkit/subscription'
261
- import { ticks } from 'foldkit-primitives/time'
262
-
263
- const subscriptions = Subscription.make<Game, GameMessage>()(() => ({
264
- clock: ticks({
265
- intervalMs: (game: Game) =>
266
- game.playing ? Option.some(Math.max(80, 150 - game.points)) : Option.none(),
267
- onTick: () => GameMessage.TickedClock(),
268
- }),
106
+ import { keyboardEvents } from 'foldkit-primitives/events'
107
+
108
+ const subscriptions = Subscription.make<GameModel, GameMessage>()(() => ({
109
+ keys: Subscription.persistent(
110
+ keyboardEvents({ preventDefault: press => press.key.startsWith('Arrow') }).pipe(
111
+ Stream.filter(event => event._tag === 'Pressed'),
112
+ Stream.map(({ key }) => GameMessage.PressedKey({ key })),
113
+ ),
114
+ ),
269
115
  }))
270
116
  ```
271
117
 
272
- A Model change that leaves the interval alone does nothing. A new interval
273
- applies from the next tick, without restarting the clock, so a game that
274
- speeds up keeps its rhythm instead of ticking at once; `None` stops it, and
275
- `Some` again starts afresh, one interval before the first tick. `Timer` and
276
- `Interval` are built on it.
277
-
278
- `debounce({ name, value })` is a factory over any value Schema (like
279
- `history`): `Changed` restarts a `{ delayMs }` timer, and only the latest
280
- value settles — as an OutMessage the placement must handle with `onOut`, so
281
- a settled query can never be dropped by omission. Each `Changed` bumps a
282
- generation the scheduled `Settled` carries; a superseded timer emits nothing.
283
-
284
- `Throttle` is the leading edge to Debounce's trailing one: the first
285
- `Attempted` in an `{ intervalMs }` window surfaces a `Throttled` OutMessage
286
- (`onOut`, likewise required), the rest are dropped. `Attempted` reads the
287
- clock through a Command, so the check runs on Effect time and tests drive
288
- it; the boundary counts as past (`>=`). Pair the two rather than adding a
289
- second timer.
290
-
291
- `formatRelativeTime(from, to, locale?)` picks the unit (seconds through
292
- years) and lets `Intl.RelativeTimeFormat` word it — locales come from the
293
- platform, not a phrase table. There is deliberately no `now` helper:
294
- `Clock.currentTimeMillis` already is it.
295
-
296
- ## Events: `foldkit-primitives/events`
297
-
298
- > Reference: [`./events/README.md`](./events/README.md)
299
-
300
- `Visibility` keeps `visible: boolean` in the Model, read from the document
301
- at startup (SSR assumes visible) and kept current by `visibilitychange`:
302
- one Message `Changed { visible }`, no args. A hidden page is the
303
- application's cue to pause polling and streams; the decision stays in
304
- application `update`, not here.
305
-
306
- `WindowSize` keeps raw `{ width, height }` in the Model, read from the
307
- window on subscribe and kept current by one `resize` listener. SSR starts
308
- at zero; teardown removes the listener.
309
-
310
- `Idle` keeps `idle: boolean` in the Model, args `{ timeoutMs }` (positive
311
- and finite). While active, activity (mouse, keys, pointer, scroll) debounced past the
312
- timeout settles to `BecameIdle`; while idle, the first activity wakes to
313
- `BecameActive` and the dependency flip restarts the watch. Starts active —
314
- a lurker idles when the silence elapses, because subscribe time seeds the
315
- debounce as last-known-alive.
316
-
317
- `keyboardEvents()`, `pointerEvents()`, `scrollEvents()`, and
318
- `activeElementEvents()` are entries, not bundles: the parent owns whatever
319
- key, cursor, scroll, or focus state it keeps. They report presses (with
320
- repeat and modifiers) and releases, moves `{ x, y }`, scroll positions, and
321
- focus `{ tag, id }` — elements cross as tag and id, never as live nodes.
322
- `matchHotkey("ctrl+shift+k", press)` answers whether a press is a shortcut,
323
- so `update` stays a table of chords; matching is exact and auto-repeat never
324
- matches. When the observed target itself depends on state, scope the entry
325
- through subscription dependencies and it restreams on change.
326
- `keyboardEvents({ preventDefault: press => ... })` cancels the default of the
327
- presses the predicate picks (the arrows scrolling a game's page,
328
- `matchHotkey('ctrl+s', press)`), decided in the listener, because a default
329
- can only be cancelled while the event is dispatching. Lift
330
- with `Subscription.persistent`, mapping into the parent's Message; without
331
- a window each stream is empty instead of throwing.
332
-
333
- ## Observers: `foldkit-primitives/observers`
334
-
335
- > Reference: [`./observers/README.md`](./observers/README.md)
336
-
337
- `Resize` and `Intersection` are Mounts, not bundles: element-scoped
338
- observation attaches in views, not Model slots. Attach `Resize()` (or
339
- `Intersection()`) with `h.OnMount` on the element. There are no ref objects
340
- to thread: a Mount receives its element directly, and views take the rest
341
- as plain arguments.
342
-
343
- `Resize()` reports `Resized { width, height }` from the element's content
344
- box; `Intersection()` reports `IntersectionChanged { isIntersecting, ratio }`
345
- on viewport crossings; `Mutation()` reports `Mutated { type, added, removed,
346
- attribute }` for child, attribute, and text changes across the whole subtree
347
- — nodes cross as names, never as live objects, and unknown record types are
348
- skipped. `Bounds()` re-measures `Measured { x, y, width, height }` on
349
- observer, scroll, and resize, starting with the current rect; without a
350
- ResizeObserver the window events still measure. Without the observer API
351
- (SSR, old browser) they emit nothing instead of throwing; teardown
352
- disconnects. Treat repeated measurements as observations, not proof that a user action occurred.
353
-
354
- ## Device: `foldkit-primitives/device`
355
-
356
- > Reference: [`./device/README.md`](./device/README.md)
357
-
358
- `Geolocation` watches the device position while placed. Model `{ status,
359
- coords, lastError }` with `status` unknown → ready; denial is its own status
360
- (actionable UI), transient failures keep the last fix and note the error.
361
- Permission code 1 maps to `Denied`, anything else to `Failed`. Without a
362
- geolocation API the stream is empty instead of throwing.
363
-
364
- `mediaDevices({ name, create? })` scans the device list on placement and
365
- re-scans on `Scan`, `DevicesChanged` (wired to `devicechange`), and every
366
- placement: `Refreshed { devices }` with `{ deviceId, groupId, kind, label }`.
367
- Denial lands as `denied` while keeping the last list; other failures keep the last list and
368
- note the error; an unknown `kind` fails the scan at the boundary instead of
369
- entering the Model.
370
-
371
- `mediaStream({ name, request? })` holds one live camera/mic stream in a
372
- Managed Resource while the Model asks for it (`requesting` or `live`).
373
- `Started` requests with the placed `{ audio, video }` constraints, `Stopped`
374
- and `Ended` release; denial parks at `denied`, any other failure parks at
375
- `idle` with the error — both clear requirements, so a failing device never
376
- spins an acquire loop. Release stops every track. The `LiveStream` tag and
377
- service are exported for commands that attach the stream to an element; one
378
- assembly holds one stream.
379
-
380
- `permissions({ name, create? })` queries `{ names }` on acquire and watches
381
- each status object's `onchange` through an ordered queue into a persistent
382
- subscription. `Snapshot` replaces the states map, `Changed` merges one,
383
- `Cleared` empties on release (which also detaches every handler). Unknown
384
- names and unknown state strings fail the acquire — never Model facts.
385
-
386
- `enterFullscreen(element)` / `exitFullscreen()` are Commands yielding
387
- `Entered`/`Exited` or `Failed` (rejected request, missing capability, with a
388
- legacy `webkit` fallback); `fullscreenChanges()` starts with the current
389
- answer then follows flips as `Changed { active }`. No Model: the document
390
- owns fullscreen state.
391
-
392
- ## DOM: `foldkit-primitives/dom`
393
-
394
- > Reference: [`./dom/README.md`](./dom/README.md)
395
-
396
- `copyText` copies text as a Command: use it in `update` beside any bundle.
397
- It yields `Copied` on success and `CopyFailed` otherwise — denial, insecure
398
- context, or no clipboard API (SSR) all become the failure Message instead of
399
- throwing. `readText()` reads it the same way, yielding a
400
- `ClipboardReadMessage`: `Read { text }`, or `ReadFailed` when the browser
401
- refuses. No Model involved: the clipboard is not
402
- application state.
403
-
404
- `share(data)` posts `{ title?, text?, url? }` to the platform sheet: `Shared`
405
- on success, `Dismissed` on sheet cancel (its own outcome, not a failure),
406
- `ShareFailed` otherwise. `loadScript(src)` appends a head script unless one
407
- carries the URL already — idempotent by URL, so concurrent placements
408
- collapse onto the first tag and share its fate — yielding `Loaded` or
409
- `LoadFailed`. A dead tag is removed, so a retry fetches afresh.
410
-
411
- `Autofocus()` focuses the element on insert, then emits `Focused` (requested,
412
- not landed: a non-focusable element may decline). `InputMask({ pattern })`
413
- masks a field against `#`/`A`/`*` placeholders with literal separators,
414
- rewrites the field with approximate caret restore, and emits
415
- `Input { value, raw }` with masked and unmasked text. The parent owns the
416
- state, like any controlled input.
417
-
418
- `KeepInView({ selector })` keeps what is marked in view: whenever an element in
419
- its subtree newly matches `selector` (the row just selected, the node just
420
- inserted), it is scrolled into view the least amount that shows it. It sends no
421
- Message and redraws nothing, so a focused row stays focused. Where there is no
422
- layout (jsdom), it scrolls nothing.
423
-
424
- `Measure({ targets: { selected: '[aria-selected="true"]' } })` measures, for
425
- each named target, the first element in its subtree that matches, relative to
426
- its scroll box, and writes `--fk-selected-x`, `-y`, `-w`, `-h` (pixels) and
427
- `--fk-selected-display` (`block`, or `none` while nothing matches) on the
428
- element (`measured('selected')` names them). A child placed absolutely from
429
- them, such as an editor's selection outline, sits over the target and scrolls
430
- with it. Where an element is, is presentation: it sends no Message and keeps
431
- nothing in the Model. It measures again when the subtree changes, as the
432
- records arrive, so the box moves in the frame the change is drawn in; and, at
433
- most once a frame, when the element scrolls, when it or a target changes size,
434
- when the window resizes, when an image or a font inside loads, and on each
435
- frame of a transition or an animation inside. Anything else that moves a
436
- target without resizing it (a stylesheet added) is seen at the next of these.
437
-
438
- ## State: `foldkit-primitives/state`
439
-
440
- > Reference: [`./state/README.md`](./state/README.md)
441
-
442
- `Pagination` keeps `{ page, perPage, total }` in the Model, with `total: null`
443
- while unknown. Every transition clamps into range: past the last page lands on
444
- it, below one lands on one, and a smaller total pulls the page back. New sizes
445
- and totals arrive as Messages (`SetPerPage` ignores a non-positive size, and
446
- `SetTotal` ignores a negative total).
447
- `pageCount` returns null while the total is unknown; `offset` gives the first
448
- item's index for a slice or a query. Loading data stays the application's job:
449
- this bundle owns the page, not the items.
450
-
451
- `history({ name, value, capacity })` makes an undo/redo bundle over any value
452
- Schema. The Model holds `{ past, present, future, group }`; `Push` records and
453
- drops the redo future (an empty future is kept as it was, so a view reading it
454
- is not drawn again per push), `Undo`/`Redo` move one step, `GoTo { step }`
455
- jumps to any kept value, counted from the oldest (0) so the present is at
456
- `past.length`, and `Clear` empties both sides while keeping the present. A `Push` may name a `group`: consecutive pushes of
457
- the same group are one step, so typing a word undoes as a whole, with no clock.
458
- The steps are also pure functions, `History.start`, `push`, `undo`, `redo`,
459
- `goTo` and `clear`, for a parent that records an edit in the same transition that makes it
460
- (the page Builder keeps its page this way). Two more are only functions:
461
- `History.close(model)` ends the group, so the same group pushed again is a step
462
- of its own, and `History.revert(model, group)` takes back the step `group` is
463
- making with nothing left to redo, which is what a cancelled edit leaves. The past holds at most `capacity` entries (default 100);
464
- a negative or fractional capacity throws at the factory, naming it. The
465
- factory attaches the Message union, so placements dispatch
466
- `EditHistory.Message.Push(...)`. `canUndo`/`canRedo` read the edges:
467
-
468
- ```ts
469
- import { history } from 'foldkit-primitives/state'
470
-
471
- const EditHistory = history({ name: 'EditHistory', value: Schema.String, capacity: 50 })
472
- const Doc = Bundle.declare(EditHistory, 'doc')
473
- ```
474
-
475
- `Locale` keeps one string in the Model, read from `navigator.language` at
476
- startup with the configured `default` as fallback; `SetLocale` switches it.
477
- `SelectionSet` keeps string ids in first-selection order: `Select` (keeps
478
- position), `Deselect`, `Toggle` (re-appends), `ReplaceAll` (deduped), and
479
- `Clear`. `isSelected` reads membership. Neither subscribes to changes; Locale reads the initial browser language when available.
480
- Keyed children — lists with stable identity — place through the bundle
481
- mechanism's `each`.
482
- `range(start, end, step?)` counts half-open numbers — the pagination page
483
- list is `range(1, (pageCount(model) ?? 0) + 1)`; a zero or non-finite step
484
- throws, naming it.
485
-
486
- `Virtual` owns a virtualized list's scroll position, measured heights, and
487
- layout: Model `{ scrollTop, heights, scrolling, generation, estimatedHeight,
488
- overscan, gap, paddingStart, paddingEnd }`, Messages
489
- `Scrolled`/`Measured`/`Prune`/`Settled`, args for the layout plus optional
490
- `initialScrollTop`/`initialHeights` restores (measurements sanitized like
491
- live ones) and a `settleMs` silence (default 150). Every scroll marks
492
- `scrolling` until the silence settles — suspend loaders and parallax on it.
493
- `Viewport` reports the container's own scrolls and `MeasureRow({ key })` reports row heights, both as Mounts;
494
- `windowFor(model, keys, viewportHeight)` answers which rows to render plus
495
- the spacer height, `isAtEnd(model, keys, viewportHeight, threshold)` is the
496
- infinite-scroll check (an empty list counts as ended), `distanceToEnd`
497
- answers the pixels remaining for prefetch thresholds, and `offsetFor`
498
- computes programmatic scroll targets the application actuates itself.
499
- These share one table of row offsets, built once per `keys` array and
500
- `heights` record and then searched, so keep the keys array between renders
501
- (derive it where the list changes, not in the view) and a scroll costs
502
- O(log n) instead of a pass over every row. Both are compared by identity:
503
- never change a keys array in place.
504
- `Prune` drops heights for departed keys — the bundle never sees key order.
505
- Poisoned positions and heights are ignored, never stored. For window-
506
- scrolled lists, map the scroll entry into `Scrolled`; for follow-bottom,
507
- hold the end while `isAtEnd` and scroll on extend; to anchor a prepend,
508
- re-`Scrolled` by the totals' delta. Render each row keyed (with
509
- `aria-rowcount`/`posinset` from the window) so per-row placements keep
510
- identity. `stickyHeader(sections, start)` answers which section header
511
- sticks — CSS `position: sticky` does the sticking. `masonry(keys, heights,
512
- options)` packs fixed-width columns shortest-first into `{ placements,
513
- totalHeight }`: layout only, every placed item renders, so it fits hundreds
514
- of images rather than hundred-thousands. The sums never name an
515
- axis: pass column widths as heights and a horizontal offset as scroll
516
- position to window a carousel the same way — no parallel horizontal
517
- bundle. Windowed grids and per-index estimates stay out by design.
518
-
519
- Persisted state lives one package over: `Mirror.kv(App, { key, fields })`
520
- keeps a Model slice in Effect's `KeyValueStore` (localStorage in the
521
- browser), restored through a `MirrorRestored` Message the application
522
- reduces. Nothing here duplicates it — reach for the mirror when a slice
523
- should survive reload, and keep this package's bundles for live facts.
524
-
525
- ## Motion: `foldkit-primitives/motion`
526
-
527
- > Reference: [`./motion/README.md`](./motion/README.md)
528
-
529
- Whether motion should be reduced is a service, `Motion`, read when a
530
- transition starts rather than sniffed once. `Presence` then exits at once,
531
- and `Tween` and `Spring` jump to `to`, in the same Messages, so the Model sees
532
- the same transitions. Provide `Motion.live` (the user's
533
- `prefers-reduced-motion`) through the assembly's resources, or `Motion.reduced`
534
- and `Motion.full` in a test or for a setting the application owns. With no
535
- service provided, motion is full, so a placement that provides nothing behaves
536
- as before. `Motion.reducedMotion` is the Effect the bundles read, for a
537
- transition of your own.
538
-
539
- `Tween` animates one number from `from` to `to` over `ms` milliseconds.
540
- Model `{ value, running }`, Messages `Started`/`Ticked`/`Finished`, args
541
- `{ from, to, ms }` (a non-positive or non-finite duration is rejected at
542
- placement). Progress comes from Effect's clock, so tests advance it with TestClock; the
543
- stream ends with `Finished` carrying the exact end value, and the value rests
544
- at `to` either way. Linear interpolation only: easing curves stay the
545
- application's job.
546
-
547
- `Presence` holds mount-transition state for exit animations. Model
548
- `{ phase, generation }` with `phase` moving shown → hiding → hidden:
549
- `Hide` starts the timed `hiding` phase, and the `Hidden` fact it yields
550
- carries its generation, so a `Show` in between wins and the late fact is
551
- ignored. Args `{ durationMs }` (positive and finite). `isVisible` reads
552
- whether content renders (shown or mid-exit). The timeout Command is the default owner; a
553
- `transitionend` Mount stays a future opt-in, not a second timer.
554
-
555
- `Spring` pulls one number toward `to` with `{ stiffness, damping }` physics
556
- (positive and finite): Model `{ value, velocity, running }`, Messages
557
- `Started`/`Stopped`/`Ticked`/`Finished`, args `{ from, to, stiffness,
558
- damping }`. Fixed 16ms semi-implicit Euler makes the trajectory identical on
559
- the live clock and TestClock; the stream ends with `Finished` carrying the
560
- exact end value even when an underdamped spring overshoots on the way.
561
- `Tween` (fixed duration, linear) versus `Spring` (physics, settles) — pick
562
- the motion, not both.
563
-
564
- ## Interaction: `foldkit-primitives/interaction`
565
-
566
- Interaction state that a view's slots must reflect: the Bundle holds it in the
567
- Model, and a matching [`foldkit-mixins`](../mixins) Behavior writes the
568
- attributes and handlers on the slots. Importing this subpath needs
569
- `foldkit-mixins`; the other subpaths do not.
570
-
571
- `RovingTabindex` is one tab stop for a set of items: arrows move focus between
572
- them, the rest stay out of the tab order. The Model slice is `{ current }`, the
573
- current item's **id**, so a reorder keeps the same item current and a resumed
574
- page knows where focus was. Args: `orientation` (`'vertical' | 'horizontal' |
575
- 'both'`), `loop`, and `virtual` (focus stays on the container and
576
- `aria-activedescendant` points at the current item).
577
-
578
- ```ts
579
- import { Bundle } from 'foldkit-bundle'
580
- import { Behavior, Behaviors, Capability, Slot, Slots, SlotView } from 'foldkit-mixins'
581
- import { RovingTabindex } from 'foldkit-primitives/interaction'
582
-
583
- const Roving = Bundle.declare(RovingTabindex.bundle, 'toolbarFocus')
584
- const Model = Schema.Struct({ ...Roving.fields, tools: Schema.Array(Tool) })
585
- const Message = defineMessageUnion({ ...Roving.cases })
586
- const Page = Bundle.parent({ Model, Message })
587
- const args = { orientation: 'horizontal', loop: true, virtual: false } as const
588
- const placements = Page.assemble(Page.at(Roving, { args }))
589
-
590
- const ToolbarSlots = Slots.define({
591
- root: Slot.make({ capability: Capability.Container }),
592
- tool: Slot.make({ capability: Capability.Focusable }),
593
- })
594
- const describeTools = (tools: ReadonlyArray<Tool>) =>
595
- Behaviors.Collection.of(tools, { id: tool => tool.id, disabled: tool => tool.disabled })
596
-
597
- // Ids on each item come from Collection; RovingTabindex reads them.
598
- const Ids = Behaviors.Collection.behavior(ToolbarSlots)<Model, Message>({
599
- item: 'tool',
600
- items: model => describeTools(model.tools),
601
- })
602
- const Focus = RovingTabindex.behavior(Roving, args)(ToolbarSlots)<Model, Message>({
603
- container: 'root',
604
- item: 'tool',
605
- items: model => describeTools(model.tools),
606
- })
607
-
608
- const Toolbar = SlotView.forMessages<Message>()
609
- .define(ToolbarSlots, (model, slots, h) => {
610
- const items = describeTools(model.tools)
611
- return h.div(
612
- slots.root.attrs([h.Role('toolbar')]),
613
- model.tools.map((tool, index) =>
614
- h.button(slots.tool.attrs([h.Key(tool.id)], items.slotItem(index)), [tool.label]),
615
- ),
616
- )
617
- })
618
- .pipe(Behavior.attach(Ids), Behavior.attach(Focus))
619
- ```
620
-
621
- What each half does: the container gets `OnKeyDownFocus`, which on an arrow,
622
- Home or End focuses the next **enabled** item synchronously by its id, prevents
623
- the default, and dispatches `Focused { id }`. Each item gets `tabindex` `0` when
624
- it is the tab stop and `-1` otherwise, and `OnFocus` reporting `Focused`, so a
625
- click makes an item current too. Before anything is current, or when the
626
- current item is gone or disabled, the first enabled item is the tab stop. Keys
627
- with ctrl, alt or meta held are left alone; `direction: model => 'rtl'` swaps
628
- left and right. The pure `move(enabled, current, key, modifiers, options)` and
629
- `tabStop(items, current)` are exported for a view that wires its own.
630
-
631
- Under `virtual` the items get no `tabindex`, the container gets
632
- `aria-activedescendant`, and a key keeps DOM focus where it is and only moves
633
- the pointer. Nothing is written on dispose: the attributes are data, so a view
634
- that no longer attaches the Behavior leaves no `tabindex` behind. PageUp and
635
- PageDown are handled when `move` is given a `page`; `ListNavigation` below
636
- does that.
637
-
638
- `Typeahead` is type-to-find for a host that has no roving tab stop, or whose
639
- focus is managed elsewhere. The Model slice is `{ query, generation }`:
640
- printable keys extend the query, a timer of `timeoutMs` on Effect's clock
641
- clears it (`generation` lets a superseded timer change nothing), and `Cleared`
642
- drops it on purpose. Which item a query picks is the pure
643
- `Typeahead.match(texts, enabled, query, current)`: one character, or one
644
- character repeated, starts *after* the current item so repeated presses cycle;
645
- a longer query starts *at* it, since the user is refining. Case and leading
646
- whitespace are ignored and disabled items are skipped. The Behavior
647
- (`Typeahead.behavior(Declared)(Slots)<Model, Message>({ host, items, text,
648
- current })`) gives the host `OnKeyDownFocus`: a printable key with no ctrl, alt
649
- or meta extends the query, focuses the match by id, and dispatches `Typed`;
650
- with no match the key is still recorded and focus stays put; a space with an
651
- empty query is left to the host.
652
-
653
- `ListNavigation` is what a list host takes when it wants both: arrows, Home,
654
- End, PageUp and PageDown by `page`, and typeahead, in **one placement**. It
655
- exists for two reasons. The resolver allows one owner per event on a slot, so
656
- `RovingTabindex` and `Typeahead` cannot both own the host's `OnKeyDownFocus`;
657
- and under `virtual` a typed key must move the pointer and extend the query in
658
- one transition, which two placements cannot do. Its Model slice is `{ current,
659
- query, generation }`, its args are `RovingTabindex`'s plus `timeoutMs` and
660
- `page`, and its Behavior takes `{ container, item, items, text, direction? }`.
661
- `Typed { char, match }` carries the item the query now picks, so `update` sets
662
- `current` and `query` together.
118
+ **A Mount**, attached to the element it observes. No ref to thread: the Mount
119
+ receives its element.
663
120
 
664
121
  ```ts
665
- const Nav = Bundle.declare(ListNavigation.bundle, 'nav')
666
- // place with { args: { orientation: 'vertical', loop: false, virtual: false, timeoutMs: 500, page: 10 } }
667
- const Keys = ListNavigation.behavior(Nav, args)(ListSlots)<Model, Message>({
668
- container: 'list',
669
- item: 'option',
670
- items: model => describeFruits(model.fruits),
671
- text: (model, index) => model.fruits[index]?.label ?? '',
672
- })
673
- ```
674
-
675
- `GridNavigation` is the two-dimensional counterpart for cells laid out in rows
676
- of `columns` (a calendar grid, a swatch picker, an emoji palette). Its Model
677
- slice and item attributes are `RovingTabindex`'s, so the two are
678
- interchangeable on a view; only the pure `move` differs. Left and right step
679
- within the row and up and down within the column, skipping disabled cells;
680
- under `wrap` a horizontal key continues into the next row and a vertical key
681
- into the next column, otherwise the key is consumed at the edge. Home and End
682
- are the row's first and last enabled cell, Ctrl+Home and Ctrl+End the grid's.
683
- RTL swaps left and right, and `virtual` works as it does for `RovingTabindex`.
122
+ import { Resize } from 'foldkit-primitives/observers'
684
123
 
685
- ```ts
686
- const Cells = Bundle.declare(GridNavigation.bundle, 'cells')
687
- // place with { args: { columns: 7, wrap: false, virtual: false } }
688
- const Keys = GridNavigation.behavior(Cells, args)(CalendarSlots)<Model, Message>({
689
- container: 'grid',
690
- item: 'day',
691
- items: model => describeDays(model.days),
692
- })
124
+ const panel = (model: PanelModel, h: HtmlBuilder<PanelMessage>) =>
125
+ h.div([h.OnMount(Resize())], [`${model.width} × ${model.height}`])
693
126
  ```
694
127
 
695
- `TreeNavigation` is the tree counterpart, after the WAI-ARIA tree pattern,
696
- for a file explorer, a page's layers, or a nested menu: Up and Down through
697
- the rows that are showing, Right opens a row or steps into it, Left closes it or
698
- steps out to its parent, Home and End go to the first and last row. The view
699
- gives every row, open or not, in tree order, each with its `parent` and whether
700
- it is a `branch`; `TreeNavigation.shown(rows, model, args)` is the rows that are
701
- showing, with their level and place among their siblings. The Model slice is
702
- `{ current, toggled }`: openness is stored as the rows toggled away from
703
- `openByDefault`, so a layers panel that starts open and a file tree that starts
704
- closed are one bundle with a different arg. The Behavior writes each showing
705
- row's `id` (through `domId`, by default the row's own), `role="treeitem"`,
706
- `aria-level`, `aria-posinset`, `aria-setsize`, `aria-expanded` on a branch,
707
- `aria-disabled`, a roving `tabindex` and `OnFocus`; the container's keys move
708
- focus by id, or open and close the current row in place. Focus in the tree
709
- follows its stop when a transition it did not see moves it or removes the
710
- focused row (the `FollowTabStop` Mount, in `foldkit-primitives/dom`, which
711
- never takes focus from outside the container). The level is also the
712
- custom property `--fk-tree-level`, 1 at the top, so one rule indents any depth:
713
- `padding-inline-start: calc(var(--fk-tree-level) * 1rem)`.
128
+ **A Command**, returned from `update`, whose result comes back as a Message
129
+ your union wraps:
714
130
 
715
131
  ```ts
716
- const Layers = Bundle.declare(TreeNavigation.bundle, 'layers')
717
- // place with { args: { openByDefault: true } }
718
- const Keys = TreeNavigation.behavior(Layers, { openByDefault: true })(TreeSlots)<Model, Message>({
719
- container: 'tree',
720
- item: 'row',
721
- rows: model => model.folders.map(folder => ({ id: folder.id, parent: folder.parent, branch: folder.hasChildren })),
722
- })
723
- ```
724
-
725
- The pure `move(shown, current, key, modifiers, model, args, direction?)` answers
726
- with `Focus`, `Open` or `Close`, for a view that wires its own.
727
-
728
- `FocusScope` is the one entry here that is a Mount, not a Bundle: which
729
- element has focus is a DOM fact, so nothing crosses to the Model. The Mount
730
- lives in `foldkit-primitives/dom`; `FocusScope.behavior(Slots)<Input,
731
- Message>({ container, contain?, restore?, initialFocus? })` attaches it to a
732
- container slot. On insert the container focuses `initialFocus`, else its first
733
- tabbable descendant, else itself. With `contain` (default), Tab from the last
734
- tabbable wraps to the first, Shift+Tab from the first wraps to the last, and
735
- focus that lands outside comes straight back; Tab in the middle is the
736
- browser's. On unmount, with `restore` (default), focus returns to the element
737
- that had it, if it is still in the document. A native `<dialog>` does all of
738
- this itself; this is for a custom overlay, a menu, or a command palette.
739
- `tabbableWithin(element)` is exported: focusable, visible descendants with a
740
- non-negative `tabindex`, in order.
741
-
742
- `Press` turns pointer and keyboard activation of one element into one fact.
743
- Foldkit's declarative pointer attributes carry no button, pointer id, or click
744
- detail, so `Press.events` is a Mount that reports what the element saw
745
- (`PointerDown`, `PointerUp`, `PointerCancelled`, `KeyDown`, `KeyUp`,
746
- `Clicked`), and the Bundle's `update` decides: primary button only, one
747
- pointer at a time, `pointerleave` and `pointercancel` cancel, Enter and Space
748
- with a repeat ignored, a click with `detail` 0 (keyboard on a native control,
749
- or assistive technology) counts, and the ghost click that follows a touch is
750
- ignored inside a window of `clickSuppressionMs` that a Command on Effect's
751
- clock closes. Enter and Space are default-prevented on the element, so a
752
- native control does not also click and Space does not scroll. Activation is
753
- the OutMessage `Pressed { pointerType, shiftKey }`, and the placement must handle it:
132
+ import { mapMessage } from 'foldkit/command'
133
+ import { copyText } from 'foldkit-primitives/dom'
754
134
 
755
- ```ts
756
- const Button = Bundle.declare(Press.bundle, 'saveButton')
757
- const placements = Page.assemble(
758
- Page.at(Button, {
759
- args: { clickSuppressionMs: 50 },
760
- onOut: () => model => ({ model, commands: [save(model)] }),
761
- }),
762
- )
763
- const Activate = Press.behavior(Button)(CardSlots)<Model, Message>({
764
- target: 'save',
765
- disabled: model => model.saving,
135
+ const copy = (model: NoteModel): Update.Return<NoteModel, NoteMessage> => ({
136
+ model,
137
+ commands: [mapMessage(copyText(model.text), message => NoteMessage.Clipboard({ message }))],
766
138
  })
767
139
  ```
768
140
 
769
- The Behavior attaches the Mount to the target slot, writes `data-pressed`
770
- while the element is down for styling, and marks a disabled target
771
- `aria-disabled`, which the Mount reads at event time so nothing is reported
772
- and no remount is needed. The Model slice is `{ pressed, pointerId, key,
773
- suppressing, generation }`; only `pressed` is meant for a view.
774
-
775
- `LongPress` is holding for `thresholdMs`. It reads the same facts
776
- `Press.events` reports, so it needs no Mount of its own; the threshold is a
777
- Command on Effect's clock carrying a generation, and a release before it fires
778
- makes its `Elapsed` a no-op. `LongPressed { pointerType }` is the OutMessage,
779
- required at placement. The Behavior writes `data-holding` while down. `Press`
780
- and `LongPress` on one slot are refused by the resolver, since both would mount
781
- `PressEvents`; a slot takes one of them.
782
-
783
- `Move` is pointer movement as facts, a Mount in `foldkit-primitives/dom`: a
784
- primary-button pointer down captures the pointer and reports `MoveStarted`,
785
- each move reports `Moved { deltaX, deltaY }` from where it went down, and up,
786
- cancel, or lost capture reports `MoveEnded { completed }`. A second pointer
787
- and a secondary button are ignored; capture is released with the Mount.
788
- `Move.behavior(Slots)<Input, Message>({ handle, toMessage })` attaches it to a
789
- `Draggable` slot and maps each fact into the view's Messages; a drag's meaning
790
- (a threshold, a snap, a reorder) is the parent's `update`.
791
-
792
- `Targets` is which marked descendant of a container the pointer is over, and
793
- which one was pressed, as one Mount on the container rather than one per item.
794
- A descendant is marked by an attribute holding its id (a canvas's
795
- `data-composition-node`, a table's `data-row`), and the nearest marked ancestor
796
- of the event's target, inside the container, is the one reported:
797
- `TargetHovered { id }` once per change, `null` when there is none or the
798
- pointer leaves, and `TargetPressed { id, shiftKey, altKey, ctrlKey, metaKey }`
799
- on a click. `preventDefault: true` stops a press's default, such as a link
800
- navigating inside an editor's canvas. The Mount is `Targets({ attribute,
801
- preventDefault })` in `foldkit-primitives/dom`; `Targets.behavior(Slots)<Input,
802
- Message>({ container, attribute, preventDefault?, toMessage })` attaches it.
803
- `targetOf(container, from, attribute)` is the pure lookup.
804
-
805
- `EditableText` is text typed into a marked descendant of a container while it
806
- is `contenteditable`, as one Mount on the container. The view decides which
807
- field is editable; the Mount focuses it as it becomes so (made editable, or
808
- drawn editable), with the caret at its end, and at no other time: a field
809
- editable all along, or another going away, moves no focus. It reads what is
810
- typed:
811
-
812
- - **Text, never markup.** It reads `innerText`. A field is one line unless it
813
- carries `aria-multiline="true"`, and in one line a line break becomes a
814
- space. Where the browser lacks `contenteditable="plaintext-only"`, a paste is
815
- inserted as its text.
816
- - **`TextEdited { field, text }`** on each change, `field` being the marking
817
- attribute's value. Nothing is reported while an input method composes; the
818
- composed text arrives once.
819
- - **`TextCommitted { field, text }`** on Enter (Shift+Enter breaks a line in a
820
- multiline field) or on leaving the field; **`TextCancelled { field, initial }`**
821
- on Escape, which also puts the text the field had when the edit began (on
822
- focus, or on the first keystroke after an edit ended) back in the DOM, the
823
- caret at its end. A view that stopped redrawing the field while it was edited
824
- would not. An edit ends once: the blur after Enter commits nothing more.
825
- - **Focus comes back to the container** when Enter or Escape ended an edit and
826
- the view then removes the field or makes it no longer editable, which leaves
827
- focus on nothing; give the container a `tabindex`, and the next key (an
828
- undo) reaches it. A field left by the author keeps no such claim.
829
- - **`EditAsked { field }`** on a double-click over a marked field that is not
830
- editable yet: the view's cue to make it so.
831
-
832
- The Mount is `EditableText({ attribute })` in `foldkit-primitives/dom`;
833
- `EditableText.behavior(Slots)<Input, Message>({ container, attribute, toMessage })`
834
- attaches it. What a change means (a prop set, an undo group) is the parent's
835
- `update`.
836
-
837
- `PointerDrag` is dragging one marked descendant onto another, marked the way
838
- `Targets` marks them. A primary press on one that moves more than
839
- `DRAG_THRESHOLD` (4px) starts a drag (`DragStarted { id }`); then, once per
840
- change, `DraggedOver { over }` says which other marked descendant the pointer
841
- is over and in which third of its box, `{ id, zone: 'before' | 'inside' |
842
- 'after' }`, or `null`. Releasing is `DragDropped { id, over }`, and Escape, a
843
- cancelled pointer, or a button found released mid-drag is `DragCancelled { id }`.
844
- An Escape that cancels is heard on the way down and goes no further, so the
845
- focused element's own Escape (a canvas's deselect) does not also run.
846
- It follows the pointer that pressed and ignores a second one; the element under
847
- it is found by position, so a touch or a pen, which the browser captures to
848
- where it went down, drags too, once the marked elements have `touch-action:
849
- none` so a finger drags rather than scrolls. The click a drop ends with is
850
- swallowed, so a `Targets` on the same container does not also press. A press
851
- in `contenteditable` text selects text and starts no drag. It writes
852
- no roles, `tabindex` or keys, so it sits beside a tree's or a listbox's own;
853
- the keyboard's way to do what a drag does is yours to give. Boxes are measured
854
- as the pointer moves and never kept; an element drawn as `display: contents`
855
- is measured by its first child (`boxOf`). The Mount is
856
- `PointerDrag({ attribute })` in `foldkit-primitives/dom`;
857
- `PointerDrag.behavior(Slots)<Input, Message>({ container, attribute, toMessage })`
858
- attaches it, and `zoneOf(box, y)` is the pure split.
859
-
860
- A drag may also land somewhere other than among its own: with
861
- `targets: { attribute: 'data-composition-node', within: '#page' }`, what is
862
- dragged is still one of the container's marked descendants (a palette's
863
- tiles), and `over` is an element marked by that attribute inside the one
864
- `within` selects (the page's nodes). Its own tiles, and a matching element
865
- outside that one, are then over nothing. `within` is looked for nearest
866
- first, under the container's closest ancestor that holds a match, so two
867
- editors on one page each drop onto their own page. Such a drag's
868
- `DraggedOver` and `DragDropped` also carry `region`: whether the pointer is
869
- inside that element, so `over: null` with `region: true` is its empty space
870
- (an empty page, the space below its last node), and with `false`, elsewhere.
871
-
872
- `FocusVisible` is the one entry whose Bundle lives elsewhere: `InputModality`
873
- in `foldkit-primitives/events` keeps `{ modality }` (`'keyboard'`, `'pointer'`,
874
- or `'unknown'` before any input), fed by the window's `keydown` (a modifier
875
- alone says nothing) and `pointerdown`. `FocusVisible.behavior(Declared)(Slots)
876
- <Model, Message>({ target })` writes `data-focus-visible` on the target while
877
- the page is driven by keyboard, so a stylesheet shows a ring with
878
- `[data-focus-visible]:focus`. CSS `:focus-visible` does this with no Model at
879
- all; this is for a design system that must decide in the Model, or show the
880
- same answer somewhere other than the focused element.
881
-
882
- `DismissLayer` closes overlays that are not native `<dialog>` or `popover`
883
- elements: Escape closes the topmost open layer, and a pointer press closes
884
- the layers it is outside of. One Bundle, **placed once**, owns the document
885
- listeners; each layer's Behavior marks its container with
886
- `data-foldkit-plus-layer="<id>"` and its trigger with the matching trigger
887
- attribute. The stack is the DOM order of the marked elements at the moment of
888
- the event, so a layer takes part exactly while it is rendered and an `open`
889
- flag in the parent Model is its whole lifecycle; nothing registers. The rules,
890
- each a test: a press inside a parent layer is outside its children, so the
891
- parent stays and the children go; a press on a layer's trigger counts as
892
- inside it, so a click on the trigger never dismisses and reopens; a layer
893
- placed with `outsidePress: false` or `escape: false` opts out of that path.
894
- `Dismiss { ids }` is the OutMessage, and the placement's `onOut` closes them:
141
+ ## The map
895
142
 
896
- ```ts
897
- const Layers = Bundle.declare(DismissLayer.bundle, 'layers')
898
- const placements = Page.assemble(
899
- Page.at(Layers, {
900
- onOut: ({ ids }) => model => ({ model: { ...model, menuOpen: ids.includes('menu') ? false : model.menuOpen } }),
901
- }),
902
- )
903
- const Dismissable = DismissLayer.behavior(Layers)(MenuSlots)<Model, Message>({
904
- layer: 'panel',
905
- trigger: 'button',
906
- id: () => 'menu',
907
- })
908
- ```
143
+ Each subpath is one concern and one import. Its README has the full
144
+ reference: every Model shape, Message, argument, and failure rule.
909
145
 
910
- The Model slice is `{ layers }`, the open layers as the last event saw them,
911
- for DevTools and agents. `toDismiss(layers, inside)` is the pure rule.
912
-
913
- `Layers.scrollLock(Slots)({ container })` and `Layers.hideOutside(Slots)({
914
- container })` are Mounts over Foldkit's own `Dom.lockScroll` and
915
- `Dom.inertOthers`: the first locks the document's scroll while the container is
916
- mounted, refcounted so nested overlays release together, with Foldkit's iOS
917
- handling; the second marks everything outside the container inert while it is
918
- mounted, keyed by an id the Mount mints so two overlays restore independently.
919
- Both live in `foldkit-primitives/dom` as `ScrollLock` and `HideOutside`. A
920
- native `<dialog>` shown modally needs neither.
921
-
922
- `Selection` is which items are selected, with `mode` `'single'` (a click
923
- replaces; `allowEmpty` says whether clicking the selected item deselects it),
924
- `'multiple'` (a click toggles), or `'none'`, and the `anchor` a range extends
925
- from. The Model slice is `{ selected, anchor }`. A range needs the items'
926
- order, which the view knows and the Bundle does not, so `Ranged { id, order }`
927
- carries it; `Selection.between(order, from, to)` is the pure span. The Behavior
928
- (`Selection.behavior(Declared, args)(Slots)<Model, Message>({ container?,
929
- item, items, click? })`) writes `aria-selected` on each item and
930
- `aria-multiselectable` on the container, and wires a plain click on each
931
- enabled item to `Activated`; pass `click: false` when `Press` or the view owns
932
- the click. For a Shift range, `Press`'s `Pressed { pointerType, shiftKey }`
933
- says whether Shift was held, and the placement's `onOut` dispatches `Ranged`.
934
-
935
- `LiveAnnounce` speaks to assistive technology: one Bundle, placed once, holds
936
- the text of a polite and an assertive live region. `say(Declared)(text,
937
- politeness?)` builds the Message to return from `update` or an `onOut`; an
938
- announcement waits `debounceMs` so a burst reads once, then clears after
939
- `clearAfterMs`, both on Effect's clock with a generation so a superseded timer
940
- changes nothing; the same text twice gets a trailing no-break space toggled,
941
- which is what makes a screen reader read it again. `LiveAnnounce.view(slice,
942
- h)` renders the two regions: put it once in the page and hide them visually
943
- with a rule on `[data-foldkit-plus-live]`, never `display: none`.
944
-
945
- ## Testing placements
946
-
947
- Every primitive is testable without the platform, following one pattern
948
- with three ingredients. First, substitute the environment: factories take
949
- `create` (streams, devices, permissions) or `request` (camera) doubles, so
950
- tests pass fakes instead of stubbing globals. Second, advance time instead
951
- of waiting it: anything on Effect's clock (debounce, throttle, presence,
952
- idle, timers, tweens) runs under `TestClock.adjust`. Third, never hang on a
953
- quiet stream: collect with a bounded `takeMessages`, which fails fast naming
954
- the stall. The settle-before-adjust rule applies throughout — yield after
955
- forking before the first `TestClock.adjust`, or dispatched events hit
956
- unregistered listeners. Each ingredient is demonstrated in this package's
957
- `test/` directory, named after its primitive.
146
+ | Subpath | What it covers | Primitives |
147
+ | --- | --- | --- |
148
+ | [`media`](./media/README.md) | the environment | `MediaQuery` (+ `PrefersDark`, `PrefersReducedMotion`), `Breakpoints`, `platformFromUA`, `isBrowser` |
149
+ | [`net`](./net/README.md) | the network | `Online`, `websocket`, `sse`, `broadcastMessages`, `postBroadcast` |
150
+ | [`time`](./time/README.md) | the clock | `Timer`, `Interval`, `ticks`, `debounce`, `Throttle`, `formatRelativeTime` |
151
+ | [`state`](./state/README.md) | UI state with nowhere else to live | `Pagination`, `history`, `Locale`, `SelectionSet`, `Virtual`, `range`, layout math |
152
+ | [`motion`](./motion/README.md) | animation | `Tween`, `Spring`, `Presence`, the `Motion` service |
153
+ | [`interaction`](./interaction/README.md) | keyboard, pointer, and focus patterns, with their Behaviors | `RovingTabindex`, `Typeahead`, `ListNavigation`, `GridNavigation`, `TreeNavigation`, `FocusScope`, `Press`, `LongPress`, `Move`, `Targets`, `PointerDrag`, `EditableText`, `FocusVisible`, `DismissLayer`, `Layers`, `Selection`, `LiveAnnounce` |
154
+ | [`device`](./device/README.md) | hardware | `Geolocation`, `mediaDevices`, `mediaStream`, `permissions`, fullscreen |
155
+ | [`events`](./events/README.md) | raw window events | `Visibility`, `WindowSize`, `Idle`, `InputModality`, `keyboardEvents`, `pointerEvents`, `scrollEvents`, `activeElementEvents`, `matchHotkey` |
156
+ | [`observers`](./observers/README.md) | element observers | `Resize`, `Intersection`, `Mutation`, `Bounds` |
157
+ | [`dom`](./dom/README.md) | element Mounts and one-shot Commands | `Autofocus`, `InputMask`, `KeepInView`, `Measure`, `FocusScope`, `FollowTabStop`, `ScrollLock`, `HideOutside`, `copyText`, `readText`, `share`, `loadScript`, `keepScroll` |
158
+
159
+ ## Rules every primitive keeps
160
+
161
+ These hold across the package, so the subpath pages do not repeat them.
162
+
163
+ - **A fact that changed nothing returns the Model it was given.** A repeated
164
+ resize, `Started` while running, a total already held: the placement then
165
+ returns the parent unchanged, Foldkit renders nothing, and a `createLazy` view
166
+ over the slice is skipped.
167
+ - **Init is a safe default, not a read.** `matches: false`, `online: true`, a
168
+ count of zero. A server render shows these; the subscription corrects them on
169
+ the client. Do not infer readiness from the default.
170
+ - **Without the platform API, nothing throws.** A stream is empty and the
171
+ slice keeps its default; a Command yields its failure Message (`CopyFailed`,
172
+ `ShareFailed`); a Mount emits nothing.
173
+ - **One placement observes once.** Two placements of one query open two
174
+ listeners; share the field. One assembly holds one socket, stream, camera,
175
+ or permission watch: their resource tags are per module, and `assemble`
176
+ refuses the second.
177
+ - **An OutMessage cannot be dropped by omission.** `debounce`, `Throttle`,
178
+ `Press`, `DismissLayer`, and the rest that surface a settled value require
179
+ `onOut` at placement. `Bundle.ignore` drops one on purpose.
180
+ - **Everything timed runs on Effect's clock.** Timers, tweens, debounces,
181
+ presence, idle, typeahead. Tests advance them with `TestClock.adjust`
182
+ instead of waiting.
183
+ - **Reduced motion is a service.** Provide `Motion.live` through the
184
+ assembly's resources, or `Motion.reduced` and `Motion.full` in a test;
185
+ absent, motion is full.
186
+ - **Elements never cross into the Model.** A focus report is `{ tag, id }`, a
187
+ mutation names nodes, a target is its marked id.
188
+
189
+ ## Testing a placement
190
+
191
+ Three ingredients, each shown in this package's `test/` directory under the
192
+ primitive's name:
193
+
194
+ 1. **Substitute the environment.** Factories take a `create` (streams,
195
+ devices, permissions, sockets) or `request` (camera) double, so a test
196
+ passes a fake instead of stubbing a global.
197
+ 2. **Advance time instead of waiting.** Anything on Effect's clock runs under
198
+ `TestClock.adjust`. Yield after forking before the first adjust, or
199
+ dispatched events reach listeners not yet registered.
200
+ 3. **Never hang on a quiet stream.** Collect with a bounded take that fails
201
+ fast naming the stall.
958
202
 
959
203
  ## With Surface and Mirror
960
204
 
961
- Placed state is ordinary Model, so the surrounding tools apply unchanged —
962
- no bundle-specific Surface or Mirror API exists, by design. Declare a Surface
963
- over the placed fields to render them or expose them to an agent; point
964
- `Mirror.url` at them to link them; spread the bundle's cases into the same
965
- unions. The field refs and wrapper Messages are the same ones the rest of the
966
- application uses.
967
-
968
- ## Failure and recovery
969
-
970
- | Failure | Behaviour |
971
- | --- | --- |
972
- | No `window` (SSR) or no API (old browser, minimal DOM) | stream is empty; the slice keeps its default |
973
- | A Command without its platform API | failure Message (`CopyFailed`, `ShareFailed`, `BroadcastFailed`), never a throw |
974
- | Listener removed (unmount, gate closed) | finalizer disconnects; resubscribing re-reads the current value |
975
- | A Message for an unplaced child | never routes: wrappers only match placed variants |
976
- | MediaStream acquisition fails | parks at `denied`/`idle` with requirements cleared; `Started` retries |
205
+ Placed state is ordinary Model, so nothing here has a Surface or Mirror API of
206
+ its own. Declare a Surface over the placed fields to render them or expose them
207
+ to an agent; point `Mirror.url` at them to link them; spread the bundle's cases
208
+ into the same unions. A slice that must survive a reload persists through
209
+ `Mirror.kv`; this package owns live facts only.
977
210
 
978
211
  ## Limits
979
212
 
980
- - One placement observes one query. Two placements of `MediaQuery` with the
981
- same query open two listeners; share the field instead.
982
- - Presets cover the common queries. Anything else passes `args` explicitly.
983
- - `/plus` Surfaces and Mirrors per primitive are future work; declare them in
984
- the application for now.
213
+ - Presets cover the common media queries; anything else passes `args`.
214
+ - `Virtual` windows one axis of a list; windowed grids stay out by design.
215
+ - `Sync.lww`-style merging, collaborative text, and other replicated state are
216
+ [`foldkit-sync`](../sync)'s, not a primitive.