{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "document-web",
  "title": "Document (Web Components)",
  "description": "A document card with its title, kind and size, copy and download, and a preview that expands.",
  "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/markdown-web",
    "@kind-ui/code-block-web",
    "@kind-ui/internal-toolbar-web",
    "@kind-ui/internal-scroll-area-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/document.ts",
      "content": "import {\n  type DocumentApi,\n  type DocumentOpenChangeReason,\n  type DocumentOptions,\n  type DocumentState,\n  documentPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport type { ActionDetails } from \"@ui-sdk/core\";\nimport { createParts, type UiActionDetail, wrappedButton } from \"@ui-sdk/web\";\nimport type {\n  AttributeProperties,\n  UiChangeEvent,\n  UiDetailedChangeEvent,\n  UiElement,\n  UiPartElement,\n} from \"@ui-sdk/web/events\";\nimport { defineCodeBlock, type KindCodeBlockElement } from \"./code-block\";\nimport { defineInternalScrollArea } from \"./internal/scroll-area\";\nimport { defineInternalToolbar } from \"./internal/toolbar\";\nimport { defineMarkdown, type KindMarkdownElement } from \"./markdown\";\n\nconst DEFAULT_PARTS = `\n  <kind-document-header>\n    <kind-document-title></kind-document-title>\n    <kind-document-meta></kind-document-meta>\n    <kind-document-toolbar>\n      <kind-internal-toolbar><ui-toolbar aria-label=\"Document actions\">\n        <kind-document-copy><ui-toolbar-button><button aria-label=\"Copy\"></button></ui-toolbar-button></kind-document-copy>\n      </ui-toolbar></kind-internal-toolbar>\n    </kind-document-toolbar>\n  </kind-document-header>\n  <kind-document-body>\n    <kind-internal-scroll-area>\n      <ui-scroll-area>\n        <ui-scroll-area-viewport>\n          <ui-scroll-area-content><kind-document-content></kind-document-content></ui-scroll-area-content>\n        </ui-scroll-area-viewport>\n        <ui-scroll-area-scrollbar><ui-scroll-area-thumb></ui-scroll-area-thumb></ui-scroll-area-scrollbar>\n      </ui-scroll-area>\n    </kind-internal-scroll-area>\n    <kind-document-expand><button></button></kind-document-expand>\n  </kind-document-body>`;\n\nconst CONTENT_PARTS = `<kind-markdown></kind-markdown><kind-code-block headerless></kind-code-block><pre></pre>`;\n\n// Parts this element wrote into, and Downloads it added. A part someone wrote into keeps what they wrote, 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>();\n\nconst fill = (part: Element | null, text: string) => {\n  if (!part || !(owned.has(part) || !part.textContent)) return;\n  owned.add(part);\n  if (part.textContent !== text) part.textContent = text;\n};\n\nconst write = <Target extends object, Key extends keyof Target>(\n  target: Target,\n  key: Key,\n  value: Target[Key],\n) => {\n  if (target[key] !== value) target[key] = value;\n};\n\ntype Movable = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n// `moveBefore` keeps a focused button focused where the browser has it; `insertBefore` blurs it.\nfunction move(parent: Movable, child: Element, before: Element | null): void {\n  if (parent.moveBefore && child.isConnected) parent.moveBefore(child, before);\n  else parent.insertBefore(child, before);\n}\n\nconst label = (part: Element, text: string | undefined) => {\n  const button = part.querySelector(\"button\");\n  if (!button) return;\n  const name = text ? `Download ${text}` : \"Download\";\n  if (button.ariaLabel !== name) button.ariaLabel = name;\n  if (button.textContent === (text ?? \"\")) return;\n  button.replaceChildren();\n  if (!text) return;\n  const span = button.appendChild(button.ownerDocument.createElement(\"span\"));\n  span.dataset.documentDownloadLabel = \"\";\n  span.textContent = text;\n};\n\n/**\n * Keeps a Download after Copy for each of the `downloads`, or one for none or one, reusing the parts it added by\n * `value`. A Download the page wrote replaces them all.\n */\nconst drawDownloads = (toolbar: Movable, { downloads, canDownload }: DocumentState) => {\n  const parts = [...toolbar.querySelectorAll(\":scope > kind-document-download\")];\n  const written = parts.some((part) => !owned.has(part));\n  const wanted =\n    !canDownload || written\n      ? []\n      : downloads.length > 1\n        ? downloads\n        : [{ id: downloads[0]?.id, label: undefined }];\n  const added = new Map(\n    parts.filter((part) => owned.has(part)).map((part) => [part.getAttribute(\"value\"), part]),\n  );\n  let previous = toolbar.querySelector(\":scope > kind-document-copy\");\n  for (const { id, label: text } of wanted) {\n    let part = added.get(id ?? null);\n    added.delete(id ?? null);\n    if (!part) {\n      part = toolbar.ownerDocument.createElement(\"kind-document-download\");\n      if (id !== undefined) part.setAttribute(\"value\", id);\n      part.innerHTML = \"<ui-toolbar-button><button></button></ui-toolbar-button>\";\n      owned.add(part);\n    }\n    label(part, text);\n    const before: Element | null = previous ? previous.nextElementSibling : toolbar.firstElementChild;\n    if (before !== part) move(toolbar, part, before);\n    previous = part;\n  }\n  for (const part of added.values()) part.remove();\n};\n\nconst drawContent = (content: Element | null, state: DocumentState) => {\n  if (!content) return;\n  if (!content.firstElementChild && !content.textContent?.trim()) content.innerHTML = CONTENT_PARTS;\n  const markdown = content.querySelector<KindMarkdownElement>(\":scope > kind-markdown\");\n  if (markdown) {\n    write(markdown, \"hidden\", state.format !== \"markdown\");\n    if (state.format === \"markdown\") {\n      write(markdown, \"source\", state.content);\n      write(markdown, \"streaming\", state.streaming);\n      write(markdown, \"highlight\", state.highlight);\n    }\n  }\n  const code = content.querySelector<KindCodeBlockElement>(\":scope > kind-code-block\");\n  if (code) {\n    write(code, \"hidden\", state.format !== \"code\");\n    if (state.format === \"code\") {\n      write(code, \"code\", state.content);\n      write(code, \"language\", state.language);\n      write(code, \"streaming\", state.streaming);\n      write(code, \"highlight\", state.highlight);\n    }\n  }\n  const text = content.querySelector<HTMLPreElement>(\":scope > pre\");\n  if (text) {\n    write(text, \"hidden\", state.format !== \"text\");\n    if (state.format === \"text\" && text.textContent !== state.content) text.textContent = state.content;\n  }\n};\n\n/**\n * `<kind-document label=\"README.md\">` fills in its header and body when it has no children, and an empty\n * `<kind-document-content>` with the view `format` names. Set `content`, and `downloads` as a property; the\n * `can-download` attribute offers Download, which fires `download` with the chosen format's `id`. A\n * `<kind-document-download value=\"…\">` written in the toolbar replaces the ones it adds. Copy fires `documentcopy`\n * first.\n */\nexport function defineDocument(): void {\n  if (customElements.get(\"kind-document\")) return;\n  defineCodeBlock();\n  defineMarkdown();\n  defineInternalScrollArea();\n  defineInternalToolbar();\n  createParts(documentPrimitive, {\n    root: {\n      tag: \"kind-document\",\n      kinds: { canDownload: \"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 KindDocumentElement).canDownload ? {} : { onDownload: undefined }),\n      events: { onCopy: \"documentcopy\" },\n      state: {\n        open: {\n          get: (api) => api.isOpen(),\n          set: (api, open) => api.setOpen(!!open),\n        },\n      },\n      api: [\"isOpen\", \"setOpen\", \"toggle\", \"copy\"],\n      render: (el, instance) => {\n        if (!el.firstElementChild) el.innerHTML = DEFAULT_PARTS;\n        const draw = () => {\n          const state = instance.get() as DocumentState;\n          fill(el.querySelector(\"kind-document-title\"), state.label);\n          fill(el.querySelector(\"kind-document-meta\"), state.meta);\n          const toolbar = el.querySelector(\"kind-document-toolbar ui-toolbar\");\n          if (toolbar) drawDownloads(toolbar, state);\n          el.querySelector(\"kind-document-body ui-scroll-area\")?.toggleAttribute(\n            \"stick-to-end\",\n            state.streaming,\n          );\n          drawContent(el.querySelector(\"kind-document-content\"), state);\n          fill(el.querySelector(\"kind-document-expand > button\"), state.open ? \"Show less\" : \"Show more\");\n        };\n        draw();\n        const unsubscribe = instance.subscribe(draw);\n        const arrivals = new MutationObserver((records) => {\n          // The blocks and lines the Markdown view and Code Block render aren't parts.\n          const arrived = records.some(\n            (record) =>\n              !(\n                record.target instanceof Element && record.target.closest(\"kind-code-block, kind-markdown\")\n              ) && [...record.addedNodes].some((node) => node instanceof Element),\n          );\n          if (arrived) draw();\n        });\n        arrivals.observe(el, { childList: true, subtree: true });\n        return () => {\n          unsubscribe();\n          arrivals.disconnect();\n        };\n      },\n    },\n    header: \"kind-document-header\",\n    title: \"kind-document-title\",\n    meta: \"kind-document-meta\",\n    toolbar: \"kind-document-toolbar\",\n    copy: { tag: \"kind-document-copy\", display: \"contents\" },\n    download: { tag: \"kind-document-download\", display: \"contents\" },\n    body: \"kind-document-body\",\n    content: \"kind-document-content\",\n    expand: { tag: \"kind-document-expand\", target: wrappedButton, display: \"contents\" },\n  });\n}\n\nexport type KindDocumentEvents = {\n  openchange: UiChangeEvent<boolean, DocumentOpenChangeReason>;\n  documentcopy: UiDetailedChangeEvent<string, Parameters<NonNullable<DocumentOptions[\"onCopy\"]>>[1]>;\n  download: CustomEvent<{ value: string | undefined } & ActionDetails & Pick<UiActionDetail, \"waitUntil\">>;\n};\n\nexport interface KindDocumentElement\n  extends UiElement<KindDocumentEvents>,\n    AttributeProperties<typeof documentPrimitive, \"api\" | \"open\" | \"downloads\" | \"highlight\"> {\n  open: boolean;\n  canDownload: boolean;\n  downloads?: DocumentOptions[\"downloads\"];\n  highlight?: DocumentOptions[\"highlight\"];\n  api: Pick<DocumentApi, \"isOpen\" | \"setOpen\" | \"toggle\" | \"copy\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-document\": KindDocumentElement;\n    \"kind-document-header\": HTMLElement;\n    \"kind-document-title\": HTMLElement;\n    \"kind-document-meta\": HTMLElement;\n    \"kind-document-toolbar\": HTMLElement;\n    \"kind-document-copy\": HTMLElement;\n    \"kind-document-download\": UiPartElement<typeof documentPrimitive, \"download\", \"value\">;\n    \"kind-document-body\": HTMLElement;\n    \"kind-document-content\": HTMLElement;\n    \"kind-document-expand\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/document.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
