# Tree

> A nested list of items that expand and collapse, to pick one or more from.

`<slab-tree>` · Navigation · built on `[role=tree]`

## Install

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

## Usage

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

<slab-tree label="Files">
  <slab-tree-item expanded>
    src
    <slab-tree-item>index.ts</slab-tree-item>
  </slab-tree-item>
  <slab-tree-item>README.md</slab-tree-item>
</slab-tree>
```

## Example

Here's a styled version, `<slab-styled-tree>`. 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-tree label="Site plan">
  <slab-styled-tree-item expanded>
    Foundation
    <slab-styled-tree-item>Footings</slab-styled-tree-item>
    <slab-styled-tree-item selected>House slab</slab-styled-tree-item>
    <slab-styled-tree-item>Garage slab</slab-styled-tree-item>
  </slab-styled-tree-item>
  <slab-styled-tree-item>
    Framing
    <slab-styled-tree-item>Walls</slab-styled-tree-item>
    <slab-styled-tree-item>Roof</slab-styled-tree-item>
  </slab-styled-tree-item>
  <slab-styled-tree-item disabled>Driveway, next spring</slab-styled-tree-item>
</slab-styled-tree>
```

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.

## Keyboard

| Key          | What it does                                                                   |
| ------------ | ------------------------------------------------------------------------------ |
| Up, Down     | Moves through the Tree Items that can be seen, skipping disabled ones.         |
| Home, End    | Moves to the first or last Tree Item.                                          |
| Right        | Expands a collapsed Tree Item, or moves to the first child of an expanded one. |
| Left         | Collapses an expanded Tree Item, or moves to the parent of one that isn't.     |
| *            | Expands every Tree Item with children at the active one's level.               |
| A character  | Moves to the next Tree Item whose label starts with what's typed.              |
| Enter, Space | Selects the active Tree Item, or toggles it when `multiple` is set.            |

With `multiple`, Shift with Up or Down moves and toggles, Shift with Space
selects from the last selected Tree Item to the active one, Control or
Command with Shift and Home or End selects from the active one to the first
or last, and Control or Command with A selects every one, or none.

## Behavior

### `<slab-tree>`

A tree with no visual styles: a `[role=tree]` of Tree Items, which nest, to select one or, when `multiple` is set, more from.

It's the APG's tree view. Focus stays on the tree, and its `aria-activedescendant` points at the active Tree Item, which is the first one or the selected one until the user moves. Down and Up move through the Tree Items that can be seen, skipping disabled ones, and Home and End go to the first and last. Right expands a collapsed Tree Item, or moves to the first child of an expanded one. Left collapses an expanded Tree Item, or moves to the parent of one that isn't. `*` expands every Tree Item with children at the active one's level. Typing moves to the next Tree Item whose label starts with what was typed. Enter, Space and a click select the active Tree Item, and a click expands or collapses one that has children.

When `multiple` is set, Enter, Space and a click toggle the Tree Item instead, and Shift with the Down or Up arrow moves and toggles. Shift with Space selects every Tree Item that can be seen from the one last selected to the active one, and Control or Command with Shift and Home or End selects every one from the active one to the first or last, moving there. Control or Command with A selects every enabled Tree Item, at every depth, or none when they all are already. These are the APG's keys for a multi-select tree.

Style it through its part, and each Tree Item through its own parts and states.

### `<slab-tree-item>`

A Tree Item with no visual styles. The host is the tree item, so style it directly, and its label and nested Tree Items through its parts.

Tree Items nested in it are its children. Each puts itself in its parent's `item` slot, inside a `[role=group]` that's `display: none` while the parent is collapsed.

It's never focused. Focus stays on its Tree, which points at the active Tree Item with `aria-activedescendant`.

Its Tree sets `:state(active)`. It sets `:state(disabled)`, `:state(expanded)`, `:state(parent)` when it has children, and `:state(selected)` itself.

## API

### `<slab-tree>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | Names the tree. |
| `multiple` | `boolean` | `false` |  |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `items` (read-only) | `TreeItem[]` | Every Tree Item, at every depth, in order. |
| `selectedItem` (read-only) | `TreeItem \| null` |  |
| `selectedItems` (read-only) | `TreeItem[]` | Every selected Tree Item, at every depth, in order. |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `change` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `TreeItem` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `tree` | The Tree Items |

