# Animated Tree for UI SDK (/docs/components/tree)

Branches open on a spring with their rows falling in, and the selected row's key glides.

```tsx title="example.tsx"
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/keyframery/tree"

type Album = { value: string; label: string; count: number; children?: Album[] }

const library: Album[] = [
  { value: "favourites", label: "Favourites", count: 48 },
  {
    value: "2026",
    label: "2026",
    count: 707,
    children: [
      {
        value: "lisbon",
        label: "Ski week",
        count: 268,
        children: [
          { value: "lisbon/arrival", label: "Arrival day", count: 84 },
          { value: "lisbon/slopes", label: "On the slopes", count: 126 },
          { value: "lisbon/dinner", label: "Team dinner", count: 58 },
        ],
      },
      {
        value: "kyoto",
        label: "Mum's 60th",
        count: 342,
        children: [
          { value: "kyoto/temples", label: "Temples", count: 190 },
          { value: "kyoto/market", label: "Nishiki market", count: 152 },
        ],
      },
      { value: "garden", label: "Garden", count: 97 },
    ],
  },
  {
    value: "2025",
    label: "2025",
    count: 986,
    children: [
      { value: "iceland", label: "Iceland road trip", count: 412 },
      { value: "wedding", label: "Maya’s wedding", count: 318 },
      { value: "flat", label: "The new flat", count: 256 },
    ],
  },
]

const icon = {
  viewBox: "0 0 16 16",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  "aria-hidden": true,
  className: "text-muted-foreground",
} as const

function FolderIcon() {
  return (
    <svg {...icon}>
      <path d="M2.5 5.25c0-.97.78-1.75 1.75-1.75h1.9c.46 0 .9.18 1.24.51l.7.7c.14.14.33.22.53.22h3.13c.97 0 1.75.78 1.75 1.75v4.07c0 .97-.78 1.75-1.75 1.75h-7.5c-.97 0-1.75-.78-1.75-1.75V5.25Z" />
    </svg>
  )
}

function PhotoIcon() {
  return (
    <svg {...icon}>
      <rect x="2.5" y="3" width="11" height="10" rx="2.25" />
      <path d="m2.75 10.75 2.55-2.55a1 1 0 0 1 1.4 0l3.05 3.05M9 10.5l.8-.8a1 1 0 0 1 1.4 0l2.05 2.05" />
      <path d="M10.25 6.25h.01" />
    </svg>
  )
}

function Albums({ albums }: { albums: Album[] }) {
  return albums.map((album) => (
    <TreeItem key={album.value} value={album.value} data-value={album.value}>
      <TreeItemLabel>
        {album.children && <TreeItemIndicator />}
        {album.children ? <FolderIcon /> : <PhotoIcon />}
        <span className="truncate">{album.label}</span>
        <span className="ml-auto pl-3 text-[12px] font-normal text-muted-foreground tabular-nums">
          {album.count}
        </span>
      </TreeItemLabel>
      {album.children && (
        <TreeGroup>
          <Albums albums={album.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

export default function TreeDemo() {
  return (
    /* A fixed height, so the card grows down as folders open and nothing moves under the pointer. */
    <div className="h-[464px] w-[300px]">
      <div className="rounded-[14px] bg-card p-2 text-card-foreground shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]">
        <div className="flex items-baseline justify-between px-2 pt-2 pb-2.5">
          <h3 className="text-[15px] font-semibold tracking-tight">Photos</h3>
          <span className="text-[12px] text-muted-foreground tabular-nums">1,693 items</span>
        </div>
        <Tree
          aria-label="Photo library"
          defaultExpanded={["2026", "lisbon"]}
          defaultValue="lisbon/slopes"
        >
          <Albums albums={library} />
        </Tree>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/tree
```

This adds `components/keyframery/tree.tsx` and its primitive, `components/keyframery/primitives/tree.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemCheckbox,
  TreeItemIndicator,
  TreeItemLabel,
  TreeItems,
} from "@/components/keyframery/tree"
```

The parts and props are the same as UI SDK's Tree. For every prop, see the [UI SDK tree reference](https://ui-sdk.dev/docs/components/tree).

## What moves [#what-moves]

