# Sortable List

> A list the user puts in order, by dragging each item by its handle or with the keyboard, while a screenreader hears where the item is as it moves.

`<slab-sortable-list>` · Data · built on `[role=list] + handle <button>s`

## Install

```sh
pnpm add slab-elements lit
```

## Usage

### React

`MySortableList.jsx`. React 19 or later, which sets props on custom elements as properties.

```jsx
import 'slab-elements/sortable-list.js';
import 'slab-elements/sortable-list.item.js';

export function MySortableList() {
  return (
    <slab-sortable-list label="Priorities">
      <slab-sortable-list-item label="Footings">
        <svg slot="handle" aria-hidden="true">…</svg>
        Footings
      </slab-sortable-list-item>
      <slab-sortable-list-item label="Walls">
        <svg slot="handle" aria-hidden="true">…</svg>
        Walls
      </slab-sortable-list-item>
    </slab-sortable-list>
  );
}
```

### Lit

`my-sortable-list.ts`. Slab is built on Lit, so its elements are at home in Lit's templates.

```ts
import 'slab-elements/sortable-list.js';
import 'slab-elements/sortable-list.item.js';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('my-sortable-list')
export class MySortableList extends LitElement {
  render() {
    return html`
      <slab-sortable-list label="Priorities">
        <slab-sortable-list-item label="Footings">
          <svg slot="handle" aria-hidden="true">…</svg>
          Footings
        </slab-sortable-list-item>
        <slab-sortable-list-item label="Walls">
          <svg slot="handle" aria-hidden="true">…</svg>
          Walls
        </slab-sortable-list-item>
      </slab-sortable-list>
    `;
  }
}
```

### Vue

`MySortableList.vue`. Let Vue's compiler know slab- tags are custom elements with isCustomElement.

```vue
<script setup>
import 'slab-elements/sortable-list.js';
import 'slab-elements/sortable-list.item.js';
</script>

<template>
  <slab-sortable-list label="Priorities">
    <slab-sortable-list-item label="Footings">
      <svg slot="handle" aria-hidden="true">…</svg>
      Footings
    </slab-sortable-list-item>
    <slab-sortable-list-item label="Walls">
      <svg slot="handle" aria-hidden="true">…</svg>
      Walls
    </slab-sortable-list-item>
  </slab-sortable-list>
</template>
```

### Svelte

`MySortableList.svelte`. Svelte binds properties and events to custom elements like any other element.

```svelte
<script>
  import 'slab-elements/sortable-list.js';
  import 'slab-elements/sortable-list.item.js';
</script>

<slab-sortable-list label="Priorities">
  <slab-sortable-list-item label="Footings">
    <svg slot="handle" aria-hidden="true">…</svg>
    Footings
  </slab-sortable-list-item>
  <slab-sortable-list-item label="Walls">
    <svg slot="handle" aria-hidden="true">…</svg>
    Walls
  </slab-sortable-list-item>
</slab-sortable-list>
```

### Ember

`MySortableList.gjs`. Ember sets attributes, and a dynamic value like {{this.max}} sets the property when the element has one. {{on}} listens for any event by its name.

```gjs
import 'slab-elements/sortable-list.js';
import 'slab-elements/sortable-list.item.js';

export const MySortableList = <template>
  <slab-sortable-list label="Priorities">
    <slab-sortable-list-item label="Footings">
      <svg slot="handle" aria-hidden="true">…</svg>
      Footings
    </slab-sortable-list-item>
    <slab-sortable-list-item label="Walls">
      <svg slot="handle" aria-hidden="true">…</svg>
      Walls
    </slab-sortable-list-item>
  </slab-sortable-list>
</template>;
```

### HTML

`index.html`. Any bundler (or an import map) takes care of the imports.

```html
<script type="module">
  import 'slab-elements/sortable-list.js';
  import 'slab-elements/sortable-list.item.js';
</script>

<slab-sortable-list label="Priorities">
  <slab-sortable-list-item label="Footings">
    <svg slot="handle" aria-hidden="true">…</svg>
    Footings
  </slab-sortable-list-item>
  <slab-sortable-list-item label="Walls">
    <svg slot="handle" aria-hidden="true">…</svg>
    Walls
  </slab-sortable-list-item>
</slab-sortable-list>
```

## Example

Here's a styled version, `<slab-styled-sortable-list>`. It's not in the package — it's an example of what you can build with the headless element. Copy it and make it yours at the bottom of this page.

