{
  "$schema": "https://zoblocks.design/schema/registry-item.json",
  "name": "chart-command-palette",
  "type": "zoblocks:component",
  "title": "Chart Command Palette",
  "description": "Actions rank above records, because a verb is usually what was meant. Patients outside your relationships are counted rather than named. Every patient search emits an audit event, including the ones that matched nobody, and a clinically significant action never runs on the first Enter.",
  "categories": [
    "clinical",
    "navigation"
  ],
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils",
    "tokens",
    "palette-core"
  ],
  "files": [
    {
      "path": "registry/zoblocks/chart-command-palette/chart-command-palette.tsx",
      "type": "zoblocks:component",
      "target": "components/zoblocks/chart-command-palette.tsx",
      "content": "\"use client\";\n\n/**\n * ChartCommandPalette — a palette for a place where search is a regulated act.\n *\n *     <ChartCommandPalette\n *       open={open}\n *       items={items}\n *       scope={{ inScope: myPatients, breakGlass: true }}\n *       onRun={run}\n *       onSearchAudit={audit}\n *       onClose={() => setOpen(false)}\n *     />\n *\n * Three behaviours are the component rather than decoration on it.\n *\n *   Patients outside your treatment relationships are counted, never named.\n *   The reader learns the search was not empty without learning who — which\n *   is the difference between a palette and a privacy incident.\n *\n *   Every patient search emits an audit event, including the ones that\n *   returned nothing.\n *\n *   A clinically significant action never runs on the first Enter. The\n *   confirmation happens inside the palette, because handing off to a modal\n *   loses the keyboard user the palette was built for.\n *\n * Styling lives in `styles/zoblocks-palette.css`, installed alongside.\n */\n\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  ITEM_KIND_LABEL,\n  applyScope,\n  auditFor,\n  describeResults,\n  describeWithheld,\n  group,\n  outcomeFor,\n  rank,\n  type PaletteItem,\n  type PatientScope,\n  type SearchAudit,\n} from \"@/lib/zoblocks-palette\";\n\nexport {\n  ITEM_KIND_LABEL,\n  KIND_ORDER,\n  KIND_WEIGHT,\n  applyScope,\n  auditFor,\n  describeResults,\n  describeWithheld,\n  group,\n  outcomeFor,\n  rank,\n  score,\n  scoreItem,\n  type ItemKind,\n  type PaletteItem,\n  type PatientScope,\n  type RankedItem,\n  type RunOutcome,\n  type ScopedResults,\n  type SearchAudit,\n  type Unavailable,\n} from \"@/lib/zoblocks-palette\";\n\nexport interface ChartCommandPaletteProps {\n  /** Whether the palette is showing. Controlled, so the host owns the shortcut that summons it. */\n  open: boolean;\n  /**\n   * Everything the palette may match.\n   *\n   * A flat list rather than registered providers: the provider interface, its\n   * abort signals and its per-source failure handling belong to the host,\n   * which is the only place that knows which of them is a slow terminology\n   * server.\n   */\n  items: readonly PaletteItem[];\n  /**\n   * The treatment relationship this search is bounded by. Every query is scoped to it, and\n   * searches it refuses are audited too.\n   */\n  scope?: PatientScope;\n  /**\n   * The empty-field prompt. Say what can be typed — \"Search, or start with a verb\" — rather\n   * than \"Ask anything\", which promises a scope the palette will refuse.\n   */\n  placeholder?: string;\n  /** Runs an item. Only ever called for an outcome of `run`. */\n  onRun?: (item: PaletteItem) => void;\n  /**\n   * Called once per search that touched the patient index — including the ones\n   * that matched nobody. The host writes the audit entry.\n   */\n  onSearchAudit?: (audit: SearchAudit) => void;\n  /** Fired on Escape, on backdrop click, and after a command runs. */\n  onClose?: () => void;\n  /** Applied to the palette's outer element. */\n  className?: string;\n}\n\nexport function ChartCommandPalette({\n  open,\n  items,\n  scope,\n  placeholder = \"Search or run a command…\",\n  onRun,\n  onSearchAudit,\n  onClose,\n  className,\n}: ChartCommandPaletteProps) {\n  const [term, setTerm] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n  /** The item awaiting its second Enter. Cleared by any other keystroke. */\n  const [confirming, setConfirming] = React.useState<string | null>(null);\n  const [announced, setAnnounced] = React.useState(\"\");\n\n  const listId = React.useId();\n  const input = React.useRef<HTMLInputElement>(null);\n  /** The element to give focus back to. Always, on every close path. */\n  const opener = React.useRef<Element | null>(null);\n\n  const results = React.useMemo(() => applyScope(rank(term, items), scope), [term, items, scope]);\n  const grouped = React.useMemo(() => group(results.visible), [results]);\n  const flat = React.useMemo(() => grouped.flatMap((entry) => entry.items), [grouped]);\n  /*\n   * The highlight, clamped to the list as it is now.\n   *\n   * The stored index resets when the query changes, but items and scope can\n   * change under a fixed query — a slow source landing, a chart closing — and\n   * an index past the end highlights nothing and makes Enter do nothing.\n   * Clamping rather than resetting keeps the reader's place when the list only\n   * grows, and survives a host that passes a fresh `items` array every render.\n   */\n  const activeIndex = Math.max(0, Math.min(active, flat.length - 1));\n  const current = flat[activeIndex]?.item;\n  const withheld = describeWithheld(results.withheld, scope);\n\n  /** Whether this term reached the patient index at all. */\n  const searchedPatients = items.some((item) => item.kind === \"patient\");\n\n  React.useEffect(() => {\n    if (!open) return;\n    opener.current = document.activeElement;\n    input.current?.focus();\n    return () => {\n      // Focus returns to the invoking element on close. Always — a palette\n      // that drops focus to the body has stranded the keyboard user it exists\n      // for.\n      (opener.current as HTMLElement | null)?.focus?.();\n    };\n  }, [open]);\n\n  React.useEffect(() => {\n    setActive(0);\n    setConfirming(null);\n  }, [term]);\n\n  /*\n   * The count, debounced.\n   *\n   * A palette that announces on every keystroke is a palette a screen-reader\n   * user cannot type into: the announcement restarts before the previous word\n   * finishes and nothing is ever heard in full.\n   */\n  React.useEffect(() => {\n    if (!open) return;\n    const timer = setTimeout(() => setAnnounced(describeResults(results, scope)), 350);\n    return () => clearTimeout(timer);\n  }, [open, results, scope]);\n\n  /*\n   * One audit event per settled search, including the empty ones.\n   *\n   * Debounced against the same delay as the announcement so a nine-character\n   * name is one entry rather than nine — but never suppressed, because a\n   * search that found nobody is still a search that was made.\n   */\n  React.useEffect(() => {\n    if (!open || !term.trim() || !onSearchAudit) return;\n    const timer = setTimeout(() => {\n      const audit = auditFor(term, results, searchedPatients);\n      if (audit) onSearchAudit(audit);\n    }, 350);\n    return () => clearTimeout(timer);\n  }, [open, term, results, searchedPatients, onSearchAudit]);\n\n  if (!open) return null;\n\n  const activate = (item: PaletteItem) => {\n    const outcome = outcomeFor(item, confirming === item.id);\n\n    if (outcome.kind === \"blocked\") return;\n    if (outcome.kind === \"argument\") {\n      // Tab semantics on Enter too: the verb keeps the palette open until it\n      // has its object.\n      setTerm(`${item.label} `);\n      input.current?.focus();\n      return;\n    }\n    if (outcome.kind === \"confirm\") {\n      setConfirming(item.id);\n      return;\n    }\n\n    onRun?.(item);\n    onClose?.();\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      onClose?.();\n      return;\n    }\n\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      setConfirming(null);\n      // From the clamped index, so a stale one past the end cannot swallow a keypress.\n      const next = activeIndex + (event.key === \"ArrowDown\" ? 1 : -1);\n      setActive(Math.max(0, Math.min(flat.length - 1, next)));\n      return;\n    }\n\n    if (event.key === \"Tab\" && current?.argument) {\n      event.preventDefault();\n      setTerm(`${current.label} `);\n      return;\n    }\n\n    if (event.key === \"Enter\" && current) {\n      event.preventDefault();\n      activate(current);\n    }\n  };\n\n  return (\n    <div className={cn(\"zb-palette\", className)} data-zb-palette=\"\" role=\"presentation\">\n      <div className=\"zb-palette__panel\">\n        <input\n          ref={input}\n          type=\"text\"\n          className=\"zb-palette__input\"\n          value={term}\n          placeholder={placeholder}\n          onChange={(event) => setTerm(event.target.value)}\n          onKeyDown={onKeyDown}\n          role=\"combobox\"\n          aria-expanded\n          aria-controls={listId}\n          aria-autocomplete=\"list\"\n          aria-label=\"Search or run a command\"\n          {...(current ? { \"aria-activedescendant\": `${listId}-${current.id}` } : {})}\n        />\n\n        {/*\n          The scroll container, not the listbox.\n\n          A `role=\"listbox\"` may own only options and groups (ARIA 1.2), so the\n          two rows that are neither — the withheld count and the empty state —\n          are siblings of the list rather than children of it. They still read\n          as rows and still sit where the results would be; they are simply not\n          pretending to be options, which is what `role=\"presentation\"` inside\n          a listbox amounts to.\n        */}\n        <div className=\"zb-palette__results\">\n          <div id={listId} className=\"zb-palette__list\" role=\"listbox\" aria-label=\"Results\">\n            {grouped.map((entry) => (\n              <div\n                key={entry.kind}\n                className=\"zb-palette__group\"\n                role=\"group\"\n                aria-label={ITEM_KIND_LABEL[entry.kind]}\n              >\n                <p className=\"zb-palette__group-label\" aria-hidden=\"true\">\n                  {ITEM_KIND_LABEL[entry.kind]}\n                </p>\n                {entry.items.map(({ item }) => {\n                  const index = flat.findIndex((candidate) => candidate.item.id === item.id);\n                  const isActive = index === activeIndex;\n                  // Armed, not \"about to be armed\": the prompt appears after\n                  // the first Enter, not on every significant row from the\n                  // moment it is listed. A confirmation shown before anybody\n                  // pressed anything is a confirmation people stop reading.\n                  const armed = confirming === item.id;\n\n                  return (\n                    <div\n                      key={item.id}\n                      id={`${listId}-${item.id}`}\n                      role=\"option\"\n                      aria-selected={isActive}\n                      aria-disabled={item.unavailable ? true : undefined}\n                      className=\"zb-palette__option\"\n                      data-zb-kind={item.kind}\n                      data-zb-active={isActive ? \"\" : undefined}\n                      data-zb-significant={item.significant ? \"\" : undefined}\n                      data-zb-armed={armed ? \"\" : undefined}\n                      data-zb-unavailable={item.unavailable ? \"\" : undefined}\n                      onMouseDown={(event) => {\n                        // Mousedown rather than click: click would blur the\n                        // input first and the combobox would lose its own\n                        // activedescendant mid-selection.\n                        event.preventDefault();\n                        setActive(index);\n                        activate(item);\n                      }}\n                    >\n                      <span className=\"zb-palette__label\">{item.label}</span>\n                      {item.detail ? (\n                        <span className=\"zb-palette__detail\">{item.detail}</span>\n                      ) : null}\n                      {item.argument ? (\n                        <span className=\"zb-palette__argument\">↹ {item.argument.label}</span>\n                      ) : null}\n                      {/*\n                        An unavailable action is shown with its reason rather\n                        than hidden. Hiding it teaches somebody the feature\n                        does not exist; showing it teaches them to reconnect.\n                      */}\n                      {item.unavailable ? (\n                        <span className=\"zb-palette__unavailable\">{item.unavailable.reason}</span>\n                      ) : null}\n                      {armed ? (\n                        <span className=\"zb-palette__confirm\">Press Enter again to confirm</span>\n                      ) : null}\n                    </div>\n                  );\n                })}\n              </div>\n            ))}\n          </div>\n\n          {/*\n            The count of what may not be named.\n            A row, not a footnote: a reader who does not see it concludes the\n            search was empty, which is the one wrong conclusion available.\n          */}\n          {withheld ? <p className=\"zb-palette__withheld\">{withheld}</p> : null}\n\n          {/* Before anything is typed there is no search and nothing to\n              report — including nothing to count, which matters: a withheld\n              total on an empty input discloses the size of the index. */}\n          {!term.trim() ? (\n            <p className=\"zb-palette__empty\">\n              Type to search, or start with a verb — “start”, “order”, “open”.\n            </p>\n          ) : null}\n\n          {term.trim() && !flat.length && !withheld ? (\n            <p className=\"zb-palette__empty\">Nothing matches “{term}”.</p>\n          ) : null}\n        </div>\n\n        {/* Debounced, so typing is not a running commentary. */}\n        <p className=\"zb-palette__sr\" aria-live=\"polite\">\n          {announced}\n        </p>\n      </div>\n    </div>\n  );\n}\n\nChartCommandPalette.displayName = \"ChartCommandPalette\";\n"
    }
  ]
}
