Navigation

v2.1.0
Structure

Sortable

A list whose items are put in order by dragging a handle or with the keys.

On this page

A sortable is a list whose items are put in order by dragging a handle or with the keys. It has no row of its own: put it on a list, a stack of cards or anything that holds items, and give each item a handle, a button named with what it moves. The sortable behavior carries an item while the others make room for it, and moves its node once, when it is dropped.

Sortable

<div class="max-w(420) mx-auto">  <ol class="list sortable" aria-label="Priorities this quarter">    <li class="list-row sortable-item" data-value="onboarding">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>      </span>      <span class="list-end">Mar 2</span>    </li>    <li class="list-row sortable-item" data-value="billing">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>      </span>      <span class="list-end">Mar 16</span>    </li>    <li class="list-row sortable-item" data-value="search">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>      </span>      <span class="list-end">Apr 6</span>    </li>    <li class="list-row sortable-item" data-value="exports">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>      </span>      <span class="list-end">Apr 27</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-react/native/16/soft/grip-vertical'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="max-w(420) mx-auto">      <ol className="list sortable" aria-label="Priorities this quarter">        <li className="list-row sortable-item" data-value="onboarding">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Onboarding</span><span className="list-description">First run, invitations and the empty states</span>          </span>          <span className="list-end">Mar 2</span>        </li>        <li className="list-row sortable-item" data-value="billing">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Billing">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Billing</span><span className="list-description">Invoices in every currency</span>          </span>          <span className="list-end">Mar 16</span>        </li>        <li className="list-row sortable-item" data-value="search">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Search">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Search</span><span className="list-description">Filters that can be saved and shared</span>          </span>          <span className="list-end">Apr 6</span>        </li>        <li className="list-row sortable-item" data-value="exports">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Exports">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Exports</span><span className="list-description">CSV and PDF for every report</span>          </span>          <span className="list-end">Apr 27</span>        </li>      </ol>      <p className="sortable-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import GripVerticalIcon from '@master/icons-svelte/native/16/soft/grip-vertical'</script><div class="max-w(420) mx-auto" {@attach attach}>  <ol class="list sortable" aria-label="Priorities this quarter">    <li class="list-row sortable-item" data-value="onboarding">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>      </span>      <span class="list-end">Mar 2</span>    </li>    <li class="list-row sortable-item" data-value="billing">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>      </span>      <span class="list-end">Mar 16</span>    </li>    <li class="list-row sortable-item" data-value="search">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>      </span>      <span class="list-end">Apr 6</span>    </li>    <li class="list-row sortable-item" data-value="exports">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>      </span>      <span class="list-end">Apr 27</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-vue/native/16/soft/grip-vertical'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="max-w(420) mx-auto">    <ol class="list sortable" aria-label="Priorities this quarter">      <li class="list-row sortable-item" data-value="onboarding">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>        </span>        <span class="list-end">Mar 2</span>      </li>      <li class="list-row sortable-item" data-value="billing">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>        </span>        <span class="list-end">Mar 16</span>      </li>      <li class="list-row sortable-item" data-value="search">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>        </span>        <span class="list-end">Apr 6</span>      </li>      <li class="list-row sortable-item" data-value="exports">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>        </span>        <span class="list-end">Apr 27</span>      </li>    </ol>    <p class="sortable-status" role="status"></p>  </div></template>
Drag a grip, or press it and then the grip of the place it goes to. With the keys, focus a grip and press Space, move with the arrow keys and press Space again.

