{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-tree-web",
  "title": "File Tree (Web Components)",
  "description": "Changed files as a folder tree, each with its change and the lines it added and removed.",
  "dependencies": [
    "@kind-ui/agent-ui@0.9.0",
    "@ui-sdk/core@0.1.0-beta.17",
    "@ui-sdk/web@0.1.0-beta.17"
  ],
  "registryDependencies": [
    "@kind-ui/agent-ui-setup",
    "@kind-ui/internal-tree-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/file-tree.ts",
      "content": "import {\n  type FileTreeApi,\n  type FileTreeExpandedChangeReason,\n  type FileTreeOptions,\n  type FileTreeRow,\n  type FileTreeSelectReason,\n  type FileTreeState,\n  type FileTreeValueChangeReason,\n  fileTreePrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport type { TreeItemData } from \"@ui-sdk/core\";\nimport { createParts } from \"@ui-sdk/web\";\nimport type { AttributeProperties, UiChangeEvent, UiElement, UiTreeElement } from \"@ui-sdk/web/events\";\nimport { defineInternalTree } from \"./internal/tree\";\n\n// Lucide \"chevron-right\", see THIRD_PARTY_NOTICES.md.\nconst CHEVRON = `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"m9 18 6-6-6-6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`;\n\n// The row each element was last drawn from, so a redraw writes only rows that changed.\nconst drawn = new WeakMap<Element, FileTreeRow>();\n\nconst element = (document: Document, tag: string, attributes: Record<string, string> = {}, text?: string) => {\n  const el = document.createElement(tag);\n  for (const [name, value] of Object.entries(attributes)) el.setAttribute(name, value);\n  if (text !== undefined) el.textContent = text;\n  return el;\n};\n\n// Every row has an indicator, a file's an empty spacer that lines its name up with a folder's. It's hidden from agents,\n// which hides UI SDK's Tree from them (a component with a part under `data-agent-hidden` is off limits) while the rows\n// stay the File Tree's.\nconst newRow = (document: Document, value: string) => {\n  const row = element(document, \"ui-tree-item\", { value });\n  const label = element(document, \"ui-tree-item-label\");\n  const item = element(document, \"kind-file-tree-item\", { value });\n  // Spaces keep the parts' words apart in the row's accessible name.\n  item.append(\n    element(document, \"span\", { \"data-file-tree-name\": \"\" }),\n    \" \",\n    element(document, \"kind-file-tree-counts\"),\n    \" \",\n    element(document, \"kind-file-tree-badge\"),\n  );\n  label.append(element(document, \"ui-tree-item-indicator\", { \"data-agent-hidden\": \"\" }), item);\n  row.append(label);\n  return row;\n};\n\n/** Writes a row's name, as text so no name is parsed as markup. */\nconst drawName = (item: Element, row: FileTreeRow) => {\n  if (drawn.get(item) === row) return;\n  drawn.set(item, row);\n  const name = item.querySelector(\":scope > [data-file-tree-name]\");\n  if (name && name.textContent !== row.name) name.textContent = row.name;\n};\n\ntype Movable = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n// `moveBefore` keeps a focused row focused where the browser has it; `insertBefore` blurs it.\nconst place = (parent: Movable, child: Element, before: Element | null) => {\n  if (before === child || (child.parentElement === parent && child.nextElementSibling === before)) return;\n  if (parent.moveBefore && child.isConnected) parent.moveBefore(child, before);\n  else parent.insertBefore(child, before);\n};\n\n/** Draws the rows into a tree or a folder's group, reusing each path's element so focus and open folders stay. */\nconst drawRows = (parent: Element, items: TreeItemData[], rows: FileTreeState[\"rows\"]) => {\n  const document = parent.ownerDocument;\n  const existing = new Map<string, Element>();\n  const wanted = new Set(items.map((data) => data.value));\n  // Rows that left go first, so the rest are already in place and keep focus where the browser has no `moveBefore`.\n  for (const row of parent.querySelectorAll(\":scope > ui-tree-item\")) {\n    const value = row.getAttribute(\"value\") ?? \"\";\n    if (wanted.has(value)) existing.set(value, row);\n    else row.remove();\n  }\n  let previous: Element | null = null;\n  for (const data of items) {\n    const row = existing.get(data.value) ?? newRow(document, data.value);\n    existing.delete(data.value);\n    const indicator = row.querySelector(\":scope > ui-tree-item-label > ui-tree-item-indicator\");\n    let group = row.querySelector(\":scope > ui-tree-group\");\n    if (data.children) {\n      if (indicator && !indicator.firstElementChild) indicator.innerHTML = CHEVRON;\n      if (!group) {\n        group = element(document, \"ui-tree-group\");\n        row.append(group);\n      }\n      drawRows(group, data.children, rows);\n    } else {\n      indicator?.replaceChildren();\n      group?.remove();\n    }\n    const item = row.querySelector(\":scope > ui-tree-item-label > kind-file-tree-item\");\n    const shown = Object.hasOwn(rows, data.value) ? rows[data.value] : undefined;\n    if (item && shown) drawName(item, shown);\n    place(parent, row, previous ? previous.nextElementSibling : parent.firstElementChild);\n    previous = row;\n  }\n};\n\n/**\n * `<kind-file-tree>` draws its rows from `entries`, set as a property. Selecting fires `pathchange`, opening or closing\n * folders fires `expandchange`, and with `can-select` a press or Enter on a file fires `fileselect`, each with the\n * path or paths as `detail.value`.\n */\nexport function defineFileTree(): void {\n  if (customElements.get(\"kind-file-tree\")) return;\n  defineInternalTree();\n  createParts(fileTreePrimitive, {\n    root: {\n      tag: \"kind-file-tree\",\n      kinds: { canSelect: \"boolean\" },\n      state: {\n        value: { get: (api) => api.getValue(), set: (api, value) => api.setValue(value as string | null) },\n        expanded: {\n          get: (api) => api.getExpanded(),\n          set: (api, value) => api.setExpanded(value as string[]),\n        },\n      },\n      // The inner Tree fires `valuechange` and `expandedchange` of its own, which a capture listener would hear first,\n      // and a native `select` bubbles from text fields.\n      events: { onValueChange: \"pathchange\", onExpandedChange: \"expandchange\", onSelect: \"fileselect\" },\n      api: [\"getValue\", \"setValue\", \"getExpanded\", \"setExpanded\", \"expand\", \"collapse\"],\n      // Without the attribute the callback is left out; with it, `@ui-sdk/web` fills it in with an event.\n      options: (el) => ((el as KindFileTreeElement).canSelect ? {} : { onSelect: undefined }),\n      render: (el, instance) => {\n        const api = instance.api as FileTreeApi;\n        const state = instance.get() as FileTreeState;\n        // The Tree reads its defaults as it connects, and draws bare rows of its own from `items` when it has none,\n        // so it gets both, and our rows, before it connects.\n        const tree =\n          el.querySelector<UiTreeElement>(\":scope > kind-internal-tree > ui-tree\") ??\n          el.ownerDocument.createElement(\"ui-tree\");\n        if (!tree.isConnected) {\n          const { \"aria-label\": label, ...props } = api.treeState(state);\n          drawRows(tree, state.items, state.rows);\n          Object.assign(tree, props);\n          tree.ariaLabel = label;\n          const host = el.ownerDocument.createElement(\"kind-internal-tree\");\n          host.append(tree);\n          el.replaceChildren(host);\n        }\n        let drawnItems = state.items;\n        let drawnRows = state.rows;\n        const draw = () => {\n          const current = instance.get() as FileTreeState;\n          if (current.items !== drawnItems || current.rows !== drawnRows) {\n            drawnItems = current.items;\n            drawnRows = current.rows;\n            drawRows(tree, current.items, current.rows);\n          }\n          // UI SDK builds a new instance, with a new controller, when the element returns to the page.\n          const { \"aria-label\": label, items, controller } = api.treeState(current);\n          if (tree.controller !== controller) tree.controller = controller;\n          if (tree.items !== items) tree.items = items;\n          if (tree.ariaLabel !== label) tree.ariaLabel = label;\n          api.syncTree();\n        };\n        draw();\n        return instance.subscribe(draw);\n      },\n    },\n    item: \"kind-file-tree-item\",\n    counts: \"kind-file-tree-counts\",\n    badge: \"kind-file-tree-badge\",\n  });\n}\n\nexport type KindFileTreeEvents = {\n  pathchange: UiChangeEvent<string | null, FileTreeValueChangeReason>;\n  expandchange: UiChangeEvent<string[], FileTreeExpandedChangeReason>;\n  fileselect: UiChangeEvent<string, FileTreeSelectReason>;\n};\n\nexport interface KindFileTreeElement\n  extends UiElement<KindFileTreeEvents>,\n    AttributeProperties<\n      typeof fileTreePrimitive,\n      \"api\" | \"entries\" | \"value\" | \"defaultValue\" | \"expanded\" | \"defaultExpanded\"\n    > {\n  entries?: FileTreeOptions[\"entries\"];\n  get value(): string | null;\n  set value(path: string | null);\n  defaultValue?: string | null;\n  get expanded(): string[];\n  set expanded(paths: string[]);\n  defaultExpanded?: string[];\n  /** Whether a press or Enter on a file fires `fileselect`, and agents may `select`. */\n  canSelect: boolean;\n  api: Pick<FileTreeApi, \"getValue\" | \"setValue\" | \"getExpanded\" | \"setExpanded\" | \"expand\" | \"collapse\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-file-tree\": KindFileTreeElement;\n    \"kind-file-tree-item\": HTMLElement;\n    \"kind-file-tree-counts\": HTMLElement;\n    \"kind-file-tree-badge\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/file-tree.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
