Synertech Web/ui v0.57.5 Site Storybook

Documentation / Data

TreeView

Client@synertech/uiOpen in Storybook

A hierarchy the reader opens, closes and moves through: folders and files, categories, an organisation chart. FileSelector reads folders, Sidebar stops at navigation, DataGrid groups flat: TreeView shows the tree itself.

The tree is given as data (items), each node with its id, its label and its children. The ARIA tree pattern in full: one node in the tab order, the up and down arrows move through the nodes shown, the right arrow opens a branch then enters it, the left one closes it then goes up to the parent; Home and End, * opens the neighbouring branches, and the first letters of a name bring the focus to it.

Selection is of one node by default, of several with selectionMode (Ctrl or ⌘ + click, Shift + click, Space), and none with "none". checkable adds three-state boxes; loadChildren loads the children of a node marked hasChildren the first time it is opened. Open, selected, checked: each state is controlled (expanded, selected, checked) or held by the tree (defaultExpanded…). A "use client" component.

Examples

Basic usage

A file tree: a click on a folder opens and selects it, a click on a file selects it. From the keyboard, the arrows, Enter and the first letters of a name.

Open in a tab
import { useState } from "react";
import { TreeView, type TreeNode } from "@synertech/ui";

function Icon({ d }: { d: string }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.4}
      strokeLinejoin="round"
    >
      <path d={d} />
    </svg>
  );
}

const folder = <Icon d="M1.5 4h4.5l1.5 1.5h7v7.5h-13z" />;

const openFolder = <Icon d="M1.5 13V4h4.5l1.5 1.5h6V7M1.5 13l2-5.5h11l-2 5.5z" />;

const dir = (id: string, label: string, children: TreeNode[]): TreeNode => ({
  id,
  label,
  icon: folder,
  expandedIcon: openFolder,
  children,
});

const file = <Icon d="M4 1.5h5l3 3v10H4zM9 1.5v3h3" />;

const leaf = (id: string, label: string): TreeNode => ({ id, label, icon: file });

const PROJECT: TreeNode[] = [
  dir("src", "src", [
    dir("src/components", "components", [
      dir("src/components/button", "button", [
        leaf("src/components/button/Button.tsx", "Button.tsx"),
        leaf("src/components/button/index.ts", "index.ts"),
      ]),
      dir("src/components/chart", "chart", [
        leaf("src/components/chart/ChartAxis.tsx", "ChartAxis.tsx"),
        leaf("src/components/chart/ChartLegend.tsx", "ChartLegend.tsx"),
      ]),
    ]),
    dir("src/hooks", "hooks", [leaf("src/hooks/useDialogA11y.ts", "useDialogA11y.ts")]),
    leaf("src/index.ts", "index.ts"),
  ]),
  leaf("package.json", "package.json"),
  leaf("README.md", "README.md"),
];

export function Basic() {
  const [selected, setSelected] = useState<string[]>(["src/components/chart/ChartLegend.tsx"]);

  return (
    <div className="w-72">
      <TreeView
        aria-label="Fichiers du projet"
        items={PROJECT}
        defaultExpanded={["src", "src/components", "src/components/chart"]}
        selected={selected}
        onSelectionChange={setSelected}
      />
      <p className="mt-3 text-sm text-gray-600 dark:text-gray-300">
        Sélection : <code>{selected[0] ?? "aucune"}</code>
      </p>
    </div>
  );
}

Multiple selection

selectionMode="multiple": Ctrl or ⌘ + click adds or removes a node, Shift + click selects a run, Space and Shift + arrows do the same from the keyboard, Ctrl or ⌘ + A selects everything shown. A folder no longer opens on a click (expandOnClick={false}): the arrow before it does.

Open in a tab
import { useState } from "react";
import { TreeView, type TreeNode } from "@synertech/ui";

function Icon({ d }: { d: string }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.4}
      strokeLinejoin="round"
    >
      <path d={d} />
    </svg>
  );
}

const folder = <Icon d="M1.5 4h4.5l1.5 1.5h7v7.5h-13z" />;

const openFolder = <Icon d="M1.5 13V4h4.5l1.5 1.5h6V7M1.5 13l2-5.5h11l-2 5.5z" />;

const dir = (id: string, label: string, children: TreeNode[]): TreeNode => ({
  id,
  label,
  icon: folder,
  expandedIcon: openFolder,
  children,
});

const file = <Icon d="M4 1.5h5l3 3v10H4zM9 1.5v3h3" />;

const leaf = (id: string, label: string): TreeNode => ({ id, label, icon: file });

