Sortable list
A list whose items the user reorders by dragging or from the keyboard, with each step announced.
Goal
A to-do list, a playlist or a priority ranking: the order is data the user edits. The list keeps one tab stop, lifts an item with Space, moves it with the arrow keys and drops it with Space, and a drag with the pointer does the same. A live region says what happened.
Primitives
- SortableController decides where the item lands, by pointer or keyboard, and announces each step. It never moves a node, so the recipe keeps the order itself.
- With
preview: truethe dragged item follows the pointer above the page and a placeholder holds its slot;createPlaceholderreturns anlibecause the container is aul. The lifted item leaves the example, so its style selects it bydata-sortable-task, not by an ancestor. - reorder turns the
fromandtoof a change into the new array, so the order is one array the recipe owns. - RovingController gives the list one tab stop and moves it with the arrows. Its
enabledreturnsfalsewhile an item is lifted, so the arrow keys that steer the lifted item do not also move focus.
Left to the recipe: the order array and writing it to the DOM in onChange, and refocusing the dropped item.
Example
Tab into the list, press Space on an item, move it with the arrow keys and press Space to drop it, or drag it with the pointer.
Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.
The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.
- Plan
- Build
- Test
- Ship
Focus an item, press Space, move with the arrows, press Space to drop
import { RadiantElement, customElement, query } from '@ecopages/radiant';
import { createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { reorder } from '@ecopages/radiant-ui/helpers';
@customElement('sortable-list-element')
export class SortableListElement extends RadiantElement {
@query('ul') private list!: HTMLElement;
@query('[data-status]') private status!: HTMLElement;
private items: HTMLElement[] = [];
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.list,
orientation: 'vertical',
getEnabled: () => this.sortable.getState() === null,
});
private readonly sortable = createSortableController(this, {
preview: true,
createPlaceholder: () => document.createElement('li'),
getContainer: () => this.list,
getItems: () => this.items,
announce: (message) => (this.status.textContent = message),
onChange: ({ item, from, to }) => {
this.items = reorder(this.items, from, to);
this.list.append(...this.items);
this.roving.focus(item);
},
});
override onConnected(): void {
this.items = [...this.list.children] as HTMLElement[];
this.roving.sync();
}
}<sortable-list-element>
<ul aria-label="Tasks">
<li data-sortable-task>Plan</li>
<li data-sortable-task>Build</li>
<li data-sortable-task>Test</li>
<li data-sortable-task>Ship</li>
</ul>
<p data-status aria-live="polite">Focus an item, press Space, move with the arrows, press Space to drop</p>
</sortable-list-element>[data-sortable-task] {
cursor: grab;
touch-action: none;
user-select: none;
}
[data-sortable-task][data-sortable-state='lifted'] {
z-index: 10;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--primary);
color: var(--on-primary);
font-size: 0.875rem;
box-shadow: var(--shadow-overlay);
list-style: none;
cursor: grabbing;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-placeholder] {
min-height: 2.5rem;
box-sizing: border-box;
outline: 1px dashed var(--primary);
outline-offset: -4px;
background: transparent;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-drop] {
box-shadow: none;
}createSortableController(this, ...) and createRovingController(this, ...) attach when the element connects and are destroyed when it disconnects. They are field initializers because each refers to the other from its callbacks: enabled reads the sortable and onChange focuses through the roving controller. The items are read in onConnected, once the element has its children.
What the Radiant form removes: the mount function and its registration, the cleanup that destroys both controllers, and the re-run after a client-side navigation.
The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.
- Plan
- Build
- Test
- Ship
Focus an item, press Space, move with the arrows, press Space to drop
import { RadiantElement, customElement, query } from '@ecopages/radiant';
import { createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { reorder } from '@ecopages/radiant-ui/helpers';
@customElement('sortable-list-element')
export class SortableListElement extends RadiantElement {
@query('ul') private list!: HTMLElement;
@query('[data-status]') private status!: HTMLElement;
private items: HTMLElement[] = [];
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.list,
orientation: 'vertical',
getEnabled: () => this.sortable.getState() === null,
});
private readonly sortable = createSortableController(this, {
preview: true,
createPlaceholder: () => document.createElement('li'),
getContainer: () => this.list,
getItems: () => this.items,
announce: (message) => (this.status.textContent = message),
onChange: ({ item, from, to }) => {
this.items = reorder(this.items, from, to);
this.list.append(...this.items);
this.roving.focus(item);
},
});
override onConnected(): void {
this.items = [...this.list.children] as HTMLElement[];
this.roving.sync();
}
}<sortable-list-element>
<ul aria-label="Tasks">
<li data-sortable-task>Plan</li>
<li data-sortable-task>Build</li>
<li data-sortable-task>Test</li>
<li data-sortable-task>Ship</li>
</ul>
<p data-status aria-live="polite">Focus an item, press Space, move with the arrows, press Space to drop</p>
</sortable-list-element>[data-sortable-task] {
cursor: grab;
touch-action: none;
user-select: none;
}
[data-sortable-task][data-sortable-state='lifted'] {
z-index: 10;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--primary);
color: var(--on-primary);
font-size: 0.875rem;
box-shadow: var(--shadow-overlay);
list-style: none;
cursor: grabbing;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-placeholder] {
min-height: 2.5rem;
box-sizing: border-box;
outline: 1px dashed var(--primary);
outline-offset: -4px;
background: transparent;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-drop] {
box-shadow: none;
}createSortableController(this, ...) and createRovingController(this, ...) attach when the element connects and are destroyed when it disconnects. They are field initializers because each refers to the other from its callbacks: enabled reads the sortable and onChange focuses through the roving controller. The items are read in onConnected, once the element has its children.
What the Radiant form removes: the mount function and its registration, the cleanup that destroys both controllers, and the re-run after a client-side navigation.
The same behavior as a single RadiantElement that owns its markup: the tasks are @state and render() draws the list.
import { RadiantElement, customElement, state } from '@ecopages/radiant';
import { createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { reorder } from '@ecopages/radiant-ui/helpers';
const initialTasks = ['Plan', 'Build', 'Test', 'Ship'];
@customElement('sortable-list-app')
export class SortableListApp extends RadiantElement<{ status: string }> {
@state tasks = initialTasks;
@state status = 'Focus an item, press Space, move with the arrows, press Space to drop';
private focusTask: string | null = null;
private readonly roving = createRovingController(this, {
getItems: () => this.items(),
getTarget: () => this.querySelector('ul'),
orientation: 'vertical',
getEnabled: () => this.sortable.getState() === null,
});
private readonly sortable = createSortableController(this, {
preview: true,
createPlaceholder: () => document.createElement('li'),
getContainer: () => this.querySelector('ul'),
getItems: () => this.items(),
announce: (message) => (this.status = message),
onChange: ({ item, from, to }) => {
this.focusTask = item.dataset.sortableTask!;
this.tasks = reorder(this.tasks, from, to);
},
});
private items(): HTMLElement[] {
return [...(this.querySelector('ul')?.children ?? [])] as HTMLElement[];
}
/**
* Attaches both controllers to the list the render produced, and focuses the item that was just moved.
*
* @remarks
* The controllers attach when the element connects, before the first render, when no list exists yet; the
* `attach()` again resolves the list each controller listens on, and `sync()` gives the roving controller the items of the committed list. The keyed items keep
* their nodes across renders, so the moved item is the same node, found by its task.
*/
protected override updated(): void {
this.sortable.attach();
this.roving.attach();
this.roving.sync();
if (this.focusTask) {
this.roving.focus(this.querySelector<HTMLElement>(`[data-sortable-task="${this.focusTask}"]`)!);
this.focusTask = null;
}
}
override render() {
return (
<>
<ul aria-label="Tasks">
{this.tasks.map((task) => (
<li key={task} data-sortable-task={task}>
{task}
</li>
))}
</ul>
<p data-status aria-live="polite">
{this.$.status}
</p>
</>
);
}
}[data-sortable-task] {
cursor: grab;
touch-action: none;
user-select: none;
}
[data-sortable-task][data-sortable-state='lifted'] {
z-index: 10;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--primary);
color: var(--on-primary);
font-size: 0.875rem;
box-shadow: var(--shadow-overlay);
list-style: none;
cursor: grabbing;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-placeholder] {
min-height: 2.5rem;
box-sizing: border-box;
outline: 1px dashed var(--primary);
outline-offset: -4px;
background: transparent;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-drop] {
box-shadow: none;
}The tasks are @state, so a drop is a new array: onChange does not touch the DOM, it writes the reordered tasks with reorder, and render() moves the keyed items. The sortable and roving controllers are still field initializers that refer to each other, but they read the list through a query instead of a stored ul and an items array, because the list is drawn by the element. updated() runs after each commit: it attaches the sortable to the committed list, syncs the roving tab stop and focuses the item that moved. The status line is bound with this.$.status, so announcing during a sort patches one text node and never re-renders the list while an item is lifted.
Compared with the Radiant element above, the markup lives inside the element, so there is nothing to keep in step with the page and the tasks are state you can change, but restyling the structure means editing the class. It also needs the render path on the server to have content before the script runs: this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads, which a page of authored children does not.
The same behavior as a RadiantController attached to markup that is already on the page.
- Plan
- Build
- Test
- Ship
Focus an item, press Space, move with the arrows, press Space to drop
import { RadiantController, controller, query } from '@ecopages/radiant';
import { createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { reorder } from '@ecopages/radiant-ui/helpers';
/**
* @remarks
* `RadiantController` has the two registration methods a radiant-ui controller needs from its host, so
* `createSortableController(this, ...)` and `createRovingController(this, ...)` attach on connect and are destroyed
* when the registry disconnects the controller, with no extra cleanup here.
*/
@controller('sortable-list')
export class SortableListController extends RadiantController {
@query('ul') private list!: HTMLElement;
@query('[data-status]') private status!: HTMLElement;
private items: HTMLElement[] = [];
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.list,
orientation: 'vertical',
getEnabled: () => this.sortable.getState() === null,
});
private readonly sortable = createSortableController(this, {
preview: true,
createPlaceholder: () => document.createElement('li'),
getContainer: () => this.list,
getItems: () => this.items,
announce: (message) => (this.status.textContent = message),
onChange: ({ item, from, to }) => {
this.items = reorder(this.items, from, to);
this.list.append(...this.items);
this.roving.focus(item);
},
});
override connect(): void {
super.connect();
this.items = [...this.list.children] as HTMLElement[];
this.roving.sync();
}
}<div data-controller="sortable-list">
<ul aria-label="Tasks">
<li data-sortable-task>Plan</li>
<li data-sortable-task>Build</li>
<li data-sortable-task>Test</li>
<li data-sortable-task>Ship</li>
</ul>
<p data-status aria-live="polite">Focus an item, press Space, move with the arrows, press Space to drop</p>
</div>[data-sortable-task] {
cursor: grab;
touch-action: none;
user-select: none;
}
[data-sortable-task][data-sortable-state='lifted'] {
z-index: 10;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--primary);
color: var(--on-primary);
font-size: 0.875rem;
box-shadow: var(--shadow-overlay);
list-style: none;
cursor: grabbing;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-placeholder] {
min-height: 2.5rem;
box-sizing: border-box;
outline: 1px dashed var(--primary);
outline-offset: -4px;
background: transparent;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-drop] {
box-shadow: none;
}Compared with the Radiant element, there is no custom element tag to define: the markup is a plain div that a server or CMS can render, and data-controller="sortable-list" attaches the class through the registry, which the docs site starts once over the document. The body is the element's, with @query finding the parts and the sortable and roving controllers declared the same way, because a RadiantController accepts createSortableController(this, ...) as a host. The items are read in connect() after super.connect(). When the element is removed the registry disconnects the controller and both primitives are destroyed.
A mount function wires the controllers to the markup and returns the cleanup that undoes it.
- Plan
- Build
- Test
- Ship
Focus an item, press Space, move with the arrows, press Space to drop
import { RovingController, SortableController } from '@ecopages/radiant-ui/controllers';
import { reorder } from '@ecopages/radiant-ui/helpers';
export function mount(root: HTMLElement): () => void {
const list = root.querySelector('ul')!;
const status = root.querySelector('[data-status]')!;
let items = [...list.children] as HTMLElement[];
const roving = new RovingController({
getItems: () => items,
getTarget: () => list,
orientation: 'vertical',
getEnabled: () => sortable.getState() === null,
});
const sortable = new SortableController({
preview: true,
createPlaceholder: () => document.createElement('li'),
getContainer: () => list,
getItems: () => items,
announce: (message) => (status.textContent = message),
onChange: ({ item, from, to }) => {
items = reorder(items, from, to);
list.append(...items);
roving.focus(item);
},
});
sortable.attach();
roving.attach();
roving.sync();
return () => {
sortable.destroy();
roving.destroy();
};
}<div data-example="sortable-list">
<ul aria-label="Tasks">
<li data-sortable-task>Plan</li>
<li data-sortable-task>Build</li>
<li data-sortable-task>Test</li>
<li data-sortable-task>Ship</li>
</ul>
<p data-status aria-live="polite">Focus an item, press Space, move with the arrows, press Space to drop</p>
</div>[data-sortable-task] {
cursor: grab;
touch-action: none;
user-select: none;
}
[data-sortable-task][data-sortable-state='lifted'] {
z-index: 10;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--primary);
color: var(--on-primary);
font-size: 0.875rem;
box-shadow: var(--shadow-overlay);
list-style: none;
cursor: grabbing;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-placeholder] {
min-height: 2.5rem;
box-sizing: border-box;
outline: 1px dashed var(--primary);
outline-offset: -4px;
background: transparent;
}
:is([data-example='sortable-list'], sortable-list-element, [data-controller='sortable-list'], sortable-list-app)
[data-sortable-drop] {
box-shadow: none;
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
Styles
The lifted item and the placeholder are styled by data-sortable-state and data-sortable-placeholder; touch-action: none on the items lets a touch drag reorder instead of scrolling. The stylesheet is the sortable-list.css tab in the files above.