| Move        | What you see                                                                           |
| ----------- | -------------------------------------------------------------------------------------- |
| **Glide**   | The selected row's key glides to the new row; a lighter highlight follows the pointer. |
| **Height**  | A branch opens to its real height.                                                     |
| **Cascade** | Its rows fall in one after another, and the chevron turns.                             |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's tree with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/tree"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/tree"
```

## Parts [#parts]

The finished component exports 7 parts:

`Tree`, `TreeGroup`, `TreeItem`, `TreeItemCheckbox`, `TreeItemIndicator`, `TreeItemLabel`, `TreeItems`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the tree moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/tree.tsx**

```tsx
"use client"

/* Styled tree: the animated primitive plus the Keyframery look. */

import * as React from "react"

import {
  Tree as TreeRoot,
  TreeGroup as TreeGroupPart,
  TreeItem as TreeItemPart,
  TreeItemCheckbox as TreeItemCheckboxPart,
  TreeItemIndicator as TreeItemIndicatorPart,
  TreeItemLabel as TreeItemLabelPart,
  treeFromPaths,
  type TreeItemData,
  type TreeMode,
  type TreeProps,
} from "@/components/keyframery/primitives/tree"
import { cn } from "@/lib/utils"

const icon = {
  viewBox: "0 0 16 16",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeLinecap: "round",
  strokeLinejoin: "round",
} as const

/* Lets rows rendered from data know whether the tree has checkboxes. */
const CheckableContext = React.createContext(false)

function Tree<Mode extends TreeMode = "single">({
  className,
  children,
  ...props
}: TreeProps<Mode>) {
  const { items, paths } = props
  const data = React.useMemo(
    () => items ?? (paths ? treeFromPaths(paths) : undefined),
    [items, paths],
  )
  return (
    <CheckableContext.Provider value={!!props.checkable}>
      <TreeRoot
        className={cn(
          "flex min-w-0 flex-col text-[13px] outline-none",
          /* The two gliding surfaces: a light one under the pointer, the selected row's key. */
          "before:rounded-[8px] before:bg-accent/45 dark:before:bg-accent/40",
          "after:rounded-[8px] after:bg-accent dark:after:bg-accent",
          className,
        )}
        {...props}
      >
        {children ?? (data ? <TreeItems items={data} /> : null)}
      </TreeRoot>
    </CheckableContext.Provider>
  )
}

/* UI SDK calls an item a branch when it finds its own TreeGroup inside. Ours wraps that
   part, so the item looks for either one and says so itself. */
function hasGroup(children: React.ReactNode): boolean {
  return React.Children.toArray(children).some(
    (child) =>
      React.isValidElement<{ children?: React.ReactNode }>(child) &&
      (child.type === TreeGroup ||
        child.type === TreeGroupPart ||
        hasGroup(child.props.children)),
  )
}

function TreeItem({
  className,
  branch,
  children,
  ...props
}: React.ComponentProps<typeof TreeItemPart>) {
  return (
    <TreeItemPart
      branch={
        branch ?? (typeof children === "function" ? undefined : hasGroup(children) || undefined)
      }
      className={cn(
        "outline-none",
        /* Focus stays on the item, and the ring is drawn on its own row. */
        "[&:focus-visible>[data-slot=tree-label]]:ring-2 [&:focus-visible>[data-slot=tree-label]]:ring-ring",
        "[&:focus-visible>[data-slot=tree-label]]:ring-offset-2 [&:focus-visible>[data-slot=tree-label]]:ring-offset-background",
        className,
      )}
      {...props}
    >
      {children}
    </TreeItemPart>
  )
}

/* The row. A leaf is padded by one chevron so it lines up with the branches beside it. */
function TreeItemLabel({
  className,
  ...props
}: React.ComponentProps<typeof TreeItemLabelPart>) {
  return (
    <TreeItemLabelPart
      className={cn(
        "relative mt-px flex h-7 min-w-0 cursor-pointer items-center gap-2 rounded-[8px] pr-2 pl-2 not-data-branch:pl-8",
        "text-[13px] leading-[1.35] font-[450] text-foreground no-underline select-none",
        "[&_svg]:size-4 [&_svg]:shrink-0",
        "transition-[color] duration-[calc(150ms*var(--kf-speed,1))] motion-reduce:transition-none!",
        "data-selected:text-accent-foreground data-current:text-accent-foreground",
        "data-disabled:cursor-not-allowed data-disabled:opacity-40 data-pending:cursor-progress",
        className,
      )}
      {...props}
    />
  )
}

