Tree
Caller-composed nested disclosure with controlled branch expansion and enabled-leaf selection propagation.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add treeSource files
Expand a file to read the source the installer copies into your app.
components/ui/tree/Tree.tsx
import * as React from 'react'
import { I18nManager, Pressable, View, type PressableProps, type ViewProps } from 'react-native'
import { Check, ChevronDown } from 'lucide-react-native'
import { Text, type TextProps } from '@/components/ui/text'
import { renderTextChildren } from '@/lib/label-children'
import { useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'
import {
treeChildren,
treeLeaves,
treeSelectionState,
toggleTreeSelection,
validTreeValues,
type TreeNode,
} from './tree.utils'
interface TreeState {
nodes: TreeNode[]
expanded: string[]
selected: string[]
disabled: boolean
expand: (value: string) => void
select: (value: string) => void
}
const Context = React.createContext<TreeState | null>(null)
const ItemContext = React.createContext<TreeNode | null>(null)
function useTree() {
const tree = React.useContext(Context)
if (!tree) throw new Error('Tree parts must be inside Tree')
return tree
}
function useItem() {
const item = React.useContext(ItemContext)
if (!item) throw new Error('Tree item parts must be inside TreeItem')
return item
}
function collectNodes(
children: React.ReactNode,
parent?: string,
disabled = false,
nodes: TreeNode[] = [],
): TreeNode[] {
React.Children.forEach(children, (child) => {
if (!React.isValidElement<{ children?: React.ReactNode; value?: string; disabled?: boolean }>(child)) return
if (child.type === TreeItem) {
const value = child.props.value
if (typeof value !== 'string') throw new Error('TreeItem requires a string value')
if (nodes.some((node) => node.value === value)) throw new Error(`TreeItem values must be unique: ${value}`)
const unavailable = disabled || !!child.props.disabled
nodes.push({ value, parent, disabled: unavailable })
collectNodes(child.props.children, value, unavailable, nodes)
} else if (child.type !== Tree) collectNodes(child.props.children, parent, disabled, nodes)
})
return nodes
}
function sameValues(left: readonly string[], right: readonly string[]) {
return left.length === right.length && left.every((value, index) => value === right[index])
}
export interface TreeProps extends ViewProps {
/** Declare TreeItem nodes in children, fragments, or transparent child containers. */
expandedValues?: string[]
defaultExpandedValues?: string[]
onExpandedValuesChange?: (values: string[]) => void
/** Selected leaf ids. Branch selection changes only enabled descendant leaves. */
selectedValues?: string[]
defaultSelectedValues?: string[]
onSelectedValuesChange?: (values: string[]) => void
disabled?: boolean
className?: string
}
export const Tree = React.forwardRef<React.ComponentRef<typeof View>, TreeProps>(
(
{
children,
expandedValues,
defaultExpandedValues = [],
onExpandedValuesChange,
selectedValues,
defaultSelectedValues = [],
onSelectedValuesChange,
disabled = false,
className,
...props
},
ref,
) => {
const nodes = React.useMemo(() => collectNodes(children), [children])
const [internalExpanded, setExpanded] = React.useState(() => [...defaultExpandedValues])
const [internalSelected, setSelected] = React.useState(() => [...defaultSelectedValues])
const expanded = validTreeValues(nodes, expandedValues ?? internalExpanded, true)
const selected = validTreeValues(nodes, selectedValues ?? internalSelected, false)
React.useEffect(() => {
if (expandedValues === undefined)
setExpanded((value) => {
const next = validTreeValues(nodes, value, true)
return sameValues(value, next) ? value : next
})
if (selectedValues === undefined)
setSelected((value) => {
const next = validTreeValues(nodes, value, false)
return sameValues(value, next) ? value : next
})
}, [nodes, expandedValues, selectedValues])
return (
<Context.Provider
value={{
nodes,
expanded,
selected,
disabled,
expand(value) {
const node = nodes.find((entry) => entry.value === value)
if (disabled || !node || node.disabled || !treeChildren(nodes, value).length) return
const next = expanded.includes(value) ? expanded.filter((id) => id !== value) : [...expanded, value]
if (expandedValues === undefined) setExpanded(next)
onExpandedValuesChange?.(next)
},
select(value) {
const node = nodes.find((entry) => entry.value === value)
if (disabled || !node || node.disabled || !treeLeaves(nodes, value, true).length) return
const next = toggleTreeSelection(nodes, value, selected)
if (selectedValues === undefined) setSelected(next)
onSelectedValuesChange?.(next)
},
}}
>
<View ref={ref} {...props} className={cn('gap-[4px]', className)}>
{children}
</View>
</Context.Provider>
)
},
)
Tree.displayName = 'Tree'
export interface TreeItemProps extends ViewProps {
value: string
disabled?: boolean
className?: string
}
export const TreeItem = React.forwardRef<React.ComponentRef<typeof View>, TreeItemProps>(
({ value, disabled: _disabled, className, ...props }, ref) => {
const tree = useTree()
const item = tree.nodes.find((node) => node.value === value)
if (!item) throw new Error('Declare TreeItem in Tree children, fragments, or transparent child containers')
return (
<ItemContext.Provider value={item}>
<View ref={ref} {...props} className={cn('min-w-0 gap-[4px]', className)} />
</ItemContext.Provider>
)
},
)
TreeItem.displayName = 'TreeItem'
export interface TreeTriggerProps extends Omit<PressableProps, 'children'> {
children?: React.ReactNode
className?: string
}
export const TreeTrigger = React.forwardRef<React.ComponentRef<typeof Pressable>, TreeTriggerProps>(
({ children, className, disabled, onPress, accessibilityState, ...props }, ref) => {
const tree = useTree(),
item = useItem()
const branch = treeChildren(tree.nodes, item.value).length > 0
const unavailable = tree.disabled || item.disabled || !!disabled || !branch
return (
<Pressable
ref={ref}
{...props}
accessibilityRole="button"
disabled={unavailable}
accessibilityState={{
...accessibilityState,
expanded: branch ? tree.expanded.includes(item.value) : undefined,
disabled: unavailable,
}}
className={cn(
'min-h-[48px] min-w-0 flex-row items-center gap-[8px] rounded-md px-[8px] py-[10px] active:bg-muted',
unavailable && 'opacity-50',
className,
)}
onPress={(event) => {
if (unavailable) return
onPress?.(event)
if (!event.defaultPrevented) tree.expand(item.value)
}}
>
{renderTextChildren(children, 'shrink font-medium')}
</Pressable>
)
},
)
TreeTrigger.displayName = 'TreeTrigger'
export interface TreeContentProps extends ViewProps {
className?: string
}
export const TreeContent = React.forwardRef<React.ComponentRef<typeof View>, TreeContentProps>(
({ className, style, ...props }, ref) => {
const tree = useTree(),
item = useItem()
const expanded = tree.expanded.includes(item.value)
return (
<View
ref={ref}
{...props}
className={cn('gap-[4px]', className)}
style={[{ paddingStart: 20 }, style, !expanded && { display: 'none' }]}
aria-hidden={!expanded}
accessibilityElementsHidden={!expanded}
importantForAccessibility={expanded ? 'auto' : 'no-hide-descendants'}
/>
)
},
)
TreeContent.displayName = 'TreeContent'
export interface TreeIndicatorProps extends ViewProps {
className?: string
}
export const TreeIndicator = React.forwardRef<React.ComponentRef<typeof View>, TreeIndicatorProps>(
({ children, className, ...props }, ref) => {
const tree = useTree()
const item = useItem()
const colors = useThemeColors()
if (!treeChildren(tree.nodes, item.value).length) return null
const expanded = tree.expanded.includes(item.value)
const indicator =
children === undefined ? (
<ChevronDown
size={20}
color={colors.mutedForeground}
style={{ transform: [{ rotate: expanded ? '0deg' : I18nManager?.isRTL ? '90deg' : '-90deg' }] }}
/>
) : (
renderTextChildren(children)
)
return (
<View
ref={ref}
{...props}
aria-hidden
pointerEvents="none"
className={cn('size-[20px] shrink-0 items-center justify-center', className)}
>
{indicator}
</View>
)
},
)
TreeIndicator.displayName = 'TreeIndicator'
export interface TreeCheckboxProps extends Omit<PressableProps, 'children'> {
className?: string
}
export const TreeCheckbox = React.forwardRef<React.ComponentRef<typeof Pressable>, TreeCheckboxProps>(
({ className, disabled, onPress, accessibilityState, ...props }, ref) => {
const tree = useTree(),
item = useItem(),
colors = useThemeColors()
const checked = treeSelectionState(tree.nodes, item.value, tree.selected)
const unavailable = tree.disabled || item.disabled || !!disabled || !treeLeaves(tree.nodes, item.value, true).length
return (
<Pressable
ref={ref}
{...props}
accessibilityRole="checkbox"
accessibilityLabel={props.accessibilityLabel ?? `Select ${item.value}`}
accessibilityState={{ ...accessibilityState, checked, disabled: unavailable }}
disabled={unavailable}
className={cn(
'size-[48px] shrink-0 items-center justify-center rounded-md active:bg-muted',
unavailable && 'opacity-50',
className,
)}
onPress={(event) => {
if (unavailable) return
onPress?.(event)
if (!event.defaultPrevented) tree.select(item.value)
}}
>
<View
pointerEvents="none"
className={cn(
'size-[20px] items-center justify-center rounded-sm border',
checked ? 'border-primary bg-primary' : 'border-input bg-background',
)}
>
{checked === 'mixed' ? (
<View className="h-[2px] w-[10px] rounded-full bg-primary-foreground" />
) : checked ? (
<Check size={14} color={colors.primaryForeground} strokeWidth={3} />
) : null}
</View>
</Pressable>
)
},
)
TreeCheckbox.displayName = 'TreeCheckbox'
export const TreeLabel = React.forwardRef<React.ComponentRef<typeof Text>, TextProps>(
({ className, ...props }, ref) => <Text ref={ref} {...props} className={cn('min-w-0 shrink', className)} />,
)
TreeLabel.displayName = 'TreeLabel'
components/ui/tree/tree.utils.ts
export interface TreeNode {
value: string
parent?: string
disabled: boolean
}
export function treeChildren(nodes: readonly TreeNode[], parent: string): TreeNode[] {
return nodes.filter((node) => node.parent === parent)
}
/** Selection values identify leaves. A branch toggles its enabled descendant leaves. */
export function treeLeaves(nodes: readonly TreeNode[], value: string, enabledOnly = false): string[] {
const node = nodes.find((entry) => entry.value === value)
if (!node || (enabledOnly && node.disabled)) return []
const children = treeChildren(nodes, value)
if (!children.length) return [value]
return children.flatMap((child) => treeLeaves(nodes, child.value, enabledOnly))
}
export function treeSelectionState(
nodes: readonly TreeNode[],
value: string,
selected: readonly string[],
): boolean | 'mixed' {
const children = treeChildren(nodes, value)
const disabled = nodes.find((node) => node.value === value)?.disabled
const leaves = treeLeaves(nodes, value, children.length > 0 && !disabled)
const count = leaves.filter((leaf) => selected.includes(leaf)).length
return count === 0 ? false : count === leaves.length ? true : 'mixed'
}
export function toggleTreeSelection(nodes: readonly TreeNode[], value: string, selected: readonly string[]): string[] {
const affected = treeLeaves(nodes, value, true)
if (!affected.length) return [...selected]
const remove = affected.every((leaf) => selected.includes(leaf))
const next = new Set(selected)
affected.forEach((leaf) => (remove ? next.delete(leaf) : next.add(leaf)))
return nodes
.filter((node) => !treeChildren(nodes, node.value).length && next.has(node.value))
.map((node) => node.value)
}
export function validTreeValues(nodes: readonly TreeNode[], values: readonly string[], branches: boolean): string[] {
const unique = new Set(values)
return nodes
.filter((node) => unique.has(node.value) && treeChildren(nodes, node.value).length > 0 === branches)
.map((node) => node.value)
}
components/ui/tree/index.ts
export * from './Tree'
Dependencies
Registry items
npm packages
lucide-react-nativereact-native-svg