logo dile-components dile-components

dile-tree-view

Web Component to present and browse hierarchical data, such as folders and files, nested categories or taxonomies. Branches expand and collapse, nodes can be selected (one or several), and branches can load their children on demand. It follows the WAI-ARIA tree view pattern, keyboard included.

Installation

npm i @dile/ui

Usage

Import the component. This file registers both <dile-tree-view> and <dile-tree-node>.

import '@dile/ui/components/tree-view/tree-view.js';

Give it the nodes with the items property:

tree.items = [
  {
    value: 'docs',
    label: 'Documents',
    icon: 'lucide.folder',
    expandedIcon: 'lucide.folder-open',
    expanded: true,
    children: [
      { value: 'cv', label: 'CV.pdf', icon: 'lucide.file' },
    ],
  },
  { value: 'notes', label: 'Notes.txt', badge: 'new' },
];

Or compose the nodes with <dile-tree-node> child elements:

<dile-tree-view label="Files">
  <dile-tree-node value="docs" label="Documents" icon="lucide.folder" expanded>
    <dile-tree-node value="cv" label="CV.pdf" icon="lucide.file"></dile-tree-node>
  </dile-tree-node>
  <dile-tree-node value="notes" label="Notes.txt" badge="new"></dile-tree-node>
</dile-tree-view>

Note: there is always a single source of truth. When items is set, the child elements are ignored; otherwise the tree reads the <dile-tree-node> elements and watches them for changes. To change the data, assign a new items array (in-place mutations are not detected) or edit the markup.

Node data

Property Type Default Description
value String index path Unique identifier of the node. Used by value, expanded, events and methods. Without it, a position path like "0.2" is used.
label String value Text of the node.
icon String Icon in the dile-iconlib "family.name" format. Import the icon file you use (e.g. @dile/iconlib/lucide-icons/folder.js).
expandedIcon String Icon shown while the branch is expanded (attribute expanded-icon).
badge String Short status text shown after the label.
disabled Boolean false The node can be focused but not selected, expanded or collapsed.
expanded Boolean false Initial state: the branch is expanded the first time the node appears.
children Array Child nodes. A node with children (even []) is a branch; without it, a leaf. With markup, add the branch attribute to declare an empty branch.
lazy Boolean false Branch whose children are loaded on demand when it is expanded the first time.

Lazy branches

A node with lazy: true and no children is a branch that is not loaded yet. When it is expanded, the tree shows a spinner on it (aria-busy="true") and dispatches dile-tree-view-load. Provide the children in one of these ways:

tree.loadChildren = async (node) => {
  const response = await fetch(`/api/folders/${node.value}`);
  return response.json();
};

Once loaded, the branch keeps its children, so collapsing and expanding again does not load them again.

A lazy branch loads whenever it ends up expanded and visible (all its ancestors expanded), not only through expand(): from the initial expanded property or attribute, from a node's own expanded: true, or from a later change to expanded or to the data, such as a lazy node that appears inside a branch that is already expanded. In every case dile-tree-view-load is dispatched, because a load starts. A lazy branch listed in expanded inside a collapsed ancestor waits until it becomes visible.

There is only one request per branch while it loads. With loadChildren, collapsing and expanding the branch during the request does not start another one. Without loadChildren, collapsing the branch clears its loading state, so the next expansion dispatches dile-tree-view-load again. If loadChildren fails, the branch collapses and is not retried until it is expanded again.

Properties

Property Type Default Description
items Array undefined Node objects. When set, <dile-tree-node> children are ignored.
selection String "single" "single", "multiple" or "none". With "none", clicking a branch or pressing Enter toggles it.
value String | Array undefined Selected value (single) or array of values (multiple). As an attribute in multiple mode, a comma separated list.
expanded Array [] Values of the expanded branches. As an attribute, a comma separated list.
label String "" Accessible name of the tree.
disabled Boolean false Disables the whole tree.
expandOnClick Boolean false Clicking a branch row selects it and also toggles it. Exposed via expand-on-click.
emptyBranchText String "Empty" Text shown inside an expanded branch without children. Empty string to show nothing. Exposed via empty-branch-text.
emptyText String "" Text shown when the tree has no nodes. Exposed via empty-text.
loadChildren Function undefined Async (node) => children[] to load lazy branches.
contentRenderer Function undefined (node) => TemplateResult to render complementary content after the label.
selectedNodes Array Read only. Node objects of the selected nodes.