const PROJECT: TreeNode[] = [
  dir("src", "src", [
    dir("src/components", "components", [
      dir("src/components/button", "button", [
        leaf("src/components/button/Button.tsx", "Button.tsx"),
        leaf("src/components/button/index.ts", "index.ts"),
      ]),
      dir("src/components/chart", "chart", [
        leaf("src/components/chart/ChartAxis.tsx", "ChartAxis.tsx"),
        leaf("src/components/chart/ChartLegend.tsx", "ChartLegend.tsx"),
      ]),
    ]),
    dir("src/hooks", "hooks", [leaf("src/hooks/useDialogA11y.ts", "useDialogA11y.ts")]),
    leaf("src/index.ts", "index.ts"),
  ]),
  leaf("package.json", "package.json"),
  leaf("README.md", "README.md"),
];

export function MultipleSelection() {
  const [selected, setSelected] = useState<string[]>([]);

  return (
    <div className="w-72">
      <TreeView
        aria-label="Fichiers à partager"
        items={PROJECT}
        defaultExpanded={["src", "src/components"]}
        selectionMode="multiple"
        expandOnClick={false}
        selected={selected}
        onSelectionChange={setSelected}
      />
      <p className="mt-3 text-sm text-gray-600 dark:text-gray-300">
        {selected.length} élément(s) sélectionné(s)
      </p>
    </div>
  );
}

Three-state boxes

checkable: checking a group checks what it holds, a group partly checked is mixed. A disabled permission keeps its state. Here nothing is selected (selectionMode="none"): a click on a permission checks it, and so does Space.

Open in a tab
import { useState } from "react";
import { TreeView, type TreeNode } from "@synertech/ui";

const PERMISSIONS: TreeNode[] = [
  {
    id: "billing",
    label: "Facturation",
    children: [
      { id: "billing.read", label: "Consulter les factures" },
      { id: "billing.create", label: "Créer une facture" },
      { id: "billing.refund", label: "Rembourser", disabled: true },
    ],
  },
  {
    id: "clients",
    label: "Clients",
    children: [
      { id: "clients.read", label: "Consulter les fiches" },
      { id: "clients.edit", label: "Modifier les fiches" },
      { id: "clients.export", label: "Exporter la liste" },
    ],
  },
  { id: "reports", label: "Rapports" },
];

export function Checkable() {
  const [checked, setChecked] = useState<string[]>(["billing.read", "clients.read"]);
  const leaves = checked.filter((id) => id.includes("."));

  return (
    <div className="w-80">
      <TreeView
        aria-label="Permissions du rôle Comptable"
        items={PERMISSIONS}
        defaultExpanded={["billing", "clients"]}
        selectionMode="none"
        checkable
        checked={checked}
        onCheckedChange={setChecked}
      />
      <p className="mt-3 text-sm text-gray-600 dark:text-gray-300">
        {leaves.length} permission(s) accordée(s)
      </p>
    </div>
  );
}

Loading on demand

A hasChildren node without children asks loadChildren for them the first time it is opened, a spinner in place of its arrow. A rejected promise closes the node again and says so; opening it again retries (Ontario fails the first time). A branch loaded empty becomes a leaf.

Open in a tab
import { TreeView, type TreeNode } from "@synertech/ui";

const REGIONS: TreeNode[] = [
  { id: "qc", label: "Québec", hasChildren: true },
  { id: "on", label: "Ontario", hasChildren: true },
  { id: "nb", label: "Nouveau-Brunswick", hasChildren: true },
];

let attempts = 0;

const CITIES: Record<string, string[]> = {
  qc: ["Montréal", "Québec", "Gatineau", "Sherbrooke"],
  on: ["Toronto", "Ottawa", "Hamilton"],
  nb: [],
};

function fetchCities(node: TreeNode): Promise<TreeNode[]> {
  return new Promise((resolve, reject) =>
    setTimeout(() => {
      if (node.id === "on" && attempts++ === 0) {
        reject(new Error("Serveur indisponible"));
        return;
      }
      resolve((CITIES[node.id] ?? []).map((city) => ({ id: `${node.id}/${city}`, label: city })));
    }, 700)
  );
}

export function LoadOnDemand() {
  return (
    <div className="w-72">
      <TreeView
        aria-label="Villes par province"
        items={REGIONS}
        loadChildren={fetchCities}
        onLoadError={() => {}}
      />
    </div>
  );
}

Custom label

renderLabel draws the label of a node and is told its state (open, selected, level): here, the number of unread messages in a Chip, read from data. The node is still named by what the label holds.

Open in a tab
import { Chip, TreeView, type TreeNode } from "@synertech/ui";

const FOLDERS: TreeNode<{ unread: number }>[] = [
  { id: "inbox", label: "Boîte de réception", data: { unread: 12 } },
  {
    id: "projects",
    label: "Projets",
    data: { unread: 3 },
    children: [
      { id: "projects/boreal", label: "Atelier Boréal", data: { unread: 2 } },
      { id: "projects/eclat", label: "Éclat Studio", data: { unread: 1 } },
    ],
  },
  { id: "archive", label: "Archives", data: { unread: 0 } },
];

