{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "context-bar-web",
  "title": "Context Bar (Web Components)",
  "description": "A row of removable context chips, the ones that don't fit behind a +N button that lists them.",
  "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"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/context-bar.ts",
      "content": "import {\n  CONTEXT_BAR_FIRST_ITEM,\n  type ContextBarApi,\n  type ContextBarListState,\n  type ContextBarOptions,\n  type ContextBarState,\n  contextBarPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport { createParts, wrappedButton, wrappedChild } from \"@ui-sdk/web\";\nimport type {\n  AttributeProperties,\n  UiChangeEvent,\n  UiDetailedChangeEvent,\n  UiElement,\n  UiPartElement,\n} from \"@ui-sdk/web/events\";\n\ntype ContextChip = ContextBarState[\"rows\"][number][\"item\"];\n\nconst DEFAULT_PARTS =\n  \"<kind-context-bar-list></kind-context-bar-list><kind-context-bar-overflow><button></button></kind-context-bar-overflow><kind-context-bar-content hidden><kind-context-bar-title><h2></h2></kind-context-bar-title><kind-context-bar-overflow-list></kind-context-bar-overflow-list></kind-context-bar-content>\";\n\n// Parts this element filled in, and so writes. A part someone wrote keeps its own, as React's children do. Kept across\n// instances, because UI SDK rebuilds one when the element returns to the page.\nconst owned = new WeakSet<Element>();\n// Each element's instance, which the content's portal reads to tell how it presents.\nconst instances = new WeakMap<Element, { get: () => unknown }>();\n// The full-screen element each bar's sheet sits in, made the first time it presents as one.\nconst viewports = new WeakMap<Element, Element>();\n// The chip each row was last filled from, so a redraw for another row's change leaves it alone.\nconst drawn = new WeakMap<Element, ContextChip>();\n\n// A host that sends new chip objects with the same content keeps each row as it is.\nconst sameChip = (a: ContextChip | undefined, b: ContextChip) =>\n  a?.id === b.id && a.label === b.label && a.kind === b.kind && a.icon === b.icon;\n\n// A part written with only whitespace inside, as indented markup is, counts as empty.\nconst owns = (part: Element | null): part is Element => {\n  if (!part || !(owned.has(part) || (!part.firstElementChild && !part.textContent?.trim()))) return false;\n  owned.add(part);\n  return true;\n};\n\n/** The icon (an image URL or an element, cloned), the label and the remove part, kept bound. */\nfunction fill(row: Element, chip: ContextChip, removeTag: string): void {\n  const document = row.ownerDocument;\n  const label = document.createElement(\"span\");\n  label.setAttribute(\"data-context-bar-label\", \"\");\n  label.textContent = chip.label;\n  const remove = row.querySelector(removeTag) ?? document.createElement(removeTag);\n  const icon = chip.icon as string | Element | undefined;\n  if (icon === undefined) {\n    row.replaceChildren(label, remove);\n    return;\n  }\n  const visual = document.createElement(\"span\");\n  visual.setAttribute(\"data-context-bar-icon\", \"\");\n  if (typeof icon === \"string\") {\n    const img = document.createElement(\"img\");\n    img.alt = \"\";\n    img.src = icon;\n    visual.append(img);\n  } else visual.append(icon.cloneNode(true));\n  row.replaceChildren(visual, label, remove);\n}\n\n// Each list's rows by chip id, so drawing reads no attributes.\nconst rowElements = new WeakMap<Element, Map<string, Element>>();\n\n/** A row per chip, in order, reusing each one's element; dropped rows leave first, so placing the rest never blurs one. */\nfunction drawRows(list: Element, rows: ContextBarListState[\"rows\"], tag: string, removeTag: string): void {\n  let byId = rowElements.get(list);\n  if (!byId) {\n    byId = new Map([...list.children].map((child) => [child.getAttribute(\"value\") ?? \"\", child]));\n    rowElements.set(list, byId);\n  }\n  const ids = new Set(rows.map(({ item }) => item.id));\n  for (const [id, child] of byId)\n    if (!ids.has(id)) {\n      child.remove();\n      byId.delete(id);\n    }\n  rows.forEach(({ item }, index) => {\n    let child = byId.get(item.id);\n    if (!child) {\n      child = list.ownerDocument.createElement(tag);\n      child.setAttribute(\"value\", item.id);\n      byId.set(item.id, child);\n    }\n    if (!sameChip(drawn.get(child), item)) fill(child, item, removeTag);\n    drawn.set(child, item);\n    if (list.children[index] !== child) list.insertBefore(child, list.children[index] ?? null);\n  });\n}\n\n/**\n * `<kind-context-bar>` fills in its list, \"+N\" button and popover when it has no children. Set `chips` as a property:\n * the chips that don't fit go behind \"+N\". With `can-remove`, Delete, Backspace or a chip's remove control fires\n * `contextremove` with the chip's `id` as `detail.value`.\n */\nexport function defineContextBar(): void {\n  if (customElements.get(\"kind-context-bar\")) return;\n  createParts(contextBarPrimitive, {\n    root: {\n      tag: \"kind-context-bar\",\n      kinds: { canRemove: \"boolean\" },\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 KindContextBarElement).canRemove ? {} : { onRemove: undefined }),\n      state: {\n        open: {\n          get: (api) => api.isOpen(),\n          set: (api, open) => api.setOpen(!!open),\n        },\n      },\n      events: { onRemove: \"contextremove\" },\n      // `remove`, `open` and `close` are offered only while available, so they aren't copied onto `api`.\n      api: [\"isOpen\", \"setOpen\", \"getChips\"],\n      // A sheet sits in a full-screen viewport, which the content moves into while it presents as one.\n      portal: {\n        slots: [\"content\"],\n        container: (el) => {\n          if ((instances.get(el)?.get() as ContextBarState | undefined)?.presentation !== \"sheet\")\n            return null;\n          let viewport = viewports.get(el);\n          if (!viewport) {\n            const created = el.ownerDocument.createElement(\"kind-context-bar-viewport\");\n            // It leaves once the content has moved back in place.\n            new MutationObserver(() => created.hasChildNodes() || created.remove()).observe(created, {\n              childList: true,\n            });\n            viewports.set(el, created);\n            viewport = created;\n          }\n          if (viewport.parentNode !== el) el.append(viewport);\n          return viewport;\n        },\n      },\n      render: (el, instance) => {\n        instances.set(el, instance);\n        const api = instance.api as ContextBarApi;\n        if (!el.firstElementChild) el.innerHTML = DEFAULT_PARTS;\n        const draw = () => {\n          const state = instance.get() as ContextBarState;\n          // As React's `ContextBarContent` places it, unless the author wrote their own, also when it's added later.\n          const content = el.querySelector(\"kind-context-bar-content\");\n          for (const [name, value] of [\n            [\"initial-focus\", CONTEXT_BAR_FIRST_ITEM],\n            [\"side-offset\", \"6\"],\n            [\"align\", \"end\"],\n          ] as const)\n            if (content && !content.hasAttribute(name)) content.setAttribute(name, value);\n          const list = el.querySelector(\"kind-context-bar-list\");\n          if (owns(list))\n            drawRows(list, api.listState(state).rows, \"kind-context-bar-chip\", \"kind-context-bar-remove\");\n          const rest = el.querySelector(\"kind-context-bar-overflow-list\");\n          if (owns(rest))\n            drawRows(\n              rest,\n              api.overflowState(state).rows,\n              \"kind-context-bar-item\",\n              \"kind-context-bar-item-remove\",\n            );\n          const button = el.querySelector(\"kind-context-bar-overflow > button\");\n          const count = `+${state.overflowCount}`;\n          if (owns(button) && state.overflowCount > 0 && button.textContent !== count)\n            button.textContent = count;\n          const title = el.querySelector(\"kind-context-bar-title > h2\");\n          if (owns(title) && title.textContent !== state.label) title.textContent = state.label;\n        };\n        draw();\n        return instance.subscribe(draw);\n      },\n    },\n    list: \"kind-context-bar-list\",\n    chip: \"kind-context-bar-chip\",\n    remove: \"kind-context-bar-remove\",\n    overflow: { tag: \"kind-context-bar-overflow\", target: wrappedButton, display: \"contents\" },\n    content: \"kind-context-bar-content\",\n    viewport: \"kind-context-bar-viewport\",\n    title: { tag: \"kind-context-bar-title\", target: wrappedChild(\"h2\"), display: \"contents\" },\n    \"overflow-list\": \"kind-context-bar-overflow-list\",\n    item: \"kind-context-bar-item\",\n    \"item-remove\": \"kind-context-bar-item-remove\",\n  });\n}\n\ntype OpenChangeReason = Parameters<NonNullable<ContextBarOptions[\"onOpenChange\"]>>[1][\"reason\"];\n\nexport type KindContextBarEvents = {\n  contextremove: UiDetailedChangeEvent<string, Parameters<NonNullable<ContextBarOptions[\"onRemove\"]>>[1]>;\n  openchange: UiChangeEvent<boolean, OpenChangeReason>;\n};\n\nexport interface KindContextBarElement\n  extends UiElement<KindContextBarEvents>,\n    AttributeProperties<typeof contextBarPrimitive, \"api\" | \"chips\" | \"open\"> {\n  /** Each chip's `icon` is an image URL or an element, which each row clones. */\n  chips?: readonly (Omit<ContextChip, \"icon\"> & { icon?: string | Element })[];\n  open: boolean;\n  /** Whether chips can be removed, each firing `contextremove`. */\n  canRemove: boolean;\n  focusFallback?: ContextBarOptions[\"focusFallback\"];\n  api: Pick<ContextBarApi, \"isOpen\" | \"setOpen\" | \"getChips\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-context-bar\": KindContextBarElement;\n    \"kind-context-bar-list\": HTMLElement;\n    \"kind-context-bar-chip\": UiPartElement<typeof contextBarPrimitive, \"chip\", \"value\">;\n    \"kind-context-bar-remove\": HTMLElement;\n    \"kind-context-bar-item-remove\": HTMLElement;\n    \"kind-context-bar-overflow\": HTMLElement;\n    \"kind-context-bar-content\": HTMLElement;\n    \"kind-context-bar-viewport\": HTMLElement;\n    \"kind-context-bar-title\": HTMLElement;\n    \"kind-context-bar-overflow-list\": HTMLElement;\n    \"kind-context-bar-item\": UiPartElement<typeof contextBarPrimitive, \"item\", \"value\">;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/context-bar.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
