Skip to content

Chart Command Palette

Stable

A command palette that understands clinical verbs, scopes every search to a treatment relationship, and audits the searches it refuses.

12 states8 props18.5 KB installedsince 0.4.0
npx @zoblocks/cli add chart-command-palette
View sourceRegistry JSON ↗

Why it exists

Clinical navigation is a menu tree six levels deep, and the fastest people in every organisation have memorised a set of shortcuts nobody documented.

A palette is the obvious answer and almost nobody ships one, for a reason that is not obvious: in healthcare, search is a regulated act. Typing a name into a global patient search is a privacy event whether or not you open the chart, and a palette that helpfully autocompletes across the whole patient index has created a compliance problem at the speed of thought. So out-of-scope matches are rendered as a count — 3 further matches, break-glass required — which is the whole design: the reader learns the search was not empty without learning who.

Patient
Searched, and the only kind of result that is scoped. Matches outside the treatment relationship are counted, never named, and the search is audited whether or not it matched.
Task
Actions map to Task, ServiceRequest and Communication creation in the host. The palette runs the verb; it never writes the resource.

Playground

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

Design language
Props
Events
  • onRun, onClose, onSearchAudit — nothing yet
Playground.tsx
import { ChartCommandPalette } from "@/components/zoblocks/chart-command-palette";export default function Example() {  return (    <ChartCommandPalette items={items} scope={scope} open />  );}

Examples

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

DatapatientRoutinepatientRestrictedpatients

Out of scope is a count, never a name

patients

Typing a name into a global patient search is a privacy event whether or not you open the chart. Matches outside your treatment relationships are rendered as a number, so the reader learns the search was not empty without learning who — and the row sits in the list rather than under it, because a reader who misses it concludes the search was empty.

Every patient search is recorded, including the empty ones

patientRestricted

A search that found nobody is still a search that was made, and in a privacy review the empty ones are the interesting ones. The component produces the record and the host keeps it; a term that never reached the patient index produces nothing, because there is nothing to record.

Actions rank above records, because a verb is what was meant

patientRoutine

The gap between a group and the next is deliberately larger than anything frequency can close. A palette where a much-visited document outranks the verb somebody just typed has stopped being a command palette — and behavioral-health verbs are first-class here, including the one with consequences: a Part 2 disclosure request routes to consent, never to a file.

A significant action never runs on the first Enter

patientRoutine

The confirmation is a row inside the palette rather than a modal, because a modal takes the keyboard away from the surface that was built for it. The marker is on the row before it is chosen, so the second Enter is not a surprise mid-keystroke.

Variants

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

Scoped

With a treatment-relationship scope. Out-of-scope patients are counted rather than named.

open=true

Unscoped

No treatment-relationship scope, so every match is named. The contrast is the argument.

open=true

Installation

Terminal
npx @zoblocks/cli add chart-command-palette

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 { ChartCommandPalette } from "@/components/zoblocks/chart-command-palette";import "@/styles/zoblocks-palette.css";<ChartCommandPalette  open={open}  items={items}  scope={{ inScope: myPatients, breakGlass: true }}  onRun={run}  onSearchAudit={(audit) => log("patient-search", audit)}  onClose={() => setOpen(false)}/>

Use it when

  • Behind ⌘K, everywhere. The palette is the shortcut the fastest clinicians already invented for themselves.
  • With a scope. Without one, patient results are unfiltered — which is the compliance problem the component exists to avoid.
  • With `onSearchAudit` wired before the first patient source is added. A palette that searches the index without recording it is worse than no palette.
  • With `significant` set on anything destructive or clinically consequential, so it takes a second Enter rather than the first.

Avoid it when

  • Without an audit sink. The component will still produce the record; nothing will keep it.
  • As a replacement for the menu. It is the fast path for people who know what they want, not the only path.
  • With the whole patient index passed as items. Pre-filter server-side; ranking a hundred thousand candidates in the render is not what this is.
  • With confirmations delegated to a modal. The palette is a keyboard surface and a modal takes the keyboard away from it mid-flow.

API

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

ChartCommandPalette