```html
<slab-styled-sortable-list label="Pour order">
  <slab-styled-sortable-list-item label="Footings">Footings</slab-styled-sortable-list-item>
  <slab-styled-sortable-list-item label="Foundation walls">Foundation walls</slab-styled-sortable-list-item>
  <slab-styled-sortable-list-item label="Garage slab">Garage slab</slab-styled-sortable-list-item>
  <slab-styled-sortable-list-item label="Driveway">Driveway</slab-styled-sortable-list-item>
</slab-styled-sortable-list>
```

Swap `slab-styled-` for `slab-` in that markup and you've got the same example as it ships: the headless elements with no CSS at all. That's your starting point.

Each item has a handle, a `<button>` named "Reorder" and the item's `label`. Drag it, and the item moves as the pointer passes the middle of the items around it. Or press Space or Enter on it to pick the item up, move it with the arrow keys, and press Space or Enter again to drop it. Escape, or moving focus away, puts it back where it was. What's in the handle is yours, such as a grip icon in its `handle` slot.

Screenreaders hear where the item is at each step, such as "Walls picked up at position 2 of 3" and "Walls moved to position 1 of 3", and each handle is described with how to move it. Word them yourself with `instructions-label` and the `grabbedLabel`, `movedLabel`, `droppedLabel` and `canceledLabel` functions, which take the item's label, its position from 1 and the number of items.

Sortable List moves the items in the DOM itself, so their order there is always the list's, and dispatches "change" when an item is dropped somewhere new. Read the new order from `items`. In a framework that renders the items from an array, set the array from `items` on "change" and key each item, so the framework's order and the list's agree. An item has `:state(grabbed)` while it's picked up or dragged.

For motion, give the items a `view-transition-name`, such as `view-transition-name: match-element`, and each move happens in a view transition, so the items glide to their new places, as in the example above. Style the animation with `::view-transition-group()` in your page's CSS. The items move at once when they have no name, in a browser without view transitions, or for someone who prefers reduced motion.

## Keyboard

| Key                  | What it does                                                    |
| -------------------- | --------------------------------------------------------------- |
| Tab                  | Moves to each item's handle, then to what's in the item.        |
| Space, Enter         | On a handle, picks its item up. While it's picked up, drops it. |
| Up Arrow, Down Arrow | Moves a picked up item one place earlier or later.              |
| Home, End            | Moves a picked up item to the start or the end of the list.     |
| Escape               | Puts a picked up or dragged item back where it was.             |

## Behavior

### `<slab-sortable-list>`

A Sortable List with no visual styles: a list whose items the user puts in order, by dragging them or with the keyboard, such as a playlist or a list of priorities.

Each Sortable List Item has a handle, a `<button>`. Drag it and the item moves as the pointer passes the items around it. Or press Space or Enter on it to pick the item up, the arrow keys to move it, Home and End to move it to the start or end, Space or Enter to drop it, and Escape to put it back where it was. Moving focus away while it's picked up puts it back as well.

Screenreaders are told where the item is as it's picked up, moved, dropped or put back, such as "Pour moved to position 2 of 3". Change what they're told with `grabbedLabel`, `movedLabel`, `droppedLabel` and `canceledLabel`.

Sortable List moves the items themselves, so their order in the DOM is always the list's. It dispatches "change" when an item is dropped somewhere new, and `items` is the new order.

### `<slab-sortable-list-item>`

A Sortable List Item with no visual styles: one item of its Sortable List, with a handle that moves it.

The handle is a `<button>` named "Reorder" and the item's `label`, and it's described by its Sortable List's `instructions-label`. Drag it to move the item, or press Space or Enter on it to pick the item up, the arrow keys to move it, Space or Enter to drop it, and Escape to put it back.

What goes in the handle is yours, such as a grip icon, through its `handle` slot. The handle is `aria-pressed` while the item is picked up.

Style it through its parts and `:state(grabbed)`, which it has while it's picked up or dragged.

## API

### `<slab-sortable-list>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | Names the list. |
| `instructions-label` | `string` |  | Describes each handle to screenreaders. "Press Space to pick it up…" in English when unset. |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `canceledLabel` | `Announcement` | What screenreaders are told when an item is put back, from its label and where it is, from 1. "Reorder canceled…" in English when unset. |
| `droppedLabel` | `Announcement` | What screenreaders are told when an item is dropped, from its label and where it is, from 1. "Pour dropped at position 2 of 3" and so on in English when unset. |
| `grabbedLabel` | `Announcement` | What screenreaders are told when an item is picked up with the keyboard, from its label and where it is, from 1. "Pour picked up at position 2 of 3" and so on in English when unset. |
| `movedLabel` | `Announcement` | What screenreaders are told when a picked up item is moved, from its label and where it is, from 1. "Pour moved to position 2 of 3" and so on in English when unset. |
| `items` (read-only) | `SortableListItem[]` | Its items, in order. |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `change` | `Event` | When the user moves an item somewhere else in the list. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `SortableListItem` | The items, in order |

