<!--
  GENERATED FILE - do not edit by hand.
  Source of truth: src/components/mds-tree/usage/ in the magma monorepo.
-->

# mds-tree - examples

> The API of this component: [`AGENTS.md`](AGENTS.md).

Correct and idiomatic ways to use the `<mds-tree>` component, ordered from most common to most specialized. The examples assume a working knowledge of the shared component rules in [`agents/conventions.md`](../../../../agents/conventions.md).

#### Nested Hierarchy

The canonical form: the root-level `<mds-tree-item>` elements are direct children of `<mds-tree>`, and `<mds-tree-item>` elements placed inside other `<mds-tree-item>` elements build depth. The tree seeds `depth = 0` on direct children, which drops their branch connector lines; nested items are indented by their nesting.

```html
<mds-tree>
  <mds-tree-item label="Direzione generale">
    <mds-tree-item label="Segreteria">
      <mds-tree-item label="Protocollo"></mds-tree-item>
      <mds-tree-item label="Archivio"></mds-tree-item>
    </mds-tree-item>
    <mds-tree-item label="Risorse umane"></mds-tree-item>
  </mds-tree-item>
</mds-tree>
```

#### Flat List

Root-level nodes with no nesting are valid too, every `<mds-tree-item>` a direct child of `<mds-tree>`. With no branch to open the tree reads as a plain list.

```html
<mds-tree>
  <mds-tree-item label="Bacheca"></mds-tree-item>
  <mds-tree-item label="Documenti"></mds-tree-item>
  <mds-tree-item label="Impostazioni"></mds-tree-item>
</mds-tree>
```

#### Programmatic Expand / Collapse

Change `expanded` on `<mds-tree>` at runtime to open or close the entire hierarchy at once. This cascades to all descendant items except those marked `async`, also when `expanded` is set in the markup; to start with a single branch open set `expanded` on that item instead.

```html
<!-- A branch expanded on mount -->
<mds-tree id="albero-pratiche">
  <mds-tree-item label="Pratiche in corso" expanded>
    <mds-tree-item label="Pratica 001/2025"></mds-tree-item>
    <mds-tree-item label="Pratica 002/2025"></mds-tree-item>
  </mds-tree-item>
</mds-tree>

<script>
  // Open or close the whole hierarchy later
  document.getElementById('albero-pratiche').expanded = true;
</script>
```

#### Folder Toggle Style

Use `toggle="folder"` for file-explorer metaphors. The toggle icon switches between a closed and open folder glyph when the item is expanded or collapsed.

```html
<mds-tree toggle="folder" actions="visible">
  <mds-tree-item label="Fascicoli">
    <mds-tree-item label="2025">
      <mds-tree-item label="Fascicolo 001"></mds-tree-item>
      <mds-tree-item label="Fascicolo 002"></mds-tree-item>
    </mds-tree-item>
    <mds-tree-item label="2024">
      <mds-tree-item label="Fascicolo 099"></mds-tree-item>
    </mds-tree-item>
  </mds-tree-item>
</mds-tree>
```

#### Right-Positioned Toggle for Navigation Menus

Set `toggle-position="right"` and `appearance="none"` for a flat navigation-menu look where the expand chevron sits at the trailing edge of the row.

```html
<mds-tree toggle="chevron" toggle-position="right" appearance="none">
  <mds-tree-item label="Protocollazione documenti">
    <mds-tree-item label="Nuovo protocollo in arrivo"></mds-tree-item>
    <mds-tree-item label="Nuovo protocollo in partenza"></mds-tree-item>
  </mds-tree-item>
  <mds-tree-item label="Gestione allegati">
    <mds-tree-item label="Scansione multipla"></mds-tree-item>
  </mds-tree-item>
</mds-tree>
```

#### Per-Item Actions via the `action` Slot

Slot `<mds-button>` or `<mds-icon>` elements into each `<mds-tree-item>` with `slot="action"`. Use `actions="auto"` (default) to reveal them on hover, or `actions="visible"` to always show them.

