{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "picker-web",
  "title": "Picker (Web Components)",
  "description": "A button that opens a searchable list of choices, with groups, two-line rows, pages and footer actions.",
  "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-command-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/picker.ts",
      "content": "import {\n  type PickerApi,\n  type PickerBaseApi,\n  type PickerBaseState,\n  type PickerCommandState,\n  type PickerItemState,\n  type PickerOpenChangeReason,\n  type PickerOptions,\n  type PickerPage,\n  type PickerRow,\n  type PickerValueChangeReason,\n  pickerPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport type { OptionsOf, Primitive } from \"@ui-sdk/core\";\nimport { createParts, type PartOptions, type RootOptions, wrappedButton } from \"@ui-sdk/web\";\nimport type { AttributeProperties, UiChangeEvent, UiElement } from \"@ui-sdk/web/events\";\nimport { defineInternalCommand } from \"./internal/command\";\n\nconst defaultParts = (tag: string) =>\n  `<${tag}-trigger><button></button></${tag}-trigger><${tag}-content hidden><${tag}-command><kind-internal-command><ui-command><ui-command-input><input data-agent-hidden></ui-command-input><ui-command-empty></ui-command-empty><ui-command-list></ui-command-list></ui-command></kind-internal-command></${tag}-command><${tag}-note></${tag}-note></${tag}-content>`;\n\ntype PickerIcon = string | Element;\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 picker's sheet sits in, made the first time it presents as one.\nconst viewports = new WeakMap<Element, Element>();\n// What each part was last drawn from, so a redraw for another part's change leaves it alone.\nconst drawn = new WeakMap<Element, unknown>();\n\nconst write = <Target extends object, Key extends keyof Target>(\n  target: Target | null,\n  key: Key,\n  value: Target[Key],\n) => {\n  if (target && target[key] !== value) target[key] = value;\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\n/** An icon as nodes: a string is an image URL, an element is copied. */\nconst iconNodes = (document: Document, icon: unknown): Node[] =>\n  typeof icon === \"string\"\n    ? [element(document, \"img\", { alt: \"\", src: icon })]\n    : icon instanceof Element\n      ? [icon.cloneNode(true)]\n      : [];\n\n/** The trigger's icon, text and chevron, drawn only when they changed. */\nconst drawTrigger = (button: Element, text: string, icon: unknown) => {\n  const document = button.ownerDocument;\n  if (!drawn.has(button) || drawn.get(button) !== icon) {\n    drawn.set(button, icon);\n    button.replaceChildren(\n      ...(icon === undefined ? [] : [element(document, \"span\", { \"data-picker-icon\": \"\" })]),\n      element(document, \"span\", { \"data-picker-text\": \"\" }),\n      element(document, \"span\", { \"data-picker-chevron\": \"\" }),\n    );\n    button.querySelector(\"[data-picker-icon]\")?.append(...iconNodes(document, icon));\n  }\n  const label = button.querySelector(\"[data-picker-text]\");\n  if (label && label.textContent !== text) label.textContent = text;\n};\n\ntype IconNodes = (document: Document, row: PickerRow) => Node[];\n\nconst rowIcon: IconNodes = (document, row) => iconNodes(document, row.icon);\n\n/** A row's content inside its `kind-picker-item`, built from its data so no label is parsed as markup. */\nconst drawItem = (\n  part: Element,\n  state: PickerItemState,\n  icon: IconNodes,\n  trailing: IconNodes | undefined,\n) => {\n  if (drawn.get(part) === state) return;\n  const previous = drawn.get(part) as PickerItemState | undefined;\n  drawn.set(part, state);\n  const document = part.ownerDocument;\n  const { row } = state;\n  if (previous?.row !== row) {\n    const text = element(document, \"span\", { \"data-picker-item-text\": \"\" });\n    text.append(element(document, \"ui-command-item-text\", {}, row.label));\n    const icons = row.icon === undefined ? [] : icon(document, row);\n    const iconEl = icons.length ? element(document, \"ui-command-item-icon\") : undefined;\n    iconEl?.append(...icons);\n    part.replaceChildren(\n      ...(iconEl ? [iconEl] : []),\n      text,\n      ...(row.meta\n        ? [\n            element(\n              document,\n              \"span\",\n              row.metaLabel ? { \"data-picker-meta\": \"\", \"aria-hidden\": \"true\" } : { \"data-picker-meta\": \"\" },\n              row.meta,\n            ),\n          ]\n        : []),\n      ...(row.meta && row.metaLabel\n        ? [element(document, \"span\", { \"data-picker-meta-label\": \"\" }, row.metaLabel)]\n        : []),\n      ...(trailing?.(document, row) ?? []),\n      element(document, \"span\", { \"data-picker-mark\": \"\" }),\n    );\n  }\n  const text = part.querySelector(\"[data-picker-item-text]\");\n  let description = text?.querySelector(\"[data-picker-description]\");\n  if (!state.description.length) description?.remove();\n  else {\n    if (!description) {\n      description = element(document, \"span\", { \"data-picker-description\": \"\" });\n      text?.append(description);\n    }\n    description.replaceChildren(\n      ...state.description.map((segment) =>\n        segment.match ? element(document, \"mark\", {}, segment.text) : segment.text,\n      ),\n    );\n  }\n};\n\ntype Movable = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n// Moves only what is out of place, so Command keeps the highlight on an item that stays. `moveBefore` doesn't\n// reconnect, where the browser has it.\nconst place = (parent: Movable, child: Element, before: Element | null) => {\n  if (child.parentElement === parent && child.nextElementSibling === before) return;\n  if (parent.moveBefore && child.isConnected && parent.isConnected) parent.moveBefore(child, before);\n  else parent.insertBefore(child, before);\n};\n\ntype CommandItemElement = HTMLElement & { keywords: string[] | undefined };\n\nconst drawRow = (document: Document, items: Map<string, Element>, row: PickerRow, itemTag: string) => {\n  const { value, label, keywords, disabled, page } = row.option;\n  let item = items.get(value) as CommandItemElement | undefined;\n  items.delete(value);\n  if (!item) {\n    item = element(document, \"ui-command-item\", { value }) as CommandItemElement;\n    const part = element(document, itemTag, { value });\n    owned.add(part);\n    item.append(part);\n  }\n  if (item.getAttribute(\"label\") !== label) item.setAttribute(\"label\", label);\n  item.toggleAttribute(\"disabled\", disabled);\n  if (page) item.setAttribute(\"page\", page);\n  else item.removeAttribute(\"page\");\n  write(item, \"keywords\", keywords);\n  write(item, \"ariaChecked\", row.option[\"aria-checked\"] ?? null);\n  return item;\n};\n\n/** Draws every page, group and row into the list, reusing their elements. */\nconst drawList = (list: Element, pages: PickerPage[], itemTag: string) => {\n  const document = list.ownerDocument;\n  const pageEls = new Map<string, Element>();\n  for (const page of list.querySelectorAll(\":scope > ui-command-page\"))\n    pageEls.set(page.getAttribute(\"value\") ?? \"\", page);\n  const items = new Map<string, Element>();\n  for (const item of list.querySelectorAll(\"ui-command-item\"))\n    items.set(item.getAttribute(\"value\") ?? \"\", item);\n  let previousPage: Element | null = null;\n  for (const { page, sections } of pages) {\n    let pageEl = pageEls.get(page ?? \"\");\n    pageEls.delete(page ?? \"\");\n    if (!pageEl) pageEl = element(document, \"ui-command-page\", page ? { value: page } : {});\n    // Placed before its rows move in, since `moveBefore` refuses a parent that isn't in the page.\n    place(list, pageEl, previousPage ? previousPage.nextElementSibling : list.firstElementChild);\n    const kept = new Set<Element>();\n    let previous: Element | null = null;\n    for (const [index, section] of sections.entries()) {\n      if (section.footer && index > 0) {\n        let separator = pageEl.querySelector(\":scope > ui-command-separator\");\n        separator ??= element(document, \"ui-command-separator\");\n        place(pageEl, separator, previous ? previous.nextElementSibling : pageEl.firstElementChild);\n        kept.add(separator);\n        previous = separator;\n      }\n      const key = section.footer ? \"\\u0000footer\" : (section.label ?? \"\");\n      let group = [...pageEl.querySelectorAll(\":scope > ui-command-group\")].find(\n        (el) => el.getAttribute(\"data-section\") === key,\n      );\n      if (!group) {\n        group = element(document, \"ui-command-group\", { \"data-section\": key });\n        if (section.label) group.append(element(document, \"ui-command-group-label\", {}, section.label));\n      }\n      place(pageEl, group, previous ? previous.nextElementSibling : pageEl.firstElementChild);\n      let last = group.querySelector(\":scope > ui-command-group-label\");\n      for (const row of section.rows) {\n        const item = drawRow(document, items, row, itemTag);\n        place(group, item, last ? last.nextElementSibling : group.firstElementChild);\n        last = item;\n      }\n      kept.add(group);\n      previous = group;\n    }\n    for (const child of [...pageEl.children]) if (!kept.has(child)) child.remove();\n    previousPage = pageEl;\n  }\n  for (const item of items.values()) item.remove();\n  for (const page of pageEls.values()) page.remove();\n};\n\n/** How a component that spreads `pickerBase` differs from Picker on Web Components. */\nexport type PickerElementsConfig<P extends Primitive> = {\n  /** The parts an empty root fills itself with: Picker's trigger and popover by default. */\n  template?: string;\n  /** Each `can-<action>` attribute's property, and the callback it offers: `canRun` offers `onAction` by default. */\n  can?: Record<string, string>;\n  /** The root's live properties: `open` and `value` by default. */\n  state?: RootOptions<P>[\"state\"];\n  /** The api methods copied onto the element: `isOpen`, `setOpen` and `getValue` by default. */\n  api?: RootOptions<P>[\"api\"];\n  /** Draws the trigger's content into the button it filled in: Picker's icon, text and chevron by default. */\n  drawTrigger?: (button: Element, state: PickerBaseState, api: PickerBaseApi) => void;\n  /** A row's icon: an image URL or a copied element by default. None draws no icon. */\n  icon?: IconNodes;\n  /** What follows a row's `meta`. */\n  trailing?: IconNodes;\n  /** More parts, as `createParts` takes them. */\n  parts?: Record<string, string | PartOptions<P>>;\n};\n\nconst pickerTrigger = (button: Element, state: PickerBaseState, api: PickerBaseApi) => {\n  const { text, icon } = api.triggerState(state);\n  drawTrigger(button, text, icon);\n};\n\n/**\n * The `createParts` map of a picker whose root is `tag` and whose parts are `<tag>-trigger`, `<tag>-content` and so\n * on: Picker's, or that of a component that spreads `pickerBase`, like Model Selector, which renames the change and\n * action events. The root fills in its trigger and list when it has no children.\n */\nexport function pickerElements<P extends Primitive>(\n  tag: string,\n  events: Record<string, string>,\n  config: PickerElementsConfig<P> = {},\n): { root: RootOptions<P> } & Record<\n  \"trigger\" | \"content\" | \"viewport\" | \"command\" | \"item\" | \"note\",\n  string | PartOptions<P>\n> {\n  const can = config.can ?? { canRun: \"onAction\" };\n  const icon = config.icon ?? rowIcon;\n  const drawTriggerOf = config.drawTrigger ?? pickerTrigger;\n  return {\n    ...config.parts,\n    root: {\n      tag,\n      kinds: Object.fromEntries(Object.keys(can).map((key) => [key, \"boolean\"])),\n      // Without the attribute the callback is left out; with it, `@ui-sdk/web` fills it in with an event.\n      options: (el) =>\n        Object.fromEntries(\n          Object.entries(can)\n            .filter(([key]) => !(el as unknown as Record<string, unknown>)[key])\n            .map(([, callback]) => [callback, undefined]),\n        ) as Partial<OptionsOf<P>>,\n      state: config.state ?? {\n        open: {\n          get: (api) => (api as PickerBaseApi).isOpen(),\n          set: (api, open) => (api as PickerBaseApi).setOpen(!!open),\n        },\n        value: {\n          get: (api) => (api as PickerBaseApi).getValue(),\n          set: (api, value) => (api as PickerBaseApi).setValue?.(String(value)),\n        },\n      },\n      // The inner Command fires `valuechange` and `action` of its own, and its items a `select`.\n      events,\n      // `setValue` is offered only while enabled, so it isn't copied onto `api`.\n      api: config.api ?? ([\"isOpen\", \"setOpen\", \"getValue\"] as RootOptions<P>[\"api\"]),\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 PickerBaseState | undefined)?.presentation !== \"sheet\")\n            return null;\n          let viewport = viewports.get(el);\n          if (!viewport) {\n            const created = el.ownerDocument.createElement(`${tag}-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        if (!el.firstElementChild) {\n          el.innerHTML = config.template ?? defaultParts(tag);\n          for (const part of el.querySelectorAll(`${tag}-trigger > button, ${tag}-command`)) owned.add(part);\n          const content = el.querySelector(`${tag}-content`);\n          // Focus moves to the search field as the list opens.\n          content?.setAttribute(\"initial-focus\", \"input\");\n          content?.setAttribute(\"side-offset\", \"6\");\n          content?.setAttribute(\"align\", \"start\");\n        }\n        const api = instance.api as PickerBaseApi;\n        const draw = () => {\n          const state = instance.get() as PickerBaseState;\n          const button = el.querySelector(`${tag}-trigger > button`);\n          if (button && owned.has(button)) drawTriggerOf(button, state, api);\n          const command = el.querySelector(`${tag}-command`);\n          const commandState: PickerCommandState = api.commandState(state);\n          if (command && owned.has(command) && drawn.get(command) !== commandState) {\n            drawn.set(command, commandState);\n            const root = command.querySelector<Element & Record<string, unknown>>(\"ui-command\");\n            if (root) for (const [key, value] of Object.entries(commandState.props)) write(root, key, value);\n            const input = command.querySelector<HTMLInputElement>(\"ui-command-input > input\");\n            write(input, \"ariaLabel\", commandState.label);\n            write(input, \"placeholder\", commandState.placeholder);\n            let status = command.querySelector(\"ui-command-status\");\n            if (commandState.statusText === undefined) status?.remove();\n            else {\n              if (!status) {\n                status = el.ownerDocument.createElement(\"ui-command-status\");\n                command.querySelector(\"ui-command-input\")?.after(status);\n              }\n              if (status.textContent !== commandState.statusText)\n                status.textContent = commandState.statusText;\n            }\n            const empty = command.querySelector(\"ui-command-empty\");\n            if (empty && empty.textContent !== commandState.emptyText)\n              empty.textContent = commandState.emptyText;\n            const list = command.querySelector(\"ui-command-list\");\n            if (list) drawList(list, commandState.pages, `${tag}-item`);\n          }\n          const note = el.querySelector(`${tag}-note`);\n          if (note && (owned.has(note) || !note.firstChild)) {\n            owned.add(note);\n            if (note.textContent !== state.note) note.textContent = state.note;\n          }\n          for (const part of el.querySelectorAll(`${tag}-command ${tag}-item`)) {\n            // An item written empty fills itself in, as React's bare `PickerItem` does.\n            if (!owned.has(part) && part.firstChild) continue;\n            owned.add(part);\n            const item = api.itemState(state, part.getAttribute(\"value\") ?? \"\");\n            if (item) drawItem(part, item, icon, config.trailing);\n          }\n        };\n        draw();\n        const unsubscribe = instance.subscribe(draw);\n        return unsubscribe;\n      },\n    },\n    trigger: { tag: `${tag}-trigger`, target: wrappedButton, display: \"contents\" },\n    content: `${tag}-content`,\n    viewport: `${tag}-viewport`,\n    command: { tag: `${tag}-command`, display: \"contents\" },\n    item: `${tag}-item`,\n    note: `${tag}-note`,\n  };\n}\n\n/**\n * `<kind-picker label=\"Work in\">` fills in its trigger and list when it has no children. Set `items`, `actions` and\n * `value` as properties; choosing an item fires `pickerchange` with its `value` as `detail.value`, and with `can-run`,\n * an action fires `pickeraction` with its `id`.\n */\nexport function definePicker(): void {\n  if (customElements.get(\"kind-picker\")) return;\n  defineInternalCommand();\n  createParts(\n    pickerPrimitive,\n    pickerElements<typeof pickerPrimitive>(\"kind-picker\", {\n      onValueChange: \"pickerchange\",\n      onAction: \"pickeraction\",\n    }),\n  );\n}\n\nexport type KindPickerEvents = {\n  pickerchange: UiChangeEvent<string, PickerValueChangeReason>;\n  pickeraction: UiChangeEvent<string, PickerValueChangeReason>;\n  openchange: UiChangeEvent<boolean, PickerOpenChangeReason>;\n};\n\ntype Item = Omit<NonNullable<PickerOptions[\"items\"]>[number], \"icon\" | \"items\"> & {\n  icon?: PickerIcon;\n  items?: Item[];\n};\n\nexport interface KindPickerElement\n  extends UiElement<KindPickerEvents>,\n    AttributeProperties<\n      typeof pickerPrimitive,\n      \"api\" | \"items\" | \"actions\" | \"value\" | \"defaultValue\" | \"open\"\n    > {\n  /**\n   * An item's `icon` is an image URL, or an element (such as an `svg`) copied into its row and the trigger. A copy\n   * keeps the element's ids, so pass an icon that uses `defs` (gradients, masks) as an image URL.\n   */\n  items?: Item[];\n  actions?: (Omit<NonNullable<PickerOptions[\"actions\"]>[number], \"icon\"> & { icon?: PickerIcon })[];\n  get value(): string | null;\n  set value(value: string);\n  defaultValue?: string | null;\n  open: boolean;\n  /** Whether a person can run the `actions`, which fires `pickeraction`. */\n  canRun: boolean;\n  api: Pick<PickerApi, \"isOpen\" | \"setOpen\" | \"getValue\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-picker\": KindPickerElement;\n    \"kind-picker-trigger\": HTMLElement;\n    \"kind-picker-content\": HTMLElement;\n    \"kind-picker-viewport\": HTMLElement;\n    \"kind-picker-command\": HTMLElement;\n    \"kind-picker-item\": HTMLElement;\n    \"kind-picker-note\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/picker.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
