Skip to content

Recent Patient Stack

Stable

A multi-chart workspace that makes the active patient unmistakable, because the alternative is eleven identical browser tabs.

14 states9 props19.2 KB installedsince 0.4.0
npx @zoblocks/cli add recent-patient-stack
View sourceRegistry JSON ↗

Why it exists

Clinicians work several charts at once and the tooling pretends they do not.

The state of the art is a dropdown of names, or worse, eleven browser tabs whose titles truncate to "Chart — Riverside…". Wrong-patient documentation survives every amount of staff training because it is not a training problem: it is two charts that look identical, one keyboard shortcut, and an interruption. A stack does three things a dropdown cannot — it makes the set visible without being opened, it gives each chart a persistent visual identity, and it carries per-chart state. The identity has to be derived from the chart rather than handed out in arrival order, or a clinician who has learned "Okonkwo is the green one" has learned something that will be false tomorrow.

Patient
Identity per chart. The accent is derived from the chart id rather than from the patient, so a merged record does not silently change colour.
Task
Outstanding work per chart — a draft order, an unsigned note, an unacknowledged result — ranked by consequence rather than by age.

Playground

Change a prop and watch the component and its code change with it.

Design language
Props
Events
  • onActivate, onClose — nothing yet
Playground.tsx
import { RecentPatientStack } from "@/components/zoblocks/recent-patient-stack";export default function Example() {  return (    <RecentPatientStack      charts={charts}      activeId="chart-okonkwo"      now="2026-08-24T10:00:00Z"      expanded={false}    />  );}

Examples

The cases worth copying. Open one in StackBlitz to run it with its dependencies installed.

DatapatientRoutinepatientRestrictedpatients

The hue is derived, not handed out

patientRoutine

A chart that was blue this morning must be blue this afternoon. The accent is an FNV-1a hash of the chart id modulo eight, so it is stable across sessions and machines — and it is never the only identity, because a clinician who has learned "Okonkwo is the green one" has learned something no new colleague knows.

Two charts that look alike both grow an identifier

patients

Marking only the newcomer would leave the reader comparing a row that has an identifier against a row that does not, which is a harder comparison than two that both do. The pass is deliberately over-eager: a false positive costs a visible MRN and a false negative costs a note in the wrong chart.

Closing is graded, not binary

patientRestricted

A clean chart closes. One with an unsigned note asks, because losing the draft is a real loss that a person may still choose. One with a draft order refuses, because an order that vanishes with its tab is an order somebody believes they placed and nothing downstream will show its absence.

Coming back re-asserts who the chart belongs to

patientRoutine

Fifteen minutes, because that is roughly the length of an interruption you do not remember having — and that is the interruption that produces the wrong-chart note. A chart with no recorded activity re-asserts too: not knowing how long you were away is not the same as having just left.

Variants

Every variant is the same accessibility contract and the same keyboard model. Pick by what the surface needs.

Bar

The tab strip. The set is visible without being opened.

expanded=false

Panel

Expanded, with the per-chart pin and close actions.

expanded=true

Installation

Terminal
npx @zoblocks/cli add recent-patient-stack

First install? Run zoblocks init once to say where your @/ alias points. The source is copied into your repository, along with anything it depends on.

Dependenciesclsxtailwind-merge

Usage

Props are the FHIR resource.

usage.tsx
import { RecentPatientStack } from "@/components/zoblocks/recent-patient-stack";import "@/styles/zoblocks-workspace.css";<RecentPatientStack  charts={open}  activeId={activeId}  now={serverTime}  onActivate={(chart, { reassert }) =>    reassert ? confirmIdentity(chart) : switchTo(chart)  }  onClose={closeChart}  onReorder={setOrder}/>

Use it when

  • In the top bar of a clinical workspace, above the chart header rather than inside it.
  • With `now` from the server, so the fifteen-minute re-assertion is not decided by a clock the user can change.
  • With the outstanding work resolved upstream — a draft order and an unsigned note are different consequences and the component ranks them, but it cannot discover them.
  • With `onReorder` wired. Without it the keyboard move is silently inert, and a drag with no keyboard path is a 2.5.7 failure.

Avoid it when

  • As a substitute for the chart header. The stack says which chart; the header says who the patient is and what must not be forgotten about them.
  • With more than about eight charts open. Past that the accents repeat, the names truncate and the stack stops being scannable — which is a workflow signal, not a component limit.
  • On a phone as a full workspace. The component narrows itself deliberately; do not widen it back.
  • With an accent assigned by arrival order. The whole value is that the hue is the same tomorrow.

API

Every prop is typed. Props not listed are forwarded to the root element.

RecentPatientStack

