Mixins / foldkit-mixins-ui

Mechanisms shared by many widgets

Each of these is described here once; the catalog rows link to it.

Application key routes

A widget's own keys are Behaviors.Keys routes on one keydown owner, and the widgets below take a routes option for keys the application answers itself (F2 renaming a tab, Ctrl+A choosing every option, ArrowDown opening results). A route is built with Keys.route(name, { on: [Keys.chord('ArrowDown')], handle }) from foldkit-mixins' Behaviors: handle receives the press (key, modifiers, the widget's input and, for a repeated slot, item) and returns an Option of a Message, or of Keys.focus(id, message) to move focus as well; Option.none() declines the press.

A route on a gesture another route on the same owner already takes throws mixins:key-conflict, naming both. Keys.first(a, b) is the way to let two routes declare one chord: a is asked first, and b only when a does not take the press or declines it.

WidgetWidget keysRoute input
CommandArrows, PageUp/PageDown, Enter (Home/End stay in input)CommandKeyInput (query, active row, visible rows)
SearchFieldEscape (when text is non-empty)Current field text
MenubarArrows, Home, EndNot read
CascadeSelectArrows, Home, End, Enter, Escape, printable keys (open panel)undefined
TourArrows, Escape (unless closeOnEscape: false)undefined
FloatingPanelEscape (unless closeOnEscape: false); drag/corner arrowsundefined
PickerArrows, Home, End on Sheet options (item.index)undefined
NavTop-level links (routes) and panel links (panelRoutes)Entry or link, item.index
TabsDelete when closable (TabsContext.routes)TabInfo
TagsInputEnter, delimiter, BackspaceTagsInput.Model
FileUploadEnter, Space, Backspace, Delete (check via conflict)FileUpload.Model
ToolbarArrows, Home, Endundefined
ts
// ArrowDown asks the first route; when there is no text to search for it declines, and
// the second moves focus into the results list and sends the same Message.
const toResults: SearchField.Route<Search> = Keys.route('Focus results', {
  on: [Keys.chord('ArrowDown')],
  handle: () => Option.some(Keys.focus('results', Search.OpenedResults())),
})

const searchWithFocus = (text: string, h: HtmlBuilder<Search>) =>
  SearchField.view(
    {
      id: 'find',
      label: 'Search products',
      value: text,
      onInput: text => Search.Typed({ text }),
      clear: { onClear: Search.Cleared() },
      routes: [Keys.first(openResults, toResults)],
    },
    h,
  )

Checking routes without drawing

Each of these widgets exports conflict(routes, input?): the mixins:key-conflict that drawing it with routes would throw, as an Option of the diagnostic, for a screen where a user rebinds keys and the candidate set must be judged before anything is drawn. It asks Keys.conflict of the widget's own routes and routes together, the own routes being the list the view itself draws, so it names the same two routes the view would, and also reports two application routes on one gesture. It reads gestures only: no handler runs and nothing is drawn.

input is the part of the view's options that decides which keys the widget owns, with the view's defaults. A widget whose own keys never vary takes routes alone. One that draws nothing while closed (Tour, FloatingPanel, the CascadeSelect panel) is checked as open, since a route that clashes in any state is a clash.

Widgetinput
Command, SearchField, CascadeSelect, Pickernone
Menubar{ direction? } ('rtl' swaps which arrow route is named)
Tour, FloatingPanel{ closeOnEscape? } (Escape reserved unless false)
Toolbar{ orientation? } (default 'horizontal')
Tabs{ close? } (Delete reserved when closable)
TagsInput{ delimiter?, direction? } (default ',')
Nav{ panelRoutes? } (checks top-level and panel link keys)
ts
// Escape is the field's own key, so this candidate is refused with the diagnostic that
// drawing the field with it would throw; a free key gives `Option.none()`.
const candidate: SearchField.Route<Search> = Keys.route('Open results', {
  on: [Keys.chord('Escape')],
  handle: () => Option.some(Search.OpenedResults()),
})
const refusal = Option.map(SearchField.conflict([candidate]), diagnostic => diagnostic.message)

Focus after removal

When the element that held focus leaves the page, the browser drops focus to body. Three mechanisms keep it, all opt-in because none sends a Message, which a Scene test of every page drawing the widget would otherwise have to resolve.

  • A neighbour takes it (FocusRecovery, from foldkit-primitives/interaction). FocusRecovery.behavior(Slots)({ owner, parts, parent? }) on the slot that holds the repeated items (the owner) marks each parts slot and names where focus goes when that part is removed, hidden, made inert or disabled: steps tried in order (same, next, previous, parent, stop, { part }, owner) until one can take it, and focus that was moved elsewhere is never taken. The widgets that draw a removable control take the part's name: recoveryPart on Alert and Card marks their dismiss button, and Toast.keepFocus is such a behavior on the toast container: from a dismissed toast's close button focus goes to the close button of the toast behind it, else the one in front, and from an action to a neighbour's action, else a close button; with no toast left, focus is not moved. Without recoveryPart, dismissing one drops focus to the page.
  • The opener gets it back (focusReturn). Dialog.focusReturn, Tour.focusReturn and FloatingPanel.focusReturn (a Sheet takes the Dialog's) give focus back to what had it before the widget opened, by FocusReturn's rules when that is gone: an element with the opener's id, its FocusRecovery fallback steps, the dialog below, then the page's first tabbable element. The Tour and the FloatingPanel keep no opener of their own; upstream's Dialog return goes to the opener and, with none, to body.
  • A control takes it (keepFocus, a Command). Drawer.keepFocus moves focus to the handle when the drawer closes with focus in its body, which the hidden body would otherwise drop to the page. SearchField.Focus and FileInput.Focus put focus back on the input after the button that held it left, and TagsInput.update returns a focus Command after a removal. FileUpload.update does the same: the next entry's remove button, else the previous, else the input, and after a retry the entry's remove button; FileUploadSort.keepFocus (opt-in, in mixins) covers what no widget Message causes.
ts
import { Alert } from 'foldkit-mixins-ui'
import { FocusRecovery } from 'foldkit-primitives/interaction'
import { Capability, Slot, Slots, SlotView } from 'foldkit-mixins'

const Container = Slot.make({ capability: Capability.Container })
const AlertListSlots = Slots.define({ list: Container, item: Container })
const Dismissal = defineMessageUnion({ Dismissed: { name: Schema.String } })
type Dismissal = typeof Dismissal.Type

// Dismissing an alert hands its focus to the next one, else the previous one.
const alertList = (names: ReadonlyArray<string>, h: HtmlBuilder<Dismissal>) => {
  const builders = SlotView.buildersFor(
    AlertListSlots,
    [
      FocusRecovery.behavior(AlertListSlots)<undefined, Dismissal>({
        owner: 'list',
        parts: { item: ['next', 'previous'] },
      }).mixin,
    ],
    { input: undefined, h },
  )
  return h.div(
    builders.list.attrs(),
    names.map(name =>
      h.keyed('div')(
        name,
        [],
        [
          Alert.view(
            {
              layout: 'inline',
              title: name,
              onDismiss: Dismissal.Dismissed({ name }),
              recoveryPart: 'item',
            },
            h,
          ),
        ],
      ),
    ),
  )
}

Form participation

Widgets that carry a value take name and put it where a form reads it, so a form that submits natively needs no hand-drawn input:

WidgetWhat name submits
Input, Textarea, PasswordInputText value (supports native required, autocomplete)
NumberFieldFormatted display text
OtpFieldCode string
Slider, AngleSliderSlider value(s) or hidden angle input
RatingNative radio value (name defaults to id)
CheckboxGroupOne hidden input per checked value, in order
SegmentedOne hidden input per chosen value, in order
TagsInputOne hidden input per tag (excludes draft)
CascadeSelectOne hidden input per path level, or one empty input
DatePickerOne hidden input per chosen day (start then end)
FileInputNative file input kept synced via FileInput.Sync
FileUploadNative file input synced for local files via Sync
Checkbox, Switch, RadioGroup, Listbox, ComboboxVia their hiddenInput / hiddenInputs Slots

A disabled Button is aria-disabled, not disabled, and still submits: refuse the submit in update.

What reaches server markup is data, not closures. A page that answers before its script runs (foldkit-ssr's resumable pages) cannot write a closure into the server's markup. There, give onInput the OnInput attribute the resumable builder makes from a Message member; the view adds it as it would the closure, and KeepTyped keeps what is typed before the script runs:

ts
import { Resume } from 'foldkit-ssr/client'

const resumableEmail = (value: string, h: HtmlBuilder<Message>) => {
  const rh = Resume.builder(h)
  return Input.view(
    {
      id: 'email',
      value,
      onInput: rh.OnInput(Message.TypedEmail),
      type: 'email',
      draw: ({ input, label }) =>
        rh.div([], [rh.label(label, ['Email']), rh.input([...input, rh.KeepTyped()])]),
    },
    rh,
  )
}

PasswordInput draws its own input, so KeepTyped goes in its attributes, which adds to a Slot before the mixins resolve. Give it only while the field is enabled: a disabled field sends nothing, and the server refuses a kept field with nothing to replay (UnkeepableField).

ts
import { PasswordInput } from 'foldkit-mixins-ui'

const resumablePassword = (password: string, shown: boolean, h: HtmlBuilder<Message>) => {
  const rh = Resume.builder(h)
  return PasswordInput.view(
    {
      id: 'password',
      label: 'Password',
      value: password,
      onInput: rh.OnInput(Message.TypedPassword),
      visible: shown,
      onToggle: Message.ToggledPassword(),
      attributes: { input: [rh.KeepTyped()] },
    },
    rh,
  )
}

Right to left

Logical properties carry most of the recipes, and a few things follow the direction explicitly:

  • A direction view option. Menu, Menubar, Nav, TreeView, Resizable, Segmented, Toolbar, TagsInput, CascadeSelect, FloatingPanel, Tour, Sidebar and a horizontal Listbox take direction?: 'ltr' | 'rtl' (a Toast stack takes it in init). Under 'rtl' the view swaps ArrowLeft and ArrowRight before building its Message, so Messages and update stay in reading order, and draws the direction as its root's dir, so the CSS (a submenu's side, a chevron) reads what the keys read. Unset, the keys read left to right and the page's dir stands.
  • readingKeys for upstream's keys. Tabs, RadioGroup and Calendar handle their arrows in upstream bundles no view option reaches, so Tabs.readingKeys, RadioGroup.readingKeys and Calendar.readingKeys, passed beside the style, are a Mount that reads each arrow by the element's own :dir() before upstream's handler sees it. They are opt-in for the reason fluid is (see Fluid highlights). RadioGroup.readingKeys reads both arrow pairs whichever way the group stands (ArrowRight and ArrowDown go on, ArrowLeft and ArrowUp back; the horizontal pair swapped on a right-to-left page).
  • Indicators. Segmented.fluid, Tabs.fluid and Nav.fluid measure their indicator again when a dir anywhere in the document changes, since flipping it moves the items without resizing anything.
ts
const TabsStyle = Recipes.Tabs.style()

Tabs.toView([TabsStyle.mixin, Tabs.readingKeys], { h }, ({ tablist, tabs }) =>
  h.div(tablist, tabs.map(tab => h.button(tab.tab, [tab.value]))),
)

Exits and reduced motion

A popup or dialog enters and leaves when drawn with @foldkit/ui's isAnimated (Menu.init(id, rows, { isAnimated: true }), a Popover's isAnimated): a popup fades and grows on the fast tier, from the side its anchor placed it on, and a dialog on the slow one, each leaving on the quicker exit. A leaving Dialog is drawn inert with isLeaving: Dialog.isLeaving(model) in its context, and the Sheet does so itself; a Disclosure's animatePanel moves the panel's height, which the recipe scales by the motion knob. Recipes.Dialog({ motion: 'none' }) (and the Sheet's) opens, closes and steps back at once.

Durations are the theme's: the motion knob multiplies them ('0' stills every recipe transition), and a duration of something that moves or resizes is also multiplied by travel, which reduced motion zeroes so that fades stay. A Marquee's viewport scrolls instead of moving under reduced motion, a ThinkingIndicator holds every movement, and a Carousel's init takes the application's reading of prefers-reduced-motion and starts an autoplaying carousel stopped.

Fluid highlights

Tabs, Segmented, Nav, Sidebar, TreeView, Menu, Listbox and Combobox take a fluid mixin list beside the style that glides one highlight, or an indicator, to the item the pointer is near and back to the chosen one; a Table and a Card group take fluid: Table.fluid and fluid: Card.fluid, values passed the same way. A Mount does the measuring and moves it. It is off by default because a Scene test resolves every Mount with a Message and these send none, so a default would burden the tests of every page that drew one; the same reason makes readingKeys, keepFocus, focusReturn, keepActiveInView and the overlayBars opt-in mixins.

Tabs.fluid measures the chosen tab on the tablist (Measure) and moves one highlight to the tab nearest the pointer (FluidHover), born at the chosen tab and returning to it:

ts
Tabs.toView([TabsStyle.mixin, ...Tabs.fluid], { h }, ({ tablist, indicator, highlight, tabs }) =>
  h.div(tablist, [h.div(indicator), h.div(highlight), ...tabs.map(tab => h.button(tab.tab, [tab.value]))]),
)

The recipe draws the line variant's rule or the pill variant's pill on the indicator, which springs to a new choice, and dims the pill while another tab is hovered. Until Tabs.fluid runs, as before a page hydrates, the indicator and highlight show nothing and the chosen tab marks itself: the recipe reads the data-fluid-hover attribute FluidHover sets while it runs.

Menus, listboxes and comboboxes draw their panels in the palette's popup tokens, so a theme's menu: { accent, color } (a bold accent row; a panel on the page's surface by default, or inverted or translucent) restyles all three, and they take Menu.fluid, Listbox.fluid and Combobox.fluid beside the style in toView. The open panel's rows sit in a rows box of this package's (the panel carries upstream's anchor, and an element holds one Mount), with a highlight first in it that follows the pointer, and the keys, which mark a row data-active; a listbox or combobox adds an indicator that glides to the chosen row. The default draw places all three, and the rows drop their own hover and chosen fill while the highlight runs. A press in a gap presses the lit row, except in a combobox, whose field keeps focus.

ts
const MenuStyle = Recipes.Menu.style()

Menu.toView([MenuStyle.mixin, ...Menu.fluid], { h })

Overlay scroll bars

The scrolling recipes share one overlay bar, after Fluid Functionalism's: a 10px bar over the scroller's edge holding a thumb that rests 4px wide in a faint ink of the text, 2px off the edge, widens to 6px under the pointer and darkens while dragged. It fades in on motion.moderate while the box scrolls or the pointer moves over it, and out on moderate-exit once both rest, after a moderate delay that lets a widened thumb narrow first. The widening travels, so reduced motion keeps the fades alone. ScrollBars from foldkit-primitives/dom drives it and sends no Message; the bar is how it looks, the Mount only where the box is scrolled. On a coarse pointer the Mount does nothing, and the browser's bar, with its physics, stays; before it runs, as before a page hydrates, so does the browser's bar.

Every one is the same shape, a mixin list passed beside the style: ScrollArea.overlayBars, Command.overlayBars, Dialog.overlayBars and VirtualList.overlayBars in the view's mixins, and Menu.overlayBars, Listbox.overlayBars and Combobox.overlayBars in toView's for a popup whose list scrolls: upstream draws that scroll region only when given itemsScrollClassName or itemsScrollAttributes, and its class joins the recipe's.

ts
const ListboxStyle = Recipes.Listbox.style()

ScrollArea.view(
  {
    content: h.p([], ['A long text']),
    style: Recipes.ScrollArea.style(),
    mixins: ScrollArea.overlayBars,
  },
  h,
)
Listbox.toView([ListboxStyle.mixin, ...Listbox.fluid, ...Listbox.overlayBars], { h })

The bar is a Slot of each component's own (bar and thumb; a popup's scrollBar and scrollThumb), beside the scroller rather than inside it, so the scroller's edge fade does not erase it. ScrollArea, Command and VirtualList always draw it, and a popup whenever its panel has a scroll; the recipe leaves it undrawn until ScrollBars marks it scrollable. A ScrollArea also marks an edge with more past it with a hairline (Utilities.scrollDivider on root, Utilities.scrollTimeline on viewport), drawn where the browser lets a parent read a child's scroll timeline (timeline-scope).

The top layer

The panels of Menu (submenus included), Menubar, Listbox and Combobox that stay where they are drawn (an anchor's portal: false) draw in the browser's top layer, so no stacking context or ancestor overflow reaches them. Such a panel carries popover="manual", and its anchor Mount is wrapped in Anchor.topLayer, which shows the panel as a popover around the Mount's own acquire and hides it once the Mount releases; the wrapper keeps the Mount's name, args and Messages, so a Scene test still resolves it, and the node stays where the runtime drew it. Light dismiss stays the application's Messages.

  • The panel sets inset: auto: the anchor writes only left and top, and the browser's inset: 0 would otherwise leave right: 0 winning right to left.
  • An unstyled panel keeps the browser's popover border, padding and Canvas fill. Every recipe's panel replaces them; an inline reset would beat the recipes.
  • Anchor.topLayer does nothing where the popover API or the element's popover attribute is missing (jsdom, a server render, a panel drawn without it), and the anchor places the panel in the page.
  • A panel that upstream portals keeps upstream's behavior, since moving a shown popover hides it again.

Popover, Tooltip and Hover Card are drawn by upstream views whose Mounts this package cannot wrap, so their panels go in the top layer another way: Anchor.layer(h), the layer slot of PopoverSlots and TooltipSlots, is an element drawn around the panel that shows itself as a popover, and the panel inside keeps upstream's anchor (Popover.anchor() and Tooltip.anchor() give portal: false and the placement: 12px and 8px off the trigger, 8px inside the viewport, flipping and shifting). A Hover Card's panel is anchored in the top layer by HoverIntent.toView(mixins, { h, anchored: { id, anchor? } }, draw), which gives the trigger HoverIntent.triggerId(id). The DatePicker's panel and modal dialogs are not in the top layer.

A box of your own whose Mount is not TopLayer takes Anchor.layerBox(h, style?): the same box without the Mount, for a Mount wrapped in Anchor.topLayer that sends Messages (Cascade Select's and Tour's do), so a Scene test can resolve it. Its inline style takes style too, since a second h.Style on the element would replace the first.

The popups' recipes take a width axis. trigger sets the panel's minimum width to its trigger's (--button-width, which upstream's anchor publishes once it has placed the panel), in place of the panel's 14rem minimum, so a narrow trigger gets a panel as narrow; auto keeps the 14rem. Combobox defaults to trigger, Listbox to auto.

Accessibility patterns

Every adapter has an A11y.pattern beside its Slots, under Patterns: the slots a widget of that kind must publish and what each must expose. The catalog lists them with a tier (stateful for a Submodel, stateless for a decorated native control), the ARIA roles involved, and the platform floor: what the widget relies on the browser for (focus-trap, escape-dismiss, top-layer, form-submission, ...), so nothing here reimplements it and a reader or an agent can ask.

ts
import { A11y, Capability, Slot, Slots } from 'foldkit-mixins'
import { Patterns } from 'foldkit-mixins-ui'

const MyTabsSlots = Slots.define({ tablist: Slot.make({ capability: Capability.Container }) })

A11y.validate(Patterns.Tabs, MyTabsSlots) // [] when a custom tabs view publishes what tabs need
Patterns.catalog.find(entry => entry.name === 'dialog')?.floor // ['focus-trap', 'escape-dismiss', ...]

A test iterates the catalog and validates each adapter's own Slots and support against its pattern, so an adapter cannot drift from the contract it claims. The patterns are written separately from the Slots, which is what makes the check mean something.

Where a pattern names obligations (who navigates, who makes an item reachable, who activates it, who names it), the entry's support lists who provides each: Mixins that contribute nothing, made with A11y.base (the widget's own markup or the upstream bundle it draws, named by source file) or A11y.native (what a native element does by itself). An adapter draws through resolveFor, so it has no view for A11y.check to read; the gate attaches support to a view over the adapter's Slots and check judges it, so an obligation nobody provides is a failure, and so is a provider nothing needs. These are claims found in source, not a rendered check; the rendered check is Conformance from foldkit-mixins/testing. Pagination, breadcrumb, table, scroll area, drawer, hover intent, picker, button group, window list, card, search field, toolbar and file input are in the catalog beside the older widgets, and a published *Slots that is neither in the catalog nor on the gate's list of Slots with nothing to require fails the gate. None of this is a WCAG claim.

