{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "casework-shared",
  "title": "Casework shared parts",
  "description": "State chips, warnings, loading and error chrome, and relative-time wording that every Casework block shares.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/casework-content",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/lib-utils",
    "@registrystack/ui-button"
  ],
  "files": [
    {
      "path": "casework/shared.tsx",
      "content": "import { useEffect, useRef, type ReactNode } from \"react\";\nimport {\n  refusalDetail,\n  type CaseworkPrincipal,\n  type CommandState,\n  type Refusal,\n} from \"@registrystack/app-runtime\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/blocks/lib/utils\";\nimport { fill, relativeDays, relativeSpan } from \"@/blocks/lib/format\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { useCaseworkContent, type CaseworkContent } from \"@/blocks/casework/casework-content\";\n\n/**\n * Parts every Casework block shares: state chips, warnings, a loading\n * marker, date and waiting-time wording, and how a person or a reference\n * prints. A block owns only what it alone renders.\n */\n\nconst unknownStatusCodes = new Set<string>();\n/**\n * A review task's state or a due state, as a small coloured chip, worded by\n * the first of `labelKeys` the content labels, or by the state alone.\n */\nexport function Badge({\n  state,\n  labelKeys = [state],\n}: {\n  state: string;\n  labelKeys?: readonly string[];\n}) {\n  const c = useCaseworkContent();\n  const label = labelKeys\n    .map((key) => c.stateLabels[key])\n    .find((words) => words !== undefined);\n  if (label === undefined && !unknownStatusCodes.has(state)) {\n    unknownStatusCodes.add(state);\n    console.warn(`No content label for status \"${state}\"; using the fallback.`);\n  }\n  return (\n    <span className={`badge badge-${state.replace(/[^a-z-]/g, \"\")}`}>\n      {label ?? c.unknownStatus}\n    </span>\n  );\n}\n\n/** A warning, a success or an informational aside, read out when it warns. */\nexport function Notice({\n  title,\n  children,\n  tone = \"info\",\n}: {\n  title?: string;\n  children: ReactNode;\n  tone?: \"info\" | \"warning\" | \"success\";\n}) {\n  return (\n    <div\n      className={`notice notice-${tone}`}\n      role={tone === \"warning\" ? \"alert\" : \"status\"}\n    >\n      {title && <h2>{title}</h2>}\n      {children}\n    </div>\n  );\n}\n\n/** Shown while a block waits on data it cannot yet render. */\nexport function Loading() {\n  const c = useBlockContent();\n  return (\n    <div className=\"loading\" role=\"status\">\n      <span className=\"loading-dot\" />\n      {c.loading}\n    </div>\n  );\n}\n\n/**\n * Full local date and time with the zone named, never a bare UTC instant,\n * written in `locale`.\n */\nexport function caseworkDateTime(value: string, locale: string) {\n  const date = new Date(value);\n  return Number.isNaN(date.valueOf())\n    ? value\n    : new Intl.DateTimeFormat(locale, {\n        day: \"numeric\",\n        month: \"long\",\n        year: \"numeric\",\n        hour: \"2-digit\",\n        minute: \"2-digit\",\n        hour12: false,\n        timeZoneName: \"short\",\n      }).format(date);\n}\n/** The device time zone, named as the officer's own calendar names it. */\nexport function caseworkLocalZone(): string {\n  return Intl.DateTimeFormat().resolvedOptions().timeZone;\n}\n/** An instant as the value a `datetime-local` control takes, in local time. */\nexport function caseworkLocalInput(value: string): string {\n  const date = new Date(value);\n  if (!Number.isFinite(date.valueOf())) return \"\";\n  const pad = (part: number) => String(part).padStart(2, \"0\");\n  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(\n    date.getDate(),\n  )}T${pad(date.getHours())}:${pad(date.getMinutes())}`;\n}\n/**\n * A local date and time as the instant Casework stores. A `datetime-local`\n * value carries no offset, so it is read in the officer's own zone, which is\n * the zone the hint beside the control names.\n */\nexport function caseworkLocalInstant(value: string): string | null {\n  if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$/.test(value)) return null;\n  const date = new Date(value);\n  if (\n    !Number.isFinite(date.valueOf()) ||\n    caseworkLocalInput(date.toISOString()) !== value\n  )\n    return null;\n  return date.toISOString();\n}\n/**\n * The relative form that sits beside a full date: \"today\", \"yesterday\",\n * \"in 3 days\", \"2 days ago\". Null when the value is not a date.\n */\nexport function caseworkRelative(\n  value: string,\n  content: CaseworkContent,\n  locale: string,\n  now = new Date(),\n): string | null {\n  const days = relativeDays(value, now);\n  if (days === null) return null;\n  if (days === 0) return content.relativeToday;\n  if (days === 1) return content.relativeYesterday;\n  if (days === -1) return content.relativeTomorrow;\n  return days > 0\n    ? fill(content.relativeDaysAgo, { days }, locale)\n    : fill(content.relativeInDays, { days: -days }, locale);\n}\n/**\n * A moment as a list reads it: how late or how soon for a due date, how long\n * ago for something that happened. Lateness is a tone the cell colours; the\n * absolute instant belongs on hover and in the rail.\n */\nexport function caseworkWhen(\n  value: string,\n  tense: \"due\" | \"since\",\n  content: CaseworkContent,\n  locale: string,\n  now = new Date(),\n): { text: string; tone: \"late\" | \"today\" | null } | null {\n  const span = relativeSpan(value, now);\n  if (!span) return null;\n  const days = relativeDays(value, now) ?? 0;\n  if (tense === \"due\" || span.value < 0) {\n    if (days > 0)\n      return {\n        text: fill(content.whenLate, { days }, locale),\n        tone: tense === \"due\" ? \"late\" : null,\n      };\n    if (days === 0)\n      return {\n        text: content.whenToday,\n        tone: tense === \"due\" ? \"today\" : null,\n      };\n    if (days === -1) return { text: content.whenTomorrow, tone: null };\n    return { text: fill(content.whenInDays, { days: -days }, locale), tone: null };\n  }\n  if (span.unit === \"minute\")\n    return {\n      text:\n        span.value < 1\n          ? content.whenJustNow\n          : fill(content.whenMinutesAgo, { minutes: span.value }, locale),\n      tone: null,\n    };\n  if (span.unit === \"hour\")\n    return {\n      text: fill(content.whenHoursAgo, { hours: span.value }, locale),\n      tone: null,\n    };\n  if (days === 1) return { text: content.whenYesterday, tone: null };\n  return { text: fill(content.whenDaysAgo, { days }, locale), tone: null };\n}\n/** The relative reading of a moment, with the absolute instant on hover. */\nexport function CaseworkWhen({\n  value,\n  tense,\n  className,\n  now,\n}: {\n  value: string | null | undefined;\n  tense: \"due\" | \"since\";\n  className?: string;\n  /** Fixes \"now\" for a deterministic reading in tests. */\n  now?: Date;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const when = value ? caseworkWhen(value, tense, c, locale, now) : null;\n  if (!value || !when)\n    return <span className={cn(\"muted\", className)}>{c.noDueDate}</span>;\n  return (\n    <time\n      dateTime={value}\n      title={caseworkDateTime(value, locale)}\n      className={cn(\n        \"casework-when\",\n        when.tone && `casework-when-${when.tone}`,\n        className,\n      )}\n    >\n      {when.text}\n    </time>\n  );\n}\n/**\n * A colleague's name as a dense table prints it: initial and family name,\n * so a column of holders stays one line wide. A single name, or an account\n * with no name, prints as it is.\n */\nexport function caseworkShortName(\n  person: Pick<CaseworkPrincipal, \"subject\" | \"displayName\">,\n) {\n  const name = caseworkPerson(person);\n  const parts = name.trim().split(/\\s+/);\n  if (parts.length < 2 || !person.displayName?.trim()) return name;\n  return `${parts[0][0]}. ${parts.slice(1).join(\" \")}`;\n}\n/**\n * How long the item has been waiting, from when Casework first saw it: in\n * minutes within the hour, hours within the day and calendar days beyond, so\n * the morning's work reads apart from the last minute's.\n */\nexport function caseworkWaiting(\n  value: string,\n  content: CaseworkContent,\n  locale: string,\n  now = new Date(),\n): string {\n  const span = relativeSpan(value, now);\n  // A clock running ahead of this device has not made the item wait.\n  if (!span || span.value < 1) return content.waitingJustNow;\n  if (span.unit === \"minute\")\n    return fill(content.waitingMinutes, { minutes: span.value }, locale);\n  if (span.unit === \"hour\")\n    return fill(content.waitingHours, { hours: span.value }, locale);\n  return fill(content.waitingDays, { days: span.value }, locale);\n}\n/**\n * The human reference of the record the item concerns, never its UUID: the\n * reference Casework joined from the source request.\n */\nexport function caseworkReference(\n  item: { reference?: string | null },\n  content: CaseworkContent,\n) {\n  return item.reference?.trim() ? item.reference : content.unnamedRequest;\n}\n/** An item's reference on screen: its own reference in mono, the fallback name as prose. */\nexport function CaseworkReference({\n  item,\n}: {\n  item: { reference?: string | null };\n}) {\n  const c = useCaseworkContent();\n  const reference = caseworkReference(item, c);\n  return item.reference?.trim() ? (\n    <span className=\"font-mono\">{reference}</span>\n  ) : (\n    reference\n  );\n}\n/**\n * The readable end of an account identifier: `officer-2` for\n * `urn:app-kit:human:officer-2`, `p-17` for a URL ending in `/p-17`. Anything\n * that is not a URI, a bare identifier or a name, prints as it is.\n */\nexport function caseworkSubjectTail(subject: string) {\n  if (!/^[a-z][a-z0-9+.-]*:\\S+$/i.test(subject)) return subject;\n  return subject.split(/[:/]/).filter(Boolean).pop() ?? subject;\n}\n/**\n * How a colleague is named on screen: the directory name when Casework has\n * one, else the readable end of their account.\n */\nexport function caseworkPerson(\n  person: Pick<CaseworkPrincipal, \"subject\" | \"displayName\">,\n) {\n  return person.displayName?.trim()\n    ? person.displayName\n    : caseworkSubjectTail(person.subject);\n}\n/**\n * The whole account subject to print beside a colleague, so a name or a\n * shortened account can be traced to the account that acted. An account\n * already printed whole has none to repeat.\n */\nexport function caseworkPersonSubject(\n  person: Pick<CaseworkPrincipal, \"subject\" | \"displayName\">,\n) {\n  return caseworkPerson(person) === person.subject ? null : person.subject;\n}\n/**\n * Who holds an item, as one phrase: the colleague Casework named, or the\n * account it authenticated, with the officer's own hold marked as theirs. An\n * item nobody holds says so, so the officer knows the hold is theirs to take.\n */\nexport function caseworkHolder(\n  item: {\n    heldByMe: boolean;\n    holder?: string | null;\n    holderPrincipal?: CaseworkPrincipal | null;\n  },\n  content: CaseworkContent,\n  locale: string,\n) {\n  const name = item.holderPrincipal\n    ? caseworkPerson(item.holderPrincipal)\n    : item.holder && caseworkSubjectTail(item.holder);\n  if (!name) return content.unclaimed;\n  return item.heldByMe ? fill(content.heldByYou, { name }, locale) : name;\n}\n/**\n * A person as an officer reads them: the line naming them, with the account\n * Casework authenticated beneath it. A colleague Casework has no name for is\n * already read by their account and has none to repeat, so the account is\n * printed only beside a name.\n */\nexport function CaseworkPerson({\n  person,\n  name,\n  subject,\n}: {\n  /** The colleague, when the screen holds the principal Casework sent. */\n  person?: CaseworkPrincipal;\n  /** The line an officer reads, when it is a sentence rather than the name. */\n  name?: ReactNode;\n  /** The account beside the name, when the screen holds it without a principal. */\n  subject?: string | null;\n}) {\n  const line = name ?? (person ? caseworkPerson(person) : null);\n  const account = subject ?? (person ? caseworkPersonSubject(person) : null);\n  return (\n    <span className=\"casework-person\">\n      <span>{line}</span>\n      {account && <span className=\"casework-person-subject\">{account}</span>}\n    </span>\n  );\n}\nexport function CaseworkDue({\n  dueAt,\n  dueState,\n  includeLabel = true,\n}: {\n  dueAt?: string | null;\n  dueState?: string;\n  includeLabel?: boolean;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const relative = dueAt ? caseworkRelative(dueAt, c, locale) : null;\n  return (\n    <div className=\"casework-due\">\n      <p className=\"muted\">\n        {dueAt ? (\n          <>\n            {includeLabel && `${c.due}: `}\n            <time dateTime={dueAt}>{caseworkDateTime(dueAt, locale)}</time>\n            {relative && ` (${relative})`}\n          </>\n        ) : (\n          c.noDueDate\n        )}\n      </p>\n      {dueState && <Badge state={dueState} />}\n    </div>\n  );\n}\n\n/**\n * What a refusal means to the officer reading a review panel, in the panel's\n * own words for the one case the kind alone does not say: `notApplied`, read\n * when the task was already read back with nothing changed.\n */\nexport function caseworkRefusalText(\n  content: CaseworkContent,\n  refusal: Refusal,\n  notApplied: string,\n): string {\n  const detail = refusalDetail(refusal);\n  if (detail === \"not-applied\") return notApplied;\n  // A review stage that excludes its initiator refuses the officer who\n  // submitted the request; someone else can still take the task.\n  if (detail === \"initiator-excluded\") return content.initiatorExcluded;\n  // A review stage that takes each approval from a different reviewer refuses\n  // the officer who already reviewed it; someone else must give the approval.\n  if (detail === \"distinct-approver-required\")\n    return content.distinctApproverRequired;\n  switch (refusal.kind) {\n    case \"held-elsewhere\":\n      return content.heldElsewhere;\n    case \"stale\":\n      return content.changed;\n    case \"gone\":\n      return content.gone;\n    case \"not-authorized\":\n      return content.notAuthorized;\n    case \"key-reused\":\n      return content.keyReused;\n    default:\n      return refusal.message || content.caseworkRefusedTitle;\n  }\n}\n\n/** The shape of a command a panel shows while its last attempt is unresolved. */\nexport interface UncertainCommand {\n  state: CommandState<unknown>;\n  retry(): Promise<unknown>;\n  check?(): Promise<unknown>;\n  dismissUnknown(): void;\n}\n/**\n * An attempt whose outcome is not known. Retry resends the same attempt;\n * nothing is resent without the officer asking. When a resend was refused in\n * a way that cannot settle it, the officer may stop waiting, which gives the\n * attempt up explicitly.\n */\nexport function Unconfirmed({\n  command,\n  text,\n  retryLabel,\n  replaceText,\n  stopLabel,\n  canRetry = true,\n}: {\n  command: UncertainCommand;\n  text: string;\n  retryLabel: string;\n  replaceText?: string;\n  stopLabel?: string;\n  canRetry?: boolean;\n}) {\n  const c = useCaseworkContent();\n  const state = command.state;\n  if (state.state === \"recovering\") return <Notice>{c.checking}</Notice>;\n  if (state.state !== \"unknown\") return null;\n  if (state.withoutAuthority)\n    return (\n      <Notice tone=\"warning\">\n        <p>{c.withoutAuthority}</p>\n        <Button variant=\"outline\" onClick={command.dismissUnknown}>\n          {c.stopWaiting}\n        </Button>\n      </Notice>\n    );\n  const refusal = state.lastRefusal;\n  const forbidden = refusal?.kind === \"not-authorized\";\n  return (\n    <Notice tone=\"warning\">\n      <p>{replaceText ?? text}</p>\n      {!replaceText && forbidden && <p>{c.retryForbidden}</p>}\n      {!replaceText && refusal && !forbidden && refusal.message && (\n        <p>{refusal.message}</p>\n      )}\n      <div className=\"actions\">\n        {canRetry && !replaceText && (\n          <Button onClick={() => void command.retry()}>{retryLabel}</Button>\n        )}\n        {command.check && (\n          <Button variant=\"outline\" onClick={() => void command.check!()}>\n            {c.check}\n          </Button>\n        )}\n        {(refusal || replaceText || !canRetry) && (\n          <Button variant=\"ghost\" onClick={command.dismissUnknown}>\n            {stopLabel ?? c.stopWaiting}\n          </Button>\n        )}\n      </div>\n    </Notice>\n  );\n}\n\n/**\n * A form's validation errors, linked to each field. Focuses when errors first\n * appear or the form reports another failed attempt, never when one is removed.\n */\nexport function ErrorSummary({\n  errors,\n  focusRequest,\n}: {\n  errors: Record<string, string>;\n  /** Change this value for each failed submit that should return focus to the summary. */\n  focusRequest?: string | number;\n}) {\n  const c = useCaseworkContent();\n  const ref = useRef<HTMLDivElement>(null);\n  const previousErrors = useRef<Record<string, string>>({});\n  const previousRequest = useRef(focusRequest);\n  const errorSignature = JSON.stringify(errors);\n  useEffect(() => {\n    const hasErrors = Object.keys(errors).length > 0;\n    const newOrChangedError = Object.entries(errors).some(\n      ([id, message]) => previousErrors.current[id] !== message,\n    );\n    const requestedAgain =\n      focusRequest !== undefined &&\n      !Object.is(previousRequest.current, focusRequest);\n    if (hasErrors && (newOrChangedError || requestedAgain))\n      ref.current?.focus();\n    previousErrors.current = { ...errors };\n    previousRequest.current = focusRequest;\n  }, [errorSignature, focusRequest]);\n  if (!Object.keys(errors).length) return null;\n  return (\n    <div className=\"error-summary\" role=\"alert\" tabIndex={-1} ref={ref}>\n      <h2>{c.validationTitle}</h2>\n      <ul>\n        {Object.entries(errors).map(([id, error]) => (\n          <li key={id}>\n            <a\n              href={`#${id}`}\n              onClick={(e) => {\n                e.preventDefault();\n                document.getElementById(id)?.focus();\n              }}\n            >\n              {error}\n            </a>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\n/**\n * Words for a proposal link BReg's client reports unavailable: the reason and\n * the recovery it names, each in the content's own words. A reason or recovery\n * the content has no words for is left out; with no reason at all the line is\n * the plain \"not available\", never a guessed cause.\n */\nexport function unavailableText(\n  content: CaseworkContent,\n  availability: { reason: string; recovery: string },\n  locale: string,\n): string {\n  const reason = Object.hasOwn(content.unavailableReasons, availability.reason)\n    ? content.unavailableReasons[availability.reason]\n    : undefined;\n  if (reason === undefined) return content.unavailableNoReason;\n  const recovery = Object.hasOwn(\n    content.unavailableRecoveries,\n    availability.recovery,\n  )\n    ? content.unavailableRecoveries[availability.recovery]\n    : \"\";\n  return fill(content.unavailableLine, { reason, recovery }, locale).trim();\n}\n\n/** What a refused review handoff says: an administrator is sent to BReg's log, others to an administrator. */\nexport function handoffRefusedText(\n  content: CaseworkContent,\n  administrator: boolean,\n): string {\n  return administrator\n    ? content.handoffRefusedAdministrator\n    : content.handoffRefusedOther;\n}\n\n/** A warning for a proposal link the client reports unavailable, worded from its reason and recovery. */\nexport function UnavailableNotice({\n  reason,\n  recovery,\n}: {\n  reason: string;\n  recovery: string;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  return (\n    <Notice tone=\"warning\">\n      <p>{unavailableText(c, { reason, recovery }, locale)}</p>\n    </Notice>\n  );\n}\n\n/** A warning for a refused review handoff, worded by `handoffRefusedText`. */\nexport function HandoffRefusedNotice({\n  administrator,\n}: {\n  administrator: boolean;\n}) {\n  const c = useCaseworkContent();\n  return (\n    <Notice tone=\"warning\">\n      <p>{handoffRefusedText(c, administrator)}</p>\n    </Notice>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/casework/shared.tsx"
    }
  ],
  "type": "registry:block"
}