#What the stylesheet draws

  • The handle. A button that holds a grip icon, quiet until the pointer or the keys reach it, with a closed-hand cursor. It is 24 by 28px and reaches 44px on a touch screen without moving the grip. It takes touch-action: none, so a drag that starts on it never scrolls the page, and the rest of the item still does.
  • The carried item lifts: a raised sheet grows around it a little past its edges, so its content does not move, with the lifted shadow and a 1.5% swell. It follows the pointer through --sortable-offset, which the behavior writes, with no easing between the pointer and the item. A rule the row draws under itself, such as a list's hairline, stays with the row it parted.
  • Making room. The items between the carried one's place and where it would land glide aside, sortable-item-back toward the start and sortable-item-forward toward the end, by --sortable-size: the carried item's size with the gap after it, measured as it is picked up. The gap that opens is where it lands. Its own place stays empty, so the reader sees where it came from.
  • The drop. The items that made room already stand where they land, so the move takes the room away and puts the node in the gap in one change. Inside a view transition, each item its own picture through view-transition-name: match-element, only the carried item travels, from where it was released to its place. The root says aria-busy="true" while that happens, and nothing else glides.

Without view transitions the carried item takes its place at once; the others are already there. With reduced motion there is no swell, no glide and no transition.

#Cards

Anything that holds items can be sorted. Here each item is a card in a stack with a gap, which the room the cards make includes; the sheet a carried card lifts on takes the card's corner through --sortable-radius.

Cards

<div class="max-w(360) mx-auto">  <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Freeze the branch</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Write the release notes</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Deploy to staging</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Announce the release</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-react/native/16/soft/grip-vertical'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="max-w(360) mx-auto">      <ol className="list sortable gap-xs" aria-label="Release checklist" style={{ '--sortable-radius': 'var(--radius-surface)' } as React.CSSProperties}>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Freeze the branch</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="notes">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Write the release notes</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="staging">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Deploy to staging</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="announce">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Announce the release</span>        </li>      </ol>      <p className="sortable-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import GripVerticalIcon from '@master/icons-svelte/native/16/soft/grip-vertical'</script><div class="max-w(360) mx-auto" {@attach attach}>  <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Freeze the branch</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Write the release notes</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Deploy to staging</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Announce the release</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-vue/native/16/soft/grip-vertical'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="max-w(360) mx-auto">    <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Freeze the branch</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Write the release notes</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Deploy to staging</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Announce the release</span>      </li>    </ol>    <p class="sortable-status" role="status"></p>  </div></template>

#The behavior

sortable takes the root, the element with the sortable class, and returns the function that detaches it.

app.js
import { sortable } from '@master/ui/behaviors/sortable.js'const priorities = sortable(document.querySelector('.sortable'))priorities.value // ['onboarding', 'billing', 'search', 'exports']
  • The pointer. A press on a handle that moves more than 4px picks the item up; less is a press. The handle says aria-pressed="true" while it is carried, the item follows the pointer and the items it passes make room. Where it would land is read from where the items stand in the layout, not from the room they are making, so the place never chases itself. The release moves it, and Escape puts it back while the others glide home. A list that scrolls is scrolled while the pointer is near one of its ends, faster the further in it is. Only the pointer that started the drag moves it.
  • Without a drag. A press on a handle that does not move, a click or a tap, picks the item up as Enter does and focuses its handle. A press on another item's handle moves it to that place and drops it; a press on its own handle drops it where it is. A pointer that cannot drag, and a screen reader's double tap, sort the list this way.
  • The keys. Enter or Space on a handle picks the item up. The arrow keys along the list move it one place at a time; they do nothing until an item is picked up, so a screen reader's own arrow keys keep working. Enter or Space drops it, Escape puts it back where it was picked up, and leaving the handle drops it.
  • What it says. Each pick, move, drop and cancel is said in the sortable-status region, a role="status" inside the root or right after it, with the item's name and its place: "Billing, position 3 of 4." Pass messages to say it in the page's language.
  • The move is the item node itself moving, with moveBefore() where the browser has it, so what the item holds keeps its state: a field's text, a playing video, focus. Elsewhere it is inserted again and its handle is focused again.
  • Events. The root dispatches input and change after a drop that changed the order. The function it returns has a value, the order of the items, each one's data-value or its text. Set it to put them in that order; that dispatches nothing.