Setting value, expanded or items from outside does not dispatch events. When the data changes, the selection is kept as it is, and if the focused node disappears the focus goes back to the first node.

Methods

Events

All events bubble and are composed. node is the node object (from items, or built from the markup).

tree.addEventListener('dile-tree-view-selection-changed', (e) => {
  console.log('Selected', e.detail.value, e.detail.node);
});

CSS Shadow Parts

CSS Custom Properties

Custom property Description Default
--dile-tree-view-font-size Font size 1rem
--dile-tree-view-text-color Text color #1e293b
--dile-tree-view-background-color Background transparent
--dile-tree-view-border Border none
--dile-tree-view-border-radius Border radius 0
--dile-tree-view-padding Padding 0
--dile-tree-view-indent Indentation per level 1.25rem
--dile-tree-view-row-gap Gap between the parts of a row 0.4rem
--dile-tree-view-row-min-height Row minimum height 2rem
--dile-tree-view-row-padding-x Row horizontal padding 0.5rem
--dile-tree-view-row-padding-y Row vertical padding 0.25rem
--dile-tree-view-row-border-radius Row border radius 6px
--dile-tree-view-hover-background-color Row background on hover #f1f5f9
--dile-tree-view-focus-ring-color Focus outline color #12c9e9
--dile-tree-view-selected-background-color Selected row background #e0f2fe
--dile-tree-view-selected-text-color Selected row text color #075985
--dile-tree-view-selected-border-radius Selected row border radius var(--dile-tree-view-row-border-radius)
--dile-tree-view-selected-indicator-color Selected row start bar color (only visible when --dile-tree-view-selected-indicator-width is set) #0284c7
--dile-tree-view-selected-indicator-width Selected row start bar width. Set it (e.g. 3px) to show the bar 0px
--dile-tree-view-selected-font-weight Selected row font weight 600
--dile-tree-view-icon-size Node icon size 1.15rem
--dile-tree-view-icon-color Node icon color --dile-tree-view-text-color or #475569
--dile-tree-view-selected-icon-color Node icon color on selected rows --dile-tree-view-selected-text-color or #075985
--dile-tree-view-toggle-size Expand/collapse toggle box size 1.25rem
--dile-tree-view-toggle-icon-size Chevron size 1rem
--dile-tree-view-toggle-color Chevron color currentColor
--dile-tree-view-badge-background-color Badge background #e2e8f0
--dile-tree-view-badge-text-color Badge text color #334155
--dile-tree-view-badge-font-size Badge font size 0.75rem
--dile-tree-view-badge-padding Badge padding 0.2rem 0.45rem
--dile-tree-view-badge-border-radius Badge border radius 999px
--dile-tree-view-spinner-size Loading spinner size 1rem
--dile-tree-view-spinner-color Loading spinner color currentColor
--dile-tree-view-empty-color Empty texts color #64748b
--dile-tree-view-empty-font-size Empty texts font size 0.875em
--dile-tree-view-disabled-node-opacity Disabled node opacity 0.5
--dile-tree-view-disabled-opacity Disabled tree opacity 0.6

Accessibility

The component follows the WAI-ARIA tree view pattern:

Key Action
Down / Up Next / previous visible node
Right Expands a closed branch; on an open branch, moves to its first child
Left Collapses an open branch; otherwise moves to the parent
Home / End First / last visible node
Enter / Space Selects the node (toggles it in multiple mode); with selection="none", toggles the branch
* Expands all sibling branches of the focused node
Letters Type-ahead: moves to the next node whose label starts with the typed text

dile-tree-view demos

Basic usage

<script type="module">
  import '@dile/ui/components/tree-view/tree-view.js';
  import '@dile/iconlib/lucide-icons/folder.js';
  import '@dile/iconlib/lucide-icons/folder-open.js';
  import '@dile/iconlib/lucide-icons/file.js';