9 props
chartsrequired
readonly OpenChart[]
Default—
The open charts, most recent first. Each carries enough to tell two patients apart, which eleven identical browser tabs do not.
activeId
string
Default—
Which chart is in front. The active patient has to be unmistakable — this is a wrong-patient control, not a tab bar.
expanded
boolean
Defaultfalse
Start expanded, showing the panel rather than the avatar row.
now
string
Default—
ISO 8601 from the host. Decides whether returning re-asserts identity.
onActivate
((chart: OpenChart, options: { reassert: boolean; }) => void)
Default—
Switch to a chart. Called with `reassert: true` when the clinician has been away long enough that the host should confirm the patient before showing the chart. Fifteen minutes is roughly the length of an interruption you do not remember.
onClose
((chart: OpenChart) => void)
Default—
Close a chart. Called only when `canClose` returns `close` or the host confirmed a `confirm`. A `refuse` never reaches here.
onExpandedChange
((expanded: boolean) => void)
Default—
Fired when the stack expands or collapses.
onPin
((chart: OpenChart, pinned: boolean) => void)
Default—
Fired when a chart is pinned, so it survives the recency ordering.
onReorder
((charts: OpenChart[]) => void)
Default—
Keyboard reordering, the equivalent of a drag (WCAG 2.5.7).

Accessibility

Screen readers and semantics

  • A tablist with roving focus. One tab stop for the whole stack; arrows move within it, Home and End jump to the ends. A workspace with eleven tab stops is a workspace a keyboard user leaves.
  • Every drag has a keyboard equivalent. Alt with the up and down arrows moves a chart rather than the focus (WCAG 2.5.7). Reordering never crosses the pinned boundary, so a keystroke cannot silently pin or unpin a chart.
  • Colour is never the only chart identity. The initials and the name are drawn in every mode, and the active chart is marked by weight and a ring as well as a hue. Eight accents rather than twelve, because twelve near-neighbours nobody can tell apart is a decoration pretending to be an identity.
  • The accessible name carries the outstanding work. "A. Okonkwo. Ward round. Unsigned note." A screen-reader user should not have to open a chart to learn there is something owed on it.
  • Refusal is not dressed as a question. Closing a chart with a draft order opens an alertdialog with one way out and no confirm button. A dialogue with only one exit that offers two is how people learn to click through the ones that matter.
  • Small screens get one legible chart. Below 40rem the inactive tabs shrink to their avatar and only the active chart keeps its name. A multi-chart workspace on a phone is a wrong-patient generator, so the set stays visible and only one chart is legible enough to act on.

Conformance · WCAG 2.2 AA · 8 of 8 pass

CriterionStatusHowEvidence
4.1.2Name, role, valuepassA tablist of tabs with aria-selected, each named with the patient, the reason the chart is open and the work outstanding on it.recent-patient-stack.test.tsx
2.1.1KeyboardpassRoving tabindex with arrow, Home and End navigation; every affordance is a native button.recent-patient-stack.test.tsx
2.5.7Dragging movementspassReordering is Alt with the up and down arrows. The pointer drag is not shipped without it, so no release can have one and not the other.recent-patient-stack.test.tsx
1.4.1Use of colourpassThe accent is one of four channels: initials, name, weight and ring. A test asserts two charts with the same accent index are still told apart by name and identifier.recent-patient-stack.test.tsx
3.2.2On inputpassMoving focus across the stack never activates a chart; activation is a click or Enter. Arrowing past a chart must not open it.recent-patient-stack.test.tsx
2.5.8Target size (minimum)passTabs carry a 36px minimum block size and every action a 28px one, both above the 24px floor.recent-patient-stack.test.tsx
4.1.3Status messagespassA close that is refused or needs confirming opens role="alertdialog" with the reason as its content rather than as a toast that disappears.recent-patient-stack.test.tsx
1.4.10ReflowpassBelow 40rem the inactive tabs shrink to their avatar and the active one keeps its name, rather than the strip scrolling eleven full-width tabs off the side.recent-patient-stack.test.tsx

Clinical

A therapist's day is six to eight charts with a note owed on each. The stack shows which notes are unsigned and how long they have been unsigned, which is the number that determines whether the week ends on time — and it is the number no dropdown of names can carry.

Industries
healthcare, behavioral-health
Workflows
documentation, care-coordination, intake
Terminology
FHIR
Permissions
patient.read
Audit
Emits no AuditEvent

Protected health information

Handles PHI

Every open patient's name is on screen at once, persistently, including during a screen share. The small-screen behaviour narrows that deliberately.

Source

Exactly what lands in your repository, read from the published registry so it can never drift from what the CLI installs.

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