sortable-row turns the list across: the offset is horizontal, the landing line stands upright, and ArrowLeft and ArrowRight move, the other way around from right to left.

Without the behavior the list keeps its order and stays readable.

A sortable is one list. Where an item also moves between lists, such as the stages of a board, use a kanban.

#Keyboard

KeysAction
Enter, SpaceOn a handle, pick the item up; again, drop it where it is
ArrowUp, ArrowDownMove the item that is picked up one place; ArrowLeft and ArrowRight in sortable-row, the other way around from right to left
Home, EndMove the item that is picked up to the first or the last place
EscapePut the item back where it was picked up, or where a drag started
TabLeave the handle, which drops the item

#Accessibility

  • Name each handle with what it moves: "Move Billing". The handle is the item's only control for its order, and dragging is never the only way: a press picks an item up and a press on another handle puts it there, and every move the pointer makes, the keys make too.
  • Keep the status region in the page from the start, empty: a region added at the moment it speaks is often not heard.
  • When the order matters to what the page does, such as priority or the steps of a workflow, say so near the list, and save the new order the way the page saves anything else.

#React, Svelte and Vue

The sortable component writes the items in the order it holds, attaches the behavior, and moves an item in its own list when the behavior asks, so the framework's rows and the page agree. Copy it into the project with npx master-ui add sortable; React, Svelte and Vue says how the components are built and used.

