foldkit-mixins 0.2.0 → 0.4.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,21 +1,51 @@
1
1
  # foldkit-mixins
2
2
 
3
- Typed slot contracts and inside-out Style/Behavior attachments for Foldkit.
4
-
5
- If you style components with CSS classes today, the failure mode is familiar: a
6
- component looks right in one place and wrong in another, and the ways out are a
7
- prop for every difference or a copy of the component. This package takes the
8
- other route. A view declares the points it is willing to let others touch —
9
- `root`, `input`, `label` — and publishes them as a typed contract. Appearance
10
- (**Style**) and interaction (**Behavior**) are then written somewhere else and
11
- attached to a named point by whoever uses the view. The view's markup, its state
12
- and its Messages are never edited.
13
-
14
- Attachments are not concatenated and handed to the renderer. A resolver merges
15
- them: classes are additive, inline styles merge per property, and an event or
16
- scalar attribute has exactly one owner — a second owner is an error with a
17
- stable diagnostic code, not a handler that silently wins. What comes out is an
18
- ordinary array of Foldkit attributes, so nothing new runs at runtime.
3
+ Typed extension points for Foldkit views.
4
+
5
+ A component eventually gets used somewhere its author did not anticipate. One caller wants a
6
+ brand treatment, another wants a tooltip, another wants analytics, another needs an ARIA
7
+ attribute or a `ResizeObserver`. The usual answers are to keep adding props or to copy the
8
+ component and edit its markup.
9
+
10
+ `foldkit-mixins` takes a different approach:
11
+
12
+ > **A view declares where it may be customized once. Callers attach appearance and
13
+ > element-level behavior to those named points later.**
14
+
15
+ The view keeps its markup, state and Messages. The caller gets a typed customization surface
16
+ instead of an open-ended bag of props.
17
+
18
+ ```text
19
+ Without a slot contract With a slot contract
20
+
21
+ Button Button
22
+ ├─ className ├─ root slot
23
+ ├─ iconClassName ├─ icon slot
24
+ ├─ tooltip └─ label slot
25
+ ├─ tracking
26
+ ├─ ariaLabelOverride callers attach independently:
27
+ ├─ onFocusDecoration ├─ BrandStyle
28
+ └─ ... ├─ TooltipBehavior
29
+ └─ AnalyticsBehavior
30
+ ```
31
+
32
+ This is not a second component system and it is not a state library. A slot ultimately resolves
33
+ to ordinary Foldkit attributes.
34
+
35
+ ## The mental model
36
+
37
+ There are five ideas to learn:
38
+
39
+ | Concept | Meaning |
40
+ | --- | --- |
41
+ | **Slot** | A named extension point in a view: `root`, `input`, `label`, `trigger`, ... |
42
+ | **Slots** | The contract describing which extension points exist and what each permits. |
43
+ | **Style** | Appearance attached to a slot: classes, inline declarations and compiled CSS rules. |
44
+ | **Behavior** | Element-level interaction attached to a slot: attributes and an optional Foldkit `Mount`. Never application state. |
45
+ | **SlotView** | A pure Foldkit view that renders those slots and resolves attached Style/Behavior. |
46
+
47
+ `Style` and `Behavior` both compile to a `Mixin`. The resolver combines their contributions and
48
+ rejects ambiguous ownership instead of silently choosing a winner.
19
49
 
20
50
  ```text
21
51
  Slots contract
@@ -24,29 +54,44 @@ ordinary array of Foldkit attributes, so nothing new runs at runtime.
24
54
  Style Behavior
25
55
  appearance interaction
26
56
  │ │
27
- └───────────┬──────────┘
57
+ └───────────┬───────────┘
28
58
  ▼
29
59
  Mixin
30
- slot contributions
60
+ │
61
+ ▼
62
+ resolver
31
63
  │
32
64
  ▼
33
65
  ordinary Foldkit attributes
34
66
  ```
35
67
 
68
+ ## Why not just `className` and props?
69
+
70
+ A class name says only "append this string." A slot is a **typed public customization point**.
71
+ It can say:
72
+
73
+ - this point is a text input rather than an arbitrary element;
74
+ - it publishes `input` but not `click`;
75
+ - callers may set `aria-invalid` but may not replace the structural `role`;
76
+ - this point is internal and cannot be targeted publicly;
77
+ - two independent behaviors may not both own the same event.
78
+
79
+ That matters once a design system, a feature, accessibility logic and product-specific behavior
80
+ all need to customize the same view without knowing about each other.
81
+
36
82
  ## Use it when
37
83
 
38
- - A view should be restyled or decorated where it is used, not where it is
39
- defined, and you want that customization checked rather than hoped for.
40
- - Appearance and interaction come from different places — a design system and a
41
- feature — and neither should have to know about the other.
42
- - You want CSS as data: deterministic class names and rule text you can put in
43
- one `<style>` block, identical on the server and the client.
84
+ Use mixins when a view should be restyled or decorated **where it is used**, not only where it is
85
+ defined, and you want those customizations checked.
44
86
 
