{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "question-web",
  "title": "Question (Web Components)",
  "description": "Single choice, multiple choice and free text questions in one form, then the recorded answers.",
  "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-radio-web",
    "@kind-ui/internal-checkbox-web",
    "@kind-ui/internal-textarea-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/question.ts",
      "content": "import {\n  type QuestionApi,\n  type QuestionOptions,\n  type QuestionState,\n  type QuestionValueChangeReason,\n  questionPrimitive,\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 { AttributeProperties, UiChangeEvent, UiElement, UiPartElement } from \"@ui-sdk/web/events\";\nimport { defineInternalCheckbox } from \"./internal/checkbox\";\nimport { defineInternalRadio } from \"./internal/radio\";\nimport { defineInternalTextarea } from \"./internal/textarea\";\n\ntype Question = NonNullable<QuestionOptions[\"questions\"]>[number];\n\nconst PENDING_MARK = `<span data-kind-pending-mark=\"\" data-status-mark=\"\" data-status=\"running\" aria-hidden=\"true\"></span>`;\nconst DEFAULT_PARTS = `<kind-question-actions><kind-question-submit><button>${PENDING_MARK}<span data-kind-label></span></button></kind-question-submit><kind-question-skip><button>${PENDING_MARK}<span data-kind-label></span></button></kind-question-skip><kind-question-status><span data-question-label></span></kind-question-status><kind-question-error>Answers not sent. Try again.</kind-question-error></kind-question-actions><kind-question-summary><span data-question-outcome><kind-question-summary-icon></kind-question-summary-icon><span data-question-label></span></span><dl></dl></kind-question-summary>`;\nconst CHECK = `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"3.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M20 6 9 17l-5-5\"/></svg>`;\n\n// Parts this element wrote text into, and questions it added. A part someone wrote text into keeps it, and a question\n// someone wrote stays, as React's children do. Kept across instances, because UI SDK rebuilds one when the element\n// returns to the page.\nconst owned = new WeakSet<Element>();\n// Radio groups the element named, so a page's own name stays.\nconst named = new WeakSet<Element>();\n// The question each item this element fills was drawn from, so a changed question is drawn again.\nconst drawn = new WeakMap<Element, Question>();\n\n// The default buttons hold their running mark beside a label span; a button someone wrote takes the label itself.\nconst label = (button: Element | null) => button?.querySelector(\"[data-kind-label]\") ?? button;\n\nconst fill = (part: Element | null | undefined, 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 | 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/** A question's prompt and its choices or text box, built from its data so no option text is parsed as markup. */\nconst questionParts = (document: Document, question: Question): Element[] => {\n  const prompt = element(document, \"kind-question-prompt\");\n  if (question.kind === \"text\") {\n    const textarea = element(document, \"textarea\", { rows: \"3\" });\n    const box = element(document, \"ui-textarea\");\n    box.append(textarea);\n    const wrapper = element(document, \"kind-internal-textarea\");\n    wrapper.append(box);\n    const text = element(document, \"kind-question-text\");\n    text.append(wrapper);\n    return [prompt, text];\n  }\n  const single = question.kind === \"single\";\n  const group = element(document, single ? \"ui-radio-group\" : \"ui-checkbox-group\");\n  for (const option of question.options ?? []) {\n    const control = element(document, single ? \"ui-radio\" : \"ui-checkbox\", { value: option.value });\n    const indicator = element(document, single ? \"ui-radio-indicator\" : \"ui-checkbox-indicator\");\n    if (!single) indicator.innerHTML = CHECK;\n    control.append(indicator);\n    const text = element(document, \"span\", { \"data-question-option-text\": \"\" });\n    text.append(element(document, \"span\", {}, option.label));\n    if (option.description)\n      text.append(element(document, \"span\", { \"data-question-option-description\": \"\" }, option.description));\n    const label = element(document, \"label\", { \"data-question-option\": \"\" });\n    label.append(control, text);\n    group.append(label);\n  }\n  const wrapper = element(document, single ? \"kind-internal-radio\" : \"kind-internal-checkbox\");\n  wrapper.append(group);\n  const choices = element(document, \"kind-question-choices\");\n  choices.append(wrapper);\n  return [prompt, choices];\n};\n\ntype Movable = Element & { moveBefore?: (node: Node, child: Node | null) => void };\n\n// `moveBefore` keeps a focused question focused where the browser has it; `insertBefore` blurs it.\nfunction move(form: Movable, item: Element, before: Element | null): void {\n  if (form.moveBefore && item.isConnected) form.moveBefore(item, before);\n  else form.insertBefore(item, before);\n}\n\nconst sameOptions = (a: Question[\"options\"] = [], b: Question[\"options\"] = []) =>\n  a.length === b.length &&\n  a.every(\n    (option, index) =>\n      option.value === b[index]?.value &&\n      option.label === b[index]?.label &&\n      option.description === b[index]?.description,\n  );\n\n/**\n * Adds a question for each one the form lacks, in order before the actions, and removes the ones it added for\n * questions that left or that a written item replaced. Fills the items it added, and written ones left empty, again\n * when a question's kind or options change, so a new array with the same content keeps focus.\n */\nconst drawQuestions = (form: Movable, questions: Question[]) => {\n  const items = new Map<string | null, Element>();\n  for (const child of form.querySelectorAll(\":scope > kind-question-item\")) {\n    const value = child.getAttribute(\"value\");\n    const earlier = items.get(value);\n    if (!earlier) items.set(value, child);\n    else if (owned.has(child)) child.remove();\n    else if (owned.has(earlier)) {\n      earlier.remove();\n      items.set(value, child);\n    }\n  }\n  const ids = new Set<string | null>(questions.map((question) => question.id));\n  for (const [id, child] of items) if (owned.has(child) && !ids.has(id)) child.remove();\n  let previous: Element | null = null;\n  for (const question of questions) {\n    let child = items.get(question.id);\n    if (!child) {\n      child = form.ownerDocument.createElement(\"kind-question-item\");\n      child.setAttribute(\"value\", question.id);\n      owned.add(child);\n    }\n    if (drawn.has(child) || owned.has(child) || !child.firstChild) {\n      const before = drawn.get(child);\n      if (before?.kind !== question.kind || !sameOptions(before.options, question.options))\n        child.replaceChildren(...questionParts(form.ownerDocument, question));\n      drawn.set(child, question);\n    }\n    const after: Element | null = previous\n      ? previous.nextElementSibling\n      : (form.querySelector(\":scope > kind-question-item\") ??\n        form.querySelector(\":scope > kind-question-actions\"));\n    if (owned.has(child) && after !== child) move(form, child, after);\n    previous = child;\n  }\n};\n\nconst drawSummary = (list: Element | null, items: ReturnType<QuestionApi[\"summaryState\"]>[\"items\"]) => {\n  if (!list || !(owned.has(list) || !list.firstChild)) return;\n  owned.add(list);\n  const document = list.ownerDocument;\n  list.replaceChildren(\n    ...items.map((item) => {\n      const row = element(document, \"div\");\n      row.append(\n        element(document, \"dt\", {}, item.prompt),\n        element(\n          document,\n          \"dd\",\n          item.answer === undefined ? { \"data-empty\": \"\" } : {},\n          item.answer ?? \"No answer\",\n        ),\n      );\n      return row;\n    }),\n  );\n};\n\n// A `form` the element holds, else one it adds, so Enter on a choice submits as it does in React.\nconst ownForm = (el: HTMLElement): HTMLFormElement =>\n  el.querySelector<HTMLFormElement>(\":scope > form\") ??\n  el.appendChild(el.ownerDocument.createElement(\"form\"));\n\n/**\n * `<kind-question label=\"Deploy questions\">` fills in its form when it has no children. Set `questions`, `value` and\n * `submitted` as properties. The `can-submit` and `can-skip` attributes show Submit and Skip, which fire\n * `questionsubmit` and `skip` with the answers as `detail.value`: call `event.detail.waitUntil(promise)` to keep the\n * form locked until it settles. Write a `<kind-question-item value=\"…\">` inside a `<form>` child to render a question\n * yourself; one written empty gets the question's prompt and its choices or text box.\n */\nexport function defineQuestion(): void {\n  if (customElements.get(\"kind-question\")) return;\n  defineInternalRadio();\n  defineInternalCheckbox();\n  defineInternalTextarea();\n  createParts(questionPrimitive, {\n    root: {\n      tag: \"kind-question\",\n      target: ownForm,\n      display: \"contents\",\n      kinds: { canSubmit: \"boolean\", canSkip: \"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        const { canSubmit, canSkip } = el as KindQuestionElement;\n        return { ...(!canSubmit && { onSubmit: undefined }), ...(!canSkip && { onSkip: undefined }) };\n      },\n      events: { onSubmit: \"questionsubmit\" },\n      defaults: { agentConfirm: true },\n      state: {\n        value: {\n          get: (api) => api.getValue(),\n          set: (api, value) => api.setValue(value ?? {}),\n        },\n      },\n      api: [\"getValue\", \"setValue\", \"select\", \"setText\"],\n      render: (el, instance) => {\n        const form = ownForm(el);\n        if (!form.querySelector(\":scope > kind-question-actions\"))\n          form.insertAdjacentHTML(\"beforeend\", DEFAULT_PARTS);\n        const api = instance.api as QuestionApi;\n        const draw = () => {\n          const state = instance.get() as QuestionState;\n          drawQuestions(form, state.questions);\n          for (const item of form.querySelectorAll(\":scope > kind-question-item\")) {\n            const id = item.getAttribute(\"value\") ?? \"\";\n            const question = state.questions.find((each) => each.id === id);\n            if (!question) continue;\n            const prompt = item.querySelector(\"kind-question-prompt\");\n            if (prompt && (owned.has(prompt) || !prompt.firstChild)) {\n              owned.add(prompt);\n              const required = prompt.querySelector(\"[data-question-required]\");\n              if (prompt.firstChild?.textContent !== question.prompt || !!required !== !!question.required) {\n                prompt.replaceChildren(question.prompt);\n                if (question.required)\n                  prompt.append(\n                    \" \",\n                    element(el.ownerDocument, \"span\", { \"data-question-required\": \"\" }, \"Required\"),\n                  );\n              }\n            }\n            const choices = api.choicesState(id, state);\n            if (choices) {\n              const group = item.querySelector<Element & { controller?: unknown; readOnly?: boolean }>(\n                \"kind-question-choices :is(ui-radio-group, ui-checkbox-group)\",\n              );\n              write(group, \"controller\", choices.controller);\n              write(group, \"readOnly\", choices.readOnly);\n              // Named by its prompt's text (a render file can't write `aria-labelledby`), unless the page named a\n              // group it wrote.\n              if (\n                group &&\n                prompt &&\n                choices.kind === \"single\" &&\n                (named.has(group) ||\n                  (!group.hasAttribute(\"aria-label\") && !group.hasAttribute(\"aria-labelledby\")))\n              ) {\n                named.add(group);\n                write(group, \"ariaLabel\", prompt.textContent?.trim() ?? \"\");\n              }\n            }\n            const text = api.textState(id, state);\n            if (text) {\n              write(\n                item.querySelector<Element & { controller?: unknown }>(\"kind-question-text ui-textarea\"),\n                \"controller\",\n                text.controller,\n              );\n              const textarea = item.querySelector<HTMLTextAreaElement>(\"kind-question-text textarea\");\n              write(textarea, \"readOnly\", text.readOnly);\n              write(textarea, \"placeholder\", text.placeholder ?? \"\");\n              write(textarea, \"ariaLabel\", text.label);\n            }\n          }\n          api.syncAnswers();\n          fill(label(form.querySelector(\"kind-question-submit button\")), state.submitLabel);\n          fill(label(form.querySelector(\"kind-question-skip button\")), state.skipLabel);\n          fill(\n            form.querySelector(\"kind-question-status [data-question-label]\"),\n            state.pressed === \"skip\" ? \"Skipping\" : \"Sending answers\",\n          );\n          const summary = api.summaryState(state);\n          fill(\n            form.querySelector(\"kind-question-summary [data-question-outcome] [data-question-label]\"),\n            summary.outcome,\n          );\n          drawSummary(form.querySelector(\"kind-question-summary dl\"), summary.items);\n        };\n        draw();\n        const unsubscribe = instance.subscribe(draw);\n        // Parts and questions written or removed after the element connects redraw it.\n        const arrivals = new MutationObserver((records) => {\n          const changed = records.some((record) =>\n            [...record.addedNodes, ...record.removedNodes].some(\n              (node) => node instanceof Element && !node.closest(\"kind-question-summary dl\"),\n            ),\n          );\n          if (changed) draw();\n        });\n        arrivals.observe(form, { childList: true, subtree: true });\n        return () => {\n          unsubscribe();\n          arrivals.disconnect();\n        };\n      },\n    },\n    item: \"kind-question-item\",\n    prompt: \"kind-question-prompt\",\n    choices: \"kind-question-choices\",\n    text: \"kind-question-text\",\n    actions: \"kind-question-actions\",\n    submit: { tag: \"kind-question-submit\", target: wrappedButton, display: \"contents\" },\n    skip: { tag: \"kind-question-skip\", target: wrappedButton, display: \"contents\" },\n    status: \"kind-question-status\",\n    \"status-icon\": \"kind-question-status-icon\",\n    error: \"kind-question-error\",\n    summary: \"kind-question-summary\",\n    \"summary-icon\": \"kind-question-summary-icon\",\n  });\n}\n\ntype AnswersEvent = CustomEvent<\n  { value: NonNullable<QuestionOptions[\"value\"]> } & ActionDetails & Pick<UiActionDetail, \"waitUntil\">\n>;\n\nexport type KindQuestionEvents = {\n  questionsubmit: AnswersEvent;\n  skip: AnswersEvent;\n  valuechange: UiChangeEvent<NonNullable<QuestionOptions[\"value\"]>, QuestionValueChangeReason>;\n};\n\nexport interface KindQuestionElement\n  extends UiElement<KindQuestionEvents>,\n    AttributeProperties<\n      typeof questionPrimitive,\n      \"api\" | \"questions\" | \"value\" | \"defaultValue\" | \"submitted\"\n    > {\n  canSubmit: boolean;\n  canSkip: boolean;\n  questions?: QuestionOptions[\"questions\"];\n  value: NonNullable<QuestionOptions[\"value\"]>;\n  defaultValue?: QuestionOptions[\"defaultValue\"];\n  submitted?: QuestionOptions[\"submitted\"];\n  api: Pick<QuestionApi, \"getValue\" | \"setValue\" | \"select\" | \"setText\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-question\": KindQuestionElement;\n    \"kind-question-item\": UiPartElement<typeof questionPrimitive, \"item\", \"value\">;\n    \"kind-question-prompt\": HTMLElement;\n    \"kind-question-choices\": HTMLElement;\n    \"kind-question-text\": HTMLElement;\n    \"kind-question-actions\": HTMLElement;\n    \"kind-question-submit\": HTMLElement;\n    \"kind-question-skip\": HTMLElement;\n    \"kind-question-status\": HTMLElement;\n    \"kind-question-status-icon\": HTMLElement;\n    \"kind-question-error\": HTMLElement;\n    \"kind-question-summary\": HTMLElement;\n    \"kind-question-summary-icon\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/question.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