#### CSS parts

| Name | Description |
| --- | --- |
| `list` | The items |

### `<slab-sortable-list-item>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | Names the item, in its handle's name and in what screenreaders are told as it moves. |
| `handle-label` | `string` |  | Names the handle. "Reorder" and `label` in English when unset. |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `grabbed` | `boolean` | Set by its Sortable List. |
| `instructions` | `string` | Set by its Sortable List. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `handle` | `Element \| string` | Shown in the handle, such as a grip icon |
| `(default)` | `Element \| string` | The item's content |

#### CSS parts

| Name | Description |
| --- | --- |
| `content` | Holds the content |
| `handle` | The button that moves the item |

#### CSS states

| Name | Description |
| --- | --- |
| `:state(grabbed)` | While it's picked up or dragged. |

## Copy and own it

`<slab-styled-sortable-list>` isn't in the package. It's an example — copy it into your project and change whatever you want. Keyboard, focus, ARIA, forms, and events all come from the headless element, and the styles only reach in through `::part()` and `:state()`, same as yours would.

### Lit

Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. To use it, copy these files, swap the tag in `@customElement()` for one of your own, and import it. `tokens.styles.ts` holds the colors and fonts every styled example shares, so you only need it once.

#### TypeScript

These files are TypeScript, and `@customElement()` is one of Lit's decorators (TypeScript's experimental flavor). You'll need two options in your tsconfig, per [Lit's docs](https://lit.dev/docs/components/decorators/#decorators-typescript): `experimentalDecorators` to compile them, and `useDefineForClassFields` turned off so class fields don't stomp on the accessors Lit sets up.

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "useDefineForClassFields": false
  }
}
```

Using plain JavaScript? Drop the types and register the class with `customElements.define()` instead of the decorator.

#### sortable-list.ts

```ts
import { customElement } from 'lit/decorators.js';
import SortableList from 'slab-elements/sortable-list.js';
import styles from './sortable-list.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-sortable-list': StyledSortableList;
  }
}

/**
 * Sortable List, styled: a column of raised items, each with a grip to drag
 * it by.
 */
@customElement('slab-styled-sortable-list')
export default class StyledSortableList extends SortableList {
  static override styles = [tokens, styles];
}
```

#### sortable-list.styles.ts

```ts
import { css } from 'lit';

/*
  The items are a column with a little room between them, so each one's
  shadow shows.
*/
export default css`
  :host {
    color: var(--ink);
    font-family: var(--font-body);
  }

  [part~='list'] {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
`;
```

#### sortable-list.item.ts

```ts
import { customElement } from 'lit/decorators.js';
import SortableListItem from 'slab-elements/sortable-list.item.js';
import styles from './sortable-list.item.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-sortable-list-item': StyledSortableListItem;
  }
}

/**
 * Sortable List Item, styled: a raised row with a dotted grip at its start.
 * It's lifted and outlined in ember while it's picked up or dragged.
 */
@customElement('slab-styled-sortable-list-item')
export default class StyledSortableListItem extends SortableListItem {
  static override styles = [tokens, styles];
}
```

#### sortable-list.item.styles.ts

```ts
import { css } from 'lit';