</script>
<dile-tree-view label="Files" value="cv">
  <dile-tree-node value="docs" label="Documents" icon="lucide.folder" expanded-icon="lucide.folder-open" expanded>
    <dile-tree-node value="cv" label="CV.pdf" icon="lucide.file"></dile-tree-node>
    <dile-tree-node value="letter" label="Letter.docx" icon="lucide.file" disabled></dile-tree-node>
    <dile-tree-node value="archive" label="Archive" icon="lucide.folder" expanded-icon="lucide.folder-open">
      <dile-tree-node value="old" label="Old notes.txt" icon="lucide.file"></dile-tree-node>
    </dile-tree-node>
  </dile-tree-node>
  <dile-tree-node value="empty" label="Empty folder" icon="lucide.folder" expanded-icon="lucide.folder-open" branch></dile-tree-node>
  <dile-tree-node value="notes" label="Notes.txt" icon="lucide.file" badge="new"></dile-tree-node>
</dile-tree-view>

Data, multiple selection and events

<script type="module">
  import { LitElement, html } from 'lit';

  class TreeViewSelectionDemo extends LitElement {
    static properties = { selected: { type: Array } };
    constructor() {
      super();
      this.selected = ['frontend'];
      this.items = [
        { value: 'web', label: 'Web development', expanded: true, children: [
          { value: 'frontend', label: 'Frontend', badge: '12' },
          { value: 'backend', label: 'Backend', badge: '8' },
        ] },
        { value: 'design', label: 'Design', children: [
          { value: 'ux', label: 'UX' },
          { value: 'ui', label: 'UI', disabled: true },
        ] },
      ];
    }
    render() {
      return html`
        <dile-tree-view
          label="Categories"
          selection="multiple"
          .items=${this.items}
          .value=${this.selected}
          @dile-tree-view-selection-changed=${(e) => this.selected = e.detail.value}
        ></dile-tree-view>
        <p>Selected: ${this.selected.join(', ') || 'none'}</p>
      `;
    }
  }
  customElements.define('tree-view-selection-demo', TreeViewSelectionDemo);
</script>
<tree-view-selection-demo></tree-view-selection-demo>

Lazy branches

<script type="module">
  const tree = document.getElementById('lazyTree');
  let counter = 0;
  tree.items = [
    { value: 'server', label: 'Remote server', icon: 'lucide.folder', expandedIcon: 'lucide.folder-open', lazy: true },
    { value: 'void', label: 'Empty remote folder', icon: 'lucide.folder', expandedIcon: 'lucide.folder-open', lazy: true },
  ];
  tree.loadChildren = (node) => new Promise((resolve) => {
    setTimeout(() => {
      if (node.value === 'void') return resolve([]);
      counter++;
      resolve([
        { value: `${node.value}-file-${counter}`, label: `File ${counter}.txt`, icon: 'lucide.file' },
        { value: `${node.value}-dir-${counter}`, label: `Subfolder ${counter}`, icon: 'lucide.folder', expandedIcon: 'lucide.folder-open', lazy: true },
      ]);
    }, 1000);
  });
</script>
<dile-tree-view id="lazyTree" label="Remote files"></dile-tree-view>

Without selection

With selection="none" the tree is only for browsing: clicking a branch toggles it.

<dile-tree-view label="Menu" selection="none">
  <dile-tree-node label="Settings" expanded>
    <dile-tree-node label="Profile"></dile-tree-node>
    <dile-tree-node label="Security"></dile-tree-node>
  </dile-tree-node>
  <dile-tree-node label="Help"></dile-tree-node>
</dile-tree-view>

Styled

<style>
  .styled-tree {
    --dile-tree-view-background-color: #1e1b4b;
    --dile-tree-view-text-color: #e0e7ff;
    --dile-tree-view-icon-color: #a5b4fc;
    --dile-tree-view-hover-background-color: #312e81;
    --dile-tree-view-selected-background-color: #4338ca;
    --dile-tree-view-selected-text-color: #ffffff;
    --dile-tree-view-badge-background-color: #fbbf24;
    --dile-tree-view-badge-text-color: #1e1b4b;
    --dile-tree-view-border-radius: 12px;
    --dile-tree-view-padding: 0.5rem;
  }
</style>
<dile-tree-view class="styled-tree" label="Projects" value="api">
  <dile-tree-node value="apps" label="Apps" icon="lucide.folder" expanded-icon="lucide.folder-open" expanded>
    <dile-tree-node value="api" label="API" icon="lucide.file" badge="3"></dile-tree-node>
    <dile-tree-node value="web" label="Web" icon="lucide.file"></dile-tree-node>
  </dile-tree-node>
</dile-tree-view>