{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "selection-web",
  "title": "Selection (Web Components)",
  "description": "A small toolbar of actions that floats above text a person selects in a reply.",
  "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-toolbar-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/selection.ts",
      "content": "import {\n  type SelectionApi,\n  type SelectionOptions,\n  type SelectionState,\n  selectionPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport { createParts } from \"@ui-sdk/web\";\nimport type {\n  AttributeProperties,\n  UiDetailedChangeEvent,\n  UiElement,\n  UiPartElement,\n} from \"@ui-sdk/web/events\";\nimport { defineInternalToolbar } from \"./internal/toolbar\";\n\n// Toolbars this element added, and so places and draws the actions of. A toolbar someone wrote keeps its items, as React's\n// children do. Kept across instances, because UI SDK rebuilds one when the element returns to the page.\nconst owned = new WeakSet<Element>();\ntype Movable = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n// Items this element filled in, written empty or added by it, and so draws the action of.\nconst filled = new WeakSet<Element>();\nconst ITEM_PARTS = \"<ui-toolbar-button><button></button></ui-toolbar-button>\";\n\nconst createItem = (doc: Document, id: string) => {\n  const item = doc.createElement(\"kind-selection-item\");\n  item.setAttribute(\"value\", id);\n  item.innerHTML = ITEM_PARTS;\n  filled.add(item);\n  return item;\n};\n\n/** Writes the item's action into its button: label, `title` from its description, `disabled` without `can-run`. */\nconst drawItem = (item: Element, { actionsById, canRun }: SelectionState) => {\n  const action = Object.hasOwn(actionsById, item.getAttribute(\"value\") ?? \"\")\n    ? actionsById[item.getAttribute(\"value\") ?? \"\"]\n    : undefined;\n  item.querySelector(\"ui-toolbar-button\")?.toggleAttribute(\"disabled\", !canRun);\n  const button = item.querySelector(\"button\");\n  if (!button) return;\n  const label = action?.label ?? \"\";\n  if (button.textContent !== label) button.textContent = label;\n  if (action?.description) {\n    if (button.title !== action.description) button.title = action.description;\n  } else button.removeAttribute(\"title\");\n};\n\n/**\n * Draws an item for each action, reusing the item of an action with the same id and moving only what is out of\n * place, so a focused button keeps focus. `moveBefore` doesn't take focus away, where the browser has it.\n */\nconst drawItems = (bar: Movable, state: SelectionState) => {\n  const items = new Map<string, Element>();\n  for (const item of bar.querySelectorAll(\":scope > kind-selection-item\"))\n    items.set(item.getAttribute(\"value\") ?? \"\", item);\n  let previous: Element | null = null;\n  for (const { id } of state.actions) {\n    const item = items.get(id) ?? createItem(bar.ownerDocument, id);\n    items.delete(id);\n    drawItem(item, state);\n    const before: Element | null = previous ? previous.nextElementSibling : bar.firstElementChild;\n    if (before !== item) {\n      if (bar.moveBefore && item.isConnected) bar.moveBefore(item, before);\n      else bar.insertBefore(item, before);\n    }\n    previous = item;\n  }\n  for (const item of items.values()) item.remove();\n};\n\n/**\n * `<kind-selection can-run>` holds the reply in a `<kind-selection-content>` you write, and adds a\n * `<kind-selection-toolbar>` after it with one button per action. Set `actions` as a property; the `can-run`\n * attribute lets a person choose one, which fires `selectionaction` with `{ actionId, text }` as `detail.value`.\n * Escape or a press outside fires `dismiss` with the selected text. A toolbar you write yourself is\n * `<kind-internal-toolbar><ui-toolbar>` holding `<kind-selection-item value=\"…\"><ui-toolbar-button><button>`s, and\n * keeps what you write in it.\n */\nexport function defineSelection(): void {\n  if (customElements.get(\"kind-selection\")) return;\n  defineInternalToolbar();\n  createParts(selectionPrimitive, {\n    root: {\n      tag: \"kind-selection\",\n      kinds: { canRun: \"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 KindSelectionElement).canRun ? {} : { onAction: undefined }),\n      events: { onAction: \"selectionaction\" },\n      api: [\"getActions\"],\n      render: (el, instance) => {\n        let drawn: Pick<SelectionState, \"actions\" | \"label\" | \"canRun\"> | undefined;\n        const place = () => {\n          const content = el.querySelector(\":scope > kind-selection-content\");\n          let toolbar = el.querySelector(\":scope > kind-selection-toolbar\");\n          if (!toolbar) {\n            toolbar = el.ownerDocument.createElement(\"kind-selection-toolbar\");\n            toolbar.innerHTML = \"<kind-internal-toolbar><ui-toolbar></ui-toolbar></kind-internal-toolbar>\";\n            owned.add(toolbar);\n            drawn = undefined;\n          } else if (!owned.has(toolbar) || !content || content.nextElementSibling === toolbar) return;\n          // It must follow the content: Tab moves from the content to the toolbar.\n          if (content) content.after(toolbar);\n          else el.append(toolbar);\n        };\n        const draw = () => {\n          place();\n          const state = instance.get() as SelectionState;\n          if (\n            drawn &&\n            drawn.actions === state.actions &&\n            drawn.label === state.label &&\n            drawn.canRun === state.canRun\n          ) {\n            return;\n          }\n          drawn = { actions: state.actions, label: state.label, canRun: state.canRun };\n          const toolbar = el.querySelector(\":scope > kind-selection-toolbar\");\n          const bar = toolbar && owned.has(toolbar) ? toolbar.querySelector(\"ui-toolbar\") : null;\n          if (bar) {\n            if (bar.ariaLabel !== state.label) bar.ariaLabel = state.label;\n            drawItems(bar, state);\n          }\n          // Items a page wrote empty are filled in, as React's defaults are.\n          for (const item of el.querySelectorAll(\"kind-selection-item\")) {\n            if (!filled.has(item) && !item.firstElementChild && !item.textContent?.trim()) {\n              item.innerHTML = ITEM_PARTS;\n              filled.add(item);\n            }\n            if (filled.has(item)) drawItem(item, state);\n          }\n        };\n        draw();\n        const unsubscribe = instance.subscribe(draw);\n        // The content and written items may arrive after the element connects, as a streamed reply's do.\n        const arrivals = new MutationObserver((records) => {\n          const arrived = records.some(\n            (record) =>\n              !(record.target instanceof Element && record.target.closest(\"kind-selection-content\")) &&\n              [...record.addedNodes].some((node) => node instanceof Element),\n          );\n          if (!arrived) return;\n          drawn = undefined;\n          draw();\n        });\n        arrivals.observe(el, { childList: true, subtree: true });\n        return () => {\n          unsubscribe();\n          arrivals.disconnect();\n        };\n      },\n    },\n    content: \"kind-selection-content\",\n    toolbar: \"kind-selection-toolbar\",\n    item: { tag: \"kind-selection-item\", display: \"contents\" },\n  });\n}\n\nexport type KindSelectionEvents = {\n  selectionaction: UiDetailedChangeEvent<\n    Parameters<NonNullable<SelectionOptions[\"onAction\"]>>[0],\n    Parameters<NonNullable<SelectionOptions[\"onAction\"]>>[1]\n  >;\n  dismiss: UiDetailedChangeEvent<string, Parameters<NonNullable<SelectionOptions[\"onDismiss\"]>>[1]>;\n};\n\nexport interface KindSelectionElement\n  extends UiElement<KindSelectionEvents>,\n    AttributeProperties<typeof selectionPrimitive, \"api\" | \"actions\"> {\n  canRun: boolean;\n  actions?: SelectionOptions[\"actions\"];\n  api: Pick<SelectionApi, \"getActions\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-selection\": KindSelectionElement;\n    \"kind-selection-content\": HTMLElement;\n    \"kind-selection-toolbar\": HTMLElement;\n    \"kind-selection-item\": UiPartElement<typeof selectionPrimitive, \"item\", \"value\">;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/selection.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