45
- **Not for state.** A Behavior owns none of it. A widget's open/selected/value is
46
- a Foldkit Model or Submodel, a transition is `update`, a network call is Message
47
- → Command, and an element-scoped effect (focus trap, `ResizeObserver`) is a
48
- `Mount`. There are no hooks, no atoms, no query cache and no second update loop
49
- here — a Behavior that "needs state" is a signal to reach for a Submodel.
87
+ Typical examples are a design system styling a feature component, a tooltip attached by a caller,
88
+ analytics on an existing action, ARIA decoration, a focus trap, a `ResizeObserver`, keyboard
89
+ behavior, or a reusable visual recipe.
90
+
91
+ **Not for state.** A widget's open/selected/value belongs in a Foldkit Model or Submodel. A
92
+ transition is `update`; a network call is Message → Command; an element-scoped effect is a
93
+ `Mount`. A Behavior that "needs state" is a signal to reach for a Submodel, not to hide an atom
94
+ inside the mixin.
50
95
 
51
96
  ## Install
52
97
 
@@ -54,11 +99,18 @@ here — a Behavior that "needs state" is a signal to reach for a Submodel.
54
99
  pnpm add foldkit-mixins
55
100
  ```
56
101
 
57
- `foldkit` and `effect` are peer dependencies. `foldkit-mixins-surface` bridges a
58
- Surface projection, and `foldkit-mixins-ui` adapts `@foldkit/ui`.
102
+ `foldkit` and `effect` are peer dependencies. `foldkit-mixins-surface` bridges a Surface
103
+ projection, and `foldkit-mixins-ui` adapts `@foldkit/ui` components.
104
+
105
+ The design-system pieces are subpaths, so an application that only attaches classes pays for
106
+ none of them: `foldkit-mixins/layers`, `/theme`, `/layout`, `/defaults`, and `/prose` (see
107
+ [styleImprovements-DESIGN.md](../../docs/design/styleImprovements-DESIGN.md)).
59
108
 
60
109
  ## Quick start
61
110
 
111
+ The component author publishes the extension points. Style and Behavior can then be authored
112
+ elsewhere and attached by the caller.
113
+
62
114
  ```ts
63
115
  import { Schema } from 'effect'
64
116
  import { defineMessageUnion } from 'foldkit/message'
@@ -69,7 +121,7 @@ type Message = typeof Message.Type
69
121
 
70
122
  type FieldInput = { readonly value: string; readonly invalid: boolean }
71
123
 