/*
  The grip sits at the start of each row, and the content fills the rest. The
  grip's dots are the handle's own, hidden from screenreaders, which read
  its name instead.
*/
export default css`
  :host {
    align-items: center;
    background-color: var(--paper);
    border: var(--border);
    box-shadow: var(--shadow);
    color: var(--ink);
    display: flex;
    font-family: var(--font-body);
    gap: 0.75rem;
    padding: 0.5rem 0.75rem 0.5rem 0.25rem;
    transition:
      box-shadow 100ms,
      translate 100ms;

    /*
      Each item is its own view transition group, so Sortable List glides it
      from where it was to where it's moved.
    */
    view-transition-name: match-element;
  }

  :host(:state(grabbed)) {
    box-shadow: 6px 6px 0 var(--ember);
    translate: -2px -2px;
  }

  [part~='handle'] {
    align-items: center;
    align-self: stretch;
    background: none;
    border: none;
    color: var(--ash);
    cursor: grab;
    display: flex;
    flex: none;
    font: inherit;
    font-size: 1.25rem;
    justify-content: center;
    line-height: 1;
    margin: 0;
    min-block-size: 2.25rem;
    min-inline-size: 2rem;
    padding: 0;

    /* Six dots, in two columns. */
    &::before {
      content: '⠿' / '';
    }

    &:hover {
      color: var(--ink);
    }

    &:focus-visible {
      outline: 3px solid var(--ember);
      outline-offset: 2px;
    }
  }

  :host(:state(grabbed)) [part~='handle'] {
    color: var(--ember-deep);
    cursor: grabbing;
  }

  [part~='content'] {
    flex: 1 1 auto;
    min-inline-size: 0;
    overflow-wrap: anywhere;
  }
`;
```

#### tokens.styles.ts

```ts
import { css } from 'lit';

/*
  The styled components' palette and type, taken from the logo: ink for the
  courses, ember for the base, paper behind them.

  Each is a short alias for a "--slab-styled-*" property, with the default as
  its fallback. Retheming is "--slab-styled-ember" and the rest on ":root",
  which every shadow root inherits. Were the defaults declared under those
  names here instead, each host's own declaration would shadow the page's.

  Each default is "light-dark()", so the components follow the page's
  "color-scheme": "dark" for dark, "light" for light, and "light dark" to
  follow the operating system. Ink and paper trade places in the dark, so
  ink is always the text and paper always what's behind it. Contrast is given
  as light, then dark.
*/
export default css`
  :host {
    /* Secondary text. 6.8:1 and 6.9:1 on paper. */
    --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
    --border: 2px solid var(--ink);

    /* Behind disabled and read-only controls, and hovered rows. */
    --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

    /*
      The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
      enough for borders, fills and large text, but not always for small text,
      which takes "--ember-deep".
    */
    --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

    /*
      Orange for small text on paper, and for paper text on it. 5.7:1 and
      7.4:1.
    */
    --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
    --font-body: var(
      --slab-styled-font-body,
      'IBM Plex Sans',
      system-ui,
      sans-serif
    );
    --font-display: var(
      --slab-styled-font-display,
      'Zilla Slab',
      rockwell,
      'Roboto Slab',
      serif
    );
    --font-mono: var(
      --slab-styled-font-mono,
      'IBM Plex Mono',
      ui-monospace,
      monospace
    );
    --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
    --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

    /* The hard, offset shadow a raised surface casts. */
    --shadow: 4px 4px 0 var(--ink);
  }

  /*
    Forced colors, such as Windows' contrast themes, replace every color that
    isn't a system color, so ember fills and paper marks all become the same
    background, and a checked Checkbox looks like an unchecked one. The palette
    becomes the user's system colors instead, which are kept. Ember is the
    highlight, the color of what's selected, and ember-deep, being for text and
    for paper text on it, is the text color.
  */
  @media (forced-colors: active) {
    :host {
      --ash: GrayText;
      --chalk: Canvas;
      --ember: Highlight;
      --ember-deep: CanvasText;
      --ink: CanvasText;
      --paper: Canvas;
    }
  }
`;
```

### React, Vue, Svelte and Ember

The same styles, written from outside the element, so there's nothing to subclass. The CSS styles every `<slab-sortable-list>` on the page. Import `tokens.css`, the colors and fonts every styled example shares, once, wherever your global styles go.

In React and Vue, each component registers its headless element and imports its CSS. Use it like the element: its props are the element's attributes and properties.

In Svelte, import `sortable-list.js` once, such as in your root layout, and use `<slab-sortable-list>` as is. A Svelte component around it would take `slot="…"` content as its own slot and drop it.

In Ember, each component registers its headless element and imports its CSS. Use it like the element: its attributes and its content go to the element.

#### SortableList.jsx

```jsx
import 'slab-elements/sortable-list.js';
import './sortable-list.css';
import 'slab-elements/sortable-list.item.js';
import './sortable-list.item.css';

export function SortableList(props) {
  return <slab-sortable-list {...props} />;
}

export function SortableListItem(props) {
  return <slab-sortable-list-item {...props} />;
}
```

#### SortableList.vue

```vue
<script setup>
import 'slab-elements/sortable-list.js';
import './sortable-list.css';
</script>

<template>
  <slab-sortable-list><slot /></slab-sortable-list>
