Tree
Browse and select items in a nested list.
Demos
Button.vue selected
Usage
<script setup lang="ts">
import { Accordion } from '~/components/ui/accordion'
const items = [
{ value: 'source', label: 'Do I own the source?', content: 'Yes. Copy and adapt the files.' },
]
</script>
<template>
<Accordion :items="items" />
</template>
Selection highlight
Use selection-highlight to control the width of the selected area and sliding hover:
full: spans the row width, including indentation.indented: starts after the node's indentation and fills the remaining content width.label: wraps the label text.
Switch between these scopes with Selection highlight in the playground above. This controls appearance; selection-mode controls whether users can select one, multiple, or no nodes.
<AppLayout :viewport="false" scroll="page">
<template #header>Workspace</template>
<template #left><ProjectNavigation /></template>
<ProjectList />
<template #footer>2 projects</template>
</AppLayout>
Multiple selection
Select a branch to select its descendants. A partial selection shows a dash, and check marks stay at the trailing edge. Disclosure buttons expand independently from selection.
1 selected
<AppLayout :layout="{ header: 'full', footer: 'content' }">
<template #left><ProjectNavigation /></template>
<ProjectList />
<template #right><ProjectDetails /></template>
</AppLayout>
Loading branches
Use has-children for a branch that has not loaded yet. Add its key to loading-keys during the request, then update its children. The disclosure shows progress while you load data.
No item selected
Large trees
This example renders a window of 1,000 files. Row height follows size, including touch targets. Arrow keys and typeahead keep working; Home and End move to the first and last enabled item.
No item selected
Set virtualize to true or an options object. IPEX calculates the item height from the selected size and its 2px row spacing. Override itemHeight when you provide custom row geometry; it must include that spacing.
Empty state
Use labels.empty for a message or the empty slot for custom content.
Installation
Complete the shared installation. Copy Tree.vue and index.ts into app/components/ui/tree/.
<script setup lang="ts" generic="T extends object">
import { Tree as Primitive } from 'akaza-ui'
import type * as Akaza from 'akaza-ui'
import {
computed,
nextTick,
onMounted,
onBeforeUnmount,
ref,
watch,
useAttrs,
useTemplateRef,
} from 'vue'
import { cn } from '../../../utils/ui'
import uiConfig from '../ui.config'
import {
treeVariants,
treeGeometry,
resolveTreeVariants,
type TreeProps,
type TreeSlots,
} from './index'
defineOptions({ inheritAttrs: false })
// Preserve Akaza defaults when optional props, including Boolean aliases, are omitted.
const props = withDefaults(defineProps<TreeProps<T>>(), {
labelKey: undefined,
childrenKey: undefined,
disabledKey: undefined,
selectableKey: undefined,
defaultExpandedKey: undefined,
slotKey: undefined,
textValue: undefined,
hasChildren: undefined,
defaultValue: undefined,
defaultExpanded: undefined,
loadingKeys: undefined,
selectionMode: undefined,
selectionBehavior: undefined,
selectionPropagation: undefined,
selectionHighlight: 'full',
selectOnFocus: undefined,
expandOnClick: undefined,
disabled: undefined,
readOnly: undefined,
typeahead: undefined,
transition: undefined,
indent: undefined,
orientation: undefined,
dir: undefined,
virtualize: undefined,
ariaLabel: undefined,
ariaLabelledby: undefined,
ariaDescribedby: undefined,
labels: undefined,
as: undefined,
ui: undefined,
modelValue: undefined,
expanded: undefined,
})
defineSlots<TreeSlots<T>>()
const attrs = useAttrs()
const resolvedVariants = computed(() => resolveTreeVariants(props, uiConfig))
const styles = computed(() => treeVariants(resolvedVariants.value))
const geometry = computed(() => treeGeometry[resolvedVariants.value.size ?? 'sm'])
const coarsePointer = ref(false)
let pointerQuery: MediaQueryList | undefined
function updatePointer() {
coarsePointer.value = pointerQuery?.matches ?? false
}
onMounted(() => {
pointerQuery = window.matchMedia('(pointer: coarse)')
updatePointer()
pointerQuery.addEventListener('change', updatePointer)
})
onBeforeUnmount(() => pointerQuery?.removeEventListener('change', updatePointer))
const virtualOptions = computed(() => {
if (!props.virtualize) return false
const options = typeof props.virtualize === 'object' ? props.virtualize : {}
return {
...options,
itemHeight:
options.itemHeight ?? Math.max(coarsePointer.value ? 44 : 0, geometry.value.rowHeight) + 2,
}
})
const mergedUi = computed(() => {
const overrides = props.ui as Record<string, string | undefined> | undefined
return Object.fromEntries(
Object.entries(styles.value).map(([part, style]) => [
part,
cn(
style(),
part === 'toggleIcon' && props.transition === false ? 'transition-none' : undefined,
part === 'viewport' && props.virtualize ? 'max-h-none' : undefined,
part === 'viewport' && props.transition === false ? 'before:transition-none' : undefined,
overrides?.[part],
part === 'root' ? props.class : undefined,
),
]),
)
})
const primitiveProps = computed(() => {
const { class: _class, ui: _ui, size: _size, variant: _variant, ...native } = props
return {
...native,
indent: props.indent ?? geometry.value.indent,
virtualize: virtualOptions.value,
}
})
const primitive = useTemplateRef<
{ tree: Akaza.TreeController<T>; $el: HTMLElement } & Pick<
Akaza.TreeController<T>,
| 'getNode'
| 'getItem'
| 'focus'
| 'select'
| 'toggleSelection'
| 'expand'
| 'collapse'
| 'toggleExpanded'
| 'expandAll'
| 'collapseAll'
| 'activate'
>
>('primitive')
let hoveredItem: HTMLElement | null = null
let hoverObserver: ResizeObserver | undefined
let itemObserver: MutationObserver | undefined
function hoverViewport() {
return primitive.value?.$el?.querySelector<HTMLElement>('.akaza-tree-viewport')
}
function updateHover() {
const viewport = hoverViewport()
if (!viewport) return
const target =
hoveredItem?.isConnected && !hoveredItem.hasAttribute('aria-disabled')
? hoveredItem.querySelector<HTMLElement>('.akaza-tree-selection')
: null
if (!target) {
viewport.style.setProperty('--tree-hover-opacity', '0')
return
}
const origin = viewport.getBoundingClientRect()
const rect = target.getBoundingClientRect()
viewport.style.setProperty('--tree-hover-x', `${rect.left - origin.left + viewport.scrollLeft}px`)
viewport.style.setProperty('--tree-hover-y', `${rect.top - origin.top + viewport.scrollTop}px`)
viewport.style.setProperty('--tree-hover-width', `${rect.width}px`)
viewport.style.setProperty('--tree-hover-height', `${rect.height}px`)
viewport.style.setProperty('--tree-hover-radius', getComputedStyle(target).borderRadius)
viewport.style.setProperty(
'--tree-hover-opacity',
hoveredItem?.getAttribute('aria-selected') === 'true' ? '0' : '1',
)
}
function onItemHover(event: PointerEvent) {
if (event.pointerType === 'touch') return
hoveredItem =
event.target instanceof Element ? event.target.closest<HTMLElement>('.akaza-tree-item') : null
updateHover()
}
function clearHover() {
hoveredItem = null
updateHover()
}
onMounted(() => {
const viewport = hoverViewport()
if (!viewport) return
hoverObserver = new ResizeObserver(updateHover)
hoverObserver.observe(viewport)
const wrapper = viewport.querySelector('.akaza-tree-virtual-wrapper')
if (wrapper) hoverObserver.observe(wrapper)
itemObserver = new MutationObserver(updateHover)
itemObserver.observe(viewport, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['aria-selected', 'aria-disabled'],
})
viewport.addEventListener('scroll', clearHover, { passive: true })
})
onBeforeUnmount(() => {
hoverObserver?.disconnect()
itemObserver?.disconnect()
hoverViewport()?.removeEventListener('scroll', clearHover)
})
watch(
() => [props.selectionHighlight, props.size, props.modelValue, props.indent, props.dir],
() => {
void nextTick(updateHover)
},
{ flush: 'post' },
)
watch(
() => virtualOptions.value && virtualOptions.value.itemHeight,
(height, previous) => {
if (!height) return
const viewport = primitive.value?.$el?.querySelector<HTMLElement>('.akaza-tree-viewport')
const anchor = viewport && previous ? Math.floor(viewport.scrollTop / previous) : 0
void nextTick(() => {
if (!viewport) return
viewport.scrollTop = anchor * height
viewport.dispatchEvent(new Event('scroll'))
})
},
)
defineExpose({
get tree() {
return primitive.value!.tree
},
get getNode() {
return primitive.value!.getNode
},
get getItem() {
return primitive.value!.getItem
},
get focus() {
return primitive.value!.focus
},
get select() {
return primitive.value!.select
},
get toggleSelection() {
return primitive.value!.toggleSelection
},
get expand() {
return primitive.value!.expand
},
get collapse() {
return primitive.value!.collapse
},
get toggleExpanded() {
return primitive.value!.toggleExpanded
},
get expandAll() {
return primitive.value!.expandAll
},
get collapseAll() {
return primitive.value!.collapseAll
},
get activate() {
return primitive.value!.activate
},
})
</script>
<template>
<component
:is="Primitive"
ref="primitive"
v-bind="{ ...primitiveProps, ...attrs }"
:ui="mergedUi"
@pointerover="onItemHover"
@pointerleave="clearHover"
@transitionend="updateHover"
>
<template v-if="!$slots.empty" #empty>
<svg
class="size-7 text-dimmed"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
>
<path
d="M3 7h6l2 2h10v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm0 0V5a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v2"
/>
</svg>
<span>{{ labels?.empty ?? 'No items to display.' }}</span>
</template>
<template v-if="selectionMode === 'multiple' && !$slots.trailing" #trailing="{ node }">
<span
:class="mergedUi.selectionIndicator"
:data-state="node.isIndeterminate ? 'mixed' : node.isSelected ? 'checked' : 'unchecked'"
aria-hidden="true"
>
<svg
v-if="node.isSelected || node.isIndeterminate"
class="size-full"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
stroke-width="1.5"
>
<path :d="node.isIndeterminate ? 'M4 8h8' : 'm4 8 3 3 5-6'" />
</svg>
</span>
<span v-if="node.isIndeterminate" class="sr-only">Partially selected</span>
</template>
<template v-if="!$slots.toggle" #toggle="{ node }">
<svg
:class="[mergedUi.toggleIcon, node.isLoading && 'motion-safe:animate-spin']"
:data-akaza-state="node.isExpanded ? 'expanded' : 'collapsed'"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
aria-hidden="true"
>
<path :d="node.isLoading ? 'M12 3a9 9 0 1 0 9 9' : 'm9 5 7 7-7 7'" />
</svg>
</template>
<template v-for="(_, name) in $slots" #[name]="scope"
><slot :name="name as keyof TreeSlots<T>" v-bind="scope ?? {}"
/></template>
</component>
</template>
API
Variants and defaults
| Prop | Values | Default |
|---|---|---|
variant | soft, subtle | soft |
size | xs, sm, md, lg, xl | sm |
soft uses the same neutral selection fill as the sidebar. subtle adds an inset border. Tree selection defaults to the full row; choose indented or label when the selected area should follow the hierarchy more closely. Focus rings appear for keyboard navigation. Hover moves between nodes with a sliding highlight that follows the same boundary.
Row height, disclosure target, icons, text, padding, and corners scale together. Branches and leaves at the same depth share one label column. Default indent steps are 12/16/20/24/28px for xs/sm/md/lg/xl; an explicit indent overrides them.
Models
| Model | Type | Default | Description |
|---|---|---|---|
v-model | TreeKey | TreeKey[] | null | null | Selected key in single mode or selected keys in multiple mode. |
v-model:expanded | TreeKey[] | defaultExpanded | Expanded branch keys. |
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items | readonly T[] | required | Nested tree data. |
itemKey | keyof T | (item) => TreeKey | required | Stable, globally unique item key. |
labelKey | keyof T | (item) => unknown | "label" | Label accessor. |
childrenKey | keyof T | (item) => T[] | "children" | Child collection accessor. |
disabledKey | keyof T | (item) => unknown | "disabled" | Disabled state accessor. |
selectableKey | keyof T | (item) => unknown | "selectable" | Selectable state accessor. |
defaultExpandedKey | keyof T | (item) => unknown | "defaultExpanded" | Initial expansion accessor. |
slotKey | keyof T | (item) => unknown | "slot" | Dynamic item slot accessor. |
textValue | (item: T) => string | label text | Text used by typeahead. |
hasChildren | (item: T) => boolean | - | Marks a branch before its children are loaded. |
defaultValue | TreeSelection | null | Initial uncontrolled selection. |
defaultExpanded | TreeKey[] | item defaults | Initial uncontrolled expansion. |
loadingKeys | readonly TreeKey[] | [] | Branches currently loading children. |
selectionMode | "none" | "single" | "multiple" | "single" | Selection mode. |
selectionBehavior | "replace" | "toggle" | "toggle" | Multiple-selection behavior without a modifier key. |
selectionPropagation | "none" | "up" | "down" | "both" | "none" | Branch selection propagation. |
selectionHighlight | "full" | "indented" | "label" | "full" | Visual boundary used by ui.selection; ARIA selection remains on the complete item. |
selectOnFocus | boolean | false | Selects a node when roving focus reaches it. |
expandOnClick | boolean | true | Toggles a branch when its non-interactive row content is clicked. Toggle buttons always work. |
disabled | boolean | false | Disables the tree. |
readOnly | boolean | false | Blocks selection changes while preserving navigation and expansion. |
typeahead | boolean | true | Enables printable-character navigation. |
transition | boolean | true | Enables built-in branch row motion. Ignored during virtualization. |
indent | number | size-dependent | Indentation in pixels for each nested level. |
orientation | "vertical" | "horizontal" | "vertical" | Navigation orientation. |
dir | "ltr" | "rtl" | "ltr" | Text direction and horizontal Arrow behavior. |
virtualize | boolean | TreeVirtualOptions | false | Enables fixed-height row virtualization. |
ariaLabel | string | "Tree" | Accessible tree label. |
ariaLabelledby | string | - | Id of an accessible label. |
ariaDescribedby | string | - | Id of supporting text. |
labels | TreeLabels<T> | - | Expand, collapse, loading, and empty labels. |
as | string | Component | "div" | Root element or component. |
ui | TreeUi | - | Classes for structural parts. |
TreeVirtualOptions accepts height, itemHeight, and overscan numbers.
Slots
| Slot | Props | Description |
|---|---|---|
item | item, node, actions, toggleProps, tree | Replaces generated content inside every row. |
item-[name] | same as item | Content replacement selected by an item's slot value. |
toggle | item, node, actions, toggleProps, tree | Toggle content inside the generated button. |
indicator | item, node, actions, toggleProps, tree | Selection indicator. |
icon | item, node, actions, toggleProps, tree | Item icon. |
label | item, node, actions, toggleProps, tree | Item content. May contain a title and supporting text. |
trailing | item, node, actions, toggleProps, tree | Trailing content or controls. |
loading | item, node, actions, toggleProps, tree | Expanded lazy-branch loading content. |
empty | tree | Empty state. |
node exposes key, parent, depth, sibling position, label, and branch, expansion, selection, indeterminate, focus, disabled, selectable, and loading state.
Events
| Event | Payload | Description |
|---|---|---|
selection-change | (value, details) | Fired before selection updates. |
expanded-change | (keys, details) | Fired before expansion updates. details.expanded reports the requested branch state. |
focus-change | (key, details) | Fired before the roving focus key changes. |
activate | (item, details) | Fired on row click, touch, or Enter. |
Event details include key, item, reason, the original event when available, and cancel(). Calling cancel() in a change event prevents its model update.
Keyboard
| Key | Behavior |
|---|---|
ArrowDown / ArrowUp | Move through visible items in a vertical tree. |
ArrowRight | Expand a collapsed branch, then move to its first child. In RTL, ArrowLeft does this. |
ArrowLeft | Collapse an expanded branch, then move to its parent. In RTL, ArrowRight does this. |
Home / End | Move to the first/last enabled visible item. |
* | Expand all enabled branches at the current level. |
Space | Select or toggle the focused item. |
Enter | Select and activate the focused item. |
Shift + movement Arrow or Home / End | Extend a multiple-selection range from its anchor. |
Ctrl+A / Cmd+A | Select all enabled items in multiple mode. |
| printable characters | Move to the next visible label matching the typed prefix. |
Horizontal orientation maps movement to Left/Right and expansion to Down/Up. One visible enabled item participates in the page tab order.
In multiple mode, Shift + click selects the visible range from the last selection anchor. Ctrl / Cmd + Shift + click adds that range to the current selection.