Touch targets and icons

Touch and Icons are style mechanisms, not components: no slots, no views. Compose them into your own slots. The recipes' own controls already stand 44px tall where the pointer is coarse: Defaults.reset sets --fk-touch-floor there, and a control's height on the size ladder is at least that (a region that must stay dense sets it to 0px). For your own slots, Touch.target floors one control at 44px where the pointer is coarse; Touch.targets floors every boxed control a region draws. Icons.glyph(size) draws the icon in --icon before the element's words, and Icons.byAttribute(attribute, icons) sets --icon from an attribute's value, where icons maps each value to its resolved url(…):

ts
import { Layers } from 'foldkit-mixins'

const TileSlots = Slots.define({ tile: Slot.make({ capability: Capability.Container }) })

const TileStyle = Style.forSlots(TileSlots)(
  {
    tile: Style.compose(
      Touch.target,
      Icons.glyph('1rem'),
      Icons.byAttribute('data-block', { Hero: iconUrl('hero') }),
    ),
  },
  { layer: Layers.standard.layer('app') },
)

The icons the components draw themselves (a search field's magnifier, a toast's mark, a locked cell's padlock) are the theme's icon tokens: Heroicons' outline set (MIT), restroked to 2px, by default. An application's own pack replaces them as its own tokens: AppStyle.make({ theme, tokens: Icons.tokens(pack, { width?, corners? }) }), where pack holds an IconData for each name the components draw (ChromeIcon from foldkit-mixins/theme; one missing is a type error), and the stroke is redrawn into each mask, which CSS cannot reach once it is a url().