Mixins / foldkit-mixins-ui
One factory for each part
A widget's look, state, drawing and features each have one place they are given (Look, state, drawing, features). This section shows each with code.
State: fold it by hand, or place a Bundle
A stateful widget exports Model, Message, init and update. The
application keeps the Model in a field of its own, wraps the widget's Messages
in one of its own, and folds them. Written out, for a field of tags:
import { Schema } from 'effect'
import * as Command from 'foldkit/command'
import type { Html, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import type { Return } from 'foldkit/update'
import { TagsInput } from 'foldkit-mixins-ui'
const Model = Schema.Struct({ labels: TagsInput.Model })
type Model = typeof Model.Type
const Message = defineMessageUnion({ GotLabelsMessage: { message: TagsInput.Message } })
type Message = typeof Message.Type
export const initial: Model = {
labels: TagsInput.init({ id: 'labels', tags: ['urgent'], max: 3 }),
}
export const update = (model: Model, message: Message): Return<Model, Message> =>
Message.match(message, {
GotLabelsMessage: ({ message }) => {
const result = TagsInput.update(model.labels, message)
// The field's own Commands (it refocuses after a removal) speak its Messages.
const commands = Command.mapMessages(result.commands, message =>
Message.GotLabelsMessage({ message }),
)
// Nothing changed: hand back the Model given, so nothing is drawn again.
return result.model === model.labels
? { model, commands }
: { model: modifyFields(model, { labels: () => result.model }), commands }
},
})
export const view = (model: Model, h: HtmlBuilder<Message>): Html =>
TagsInput.view(
{
model: model.labels,
onMessage: message => Message.GotLabelsMessage({ message }),
label: 'Labels, up to three',
},
h,
)That is the whole of it, and for a page with one or two widgets it is the
smaller choice: it adds nothing to the bundle. Bundles.X is the same init
and update packaged for
foldkit-bundle,
which derives the field, the wrapper Message and the fold above from one
placement:
import type { Html, HtmlBuilder } from 'foldkit/html'
import { Bundle } from 'foldkit-bundle'
import { Bundles, TagsInput } from 'foldkit-mixins-ui'
const App = Bundle.compose({}).pipe(
Bundle.withChild('labels', Bundles.TagsInput, {
args: { id: 'labels', tags: ['urgent'], max: 3 },
}),
)
type Model = typeof App.Model.Type
type Message = typeof App.Message.Type
const view = (model: Model, h: HtmlBuilder<Message>): Html =>
TagsInput.view(
{
model: model.labels,
onMessage: message => App.Message.GotLabelsMessage({ message }),
label: 'Labels, up to three',
},
h,
)
export const config = App.placements.runtime({ Model: App.Model, initial: {}, view })The first placement costs a page about 6 kB (brotli) of foldkit-bundle; the
second and every later one share it. foldkit-bundle is a peer dependency:
install it when you place a Bundle, and a page that folds by hand never loads
it.
- A Bundle is headless. It holds no view; draw the placed Model with the
widget's
view. - Its
argsareinit's options, checked by a Schema and given toupdatetoo. Bundlesis a namespace of one file per widget, asRecipesis, so readingBundles.TagsInputkeeps that file and no other Bundle.
Who owns the value follows from its type. Where the value's type is the
widget's own (a TagsInput's tags), the Bundle holds it and the application
reads it from the placed Model, model.labels.tags. Where the type is the
application's (the items of a Combobox), the application keeps the value in
its own field and the Bundle holds only the interaction: open or closed, the
row the keys are on, the text typed. A Choice says how that field is read
and folded, and the Bundle reports each change for the application to answer:
import { Schema } from 'effect'
import { Bundle } from 'foldkit-bundle'
import type { Html, HtmlBuilder } from 'foldkit/html'
import { Bundles, Combobox } from 'foldkit-mixins-ui'
const cities = ['Lisbon', 'Porto', 'Faro'] as const
const City = Combobox.one(cities)
const App = Bundle.compose({ city: Schema.Option(Schema.Literals(cities)) }).pipe(
Bundle.withChild('cityBox', Bundles.Combobox, {
args: { id: 'city' },
// `out` is a `ChoiceChange`; `City.picked` looks the reported value up
// among `cities`, so `city` stays an `Option` of one of them.
onOut: out => model => ({ model: { ...model, city: City.picked(model.city, out) } }),
}),
)
export const initial = App.placements.initial({ city: City.empty })
// The same `Choice` reads the field for the drawing: the chosen row, the resting text.
export const cityField = (model: typeof App.Model.Type, h: HtmlBuilder<typeof App.Message.Type>): Html =>
Combobox.view(
{
model: model.cityBox,
onMessage: message => App.Message.GotCityBoxMessage({ message }),
label: 'City',
choice: City,
value: model.city,
filter: Combobox.contains,
clear: true,
},
h,
)Combobox.one(items) holds an Option of an item, Combobox.many(items) a
list of them in the order chosen (place the Bundle with multiple: true, which
its update reads: choosing leaves the list open), and Combobox.text(items)
the typed text itself, with the items as suggestions. Each is a file of its
own. Choice is an interface you may implement; a rule of your own usually
wraps a shipped one:
import { Combobox, type Choice } from 'foldkit-mixins-ui'
/** At most three: a fourth choice leaves the value as it was. */
export const upToThree = <Item extends string>(
items: ReadonlyArray<Item>,
): Choice<Item, ReadonlyArray<Item>> => {
const many = Combobox.many(items)
return {
...many,
picked: (value, change) => {
const next = many.picked(value, change)
return next.length > 3 ? value : next
},
}
}Where the value's type is the widget's own and a parent usually acts on a
change, the Bundle reports it. A Calendar holds its Selection and reports
Changed, which a placement answers or ignores by name:
import { Option } from 'effect'
import { Bundle } from 'foldkit-bundle'
import * as Dates from 'foldkit/calendar'
import type { Html, HtmlBuilder } from 'foldkit/html'
import { Bundles, Calendar } from 'foldkit-mixins-ui'
const today = Dates.make(2026, 2, 11)
const App = Bundle.compose({}).pipe(
Bundle.withChild('trip', Bundles.Calendar, {
// The selection's tag is the mode; `months: 2` draws two side by side.
args: { id: 'trip', today, selection: Calendar.empty('Range'), months: 2, minDate: today },
// `Changed` carries the new selection; this page only reads it from the Model.
onOut: Bundle.ignore,
}),
)
type Model = typeof App.Model.Type
type Message = typeof App.Message.Type
export const nights = (model: Model): number =>
Option.match(Calendar.rangeOf(model.trip.selection), {
onNone: () => 0,
onSome: ({ start, end }) => Dates.daysUntil(start, end),
})
export const view = (model: Model, h: HtmlBuilder<Message>): Html =>
Calendar.view(
{
model: model.trip,
onMessage: message => App.Message.GotTripMessage({ message }),
label: 'Trip dates',
presets: [{ label: 'Next week', selection: Calendar.nextDays(today, 7) }],
today: { label: 'This month' },
footer: h.p([], [`${nights(model)} nights`]),
},
h,
)Combobox.view(options, h) takes that choice and the value, and draws
the rest from data:
- Rows.
option: item => RowContentgives a row itslabel(which also names a chip and the resting text),description,icon,trailing,contentin the label's place, anddisabled; without it a row is its item.itemsnarrows what is offered now (a fetched page);filterkeeps the rows whose label matches the typed text, withCombobox.containsandCombobox.startsWithshipped as values, so a page that fetches for the text ships neither.groupByandheadinggroup adjacent rows. - The field.
placeholder,empty(drawn in the list's place),clear(truefor a button with a drawn cross, or{ content }),chipsfor a choice of several,buttonContent,disabled,invalid,readOnly,name,openOnFocus,anchor, andwords(clear,remove, the second with{label}). - Clearing empties the field's text through the Combobox's own Message.
The value follows through the
Choice:Combobox.texttakes the empty text, and a combobox placed withnullable: truereportsClearedSelectionwhen an emptied field is left. - A value chosen before the page drew needs the Bundle's
textarg (the chosen row's label), since upstream writes the resting text only as the field is left. Combobox.configure({ base, presets })bindsfilter,placeholder,chips,openOnFocus,anchor,words,style,mixinsandclear: true.Combobox.fluidandCombobox.overlayBarsare files of their own: a page that passes neither ships neitherFluidHover,MeasurenorScrollBars.
The toView adapter and the ComboboxView bundles stay as the rung below.
Listbox.view(options, h) and Picker.view(options, h) take the same choice and
value and the same option, groupBy, heading, items, placeholder,
disabled, invalid, name and words (clear, the button's name), over
Bundles.Listbox and Bundles.Picker: a Listbox's Listbox.one(items) or
Listbox.many(items) (multiple: true in the Bundle's args, since choosing
leaves a multiple list open), a Picker's Picker.one(items). The value is the
application's, so clear is { onClear, content? }: the button sends the
application's own Message, which empties the field through the same choice
(ChoiceChange.ClearedSelection()). Listbox.fluid and Listbox.overlayBars are
files of their own, like the Combobox's.
Drawing: configure once, call with what differs
X.configure({ base, presets }) returns the widget's own view, bound to
options an application would otherwise repeat at every call: its compiled
style, its words, its mixins, its structural choices.
import type { Html, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { Button, Recipes } from 'foldkit-mixins-ui'
const Message = defineMessageUnion({ Saved: {}, Deleted: {} })
type Message = typeof Message.Type
// Styles are compiled once, in a module the build may ship as data.
const Quiet = Recipes.Button.style({ tone: 'neutral', variant: 'outline' })
const Danger = Recipes.Button.style({ tone: 'danger' })
export const AppButton = Button.configure({
base: { style: Quiet },
presets: { danger: { style: Danger } },
})
export const actions = (h: HtmlBuilder<Message>): ReadonlyArray<Html> => [
AppButton.view({ label: 'Save', onClick: Message.Saved() }, h),
AppButton.view({ label: 'Delete', preset: 'danger', onClick: Message.Deleted() }, h),
]- The order is
base, the named preset, the call. A later one wins per option, so a style given at the call replaces the preset's. Two options merge instead:mixinsconcatenate in that order, andwordsmerge word by word. An option given asundefinedis not given. - The preset names are the keys you wrote.
preset: 'dangr'is a type error, andpresetis no option at all wherepresetswas left out. A name computed at run time that matches none throws, naming the ones declared. - A preset holds what takes no Message and no state:
style,mixins,wordsand each widget's own list (typefor a Button;placeholder,addOnBluranddirectionfor a TagsInput;weekNumbers,caption,paging,today,presetsanddetailfor a Calendar;filter,placeholder,chips,openOnFocus,anchorandclear: truefor a Combobox).onClick,onMessage,model,labeland anything drawn (icon,aside,footer) stay at the call. - A preset may hold behaviour. A mixin with a Mount given in a preset attaches to every use of that preset, and the page ships that Behavior only because the application's own module imported it. A Mount that sends no Message has to be resolved by the application's Scene tests of every page that draws the preset.
- It holds no state. A widget's starting values are
init's options, or a Bundle'sargs.
Look: recipe modules hold style and nothing else
A shipped recipe module imports style code only: foldkit-mixins styles,
theme references, other recipes' pieces, icon masks. It never imports a
widget, a Behavior or anything with a Mount, which is what lets a build
evaluate a style module and ship class names in its place
(Style modules shipped as data).
An axis selects what CSS can express over the same markup. A choice that
changes the markup is a view option, which the view writes as a data-*
attribute for the recipe to read. A look a shipped recipe lacks is added to
it, not forked from it:
import { Style } from 'foldkit-mixins'
import { Recipes } from 'foldkit-mixins-ui'
const Buttons = Recipes.Button.add({
tone: { brand: { button: Style.self({ background: 'rebeccapurple', color: 'white' }) } },
})
export const Brand = Buttons.style({ tone: 'brand', variant: 'solid' })