Primitives / Interaction

Finding and moving

Typeahead is type-to-find for a host that has no roving tab stop, or whose focus is managed elsewhere. The Model slice is { query, generation }: printable keys extend the query, a timer of timeoutMs on Effect's clock clears it (generation lets a superseded timer change nothing), and Cleared drops it on purpose. Which item a query picks is the pure Typeahead.match(texts, enabled, query, current): one character, or one character repeated, starts after the current item so repeated presses cycle; a longer query starts at it, since the user is refining. Case and leading whitespace are ignored and disabled items are skipped. The Behavior, Typeahead.behavior(Declared)(Slots)<Model, Message>({ host, items, text, current }), gives the host OnKeyDownFocus: a printable key with no ctrl, alt, or meta extends the query, focuses the match by id, and dispatches Typed; with no match the key is still recorded and focus stays put; a space with an empty query is left to the host.

ListNavigation is what a list host takes when it wants both: arrows, Home, End, PageUp and PageDown by page, and typeahead, in one placement. It exists for two reasons. The resolver allows one owner per event on a slot, so RovingTabindex and Typeahead cannot both own the host's OnKeyDownFocus; and under virtual a typed key must move the pointer and extend the query in one transition, which two placements cannot do. Its Model slice is { current, query, generation }, its args are RovingTabindex's plus timeoutMs and page, and its Behavior takes { container, item, items, text, direction?, typeahead?, commit? }. typeahead: false leaves printable keys to the container (a search field); arrows still move the pointer. commit(input, id) runs on unmodified Enter when current is an enabled item and returns that parent Message from the same handler, so the field does not grow a second key listener. Typed { char, match } carries the item the query now picks, so update sets current and query together.

ts
import { ListNavigation } from 'foldkit-primitives/interaction'

const Nav = Bundle.declare(ListNavigation.bundle, 'nav')
const navArgs = { orientation: 'vertical', loop: false, virtual: false, timeoutMs: 500, page: 10 } as const
const Keys = ListNavigation.behavior(Nav, navArgs)(ListSlots)<ListModel, ListMessage>({
  container: 'list',
  item: 'option',
  items: model => describeFruits(model.fruits),
  text: (model, index) => model.fruits[index]?.label ?? '',
})

Routes. RovingTabindex, ListNavigation, GridNavigation, TreeNavigation and Typeahead each export keys, the route their Behavior installs as the container's one keydown handler (and SpinValue.keys in foldkit-mixins). keys takes the same placed Bundle and args as behavior, then the options without the slot names, and returns a Keys.route, so a field that also wants Escape to clear lists it beside its own route in one Keys.behavior instead of failing mixins:event-conflict. A route declares the chords it takes, each with Shift up and down (the moves ignore Shift), so Keys.chord('ArrowDown') beside ListNavigation.keys throws mixins:key-conflict at definition, and ListNavigation.keys declares every printable key unless typeahead is false. Under virtual the route answers the Message alone; otherwise it also moves focus to the item. A Keys.behavior writes only keydown: the router's slot gets none of the primitive's other attributes. ListNavigation.item(Nav, args)(Slots)({ item, items }) is its item half, each item's tab stop and the OnFocus reporting it current; for the other primitives draw RovingTabindex.itemAttributes on the items. Draw aria-activedescendant on the container yourself under virtual, or attach the primitive's own behavior when no other route shares its slot.

GridNavigation is the two-dimensional counterpart for cells laid out in rows of columns (a calendar grid, a swatch picker, an emoji palette). Its Model slice and item attributes are RovingTabindex's, so the two are interchangeable on a view; only the pure move differs. Left and right step within the row and up and down within the column, skipping disabled cells; under wrap a horizontal key continues into the next row and a vertical key into the next column, otherwise the key is consumed at the edge. Home and End are the row's first and last enabled cell, Ctrl+Home and Ctrl+End the grid's. RTL swaps left and right, and virtual works as it does for RovingTabindex. Given a page in its args, PageUp and PageDown move that many rows (at the same column, stopping at the first and last row); without one they are left to the page. routes, an option of GridNavigation.behavior as of InlineEdit.behavior and Tabs, are the application's keys (Space, Ctrl+A) on the grid's one keydown owner: the grid answers its own keys, then yours, and a route on a key the grid takes, Shift+arrow included, throws mixins:key-conflict at definition, naming both.

SpatialNavigation is arrow keys over freely placed items (a board, a canvas, a dashboard of cards), where there are no rows or columns: each arrow moves the one tab stop to the nearest item drawn in that direction, measured when the key is handled and never kept, so an item that moved between two presses is found where it is now. The rule is the pure nearest(items, current, direction), and directions are physical (left is left in a right-to-left page). Its Model slice and item attributes are RovingTabindex's. Like RovingTabindex it provides A11y.Navigation on the container and A11y.FocusStrategy on each item. Its one arg, id, names the board on the page, so two boards each find their own items.