</template>
```

#### SortableListItem.vue

```vue
<script setup>
import 'slab-elements/sortable-list.item.js';
import './sortable-list.item.css';
</script>

<template>
  <slab-sortable-list-item><slot /></slab-sortable-list-item>
</template>
```

#### sortable-list.js

```js
import 'slab-elements/sortable-list.js';
import './sortable-list.css';
import 'slab-elements/sortable-list.item.js';
import './sortable-list.item.css';
```

#### SortableList.gjs

```gjs
import 'slab-elements/sortable-list.js';
import './sortable-list.css';

export const SortableList = <template>
  <slab-sortable-list ...attributes>{{yield}}</slab-sortable-list>
</template>;
```

#### SortableListItem.gjs

```gjs
import 'slab-elements/sortable-list.item.js';
import './sortable-list.item.css';

export const SortableListItem = <template>
  <slab-sortable-list-item ...attributes>{{yield}}</slab-sortable-list-item>
</template>;
```

#### sortable-list.css

```css
slab-sortable-list {
  color: var(--ink);
  font-family: var(--font-body);
}

slab-sortable-list::part(list) {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
```

#### sortable-list.item.css

```css
slab-sortable-list-item {
  align-items: center;
  background-color: var(--paper);
  border: var(--border);
  box-shadow: var(--shadow);
  color: var(--ink);
  display: flex;
  font-family: var(--font-body);
  gap: 0.75rem;
  padding: 0.5rem 0.75rem 0.5rem 0.25rem;
  transition:
    box-shadow 100ms,
    translate 100ms;
  /*
    Each item is its own view transition group, so Sortable List glides it
    from where it was to where it's moved.
  */
  view-transition-name: match-element;
}

slab-sortable-list-item:state(grabbed) {
  box-shadow: 6px 6px 0 var(--ember);
  translate: -2px -2px;
}

slab-sortable-list-item::part(handle) {
  align-items: center;
  align-self: stretch;
  background: none;
  border: none;
  color: var(--ash);
  cursor: grab;
  display: flex;
  flex: none;
  font: inherit;
  font-size: 1.25rem;
  justify-content: center;
  line-height: 1;
  margin: 0;
  min-block-size: 2.25rem;
  min-inline-size: 2rem;
  padding: 0;
}

/* Six dots, in two columns. */
slab-sortable-list-item::part(handle)::before {
  content: '⠿' / '';
}

slab-sortable-list-item::part(handle):hover {
  color: var(--ink);
}

slab-sortable-list-item::part(handle):focus-visible {
  outline: 3px solid var(--ember);
  outline-offset: 2px;
}

slab-sortable-list-item:state(grabbed)::part(handle) {
  color: var(--ember-deep);
  cursor: grabbing;
}

slab-sortable-list-item::part(content) {
  flex: 1 1 auto;
  min-inline-size: 0;
  overflow-wrap: anywhere;
}
```

#### tokens.css

```css
:root {
  /* Secondary text. 6.8:1 and 6.9:1 on paper. */
  --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
  --border: 2px solid var(--ink);

  /* Behind disabled and read-only controls, and hovered rows. */
  --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

  /*
    The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
    enough for borders, fills and large text, but not always for small text,
    which takes "--ember-deep".
  */
  --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

  /*
    Orange for small text on paper, and for paper text on it. 5.7:1 and
    7.4:1.
  */
  --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
  --font-body: var(
    --slab-styled-font-body,
    'IBM Plex Sans',
    system-ui,
    sans-serif
  );
  --font-display: var(
    --slab-styled-font-display,
    'Zilla Slab',
    rockwell,
    'Roboto Slab',
    serif
  );
  --font-mono: var(
    --slab-styled-font-mono,
    'IBM Plex Mono',
    ui-monospace,
    monospace
  );
  --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
  --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

  /* The hard, offset shadow a raised surface casts. */
  --shadow: 4px 4px 0 var(--ink);
}

/*
  Forced colors, such as Windows' contrast themes, replace every color that
  isn't a system color, so ember fills and paper marks all become the same
  background, and a checked Checkbox looks like an unchecked one. The palette
  becomes the user's system colors instead, which are kept. Ember is the
  highlight, the color of what's selected, and ember-deep, being for text and
  for paper text on it, is the text color.
*/
@media (forced-colors: active) {
  :host {
    --ash: GrayText;
    --chalk: Canvas;
    --ember: Highlight;
    --ember-deep: CanvasText;
    --ink: CanvasText;
    --paper: Canvas;
  }
}
```
