Tree multi select
A multi-select tree with checkbox indicators. Checking a parent checks all children. Supports indeterminate state for partially checked groups.
treeselect
Pick technologies
Frontend
React
Vue
Angular
Backend
Node.js
Python
Go ecosystem
DevOps
import { type KeyboardEvent, useState } from 'react';
import { Box, Checkbox, Combobox, Input, Pill, PillsInput, useCombobox } from '@mantine/core';
import classes from './TreeMultiSelectCombobox.module.css';
interface TreeNode {
value: string;
label: string;
children?: TreeNode[];
}
interface FlatNode {
node: TreeNode;
level: number;
parent: string | null;
hasChildren: boolean;
expanded: boolean;
isLastChild: boolean;
lineGuides: boolean[];
}
const data: TreeNode[] = [
{
value: 'frontend',
label: 'Frontend',
children: [
{ value: 'react', label: 'React' },
{ value: 'vue', label: 'Vue' },
{ value: 'angular', label: 'Angular' },
],
},
{
value: 'backend',
label: 'Backend',
children: [
{ value: 'node', label: 'Node.js' },
{ value: 'python', label: 'Python' },
{
value: 'go-ecosystem',
label: 'Go ecosystem',
children: [
{ value: 'go', label: 'Go' },
{ value: 'gin', label: 'Gin' },
],
},
],
},
{ value: 'devops', label: 'DevOps' },
];
function ChevronIcon({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 15 15" fill="none" style={{ display: 'block' }}>
<path
d="M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z"
fill="currentColor"
fillRule="evenodd"
clipRule="evenodd"
/>
</svg>
);
}
function flattenTree(
nodes: TreeNode[],
expandedState: Record<string, boolean>,
level: number = 1,
parentGuides: boolean[] = [],
parent: string | null = null
): FlatNode[] {
const result: FlatNode[] = [];
nodes.forEach((node, index) => {
const isLast = index === nodes.length - 1;
const hasChildren = !!node.children?.length;
const isExpanded = !!expandedState[node.value];
const childGuides = level >= 2 ? [...parentGuides, !isLast] : [];
result.push({
node,
level,
parent,
hasChildren,
expanded: isExpanded,
isLastChild: isLast,
lineGuides: level >= 2 ? parentGuides : [],
});
if (hasChildren && isExpanded) {
result.push(
...flattenTree(node.children!, expandedState, level + 1, childGuides, node.value)
);
}
});
return result;
}
function getLeafValues(node: TreeNode): string[] {
if (!node.children?.length) {
return [node.value];
}
return node.children.flatMap(getLeafValues);
}
function findLabel(nodes: TreeNode[], value: string): string | null {
for (const node of nodes) {
if (node.value === value) {
return node.label;
}
if (node.children) {
const found = findLabel(node.children, value);
if (found) {
return found;
}
}
}
return null;
}
function isChecked(node: TreeNode, selected: string[]): boolean {
if (!node.children?.length) {
return selected.includes(node.value);
}
return getLeafValues(node).every((v) => selected.includes(v));
}
function isIndeterminate(node: TreeNode, selected: string[]): boolean {
if (!node.children?.length) {
return false;
}
const leaves = getLeafValues(node);
const checkedCount = leaves.filter((v) => selected.includes(v)).length;
return checkedCount > 0 && checkedCount < leaves.length;
}
function findNode(nodes: TreeNode[], value: string): TreeNode | null {
for (const node of nodes) {
if (node.value === value) {
return node;
}
if (node.children) {
const found = findNode(node.children, value);
if (found) {
return found;
}
}
}
return null;
}
function TreeOption({
flatNode,
selected,
onToggleExpand,
}: {
flatNode: FlatNode;
selected: string[];
onToggleExpand: (value: string) => void;
}) {
const { node, level, hasChildren, expanded, isLastChild, lineGuides } = flatNode;
const checked = isChecked(node, selected);
const indeterminate = isIndeterminate(node, selected);
return (
<Combobox.Option
value={node.value}
active={checked}
className={classes.option}
mod={{ nested: level > 1, leaf: !hasChildren }}
style={{ '--level': level }}
>
{level > 1 && (
<>
{lineGuides.map(
(show, index) =>
show && (
<Box
key={index}
component="span"
className={classes.guide}
style={{ '--guide-index': index }}
/>
)
)}
<span className={classes.connector} data-last={isLastChild || undefined} />
<span className={classes.elbow} />
</>
)}
{hasChildren && (
<span
aria-hidden
className={classes.chevron}
data-expanded={expanded || undefined}
onClick={(event) => {
event.stopPropagation();
event.preventDefault();
onToggleExpand(node.value);
}}
onMouseDown={(event) => event.preventDefault()}
>
<ChevronIcon size={16} />
</span>
)}
<Checkbox.Indicator
checked={checked || indeterminate}
indeterminate={!checked && indeterminate}
size="18px"
/>
<span className={classes.label}>{node.label}</span>
</Combobox.Option>
);
}
export function TreeMultiSelectCombobox() {
const store = useCombobox({
onDropdownClose: () => store.resetSelectedOption(),
});
const [selected, setSelected] = useState<string[]>([]);
const [expanded, setExpanded] = useState<Record<string, boolean>>({
frontend: true,
backend: true,
});
const flatNodes = flattenTree(data, expanded);
const toggleExpand = (val: string) => {
setExpanded((prev) => ({ ...prev, [val]: !prev[val] }));
};
const toggleSelect = (node: TreeNode) => {
const leaves = getLeafValues(node);
const allChecked = leaves.every((v) => selected.includes(v));
if (allChecked) {
setSelected((prev) => prev.filter((v) => !leaves.includes(v)));
} else {
setSelected((prev) => Array.from(new Set([...prev, ...leaves])));
}
};
const handleOptionSubmit = (val: string) => {
const node = findNode(data, val);
if (node) {
toggleSelect(node);
}
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Backspace' && selected.length > 0) {
setSelected((prev) => prev.slice(0, -1));
}
if (!store.dropdownOpened) {
return;
}
const index = store.getSelectedOptionIndex();
if (index < 0 || index >= flatNodes.length) {
return;
}
const current = flatNodes[index];
if (event.key === 'ArrowRight' && current.hasChildren && !current.expanded) {
event.preventDefault();
toggleExpand(current.node.value);
}
if (event.key === 'ArrowLeft') {
if (current.hasChildren && current.expanded) {
event.preventDefault();
toggleExpand(current.node.value);
} else if (current.parent) {
event.preventDefault();
const parentIndex = flatNodes.findIndex((n) => n.node.value === current.parent);
if (parentIndex >= 0) {
store.selectOption(parentIndex);
}
}
}
};
const pills = selected.map((item) => (
<Pill
key={item}
withRemoveButton
onRemove={() => setSelected((prev) => prev.filter((v) => v !== item))}
>
{findLabel(data, item) ?? item}
</Pill>
));
return (
<Combobox store={store} withinPortal={false} onOptionSubmit={handleOptionSubmit}>
<Combobox.DropdownTarget>
<PillsInput
pointer
onClick={() => store.toggleDropdown()}
rightSection={<Combobox.Chevron />}
rightSectionPointerEvents="none"
>
<Pill.Group>
{pills.length > 0 ? pills : <Input.Placeholder>Pick technologies</Input.Placeholder>}
<Combobox.EventsTarget>
<PillsInput.Field
type="hidden"
aria-label="Pick technologies"
onKeyDown={handleKeyDown}
onBlur={() => store.closeDropdown()}
/>
</Combobox.EventsTarget>
</Pill.Group>
</PillsInput>
</Combobox.DropdownTarget>
<Combobox.Dropdown>
<Combobox.ScrollArea mah={250} viewportProps={{ tabIndex: -1 }}>
<Combobox.Options aria-multiselectable>
{flatNodes.map((flatNode) => (
<TreeOption
key={flatNode.node.value}
flatNode={flatNode}
selected={selected}
onToggleExpand={toggleExpand}
/>
))}
</Combobox.Options>
</Combobox.ScrollArea>
</Combobox.Dropdown>
</Combobox>
);
}