export function CustomLabel() {
  return (
    <div className="w-72">
      <TreeView
        aria-label="Dossiers"
        items={FOLDERS}
        defaultExpanded={["projects"]}
        defaultSelected={["inbox"]}
        renderLabel={(node) => (
          <span className="flex items-center justify-between gap-2">
            <span className="truncate">{node.label}</span>
            {node.data && node.data.unread > 0 ? (
              <Chip size="sm" variant="soft" color="primary">
                {node.data.unread}
              </Chip>
            ) : null}
          </span>
        )}
      />
    </div>
  );
}

API reference

Components

TreeView

ComponentClient

A hierarchy the reader opens, closes and moves through: folders and files, categories, an organisation chart.

The ARIA tree pattern in full: one node in the tab order, the arrows moving through the nodes shown (right opens a branch then enters it, left closes it then goes up to its parent), Home and End, * opening the siblings of the node, and the first letters of a name bringing the focus to it. Selection of one node or several, three-state boxes, and children loaded the first time their branch is opened.

import { TreeView } from "@synertech/ui";

Props — TreeViewProps

PropTypeDefaultDescription
items• TreeNode<T>[] —

The roots of the tree, each with its children.

checkable boolean false

A box before each node, with three states: checking a branch checks what is under it, and a branch with some of its children checked is mixed. Space and a click on the box check; a disabled node keeps its state.

checked string[] —

The checked nodes, when the application holds them.

defaultChecked string[] —

The nodes checked at first, when the tree holds them itself.

defaultExpanded string[] —

The branches open at first, when the tree holds them itself.

defaultSelected string[] —

The nodes selected at first, when the tree holds them itself.

emptyState ReactNode —

Shown in place of the tree when items is empty: an EmptyState of size sm.

expanded string[] —

The open branches, when the application holds them.

expandOnClick boolean true

A click or Enter on a branch opens or closes it, beside selecting it. false leaves that to the arrow before it and the arrow keys.

indent number 20

The step of each level, in pixels.

labels UILabelsOf<"treeView"> —

The texts of this tree, over those of the UILabelsProvider.

loadChildren (node: TreeNode<T>) => Promise<TreeNode<T>[]> —

Loads the children of a node marked hasChildren, the first time it is opened. The node shows a spinner meanwhile; a promise that fails closes it again, and opening it once more tries again.

onCheckedChange (checked: string[]) => void —

Called with every node checked, in the order of the tree: a branch whose children are all checked comes with them. A branch checked before its children were loaded stands for them.

onExpandedChange (expanded: string[]) => void —

Called with the open branches, in the order of the tree, when one opens or closes.

onLoadError (error: unknown, node: TreeNode<T>) => void —

Called when loadChildren fails. Without it, the error is written in the console.

onSelectionChange (selected: string[]) => void —

Called with the selected nodes, in the order of the tree.

renderLabel (node: TreeNode<T>, state: TreeItemState) => ReactNode —

Draws the label of a node in place of its label: a count, a badge.

selected string[] —

The selected nodes, when the application holds them.

selectionMode TreeSelectionMode "single"

How many nodes can be selected. single: a click or Enter selects one. multiple: Ctrl / ⌘ + click and Space add or remove one, Shift + click selects a run, Ctrl / ⌘ + A everything shown. none: a click only opens and closes.

+ 273 inherited native attributes from HTMLAttributes, AriaAttributes, DOMAttributes (className, id, aria-*, event handlers…).

Types

TreeItemState

Interface

What renderLabel is told about the node it draws.

interface TreeItemState
FieldTypeDefaultDescription
checked• TreeCheckState —
disabled• boolean —
expanded• boolean —
level• number —

1 for a root.

loading• boolean —

Its children are being loaded.

selected• boolean —

TreeNode

Interface

A node of a TreeView: a leaf, or a branch with children (or with hasChildren, its children loaded when it is first opened).

interface TreeNode<T = unknown>
FieldTypeDefaultDescription
id• string —

The identifier of the node, unique in the tree: what expanded, selected and checked hold.

label• ReactNode —

What the node shows: its name.

children TreeNode<T>[] —

The children of a branch. An empty array is a branch with nothing in it, drawn as a leaf.

data T —

Anything the application keeps with the node: a path, a record.

disabled boolean —

The node is shown, read and opened, but neither selected nor checked.

expandedIcon ReactNode —

The picture of an open branch, in place of icon: an open folder.

hasChildren boolean —

A branch whose children are not there yet: loadChildren is called the first time it is opened.

icon ReactNode —

A picture before the label, decorative: hidden from assistive technologies.

textValue string —

The text typing a first letter looks for. Left out, the text of label: give it when the label holds more than words.

The state of a node's box, in a tree with checkable.

type TreeCheckState = "checked" | "mixed" | "unchecked"

How many nodes the reader can select: none, one, or several.

type TreeSelectionMode = "none" | "single" | "multiple"