Mixins / foldkit-mixins-ui

Choosing a value

The application keeps the chosen value in its Model. Widgets that submit natively take name (Form participation).

WidgetWhat it doesState
CheckboxSingle checkbox with label and descriptionApplication / Adapter
CheckboxGroupMulti-select checkboxes with selectAll helperApplication
SwitchOn/off toggle switch with optional drag behaviorApplication / Adapter
RadioGroupSingle-choice radio list with focus cursorSmall Model / Bundle
SegmentedSingle-select or toggle button trayApplication
SelectNative <select> with optgroup supportApplication / Adapter
ListboxCustom select dropdown with single/multi choiceSmall Model / Bundle
ComboboxFilterable select or tags input with suggestionsSmall Model / Bundle
PickerDropdown on desktop, bottom sheet on mobileSmall Model / Bundle
CascadeSelectNested path picker across hierarchical optionsSmall Model / Bundle

Ranges, ratings, colors, and dates

WidgetWhat it doesState
SliderNative range input for one value, range, or thumbsApplication
AngleSlider0–360° circular dial with drag and steppersSmall Model / Bundle
RatingStar/glyph radio group with half-step precisionApplication
ColorPickerSB area, hue/alpha sliders, formats, and eyedropperSmall Model / Bundle
CalendarInline single, range, or multiple date pickerSmall Model / Bundle
DatePickerCalendar inside a popover with form inputsAdapter / Bundle
  • CheckboxGroup. Each option uses RowContent (value, label, description, icon, trailing, content, disabled). Pure helpers toggled, coverage (none | some | all), and setEnabled manage selections, and selectAll renders a tri-state toggle row. Recipes.CheckboxGroup offers variant: 'plain' | 'list' | 'card'.
  • RadioGroup. Bundles.RadioGroup manages the focus cursor and reports Selected; value stays an Option in your Model. RadioGroup.readingKeys binds both arrow axes (Right to left).
  • Select, Listbox, and Combobox. Select wraps native <select>. Listbox and Combobox are custom popups backed by Choice (one, many, text) with parts for custom row rendering, optional fluid highlights and overlayBars, and clear buttons. Combobox adds chips for multi-select, empty status text, and Home/End kept on the text caret. See Why some components needed a fork.
  • AngleSlider. AngleSlider.init and update(layout) (or Bundles.AngleSlider) track the angle and drag state; AngleSlider.configure fixes look, layout (step, largeStep, marks, restrictToMarks), and words.

Segmented

A single choice (the default) is a radio group: a role="radiogroup" of role="radio" options with aria-checked, one tab stop, and the arrows, Home and End move the choice and the focus. It requires id, which prefixes the options' ids, since the arrows move focus by them; direction: 'rtl' swaps ArrowLeft and ArrowRight. With multiple: true it is a toggle group, shadcn's and Zag's: a role="group" of aria-pressed buttons, each a tab stop and each filling itself (draw it without Segmented.fluid, whose pill marks one). name submits the chosen values as hidden inputs; disabled turns the group off (aria-disabled, no key or press taken). An option takes an icon, alone with iconOnly (named by aria-label and title). Its indicator and highlight Slots, drawn first in the group and given Segmented.fluid, slide the pressed option's pill to a new press and move the hover to the option the pointer is on (see Fluid highlights); until it runs the pressed option fills itself.

