Primitives / Interaction
Reorder: moving an item by keys and by pointer
Reorder is the keyboard path a drag lacks, and the pointer's drag mapped
onto the same draft. One Bundle holds what is held and where it would land;
the parent owns the list and decides whether the move happens.
Space/Enter on an item → Grabbed (held, over its own place) out PickedUp
arrows, Home, End → Stepped (over the next place) out PassedOver
Space/Enter → Dropped out Moved { id, to } | PutBack
Escape, focus leaving → Cancelled out PutBack
pointer press and move → the same Messages, from PointerDrag's factsNothing moves while an item is held: the view draws a drop line from the
marks the Behavior writes (data-reorder="held" on the held item,
data-reorder-over="before|inside|after" on the place), so focus stays on the
held item. On the drop the parent applies Moved to its own data, or refuses
it, and the facts are what it reads out through LiveAnnounce:
import { Schema } from 'effect'
import type { HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Bundle } from 'foldkit-bundle'
import { Behavior, Capability, Event, Slot, SlotView, Slots } from 'foldkit-mixins'
import { FocusRecovery, LiveAnnounce, Reorder } from 'foldkit-primitives/interaction'
const Rows = Bundle.declare(Reorder.bundle, 'rows')
const Live = Bundle.declare(LiveAnnounce.bundle, 'live')
const Model = Schema.Struct({ ...Rows.fields, ...Live.fields, ids: Schema.Array(Schema.String) })
type Model = typeof Model.Type
const Message = defineMessageUnion({ ...Rows.cases, ...Live.cases })
type Message = typeof Message.Type
const Parent = Bundle.parent({ Model, Message })
const Announcer = Parent.at(Live, { args: { debounceMs: 150, clearAfterMs: 5000 } })
const assembly = Parent.assemble(
Announcer,
Parent.at(Rows, {
onOut: (fact: Reorder.OutMessage) => (model: Model) => {
const moved = Reorder.OutMessage.match(fact, {
Moved: move => modifyFields(model, { ids: ids => Reorder.apply(ids, move) }),
PickedUp: () => model,
PassedOver: () => model,
PutBack: () => model,
})
return Announcer.helpers.announce(Reorder.announcement(fact, { label: id => id }))(moved)
},
}),
)
const ListSlots = Slots.define({
list: Slot.make({ capability: Capability.Container }),
row: Slot.make({ capability: Capability.Base }),
grip: Slot.make({ capability: Capability.Focusable, events: [Event.KeyDown, Event.Blur] }),
})
const List = SlotView.over(ListSlots)<Model, Message>()
const SortableList = List.define((model, slots, h) =>
h.ul(
slots.list.attrs([]),
model.ids.map((id, index) =>
h.li(slots.row.attrs([h.Key(id)], { index, id }), [
h.button(slots.grip.attrs([h.Type('button')], { index, id }), [id]),
]),
),
),
).pipe(
Behavior.attach(
Reorder.behavior(Rows)(List)({
container: 'list',
item: 'row',
handle: 'grip',
items: model => model.ids,
}),
),
// A keyed move takes the element out and back, and the browser drops its focus.
Behavior.attach(FocusRecovery.behavior(List)({ owner: 'list', parts: { grip: ['same'] } })),
)
const view = (model: Model, h: HtmlBuilder<Message>) =>
h.main([], [SortableList(model, h), LiveAnnounce.view(model.live, h)])
void assembly
void viewReorder.behavior puts the pointer path (PointerDrag) on the container, the
marks on each item, and the key route on the handle, which may be the row
itself. Nothing here fetches or writes your list: Moved is a fact, and
Reorder.apply(ids, moved) is the pure move for a flat list (it returns the
list it was given when nothing changes). The pointer's middle third over a row
that takes nothing is that row's own slot, before or after it as the keys walk
it, so a flat list never shows, announces or drops inside.
Beside a roving tab stop. A list with ListNavigation already owns its
container's keydown, and both take the arrows. Give the placement
handle: Reorder.routed and current, the item the keyboard is on: it hands
back { behavior, keys }, where keys is the route built from the same
options (items, parent, accepts, orientation, grab), to list first in
the container's router. Before a grab the route answers only its grab chords,
so the arrows navigate; while an item is held it takes them, and focus stays on
the held row. Focus leaving the row, or the list (whose rows never take focus
under aria-activedescendant), puts the grab back.
Space and Enter are the list's too. A grab is Space or Enter by default, and a listbox that selects with Space, activates with Enter or types a space into its typeahead wants them as well: the route, listed first, would take every one. Give such a list a grab chord of its own. Here Space selects and Alt+Enter picks the row up (while it is held, Space, Enter and Alt+Enter drop it):
import { Match, Option, Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Bundle } from 'foldkit-bundle'
import { Behavior, Behaviors, Capability, Event, Slot, SlotView, Slots } from 'foldkit-mixins'
import { ListNavigation, Reorder, Selection } from 'foldkit-primitives/interaction'
const { Keys } = Behaviors
const Rows = Bundle.declare(Reorder.bundle, 'rows')
const Nav = Bundle.declare(ListNavigation.bundle, 'nav')
const Picks = Bundle.declare(Selection.bundle, 'picks')
const Model = Schema.Struct({
...Rows.fields,
...Nav.fields,
...Picks.fields,
ids: Schema.Array(Schema.String),
})
type Model = typeof Model.Type
const Message = defineMessageUnion({
...Rows.cases,
...Nav.cases,
...Picks.cases,
Selected: { id: Schema.String },
})
type Message = typeof Message.Type
const navArgs = { orientation: 'vertical', loop: false, virtual: false, timeoutMs: 500, page: 5 } as const
const pickArgs = { mode: 'single', allowEmpty: false } as const
const Parent = Bundle.parent({ Model, Message })
const Picked = Parent.at(Picks, { args: pickArgs })
const assembly = Parent.assemble(
Parent.at(Nav, { args: navArgs }),
Picked,
Parent.at(Rows, {
onOut: (fact: Reorder.OutMessage) => (model: Model) => ({
model: Reorder.OutMessage.match(fact, {
Moved: move => modifyFields(model, { ids: ids => Reorder.apply(ids, move) }),
PickedUp: () => model,
PassedOver: () => model,
PutBack: () => model,
}),
}),
}),
)
const ListboxSlots = Slots.define({
list: Slot.make({ capability: Capability.Container, events: [Event.KeyDown] }),
option: Slot.make({ capability: Capability.Focusable, events: [Event.Focus, Event.Blur] }),
})
const Listbox = SlotView.over(ListboxSlots)<Model, Message>()
const items = (model: Model) => Behaviors.Collection.of(model.ids, { id: id => id })
const Sorting = Reorder.behavior(Rows)(Listbox)({
container: 'list',
item: 'option',
handle: Reorder.routed,
items: model => model.ids,
current: model => Option.fromNullishOr(model.nav.current),
grab: [Keys.chord('Enter', { alt: true })],
})
// Space selects the row the keyboard is on, unless typeahead is mid-word: the parent's own
// Message, which `update` applies through Selection's helper.
const select = Keys.route<Model, Message>('Select', {
on: [Keys.chord(' ')],
handle: ({ input }) =>
input.nav.query === ''
? Option.map(Option.fromNullishOr(input.nav.current), id => Message.Selected({ id }))
: Option.none(),
})
const update = assembly.update((model, message) =>
Match.valueTags(message, { Selected: ({ id }) => Picked.helpers.activate(id)(model) }),
)
const navigation = ListNavigation.keys(Nav, navArgs)<Model, Message>({
items,
text: (model, index) => model.ids[index] ?? '',
})
const SortableListbox = Listbox.define((model, slots, h) =>
h.ul(
slots.list.attrs([h.Role('listbox'), h.AriaLabel('Priorities')]),
model.ids.map((id, index) =>
h.li(slots.option.attrs([h.Key(id), h.Id(id), h.Role('option')], { index, id }), [id]),
),
),
).pipe(
Behavior.attach(
Keys.behavior(Listbox)({
slot: 'list',
routes: [Keys.first(Sorting.keys, Keys.first(select, navigation))],
}),
),
Behavior.attach(Sorting.behavior),
Behavior.attach(
Selection.behavior(Picks, pickArgs)(Listbox)({ container: 'list', item: 'option', items }),
),
// The roving tab stop: ListNavigation's item half, since its key half is in the router above.
Behavior.attach(ListNavigation.item(Nav, navArgs)(Listbox)({ item: 'option', items })),
)
void update
void SortableListboxA tree. Give items the rows that show, flat, with parent and
accepts. The places then walk the tree: before each row, inside a row that
accepts items and shows none of its own (as its last child), and after each
level that ends. The held row's own rows are never offered, and the Behavior
takes its mark off them while it is held, so the pointer finds no place there.
A drag that reached one in the frame before that drawing can still drop on it,
and only the parent knows the tree, so the guard is the parent's: its update
refuses such a Moved with Reorder.movesIntoItself, and announcement
reads the same test as words.refused:
const parents = new Map([
['intro', 'docs'],
['guide', 'docs'],
])
const parent = (id: string) => Option.fromNullishOr(parents.get(id))
// The one test: `onOut` leaves the list alone on a `Moved` it holds for, and the words say so.
const refuses = (move: Reorder.Move) => Reorder.movesIntoItself({ ...move, parent })
const intoItself = Reorder.OutMessage.Moved({
id: 'docs',
by: 'pointer',
to: { id: 'intro', zone: 'after' },
})
Reorder.announcement(intoItself, { label: id => id, refuses }) // 'docs cannot go there; put back where it was.'Reorder.places is the walk itself, for a view that shows "position 2 of 5".
Words, direction, keys faster than a frame. announcement reads each
fact with words (English templates with {item} and {target}; pass your
own). orientation: 'horizontal' walks with Left and Right, and
direction: () => 'rtl' swaps them. Each arrow carries the places as drawn
and steps from the Model's over, and the route remembers its own grab on a
drawing, so keys pressed faster than a frame each count.
Limits: one draft per placement (a second grab while an item is held is
refused, and the pointer never steers a key grab, nor the keys a pointer one);
a pointer drag onto targets elsewhere is PointerDrag's, not this one's; an
empty list offers no place, since a place names an item.