The item slot must have Capability.Focusable, since each item takes the tab stop and focus; a slot of another capability (a Container) throws mixins:capability-mismatch (Behavior requires capability "Focusable" on slot "card", which has "Container") when the Behavior is defined. A Container or an Interactive slot is fine for the container. A card that Selection also drives takes Focusable too, which satisfies Selection's Interactive item.

ts
import { SpatialNavigation } from 'foldkit-primitives/interaction'

const Board = Bundle.declare(SpatialNavigation.bundle, 'board')
const BoardKeys = SpatialNavigation.behavior(Board, { id: 'cards' })(BoardSlots)<
  BoardModel,
  BoardMessage
>({
  container: 'board',
  item: 'card',
  items: model => describeCards(model.cards),
})

InlineEdit edits a plain value where it is shown, in an <input>: Enter, F2, a double click or a typed key starts, Enter saves, Escape puts it back and closes no dialog around it. The Model slice holds the item being edited, its draft and the parent's refusal; nothing is read back from the field. A changed value commits as the Committed OutMessage, which the placement's onOut saves or hands back to refuse with a reason, keeping the editor open on the same draft; an unchanged value commits nothing. Enter and Escape on the field are Behaviors.Keys routes; its routes option adds more (Tab moving to the next cell), and a route on a key it already owns is a mixins:key-conflict naming both. The placement's helpers are start(id, text) (a Rename menu item begins an edit) and refuse(committed, error), which onOut calls to reopen the editor on the same draft with a reason; blur says whether leaving the field commits or cancels, and the field needs an aria-label of its own.

ts
import { modifyFields } from 'foldkit/struct'
import { InlineEdit } from 'foldkit-primitives/interaction'

const Rename = Bundle.declare(InlineEdit.bundle, 'rename')
const renameArgs = { id: 'notes', blur: 'commit' } as const
const Renamed = NotePage.at(Rename, {
  args: renameArgs,
  onOut: committed => model => ({
    model: modifyFields(model, {
      notes: notes =>
        notes.map(note => (note.id === committed.id ? { ...note, title: committed.value } : note)),
    }),
  }),
})
const Renames = InlineEdit.behavior(Rename, renameArgs)(NoteSlots)<NoteModel, NoteMessage>({
  display: 'title',
  input: 'field',
  error: 'error',
  value: (model, id) => model.notes.find(note => note.id === id)?.title ?? '',
})
ts
import { GridNavigation } from 'foldkit-primitives/interaction'

const Cells = Bundle.declare(GridNavigation.bundle, 'cells')
const gridArgs = { columns: 7, wrap: false, virtual: false } as const
const DayKeys = GridNavigation.behavior(Cells, gridArgs)(CalendarSlots)<CalendarModel, CalendarMessage>({
  container: 'grid',
  item: 'day',
  items: model => describeDays(model.days),
})