```html
<mds-tree actions="auto">
  <mds-tree-item label="Relazione annuale 2025">
    <mds-button
      slot="action"
      icon="mi/baseline/download"
      variant="dark"
      tone="text"
      title="Scarica"
    ></mds-button>
    <mds-button
      slot="action"
      icon="mi/baseline/more-vert"
      variant="dark"
      tone="text"
      title="Altre opzioni"
    ></mds-button>
    <mds-tree-item label="Capitolo 1"></mds-tree-item>
    <mds-tree-item label="Capitolo 2"></mds-tree-item>
  </mds-tree-item>
</mds-tree>
```

#### Listening to Expand and Collapse Events

`<mds-tree-item>` emits `mdsTreeItemCollapse` when it closes, and `mdsTreeItemExpand` only when an item marked `async` is asked to open (see below): opening a regular item emits nothing. Both events bubble, so one listener on the tree catches them. Listen via `addEventListener` - do not rely on native `change` / `click` bubbling through shadow DOM.

```html
<mds-tree id="albero-categorie">
  <mds-tree-item label="Categoria A">
    <mds-tree-item label="Sottocategoria A1"></mds-tree-item>
  </mds-tree-item>
</mds-tree>

<script>
  // emitted only by items marked async
  document.getElementById('albero-categorie').addEventListener('mdsTreeItemExpand', (event) => {
    console.log('espanso:', event.detail.element.label);
  });

  document.getElementById('albero-categorie').addEventListener('mdsTreeItemCollapse', (event) => {
    console.log('collassato:', event.detail.element.label);
  });
</script>
```

#### Async Lazy-Loading Branches

Mark a `<mds-tree-item>` with `async` when its children must be fetched on demand. The item shows a loading spinner on click and emits `mdsTreeItemExpand`. Resolve the branch by calling `element.expand()` on the item once data is ready, then remove `async` so that reopening the branch later does not fetch it again. An item looks for child items only when it first renders: one that has none then shows no toggle (and no spinner), and children appended later do not add it.

```html
<mds-tree>
  <mds-tree-item label="Comune di Rimini" icon="mgg/historic-building">
    <mds-tree-item label="Ufficio" async class="ufficio-item" icon="mi/baseline/desk">
      <!-- children appended by the script below -->
    </mds-tree-item>
  </mds-tree-item>
</mds-tree>

<script>
  document.querySelector('.ufficio-item').addEventListener('mdsTreeItemExpand', async (event) => {
    const { element } = event.detail;
    if (!element.async) return;
    const children = await fetchChildren(element.label);
    children.forEach((nome) => {
      const item = document.createElement('mds-tree-item');
      item.label = nome;
      element.appendChild(item);
    });
    element.expand();
    element.async = false;
  });
</script>
```

#### Icon on Individual Items

Use the `icon` prop on `<mds-tree-item>` to show a glyph next to the label. Reference icons by their slug from the Magma icon library.

```html
<mds-tree toggle="chevron">
  <mds-tree-item label="Comune di Rimini" icon="mgg/historic-building">
    <mds-tree-item label="Sindaco" icon="mdi/handshake">
      <mds-tree-item label="Segretario generale" icon="mi/baseline/draw"></mds-tree-item>
    </mds-tree-item>
  </mds-tree-item>
</mds-tree>
```

#### Styling Customization

The only public CSS custom property of the tree is `--mds-tree-line-clamp`, the number of lines a label keeps with `truncate="all"` (2 by default). The colours of the labels, branches and toggles, their spacing and the transitions follow the semantic roles, so dark mode and high-contrast modes keep working: shape the tree with its props (`appearance`, `toggle`, `toggle-position`, `truncate`, `actions`) instead. Set the property on the host element or a parent selector.

```css
.navigazione-laterale mds-tree {
  --mds-tree-line-clamp: 3;
}
```

The toggle of an open item takes its expanded colours, and the connectors of the branches follow the distance between the toggle and the label of every item.