ui/sortable.tsx
'use client'import { useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'import { sortable, type SortableMessages } from '@master/ui/behaviors/sortable.js'import { useBehavior } from './use-behavior'export interface SortableItem {  /** What the item stands for in the order. */  value: string  /** What the item is called: its handle is named "Move <label>", and the status says it. */  label: string}export interface SortableProps<T extends SortableItem> extends Omit<ComponentProps<'ol'>, 'children' | 'defaultValue' | 'ref'> {  items: T[]  /** The order, as the items' values. The order of `items` by default. */  value?: string[]  defaultValue?: string[]  onValueChange?: (value: string[]) => void  /** What an item shows beside its handle. */  children: (item: T) => ReactNode  /** Classes of each item, such as `list-row` in a `list`. */  itemClassName?: string  /** The accessible name of a handle. `Move <label>` by default. */  handleLabel?: (item: T) => string  /** What the status region says, in the page's language. */  messages?: SortableMessages}/** * A list the reader puts in order. React writes the items in the order it holds; the behavior carries them * with the pointer and the keys, and asks React to move one when it is dropped. */export function Sortable<T extends SortableItem>({ items, value, defaultValue, onValueChange, children, itemClassName, handleLabel = item => `Move ${item.label}`, messages, className, ...root }: SortableProps<T>) {  const [kept, setKept] = useState(() => value ?? defaultValue ?? items.map(item => item.value))  const order = value ?? kept  const shown = [...items].sort((a, b) => rank(order, a.value) - rank(order, b.value))  const latest = useRef(shown)  latest.current = shown  // A move waits for the render that puts the item in its place, so a view transition pictures it there.  const waiting = useRef<(() => void)[]>([])  useLayoutEffect(() => {    waiting.current.splice(0).forEach(done => done())  })  const move = (from: number, to: number) => new Promise<void>((done) => {    const next = latest.current.map(item => item.value)    const [moved] = next.splice(from, 1)    next.splice(to, 0, moved!)    waiting.current.push(done)    setKept(next)    onValueChange?.(next)  })  const ref = useBehavior(sortable, { messages, move })  return (    <>      <ol className={className ? `sortable ${className}` : 'sortable'} ref={ref} {...root}>        {shown.map(item => (          <li className={itemClassName ? `sortable-item ${itemClassName}` : 'sortable-item'} data-value={item.value} key={item.value}>            <button type="button" className="sortable-handle" aria-pressed="false" aria-label={handleLabel(item)}><svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>            {children(item)}          </li>        ))}      </ol>      <p className="sortable-status" role="status" />    </>  )}/** Where a value stands in an order; one the order leaves out goes after it. */function rank(order: string[], value: string) {  const index = order.indexOf(value)  return index < 0 ? order.length : index}
ui/Sortable.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLOlAttributes } from 'svelte/elements'  import type { SortableMessages } from '@master/ui/behaviors/sortable.js'  export interface SortableItem {    /** What the item stands for in the order. */    value: string    /** What the item is called: its handle is named "Move <label>", and the status says it. */    label: string  }  export interface SortableProps<T extends SortableItem> extends Omit<HTMLOlAttributes, 'children'> {    items: T[]    /** The order, as the items' values. Bind it, or leave it out: the order of `items`. */    value?: string[]    onValueChange?: (value: string[]) => void    /** What an item shows beside its handle. */    children: Snippet<[T]>    /** Classes of each item, such as `list-row` in a `list`. */    itemClass?: string    /** The accessible name of a handle. `Move <label>` by default. */    handleLabel?: (item: T) => string    /** What the status region says, in the page's language. */    messages?: SortableMessages  }</script><script lang="ts" generics="T extends SortableItem">  import { tick, untrack } from 'svelte'  import { sortable } from '@master/ui/behaviors/sortable.js'  import { behavior } from './behavior.svelte.js'  let { items, value = $bindable(), onValueChange, children, itemClass, handleLabel = (item: T) => `Move ${item.label}`, messages, class: className, ...root }: SortableProps<T> = $props()  let kept = $state(untrack(() => value) ?? untrack(() => items.map(item => item.value)))  const order = $derived(value ?? kept)  const rank = (value: string) => {    const index = order.indexOf(value)    return index < 0 ? order.length : index  }  const shown = $derived([...items].sort((a, b) => rank(a.value) - rank(b.value)))  // A move waits for the render that puts the item in its place, so a view transition pictures it there.  const move = async (from: number, to: number) => {    const next = shown.map(item => item.value)    const [moved] = next.splice(from, 1)    next.splice(to, 0, moved!)    kept = next    value = next    onValueChange?.(next)    await tick()  }  const attach = behavior(sortable, () => ({ messages, move }))</script><!--  @component  A list the reader puts in order. Svelte writes the items in the order it holds; the behavior carries them  with the pointer and the keys, and asks Svelte to move one when it is dropped.--><ol class={['sortable', className]} {@attach attach} {...root}>  {#each shown as item (item.value)}    <li class={['sortable-item', itemClass]} data-value={item.value}>      <button type="button" class="sortable-handle" aria-pressed="false" aria-label={handleLabel(item)}><svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>      {@render children(item)}    </li>  {/each}</ol><p class="sortable-status" role="status"></p>
ui/Sortable.vue
<script setup lang="ts" generic="T extends { value: string, label: string }">import { computed, nextTick, ref, useTemplateRef } from 'vue'import { sortable, type SortableMessages } from '@master/ui/behaviors/sortable.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { items, itemClass, handleLabel = (item: T) => `Move ${item.label}`, messages } = defineProps<{  /** Each with the value it stands for in the order and the label its handle and the status say. */  items: T[]  /** Classes of each item, such as `list-row` in a `list`. */  itemClass?: string  /** The accessible name of a handle. `Move <label>` by default. */  handleLabel?: (item: T) => string  /** What the status region says, in the page's language. */  messages?: SortableMessages}>()/** The order, as the items' values: `v-model`. The order of `items` by default. */const model = defineModel<string[]>()defineSlots<{  /** What an item shows beside its handle. */  default?: (props: { item: T }) => unknown}>()/* * A list the reader puts in order. Vue writes the items in the order it holds; the behavior carries them * with the pointer and the keys, and asks Vue to move one when it is dropped. */const kept = ref<string[]>(model.value ?? items.map(item => item.value))const order = computed(() => model.value ?? kept.value)const rank = (value: string) => {  const index = order.value.indexOf(value)  return index < 0 ? order.value.length : index}const shown = computed(() => [...items].sort((a, b) => rank(a.value) - rank(b.value)))// A move waits for the render that puts the item in its place, so a view transition pictures it there.const move = async (from: number, to: number) => {  const next = shown.value.map(item => item.value)  const [moved] = next.splice(from, 1)  next.splice(to, 0, moved!)  kept.value = next  model.value = next  await nextTick()}const root = useTemplateRef<HTMLOListElement>('root')useBehavior(root, sortable, () => ({ messages, move }))</script><template>  <ol class="sortable" ref="root" v-bind="$attrs">    <li v-for="item in shown" :key="item.value" class="sortable-item" :class="itemClass" :data-value="item.value">      <button type="button" class="sortable-handle" aria-pressed="false" :aria-label="handleLabel(item)"><svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>      <slot :item="item" />    </li>  </ol>  <p class="sortable-status" role="status" /></template>

