{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-tree-view",
  "type": "registry:ui",
  "title": "react-tw/tree-view.tsx",
  "description": "Carbon `TreeView` as React + Tailwind components, the look and rules of `<ui-tree-view>`: a Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "@purpurabog/ui@^2.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-tree",
    "@kanok-ui/tw-field",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/tree-view.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/tree-view.tsx",
      "content": "import { Children, createContext, isValidElement, useContext, useId, useMemo, type CSSProperties, type ReactNode, type ComponentProps } from 'react';\nimport { treeNodeIndent, treeNodeOffset } from '../core/tree.ts';\nimport { TreeView as TreeViewPrimitive } from '@purpurabog/ui/headless';\nimport { fieldLabelClasses } from './field.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport { cn } from './lib/utils.ts';\n\nexport type TreeViewSize = 'xs' | 'sm';\n\n/** What the styled nodes need to look right; the state (selection, Tab stop, keys, lazy loading) is the primitive's. */\ninterface TreeLookValue {\n    size: TreeViewSize;\n}\n\nconst TreeLookContext = createContext<TreeLookValue | null>(null);\n\nexport interface TreeViewProps extends Omit<ComponentProps<'div'>, 'label' | 'hideLabel' | 'size' | 'multiselect' | 'selected' | 'defaultSelected' | 'onSelect' | 'active' | 'defaultActive' | 'onActivate' | 'className' | 'children'> {\n    /** The tree's name, shown above it (Carbon label). */\n    label: string;\n    /** Keep the label for screen readers only. */\n    hideLabel?: boolean;\n    /** Rows: sm 32px (default), xs 24px. */\n    size?: TreeViewSize;\n    /** Ctrl / ⌘ + click and Space toggle nodes in and out of the selection; Ctrl + A selects all. */\n    multiselect?: boolean;\n    /** Selected node values (controlled). */\n    selected?: readonly string[];\n    defaultSelected?: readonly string[];\n    onSelect?: (selected: string[], value: string) => void;\n    /** The node last activated (the 4px marker; controlled). */\n    active?: string;\n    defaultActive?: string;\n    onActivate?: (value: string) => void;\n    className?: string;\n    /** `<TreeNode>`s. */\n    children: ReactNode;\n}\n\n/**\n * Carbon `TreeView` as React + Tailwind components, the look and rules of `<ui-tree-view>`: a\n * `role=tree` of nested `<TreeNode>`s. Click or Space selects (and makes the node active);\n * `multiselect` toggles with Ctrl / ⌘ + click or Space and selects all with Ctrl + A. Up / Down move\n * through the visible nodes, Home / End jump, Left / Right collapse / expand (or move to the parent /\n * first child), Enter toggles and selects, typing jumps to a label (the headless TreeView: core/tree,\n * core/typeahead).\n */\nexport function TreeView({ label, hideLabel = false, size = 'sm', multiselect = false, selected, defaultSelected, onSelect, active, defaultActive, onActivate, className, children, ...rest }: Readonly<TreeViewProps>) {\n    const id = useId();\n    const look = useMemo<TreeLookValue>(() => ({ size }), [size]);\n    return (\n        <div {...rest} className={cn('block overflow-hidden font-sans', className)}>\n            {hideLabel || !label ? null : (\n                <span id={`${id}-label`} className={cn(fieldLabelClasses, 'block')}>\n                    {label}\n                </span>\n            )}\n            <TreeViewPrimitive.Root\n                aria-label={hideLabel ? label : undefined}\n                aria-labelledby={hideLabel || !label ? undefined : `${id}-label`}\n                multiselect={multiselect}\n                selected={selected}\n                defaultSelected={defaultSelected}\n                onSelect={onSelect}\n                active={active}\n                defaultActive={defaultActive}\n                onActivate={onActivate}\n                className=\"m-0 p-0\"\n            >\n                <TreeLookContext.Provider value={look}>{children}</TreeLookContext.Provider>\n            </TreeViewPrimitive.Root>\n        </div>\n    );\n}\n\nexport interface TreeNodeProps extends Omit<ComponentProps<'div'>, 'label' | 'value' | 'icon' | 'href' | 'disabled' | 'expanded' | 'defaultExpanded' | 'onToggle' | 'lazy' | 'onLazyLoad' | 'className' | 'children'> {\n    /** The label (Carbon React: a node). Type-ahead and the default `value` read its text (strings inside its elements); give `value` when it has none. */\n    label: ReactNode;\n    /** Identifies the node in `selected` / `active`; defaults to the label's text. */\n    value?: string;\n    /** A 16px icon before the label. */\n    icon?: ReactNode;\n    /** Beyond Carbon: content at the end of the row (an amount, a count, a badge), kept whole while the label truncates; it then describes the node, which the label alone names. */\n    end?: ReactNode;\n    /** Turns the label into a link. */\n    href?: string;\n    disabled?: boolean;\n    /** Open (controlled). */\n    expanded?: boolean;\n    defaultExpanded?: boolean;\n    onToggle?: (expanded: boolean) => void;\n    /**\n     * A branch whose children aren't loaded yet (Shoelace's `lazy`; Carbon has no pattern): expanding it\n     * the first time shows a spinner and calls `onLazyLoad` — render the children when they arrive. A\n     * returned promise that resolves with no children makes it a leaf; one that rejects closes it to retry.\n     */\n    lazy?: boolean;\n    onLazyLoad?: (value: string) => void | Promise<void>;\n    className?: string;\n    /** Child `<TreeNode>`s. */\n    children?: ReactNode;\n}\n\nconst CARET_TONE = { rest: 'fill-icon-secondary group-hover/row:fill-icon-primary', strong: 'fill-icon-primary', off: 'fill-icon-disabled' } as const;\nconst ICON_TONE = { rest: '[&>svg]:fill-icon-secondary group-hover/row:[&>svg]:fill-icon-primary', strong: '[&>svg]:fill-icon-primary', off: '[&>svg]:fill-icon-disabled' } as const;\n\nconst caret = (expanded: boolean, colour: string) => (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className={cn('size-4 transition-all duration-(--ui-duration-moderate) ease-carbon', expanded ? '[transform:rotate(0)]' : '[transform:rotate(-90deg)]', colour)}>\n        <path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" />\n    </svg>\n);\n\n/** Carbon's small loader (as InlineLoading), in place of the caret while a lazy branch loads. */\nconst spinner = (\n    <svg viewBox=\"0 0 100 100\" aria-hidden=\"true\" className=\"size-4 animate-spin [animation-duration:690ms] motion-reduce:[animation-duration:0s]\">\n        <circle cx=\"50%\" cy=\"50%\" r=\"42\" className=\"fill-none stroke-layer-active-1 [stroke-dasharray:276.46_276.46] [stroke-dashoffset:-22] [stroke-linecap:butt] [stroke-width:16]\" />\n        <circle cx=\"50%\" cy=\"50%\" r=\"42\" className=\"fill-none stroke-interactive [stroke-dasharray:276.46_276.46] [stroke-dashoffset:143.76] [stroke-linecap:butt] [stroke-width:16]\" />\n    </svg>\n);\n\n/**\n * One node of a TreeView (Carbon `TreeNode`): nest `<TreeNode>`s as children to make a branch\n * (expand with the caret, Enter or Right; collapse with Left); `href` makes the label a link.\n */\ntype Tone = keyof typeof CARET_TONE;\n\n/** Caret and icon: secondary, primary on hover or when selected; disabled wins. */\nfunction toneOf(disabled: boolean, selected: boolean): Tone {\n    if (disabled) return 'off';\n    return selected ? 'strong' : 'rest';\n}\n\nfunction nodeClasses(disabled: boolean, className?: string) {\n    return cn(\n        // --ui-tree-*: a design can drop the fill, round the rows and mark the active one as the side nav's current page\n        'block cursor-pointer bg-[var(--ui-tree-background,var(--ui-layer-1))] text-ink-muted outline-none',\n        !disabled && '[&:focus>[data-row]]:outline-[length:var(--ui-focus-width,2px)] [&:focus>[data-row]]:-outline-offset-2 [&:focus>[data-row]]:outline-focus [&:focus>[data-row]]:outline-solid [&:focus:not(:focus-visible)>[data-row]]:outline-[color:var(--ui-tree-pointer-outline,var(--ui-focus))]',\n        disabled && 'cursor-not-allowed bg-[var(--ui-tree-background,var(--ui-field-1))] text-ink-disabled',\n        className,\n    );\n}\n\n/** A node's row: 32px (xs 24px), hover and selected fills, the 4px active bar; it bleeds back to the tree's edge (Carbon offset). */\nfunction nodeRowClasses({ branch, xs, selected, disabled, active }: { branch: boolean; xs: boolean; selected: boolean; disabled: boolean; active: boolean }) {\n    return cn(\n        'group/row relative box-border flex min-h-8 flex-1 items-center rounded-[var(--ui-tree-row-radius,0px)] ms-(--_lead) ps-(--_offset) type-body-sm leading-[18px]!',\n        !branch && 'py-[7px]',\n        xs && 'min-h-6',\n        xs && !branch && 'py-0',\n        'hover:bg-layer-hover-1 hover:text-ink',\n        selected && 'bg-[var(--ui-tree-selected,var(--ui-layer-selected-1))] text-ink hover:bg-[var(--ui-tree-selected-hover,var(--ui-layer-selected-hover-1))]',\n        disabled && 'hover:bg-[var(--ui-tree-background,var(--ui-field-1))] hover:text-ink-disabled',\n        active && [\n            \"before:absolute before:start-0 before:top-(--ui-tree-mark-inset,0px) before:h-[calc(100%-2*var(--ui-tree-mark-inset,0px))] before:w-[var(--ui-tree-mark-width,4px)] before:rounded-[var(--ui-tree-mark-radius,0px)]\",\n            \"before:bg-[var(--ui-tree-mark,var(--ui-interactive))] before:content-[''] forced-colors:before:w-1 forced-colors:before:bg-[Highlight]\",\n        ],\n        selected && 'forced-colors:outline-1 forced-colors:outline-[Highlight] forced-colors:outline-solid',\n    );\n}\n\n/** A label's text: its strings and numbers, through its elements' children. */\nfunction textOf(node: ReactNode): string {\n    if (typeof node === 'string' || typeof node === 'number') return String(node);\n    if (Array.isArray(node)) return node.map(textOf).join('');\n    if (isValidElement<{ children?: ReactNode }>(node)) return textOf(node.props.children);\n    return '';\n}\n\n/** Whether there is end content to show (0 is an amount; false and null are not). */\nconst shows = (node: ReactNode) => node !== undefined && node !== null && typeof node !== 'boolean';\n\n/** The label, as a link with `href` (out of the tab order: the node takes focus). */\nfunction NodeText({ href, label, id }: Readonly<{ href?: string; label: ReactNode; id?: string }>) {\n    if (!href) {\n        return (\n            <span id={id} className=\"truncate\">\n                {label}\n            </span>\n        );\n    }\n    return (\n        <a id={id} href={href} tabIndex={-1} className=\"truncate text-inherit no-underline\">\n            {label}\n        </a>\n    );\n}\n\nexport function TreeNode({ label, value, icon, end, href, disabled = false, expanded, defaultExpanded, onToggle, lazy, onLazyLoad, className, children, ...rest }: Readonly<TreeNodeProps>) {\n    const look = useContext(TreeLookContext);\n    const id = useId();\n    if (!look) throw new Error('<TreeNode> goes inside <TreeView>');\n    const text = textOf(label);\n    // with end content the label alone names the node and the end content describes it; an author's own name wins\n    const named = shows(end) && !rest['aria-label'] && !rest['aria-labelledby'];\n    const ids = named ? { label: `${id}-label`, end: `${id}-end` } : undefined;\n    return (\n        <TreeViewPrimitive.Node\n            {...rest}\n            aria-labelledby={ids?.label ?? rest['aria-labelledby']}\n            aria-describedby={ids?.end ?? rest['aria-describedby']}\n            value={value || text}\n            label={text}\n            hasChildren={Children.toArray(children).some(isValidElement)}\n            disabled={disabled}\n            expanded={expanded}\n            defaultExpanded={defaultExpanded}\n            onToggle={onToggle}\n            lazy={lazy}\n            onLazyLoad={onLazyLoad}\n            className={nodeClasses(disabled, className)}\n        >\n            <TreeNodeBody size={look.size} label={label} icon={icon} end={end} href={href} ids={ids}>\n                {children}\n            </TreeNodeBody>\n        </TreeViewPrimitive.Node>\n    );\n}\n\n/** A node's row (caret or spinner, icon, label) and its child nodes, inside its primitive (they follow its state). */\nfunction TreeNodeBody({ size, label, icon, end, href, ids, children }: Readonly<{ size: TreeViewSize; label: ReactNode; icon?: ReactNode; end?: ReactNode; href?: string; ids?: { label: string; end: string }; children?: ReactNode }>) {\n    const t = useTranslation().common;\n    const { branch, expanded, loading, selected, active, disabled, depth } = TreeViewPrimitive.useNodeContext();\n    const xs = size === 'xs';\n    const withIcon = !!icon;\n    // the row bleeds back to the tree's edge (margin = indent − offset) so hover and selection span the full width (Carbon offset)\n    const indent = treeNodeIndent(branch, withIcon);\n    const offsetPx = treeNodeOffset(depth, branch, withIcon);\n    const tone = toneOf(disabled, selected);\n    return (\n        <>\n            <TreeViewPrimitive.Row data-row=\"\" style={{ '--_offset': `${offsetPx}px`, '--_lead': `${indent - offsetPx}px` } as CSSProperties} className={nodeRowClasses({ branch, xs, selected, disabled, active })}>\n                {branch ? (\n                    // the caret toggles the branch (only it: a click on the row selects); a spinner while a lazy branch loads\n                    <TreeViewPrimitive.Toggle className=\"-ms-1 me-1 box-border flex size-6 cursor-pointer items-center border-0 bg-transparent py-0 ps-1 pe-0 text-inherit outline-none disabled:cursor-not-allowed\">\n                        {loading ? spinner : caret(expanded, CARET_TONE[tone])}\n                    </TreeViewPrimitive.Toggle>\n                ) : null}\n                <span className={cn('flex min-w-0 items-center', withIcon && cn('[&>svg]:mx-2 [&>svg]:size-4 [&>svg]:shrink-0', branch && '[&>svg]:ms-1', ICON_TONE[tone]))}>\n                    {icon}\n                    <NodeText href={disabled ? undefined : href} label={label} id={ids?.label} />\n                </span>\n                {shows(end) ? (\n                    // beyond Carbon: whole and end-aligned; the label takes the rest and truncates\n                    <span id={ids?.end} className=\"ms-auto flex shrink-0 items-center ps-2 pe-4\">\n                        {end}\n                    </span>\n                ) : null}\n                {loading ? <span className=\"sr-only\">, {t.loading}</span> : null}\n            </TreeViewPrimitive.Row>\n            <TreeViewPrimitive.Group style={{ '--_indent': `${indent}px` } as CSSProperties} className=\"m-0 ms-(--_indent) list-none p-0\">\n                {children}\n            </TreeViewPrimitive.Group>\n        </>\n    );\n}\n"
    }
  ]
}