/* The chevron. It turns as the branch opens, and gives way to a spinner while children load. */
function TreeItemIndicator({
  className,
  children,
  ...props
}: React.ComponentProps<typeof TreeItemIndicatorPart>) {
  return (
    <TreeItemIndicatorPart
      className={cn(
        "group/indicator -m-0.5 grid size-5 shrink-0 place-items-center rounded-[6px] text-muted-foreground",
        "hover:bg-foreground/[0.08] hover:text-foreground data-failed:text-destructive",
        className,
      )}
      {...props}
    >
      {children ?? (
        <>
          <svg {...icon} className="group-data-loading/indicator:hidden">
            <path d="M6 3.75 10.25 8 6 12.25" />
          </svg>
          <svg
            {...icon}
            className="hidden animate-spin [animation-duration:calc(700ms*var(--kf-speed,1))] group-data-loading/indicator:block motion-reduce:[animation-duration:calc(1600ms*var(--kf-speed,1))]"
          >
            <circle cx="8" cy="8" r="5.75" opacity="0.28" />
            <path d="M8 2.25A5.75 5.75 0 0 1 13.75 8" />
          </svg>
        </>
      )}
    </TreeItemIndicatorPart>
  )
}

/* The check draws itself. A branch with only some of its items checked shows a dash. */
function TreeItemCheckbox({
  className,
  children,
  ...props
}: React.ComponentProps<typeof TreeItemCheckboxPart>) {
  return (
    <TreeItemCheckboxPart
      className={cn(
        "group/checkbox grid size-4 shrink-0 place-items-center rounded-[5px] bg-background text-primary-foreground *:[grid-area:1/1]",
        "shadow-[0_0_0_1px_rgb(0_0_0/0.14),0_1px_2px_rgb(0_0_0/0.05)]",
        "dark:bg-accent/40 dark:shadow-[0_0_0_1px_rgb(255_255_255/0.14)]",
        "not-data-disabled:data-unchecked:hover:shadow-[0_0_0_1px_rgb(0_0_0/0.24),0_1px_2px_rgb(0_0_0/0.06)]",
        "dark:not-data-disabled:data-unchecked:hover:shadow-[0_0_0_1px_rgb(255_255_255/0.24)]",
        "transition-[background-color,box-shadow] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!",
        "data-checked:bg-primary data-indeterminate:bg-primary dark:data-checked:bg-primary dark:data-indeterminate:bg-primary",
        "data-checked:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.25)] data-indeterminate:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.25)]",
        "dark:data-checked:shadow-[inset_0_1px_0_rgb(255_255_255/0.7),0_1px_2px_rgb(0_0_0/0.5)] dark:data-indeterminate:shadow-[inset_0_1px_0_rgb(255_255_255/0.7),0_1px_2px_rgb(0_0_0/0.5)]",
        "data-disabled:opacity-50",
        className,
      )}
      {...props}
    >
      {children ?? (
        <>
          <svg {...icon} strokeWidth={1.75}>
            <path
              d="M4.25 8.4 6.9 11l4.85-5.75"
              pathLength={1}
              className="transition-[stroke-dashoffset] duration-[calc(200ms*var(--kf-speed,1))] ease-house [stroke-dasharray:1] [stroke-dashoffset:1] group-data-checked/checkbox:[stroke-dashoffset:0] motion-reduce:transition-none!"
            />
          </svg>
          <svg {...icon} strokeWidth={1.75}>
            <path
              d="M4.75 8h6.5"
              pathLength={1}
              className="transition-[stroke-dashoffset] duration-[calc(200ms*var(--kf-speed,1))] ease-house [stroke-dasharray:1] [stroke-dashoffset:1] group-data-indeterminate/checkbox:[stroke-dashoffset:0] motion-reduce:transition-none!"
            />
          </svg>
        </>
      )}
    </TreeItemCheckboxPart>
  )
}

/* A branch's children, behind a hairline guide that drops from the chevron above.
   The clip reaches 4px past the box, so a focus ring on a row inside is never cut. */
function TreeGroup({
  className,
  ...props
}: React.ComponentProps<typeof TreeGroupPart>) {
  return (
    <TreeGroupPart
      className={cn(
        "relative ml-[15.5px] flex flex-col pl-[6.5px]",
        "before:absolute before:inset-y-1 before:left-0 before:w-px before:bg-border",
        className,
      )}
      {...props}
    />
  )
}