#Classes

ClassDescription
sortableWhat holds the items: a list or a stack. While an item is carried the cursor is a closed hand
sortable-rowThe items run across: the offset and the room the items make are horizontalApply with sortable
sortable-itemAn item. It stands for its data-value, or its text. Carried, it lifts on a raised sheet a little past its edges and follows the pointer
sortable-item-backSet by the behavior during a drag on the items between the carried one's place and where it would land, when it is carried toward the end: each glides toward the start by --sortable-sizeApply with sortable-item
sortable-item-forwardSet by the behavior during a drag when the carried item goes toward the start: each item it passes glides toward the end by --sortable-sizeApply with sortable-item
sortable-handleThe button that carries the item, holding a grip icon: name it with what it moves. A 24 by 28px target, 44px on touch screens
sortable-statusA region that says each pick, move and drop, inside the root or right after it. It takes no room

#Custom properties

PropertyDefaultDescription
--sortable-offsetHow far the carried item is from its place along the list; the script writes it
--sortable-sizeOn the root during a drag: the carried item's size with the gap after it, the distance the others make room by; the script writes it
--sortable-radiusvar(--radius-control)The corner of the sheet a carried item lifts on

#Source

@master/ui/components/sortable.css
/* * Sortable: a list whose items are put in order by dragging a handle or with the keys. * It has no row of its own: it is put on a list, a stack of cards or anything that holds items, and adds * three things. The handle, a quiet grip that says the item can be carried. The carried item, which lifts: * a raised sheet grows around it a little past its edges, so its content does not move, with the lifted * shadow and a slight swell, and it follows the pointer through --sortable-offset. And the room it would land * in: the items between its place and that one glide aside by --sortable-size, so the gap is where it goes, * and nothing under the pointer answers it while they do. * The behavior moves the node once, on the drop, inside a view transition where there is one; the items that * made room are already where they land, so only the carried one travels. */@layer components.ui {  .sortable {    --sortable-radius: var(--radius-control);    /*     * While an item is carried, the cursor is a closed hand wherever the pointer goes, and the items it passes     * are not under the pointer: a row's hover or a handle's open hand would flicker on each item as it glides     * aside beneath it. The pointer stays with the carried handle, which holds it.     */    &:has(.sortable-handle[aria-pressed="true"]) {      cursor: grabbing;      user-select: none;      -webkit-user-select: none;      .sortable-item {        pointer-events: none;        /* Each item glides on a layer of its own, so its words are not drawn again at every step. */        will-change: translate;        /* Each item is its own picture in the view transition of a move, so each slides to its place. */        view-transition-name: match-element;      }    }    /*     * Picked up by the keys or by a press without a drag, the carried handle has focus and nothing follows the     * pointer: every handle takes a press again, another item's to move it to that place, its own to drop it.     */    &:has(.sortable-handle[aria-pressed="true"]:focus) .sortable-handle:not(:disabled) {      pointer-events: auto;    }    /* While the items change places, nothing glides but the transition, or an item would travel twice. */    &[aria-busy="true"] .sortable-item {      transition: none;    }  }  .sortable-item {    position: relative;    scroll-margin: .5rem;    transition-property: translate, scale;    transition-duration: var(--duration-base);    transition-timing-function: var(--easing-glide);    /* Making room for the carried item: toward the start of the list, or toward its end. */    &.sortable-item-back {      translate: 0 calc(-1 * var(--sortable-size, 0px));    }    &.sortable-item-forward {      translate: 0 var(--sortable-size, 0px);    }    /* Carried: above the others, a little larger, on a raised sheet, and under the pointer. */    &:has(.sortable-handle[aria-pressed="true"]) {      z-index: 2;      scale: 1.015;      translate: 0 var(--sortable-offset, 0px);      pointer-events: none;      /* The pointer moves it: no easing between the pointer and the item. */      transition-property: scale;      &::before {        content: '';        position: absolute;        inset: -.25rem -.5rem;        z-index: -1;        border-radius: calc(var(--sortable-radius) * var(--corner-scale));        corner-shape: var(--corner-shape);        @apply --surface-sheet;        box-shadow: var(--shadow-lifted);      }      /* A rule the row draws under itself, such as a list's hairline, stays with the row it parted. */      &::after {        opacity: 0;      }    }    @media (prefers-reduced-motion: reduce) {      transition-property: none;      &:has(.sortable-handle[aria-pressed="true"]) {        scale: 1;      }    }    @media (forced-colors: active) {      &:has(.sortable-handle[aria-pressed="true"])::before {        outline: 2px solid Highlight;      }    }  }  /* Across: the items run along the line, and both the offset and the room are horizontal. */  .sortable-row .sortable-item {    &.sortable-item-back {      translate: calc(-1 * var(--sortable-size, 0px)) 0;    }    &.sortable-item-forward {      translate: var(--sortable-size, 0px) 0;    }    &:dir(rtl) {      &.sortable-item-back {        translate: var(--sortable-size, 0px) 0;      }      &.sortable-item-forward {        translate: calc(-1 * var(--sortable-size, 0px)) 0;      }    }    &:has(.sortable-handle[aria-pressed="true"]) {      translate: var(--sortable-offset, 0px) 0;    }  }  /* The handle: a grip of six points, quiet until the pointer or the keys reach it. */  .sortable-handle {    position: relative;    display: inline-grid;    flex: none;    place-items: center;    width: 1.5rem;    height: 1.75rem;    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--radius-chip) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: var(--color-text-muted);    appearance: none;    cursor: grab;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;    transition-property: background-color, color;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    /* The glyph is the button's icon. It takes no pointer of its own, so a press is the button's. */    .icon {      pointer-events: none;      width: .875rem;      height: .875rem;    }    /* The target reaches 44px on touch without moving the grip. */    &::after {      content: '';      position: absolute;      inset: -.25rem;      @media (pointer: coarse) {        inset: min(-.25rem, calc((100% - 2.75rem) / 2));      }    }    @media (hover: hover) {      &:hover:not(:disabled) {        background: var(--color-surface-chip);        color: var(--color-text-strong);      }    }    &:focus-visible {      @apply --focus-ring;      outline-offset: 0;      color: var(--color-text-strong);    }    /* Carried: the grip sits in a well, as a pressed button does. */    &[aria-pressed="true"] {      background: var(--color-surface-inset);      color: var(--color-text-strong);      box-shadow: var(--shadow-pressed);      cursor: grabbing;    }    &:disabled {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      .icon {        color: ButtonText;      }      /* The grip is a fill, so the system's disabled ink is given to it here, as the color is given above. */      &:disabled .icon {        color: GrayText;      }    }  }  /* What the status region says is for assistive technology: it takes no room. */  .sortable-status {    position: absolute;    width: 1px;    height: 1px;    margin: -1px;    padding: 0;    overflow: hidden;    clip-path: inset(50%);    white-space: nowrap;  }}