{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "casework-staffing",
  "title": "Casework staffing",
  "description": "Moving one person's review tasks in a queue to a colleague, previewed and then confirmed as one move, and recording and ending an officer's absence cover, with every refusal shown in the host's words.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/casework-announce",
    "@registrystack/casework-content",
    "@registrystack/casework-shared",
    "@registrystack/field-renderers",
    "@registrystack/lib-content",
    "@registrystack/ui-alert-dialog",
    "@registrystack/ui-button",
    "@registrystack/ui-combobox",
    "@registrystack/ui-input",
    "@registrystack/ui-sheet",
    "@registrystack/lib-format"
  ],
  "files": [
    {
      "path": "casework/staffing.tsx",
      "content": "import {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type FormEvent,\n  type ReactNode,\n} from \"react\";\nimport type {\n  AuthenticatedSession,\n  CaseworkStaffingAbsence,\n  CaseworkStaffingApplyResult,\n  CaseworkStaffingCaseloadPreview,\n  CaseworkPrincipal,\n  CaseworkStaffingPrincipal,\n  ReviewTask,\n  ReviewTaskDetail,\n} from \"@registrystack/app-runtime\";\nimport type { CommandState } from \"@registrystack/app-runtime\";\nimport {\n  commandUnresolved,\n  staffingWriteStuck,\n  useAbsenceEnd,\n  useAbsenceSave,\n  useAuthority,\n  useCaseloadMove,\n  useCaseloadPreview,\n  useRereadOnRefusal,\n  useReviewTaskAssignment,\n  useStaffingRecovery,\n  useStaffingTargets,\n  type CaseloadPreviewInput,\n  type StaffingTargets,\n} from \"@registrystack/app-runtime/react\";\nimport {\n  AlertDialog,\n  AlertDialogAction,\n  AlertDialogCancel,\n  AlertDialogContent,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogHeader,\n  AlertDialogTitle,\n} from \"@/components/ui/alert-dialog\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n  Combobox,\n  ComboboxContent,\n  ComboboxEmpty,\n  ComboboxInput,\n  ComboboxItem,\n  ComboboxList,\n} from \"@/components/ui/combobox\";\nimport { Input } from \"@/components/ui/input\";\nimport {\n  Sheet,\n  SheetClose,\n  SheetContent,\n  SheetFooter,\n  SheetHeader,\n  SheetTitle,\n} from \"@/components/ui/sheet\";\nimport { FieldFrame, InputField } from \"@/blocks/fields/input-field\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\nimport { LiveAnnouncer, useAnnouncement } from \"@/blocks/casework/announce\";\nimport { useCaseworkContent } from \"@/blocks/casework/casework-content\";\nimport {\n  CaseworkPerson,\n  caseworkDateTime,\n  caseworkLocalInput,\n  caseworkLocalInstant,\n  caseworkLocalZone,\n  caseworkPerson,\n  caseworkPersonSubject,\n  ErrorSummary,\n  Loading,\n  Notice,\n} from \"@/blocks/casework/shared\";\n\n/**\n * The staffing surfaces: the caseload move a supervisor previews and confirms\n * on the Staffing page, the drawer and dialog that record or end absence\n * cover, and the form that hands one review task on to a colleague. Casework\n * decides who is eligible and what may move; these screens carry\n * presentation and wording only. A choice is sent back as the opaque\n * reference Casework issued, or, for a review task's assignment, as the\n * issuer and subject Casework named the colleague by; never as a name.\n */\n\n/**\n * How a page renders an error: with a retry when the write or read can be\n * sent again, without one for a refusal, which is answered once and stands.\n */\ntype RenderError = (error: unknown, retry?: () => void) => ReactNode;\n\ninterface TargetOption {\n  /** The session-bound reference Casework issued; the only value ever sent. */\n  value: string;\n  label: string;\n  /** The subject shown beside a name, and nothing when the name is the subject. */\n  subject: string | null;\n}\n\ntype Targets = StaffingTargets;\nexport { useStaffingAbsenceCover } from \"@registrystack/app-runtime/react\";\n\n/**\n * What Casework said about the page of colleagues it answered, in the words\n * every screen reading a bounded page uses. A page that is complete but empty\n * says so instead: the list is not short, there is nobody on it.\n */\nfunction TargetStatus({ targets }: { targets: Targets }) {\n  const c = useCaseworkContent();\n  if (!targets.loaded) return null;\n  const shortfall = targets.pageStatus\n    ? c.caseworkPageStatus[targets.pageStatus]\n    : undefined;\n  if (shortfall) return <p className=\"staffing-status\">{shortfall}</p>;\n  if (!targets.items.length)\n    return <p className=\"staffing-status\">{c.targetsUnavailable}</p>;\n  return null;\n}\n\n/** What Casework said about a colleague list, and the way to read more of it. */\nfunction TargetListStatus({\n  targets,\n  announce,\n}: {\n  targets: Targets;\n  announce?: (message: string) => void;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  return (\n    <>\n      <TargetStatus targets={targets} />\n      {targets.hasNextPage && (\n        <div className=\"actions\">\n          <Button\n            variant=\"outline\"\n            disabled={targets.isFetchingNextPage}\n            onClick={async () => {\n              const more = await targets.fetchNextPage();\n              const count =\n                more.data?.pages.reduce(\n                  (total, page) => total + page.items.length,\n                  0,\n                ) ?? 0;\n              announce?.(fill(c.moreTargetsLoaded, { count }, locale));\n            }}\n          >\n            {c.moreTargets}\n          </Button>\n        </div>\n      )}\n    </>\n  );\n}\n\nfunction TargetCombobox({\n  name,\n  label,\n  value,\n  onChange,\n  error,\n  targets,\n  announce,\n  inline = false,\n  exclude,\n  listStatus = true,\n}: {\n  name: string;\n  label: string;\n  value: string;\n  onChange: (value: string) => void;\n  error?: string;\n  targets: Targets;\n  announce?: (message: string) => void;\n  /**\n   * Renders the list in the field's own flow rather than in a portalled\n   * popup, for a field inside a dialog: the list stays inside the dialog's\n   * focus trap. Base UI treats an inline list as always expanded, so the\n   * combobox is only inline while its list is open; closed, it reports\n   * itself collapsed and points at no list.\n   */\n  inline?: boolean;\n  /** A reference left out of the list, such as the person being covered. */\n  exclude?: string;\n  /**\n   * Says under the field what Casework said about its list, with the way to\n   * read more of it. A form whose fields share one list says it once instead.\n   */\n  listStatus?: boolean;\n}) {\n  const c = useCaseworkContent();\n  const [listOpen, setListOpen] = useState(false);\n  const options: TargetOption[] = useMemo(\n    () =>\n      targets.items\n        .filter((target) => target.ref !== exclude)\n        .map((target) => ({\n          value: target.ref,\n          label: caseworkPerson(target.principal),\n          subject: caseworkPersonSubject(target.principal),\n        })),\n    [targets.items, exclude],\n  );\n  const list = (\n    <>\n      <ComboboxEmpty>{c.noMatchingColleague}</ComboboxEmpty>\n      {/* The list is portalled out of the field, so it carries the name\n          the shared component requires instead of inheriting the field's. */}\n      <ComboboxList aria-label={c.targetList}>\n        {(option: TargetOption) => (\n          <ComboboxItem key={option.value} value={option}>\n            <CaseworkPerson name={option.label} subject={option.subject} />\n          </ComboboxItem>\n        )}\n      </ComboboxList>\n    </>\n  );\n  const selected = options.find((option) => option.value === value) ?? null;\n  return (\n    <div className={`field ${error ? \"field-error\" : \"\"}`}>\n      <label htmlFor={name}>{label}</label>\n      {error && (\n        <p className=\"field-error-message\" id={`${name}-error`}>\n          {error}\n        </p>\n      )}\n      <Combobox\n        items={options}\n        value={selected}\n        onValueChange={(next: TargetOption | null) =>\n          onChange(next ? next.value : \"\")\n        }\n        isItemEqualToValue={(a: TargetOption, b: TargetOption) =>\n          a.value === b.value\n        }\n        {...(inline\n          ? {\n              inline: listOpen,\n              open: listOpen,\n              onOpenChange: (open: boolean) => setListOpen(open),\n            }\n          : {})}\n      >\n        {/* The input opens the list on its own, so the list is reached from\n            the input alone: at a phone's width the field has no room for a\n            second control beside what an officer types. */}\n        <ComboboxInput\n          id={name}\n          name={name}\n          placeholder={c.selectTarget}\n          showTrigger={false}\n          aria-invalid={!!error}\n          aria-describedby={error ? `${name}-error` : undefined}\n        />\n        {inline ? (\n          listOpen && (\n            <div className=\"mt-1 max-h-60 overflow-y-auto rounded-md border bg-popover shadow-sm\">\n              {list}\n            </div>\n          )\n        ) : (\n          <ComboboxContent>{list}</ComboboxContent>\n        )}\n      </Combobox>\n      {listStatus && <TargetListStatus targets={targets} announce={announce} />}\n    </div>\n  );\n}\n\n/**\n * Moves focus to the panel that reports a write's outcome, so the officer\n * reads the answer where they are instead of hunting for it down the page.\n * Focus moves in the commit that shows the panel, and once more a frame\n * later if it was taken away: a form that unmounts with focus on its submit\n * button inside a drawer lets the drawer reclaim focus a frame after the\n * button left, which an answer arriving sooner than that would lose to.\n */\nfunction useOutcomeFocus<T extends HTMLElement>(shown: boolean) {\n  const panel = useRef<T>(null);\n  useLayoutEffect(() => {\n    const target = panel.current;\n    if (!shown || !target) return;\n    target.focus();\n    const frame = requestAnimationFrame(() => {\n      if (document.activeElement !== target) target.focus();\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [shown]);\n  return panel;\n}\n\n/**\n * A staffing write Casework could not confirm. The same attempt is offered\n * again; a second attempt is never created from this notice. An attempt the\n * host can no longer resend is left for the officer to check, and can be put\n * away.\n */\nfunction UnknownWrite({\n  message,\n  state,\n  retry,\n  dismiss,\n}: {\n  message: string;\n  state: CommandState<unknown>;\n  retry: () => void;\n  dismiss: () => void;\n}) {\n  const c = useCaseworkContent();\n  if (staffingWriteStuck(state))\n    return (\n      <Notice tone=\"warning\">\n        <p>{c.unknownStuck}</p>\n        <Button variant=\"outline\" onClick={dismiss}>\n          {c.stopShowing}\n        </Button>\n      </Notice>\n    );\n  return (\n    <Notice tone=\"warning\">\n      <p>{message}</p>\n      <Button\n        variant=\"outline\"\n        disabled={state.state === \"recovering\"}\n        onClick={retry}\n      >\n        {c.exactRetry}\n      </Button>\n    </Notice>\n  );\n}\n\n/**\n * The staffing writes of this session whose outcome is unknown, offered back\n * from any page: each is retried as the same attempt, never sent afresh.\n */\nexport function StaffingPendingNotice({ route }: { route: string }) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const recovery = useStaffingRecovery();\n  const { clearOutcome } = recovery;\n  const live = recovery.pending.filter(\n    (entry) => !entry.withoutAuthority,\n  ).length;\n  const orphaned = recovery.pending.length - live;\n  // An outcome is read where it was reported; the next page starts clean.\n  useEffect(() => clearOutcome(), [route]); // eslint-disable-line react-hooks/exhaustive-deps\n  if (!recovery.pending.length)\n    return recovery.outcome === \"confirmed\" ||\n      recovery.outcome === \"refused\" ? (\n      <div className=\"staffing-pending\">\n        <Notice tone={recovery.outcome === \"confirmed\" ? \"success\" : \"info\"}>\n          {recovery.outcome === \"confirmed\"\n            ? c.pendingRecorded\n            : c.pendingRefused}\n        </Notice>\n      </div>\n    ) : null;\n  const stuck = recovery.stuck.length > 0;\n  return (\n    <div className=\"staffing-pending\">\n      <Notice tone=\"warning\" title={c.pendingTitle}>\n        {live > 0 && <p>{fill(c.pendingBody, { count: live }, locale)}</p>}\n        {recovery.outcome === \"refused\" && <p>{c.pendingRefused}</p>}\n        {recovery.outcome === \"unknown\" && (\n          <p>{stuck ? c.unknownStuck : c.pendingStill}</p>\n        )}\n        {orphaned > 0 && <p>{c.pendingWithoutAuthority}</p>}\n        <div className=\"actions\">\n          {live > 0 && (\n            <Button\n              disabled={recovery.busy}\n              onClick={() => void recovery.retryAll()}\n            >\n              {c.pendingRetry}\n            </Button>\n          )}\n          {(orphaned > 0 || stuck) && (\n            <Button variant=\"outline\" onClick={recovery.forget}>\n              {c.stopShowing}\n            </Button>\n          )}\n        </div>\n      </Notice>\n    </div>\n  );\n}\n\n/** The ways one review task is handed on to a colleague. */\nexport type ReviewAssignmentOperation = \"assign\" | \"delegate\";\n\n/**\n * The ways of handing a review task on to offer an officer: a supervisor\n * assigns it, the officer holding it delegates it, and a decided task goes\n * nowhere. An offer grants nothing; Casework checks every assignment again.\n */\nexport function reviewAssignmentOperations(\n  task: Pick<ReviewTask, \"status\" | \"heldByYou\">,\n  profile: AuthenticatedSession[\"caseworkProfile\"],\n): ReviewAssignmentOperation[] {\n  if (task.status === \"decided\") return [];\n  const operations: ReviewAssignmentOperation[] = [];\n  if (profile === \"supervisor\") operations.push(\"assign\");\n  if (task.heldByYou) operations.push(\"delegate\");\n  return operations;\n}\n\n/**\n * The colleague chosen from a list, named as Casework names a person: by\n * issuer and subject. The reference the list keys them by is bound to this\n * session's read of the list, and is never sent.\n */\nexport function assignmentPrincipal(\n  targets: readonly CaseworkStaffingPrincipal[],\n  ref: string,\n): { issuer: string; subject: string } | undefined {\n  const target = ref ? targets.find((item) => item.ref === ref) : undefined;\n  return target\n    ? { issuer: target.principal.issuer, subject: target.principal.subject }\n    : undefined;\n}\n\n/**\n * Hands one review task on to a colleague: a supervisor assigns it, the\n * officer holding it delegates it. The colleagues are read when the officer\n * opens the form. An attempt that has not settled keeps the form open and in\n * view, even once the task as read again offers nothing more to do.\n */\nexport function ReviewAssignmentForm({\n  task,\n  reread,\n  rereading,\n  renderError,\n}: {\n  task: ReviewTaskDetail;\n  /** Reads the task again, after a refusal that says it moved on. */\n  reread: () => void;\n  /** Whether the task is being read again; nothing is sent until it is. */\n  rereading: boolean;\n  renderError: RenderError;\n}) {\n  const c = useCaseworkContent();\n  const operations = reviewAssignmentOperations(\n    task,\n    useAuthority().caseworkProfile,\n  );\n  // An unresolved assignment of this task is restored wherever it is shown.\n  const command = useReviewTaskAssignment(task.taskId);\n  const state = command.state;\n  useRereadOnRefusal(state, reread);\n  const [opened, setOpened] = useState(false);\n  const open =\n    opened || (state.state !== \"idle\" && state.state !== \"confirmed\");\n  const formShown = open && operations.length > 0;\n  const targets = useStaffingTargets(\n    formShown\n      ? { purpose: \"assignment\", queue: task.queue, limit: \"100\" }\n      : null,\n  );\n  const [announcement, announce] = useAnnouncement();\n  const [chosen, setChosen] = useState<ReviewAssignmentOperation>();\n  const operation =\n    chosen && operations.includes(chosen) ? chosen : operations[0];\n  const [targetRef, setTargetRef] = useState(\"\");\n  const [reason, setReason] = useState(\"\");\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  const confirmed = state.state === \"confirmed\";\n  const assignmentOutcome = useOutcomeFocus<HTMLDivElement>(confirmed);\n\n  if (!operations.length && state.state === \"idle\") return null;\n\n  function submit(event: FormEvent) {\n    event.preventDefault();\n    if (command.locked || rereading) return;\n    const to = assignmentPrincipal(targets.items, targetRef);\n    const next: Record<string, string> = {};\n    if (!operation) next[\"staffing-action\"] = c.requiredError;\n    if (!to) next[\"staffing-target\"] = c.requiredError;\n    setErrors(next);\n    if (!operation || !to) return;\n    void command.assign(task, operation, to, reason.trim() || undefined);\n  }\n\n  return (\n    <section className=\"staffing-assignment\">\n      {operations.length > 0 && (\n        <Button\n          variant=\"outline\"\n          aria-expanded={open}\n          // While the outcome is unknown nothing here can hide it.\n          disabled={command.locked}\n          onClick={() => {\n            if (!open) return setOpened(true);\n            setOpened(false);\n            command.dismiss();\n          }}\n        >\n          {c.assignmentHeading}\n        </Button>\n      )}\n      {formShown && (\n        <>\n          <p>{c.assignmentDescription}</p>\n          <LiveAnnouncer message={announcement} />\n          {targets.isPending ? (\n            <Loading />\n          ) : targets.error ? (\n            renderError(targets.error, () => void targets.refetch())\n          ) : (\n            <form onSubmit={submit}>\n              <ErrorSummary errors={errors} />\n              {/* While the outcome is unknown nothing here can start a second\n                  attempt. */}\n              <fieldset disabled={command.locked} className=\"min-w-0\">\n                <InputField\n                  name=\"staffing-action\"\n                  label={c.assignmentAction}\n                  value={operation ?? \"\"}\n                  onChange={(value) => {\n                    const next = operations.find((name) => name === value);\n                    if (next) setChosen(next);\n                  }}\n                  error={errors[\"staffing-action\"]}\n                  options={operations.map((name) => ({\n                    value: name,\n                    label: c.actionLabels[name],\n                  }))}\n                />\n                <TargetCombobox\n                  name=\"staffing-target\"\n                  label={c.assignmentTarget}\n                  value={targetRef}\n                  onChange={setTargetRef}\n                  error={errors[\"staffing-target\"]}\n                  targets={targets}\n                  announce={announce}\n                />\n                <InputField\n                  name=\"staffing-reason\"\n                  label={c.assignmentReason}\n                  value={reason}\n                  onChange={setReason}\n                  hint={c.assignmentReasonHint}\n                  required={false}\n                  multiline\n                />\n              </fieldset>\n              {!command.locked && operation && (\n                <Button type=\"submit\" disabled={rereading}>\n                  {c.actionLabels[operation]}\n                </Button>\n              )}\n            </form>\n          )}\n        </>\n      )}\n      {state.state === \"refused\" && renderError(state.error)}\n      {commandUnresolved(state) && (\n        <UnknownWrite\n          message={c.assignmentUnknown}\n          state={state}\n          retry={() => void command.retry()}\n          dismiss={command.dismissUnknown}\n        />\n      )}\n      {confirmed && (\n        <div className=\"staffing-outcome\" tabIndex={-1} ref={assignmentOutcome}>\n          <Notice tone=\"success\">{c.assignmentConfirmed}</Notice>\n        </div>\n      )}\n    </section>\n  );\n}\n\n/** Whether two staffing records carry the same authority identity. */\nexport function isSamePerson(\n  left: CaseworkPrincipal,\n  right: CaseworkPrincipal,\n) {\n  return left.issuer === right.issuer && left.subject === right.subject;\n}\n\n/** Where focus goes when a dialog closes: the control that opened it, else the page title. */\ntype FinalFocus = () => HTMLElement | null;\n\n/** One way to move the review tasks a person holds, offered once their cover is saved. */\nexport interface MoveOffer {\n  key: string;\n  queueLabel: string;\n  open: () => void;\n}\n\n/**\n * The drawer that records or edits one absence cover. Cover changes where new\n * assignments go; it moves nothing already held, so the drawer says so and\n * offers the move once the cover is saved.\n */\nexport function AbsenceDrawer({\n  open,\n  onOpenChange,\n  absence,\n  person,\n  directoryRef,\n  finalFocus,\n  moveOffers,\n  renderError,\n}: {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** The cover being edited; absent when a new one is recorded. */\n  absence?: CaseworkStaffingAbsence;\n  /** The person away, when the drawer opens from their row. */\n  person?: CaseworkStaffingPrincipal;\n  directoryRef: string;\n  finalFocus: FinalFocus;\n  moveOffers: (principal: CaseworkPrincipal) => MoveOffer[];\n  renderError: RenderError;\n}) {\n  const c = useCaseworkContent();\n  const [unresolved, setUnresolved] = useState(false);\n  return (\n    <Sheet\n      open={open}\n      onOpenChange={(next) => {\n        if (next || !unresolved) onOpenChange(next);\n      }}\n    >\n      <SheetContent\n        side=\"inline-end\"\n        showCloseButton={false}\n        finalFocus={finalFocus}\n        className=\"overflow-y-auto\"\n      >\n        <SheetHeader>\n          <SheetTitle className=\"mb-0\">\n            {absence ? c.editAbsence : c.createAbsence}\n          </SheetTitle>\n        </SheetHeader>\n        <AbsenceForm\n          absence={absence}\n          person={person}\n          directoryRef={directoryRef}\n          moveOffers={moveOffers}\n          onUnresolvedChange={setUnresolved}\n          renderError={renderError}\n        />\n      </SheetContent>\n    </Sheet>\n  );\n}\n\n/** A local date and a local time, as the two controls hold them. */\nfunction splitLocal(value: string): [string, string] {\n  const [date = \"\", time = \"\"] = caseworkLocalInput(value).split(\"T\");\n  return [date, time];\n}\n\nexport function AbsenceForm({\n  absence,\n  person,\n  directoryRef,\n  moveOffers,\n  onUnresolvedChange,\n  renderError,\n}: {\n  absence?: CaseworkStaffingAbsence;\n  person?: CaseworkStaffingPrincipal;\n  directoryRef: string;\n  moveOffers: (principal: CaseworkPrincipal) => MoveOffer[];\n  onUnresolvedChange: (unresolved: boolean) => void;\n  renderError: RenderError;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const [announcement, announce] = useAnnouncement();\n  const fixed = absence?.person ?? person;\n  const people = useStaffingTargets(\n    fixed ? null : { purpose: \"absencePerson\", limit: \"100\" },\n  );\n  const [personRef, setPersonRef] = useState(fixed?.ref ?? \"\");\n  const covers = useStaffingTargets(\n    personRef ? { purpose: \"absenceCover\", personRef, limit: \"100\" } : null,\n  );\n  const [coverRef, setCoverRef] = useState(absence?.cover.ref ?? \"\");\n  const initialFrom = absence ? splitLocal(absence.from) : [\"\", \"\"];\n  const initialUntil = absence ? splitLocal(absence.until) : [\"\", \"\"];\n  const [fromDate, setFromDate] = useState(initialFrom[0]);\n  const [fromTime, setFromTime] = useState(initialFrom[1]);\n  const [untilDate, setUntilDate] = useState(initialUntil[0]);\n  const [untilTime, setUntilTime] = useState(initialUntil[1]);\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  // An unresolved edit of this cover, or an unresolved new cover, is restored\n  // whenever the drawer opens again, even after a reload.\n  const command = useAbsenceSave(absence ? absence.ref : \"create\");\n  const confirmed = command.state.state === \"confirmed\";\n  const outcome = useOutcomeFocus<HTMLDivElement>(confirmed);\n\n  useEffect(\n    () => onUnresolvedChange(command.locked),\n    [onUnresolvedChange, command.locked],\n  );\n\n  const principal =\n    fixed?.principal ??\n    people.items.find((target) => target.ref === personRef)?.principal;\n  const name = principal ? caseworkPerson(principal) : undefined;\n\n  function submit(event: FormEvent) {\n    event.preventDefault();\n    if (command.locked) return;\n    const start = caseworkLocalInstant(`${fromDate}T${fromTime}`);\n    const end = caseworkLocalInstant(`${untilDate}T${untilTime}`);\n    const next: Record<string, string> = {};\n    if (!personRef) next[\"absence-person\"] = c.requiredError;\n    if (!coverRef) next[\"absence-cover\"] = c.requiredError;\n    if (!start) next[\"absence-from-date\"] = c.requiredError;\n    if (!end) next[\"absence-until\"] = c.requiredError;\n    else if (start && end <= start) next[\"absence-until\"] = c.invalidInterval;\n    setErrors(next);\n    if (Object.keys(next).length || !start || !end) return;\n    const common = { directoryRef, coverRef, from: start, until: end };\n    void command.run(\n      absence\n        ? { ...common, absenceRef: absence.ref }\n        : { ...common, personRef },\n    );\n  }\n\n  if (confirmed)\n    return (\n      <div className=\"flex flex-1 flex-col\">\n        <div\n          className=\"staffing-outcome flex flex-col gap-3 px-4\"\n          tabIndex={-1}\n          ref={outcome}\n        >\n          <Notice tone=\"success\">{c.absenceConfirmed}</Notice>\n          {principal &&\n            moveOffers(principal).map((offer) => (\n              <Button key={offer.key} variant=\"outline\" onClick={offer.open}>\n                {`${fill(c.caseloadTitle, { person: name!, queue: offer.queueLabel }, locale)}…`}\n              </Button>\n            ))}\n        </div>\n        <SheetFooter>\n          <SheetClose render={<Button variant=\"outline\" />}>\n            {c.close}\n          </SheetClose>\n        </SheetFooter>\n      </div>\n    );\n\n  if (!fixed && people.isPending) return <Loading />;\n  if (!fixed && people.error)\n    return renderError(people.error, () => void people.refetch());\n\n  const zone = caseworkLocalZone();\n  return (\n    <form className=\"flex flex-1 flex-col\" onSubmit={submit} noValidate>\n      <div className=\"px-4\">\n        <LiveAnnouncer message={announcement} />\n        <ErrorSummary errors={errors} />\n        {/* While the outcome is unknown nothing here can start a second\n            attempt. */}\n        <fieldset disabled={command.locked} className=\"min-w-0\">\n          {fixed ? (\n            <div className=\"field\">\n              <p className=\"field-label\">{c.person}</p>\n              <CaseworkPerson person={fixed.principal} />\n            </div>\n          ) : (\n            <TargetCombobox\n              inline\n              name=\"absence-person\"\n              label={c.person}\n              value={personRef}\n              onChange={(value) => {\n                setPersonRef(value);\n                setCoverRef(\"\");\n              }}\n              error={errors[\"absence-person\"]}\n              targets={people}\n              announce={announce}\n            />\n          )}\n          {personRef && (\n            <TargetCombobox\n              inline\n              name=\"absence-cover\"\n              label={c.cover}\n              value={coverRef}\n              onChange={setCoverRef}\n              error={errors[\"absence-cover\"]}\n              targets={covers}\n              exclude={personRef}\n              announce={announce}\n            />\n          )}\n          {covers.error &&\n            renderError(covers.error, () => void covers.refetch())}\n          <WhenField\n            id=\"absence-from-date\"\n            legend={c.from}\n            dateLabel={c.fromDate}\n            timeLabel={c.fromTime}\n            date={fromDate}\n            time={fromTime}\n            onDate={setFromDate}\n            onTime={setFromTime}\n            error={errors[\"absence-from-date\"]}\n          />\n          <WhenField\n            id=\"absence-until\"\n            legend={c.until}\n            dateLabel={c.untilDate}\n            timeLabel={c.untilTime}\n            date={untilDate}\n            time={untilTime}\n            onDate={setUntilDate}\n            onTime={setUntilTime}\n            error={errors[\"absence-until\"]}\n          />\n          <p className=\"mb-3 text-xs text-muted-foreground\">\n            {fill(c.zoneHint, { zone }, locale)}\n          </p>\n          {name && <p className=\"mb-3 text-sm\">{fill(c.heldWork, { person: name }, locale)}</p>}\n        </fieldset>\n        {command.state.state === \"refused\" && renderError(command.state.error)}\n        {commandUnresolved(command.state) && (\n          <UnknownWrite\n            message={c.absenceUnknown}\n            state={command.state}\n            retry={() => void command.retry()}\n            dismiss={command.dismissUnknown}\n          />\n        )}\n      </div>\n      <SheetFooter className=\"flex-row justify-end\">\n        {!command.locked && (\n          <SheetClose render={<Button variant=\"outline\" />}>\n            {c.cancel}\n          </SheetClose>\n        )}\n        {!command.locked && (\n          <Button type=\"submit\">\n            {absence ? c.saveAbsenceChanges : c.saveAbsence}\n          </Button>\n        )}\n      </SheetFooter>\n    </form>\n  );\n}\n\n/**\n * One end of a cover, entered as a local date and a local time. The date\n * control carries the field's id, so an error summary link lands on it.\n */\nfunction WhenField({\n  id,\n  legend,\n  dateLabel,\n  timeLabel,\n  date,\n  time,\n  onDate,\n  onTime,\n  error,\n}: {\n  id: string;\n  legend: string;\n  dateLabel: string;\n  timeLabel: string;\n  date: string;\n  time: string;\n  onDate: (value: string) => void;\n  onTime: (value: string) => void;\n  error?: string;\n}) {\n  const described = error ? `${id}-error` : undefined;\n  return (\n    <fieldset className={`field ${error ? \"field-error\" : \"\"}`}>\n      <legend className=\"field-label\">{legend}</legend>\n      {error && (\n        <p className=\"field-error-message\" id={`${id}-error`}>\n          {error}\n        </p>\n      )}\n      <div className=\"flex flex-wrap gap-2\">\n        <label className=\"sr-only\" htmlFor={id}>\n          {dateLabel}\n        </label>\n        <Input\n          id={id}\n          type=\"date\"\n          className=\"w-auto min-w-0 flex-1\"\n          value={date}\n          onChange={(event) => onDate(event.target.value)}\n          aria-invalid={!!error}\n          aria-describedby={described}\n        />\n        <label className=\"sr-only\" htmlFor={`${id}-time`}>\n          {timeLabel}\n        </label>\n        <Input\n          id={`${id}-time`}\n          type=\"time\"\n          className=\"w-32\"\n          value={time}\n          onChange={(event) => onTime(event.target.value)}\n          aria-invalid={!!error}\n          aria-describedby={described}\n        />\n      </div>\n    </fieldset>\n  );\n}\n\n/**\n * Ending a cover is confirmed in a dialog that names the person and the dates\n * being ended. An unconfirmed end is offered back as the same attempt.\n */\nexport function EndAbsenceDialog({\n  open,\n  onOpenChange,\n  absence,\n  directoryRef,\n  finalFocus,\n  onEnded,\n  renderError,\n}: {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  absence: CaseworkStaffingAbsence;\n  directoryRef: string;\n  finalFocus: FinalFocus;\n  onEnded: () => void;\n  renderError: RenderError;\n}) {\n  // An unresolved end of this cover is restored when the dialog opens again.\n  const command = useAbsenceEnd(absence.ref);\n  return (\n    <AlertDialog\n      open={open}\n      onOpenChange={(next) => {\n        if (next || !command.locked) onOpenChange(next);\n      }}\n    >\n      <AlertDialogContent finalFocus={finalFocus}>\n        <EndAbsenceBody\n          absence={absence}\n          directoryRef={directoryRef}\n          command={command}\n          onEnded={onEnded}\n          renderError={renderError}\n        />\n      </AlertDialogContent>\n    </AlertDialog>\n  );\n}\n\n/**\n * The confirmation itself: the person and the dates being ended, and the\n * command's own outcome. Split from its dialog, which wraps content in a\n * portal a static render never sees, so the confirm and retry logic can be\n * exercised directly.\n */\nexport function EndAbsenceBody({\n  absence,\n  directoryRef,\n  command,\n  onEnded,\n  renderError,\n}: {\n  absence: CaseworkStaffingAbsence;\n  directoryRef: string;\n  command: ReturnType<typeof useAbsenceEnd>;\n  onEnded: () => void;\n  renderError: RenderError;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n\n  async function settle(answer: Promise<CommandState<unknown>>) {\n    if ((await answer).state === \"confirmed\") onEnded();\n  }\n\n  return (\n    <>\n      <AlertDialogHeader>\n        <AlertDialogTitle className=\"mb-0\">\n          {c.confirmEndAbsenceTitle}\n        </AlertDialogTitle>\n        <AlertDialogDescription className=\"mb-0\">\n          {fill(\n            c.confirmEndAbsenceBody,\n            {\n              person: caseworkPerson(absence.person.principal),\n              from: caseworkDateTime(absence.from, locale),\n              until: caseworkDateTime(absence.until, locale),\n            },\n            locale,\n          )}\n        </AlertDialogDescription>\n      </AlertDialogHeader>\n      {command.state.state === \"refused\" && renderError(command.state.error)}\n      {commandUnresolved(command.state) && (\n        <UnknownWrite\n          message={c.absenceUnknown}\n          state={command.state}\n          retry={() => void settle(command.retry())}\n          dismiss={command.dismissUnknown}\n        />\n      )}\n      <AlertDialogFooter>\n        {!command.locked && <AlertDialogCancel>{c.cancel}</AlertDialogCancel>}\n        {!command.locked && (\n          <AlertDialogAction\n            variant=\"destructive\"\n            onClick={() =>\n              void settle(\n                command.run({ directoryRef, absenceRef: absence.ref }),\n              )\n            }\n          >\n            {c.confirmEndAbsence}\n          </AlertDialogAction>\n        )}\n      </AlertDialogFooter>\n    </>\n  );\n}\n\n/** A queue a caseload can move in, as Casework named it. */\nexport interface CaseloadQueue {\n  queue: string;\n  queueLabel: string;\n}\n\n/**\n * What the officer has chosen for one caseload move. The page holds it, so an\n * absence cover's move offer can start the form with the queue and the\n * person away; that person is matched to the reference Casework issues for\n * the queue, and nothing can be previewed until a reference is chosen.\n */\nexport interface CaseloadDraft {\n  queue: string;\n  fromRef: string;\n  toRef: string;\n  reason: string;\n  /** The person away, when an absence cover's move offer started the form. */\n  fromPrincipal?: CaseworkPrincipal;\n}\n\nexport const emptyCaseloadDraft: CaseloadDraft = {\n  queue: \"\",\n  fromRef: \"\",\n  toRef: \"\",\n  reason: \"\",\n};\n\n/**\n * What a preview asks Casework for, or which fields stop it being asked. The\n * movement is named by Casework's own references and the reason alone, so a\n * name on screen never decides who is moved.\n */\nexport function caseloadPreviewRequest(\n  value: Pick<CaseloadDraft, \"queue\" | \"fromRef\" | \"toRef\" | \"reason\">,\n  required: string,\n): { input?: CaseloadPreviewInput; errors: Record<string, string> } {\n  const reason = value.reason.trim();\n  const errors: Record<string, string> = {};\n  if (!value.queue) errors[\"caseload-queue\"] = required;\n  if (!value.fromRef) errors[\"caseload-from-person\"] = required;\n  if (!value.toRef) errors[\"caseload-to-person\"] = required;\n  if (!reason) errors[\"caseload-reason\"] = required;\n  if (Object.keys(errors).length) return { errors };\n  return {\n    input: {\n      queue: value.queue,\n      fromRef: value.fromRef,\n      toRef: value.toRef,\n      reason,\n    },\n    errors,\n  };\n}\n\n/**\n * Reads a move's answer. A confirmed move spends its preview, and a refused\n * one cannot be confirmed again, so both drop the preview and the officer\n * previews afresh; an unknown outcome keeps it while the same attempt is\n * retried. Answers with Casework's own count only once it confirmed the move.\n */\nexport async function settleCaseload(\n  answer: Promise<CommandState<CaseworkStaffingApplyResult>>,\n  reset: () => void,\n): Promise<number | undefined> {\n  const settled = await answer;\n  if (settled.state === \"confirmed\" && settled.value.outcome === \"confirmed\") {\n    reset();\n    return settled.value.moved;\n  }\n  if (settled.state === \"refused\") reset();\n  return undefined;\n}\n\n/** Confirms a preview by its reference alone: Casework moves exactly the set it fenced. */\nexport function applyCaseload(\n  command: {\n    run: (body: {\n      previewRef: string;\n    }) => Promise<CommandState<CaseworkStaffingApplyResult>>;\n  },\n  previewed: Pick<CaseworkStaffingCaseloadPreview, \"previewRef\">,\n  reset: () => void,\n): Promise<number | undefined> {\n  return settleCaseload(\n    command.run({ previewRef: previewed.previewRef }),\n    reset,\n  );\n}\n\n/**\n * Moving the review tasks one person holds in one queue to a colleague. The\n * officer chooses the queue, both people and a reason, and previews: Casework\n * answers how many review tasks would move and until when the preview holds.\n * Confirming sends that preview's reference alone, and the count moved is\n * shown only once Casework confirms it. The form is controlled, so the page\n * can start it from an absence cover's move offer.\n */\nexport function CaseloadMoveForm({\n  queues,\n  queuesPartial = false,\n  value,\n  onChange,\n  renderError,\n}: {\n  queues: readonly CaseloadQueue[];\n  /** Casework listed only part of what the queues were read from. */\n  queuesPartial?: boolean;\n  value: CaseloadDraft;\n  onChange: (value: CaseloadDraft) => void;\n  renderError: RenderError;\n}) {\n  const c = useCaseworkContent();\n  const blockWords = useBlockContent();\n  const locale = useLocale();\n  const [announcement, announce] = useAnnouncement();\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  const targets = useStaffingTargets(\n    value.queue\n      ? { purpose: \"assignment\", queue: value.queue, limit: \"100\" }\n      : null,\n  );\n  const named = value.fromPrincipal;\n  const fromRef =\n    value.fromRef ||\n    (named &&\n      targets.items.find((target) => isSamePerson(target.principal, named))\n        ?.ref) ||\n    \"\";\n  // One movement per queue and person at a time: an unresolved one is\n  // restored whenever the same move is chosen again, even after a reload.\n  const command = useCaseloadMove(\n    value.queue && fromRef ? `${value.queue}/${fromRef}` : undefined,\n  );\n  const caseload = useCaseloadPreview();\n  const { previewed } = caseload;\n  const settled = command.state;\n  const moved =\n    settled.state === \"confirmed\" && settled.value.outcome === \"confirmed\"\n      ? settled.value.moved\n      : undefined;\n  const previewPanel = useOutcomeFocus<HTMLDivElement>(previewed !== null);\n  const movedPanel = useOutcomeFocus<HTMLDivElement>(moved !== undefined);\n\n  function nameOf(ref: string) {\n    const target = targets.items.find((each) => each.ref === ref);\n    return target ? caseworkPerson(target.principal) : c.caseloadUnlisted;\n  }\n\n  // Any change makes the last preview and answer about a different move.\n  function change(next: Partial<CaseloadDraft>) {\n    onChange({ ...value, fromRef, ...next });\n    caseload.reset();\n    command.dismiss();\n  }\n\n  async function preview(event: FormEvent) {\n    event.preventDefault();\n    if (command.locked || caseload.pending) return;\n    const request = caseloadPreviewRequest(\n      { ...value, fromRef },\n      c.requiredError,\n    );\n    setErrors(request.errors);\n    if (!request.input) return;\n    command.dismiss();\n    await caseload.preview(request.input);\n  }\n\n  const refusal = settled.state === \"refused\" ? settled : undefined;\n  return (\n    <>\n      <LiveAnnouncer message={announcement} />\n      <ErrorSummary errors={errors} />\n      <form noValidate onSubmit={(event) => void preview(event)}>\n        {/* While a move's outcome is unknown nothing here can start another. */}\n        <fieldset disabled={command.locked} className=\"min-w-0\">\n          <FieldFrame\n            name=\"caseload-queue\"\n            label={c.caseloadQueue}\n            error={errors[\"caseload-queue\"]}\n            required\n          >\n            <select\n              id=\"caseload-queue\"\n              name=\"caseload-queue\"\n              value={value.queue}\n              onChange={(event) =>\n                change({\n                  queue: event.target.value,\n                  fromRef: \"\",\n                  toRef: \"\",\n                  fromPrincipal: undefined,\n                })\n              }\n              aria-invalid={!!errors[\"caseload-queue\"]}\n              aria-describedby={\n                errors[\"caseload-queue\"] ? \"caseload-queue-error\" : undefined\n              }\n              required\n            >\n              <option value=\"\">{blockWords.selectOption}</option>\n              {queues.map((queue) => (\n                <option key={queue.queue} value={queue.queue}>\n                  {queue.queueLabel}\n                </option>\n              ))}\n            </select>\n            {queuesPartial && (\n              <p className=\"staffing-status\">{c.caseloadQueuesPartial}</p>\n            )}\n          </FieldFrame>\n          {value.queue &&\n            (targets.isPending ? (\n              <Loading />\n            ) : targets.error ? (\n              renderError(targets.error, () => void targets.refetch())\n            ) : (\n              <>\n                {named && targets.loaded && !fromRef && (\n                  <p className=\"staffing-status\">\n                    {fill(c.caseloadNoMove, { person: caseworkPerson(named) }, locale)}\n                  </p>\n                )}\n                <TargetCombobox\n                  name=\"caseload-from-person\"\n                  label={c.moveFrom}\n                  value={fromRef}\n                  onChange={(ref) =>\n                    change({\n                      fromRef: ref,\n                      fromPrincipal: undefined,\n                      toRef: ref === value.toRef ? \"\" : value.toRef,\n                    })\n                  }\n                  error={errors[\"caseload-from-person\"]}\n                  targets={targets}\n                  listStatus={false}\n                />\n                <TargetCombobox\n                  name=\"caseload-to-person\"\n                  label={c.moveTo}\n                  value={value.toRef}\n                  onChange={(ref) => change({ toRef: ref })}\n                  error={errors[\"caseload-to-person\"]}\n                  targets={targets}\n                  exclude={fromRef}\n                  listStatus={false}\n                />\n                {/* Both people come from one colleague list, so what Casework\n                    said about it, and the way to read more, show once. */}\n                <TargetListStatus targets={targets} announce={announce} />\n              </>\n            ))}\n          <InputField\n            name=\"caseload-reason\"\n            label={c.movementReason}\n            value={value.reason}\n            onChange={(reason) => change({ reason })}\n            error={errors[\"caseload-reason\"]}\n            multiline\n          />\n          <div className=\"actions\">\n            <Button type=\"submit\" variant=\"outline\" disabled={caseload.pending}>\n              {c.previewCaseload}\n            </Button>\n          </div>\n        </fieldset>\n      </form>\n\n      {caseload.failure !== undefined && renderError(caseload.failure)}\n      {previewed && (\n        <div className=\"staffing-preview\" tabIndex={-1} ref={previewPanel}>\n          {previewed.taskCount > 0 ? (\n            <>\n              <p>\n                {fill(\n                  c.caseloadPreviewSummary,\n                  {\n                    count: previewed.taskCount,\n                    queue: previewed.queueLabel,\n                    from: nameOf(fromRef),\n                    to: nameOf(value.toRef),\n                  },\n                  locale,\n                )}\n              </p>\n              <p className=\"staffing-status\">\n                {fill(\n                  c.caseloadPreviewExpires,\n                  { when: caseworkDateTime(previewed.expiresAt, locale) },\n                  locale,\n                )}\n              </p>\n              {!command.locked && (\n                <div className=\"actions\">\n                  <Button\n                    onClick={() =>\n                      void applyCaseload(command, previewed, caseload.reset)\n                    }\n                  >\n                    {fill(c.confirmCaseload, { count: previewed.taskCount }, locale)}\n                  </Button>\n                </div>\n              )}\n            </>\n          ) : (\n            <p>\n              {fill(\n                c.caseloadPreviewNothing,\n                { from: nameOf(fromRef), queue: previewed.queueLabel },\n                locale,\n              )}\n            </p>\n          )}\n        </div>\n      )}\n      {refusal &&\n        (refusal.refusal.kind === \"expired-reference\" ? (\n          <Notice tone=\"warning\">{c.caseloadPreviewGone}</Notice>\n        ) : (\n          renderError(refusal.error)\n        ))}\n      {commandUnresolved(settled) && (\n        <UnknownWrite\n          message={c.caseloadUnknown}\n          state={settled}\n          retry={() => void settleCaseload(command.retry(), caseload.reset)}\n          dismiss={command.dismissUnknown}\n        />\n      )}\n      {moved !== undefined && (\n        <div className=\"staffing-outcome\" tabIndex={-1} ref={movedPanel}>\n          <Notice tone=\"success\">{fill(c.caseloadMoved, { count: moved }, locale)}</Notice>\n        </div>\n      )}\n    </>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/casework/staffing.tsx"
    }
  ],
  "type": "registry:block"
}