Tree

Table of Contents

Basic Usage

Create a tree using the k-tree component. Set your data by setting the data property.

<k-tree id="myTree"></k-tree>
<script type="module">
import Tree from '/src/components/Tree.js';
const tree = document.getElementById('myTree');
tree.data = {
name: 'John Doe',
age: 30,
active: true,
hobbies: ['reading', 'coding'],
address: {
street: '123 Main St',
city: 'New York'
}
};
</script>

Controlling Initial Depth

Use the depth attribute to control how many levels of branches are open by default. This example shows depth set to 2:

<k-tree id="depthTree" depth="2"></k-tree>
<script type="module">
import Tree from '/src/components/Tree.js';
const tree = document.getElementById('depthTree');
tree.data = {
company: 'Tech Corp',
departments: {
engineering: {
frontend: ['Alice', 'Bob'],
backend: ['Charlie', 'Diana']
},
sales: {
team: ['Eve', 'Frank']
}
}
};
</script>

Custom Leaf Types

You can define custom leaf types to handle specific data types. Create a class that extends TreeLeaf, implement a detect static method that checks for specific properties, and a render method, then register it with Tree.addLeaf().

<k-tree id="customTree"></k-tree>
<script type="module">
import Tree, { TreeLeaf } from '/src/components/Tree.js';
import { html } from '../src/lit-all.min.js';

class DateLeaf extends TreeLeaf {
render(){
const { month, day, year } = this.value;
return html`<span class="tc-warning">📅 ${month}/${day}/${year}</span>`;
}

static detect = value => {
return typeof value === 'object'
&& value !== null
&& 'month' in value
&& 'day' in value
&& 'year' in value;
};
}

Tree.addLeaf(DateLeaf);

const tree = document.getElementById('customTree');
tree.data = {
event: 'Tech Conference 2025',
startDate: { month: 10, day: 15, year: 2025 },
endDate: { month: 10, day: 17, year: 2025 },
location: 'San Francisco',
attendees: 250
};
</script>

JavaScript Reference

Constructor

Extends ShadowComponent
new Tree()

Creates a new Tree component instance.

Requirements

Properties

data Object | Array

The data to display in the tree. Can be any JavaScript object or array. Nested objects and arrays will be rendered as collapsible branches.

depth Number default: 0

The number of branch levels that should be open by default. A value of 0 means all branches are closed, 1 means the first level is open, 2 means the first two levels are open, etc. This property is reflected as an attribute.

editable Boolean

Whether the tree should be editable. Note: This feature is not yet implemented.

Methods

Tree.addLeaf(...leafClasses) Static

Register one or more custom leaf classes. Leaf classes should extend TreeLeaf and implement:

Leafs are checked in order of registration (most recently added first).

Default Leaf Types

The Tree component comes with built-in leaf types for JavaScript primitives:

Objects and arrays that don't match any registered leaf type are rendered as collapsible branches.