{
  "$schema": "https://zoblocks.design/schema/registry-item.json",
  "name": "recent-patient-stack",
  "type": "zoblocks:component",
  "title": "Recent Patient Stack",
  "description": "Each open chart gets a hue derived from its id, so it is the same colour in every session. Two charts whose names look alike both grow an identifier. Per-chart badges carry the unfinished work, closing is graded rather than binary, and returning after fifteen minutes away re-asserts who the chart belongs to.",
  "categories": [
    "clinical",
    "navigation"
  ],
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils",
    "tokens",
    "workspace-core"
  ],
  "files": [
    {
      "path": "registry/zoblocks/recent-patient-stack/recent-patient-stack.tsx",
      "type": "zoblocks:component",
      "target": "components/zoblocks/recent-patient-stack.tsx",
      "content": "\"use client\";\n\n/**\n * RecentPatientStack — a multi-chart workspace that makes the active patient\n * unmistakable, because the alternative is eleven identical browser tabs.\n *\n *     <RecentPatientStack\n *       charts={open}\n *       activeId={activeId}\n *       now={serverTime}\n *       onActivate={switchChart}\n *       onClose={closeChart}\n *     />\n *\n * A stack does three things a dropdown cannot: it makes the set visible\n * without being opened, it gives each chart a persistent visual identity, and\n * it carries per-chart state — a draft note, a pending order, an unread\n * result.\n *\n * The identity is derived from the chart id rather than handed out in arrival\n * order, so it is the same hue in every session. Colour is never the only\n * identity: the initials and the name are always present, and two charts whose\n * names look alike both grow an identifier.\n *\n * Not offered on a phone. A multi-chart workspace on a 375px screen is a\n * wrong-patient generator, so below the breakpoint the stack renders as a\n * single active chart and a switcher — see the stylesheet.\n *\n * Styling lives in `styles/zoblocks-workspace.css`, installed alongside.\n */\n\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  WORK_SHORT,\n  canClose,\n  chartAccent,\n  describeChart,\n  describeWork,\n  moveChart,\n  needsIdentifier,\n  needsReassertion,\n  orderCharts,\n  worstWork,\n  type CloseVerdict,\n  type OpenChart,\n} from \"@/lib/zoblocks-workspace\";\n\nexport {\n  ACCENT_COUNT,\n  REASSERT_AFTER_MS,\n  WORK_LABEL,\n  WORK_ORDER,\n  WORK_SHORT,\n  canClose,\n  chartAccent,\n  describeChart,\n  describeWork,\n  fnv1a,\n  moveChart,\n  needsIdentifier,\n  needsReassertion,\n  orderCharts,\n  similarPairs,\n  worstWork,\n  type CloseVerdict,\n  type OpenChart,\n  type OutstandingWork,\n  type WorkKind,\n} from \"@/lib/zoblocks-workspace\";\n\n/**\n * Two letters, from the display name.\n *\n * Built by slicing rather than by indexing. The indexed version needed two\n * `?? \"\"` fallbacks that no input could reach — `split` on a trimmed string\n * never yields an empty word — and an unreachable fallback is a branch no\n * honest test can cover.\n */\nfunction initials(display: string): string {\n  const letters = display\n    .replace(/,.*$/, \"\")\n    .trim()\n    .split(/\\s+/)\n    .filter(Boolean)\n    .map((word) => word.charAt(0).toUpperCase());\n\n  // First and last for a full name; whatever there is for one word or none.\n  return (letters.length > 1 ? [...letters.slice(0, 1), ...letters.slice(-1)] : letters).join(\"\");\n}\n\nexport interface RecentPatientStackProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\" | \"onSelect\"\n> {\n  /**\n   * The open charts, most recent first. Each carries enough to tell two patients apart, which\n   * eleven identical browser tabs do not.\n   */\n  charts: readonly OpenChart[];\n  /**\n   * Which chart is in front. The active patient has to be unmistakable — this is a\n   * wrong-patient control, not a tab bar.\n   */\n  activeId?: string;\n  /** ISO 8601 from the host. Decides whether returning re-asserts identity. */\n  now?: string;\n  /**\n   * Switch to a chart.\n   *\n   * Called with `reassert: true` when the clinician has been away long enough\n   * that the host should confirm the patient before showing the chart. Fifteen\n   * minutes is roughly the length of an interruption you do not remember.\n   */\n  onActivate?: (chart: OpenChart, options: { reassert: boolean }) => void;\n  /**\n   * Close a chart.\n   *\n   * Called only when `canClose` returns `close` or the host confirmed a\n   * `confirm`. A `refuse` never reaches here.\n   */\n  onClose?: (chart: OpenChart) => void;\n  /** Fired when a chart is pinned, so it survives the recency ordering. */\n  onPin?: (chart: OpenChart, pinned: boolean) => void;\n  /** Keyboard reordering, the equivalent of a drag (WCAG 2.5.7). */\n  onReorder?: (charts: OpenChart[]) => void;\n  /** Start expanded, showing the panel rather than the avatar row. */\n  expanded?: boolean;\n  /** Fired when the stack expands or collapses. */\n  onExpandedChange?: (expanded: boolean) => void;\n}\n\nexport function RecentPatientStack({\n  charts,\n  activeId,\n  now,\n  onActivate,\n  onClose,\n  onPin,\n  onReorder,\n  expanded = false,\n  onExpandedChange,\n  className,\n  ...rest\n}: RecentPatientStackProps) {\n  const ordered = React.useMemo(() => orderCharts(charts), [charts]);\n  const ambiguous = React.useMemo(() => needsIdentifier(charts), [charts]);\n  const owed = describeWork(charts, now);\n\n  /**\n   * The confirmation a `confirm` verdict opens, and the refusal it never does.\n   *\n   * Typed to exclude `close`, because a chart that closes never opens a panel —\n   * holding the full union here meant the panel carried a `kind === \"close\"`\n   * branch that could not be reached and rendered `null` if it somehow were,\n   * which is a dead branch pretending to be a safety net.\n   */\n  const [pending, setPending] = React.useState<{\n    chart: OpenChart;\n    verdict: Exclude<CloseVerdict, { kind: \"close\" }>;\n  } | null>(null);\n\n  const tabs = React.useRef<Array<HTMLButtonElement | null>>([]);\n\n  const activate = (chart: OpenChart) => {\n    onActivate?.(chart, { reassert: now ? needsReassertion(chart, now) : true });\n  };\n\n  const attemptClose = (chart: OpenChart) => {\n    const verdict = canClose(chart);\n    if (verdict.kind === \"close\") {\n      onClose?.(chart);\n      return;\n    }\n    // Both `confirm` and `refuse` surface the same panel; only one of them\n    // offers a way through it.\n    setPending({ chart, verdict });\n  };\n\n  /**\n   * Roving tabindex across the stack, plus the keyboard equivalent of a drag.\n   *\n   * `Alt` + arrow moves a chart rather than the focus, which is the WCAG 2.5.7\n   * requirement: every pointer-drag needs a single-pointer or keyboard path.\n   */\n  const onKeyDown = (\n    event: React.KeyboardEvent<HTMLButtonElement>,\n    // Taken from the row that rendered the handler rather than looked up by\n    // index. The lookup needed a `!chart` guard that nothing could reach, and\n    // an unreachable guard is a line no test can honestly cover.\n    chart: OpenChart,\n    index: number,\n  ) => {\n    if (event.altKey && (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")) {\n      event.preventDefault();\n      onReorder?.(moveChart(ordered, chart.id, event.key === \"ArrowDown\" ? 1 : -1));\n      return;\n    }\n\n    const step =\n      event.key === \"ArrowRight\" || event.key === \"ArrowDown\"\n        ? 1\n        : event.key === \"ArrowLeft\" || event.key === \"ArrowUp\"\n          ? -1\n          : event.key === \"Home\"\n            ? -index\n            : event.key === \"End\"\n              ? ordered.length - 1 - index\n              : 0;\n    if (!step) return;\n\n    event.preventDefault();\n    const next = Math.min(ordered.length - 1, Math.max(0, index + step));\n    tabs.current[next]?.focus();\n  };\n\n  const hasActive = ordered.some((chart) => chart.id === activeId);\n\n  return (\n    <div\n      {...rest}\n      className={cn(\"zb-stack\", className)}\n      data-zb-stack=\"\"\n      data-zb-expanded={expanded ? \"\" : undefined}\n    >\n      <div className=\"zb-stack__bar\">\n        <div\n          className=\"zb-stack__tabs\"\n          role=\"tablist\"\n          aria-label=\"Open charts\"\n          aria-orientation={expanded ? \"vertical\" : \"horizontal\"}\n        >\n          {ordered.map((chart, index) => {\n            const active = chart.id === activeId;\n            const worst = worstWork(chart);\n            const showIdentifier = ambiguous.has(chart.id);\n\n            return (\n              <button\n                key={chart.id}\n                type=\"button\"\n                ref={(node) => {\n                  tabs.current[index] = node;\n                }}\n                role=\"tab\"\n                aria-selected={active}\n                // Roving: one stop for the whole stack, arrows within it.\n                // An activeId that matches no chart (closed elsewhere, or not\n                // yet loaded) falls back to the first tab, never to none.\n                tabIndex={active || (!hasActive && index === 0) ? 0 : -1}\n                className=\"zb-stack__tab\"\n                data-zb-accent={chartAccent(chart.id)}\n                data-zb-active={active ? \"\" : undefined}\n                data-zb-pinned={chart.pinned ? \"\" : undefined}\n                data-zb-work={worst?.kind}\n                aria-label={describeChart(chart, { showIdentifier })}\n                onClick={() => activate(chart)}\n                onKeyDown={(event) => onKeyDown(event, chart, index)}\n              >\n                {/*\n                  The face when there is one, the initials when there is not.\n                  The accent ring is drawn either way, so the hue identity\n                  survives a chart that has no photograph on file.\n                */}\n                <span className=\"zb-stack__avatar\" aria-hidden=\"true\">\n                  {chart.photo ? (\n                    // eslint-disable-next-line @next/next/no-img-element -- ships to consumers; no framework image component.\n                    <img className=\"zb-stack__face\" src={chart.photo} alt=\"\" />\n                  ) : (\n                    initials(chart.display)\n                  )}\n                </span>\n\n                {/*\n                  The name is present in every mode. Colour is an accelerant\n                  for a reader who already knows the chart, never the thing\n                  that identifies it.\n                */}\n                <span className=\"zb-stack__who\" aria-hidden=\"true\">\n                  <span className=\"zb-stack__name\">{chart.display}</span>\n                  {/*\n                    Two charts whose names look alike both grow an identifier.\n                    Marking only the newcomer would leave the reader comparing\n                    a row that has one against a row that does not.\n                  */}\n                  {showIdentifier && chart.identifier ? (\n                    <span className=\"zb-stack__identifier\">{chart.identifier}</span>\n                  ) : null}\n                  {chart.reason ? <span className=\"zb-stack__reason\">{chart.reason}</span> : null}\n                </span>\n\n                {worst ? (\n                  // One word on the tab; the long form is in the accessible\n                  // name and in the panel, where there is room for it.\n                  <span className=\"zb-stack__work\" aria-hidden=\"true\">\n                    {WORK_SHORT[worst.kind]}\n                  </span>\n                ) : null}\n              </button>\n            );\n          })}\n        </div>\n\n        <div className=\"zb-stack__controls\">\n          {owed ? (\n            <span className=\"zb-stack__owed\" aria-hidden=\"true\">\n              {owed}\n            </span>\n          ) : null}\n          {onExpandedChange ? (\n            <button\n              type=\"button\"\n              className=\"zb-stack__expand\"\n              aria-expanded={expanded}\n              onClick={() => onExpandedChange(!expanded)}\n            >\n              {expanded ? \"Collapse charts\" : `${charts.length} charts`}\n            </button>\n          ) : null}\n        </div>\n      </div>\n\n      {/*\n        Per-chart actions live in the expanded panel rather than on the tab.\n        A close affordance inside a tab is one mis-tap from losing a draft, and\n        the tab is already the target for the thing people mean to do.\n      */}\n      {expanded ? (\n        <ul className=\"zb-stack__panel\">\n          {ordered.map((chart) => (\n            <li key={chart.id} className=\"zb-stack__row\" data-zb-accent={chartAccent(chart.id)}>\n              <span className=\"zb-stack__row-name\">{chart.display}</span>\n              {ambiguous.has(chart.id) && chart.identifier ? (\n                <span className=\"zb-stack__identifier\">{chart.identifier}</span>\n              ) : null}\n              {onPin ? (\n                <button\n                  type=\"button\"\n                  className=\"zb-stack__action\"\n                  aria-pressed={Boolean(chart.pinned)}\n                  onClick={() => onPin(chart, !chart.pinned)}\n                >\n                  {chart.pinned ? \"Unpin\" : \"Pin\"}\n                </button>\n              ) : null}\n              {onClose ? (\n                <button\n                  type=\"button\"\n                  className=\"zb-stack__action\"\n                  data-zb-close=\"\"\n                  onClick={() => attemptClose(chart)}\n                >\n                  Close {chart.display}\n                </button>\n              ) : null}\n            </li>\n          ))}\n        </ul>\n      ) : null}\n\n      {/*\n        Confirm and refuse look different because they are different.\n        A draft order that vanishes with its tab is an order somebody believes\n        they placed, and nothing downstream will show its absence — so it is\n        not offered, rather than offered with a warning.\n      */}\n      {pending ? (\n        <div\n          className=\"zb-stack__verdict\"\n          data-zb-verdict={pending.verdict.kind}\n          role=\"alertdialog\"\n          aria-label={pending.verdict.kind === \"refuse\" ? \"Cannot close\" : \"Close this chart?\"}\n        >\n          <p className=\"zb-stack__verdict-reason\">{pending.verdict.reason}</p>\n          <div className=\"zb-stack__verdict-actions\">\n            {pending.verdict.kind === \"confirm\" ? (\n              <button\n                type=\"button\"\n                onClick={() => {\n                  onClose?.(pending.chart);\n                  setPending(null);\n                }}\n              >\n                Close and lose the draft\n              </button>\n            ) : null}\n            <button type=\"button\" onClick={() => setPending(null)}>\n              {pending.verdict.kind === \"refuse\" ? \"Back to the chart\" : \"Keep it open\"}\n            </button>\n          </div>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nRecentPatientStack.displayName = \"RecentPatientStack\";\n"
    }
  ]
}