The recipe: the chosen option takes the accent's tint, flat; that rule lives on the group, in variants, so icon tiles take the group piece alone, and an icon button's own background, a variant too, does not hide it. tray is a muted tray, a plain row (which sets no display: the Builder owns its narrow tabs' visibility; its options tint themselves on hover as every hover is) or an underline, each as wide as its options (width: 'fill' for a strip as wide as its container). size steps the tray and its options on the ladder (xs a half step below compact, 24px), the tray's inset counted in, so a tray is as tall as a button beside it.

The recipe's tray and size are selected per slot:

ts
import { Layers, Style } from 'foldkit-mixins'
import { Recipes, SegmentedSlots } from 'foldkit-mixins-ui'

const SegmentedStyle = Style.forSlots(SegmentedSlots)(
  {
    group: Recipes.Segmented({ tray: 'plain', size: 'sm' }).group,
    option: Recipes.Segmented({ tray: 'plain', size: 'sm' }).option,
  },
  { layer: Layers.standard.layer('app') },
)

Then a toggle group draws the options from the application's pressed values:

ts
Segmented.view(
  {
    multiple: true,
    label: 'Text style',
    options: [
      { value: 'bold', label: 'Bold' },
      { value: 'italic', label: 'Italic' },
    ],
    pressed: model.marks,
    onPress: mark => Message.ToggledMark({ mark }),
    style: SegmentedStyle,
  },
  h,
)
// in update: modifyFields(model, { marks: () => Segmented.toggled(model.marks, mark, { multiple: true }) })

Switch and Checkbox

Checkbox.view and Switch.view draw the whole row from options: the control, its label, a line of description that also describes it, and a labelAside slot beside the label. The row carries data-checked, data-disabled, data-invalid and data-position for the recipe, so variant: 'card' (the row boxed, filled while checked, one press target with the label stretched over it) is CSS over the same markup. Checkbox.toView and Switch.toView stay the adapters, for a layout of your own.

Switch.draggable(onToggle) beside the style lets the thumb be dragged: it follows the pointer past 4px, and on release onToggle is sent for the side its middle is on (nothing when that is the side it began on); a click after a drag is swallowed, right to left mirrors it, and a disabled or read-only switch does not drag. The thumb is held where it was let go for 300ms or until aria-checked changes, so an update that refuses the toggle sends it back. Pass the onToggle the view was given.

Picker

Both halves are drawn and the recipe shows one, so nothing reads the width: the Listbox (its panel kept in place) at or above the breakpoint, and below it an opener whose Sheet lists the options as a listbox, the chosen one (or the first) focused, the arrows, Home and End moving focus, Enter, Space or a tap choosing and closing it. The application keeps the value, read through the Listbox's Choice, and Value is inferred from the choice (Picker.one(items): at most one item, since the Sheet closes at a pick). Rows are RowContent; groupBy and heading group them in the dropdown and in the Sheet; clear draws the Listbox's button beside the trigger and beside the opener; name submits the choice once. Opening the Sheet closes a Listbox left open. listbox takes Recipes.Listbox, which also draws the options' and the trigger's content (Listbox.parts), and sheet takes Recipes.Sheet. routes are application key routes on a Sheet option (item.index is its place); the dropdown's keys are the Listbox's.

CascadeSelect

The trigger is a combobox opening a top-layer APG tree, a column per level or one level at a time (layout: 'drill'; the columns also drill in on their own when they would not fit the window, measured as the popup opens). config is { nodes, parents?, closeOnSelect?, loop? }, the same object the view takes; only an option without children is chosen unless parents allows any. The arrows move within and between levels (swapped right to left), Home and End jump to the ends, letters typed within half a second find the row whose label starts with them (CascadeSelect.Model.typeahead, cleared by the QueryExpired Message), Enter and Space choose (Space opens the closed trigger too). With name a form submits one hidden input per level of the path (an id may hold any character, so no separator joins them), or one empty input when nothing is chosen.

The chosen path is the widget's own value, so Bundles.CascadeSelect holds it: its args are { id, value?, config }, the config object the view takes too, and it reports Changed { value } when the path moves (answer Bundle.ignore where the parent only reads model.<field>.value). helpers.set(path) is how the parent writes it: an empty path clears, a path that cannot be chosen is ignored, and nothing is reported. The fixed text is words (placeholder, clear, back with {label}), and clear: true (or { content }) draws the button that empties the value. option: node => RowContent draws a row's icon, description and trailing (its disabled is the node's); triggerText: labels => string collapses a long path on the trigger; config.inline draws the tree in place, always open, with no trigger, which Tab focuses (pass the same config to init or the Bundle). Not built: several chosen paths (a tree with indeterminate branches), a search field in the panel, a footer or side panel, and a loading level.

Slider

onCommit is sent with the value when the reader lets go (the range input's native change, which fires on release after a drag and on each key press, where onChange has sent every step on the way), and description is a line under the slider that each thumb is described by. One number is one thumb across the track, named by the label; a press anywhere on the track moves it. A range is a group named by its label holding two thumbs named by words.low and words.high (default Minimum and Maximum), each bounded by the other, so the browser stops a drag or a key at the other thumb; Slider.moved(range, 'low' | 'high', value, bounds) snaps, bounds and orders a range, and returns the same range when nothing changed. marks are values dotted on the track (data-filled where the fill covers them) and showValue draws each value, both hidden from assistive technology, which hears aria-valuetext; a mark may be { value, label } (SliderMark), its words under the track, those at either end flush with its ends. orientation: 'vertical' stands it upright; ticks dots every step. A Slider is at least 12rem wide; a holder that lays it narrower sets --fk-slider-min-length. @foldkit/ui's Slider is not adapted: draw its Submodel with Slots of your own.

Rating

precision: 0.5 draws two radios a star; a read-only value of any fraction fills its last star part way. onClear is sent by a press on the star already chosen; showValue shows the rating beside the stars, said as words or labels say it. Home and End on a star are a key route that focuses the first or last star by its id (<id>-<value>) and chooses it, as the arrows would; a read-only or disabled rating draws no route. name defaults to id. Its tones are the shared Recipes.Tone vocabulary.

ColorPicker

Keys and drags reach update as what was pressed, so fast keys each step from the last color. ColorPicker.popover takes a Popover made with contentFocus: true (it throws for one without): the panel opens on the area's thumb, a press or a drag inside never closes it, and focus leaving it closes one the keys or a finger opened (a mouse's stays open, as upstream's Popover does). popover is a file of its own, so a page drawing the picker inline keeps neither upstream's Popover nor its anchoring. The picker's own words are words (ColorPicker.words: area, saturation, brightness, hue, alpha, format, input, eyedropper, presets), Bundles.ColorPicker.with({ id, color?, format? }) places its state and reports Changed { color }, and ColorPicker.configure({ base, presets }) fixes the swatches, the sliders' look and the words once.

The view reads nothing from the environment, so the eyedropper button is the eyedropper input, false by default on a server and in a browser alike. ColorPicker.canEyedrop() is the pure feature test; call it where the application learns its environment and keep the answer in the Model. An application that only runs in a browser reads it in init:

ts
import { Schema } from 'effect'
import { ColorPicker } from 'foldkit-mixins-ui'

const PickerModel = Schema.Struct({ picker: ColorPicker.Model, eyedropper: Schema.Boolean })

const initPicker = () => ({
  model: {
    picker: ColorPicker.init({ id: 'accent' }),
    eyedropper: ColorPicker.canEyedrop(),
  },
})

A server-rendered application starts false, so the served markup and the browser's first render agree, and learns the answer after it has taken over, so the button appears instead of the picker's controls being rebuilt:

ts
import { Effect, Schema } from 'effect'
import * as Command from 'foldkit/command'
import { defineMessageUnion } from 'foldkit/message'
import { ColorPicker } from 'foldkit-mixins-ui'

const EyedropperMessage = defineMessageUnion({
  LearnedEyedropper: { available: Schema.Boolean },
})

// Send it from the Command that starts the application, with the first frame drawn.
const LearnEyedropperCommand = Command.define('LearnEyedropper', {
  messages: [EyedropperMessage.LearnedEyedropper],
  execute: Effect.sync(() =>
    EyedropperMessage.LearnedEyedropper({ available: ColorPicker.canEyedrop() }),
  ),
})

Either way the view is given eyedropper: model.eyedropper. Pressing the button runs ColorPicker.Eyedrop, which answers CancelledEyedropper and nothing else when the runtime has no eyedropper or the user closes it: a cancel changes nothing and shows nothing.

ColorPicker.color('#3b82f6') reads a literal in code (it throws on a typo); format, parse (an Option) and toOklch are pure. ColorPicker.Eyedrop and canEyedrop are the eyedropper's Command and check.

Calendar and DatePicker

A Calendar's value is a Calendar.Selection: Single, Range or Multiple, a type of the Calendar's own, so the Calendar's state holds it. Calendar.init makes that state (the month shown, a second month, the selection, a range's hover preview), Calendar.update folds it, and Calendar.view(options, h) draws it. Bundles.Calendar is the same init and update for foldkit-bundle; State has a whole example.

  • Args (Calendar.Args, also init's options): id, today, and optionally selection (default Calendar.empty('Single')), months (1 or 2), minDate, maxDate, disabledDaysOfWeek, disabledDates and locale (Calendar.localeOf('de-DE') reads one from Intl).
  • Reading the value: Calendar.selectedDate (a Single's day), rangeOf (a range with both ends), datesOf (every day held, in order), firstDate, isComplete. The Bundle reports Changed { selection } whenever the selection holds other days; its set helper, and Calendar.set(model, selection), set it from the parent and report nothing.
  • View options, all optional beyond model, onMessage and label (the group's name): weekNumbers; caption: 'grid' (the default heading button, which opens the month and year grids), 'label', or { dropdowns: { years?, month? } }, where month: 'label' writes the month as text beside a select of years; paging: 'both', 'previous', 'next', 'none', or 'end' for both buttons after the caption; today: { label, selects? }, a button that turns back to today's month and, with selects, picks it; presets, a list of { label, selection } built with Calendar.lastDays, nextDays, monthOf and day, or written by hand; detail: date => Option<string>, a line under a day's number; aside and footer, drawings of the application's own placed beside and under the months; words (Calendar.words lists them; {month}, {date}, {year}, {from} and {to} are filled); style and mixins.
  • Two months share one selection and page together: the previous button is on the first, the next on the second, and dropdowns are on the first.
  • A time list, an event list, a second field is another widget with its own state, drawn into aside or footer. The Calendar places it and knows nothing of it.
  • Calendar.configure({ base, presets }) binds weekNumbers, caption, paging, today, presets, detail, words, style and mixins (Drawing). Its presets key names sets of options; the view option presets lists selections.
  • What it costs: a page that draws through the adapter below keeps neither the state nor this view. Upstream's month and year grids ship with every calendar, since they are inside upstream's one Model and view; caption: 'label' hides them and cannot drop them.

A DatePicker is the same Calendar in a popover, with the same split. DatePicker.init(args) makes its state (upstream's picker, the selection, a range's preview), DatePicker.fold(model, message) folds it, and Bundles.DatePicker packages both; it reports Changed { selection } as the Calendar's Bundle does. DatePicker.view(options, h) draws it:

  • trigger: selection => string is the trigger's text, required: a date, both ends of a range, or a prompt. label names the trigger.
  • name submits each chosen day as an ISO date, a range's start then its end; disabled and anchor are the popover's (the default stands under the trigger's start and is not portaled).
  • The Calendar's options go to the panel: weekNumbers, caption, paging, today, presets, detail, aside, footer and words. A picker holds one month.
  • Two styles: style of DatePickerSlots (wrapper, trigger, panel, backdrop) and calendarStyle of CalendarSlots, with calendarMixins beside it.
  • Closing is the arg closes. 'complete' (the default) closes the popover on the pick, or the preset, that makes the selection whole: a day, or a range's second end. 'manual' closes on none, which a picker with a time list in aside needs. Escape, a press outside and the trigger close it either way.
  • DatePicker.configure({ base, presets }) binds everything but the wiring, trigger, name, disabled and the two drawings.
  • The state's fold is fold because DatePicker.update(selection, closes?) is the adapter's, below.

The adapter is the rung below, for a calendar an application draws or folds itself. Fold each SelectedDate through Calendar.picked; Calendar.empty(mode) starts a selection and Calendar.isComplete says when a picker may close. Spread Calendar.inputs(selection, mixins, { h }) into upstream Calendar.view's inputs: its toView (Calendar.toView(selection, mixins, { h })) marks each chosen day aria-selected, a range's ends data-selected with data-range-start/data-range-end and every day between data-in-range, and its maybeSelectedDate (Calendar.selectedDate(selection), a Single selection's day) agrees with it. The grid of a Range or Multiple selection is aria-multiselectable. Calendar.localeOf('de-DE') reads upstream's locale from Intl.

Options, the fourth argument of toView, inputs and resolve (CalendarOptions): weekNumbers, caption: 'label' or dropdowns: { model, onShow, years?, month?, words? } (month and year selects; answer onShow with Calendar.show), paging with Calendar.alongside(model, other, offset) for two months side by side, preview: { date, onPreview } for a range under the pointer, and detail: date => Option<string> for a line under a day's number (a price, "2 events") that describes its button (ResolvedDayCell.detail). ResolvedDays' paging buttons are Options, pagingAtEnd says both stand after the caption, and its heading is a caption of four kinds (Grid, Label, Dropdowns, YearDropdown). Presets: Calendar.lastDays, nextDays, monthOf, day, drawn by Calendar.presetsView.

A DatePicker also picks a whole Calendar.Selection. Fold it with DatePicker.update(selection, closes?), given the selection the application keeps: upstream closes the popover on every day picked, and this keeps it open while the day leaves the selection unfinished (a range's first end, any day of a Multiple selection), reporting SelectedDate either way for the application to fold through Calendar.picked. Draw it with DatePickerView.view taking selection and triggerContent: selection => Html in place of upstream's maybeSelectedDate and triggerContent, and toCalendarView: Calendar.toView(selection, mixins, { h }). Its toView takes no builder of the application's: DatePicker.toView(mixins, (resolved, h) => …) hands draw the date picker's builder. Under name, each chosen day is a hidden input of its own, in order (a range's start, then its end), so FormData.getAll(name) reads [start, end]; nothing chosen submits the name once, empty.