/* Rows from data: what `<Tree items={...} />` renders when it has no children. */
function TreeItems({ items }: { items: TreeItemData[] }) {
  const checkable = React.useContext(CheckableContext)
  return items.map((item) => (
    <TreeItem
      key={item.value}
      value={item.value}
      branch={item.children !== undefined}
      disabled={item.disabled}
    >
      <TreeItemLabel render={item.href ? <a href={item.href} /> : undefined}>
        {item.children && <TreeItemIndicator />}
        {checkable && <TreeItemCheckbox />}
        <span className="truncate">{item.label}</span>
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <TreeItems items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

export {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemCheckbox,
  TreeItemIndicator,
  TreeItemLabel,
  TreeItems,
}
```

**components/keyframery/primitives/tree.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/tree`: same parts, same props. Swap the import and keep your code.
   This file adds motion only. Colours, radii, shadows and spacing stay yours.
   - Glide: the selected row's key springs from row to row when the selection moves. It is the tree's
     `::after`; give it a surface with `after:` classes. A lighter hover highlight glides under the
     pointer and keyboard focus as the tree's `::before`. Both default to a tint of the text colour.
   - The chevron turns on a spring.
   - Height and Cascade: a branch opens to its height and its rows fall in one after another. */

import {
  Tree as TreeRoot,
  TreeGroup as TreeGroupPart,
  TreeItemIndicator as TreeItemIndicatorPart,
  type TreeMode,
  type TreeProps,
} from "@ui-sdk/react/tree"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/tree"

const ROW = '[data-slot="tree-label"]'
const MARK = "data-kf-tree-hl"

/* Moves the hover mark to `row`, or hides the highlight where it is (so it can glide on from there). */
function mark(root: HTMLElement, row: Element | null) {
  if (!row || row.hasAttribute("data-disabled")) {
    root.setAttribute("data-kf-idle", "")
    return
  }
  for (const old of root.querySelectorAll(`[${MARK}]`)) if (old !== row) old.removeAttribute(MARK)
  row.setAttribute(MARK, "")
  root.removeAttribute("data-kf-idle")
  if (!root.hasAttribute("data-kf-glide")) setTimeout(() => root.setAttribute("data-kf-glide", ""), 40)
}

/* The row under the pointer, or the row of the focused item (focus stays on the item). */
function rowFrom(root: HTMLElement, target: EventTarget | null) {
  if (!(target instanceof Element)) return null
  const row =
    target.closest(ROW) ??
    (target.matches('[data-slot="tree-item"]') ? target.querySelector(`:scope > ${ROW}`) : null)
  return row && root.contains(row) ? row : null
}

function Tree<Mode extends TreeMode = "single">({
  className,
  onPointerOver,
  onPointerLeave,
  onFocus,
  onBlur,
  ...props
}: TreeProps<Mode>) {
  /* Hold the selection's glide until the rows are laid out, so the key is simply there on load. */
  const [ready, setReady] = React.useState(false)
  React.useEffect(() => {
    const timer = setTimeout(() => setReady(true), 150)
    return () => clearTimeout(timer)
  }, [])
  const hovering = React.useRef(false)

  return (
    <TreeRoot
      data-kf-ready={ready || undefined}
      className={cn(
        "relative isolate [anchor-scope:--kf-tree-hl,--kf-tree-sel]",
        /* Which row each highlight rests on. A row can hold both. */
        "[&_[data-kf-tree-hl]]:[anchor-name:--kf-tree-hl]",
        "[&_[data-slot=tree-label]:is([data-selected],[data-current])]:[anchor-name:--kf-tree-sel]",
        "[&_[data-slot=tree-label][data-kf-tree-hl]:is([data-selected],[data-current])]:[anchor-name:--kf-tree-hl,--kf-tree-sel]",
        /* Hover highlight. */
        "before:pointer-events-none before:absolute before:-z-10 before:bg-[color-mix(in_oklch,currentColor_6%,transparent)]",
        "before:[position-anchor:--kf-tree-hl] before:top-[anchor(top)] before:right-[anchor(right)] before:bottom-[anchor(bottom)] before:left-[anchor(left)]",
        "before:transition-[opacity,scale] before:duration-[calc(200ms*var(--kf-speed,1))] before:ease-house",
        "data-kf-glide:before:[transition:top_calc(360ms*var(--kf-speed,1))_var(--ease-spring),right_calc(360ms*var(--kf-speed,1))_var(--ease-spring),bottom_calc(360ms*var(--kf-speed,1))_var(--ease-spring),left_calc(360ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(200ms*var(--kf-speed,1))_var(--ease-house),scale_calc(200ms*var(--kf-speed,1))_var(--ease-house)]",
        "data-kf-idle:before:scale-[0.96] data-kf-idle:before:opacity-0 not-has-[[data-kf-tree-hl]]:before:opacity-0",
        /* Selection key. It hides while its row is inside a closing branch. */
        "after:pointer-events-none after:absolute after:-z-10 after:bg-[color-mix(in_oklch,currentColor_10%,transparent)]",
        "after:[position-anchor:--kf-tree-sel] after:top-[anchor(top)] after:right-[anchor(right)] after:bottom-[anchor(bottom)] after:left-[anchor(left)]",
        "after:transition-[opacity] after:duration-[calc(200ms*var(--kf-speed,1))] after:ease-house",
        "data-kf-ready:after:[transition:top_calc(380ms*var(--kf-speed,1))_var(--ease-spring),right_calc(380ms*var(--kf-speed,1))_var(--ease-spring),bottom_calc(380ms*var(--kf-speed,1))_var(--ease-spring),left_calc(380ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(200ms*var(--kf-speed,1))_var(--ease-house)]",
        "not-has-[[data-slot=tree-label]:is([data-selected],[data-current])]:after:opacity-0",
        "has-[[data-ending-style]_[data-slot=tree-label]:is([data-selected],[data-current])]:after:opacity-0",
        "motion-reduce:before:[transition:none]! motion-reduce:after:[transition:none]!",
        className,
      )}
      onPointerOver={(event) => {
        onPointerOver?.(event)
        hovering.current = true
        const row = rowFrom(event.currentTarget, event.target)
        if (row) mark(event.currentTarget, row)
      }}
      onPointerLeave={(event) => {
        onPointerLeave?.(event)
        hovering.current = false
        const root = event.currentTarget
        mark(root, rowFrom(root, root.querySelector(":focus-visible")))
      }}
      onFocus={(event) => {
        onFocus?.(event)
        const target = event.target as Element
        if (!hovering.current && target.matches(":focus-visible")) mark(event.currentTarget, rowFrom(event.currentTarget, target))
      }}
      onBlur={(event) => {
        onBlur?.(event)
        const root = event.currentTarget
        if (!hovering.current && !root.contains(event.relatedTarget as Node | null)) mark(root, null)
      }}
      {...props}
    />
  )
}

function TreeItemIndicator({ className, ...props }: React.ComponentProps<typeof TreeItemIndicatorPart>) {
  return (
    <TreeItemIndicatorPart
      className={cn(
        "[transition:rotate_calc(520ms*var(--kf-speed,1))_var(--ease-pop),color_calc(150ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(150ms*var(--kf-speed,1))_var(--ease-house)] data-expanded:rotate-90",
        "motion-reduce:[transition:none]!",
        className,
      )}
      {...props}
    />
  )
}

/* Opens to its height while its rows cascade in; closes a little faster, all at once. */
function TreeGroup({ className, ...props }: React.ComponentProps<typeof TreeGroupPart>) {
  return (
    <TreeGroupPart
      className={cn(
        "h-(--tree-group-height,auto) [clip-path:inset(-4px_-100vw)]",
        "transition-[height] duration-[calc(380ms*var(--kf-speed,1))] ease-house",
        "data-starting-style:h-0 data-ending-style:h-0 data-ending-style:duration-[calc(260ms*var(--kf-speed,1))]",
        "*:transition-[opacity,translate,filter] *:duration-[calc(420ms*var(--kf-speed,1))] *:ease-spring",
        "*:[transition-delay:calc((min(sibling-index(),10)-1)*calc(36ms*var(--kf-speed,1))+calc(30ms*var(--kf-speed,1)))]",
        "data-starting-style:*:translate-y-2 data-starting-style:*:opacity-0 data-starting-style:*:blur-[4px] data-starting-style:*:transition-none",
        "data-ending-style:*:opacity-0 data-ending-style:*:blur-[2px] data-ending-style:*:duration-[calc(200ms*var(--kf-speed,1))] data-ending-style:*:ease-house data-ending-style:*:[transition-delay:0ms]",
        "motion-reduce:transition-none! motion-reduce:*:transition-none",
        className,
      )}
      {...props}
    />
  )
}

export { Tree, TreeGroup, TreeItemIndicator }
```

## Questions

### How does the animated Tree for UI SDK move?

Glide: The selected row's key glides to the new row; a lighter highlight follows the pointer. Height: A branch opens to its real height. Cascade: Its rows fall in one after another, and the chevron turns.

### Do I need Motion or Framer Motion for the animated Tree?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/tree` instead. It has the same parts and props as `@ui-sdk/react/tree` and adds motion only.

### What happens to the Tree when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