72
- // 1. The view publishes the attachment points it will honor.
124
+ // 1. The component author publishes the extension points it supports.
73
125
  const FieldSlots = Slots.define({
74
126
  root: Slot.make({ capability: Capability.Container }),
75
127
  input: Slot.make({
@@ -79,13 +131,13 @@ const FieldSlots = Slots.define({
79
131
  }),
80
132
  })
81
133
 
82
- // 2. Appearance, authored anywhere.
134
+ // 2. Appearance can live in a design system or another module.
83
135
  const FieldStyle = Style.forSlots(FieldSlots)({
84
136
  root: Style.compose(Style.class('field'), Style.inline({ display: 'grid' })),
85
137
  input: Style.class('field-input'),
86
138
  })
87
139
 
88
- // 3. Interaction, built from the view's own input and builder.
140
+ // 3. Element-level behavior can be authored independently.
89
141
  const Validation = Behavior.forSlots(FieldSlots)<FieldInput, Message>({
90
142
  input: Behavior.slot({
91
143
  requires: { capability: Capability.TextInput, attributes: [Attr.AriaInvalid] },
@@ -93,8 +145,8 @@ const Validation = Behavior.forSlots(FieldSlots)<FieldInput, Message>({
93
145
  }),
94
146
  })
95
147
 
96
- // 4. The view, and the two attachments. `forMessages` fixes the Message
97
- // universe the view renders into, so `h` is typed without an annotation.
148
+ // 4. The pure view renders through the slots. Attachments return a new view;
149
+ // the original view is unchanged.
98
150
  const Field = SlotView.forMessages<Message>()
99
151
  .define(FieldSlots, (input: FieldInput, slots, h) =>
100
152
  h.label(slots.root.attrs(), [
@@ -109,58 +161,107 @@ const Field = SlotView.forMessages<Message>()
109
161
  .pipe(Style.attach(FieldStyle), Behavior.attach(Validation))
110
162
  ```
111
163
 
112
- `slots.input.attrs(base)` returns the base attributes plus every attached
113
- contribution; base attributes, event Messages and any `ChildAttribute` survive.
114
- `Style.attach` and `Behavior.attach` return a new view — the original is
115
- unchanged.
164
+ `slots.input.attrs(base)` returns the view's base attributes plus every resolved contribution.
165
+ Base attributes, event Messages and any `ChildAttribute` survive. The caller did not copy the
166
+ markup or add a `validationBehavior` prop to the component.
167
+
168
+ ### Render it and interpret the result
169
+
170
+ `Field` is a view function. From a parent view with a compatible builder, call
171
+ `Field({ value: model.value, invalid: model.invalid }, h)`. The input's value
172
+ comes from the parent; typing emits `ChangedValue`; the parent update must
173
+ store that value before the next render. Mixins owns none of that state.
174
+
175
+ In this example, `FieldStyle` supplies classes and a grid layout, while
176
+ `Validation` supplies `aria-invalid`. The input's `OnInput` remains owned by
177
+ the base view. Adding another `OnInput` attachment is a conflict, not a way to
178
+ chain a second application update. Compose the action in the existing Message
179
+ handler instead.
180
+
181
+ For `Style.pseudo`, `Style.media`, or other compiled rules, also install the
182
+ text returned by `Style.stylesheet(style)` in the page. Calling a SlotView
183
+ returns HTML; it does not inject a stylesheet for you.
184
+
185
+ ## What the resolver guarantees
116
186
 
117
- ## Slots
187
+ Attachments are not concatenated and left to renderer order. The resolver applies explicit rules:
118
188
 
119
- A slot is named metadata, not a DOM node:
189
+ - classes are additive and deduplicated into one `Class`;
190
+ - inline styles from Style pieces merge per property, later attachments winning, over the
191
+ view's base; a property a Behavior sets (through `h.Style` in its attributes) has exactly one
192
+ owner, so a Style piece, the base, or a second Behavior setting the same property is an error;
193
+ - an event or scalar attribute has exactly one owner — a second owner is an error;
194
+ - a `ChildAttribute` (a Submodel's published handler) is preserved by identity;
195
+ - `Key` and `InnerHTML` are structural and cannot be overridden;
196
+ - multiple mount contributions compose into exactly one `OnMount`.
197
+
198
+ Conflicts throw `Diagnostics.DiagnosticError` with stable codes such as
199
+ `mixins:event-conflict`, `mixins:style-property-conflict` and `mixins:protected-attribute`, so tests,
200
+ DevTools and editor tooling can all speak the same diagnostic language. The style rule exists
201
+ because a positioning Behavior that writes `top` and a Style that also sets `top` would otherwise
202
+ fight silently, last writer winning.
203
+
204
+ ## Slots: the public contract
205
+
206
+ A slot is metadata, not a DOM node:
120
207
 
121
208
  ```ts
122
209
  Slot.make({
123
- capability: Capability.TextInput, // what it structurally is
124
- events: [Event.Input], // what it emits
125
- attributes: [Attr.AriaInvalid], // what it exposes
126
- hidden: false, // internal attachment points are hidden
210
+ capability: Capability.TextInput,
211
+ events: [Event.Input],
212
+ attributes: [Attr.AriaInvalid],
213
+ hidden: false,
127
214
  protected: { events: [Event.Click], attributes: [Attr.Role], style: ['position'] },
128
215
  })
129
216
  ```
130
217
 
131
- - **Capability** is a hierarchy: `Base → Interactive → { Container, Focusable →
132
- TextInput, Draggable }`, plus `Base → Collection`. A behavior that requires
133
- `Interactive` attaches to a `TextInput`. Extend it with
134
- `Capability.make(name, { extends })`.
135
- - **Event** and **Attr** are branded tokens; `Event.make`/`Attr.make` add custom
136
- ones. They are metadata: they do not install handlers.
137
- - **Requirement** tokens name platform needs (`Keyboard`, `Pointer`,
138
- `Clipboard`) for tooling to read.
139
- - `hidden` reserves an internal point that public mixins cannot target: Style
140
- and Behavior specs do not even offer the key.
141
- - `protected` keeps structural pieces (an event, an attribute, a style property)
142
- from being replaced by an attachment.
218
+ - **Capability** describes structural compatibility. The built-in hierarchy is
219
+ `Base → Interactive → { Container, Focusable → TextInput, Draggable }`, plus
220
+ `Base → Collection`. A behavior that requires `Interactive` may attach to a `TextInput`.
221
+ Extend it with `Capability.make(name, { extends })`.
222
+ - **Event** and **Attr** are branded metadata tokens. `Event.make` and `Attr.make` add custom ones;
223
+ declaring them does not install handlers.
224
+ - **Requirement** tokens name platform needs such as `Keyboard`, `Pointer` and `Clipboard` for
225
+ tooling to inspect.
226
+ - `hidden` reserves an internal extension point: public Style and Behavior specs do not even offer
227
+ that key.
228
+ - `protected` keeps structural events, attributes or style properties from being replaced by an
229
+ attachment.
143
230
 
144
- Names come from the `Slots.define` keys, never repeated inside the value.
231
+ Names come from the keys passed to `Slots.define`; they are never repeated inside each slot.
145
232
 
146
- ## Style
233
+ ## Style: appearance as data
147
234
 
148
- Pure data; it never touches the DOM.
235
+ Style is pure data. It never touches the DOM.
236
+
237
+ Every piece takes `Declarations`: camelCase CSS properties (typed by
238
+ [`csstype`](https://github.com/frenic/csstype)) and custom properties, each a
239
+ string. A misspelled or kebab-case property in an object literal is a type
240
+ error; the compiler writes the kebab-case name. Values are not checked, so
241
+ `var(...)` and `light-dark(...)` pass through.
149
242
 
150
243
  | Primitive | Meaning |
151
244
  | --- | --- |
152
245
  | `Style.class(...)` | class tokens |
153
246
  | `Style.inline({...})` | inline declarations |
154
- | `Style.compose(...)` | concatenate classes, later declarations win per property |
247
+ | `Style.compose(...)` | concatenate classes; later declarations win per property |
155
248
  | `Style.when(condition, piece)` | a boolean known at authoring time |
156
249
  | `Style.whenInput(predicate, piece)` | a condition read from the view input at render time |
157
- | `Style.recipe({ base, variants, defaults, compound })` | returns `selection => StyleValue` |
158
- | `Style.pseudo`/`media`/`supports`/`container`/`nest` | rule-based appearance |
159
- | `Style.keyframes`/`global` | class-independent CSS |
160
- | `Theme.define`/`variable`/`variables` | typed tokens and CSS custom properties |
161
-
162
- Rule-based styles compile to **one deterministic class** (an FNV-1a hash of the
163
- canonical rule text) plus CSS as data:
250
+ | `Style.recipe({ base, variants, defaults, compound })` | one slot: returns `selection => StyleValue` |
251
+ | `Style.recipeFor(Slots)({ base, variants, defaults, compound })` | every slot: returns `selection => StylePieces`; `null` unsets a defaulted axis; `.extend(patch)` merges per slot and refuses a slot the contract lacks |
252
+ | `Style.perItem(item => piece)` / `Style.stagger({ stepMs })` | a piece from the item the slot is rendered for (`attrs(base, item)`); stagger writes `--fk-index` and a `calc` delay |
253
+ | `Style.forCapability(Slots)(capability, piece)` | one piece for every public slot whose capability satisfies it |
254
+ | `Style.self` / `pseudo` / `media` / `supports` / `container` / `nest` | rule-based appearance; `self` is a rule on the element's own class (`&{…}`), for declarations a layer must hold |
255
+ | `Style.keyframes` / `global` | class-independent CSS |
256
+ | `Theme.define` / `Theme.ref(theme)` / `variables` | typed tokens; every token as a typed `var(--fk-group-name)` reference (`Theme.ref(theme).surface.base`), built once per theme; the tokens as inline custom properties |
257
+ | `Theme.lightDark(light, dark)` / `Theme.compose(base, over)` | a token that follows the color scheme with CSS `light-dark()`; themes merged at definition time |
258
+ | `Theme.root(theme, { omit?, colorScheme? })` / `Theme.scoped(theme, selector, overrides)` | from `foldkit-mixins/theme`: tokens as `:root` custom properties, or as overrides under a selector; unlayered global pieces for `Style.stylesheet` |
259
+ | `Theme.tokens` / `Theme.oklch(knobs)` / `Theme.breakpointWidths(theme)` | from `foldkit-mixins/theme`: the shipped spacing, type, radius, motion, border and breakpoint scales; a whole palette derived from an accent and a few knobs; the breakpoints as pixel widths for `foldkit-primitives/media` |
260
+ | `Layers.define(names)` / `Layers.standard` | cascade layers as a value: `names`, `declare` (the `@layer …;` statement as a global piece), `in(name, piece)` (a piece's unlayered rules and global CSS inside that layer; what is already layered keeps its layer; a piece wholly in another layer is `style:relayered`) and `layer(name)` (the placement `Style.forSlots(S)(pieces, { layer })` takes, so a slot style is compiled in that layer). A name outside the order is a type error. `standard` is `reset, tokens, theme, defaults, components, layouts, variants, utilities, app`; also under `foldkit-mixins/layers` |
261
+ | `Style.stylesheet(...)` | one `<style>` block from `NamedStyle`s and bare `StyleValue`s: the layer order hoisted first (two different orders is `style:conflicting-layer-order`), then global chunks, then scoped classes, deduplicated. Once an order is declared, a rule outside it is `style:unlayered-rule`, since it would beat every layer; keyframes, font faces and `@property` pass |
262
+
263
+ Rule-based Style compiles to one deterministic class (an FNV-1a hash of canonical rule text) plus
264
+ CSS as data:
164
265
 
165
266
  ```ts
166
267
  const CardStyle = Style.forSlots(FieldSlots)({
@@ -171,59 +272,269 @@ const CardStyle = Style.forSlots(FieldSlots)({
171
272
  ),
172
273
  })
173
274
 
174
- CardStyle.css // `.style-…:hover{box-shadow:0 1px 2px}@media …{…}`
175
- Style.stylesheet(FieldStyle, CardStyle) // every style you use, deduplicated
275
+ CardStyle.css
276
+ Style.stylesheet(FieldStyle, CardStyle)
277
+ ```
278
+
279
+ Equal rules share a class, so server and client derive the same class and CSS. A rule piece
280
+ inside `Style.whenInput` compiles to its class like any other; the class is static and only its
281
+ presence follows the input, and its CSS is in `Style.stylesheet` whether or not the condition
282
+ ever holds.
283
+
284
+ Beyond `self`, `pseudo`, `media`, `supports`, `container` and `nest`, the rule pieces are:
285
+
286
+ - `Style.states({ open: { opacity: '1' } })` compiles to `&[data-state="open"]`, for Behaviors that
287
+ write `data-state`; `whenInput` when the view knows, `states` when the DOM does;
288
+ - `Style.responsive(breakpoints, { md: { display: 'flex' } })`, named breakpoints from the record
289
+ you pass, so a misspelled one is a type error;
290
+ - `Style.enter({ opacity: '0' })`, a `@starting-style` rule the element animates from, with
291
+ `Style.allowDiscrete` when `display` takes part;
292
+ - `Style.vars({ '--gap': '1rem' })` and `Style.viewTransitionName('hero')`, declarations;
293
+ - `Style.grid({ areas: [['header', 'header'], ['nav', 'main']], columns, rows, gap })`, a grid
294
+ template with typed areas: `.style` for the container and `.area('main')` for a child, where
295
+ a name the template lacks is a type error and a ragged template raises
296
+ `mixins:ragged-grid-areas`;
297
+ - `Selector.attr`, `not`, `is`, `child`, `descendant`, `sibling`, `siblings` build the selector
298
+ strings `pseudo` and `nest` take. Each takes a selector list: every top-level selector is
299
+ scoped to the class (`:is(a, b)` is not split), and a selector that writes `&` places the class
300
+ itself (`nest('[data-open] &')`).
301
+
302
+ ### Theme from a few knobs
303
+
304
+ `foldkit-mixins/theme` extends the root `Theme` with the pieces a page ships. `Theme.oklch` takes
305
+ an accent color and a few knobs (hue shifts, surface saturation and contrast, a contrast factor,
306
+ feedback hues) and returns typed tokens for surfaces, text, outlines, and the accent, secondary,
307
+ tertiary and feedback families. Only the `knob` group holds literals; every other value is a CSS
308
+ expression over other tokens (`oklch(from …)`, `color-mix()`, `light-dark()`), so the browser does
309
+ the derivation and one knob override recolors everything below it. `Theme.tokens` is the
310
+ non-color scales, with `space` and `radius` multiplied by the `density` and `radius-factor` knobs.
311
+
312
+ A theme reaches the page as pieces, and the page chooses the layers:
313
+
314
+ ```ts
315
+ import { Layers, Slot, Slots, Capability, Style } from 'foldkit-mixins'
316
+ import { Theme } from 'foldkit-mixins/theme'
317
+
318
+ const L = Layers.standard
319
+ const theme = Theme.compose(Theme.tokens, Theme.oklch({ accent: { h: 280, c: 0.15, l: '60%' } }))
320
+ const t = Theme.ref(theme) // t.surface.base is 'var(--fk-surface-base)'; a missing name is a type error
321
+
322
+ const PageSlots = Slots.define({ root: Slot.make({ capability: Capability.Container }) })
323
+ // Born in the app layer: the view attaches this same value, so its classes are the sheet's.
324
+ const PageStyle = Style.forSlots(PageSlots)(
325
+ { root: Style.self({ background: t.surface.base, color: t.text.default }) },
326
+ { layer: L.layer('app') },
327
+ )
328
+
329
+ export const sheet = Style.stylesheet(
330
+ L.declare,
331
+ L.in('tokens', Theme.root(Theme.tokens)),
332
+ L.in('theme', Theme.root(theme, { omit: Theme.tokens })),
333
+ L.in('theme', Theme.scoped(theme, ':root[data-theme="ocean"]', { knob: { 'accent-h': '215' } })),
334
+ PageStyle,
335
+ )
336
+ ```
337
+
338
+ Once the sheet declares an order, every rule in it must sit in one of its layers: an unlayered
339
+ rule would beat all of them, `app` included, so `Style.stylesheet` refuses it with
340
+ `style:unlayered-rule`. A slot style takes its layer when it is compiled, with the `layer`
341
+ option; a layout or recipe it composes keeps the layer it was already given. `L.in` takes only
342
+ bare pieces: a layer is part of a rule's identity, so layering a finished style would copy it
343
+ under new class names that no view attaches.
344
+
345
+ `omit` leaves out the tokens another theme already declared, so the scales go out once in
346
+ `tokens` and the palette once in `theme`. Which theme is active is a Model fact: the view writes
347
+ `data-theme` on the root, and `Theme.scoped` only says what the value means. A scheme the user
348
+ picks works the same way with a `data-color-scheme` selector and a `color-scheme` override; a
349
+ scheme the browser picks needs nothing, because the `light-dark()` values follow it. The palette
350
+ needs relative color syntax and `light-dark()` (Chrome 123, Firefox 128, Safari 17.5).
351
+
352
+ `Style.responsive(Theme.tokens.breakpoint, { md: { … } })` and
353
+ `Theme.breakpointWidths(Theme.tokens)` (for the `Breakpoints` bundle) name the same breakpoints;
354
+ a query that is not a plain `min-width` raises `theme:unparseable-breakpoint`.
355
+
356
+ ### Layout
357
+
358
+ `foldkit-mixins/layout` ships the common arrangements as pieces: `Layout.stack`, `cluster`,
359
+ `split`, `sidebar`, `switcher`, `reel`, `center`, `frame`, `pad`, and `autoGrid`, plus
360
+ `Layout.intrinsic` (a stack child that keeps its own width) and `Layout.aside` (the sidebar
361
+ child). Each compiles to rule text that is the same for every caller and reads `--fk-l-*`
362
+ variables with token fallbacks; the options only write those variables inline, so ten stacks
363
+ with ten gaps are one rule and ten inline declarations. The pieces are unlayered; put them in
364
+ `layouts`:
365
+
366
+ ```ts
367
+ import { Layers, Style } from 'foldkit-mixins'
368
+ import { Layout } from 'foldkit-mixins/layout'
369
+
370
+ const L = Layers.standard
371
+
372
+ const CardStyle = Style.forSlots(CardSlots)({
373
+ root: L.in('layouts', Layout.stack({ gap: 'var(--fk-space-sm)' })),
374
+ actions: L.in('layouts', Layout.cluster({ justify: 'end' })),
375
+ })
176
376
  ```
177
377
 
178
- Equal rules share a class; nothing mutates the DOM, so the server and the client
179
- derive the same class and rules. Rules inside `Style.whenInput` are rejected
180
- (`style:conditional-rules-unsupported`) because the class is static while the
181
- condition is not. See [DESIGN.md](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/mixins-DESIGN.md) for the compiler's scope.
378
+ `split` adapts to its container by default (`container-type: inline-size` and a `@container`
379
+ query); `{ contain: false }` uses `@media` on the viewport instead. Its breakpoint and
380
+ `stack`'s `split` index are in the rule text, because a query cannot read a variable, so each
381
+ distinct value is its own class. `sidebar` and `switcher` are flex math and need no query.
382
+
383
+ ### Defaults and prose
384
+
385
+ `foldkit-mixins/defaults` is the baseline plain HTML gets before any slot is styled: `Defaults.reset`
386
+ (box model, media, form-control fonts, reduced motion) and `body`, `headings`, `links`, `code`,
387
+ `controls`, composed as `Defaults.all` (everything except `reset`). Each is element-selector CSS
388
+ under `:where()` over `--fk-*` tokens with a fallback, so a class rule always beats it and it reads
389
+ with or without a theme. `foldkit-mixins/prose` is the longform contract: `Prose.style({ measure?,
390
+ rhythm? })` is one class for every caller (the rhythm between unlike elements: heading to
391
+ paragraph, list to paragraph, around figures) whose options are `--fk-prose-*` variables on the
392
+ element. Both are unlayered; the page places them:
393
+
394
+ ```ts
395
+ import { Layers, Style } from 'foldkit-mixins'
396
+ import { Defaults } from 'foldkit-mixins/defaults'
397
+ import { Prose } from 'foldkit-mixins/prose'
398
+
399
+ const L = Layers.standard
400
+ const Article = Style.forSlots(ArticleSlots)({ body: L.in('components', Prose.style({ measure: '60ch' })) })
401
+
402
+ export const sheet = Style.stylesheet(
403
+ L.declare,
404
+ L.in('reset', Defaults.reset),
405
+ L.in('defaults', Defaults.all),
406
+ Article,
407
+ )
408
+ ```
182
409
 
183
- ## Behavior
410
+ ## Behavior: reusable element-level interaction
184
411
 
185
- A named set of interaction contributions. Attributes are built while resolving,
186
- from the view's `input` and `h`, so the view's Message universe is the only one
187
- a behavior can emit into. `requires` is checked against the slot contract at
188
- definition time: a behavior that needs `Event.Click` cannot attach to a slot
189
- that does not publish it.
412
+ A Behavior is a reusable bundle of element-level interaction that does **not** own application
413
+ state. Its attributes are built while resolving from the view's `input` and `h`, so it can only
414
+ emit Messages from the view's own Message universe. Like an agent capability,
415
+ a Behavior points one way — toward a Message — and never gets a Model setter.
190
416
 
191
417
  ```ts
192
418
  const Focus = Behavior.forSlots(FieldSlots)<FieldInput, Message>({
193
419
  input: Behavior.slot({
194
420
  requires: { capability: Capability.TextInput },
195
421
  attributes: ({ input, h }) => (input.invalid ? [h.AriaInvalid(true)] : []),
196
- mount: input => MeasureField(input.value), // your own `Mount.define*` action
422
+ mount: input => MeasureField(input.value), // your own Mount.define* action
197
423
  }),
198
424
  })
199
425
  ```
200
426
 
201
- Multiple mount contributions compose into **one** `OnMount` per element.
427
+ `requires` is checked against the slot contract at definition time. A behavior that requires
428
+ `Event.Click` cannot attach to a slot that did not publish click. Multiple mount contributions
429
+ compose into one `OnMount` per element.
430
+
431
+ A slot rendered once per item (rows, tabs, options) tells the Behavior which repetition it is
432
+ resolving through the second argument of `attrs`:
433
+
434
+ ```ts
435
+ h.ul(slots.list.attrs(), items.map((item, index) =>
436
+ h.li(slots.row.attrs([h.Key(item.id)], { index, id: item.id, count: items.length }), [item.label]),
437
+ ))
438
+ ```
439
+
440
+ The Behavior receives it as `item` (`{ index, id?, count? }`) in `attributes` and as the second
441
+ argument of `mount`, so one Behavior can write `tabindex="0"` on the current row and `-1` on the
442
+ rest, or `aria-posinset` and `aria-setsize` on each. Without an item argument, `item` is
443
+ `undefined` and the Behavior decorates the slot as a single element.
444
+
445
+ ### Ready-made Behaviors
446
+
447
+ `Behaviors` holds Behaviors that own no state. The first is `Collection`: describe the parent's
448
+ array once, and a view and the Behaviors on it agree about identity, order, and disabled items.
449
+
450
+ ```ts
451
+ import { Behaviors } from 'foldkit-mixins'
452
+
453
+ const items = Behaviors.Collection.of(input.tools, {
454
+ id: tool => tool.id,
455
+ disabled: tool => tool.disabled,
456
+ }) // ids, size, at, indexOf, isDisabled, enabled, slotItem
457
+
458
+ const Ids = Behaviors.Collection.behavior(ToolbarSlots)<ToolbarInput, Message>({
459
+ item: 'tool',
460
+ items: input => Behaviors.Collection.of(input.tools, { id: tool => tool.id }),
461
+ posInSet: true,
462
+ })
463
+
464
+ // in the view: slots.tool.attrs([h.Key(tool.id)], items.slotItem(index))
465
+ ```
466
+
467
+ `of` is pure and refuses two items with one id (`mixins:duplicate-item-id`), since an id is what
468
+ `aria-activedescendant` and `aria-controls` rely on. The Behavior writes `id`, `aria-disabled`,
469
+ and with `posInSet` `aria-posinset` and `aria-setsize`, reading the item context the view passes;
470
+ it contributes nothing to a slot resolved without one. Behaviors that need state, such as a
471
+ roving tab stop or a press, live in `foldkit-primitives` as a Bundle plus its Behavior.
472
+
473
+ Four more stateless Behaviors say a parent's state in ARIA, so a custom view
474
+ gets it right without hand-writing it. Each takes slot names and functions of
475
+ the view's input; none owns anything.
476
+
477
+ - `Behaviors.Disclosure.behavior(Slots)<Input, Message>({ trigger, content, open, id })`
478
+ writes `aria-expanded` and `aria-controls` on the trigger, `id` and `hidden`
479
+ on the content. The floor is `<details>`.
480
+ - `Behaviors.ToggleState.behavior(Slots)({ control, state, as: 'checked' | 'pressed' })`
481
+ writes `aria-checked` (checkbox, switch, radio, option) or `aria-pressed` (a
482
+ toggle button) from a `boolean | 'mixed'`.
483
+ - `Behaviors.FieldAssociation.behavior(Slots)({ control, label, description?, error?, id, invalid?, required? })`
484
+ derives `<id>`, `<id>-label`, `<id>-description`, `<id>-error` from one base
485
+ id (`FieldAssociation.ids(id)` for a view that renders them itself) and
486
+ writes `id`, `for`, `aria-labelledby`, `aria-describedby` (the error joins
487
+ while `invalid`), `aria-invalid`, `aria-required`. Derived, not minted, so a
488
+ resumed page and a test agree.
489
+ - `Behaviors.SpinValue.behavior(Slots)({ control, value, onChange, min?, max?, step?, page?, text? })`
490
+ writes the `spinbutton` role and `aria-value*`, and steps the parent's number
491
+ with ArrowUp and ArrowDown by `step`, PageUp and PageDown by `page` (default
492
+ ten steps), Home and End to the bounds, clamped and default-prevented;
493
+ `SpinValue.spin(value, key, modifiers, bounds)` is the pure step. A
494
+ press-and-hold repeat and the wheel are not handled: Foldkit's wheel
495
+ attribute carries no delta, and a repeat is a timer the Model would own.
496
+
202
497
 
203
498
  ## SlotView
204
499
 
205
500
  `SlotView.define(slots, render)` is a pure view that publishes slots. Attach with
206
501
  `SlotView.attach`, `Style.attach` or `Behavior.attach`; each returns a new view.
207
502
 
208
- Nothing but the render callback's builder names the view's Message universe, so
209
- plain `define` infers it from an explicit `h: HtmlBuilder<Message>` annotation on
210
- that parameter. Without one, `Message` is `unknown` and the first error lands at
211
- `Style.attach`/`Behavior.attach` as a variance mismatch that never mentions the
212
- annotation. `SlotView.forMessages<Message>().define(slots, render)` fixes the
213
- universe up front instead; `Input` still comes from the callback's own `input`
214
- annotation.
503
+ Nothing but the render callback's builder names the view's Message universe, so plain `define`
504
+ infers it from an explicit `h: HtmlBuilder<Message>` annotation. Without one, `Message` becomes
505
+ `unknown` and the eventual variance error is hard to read.
506
+ `SlotView.forMessages<Message>().define(slots, render)` fixes the universe up front instead;
507
+ `Input` still comes from the callback's own `input` annotation.
508
+
509
+ `Behavior.attach` uses the behavior's `Input` as the attached view's `Input`, so declare a
510
+ behavior over the view's input type, not merely the subset of fields it happens to read.
511
+
512
+ For per-item groups such as tabs, options or calendar cells, use
513
+ `SlotView.buildersFor(slots, mixins, { input, h })` and map the items yourself. One contribution
514
+ then applies to every item while each item's base attributes retain their own event ownership.
215
515
 
216
- `Behavior.attach` takes the behavior's `Input` as the attached view's `Input`, so
217
- declare the behavior over the view's input type, not over the subset of fields it
218
- reads — a subset is rejected, and a superset widens what the view must be called
219
- with.
516
+ ## With `foldkit-surface`
220
517
 
221
- For a component whose render payload has **per-item** groups (tabs, options,
222
- calendar cells), call `SlotView.buildersFor(slots, mixins, { input, h })` and map
223
- the items yourself — one contribution then applies to every item while each
224
- item's base keeps its own event ownership.
518
+ Mixins do not require Surface, but the two fit naturally: Surface says **what a feature may
519
+ observe and emit**; slots say **where that feature may be customized**.
225
520
 
226
- ## A11y
521
+ `foldkit-mixins-surface` renders a Surface projection through a `SlotView`, so a Behavior reads the
522
+ projected input rather than the root application Model, and its builder carries the Surface's
523
+ Message subset.
524
+
525
+ ```text
526
+ Application Model / Message
527
+ │
528
+ Surface
529
+ what may be seen/emitted
530
+ │
531
+ SlotView
532
+ where it may be customized
533
+ │
534
+ Style + Behavior
535
+ ```
536
+
537
+ ## Accessibility contracts
227
538
 
228
539
  ```ts
229
540
  const DialogPattern = A11y.pattern({
@@ -231,37 +542,75 @@ const DialogPattern = A11y.pattern({
231
542
  content: { capability: Capability.Container },
232
543
  })
233
544
 
234
- A11y.validate(DialogPattern, DialogSlots) // ReadonlyArray<A11yDiagnostic>
545
+ A11y.validate(DialogPattern, DialogSlots)
235
546
  ```
236
547
 
237
- `validate` is pure and DOM-independent: it checks the declared contract, never a
238
- rendered tree, and reports missing or hidden slots, capability mismatches and
239
- unpublished events or attributes in authored order. A requirement marked
240
- `optional` tolerates an absent slot but still checks a present one. It does not
241
- certify WCAG.
548
+ `A11y.validate` is pure and DOM-independent. It checks the declared contract for missing or hidden
549
+ slots, capability mismatches and unpublished events or attributes. An optional requirement
550
+ tolerates an absent slot but still checks a present one. It does **not** certify WCAG compliance.
551
+
552
+ ## Introspection
553
+
554
+ The contracts are data:
555
+
556
+ - `Slots.describe(contract)` and `Slot.describe(slot)` return serializable metadata.
557
+ - `Mixin.compose` combines mixins; `Mixin.make`, `Mixin.dynamic` and `Mixin.empty` build them.
558
+ - diagnostics have stable codes and structured `details`, so the same information can feed tests,
559
+ DevTools, documentation or agent tooling.
560
+
561
+ ## Testing and static output
242
562
 
243
- ## Introspection and diagnostics
563
+ `SlotView.inertBuilder<Message>()` is an `HtmlBuilder` with no runtime behind it. Rendering a
564
+ view with it builds the same tagged attributes and elements, but nothing mounts and handlers are
565
+ never dispatched. Use it in tests, demos and static output, not as a renderer.
244
566
 
245
- - `Slots.describe(contract)` and `Slot.describe(slot)` return serializable
246
- metadata.
247
- - Conflicts throw a `Diagnostics.DiagnosticError` with a stable code
248
- (`mixins:event-conflict`, `mixins:protected-attribute`, …) and a `details`
249
- record, so tests, DevTools and editor tooling share one shape.
250
- - `Mixin.compose` merges mixins; `Mixin.make`/`Mixin.dynamic`/`Mixin.empty` build
251
- them.
567
+ `Attributes` reads a resolved bundle, such as the result of `slots.x.attrs(base)`, by tag.
568
+ `Attributes.find(bundle, tag)` returns the **first** match typed as that variant, so `value`,
569
+ `message` or `action` need no cast; `Attributes.filter` returns every match in bundle order;
570
+ `Attributes.tagOf` returns an entry's tag. Opaque `ChildAttribute` entries have no readable tag
571
+ and are skipped.
572
+
573
+ ```ts
574
+ import { Attributes, type SlotAttributes } from 'foldkit-mixins'
575
+
576
+ let input: SlotAttributes<Message> = []
577
+ const Probe = SlotView.forMessages<Message>()
578
+ .define(FieldSlots, (field: FieldInput, slots, h) => {
579
+ input = slots.input.attrs([h.Value(field.value)])
580
+ return h.input(input)
581
+ })
582
+ .pipe(Style.attach(FieldStyle), Behavior.attach(Validation))
583
+
584
+ Probe({ value: 'Ada', invalid: true }, SlotView.inertBuilder<Message>())
585
+
586
+ Attributes.find(input, 'Class')?.value // 'field-input'
587
+ Attributes.find(input, 'AriaInvalid')?.value // true
588
+ ```
589
+
590
+ ## `@foldkit/ui`
591
+
592
+ `foldkit-mixins-ui` adapts `@foldkit/ui` components that expose attribute bundles or a consumer
593
+ render seam. Button, Input, Checkbox, Disclosure, Dialog, Popover, Tooltip, Slider, Tabs,
594
+ RadioGroup, Calendar and others are covered.
595
+
596
+ Some components build their entire element tree internally and expose no attachment seam; those
597
+ cannot be adapted without changing the component API. Others simply do not have an adapter yet.
598
+ See the [guide](https://github.com/doeixd/foldkit-plus/blob/main/docs/mixins.md) for the current
599
+ boundary.
252
600
 
253
601
  ## Status
254
602
 
255
- The API is still settling (`0.1.0`), and this package replaces none of Foldkit's
256
- own machinery — Commands, Subscriptions, Mounts, ManagedResources, `@foldkit/ui`.
257
- [DESIGN.md](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/mixins-DESIGN.md) records the substrate probes and the decisions they
258
- forced.
603
+ The API is still settling (`0.2.x`). This package replaces none of Foldkit's state or effect
604
+ machinery — Commands, Subscriptions, Mounts, ManagedResources, Models or Submodels. Its job is
605
+ narrower: make view customization explicit, typed and composable.
606
+
607
+ The [design note](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/mixins-DESIGN.md)
608
+ records the substrate probes and implementation decisions.
259
609
 
260
610
  ## See also
261
611
 
262
- - [Inside-out view composition](https://github.com/doeixd/foldkit-plus/blob/main/docs/mixins.md) — the mental
263
- model, the four concerns, and the resolver's rules.
264
- - [`foldkit-mixins-surface`](https://github.com/doeixd/foldkit-plus/tree/main/packages/mixins-surface) renders a Surface projection through a SlotView, and
265
- [`foldkit-mixins-ui`](https://github.com/doeixd/foldkit-plus/tree/main/packages/mixins-ui) adapts `@foldkit/ui` components.
266
- - [`examples/mixins`](https://github.com/doeixd/foldkit-plus/tree/main/examples/mixins) — a runnable trace; [`examples/todo-app`](https://github.com/doeixd/foldkit-plus/tree/main/examples/todo-app) styles a whole
267
- application this way.
612
+ - [Inside-out view composition](https://github.com/doeixd/foldkit-plus/blob/main/docs/mixins.md) — the mental model and when to use it.
613
+ - [`foldkit-mixins-surface`](https://github.com/doeixd/foldkit-plus/tree/main/packages/mixins-surface) — bind a Surface projection and Message subset to a SlotView.
614
+ - [`foldkit-mixins-ui`](https://github.com/doeixd/foldkit-plus/tree/main/packages/mixins-ui) — adapters for `@foldkit/ui`.
615
+ - [`examples/mixins`](https://github.com/doeixd/foldkit-plus/tree/main/examples/mixins) — a focused runnable trace.
616
+ - [`examples/todo-app`](https://github.com/doeixd/foldkit-plus/tree/main/examples/todo-app) — a whole application styled this way.