8 props
itemsrequired
readonly PaletteItem[]
Default—
Everything the palette may match. A flat list rather than registered providers: the provider interface, its abort signals and its per-source failure handling belong to the host, which is the only place that knows which of them is a slow terminology server.
openrequired
boolean
Default—
Whether the palette is showing. Controlled, so the host owns the shortcut that summons it.
className
string
Default—
Applied to the palette's outer element.
onClose
(() => void)
Default—
Fired on Escape, on backdrop click, and after a command runs.
onRun
((item: PaletteItem) => void)
Default—
Runs an item. Only ever called for an outcome of `run`.
onSearchAudit
((audit: SearchAudit) => void)
Default—
Called once per search that touched the patient index — including the ones that matched nobody. The host writes the audit entry.
placeholder
string
Default"Search or run a command…"
The empty-field prompt. Say what can be typed — "Search, or start with a verb" — rather than "Ask anything", which promises a scope the palette will refuse.
scope
PatientScope
Default—
The treatment relationship this search is bounded by. Every query is scoped to it, and searches it refuses are audited too.

Accessibility

Screen readers and semantics

  • A combobox with an active descendant. role="combobox" on the input with aria-activedescendant pointing at the highlighted option, so focus never leaves the field a person is typing into.
  • The result count is announced once, not per keystroke. The live region is debounced by 350ms. A palette that announces on every keystroke restarts its own announcement before the previous word finishes, and a screen-reader user hears nothing in full.
  • Focus returns to the invoking element on every close path. Escape, running an item, and an external close all restore focus to whatever was focused when the palette opened. A palette that drops focus to the body has stranded the user it exists for.
  • Unavailable actions are shown with the reason. aria-disabled with the reason as text — "Offline", "Requires prescriber role". An action that vanishes teaches somebody the feature does not exist; one shown disabled teaches them what to change.
  • The withheld count is a row, not a footnote. It sits in the list where the results would be. A reader who does not see it concludes the search was empty, which is the one wrong conclusion available.
  • Groups are labelled groups. Each section is role="group" with its own name inside the listbox, so a screen reader announces "Actions, 3 items" rather than reading twelve options as one undifferentiated list.

Conformance · WCAG 2.2 AA · 8 of 8 pass

CriterionStatusHowEvidence
4.1.2Name, role, valuepassA labelled combobox with aria-expanded, aria-controls and aria-activedescendant; a listbox of options with aria-selected, and labelled groups inside it.chart-command-palette.test.tsx
2.1.1KeyboardpassArrows move the active option, Tab accepts an argument, Enter runs, Escape closes. Nothing needs a pointer.chart-command-palette.test.tsx
2.4.3Focus orderpassFocus stays in the input for the whole session and returns to the invoking element on close — a test asserts it, because this is the failure that strands a keyboard user.chart-command-palette.test.tsx
4.1.3Status messagespassaria-live="polite" carrying the result count and the withheld count, debounced by 350ms so typing does not restart the announcement on every keystroke.chart-command-palette.test.tsx
3.3.4Error preventionpassA significant action requires a second Enter, and the confirmation is a row in the palette rather than a modal that takes the keyboard away.chart-command-palette.test.tsx
1.4.1Use of colourpassThe active row carries a bar and a background; a significant action carries a marker before its confirmation; an unavailable one is struck through and states its reason in words.chart-command-palette.test.tsx
2.5.8Target size (minimum)passOptions are 32px on a pointer device and 44px below 40rem, both above the 24px floor.chart-command-palette.test.tsx
1.4.10ReflowpassBelow 40rem the palette becomes a full-screen sheet with taller rows and no keyboard hints, because there is no keyboard to hint at.chart-command-palette.test.tsx

Clinical

Behavioral-health verbs are distinct and worth first-class ranking — start PHQ-9, open safety plan, log a collateral contact, document a no-show, begin group note — and one of them has consequences: a Part 2 disclosure request routes to a consent workflow rather than to a document.

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

Protected health information

Handles PHI

Searches the patient index. The out-of-scope count and the audit record exist because a search is a privacy event before any chart is opened.

Source

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

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