### `<slab-tree-item>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `disabled` | `boolean` | `false` |  |
| `expanded` | `boolean` | `false` | Whether its children are shown, when it has any. |
| `label` | `string` |  | Names the Tree Item in place of its text, and is what typeahead matches against. |
| `selected` | `boolean` | `false` | Like Option's, the attribute is the default state and the property is the current one. Style `:state(selected)` rather than `[selected]`. |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `items` (read-only) | `TreeItem[]` | Its children. |
| `text` (read-only) | `string` | What the user reads as the Tree Item's name: its label, or its own text when it has no label. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `Element \| string` | The label, plus anything else a design puts in a Tree Item |
| `item` | `TreeItem` | Its children. A nested Tree Item puts itself here. |

#### CSS parts

| Name | Description |
| --- | --- |
| `group` | Its children |
| `label` | The label |

## Copy and own it

`<slab-styled-tree>` isn't in the package. It's an example — copy it into your project and change whatever you want. Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. 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.

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.

### tree.ts

```ts
import { customElement } from 'lit/decorators.js';
import Tree from 'slab-elements/tree.js';
import styles from './tree.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-tree': StyledTree;
  }
}

/**
 * Tree, styled: its Tree Items in an ink-bordered box that casts an ember
 * shadow while it's focused.
 */
@customElement('slab-styled-tree')
export default class StyledTree extends Tree {
  static override styles = [tokens, styles];
}
```

### tree.styles.ts

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

/*
  Focus stays on the tree and the active Tree Item shows where the keyboard
  is, so the tree's own focus is the shadow, as Listbox's is.
*/
export default css`
  [part~='tree'] {
    background-color: var(--paper);
    border: var(--border);
    color: var(--ink);
    font-family: var(--font-body);
    padding: 0.25rem 0;
    transition: box-shadow 100ms;

    &:focus-visible {
      box-shadow: 4px 4px 0 var(--ember);
      outline: 2px solid transparent;
    }

    @media (prefers-reduced-motion: reduce) {
      transition: none;
    }
  }
`;
```

### tree.item.ts

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

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-tree-item': StyledTreeItem;
  }
}

/**
 * Tree Item, styled: a row with a chevron that turns down when it's
 * expanded, inverting to paper on ink while it's active, as Option does.
 * Its children are indented under a rule.
 */
@customElement('slab-styled-tree-item')
export default class StyledTreeItem extends TreeItem {
  static override styles = [tokens, styles];
}
```

### tree.item.styles.ts

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

export default css`
  [part~='label'] {
    align-items: center;
    border-inline-start: 4px solid transparent;
    cursor: pointer;
    display: flex;
    gap: 0.5rem;
    padding: 0.375rem 0.75rem;
    transition:
      background-color 100ms,
      color 100ms;

    /*
      The chevron, a corner of border, turned to point at the children. A Tree
      Item with none keeps the room, so labels line up.
    */
    &::before {
      block-size: 0.4375rem;
      content: '';
      flex-shrink: 0;
      inline-size: 0.4375rem;
      rotate: -45deg;
      transition: rotate 150ms;
    }

    &:hover {
      background-color: var(--chalk);
    }
  }

  :host(:state(parent)) [part~='label']::before {
    border-block-end: 2px solid currentcolor;
    border-inline-end: 2px solid currentcolor;
  }

  :host(:state(expanded)) [part~='label']::before {
    rotate: 45deg;
  }

  :host(:state(selected)) [part~='label'] {
    border-inline-start-color: var(--ember);
    font-weight: 600;
  }

  /* After ":hover", which ":state(active)" wins over. */
  :host(:state(active)) [part~='label'] {
    background-color: var(--ink);
    color: var(--paper);
  }

  :host(:state(disabled)) [part~='label'] {
    color: var(--ash);
    cursor: not-allowed;
    text-decoration: line-through;
  }

  [part~='group'] {
    border-inline-start: 2px solid var(--chalk);
    margin-inline-start: 1.125rem;
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='label'],
    [part~='label']::before {
      transition: none;
    }
  }
`;
```

### 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);
  }
`;
```