TreeNavigation is the tree counterpart, after the WAI-ARIA tree pattern, for a file explorer, a page's layers, or a nested menu: Up and Down through the rows that are showing, Right opens a row or steps into it, Left closes it or steps out to its parent, Home and End go to the first and last row. The view gives every row, open or not, in tree order, each with its parent and whether it is a branch; TreeNavigation.shown(rows, model, args) is the rows that are showing, with their level and place among their siblings. The Model slice is { current, toggled }: openness is stored as the rows toggled away from openByDefault, so a layers panel that starts open and a file tree that starts closed are one bundle with a different arg. The Behavior writes each showing row's id (through domId, by default the row's own), role="treeitem", aria-level, aria-posinset, aria-setsize, aria-expanded on a branch, aria-disabled, a roving tabindex, and OnFocus; the container's keys move focus by id, or open and close the current row in place. Focus in the tree follows its stop when a transition it did not see moves it or removes the focused row (the FollowTabStop Mount in foldkit-primitives/dom, which never takes focus from outside the container, and reads only the tree's own stops: each roving primitive marks its container data-fk-roving, so a row holding a RovingTabindex toolbar keeps the toolbar's). A tree that also wants a fallback when the last row goes has FocusRecovery on its container or around it, with the rows as parts: while a row is left, FollowTabStop takes the tree's stop, and FocusRecovery's steps run once none is. The level is also the custom property --fk-tree-level, 1 at the top, so one rule indents any depth: padding-inline-start: calc(var(--fk-tree-level) * 1rem).

ts
import { TreeNavigation } from 'foldkit-primitives/interaction'

const Layers = Bundle.declare(TreeNavigation.bundle, 'layers')
const TreeKeys = TreeNavigation.behavior(Layers, { openByDefault: true })(TreeSlots)<TreeModel, TreeMessage>({
  container: 'tree',
  item: 'row',
  rows: model =>
    model.folders.map(folder => ({ id: folder.id, parent: folder.parent, branch: folder.hasChildren })),
})

The pure move(shown, current, key, modifiers, model, args, direction?) answers with Focus, Open, or Close.

FocusScope is the one entry here that is a Mount, not a Bundle: which element has focus is a DOM fact, so nothing crosses to the Model. The Mount lives in foldkit-primitives/dom; FocusScope.behavior(Slots)<Input, Message>({ container, contain?, restore?, initialFocus? }) attaches it to a container slot. On insert the container focuses initialFocus, else its first tabbable descendant, else itself. With contain (default), Tab from the last tabbable wraps to the first, Shift+Tab from the first wraps to the last, and focus that lands outside comes straight back; Tab in the middle is the browser's. On unmount, with restore (default), focus returns to the element that had it; when that is gone (removed by the action the overlay was opened for, or drawn again) and focus went with the scope, it goes by the rules of FocusReturn: an element with the same id, the opener's FocusRecovery steps, the layer below, the page's first tabbable element. Focus the user moved elsewhere stays. A native <dialog> does all of this itself; this is for a custom overlay, a menu, or a command palette.

FocusRecovery keeps focus when the element that has it goes away: a removed row, a clear button that leaves with the text, a part made inert, hidden or disabled. The browser drops focus to body; the Mount runs in the same task as the change, before that, and moves focus along a fallback the application declares. Like FocusScope it is DOM, not state: nothing crosses to the Model except what the target's own OnFocus already reports. Where FocusScope acts when a scope appears or goes and FollowTabStop follows a roving stop, FocusRecovery acts only on focus that was lost with a part.

focus on a marked part, remembered with its slot, key and neighbours
  -> the part is removed, hidden, made inert/disabled, or moved in the tree
  -> focus is lost (not moved: a dialog the action opened keeps it)
  -> the part's steps in order, until one can take focus
  -> none: the next owner out decides; with none, focus stays where it is
ts
import { FocusRecovery } from 'foldkit-primitives/interaction'

const Recovers = FocusRecovery.behavior(RecoveryView)({
  owner: 'root',
  parts: {
    input: [],
    clear: [{ part: 'input' }],
    row: ['next', 'previous', { part: 'input' }],
  },
})

owner is a slot of the contract, and a { part } step names a key of parts, so a step to a part parts does not declare is a type error. A key of parts that is a slot is marked on it. A key that is no slot names a part a widget draws itself: an Alert's or a Card's recoveryPart: 'dismiss' marks its dismiss button as that part, so parts: { dismiss: ['next', 'previous', { part: 'add' }], add: [] } recovers to it without declaring a dismiss slot that is never drawn. Such a name is not checked against the widget, so a misspelling on either side finds nothing. The { part } check needs the inferred form, behavior(Bound)({ … }) over a SlotView.over(Slots)<Input, Message>() binder: TypeScript cannot infer part of a call's type arguments, so behavior(Slots)<Input, Message>({ … }) checks a { part } against any string. The Behavior draws marks, which a server render has: data-fk-focus-owner on the owner, data-fk-focus-part on each part, and data-fk-focus-key from item.id on a slot drawn per item. Attach it beside the Behaviors already on the owner: the resolver composes their Mounts. It is opt-in, since a Mount that sends no Message cannot be resolved by a Scene test of every page that draws the component.

The steps of a part, in order, until one finds an element that is connected, showing, and focusable (and this owner's own):

StepFinds
samethe same slot and key if redrawn (handles focus dropped on keyed reorder)
next, previousthe nearest sibling of the same slot in the order last seen while focused
parentthe item returned by parent(input, item), or the closest enclosing part
stopthis owner's part with tabindex="0"
{ part }the first part of that slot
ownerthe owner element, when it is focusable

Focus moves with preventScroll, then scrollIntoView({ block: 'nearest' }), which moves nothing when the target is showing. It never moves when focus is somewhere else (the user, or an action that opened a dialog, got there first), and a claim ends once decided, so a part drawn later takes nothing. Owners nest: the innermost one decides; one with no step left sends a bubbling foldkit-plus:focus-unrecovered, and the next owner out with a part of its own around the inner one acts for that part (an owner between with none lets it pass); with none left focus stays on body, and it never goes outside the owners it was in. A whole owner removed decides nothing; its outer owner does.

A row that is not drawn yet is not found: next sees what is drawn. For a windowed list, let update, which knows the row it wants, scroll and focus by Command after the scroll settles (ListNavigation's helpers.focus, then Dom.focus); a Mount that held "focus row 41 when it appears" would take focus from a user who has moved on. Ids are read as attributes and compared as strings, never put in a selector, so a:b and x"y work.