{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "test-results-web",
  "title": "Test Results (Web Components)",
  "description": "A test run's pass, fail and skip counts over a filterable tree of suites, each failure open to its stack trace.",
  "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/stack-trace-web",
    "@kind-ui/internal-tree-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/test-results.ts",
      "content": "import {\n  emptyTestsText,\n  type StepOpenChangeReason,\n  type TestResultsApi,\n  type TestResultsExpandedChangeReason,\n  type TestResultsFilter,\n  type TestResultsFilterChangeReason,\n  type TestResultsOptions,\n  type TestResultsRow,\n  type TestResultsState,\n  testResultsPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport type { TreeItemData } from \"@ui-sdk/core\";\nimport { createParts, wrappedButton } from \"@ui-sdk/web\";\nimport type {\n  AttributeProperties,\n  UiChangeEvent,\n  UiElement,\n  UiPartElement,\n  UiTreeElement,\n} from \"@ui-sdk/web/events\";\nimport { defineInternalTree } from \"./internal/tree\";\nimport { defineStackTrace } from \"./stack-trace\";\n\nconst DEFAULT_PARTS = `<kind-test-results-trigger><button><kind-test-results-icon></kind-test-results-icon><kind-test-results-title></kind-test-results-title><kind-test-results-meta></kind-test-results-meta></button></kind-test-results-trigger><kind-test-results-filter></kind-test-results-filter><kind-test-results-content><div data-test-results-panel><kind-test-results-tree></kind-test-results-tree><kind-test-results-empty></kind-test-results-empty></div></kind-test-results-content>`;\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// Parts this element wrote into. A part someone wrote into keeps what they wrote, as React's children do. Kept\n// across instances, because UI SDK rebuilds one when the element returns to the page.\nconst owned = new WeakSet<Element>();\n\n// Whitespace a page wrote between tags doesn't count.\nconst isEmpty = (part: Element) => !part.firstElementChild && !part.textContent?.trim();\n\nconst ownedOrEmpty = (part: Element | null): part is Element => {\n  if (!part || !(owned.has(part) || isEmpty(part))) return false;\n  owned.add(part);\n  return true;\n};\n\nconst fill = (part: Element | null, text: string) => {\n  if (ownedOrEmpty(part) && part.textContent !== text) part.textContent = text;\n};\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\nconst WORDS = { pass: \"passed\", fail: \"failed\", skip: \"skipped\" } as const;\n\nconst COUNTS = `<kind-test-results-count value=\"pass\"><button></button></kind-test-results-count><kind-test-results-count value=\"fail\"><button></button></kind-test-results-count><kind-test-results-count value=\"skip\"><button></button></kind-test-results-count>`;\n\n/** Gives an empty filter its counts, and writes each count's words into its button, unless someone wrote into it. */\nconst fillCounts = (el: Element, { counts }: TestResultsState) => {\n  const filter = el.querySelector(\"kind-test-results-filter\");\n  if (filter && isEmpty(filter)) filter.innerHTML = COUNTS;\n  for (const count of el.querySelectorAll(\"kind-test-results-count\")) {\n    const status = count.getAttribute(\"value\");\n    if (status !== \"pass\" && status !== \"fail\" && status !== \"skip\") continue;\n    fill(count.querySelector(\":scope > button\"), `${counts[status]} ${WORDS[status]}`);\n  }\n};\n\n// The row each element was last drawn from, so a redraw writes only rows that changed.\nconst drawn = new WeakMap<Element, TestResultsRow>();\n\n// Every row has an indicator, a passed or skipped test's an empty spacer that lines its name up with the others. It's\n// hidden from agents, which hides UI SDK's Tree from them while the rows stay the Test Results'.\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-test-results-item\", { value });\n  // A space keeps the name and the status's words apart in the row's accessible name.\n  item.append(\n    element(document, \"span\", { \"data-test-results-name\": \"\" }),\n    \" \",\n    element(document, \"kind-test-results-item-status\"),\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, and a failure's error into its Stack Trace. */\nconst drawRow = (row: Element, shown: TestResultsRow, motion: TestResultsState[\"motion\"]) => {\n  const name = row.querySelector(\n    \":scope > ui-tree-item-label > kind-test-results-item > [data-test-results-name]\",\n  );\n  if (name && name.textContent !== shown.name) name.textContent = shown.name;\n  const trace = row.querySelector<HTMLElementTagNameMap[\"kind-stack-trace\"]>(\n    \":scope > ui-tree-group > kind-test-results-failure > kind-stack-trace\",\n  );\n  if (!trace) return;\n  if (drawn.get(trace) !== shown) {\n    drawn.set(trace, shown);\n    Object.assign(trace, { message: shown.message || undefined, stack: shown.stack });\n  }\n  if (trace.motion !== motion) trace.motion = motion;\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 suite's group, reusing each value's element so focus and open rows stay. */\nconst drawRows = (parent: Element, items: TreeItemData[], state: TestResultsState) => {\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      if (data.children.length > 0) drawRows(group, data.children, state);\n      else if (!group.firstElementChild) {\n        const failure = element(document, \"kind-test-results-failure\", { value: data.value });\n        const trace = element(document, \"kind-stack-trace\", { \"auto-open\": \"never\" });\n        failure.append(trace);\n        group.append(failure);\n      }\n    } else {\n      indicator?.replaceChildren();\n      group?.remove();\n    }\n    const shown = Object.hasOwn(state.rows, data.value) ? state.rows[data.value] : undefined;\n    if (shown) drawRow(row, shown, state.motion);\n    place(parent, row, previous ? previous.nextElementSibling : parent.firstElementChild);\n    previous = row;\n  }\n};\n\n/**\n * Gives an empty tree part its Tree, which reads its defaults as it connects and draws bare rows of its own from\n * `items` when it has none, so it gets both, and our rows, before it connects.\n */\nconst fillTree = (part: Element | null, api: TestResultsApi, state: TestResultsState) => {\n  if (!part || !isEmpty(part)) return;\n  const document = part.ownerDocument;\n  const tree = document.createElement(\"ui-tree\");\n  const { \"aria-label\": label, ...props } = api.treeState(state);\n  drawRows(tree, props.items, state);\n  Object.assign(tree, props);\n  tree.ariaLabel = label;\n  const host = element(document, \"kind-internal-tree\");\n  host.append(tree);\n  part.replaceChildren(host);\n};\n\n/**\n * `<kind-test-results>` fills in its parts when it has no children. Set `suites` as a property; its tree gets a row\n * for each suite and test, and a failed test opens to a `<kind-stack-trace>`. Pressing a count filters the tests and\n * fires `filterchange`, and opening or closing rows fires `expandchange`, each with the filter or the open rows as\n * `detail.value`.\n */\nexport function defineTestResults(): void {\n  if (customElements.get(\"kind-test-results\")) return;\n  defineInternalTree();\n  defineStackTrace();\n  createParts(testResultsPrimitive, {\n    root: {\n      tag: \"kind-test-results\",\n      state: {\n        open: { get: (api) => api.isOpen(), set: (api, open) => api.setOpen(!!open) },\n        filter: {\n          get: (api) => api.getFilter(),\n          set: (api, filter) => api.setFilter(filter as TestResultsFilter),\n        },\n        expanded: {\n          get: (api) => api.getExpanded(),\n          set: (api, values) => api.setExpanded(values as string[]),\n        },\n      },\n      // The inner Tree fires `expandedchange` of its own, which a capture listener would hear first.\n      events: { onFilterChange: \"filterchange\", onExpandedChange: \"expandchange\" },\n      api: [\n        \"isOpen\",\n        \"setOpen\",\n        \"toggle\",\n        \"expand\",\n        \"collapse\",\n        \"getSuites\",\n        \"getFilter\",\n        \"setFilter\",\n        \"getExpanded\",\n        \"setExpanded\",\n      ],\n      render: (el, instance) => {\n        if (!el.firstElementChild) el.innerHTML = DEFAULT_PARTS;\n        const api = instance.api as TestResultsApi;\n        let drawnTree: Element | undefined;\n        let drawnItems: TreeItemData[] | undefined;\n        let drawnRows: TestResultsState[\"rows\"] | undefined;\n        let drawnMotion: TestResultsState[\"motion\"] | undefined;\n        const draw = () => {\n          const state = instance.get() as TestResultsState;\n          fill(el.querySelector(\"kind-test-results-title\"), state.title);\n          fill(el.querySelector(\"kind-test-results-meta\"), state.duration);\n          fillCounts(el, state);\n          fill(el.querySelector(\"kind-test-results-empty\"), emptyTestsText(state.filter));\n          const treePart = el.querySelector(\"kind-test-results-tree\");\n          fillTree(treePart, api, state);\n          const tree = treePart?.querySelector<UiTreeElement>(\":scope > kind-internal-tree > ui-tree\");\n          if (!tree) return;\n          const { \"aria-label\": label, items, controller: treeController } = api.treeState(state);\n          if (\n            tree !== drawnTree ||\n            items !== drawnItems ||\n            state.rows !== drawnRows ||\n            state.motion !== drawnMotion\n          ) {\n            drawnTree = tree;\n            drawnItems = items;\n            drawnRows = state.rows;\n            drawnMotion = state.motion;\n            drawRows(tree, items, state);\n          }\n          if (tree.controller !== treeController) tree.controller = treeController;\n          if (tree.items !== items) tree.items = items;\n          if (tree.ariaLabel !== label) tree.ariaLabel = label;\n          api.syncTree();\n        };\n        draw();\n        const unsubscribe = instance.subscribe(draw);\n        // A part a page adds later is filled in when it arrives, and a count when its `value` changes. The rows and\n        // stack traces drawn inside aren't parts.\n        const arrivals = new MutationObserver((records) => {\n          const arrived = records.some((record) =>\n            record.type === \"attributes\"\n              ? record.target instanceof Element && record.target.localName === \"kind-test-results-count\"\n              : !(record.target instanceof Element && record.target.closest(\"ui-tree\")) &&\n                [...record.addedNodes].some((node) => node instanceof Element),\n          );\n          if (arrived) draw();\n        });\n        arrivals.observe(el, {\n          childList: true,\n          subtree: true,\n          attributes: true,\n          attributeFilter: [\"value\"],\n        });\n        return () => {\n          unsubscribe();\n          arrivals.disconnect();\n        };\n      },\n    },\n    trigger: { tag: \"kind-test-results-trigger\", target: wrappedButton, display: \"contents\" },\n    icon: \"kind-test-results-icon\",\n    title: \"kind-test-results-title\",\n    meta: \"kind-test-results-meta\",\n    content: \"kind-test-results-content\",\n    filter: \"kind-test-results-filter\",\n    count: { tag: \"kind-test-results-count\", target: wrappedButton, display: \"contents\" },\n    tree: \"kind-test-results-tree\",\n    item: \"kind-test-results-item\",\n    \"item-status\": \"kind-test-results-item-status\",\n    failure: \"kind-test-results-failure\",\n    empty: \"kind-test-results-empty\",\n  });\n}\n\nexport type KindTestResultsEvents = {\n  openchange: UiChangeEvent<boolean, StepOpenChangeReason>;\n  filterchange: UiChangeEvent<TestResultsFilter, TestResultsFilterChangeReason>;\n  expandchange: UiChangeEvent<string[], TestResultsExpandedChangeReason>;\n};\n\nexport interface KindTestResultsElement\n  extends UiElement<KindTestResultsEvents>,\n    AttributeProperties<\n      typeof testResultsPrimitive,\n      \"api\" | \"open\" | \"suites\" | \"filter\" | \"expanded\" | \"defaultExpanded\"\n    > {\n  open: boolean;\n  suites?: TestResultsOptions[\"suites\"];\n  get filter(): TestResultsFilter;\n  set filter(filter: TestResultsFilter);\n  get expanded(): string[];\n  set expanded(values: string[]);\n  defaultExpanded?: string[];\n  api: Pick<\n    TestResultsApi,\n    | \"isOpen\"\n    | \"setOpen\"\n    | \"toggle\"\n    | \"expand\"\n    | \"collapse\"\n    | \"getSuites\"\n    | \"getFilter\"\n    | \"setFilter\"\n    | \"getExpanded\"\n    | \"setExpanded\"\n  >;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-test-results\": KindTestResultsElement;\n    \"kind-test-results-trigger\": HTMLElement;\n    \"kind-test-results-icon\": HTMLElement;\n    \"kind-test-results-title\": HTMLElement;\n    \"kind-test-results-meta\": HTMLElement;\n    \"kind-test-results-content\": HTMLElement;\n    \"kind-test-results-filter\": HTMLElement;\n    \"kind-test-results-count\": UiPartElement<typeof testResultsPrimitive, \"count\", \"value\">;\n    \"kind-test-results-tree\": HTMLElement;\n    \"kind-test-results-item\": HTMLElement;\n    \"kind-test-results-item-status\": HTMLElement;\n    \"kind-test-results-failure\": HTMLElement;\n    \"kind-test-results-empty\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/test-results.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
