{
  "$schema": "https://zoblocks.design/schema/registry-item.json",
  "name": "care-team-presence",
  "type": "zoblocks:component",
  "title": "Care Team Presence",
  "description": "Nine states rather than a green dot, each drawn as a ring shape before it is a colour. Resolves a rota to the person responsible at this moment and returns a gap when nobody is. Routes an escalation to the covering clinician before it offers an override, and warns about a documentation conflict before you type rather than at save.",
  "categories": [
    "clinical",
    "data-display"
  ],
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils",
    "tokens",
    "presence-core"
  ],
  "files": [
    {
      "path": "registry/zoblocks/care-team-presence/care-team-presence.tsx",
      "type": "zoblocks:component",
      "target": "components/zoblocks/care-team-presence.tsx",
      "content": "/**\n * CareTeamPresence — presence with clinical semantics.\n *\n *     <PresenceChip presence={marsh} now={serverTime} />\n *     <CoverageCard windows={rota} now={serverTime} onPage={page} />\n *     <ChartCoPresence others={inThisChart} now={serverTime} />\n *\n * Not \"online\". A therapist who is in session is at their desk and must not be\n * interrupted; a hospitalist who is signed out is online and is the wrong\n * person to page. The ring carries the state as a shape rather than a hue,\n * because nine colours on a 24px avatar is unreadable before it is\n * inaccessible.\n *\n * `ChartCoPresence` is the one presence signal that appears without being\n * asked for, and the reason is timing: told at save, a second note in the same\n * encounter is a merge problem; told before you type, it is a choice between\n * three reasonable options.\n *\n * Transport-agnostic. The host subscribes once and passes presence down.\n *\n * Styling lives in `styles/zoblocks-presence.css`, installed alongside.\n */\n\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  ACTIVITY_LABEL,\n  PRESENCE_LABEL,\n  PRESENCE_RING,\n  clockTime,\n  conflictsWith,\n  describeConflict,\n  describeElapsedShort,\n  describePresence,\n  isDoNotDisturb,\n  resolveCoverage,\n  resolveEscalation,\n  type ChartPresence,\n  type Clinician,\n  type CoverageWindow,\n  type EscalationTarget,\n  type Presence,\n} from \"@/lib/zoblocks-presence\";\n\nexport {\n  ACTIVITY_LABEL,\n  DO_NOT_DISTURB,\n  PRESENCE_LABEL,\n  PRESENCE_RING,\n  REDIRECTS,\n  clockTime,\n  conflictsWith,\n  coverageFromCareTeam,\n  describeConflict,\n  describeElapsedShort,\n  describePresence,\n  isDoNotDisturb,\n  resolveCoverage,\n  resolveEscalation,\n  type Activity,\n  type ChartPresence,\n  type Clinician,\n  type Coverage,\n  type CoverageWindow,\n  type EscalationTarget,\n  type Presence,\n  type PresenceState,\n} from \"@/lib/zoblocks-presence\";\n\n/**\n * Two letters, from the display name. Never a photograph.\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\n/* ------------------------------------------------------------------ */\n/* One person                                                          */\n/* ------------------------------------------------------------------ */\n\nexport interface PresenceChipProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /**\n   * The person and their current state — available, in session, signed out, off shift — with\n   * whoever is covering for them.\n   */\n  presence: Presence;\n  /** ISO 8601, supplied by the host. Needed for the degraded state's age. */\n  now?: string;\n  /** Avatar only, for a co-presence stack. The name stays in the label. */\n  compact?: boolean;\n  /**\n   * Contact this person.\n   *\n   * Routed through `resolveEscalation`, so a do-not-disturb clinician offers\n   * their cover instead and an override is a second, deliberate action.\n   */\n  onContact?: (target: EscalationTarget) => void;\n}\n\nexport const PresenceChip = React.forwardRef<HTMLDivElement, PresenceChipProps>(\n  function PresenceChip({ presence, now, compact = false, onContact, className, ...rest }, ref) {\n    const { clinician, state } = presence;\n    const escalation = resolveEscalation(presence);\n    const dnd = isDoNotDisturb(state);\n\n    return (\n      <div\n        {...rest}\n        ref={ref}\n        className={cn(\"zb-presence\", className)}\n        data-zb-presence=\"\"\n        data-zb-state={state}\n        data-zb-dnd={dnd ? \"\" : undefined}\n        data-zb-compact={compact ? \"\" : undefined}\n        role=\"group\"\n        aria-label={describePresence(presence, now)}\n      >\n        <span\n          className=\"zb-presence__avatar\"\n          data-zb-ring={PRESENCE_RING[state]}\n          aria-hidden=\"true\"\n        >\n          {initials(clinician.display)}\n        </span>\n\n        {compact ? null : (\n          <span className=\"zb-presence__body\" aria-hidden=\"true\">\n            <span className=\"zb-presence__name\">\n              {clinician.display}\n              {clinician.assignedTherapist ? (\n                <span className=\"zb-presence__assigned\">assigned therapist</span>\n              ) : null}\n            </span>\n\n            {/*\n              The role is never omitted. \"Dr Vance\" is not actionable;\n              \"Attending, night coverage until 07:00\" is, and the difference is\n              whether a reader knows they have found the right person.\n            */}\n            <span className=\"zb-presence__meta\">\n              {clinician.role ? <span className=\"zb-presence__role\">{clinician.role}</span> : null}\n              <span className=\"zb-presence__state\">{PRESENCE_LABEL[state]}</span>\n              {presence.detail ? (\n                <span className=\"zb-presence__detail\">{presence.detail}</span>\n              ) : null}\n              {presence.until ? (\n                <span className=\"zb-presence__until\">until {clockTime(presence.until, now)}</span>\n              ) : null}\n            </span>\n\n            {presence.coveredBy ? (\n              <span className=\"zb-presence__cover\">\n                → covered by {presence.coveredBy.display}\n                {presence.until ? ` until ${clockTime(presence.until, now)}` : \"\"}\n              </span>\n            ) : null}\n\n            {/*\n              A degraded channel says how stale it is. A dot that froze three\n              hours ago and still looks live is the failure this state exists\n              to prevent.\n            */}\n            {state === \"degraded\" && now && presence.since ? (\n              <span className=\"zb-presence__degraded\">\n                Last seen {describeElapsedShort(Date.parse(now) - Date.parse(presence.since))} ago ·\n                channel lost\n              </span>\n            ) : null}\n          </span>\n        )}\n\n        {onContact ? (\n          <button\n            type=\"button\"\n            className=\"zb-presence__contact\"\n            data-zb-escalation={escalation.kind}\n            onClick={() => onContact(escalation)}\n          >\n            {escalation.kind === \"covering\"\n              ? `Page ${escalation.clinician.display}`\n              : escalation.kind === \"override-required\"\n                ? \"Interrupt…\"\n                : \"Page\"}\n          </button>\n        ) : null}\n      </div>\n    );\n  },\n);\n\n/* ------------------------------------------------------------------ */\n/* Coverage                                                            */\n/* ------------------------------------------------------------------ */\n\nexport interface CoverageCardProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /**\n   * Who is covering, and when. Overlaps and gaps are both drawn: a gap in coverage is the fact\n   * a reader is looking for.\n   */\n  windows: readonly CoverageWindow[];\n  /** ISO 8601, supplied by the host. The gap this component exists to find is a window in time. */\n  now: string;\n  /**\n   * Who to reach when the primary does not answer. Rendered before it is needed rather than\n   * found during an escalation.\n   */\n  backup?: Clinician;\n  /** Fired when the reader pages somebody. The component never contacts anyone itself. */\n  onPage?: (clinician: Clinician) => void;\n}\n\n/**\n * Who is responsible right now, and until when.\n *\n * The question a PDF on a shared drive answers today. A gap in the rota is\n * rendered as a gap rather than filled with the nearest plausible name —\n * paging somebody who is asleep because the component rounded to the closest\n * window is worse than saying nobody is covering.\n */\nexport const CoverageCard = React.forwardRef<HTMLDivElement, CoverageCardProps>(\n  function CoverageCard({ windows, now, backup, onPage, className, ...rest }, ref) {\n    const coverage = resolveCoverage(windows, now, backup);\n\n    if (!coverage) {\n      return (\n        <div\n          {...rest}\n          ref={ref}\n          className={cn(\"zb-coverage zb-coverage--gap\", className)}\n          data-zb-coverage=\"gap\"\n          role=\"alert\"\n          aria-label=\"Nobody is covering this patient right now. Escalate to the on-call supervisor.\"\n        >\n          <span className=\"zb-coverage__title\" aria-hidden=\"true\">\n            Nobody is covering right now\n          </span>\n          <span className=\"zb-coverage__detail\" aria-hidden=\"true\">\n            No rota window covers this moment. Escalate to the on-call supervisor.\n          </span>\n        </div>\n      );\n    }\n\n    // Each clause is a sentence and starts like one. Joining \"Night attending\"\n    // and \"until 09:00\" with a full stop and leaving the second lower-case\n    // gives a screen reader nothing to punctuate.\n    const label = [\n      `Responsible right now: ${coverage.responsible.display}`,\n      coverage.responsible.role,\n      coverage.reason,\n      `Until ${clockTime(coverage.until, now)}`,\n      coverage.backup ? `Back-up ${coverage.backup.display}` : undefined,\n    ]\n      .filter(Boolean)\n      .join(\". \");\n\n    return (\n      <div\n        {...rest}\n        ref={ref}\n        className={cn(\"zb-coverage\", className)}\n        data-zb-coverage=\"covered\"\n        role=\"group\"\n        aria-label={`${label}.`}\n      >\n        <span className=\"zb-coverage__title\" aria-hidden=\"true\">\n          Responsible right now\n        </span>\n\n        <div className=\"zb-coverage__who\" aria-hidden=\"true\">\n          <span className=\"zb-presence__avatar\" data-zb-ring=\"solid\">\n            {initials(coverage.responsible.display)}\n          </span>\n          <span>\n            <span className=\"zb-coverage__name\">{coverage.responsible.display}</span>\n            <span className=\"zb-coverage__meta\">\n              {coverage.responsible.role ? `${coverage.responsible.role} · ` : \"\"}\n              {coverage.reason ?? \"Covering\"}\n              {` · until ${clockTime(coverage.until, now)}`}\n            </span>\n          </span>\n        </div>\n\n        {coverage.backup ? (\n          <span className=\"zb-coverage__backup\" aria-hidden=\"true\">\n            Back-up: {coverage.backup.display}\n            {coverage.backup.role ? `, ${coverage.backup.role}` : \"\"}\n            {coverage.backup.contact ? ` · ${coverage.backup.contact}` : \"\"}\n          </span>\n        ) : null}\n\n        {onPage ? (\n          <button\n            type=\"button\"\n            className=\"zb-coverage__page\"\n            onClick={() => onPage(coverage.responsible)}\n          >\n            Page {coverage.responsible.display}\n          </button>\n        ) : null}\n      </div>\n    );\n  },\n);\n\n/* ------------------------------------------------------------------ */\n/* Co-presence                                                         */\n/* ------------------------------------------------------------------ */\n\nexport interface ChartCoPresenceProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\"\n> {\n  /**\n   * Who else has this chart open right now. Two people writing the same note is a merge nobody\n   * wins.\n   */\n  others: readonly ChartPresence[];\n  /** ISO 8601, supplied by the host. Adds \"started … ago\" to the conflict notice; omitted, the notice drops that clause. */\n  now?: string;\n  /** Opens the other person's draft, read-only. */\n  onOpenTheirs?: (other: ChartPresence) => void;\n  /** Fired when the reader asks the current editor to hand over. */\n  onRequestHandoff?: (other: ChartPresence) => void;\n  /**\n   * Fired when the reader chooses to write their own addendum instead of waiting. The honest\n   * alternative to a silent overwrite.\n   */\n  onSeparateAddendum?: (other: ChartPresence) => void;\n}\n\n/**\n * Who else is in this chart, and what they are doing.\n *\n * The conflict notice is `aria-live=\"polite\"` and throttled: a stream of\n * arrival announcements is an interruption, and this component's whole purpose\n * is to prevent one kind of interruption rather than introduce another.\n */\nexport const ChartCoPresence = React.forwardRef<HTMLDivElement, ChartCoPresenceProps>(\n  function ChartCoPresence(\n    { others, now, onOpenTheirs, onRequestHandoff, onSeparateAddendum, className, ...rest },\n    ref,\n  ) {\n    const conflict = conflictsWith(others);\n\n    /*\n     * One announcement per ten seconds.\n     *\n     * Without the throttle, a ward round where six people open the same chart\n     * produces six interruptions in as many seconds — and a screen-reader user\n     * loses whatever they were reading each time.\n     */\n    const [announced, setAnnounced] = React.useState<string>(\"\");\n    // Negative infinity rather than 0: the first conflict on a freshly-mounted\n    // chart is always worth saying immediately, and `performance.now()` starts\n    // at an arbitrary point that would otherwise decide it.\n    const lastAt = React.useRef(Number.NEGATIVE_INFINITY);\n    const message = conflict ? describeConflict(conflict, now) : \"\";\n\n    React.useEffect(() => {\n      if (!message) {\n        setAnnounced(\"\");\n        return;\n      }\n      const elapsed = performance.now() - lastAt.current;\n      if (elapsed >= 10_000) {\n        lastAt.current = performance.now();\n        setAnnounced(message);\n        return;\n      }\n      const timer = setTimeout(() => {\n        lastAt.current = performance.now();\n        setAnnounced(message);\n      }, 10_000 - elapsed);\n      return () => clearTimeout(timer);\n    }, [message]);\n\n    if (!others.length) return null;\n\n    return (\n      <div\n        {...rest}\n        ref={ref}\n        className={cn(\"zb-copresence\", className)}\n        data-zb-copresence=\"\"\n        data-zb-conflict={conflict ? \"\" : undefined}\n      >\n        <span className=\"zb-copresence__stack\" aria-hidden=\"true\">\n          {others.slice(0, 4).map((other) => (\n            <span\n              key={other.clinician.id}\n              className=\"zb-presence__avatar\"\n              data-zb-ring=\"solid\"\n              data-zb-activity={other.activity}\n              title={`${other.clinician.display} — ${ACTIVITY_LABEL[other.activity]}`}\n            >\n              {initials(other.clinician.display)}\n            </span>\n          ))}\n          {others.length > 4 ? (\n            <span className=\"zb-copresence__more\">+{others.length - 4}</span>\n          ) : null}\n        </span>\n\n        {conflict ? (\n          <div className=\"zb-copresence__conflict\">\n            <p className=\"zb-copresence__message\" aria-hidden=\"true\">\n              {describeConflict(conflict, now)}\n            </p>\n            {/*\n              Three options, none of them \"carry on anyway\".\n              Told before you type, this is a choice; told at save, it is a\n              merge problem with somebody else's unsigned note.\n            */}\n            <div className=\"zb-copresence__actions\">\n              {onOpenTheirs ? (\n                <button type=\"button\" onClick={() => onOpenTheirs(conflict)}>\n                  Open theirs read-only\n                </button>\n              ) : null}\n              {onRequestHandoff ? (\n                <button type=\"button\" onClick={() => onRequestHandoff(conflict)}>\n                  Request handoff\n                </button>\n              ) : null}\n              {onSeparateAddendum ? (\n                <button type=\"button\" onClick={() => onSeparateAddendum(conflict)}>\n                  Create a separate addendum\n                </button>\n              ) : null}\n            </div>\n          </div>\n        ) : null}\n\n        {/* Polite and throttled. The component exists to prevent an\n            interruption, not to become one. */}\n        <p className=\"zb-presence__sr\" aria-live=\"polite\">\n          {announced}\n        </p>\n      </div>\n    );\n  },\n);\n"
    }
  ]
}
