SelectionController
Single and multiple selection over a collection: choose, toggle, extend a range from an anchor and select all.
Reach for it for a listbox, a table, a tag group or a grid whose value is the selected items. RuiListbox, RuiTable and RuiTagGroup use it. The decisions are the selection helpers, for a collection with its own input handling.
Import
import {
SelectionController,
createSelectionController,
type SelectionChangeDetail,
type SelectionChangeReason,
} from '@ecopages/radiant-ui/controllers';Try it
A multiple-select list composed from RovingController, which moves focus, and this controller, which selects. Click an option to toggle it, or focus the list and press Space or Enter. Shift+click, or Shift with ArrowUp, ArrowDown, Home or End, selects the range from the last option you toggled, on top of what was selected then, so moving back shrinks it. Ctrl+A (Cmd+A on a Mac) on an option selects all. The checkbox shows selectAllState and selects or clears every option.
- Apple
- Banana
- Cherry
- Date
- Fig
Nothing selected
<div data-example="selection">
<label><input type="checkbox" data-select-all /> Select all</label>
<ul role="listbox" aria-label="Fruit" aria-multiselectable="true">
<li role="option" tabindex="-1" aria-selected="false" data-value="apple">Apple</li>
<li role="option" tabindex="-1" aria-selected="false" data-value="banana">Banana</li>
<li role="option" tabindex="-1" aria-selected="false" data-value="cherry">Cherry</li>
<li role="option" tabindex="-1" aria-selected="false" data-value="date">Date</li>
<li role="option" tabindex="-1" aria-selected="false" data-value="fig">Fig</li>
</ul>
<p data-status>Nothing selected</p>
</div>import { RovingController, SelectionController } from '@ecopages/radiant-ui/controllers';
import { selectAllState } from '@ecopages/radiant-ui/helpers';
export function mount(root: HTMLElement): () => void {
const list = root.querySelector<HTMLElement>('[role="listbox"]')!;
const options = [...list.querySelectorAll<HTMLElement>('[role="option"]')];
const all = root.querySelector<HTMLInputElement>('[data-select-all]')!;
const status = root.querySelector('[data-status]')!;
const valueOf = (option: HTMLElement) => option.dataset.value!;
let value: string[] = [];
const render = () => {
for (const option of options) {
option.setAttribute('aria-selected', String(value.includes(valueOf(option))));
}
const state = selectAllState(options.map(valueOf), value);
all.checked = state === true;
all.indeterminate = state === 'mixed';
status.textContent = value.length > 0 ? `Selected: ${value.join(', ')}` : 'Nothing selected';
};
const selection = new SelectionController({
getItems: () => options,
getValue: () => value,
getMode: () => 'multiple',
getValueOf: valueOf,
getTarget: () => list,
onChange: (values) => {
value = values;
render();
},
});
const roving = new RovingController({
getItems: () => options,
getTarget: () => list,
orientation: 'vertical',
onMove: (option, event) => selection.move(option, event),
});
selection.attach();
roving.attach();
roving.sync();
const listeners = new AbortController();
const { signal } = listeners;
list.addEventListener(
'click',
(event) => {
const option = (event.target as Element).closest<HTMLElement>('[role="option"]');
if (option) {
selection.click(option, event);
option.focus();
}
},
{ signal },
);
list.addEventListener(
'keydown',
(event) => {
const option = (event.target as Element).closest<HTMLElement>('[role="option"]');
if (option && (event.key === 'Enter' || event.key === ' ')) {
event.preventDefault();
selection.activate(option);
}
},
{ signal },
);
all.addEventListener('change', () => (all.checked ? selection.selectAll() : selection.clear()), { signal });
return () => {
listeners.abort();
roving.destroy();
selection.destroy();
};
}In multiple mode a plain click toggles, so the list works on touch without a modifier key, and Ctrl/Cmd+click toggles too. For the desktop pattern where a click selects only that option and Ctrl/Cmd+click adds to it, call choose(option) on a plain click and toggle(option) with Ctrl or Cmd held.
mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
Config
| Option | Description |
|---|---|
getItems | The items in order, read on every call. Leave out the ones the user cannot reach, such as hidden ones. |
getValue | The selected values, read on every call: the component owns them. |
getMode | none, single or multiple, read on every call. |
getValueOf | The value an item stands for, such as its data-value. |
isSelectable | Return false for an item the user cannot select or deselect, such as a disabled one. Default: all can. |
getTarget | Where Ctrl/Cmd+A is heard: the host or an inner element. The key selects all only when it is pressed on an item. Omit it to leave select all to the component, through selectAll(). |
getEnabled | Return false to ignore input, such as while the component is disabled or a parent owns its selection. |
onChange | (values, { reason, item }): called with the new values when an input changed them. reason is choose, toggle, extend, select-all or clear; item is the item acted on, absent for select all and clear. The component stores the values and writes aria-selected. |
Methods
| Method | Description |
|---|---|
click(item, event) | Routes a click: Shift extends in multiple mode, any other click activates. |
activate(item) | Chooses item in single mode and toggles it in multiple mode: a click, or Enter and Space in a list. |
move(item, event) | Extends the selection to item when focus moved there by an arrow, Home, End, PageUp or PageDown with Shift held. Call it from RovingController's onMove. |
choose(item) | Makes item the only selected value and the anchor. |
toggle(item) | Adds or removes item (in single mode, selects it or clears the selection) and makes it the anchor. |
extend(item) | Selects the range from the anchor to item, on top of what was selected when the anchor was set. Multiple mode only. |
selectAll() | Selects every selectable item, keeping selected values that are not items. Multiple mode only. |
clear() | Deselects every selectable item, keeping the selected values the user cannot change. |
getAnchor() | The value a range starts from, or null before the first choose or toggle. |
Behavior
- Choosing or toggling sets the anchor and remembers the selection at that moment; extending does not. A range is that selection plus every selectable item from the anchor to the target, so Shift+ArrowDown twice then Shift+ArrowUp once selects one item less.
- Without an anchor, or when the value changed since the controller last reported it, the current value becomes the base of the range, and without an anchor the target starts it.
selectAll()andclear()make their result the base of the next range, so a later Shift+click starts from it and does not bring back what was cleared.- An item
isSelectablerefuses cannot be chosen or toggled, and select all skips it. A selected one stays selected through a range, a clear and a toggle of another item in multiple mode; in single mode, choosing or toggling another item replaces it. - Extending and select all work only in multiple mode, and nothing selects in
none.onChangeruns only when the values differ fromgetValue().
Lifecycle
attach() listens for Ctrl/Cmd+A on getTarget(). destroy() stops listening and forgets the anchor. The other methods work without attach(), since they act only when the component calls them. With a host, createSelectionController(host, config) does the same on connect and disconnect; see bindController.
Accessibility: what the controller does and what you must provide
The controller writes no ARIA and no attribute. You own aria-selected on each item, aria-multiselectable="true" on a multiple-select container, its role and name, and any select-all checkbox, whose state selectAllState gives (mixed is the checkbox's indeterminate). Space, Enter and the click handling are yours too; call activate() and click() from them. Call move(item, event) from RovingController's onMove, so Shift extends to the item roving moved to, mirrored in a right-to-left layout; a Shift+letter that typeahead reports does not extend. Ctrl/Cmd+A is heard only on an item under getTarget(), and not in a text field, so it still selects the text there.
Protected hooks
None. Change behavior through the config.