@photonhealth/react 0.0.0-stage → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +84 -2
  3. package/dist/adapters/index.d.ts +2 -0
  4. package/dist/adapters/index.d.ts.map +1 -0
  5. package/dist/adapters/index.js +2 -0
  6. package/dist/adapters/index.js.map +1 -0
  7. package/dist/adapters/tailwind.d.ts +3 -0
  8. package/dist/adapters/tailwind.d.ts.map +1 -0
  9. package/dist/adapters/tailwind.js +123 -0
  10. package/dist/adapters/tailwind.js.map +1 -0
  11. package/dist/components/ChangeList.d.ts +21 -0
  12. package/dist/components/ChangeList.d.ts.map +1 -0
  13. package/dist/components/ChangeList.js +40 -0
  14. package/dist/components/ChangeList.js.map +1 -0
  15. package/dist/components/PhotonOrder.d.ts +46 -0
  16. package/dist/components/PhotonOrder.d.ts.map +1 -0
  17. package/dist/components/PhotonOrder.js +270 -0
  18. package/dist/components/PhotonOrder.js.map +1 -0
  19. package/dist/components/PhotonPatient.d.ts +48 -0
  20. package/dist/components/PhotonPatient.d.ts.map +1 -0
  21. package/dist/components/PhotonPatient.js +83 -0
  22. package/dist/components/PhotonPatient.js.map +1 -0
  23. package/dist/components/PhotonPrescription.d.ts +43 -0
  24. package/dist/components/PhotonPrescription.d.ts.map +1 -0
  25. package/dist/components/PhotonPrescription.js +364 -0
  26. package/dist/components/PhotonPrescription.js.map +1 -0
  27. package/dist/components/ScreeningAlerts.d.ts +6 -0
  28. package/dist/components/ScreeningAlerts.d.ts.map +1 -0
  29. package/dist/components/ScreeningAlerts.js +11 -0
  30. package/dist/components/ScreeningAlerts.js.map +1 -0
  31. package/dist/components/SignedIn.d.ts +12 -0
  32. package/dist/components/SignedIn.d.ts.map +1 -0
  33. package/dist/components/SignedIn.js +84 -0
  34. package/dist/components/SignedIn.js.map +1 -0
  35. package/dist/components/TreatmentPicker.d.ts +45 -0
  36. package/dist/components/TreatmentPicker.d.ts.map +1 -0
  37. package/dist/components/TreatmentPicker.js +279 -0
  38. package/dist/components/TreatmentPicker.js.map +1 -0
  39. package/dist/components/activity.d.ts +7 -0
  40. package/dist/components/activity.d.ts.map +1 -0
  41. package/dist/components/activity.js +24 -0
  42. package/dist/components/activity.js.map +1 -0
  43. package/dist/components/display.d.ts +90 -0
  44. package/dist/components/display.d.ts.map +1 -0
  45. package/dist/components/display.js +223 -0
  46. package/dist/components/display.js.map +1 -0
  47. package/dist/components/flow.d.ts +35 -0
  48. package/dist/components/flow.d.ts.map +1 -0
  49. package/dist/components/flow.js +53 -0
  50. package/dist/components/flow.js.map +1 -0
  51. package/dist/components/format.d.ts +26 -0
  52. package/dist/components/format.d.ts.map +1 -0
  53. package/dist/components/format.js +61 -0
  54. package/dist/components/format.js.map +1 -0
  55. package/dist/components/index.d.ts +6 -0
  56. package/dist/components/index.d.ts.map +1 -0
  57. package/dist/components/index.js +6 -0
  58. package/dist/components/index.js.map +1 -0
  59. package/dist/components/open.d.ts +47 -0
  60. package/dist/components/open.d.ts.map +1 -0
  61. package/dist/components/open.js +73 -0
  62. package/dist/components/open.js.map +1 -0
  63. package/dist/components/patient/Benefits.d.ts +25 -0
  64. package/dist/components/patient/Benefits.d.ts.map +1 -0
  65. package/dist/components/patient/Benefits.js +47 -0
  66. package/dist/components/patient/Benefits.js.map +1 -0
  67. package/dist/components/patient/Clinical.d.ts +55 -0
  68. package/dist/components/patient/Clinical.d.ts.map +1 -0
  69. package/dist/components/patient/Clinical.js +117 -0
  70. package/dist/components/patient/Clinical.js.map +1 -0
  71. package/dist/components/patient/IntakeForm.d.ts +10 -0
  72. package/dist/components/patient/IntakeForm.d.ts.map +1 -0
  73. package/dist/components/patient/IntakeForm.js +324 -0
  74. package/dist/components/patient/IntakeForm.js.map +1 -0
  75. package/dist/components/patient/Summary.d.ts +48 -0
  76. package/dist/components/patient/Summary.d.ts.map +1 -0
  77. package/dist/components/patient/Summary.js +80 -0
  78. package/dist/components/patient/Summary.js.map +1 -0
  79. package/dist/components/patient/fields.d.ts +43 -0
  80. package/dist/components/patient/fields.d.ts.map +1 -0
  81. package/dist/components/patient/fields.js +71 -0
  82. package/dist/components/patient/fields.js.map +1 -0
  83. package/dist/components/patient/query.d.ts +23 -0
  84. package/dist/components/patient/query.d.ts.map +1 -0
  85. package/dist/components/patient/query.js +65 -0
  86. package/dist/components/patient/query.js.map +1 -0
  87. package/dist/components/search.d.ts +154 -0
  88. package/dist/components/search.d.ts.map +1 -0
  89. package/dist/components/search.js +295 -0
  90. package/dist/components/search.js.map +1 -0
  91. package/dist/hooks/index.d.ts +5 -0
  92. package/dist/hooks/index.d.ts.map +1 -0
  93. package/dist/hooks/index.js +5 -0
  94. package/dist/hooks/index.js.map +1 -0
  95. package/dist/hooks/useLatestCallback.d.ts +7 -0
  96. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  97. package/dist/hooks/useLatestCallback.js +14 -0
  98. package/dist/hooks/useLatestCallback.js.map +1 -0
  99. package/dist/hooks/useLive.d.ts +15 -0
  100. package/dist/hooks/useLive.d.ts.map +1 -0
  101. package/dist/hooks/useLive.js +6 -0
  102. package/dist/hooks/useLive.js.map +1 -0
  103. package/dist/hooks/useOnChange.d.ts +11 -0
  104. package/dist/hooks/useOnChange.d.ts.map +1 -0
  105. package/dist/hooks/useOnChange.js +28 -0
  106. package/dist/hooks/useOnChange.js.map +1 -0
  107. package/dist/hooks/useSession.d.ts +7 -0
  108. package/dist/hooks/useSession.d.ts.map +1 -0
  109. package/dist/hooks/useSession.js +10 -0
  110. package/dist/hooks/useSession.js.map +1 -0
  111. package/dist/index.d.ts +20 -0
  112. package/dist/index.d.ts.map +1 -0
  113. package/dist/index.js +19 -0
  114. package/dist/index.js.map +1 -0
  115. package/dist/primitives/PhotonProvider.d.ts +58 -0
  116. package/dist/primitives/PhotonProvider.d.ts.map +1 -0
  117. package/dist/primitives/PhotonProvider.js +91 -0
  118. package/dist/primitives/PhotonProvider.js.map +1 -0
  119. package/dist/primitives/defaults.d.ts +3 -0
  120. package/dist/primitives/defaults.d.ts.map +1 -0
  121. package/dist/primitives/defaults.js +67 -0
  122. package/dist/primitives/defaults.js.map +1 -0
  123. package/dist/primitives/icons.d.ts +6 -0
  124. package/dist/primitives/icons.d.ts.map +1 -0
  125. package/dist/primitives/icons.js +6 -0
  126. package/dist/primitives/icons.js.map +1 -0
  127. package/dist/primitives/index.d.ts +5 -0
  128. package/dist/primitives/index.d.ts.map +1 -0
  129. package/dist/primitives/index.js +5 -0
  130. package/dist/primitives/index.js.map +1 -0
  131. package/dist/primitives/select.d.ts +7 -0
  132. package/dist/primitives/select.d.ts.map +1 -0
  133. package/dist/primitives/select.js +16 -0
  134. package/dist/primitives/select.js.map +1 -0
  135. package/dist/primitives/types.d.ts +276 -0
  136. package/dist/primitives/types.d.ts.map +1 -0
  137. package/dist/primitives/types.js +3 -0
  138. package/dist/primitives/types.js.map +1 -0
  139. package/dist/styles.css +611 -0
  140. package/dist/test-utils/contract.d.ts +17 -0
  141. package/dist/test-utils/contract.d.ts.map +1 -0
  142. package/dist/test-utils/contract.js +261 -0
  143. package/dist/test-utils/contract.js.map +1 -0
  144. package/package.json +74 -4
  145. package/src/adapters/index.ts +1 -0
  146. package/src/adapters/tailwind.tsx +544 -0
  147. package/src/components/ChangeList.tsx +85 -0
  148. package/src/components/PhotonOrder.tsx +493 -0
  149. package/src/components/PhotonPatient.tsx +184 -0
  150. package/src/components/PhotonPrescription.tsx +605 -0
  151. package/src/components/ScreeningAlerts.tsx +28 -0
  152. package/src/components/SignedIn.tsx +144 -0
  153. package/src/components/TreatmentPicker.tsx +350 -0
  154. package/src/components/activity.ts +23 -0
  155. package/src/components/display.ts +278 -0
  156. package/src/components/flow.ts +67 -0
  157. package/src/components/format.ts +73 -0
  158. package/src/components/index.ts +5 -0
  159. package/src/components/open.ts +100 -0
  160. package/src/components/patient/Benefits.tsx +125 -0
  161. package/src/components/patient/Clinical.tsx +210 -0
  162. package/src/components/patient/IntakeForm.tsx +532 -0
  163. package/src/components/patient/Summary.tsx +310 -0
  164. package/src/components/patient/fields.tsx +144 -0
  165. package/src/components/patient/query.ts +77 -0
  166. package/src/components/search.tsx +377 -0
  167. package/src/hooks/index.ts +4 -0
  168. package/src/hooks/useLatestCallback.ts +16 -0
  169. package/src/hooks/useLive.ts +21 -0
  170. package/src/hooks/useOnChange.ts +34 -0
  171. package/src/hooks/useSession.ts +11 -0
  172. package/src/index.ts +19 -0
  173. package/src/primitives/PhotonProvider.tsx +153 -0
  174. package/src/primitives/defaults.tsx +409 -0
  175. package/src/primitives/icons.tsx +37 -0
  176. package/src/primitives/index.ts +4 -0
  177. package/src/primitives/select.ts +15 -0
  178. package/src/primitives/types.ts +276 -0
  179. package/src/styles.css +611 -0
  180. package/src/test-utils/contract.tsx +410 -0
@@ -0,0 +1,144 @@
1
+ import type { PhotonError, Session } from "@photonhealth/client";
2
+ import { useLayoutEffect, useState, useSyncExternalStore, type ReactNode } from "react";
3
+ import { useLive } from "../hooks/index.ts";
4
+ import { useCheckFailure, useComponents, useOrganization, usePhoton } from "../primitives/index.ts";
5
+
6
+ /**
7
+ * A card, once its calls can go out: signed in (to an organization) and accepted by network-api — or at once, when
8
+ * the host signs in itself. Until then, the first card in the page offers "Sign in to <Env>" ("Sign in to Photon"
9
+ * in production; a click: a redirect to Auth0, or a popup inside an iframe) and the rest render nothing; if that
10
+ * card goes, the next one offers it. When network-api can't be reached (or can't answer), it says so and offers
11
+ * "Try again" instead.
12
+ */
13
+ export function SignedIn({ children }: { children: ReactNode }) {
14
+ const ph = usePhoton();
15
+ const session = ph.session;
16
+ const snap = useLive(session);
17
+ const failure = useCheckFailure();
18
+ const refused = failure?.error.kind === "unauthorized" ? failure.error : null;
19
+ const unreachable = failure && !refused ? failure : null;
20
+ const organization = useOrganization();
21
+ const user = snap?.status === "signed-in" ? snap.user : null;
22
+ // Signed in to an organization — the one the provider names, when it names one.
23
+ const elsewhere = Boolean(user?.organization && organization && user.organization !== organization);
24
+ const ready = !session || (user?.organization && !elsewhere && !failure);
25
+ const first = useFirstCard(session, !ready);
26
+ if (ready) return <>{children}</>;
27
+ if (!session || !snap || snap.status === "starting" || !first) return null;
28
+ if (unreachable) return <Unreachable failure={unreachable} network={ph.environment} />;
29
+ const problem: { title: string; error: PhotonError | null } | null = refused
30
+ ? { title: "Photon didn't accept this sign-in", error: refused }
31
+ : user && !user.organization
32
+ ? { title: "No organization on this sign-in", error: null }
33
+ : elsewhere
34
+ ? { title: `Signed in to another organization (${user!.organization})`, error: null }
35
+ : snap.error
36
+ ? { title: "Sign-in failed", error: snap.error }
37
+ : null;
38
+ return (
39
+ <SignIn
40
+ session={session}
41
+ environment={ph.environment?.name ?? "photon"}
42
+ organization={organization}
43
+ signingIn={snap.status === "signing-in"}
44
+ problem={problem}
45
+ />
46
+ );
47
+ }
48
+
49
+ function SignIn({
50
+ session,
51
+ environment,
52
+ organization,
53
+ signingIn,
54
+ problem,
55
+ }: {
56
+ session: Session;
57
+ environment: string;
58
+ organization: string | null;
59
+ signingIn: boolean;
60
+ problem: { title: string; error: PhotonError | null } | null;
61
+ }) {
62
+ const { Alert, Button, Card, CardBody, Row, Stack } = useComponents();
63
+ return (
64
+ <Card>
65
+ <CardBody>
66
+ <Stack gap="3">
67
+ {problem && <Alert tone="critical" title={problem.title} description={problem.error?.message} />}
68
+ <Row>
69
+ <Button loading={signingIn} onClick={() => void session.signIn(organization ? { organization } : {})}>
70
+ Sign in to {environment[0]!.toUpperCase() + environment.slice(1)}
71
+ </Button>
72
+ </Row>
73
+ </Stack>
74
+ </CardBody>
75
+ </Card>
76
+ );
77
+ }
78
+
79
+ /** network-api didn't answer the sign-in's check (offline, DNS, CORS, a 5xx) — nothing a new sign-in fixes. */
80
+ function Unreachable({
81
+ failure: { error, checking, retry },
82
+ network,
83
+ }: {
84
+ failure: NonNullable<ReturnType<typeof useCheckFailure>>;
85
+ network: { networkApiUrl: string } | null;
86
+ }) {
87
+ const { Alert, Button, Card, CardBody, Row, Stack } = useComponents();
88
+ const host = network ? new URL(network.networkApiUrl).host : null;
89
+ return (
90
+ <Card>
91
+ <CardBody>
92
+ <Stack gap="3">
93
+ <Alert
94
+ tone="critical"
95
+ title="Can't reach the Photon network"
96
+ description={
97
+ error.kind === "network"
98
+ ? `${host ?? "network-api"} didn't respond. Check your connection, then try again.`
99
+ : error.message
100
+ }
101
+ />
102
+ <Row>
103
+ <Button loading={checking} onClick={retry}>
104
+ Try again
105
+ </Button>
106
+ </Row>
107
+ </Stack>
108
+ </CardBody>
109
+ </Card>
110
+ );
111
+ }
112
+
113
+ // ---- which card offers sign-in: the first one in the page, per sign-in ----
114
+
115
+ const lines = new WeakMap<Session, { cards: symbol[]; listeners: Set<() => void> }>();
116
+ const lineOf = (session: Session) => {
117
+ let line = lines.get(session);
118
+ if (!line) lines.set(session, (line = { cards: [], listeners: new Set() }));
119
+ return line;
120
+ };
121
+
122
+ /** Whether this card is first in line (cards join as they mount, in the order the page lays them out). */
123
+ function useFirstCard(session: Session | null, waiting: boolean): boolean {
124
+ const [me] = useState(() => Symbol("card"));
125
+ useLayoutEffect(() => {
126
+ if (!session || !waiting) return;
127
+ const line = lineOf(session);
128
+ line.cards.push(me);
129
+ line.listeners.forEach((l) => l());
130
+ return () => {
131
+ line.cards = line.cards.filter((card) => card !== me);
132
+ line.listeners.forEach((l) => l());
133
+ };
134
+ }, [session, waiting, me]);
135
+ return useSyncExternalStore(
136
+ (listener) => {
137
+ if (!session) return () => {};
138
+ const line = lineOf(session);
139
+ line.listeners.add(listener);
140
+ return () => line.listeners.delete(listener);
141
+ },
142
+ () => (session ? lineOf(session).cards[0] === me : false),
143
+ );
144
+ }
@@ -0,0 +1,350 @@
1
+ import { useComponents } from "../primitives/index.ts";
2
+ import type { Change, ChangeOption } from "@photonhealth/client";
3
+ import { describeTreatmentDrug, groupTreatmentOptions, orderedOptions, strengthsOf } from "./display.ts";
4
+ import { digitKey, edge, SHOWN, took, typesBack, vertical, type SearchHandle } from "./search.tsx";
5
+ import { useEffect, useRef, useState, type KeyboardEvent } from "react";
6
+
7
+ /**
8
+ * The drug search's results (search.tsx): the server's drug choices, grouped the way a prescriber decides —
9
+ * drug, then form, then strength (instead of one long list of product names), from the parts each option's
10
+ * treatment carries (display.ts). A drug's one form or one strength is said under its name, not offered as
11
+ * a chip; more than one, and its row says how many ("2 forms · 3 strengths") and opens to chips for them.
12
+ *
13
+ * Nothing is picked for the prescriber: no chip starts pressed. A drug with more than one form and strength opens
14
+ * to both — every strength it comes in — and they're picked in either order. A pick greys out what doesn't go with
15
+ * it in the other group (a form: the strengths it doesn't come in; a strength: the forms that don't come in it);
16
+ * picking it again takes it back. A greyed chip can still be picked: it drops the other group's pick, and that's
17
+ * the prescriber's to pick again — nothing is chosen for them. The pick that leaves nothing more to pick chooses
18
+ * the product: a drug with one product is its row (no chevron); otherwise the second chip — or the first, when it
19
+ * settles both (a form with one strength, a strength only one form comes in). While the choice saves (`chosen`),
20
+ * the picker stays as it was picked, a spinner on the drug's row where the chevron goes.
21
+ *
22
+ * One outline at a time — wherever focus is. The first drug starts open, and reads as selected (accent
23
+ * outline) only while focus is on the list — that's when the keys below act on it; in its chips, the chip
24
+ * focused has the outline. Keys as every search's (1–9 / 0 opens a drug; Option/Alt + the digit from
25
+ * Treatment), plus: ↓ ↑ (or J K, or Tab / Shift+Tab — past the last / first, Tab leaves the list) move between
26
+ * drugs, Home / End (or g / G) to the first / last, D to the next one; the list is one tab stop, so Tab never goes
27
+ * into a drug. Enter on a drug chooses one with one product, else goes to its first chips to pick from (from
28
+ * Treatment too); there, Tab moves between chips, F / S to the next form / strength chip, and Enter (or Space)
29
+ * picks the one focused; Esc goes back a step — from a chip to its drug, from the drug to Treatment. ← → leave the card (the card flow's: flow.ts).
30
+ * A few drugs for what's typed and Treatment puts focus on the first (`focus(true)`): typing carries on there
31
+ * until a key acts on the list (search.tsx). `handleRef` is how the Treatment field reaches the list.
32
+ */
33
+ export interface TreatmentPickerHandle extends SearchHandle {
34
+ /** Enter on the open drug: choose it if it's one product, else go to its first chips. */
35
+ enter: () => void;
36
+ }
37
+
38
+ type Chips = "form" | "strength";
39
+
40
+ export function TreatmentPicker({
41
+ change,
42
+ onChoose,
43
+ busy,
44
+ chosen,
45
+ handleRef,
46
+ onBack,
47
+ }: {
48
+ change: Change;
49
+ onChoose?: (option: ChangeOption) => void;
50
+ busy?: boolean;
51
+ /** The product chosen, while its save runs: shown picked, with a spinner on its row; nothing else can be picked. */
52
+ chosen?: ChangeOption | null;
53
+ handleRef?: { current: TreatmentPickerHandle | null };
54
+ /** Esc in the list: back to the field that searched (Treatment). */
55
+ onBack?: () => void;
56
+ }) {
57
+ const { Button, OptionList, Stack, ToggleGroup } = useComponents();
58
+ const typed = change.inputText;
59
+ const all = groupTreatmentOptions(orderedOptions({ options: change.options.filter((o) => o.path) }, typed));
60
+ const [showAll, setShowAll] = useState(false);
61
+ const drugs = showAll ? all : all.slice(0, SHOWN);
62
+ // The open drug, and its form and strength as the prescriber picks them (null: not yet).
63
+ const [pick, setPick] = useState<{ drug: number; form: number | null; strength: string | null }>({
64
+ drug: 0,
65
+ form: null,
66
+ strength: null,
67
+ });
68
+ const root = useRef<HTMLDivElement>(null);
69
+ const list = () => root.current?.querySelector<HTMLElement>('[tabindex="0"]');
70
+ const chips = (group: Chips) => [
71
+ ...(root.current?.querySelectorAll<HTMLElement>(`[data-chips="${group}"] button:not(:disabled)`) ?? []),
72
+ ];
73
+ // Focus is on the list itself (not a chip or a row): the open drug has the outline.
74
+ const [onList, setOnList] = useState(false);
75
+ // Focus is in the open drug's chips (Enter took it there): Tab moves between them.
76
+ const [inChips, setInChips] = useState(false);
77
+ // Focus was put here for the prescriber, mid-typing: keys that type go back to Treatment (typesBack).
78
+ const typing = useRef(false);
79
+ // Where focus goes once the next render is in: the list, or a chip (the other group's, once one is picked).
80
+ const focusNext = useRef<"list" | { group: Chips; at: number } | null>(null);
81
+ const firstRender = useRef(true);
82
+ useEffect(() => {
83
+ // One tab stop — the list: Tab moves between drugs (onKeyDown), not into one. Its rows and chips are reached
84
+ // with the keys; once Enter takes focus into the chips, Tab moves between them.
85
+ list()
86
+ ?.querySelectorAll<HTMLElement>("button")
87
+ .forEach((button) => (button.tabIndex = inChips && button.closest("[data-chips]") ? 0 : -1));
88
+ const next = focusNext.current;
89
+ focusNext.current = null;
90
+ if (next === "list") list()?.focus();
91
+ else if (next) chips(next.group)[next.at]?.focus();
92
+ else if (!firstRender.current) {
93
+ // Opening a drug replaces the row button that had focus; keep focus in the list so keys still work.
94
+ // Never on first render (focus stays wherever the prescriber is).
95
+ const active = document.activeElement;
96
+ if (!active || active === document.body || !active.isConnected) list()?.focus();
97
+ }
98
+ firstRender.current = false;
99
+ });
100
+
101
+ // What's shown picked: the prescriber's picks — or, while a choice saves, the product chosen.
102
+ const view = (chosen && locate(drugs, chosen)) || pick;
103
+ const drugAt = Math.min(view.drug, drugs.length - 1);
104
+ const drug = drugs[drugAt];
105
+ // One form is the drug's form; with more, none until it's picked.
106
+ const formAt = drug?.forms.length === 1 ? 0 : view.form;
107
+ // The product a form comes in at a strength, if it does.
108
+ const productOf = (formIndex: number, strength: string) =>
109
+ drug?.forms[formIndex]?.strengths.find((s) => s.label === strength)?.option ?? null;
110
+ // The forms a strength could be: those that come in it — of the one picked, once it is.
111
+ const formsFor = (strength: string) =>
112
+ drug?.forms.flatMap((_, i) => ((formAt === null || i === formAt) && productOf(i, strength) ? [i] : [])) ?? [];
113
+
114
+ // Busy, or a choice saving: nothing can be picked (a saving choice still looks as picked, not disabled).
115
+ const disabled = (busy && !chosen) || !onChoose;
116
+ const locked = disabled || Boolean(chosen);
117
+ const choose = (option: ChangeOption) => !locked && onChoose?.(option);
118
+ // A drug with one product: its row is the choice.
119
+ const onlyOption = (i: number) => {
120
+ const forms = drugs[i]!.forms;
121
+ return forms.length === 1 && forms[0]!.strengths.length === 1 ? forms[0]!.strengths[0]!.option : null;
122
+ };
123
+ const openDrug = (i: number) => {
124
+ if (chosen) return;
125
+ setPick({ drug: i, form: null, strength: null });
126
+ focusNext.current = "list";
127
+ };
128
+ // The first chip in a group that goes with the other group's pick (`form` / `strength`; null: nothing picked).
129
+ const firstFitting = (group: Chips, form: number | null, strength: string | null) => {
130
+ if (!drug) return 0;
131
+ const at =
132
+ group === "form"
133
+ ? drug.forms.findIndex((_, i) => strength === null || productOf(i, strength))
134
+ : strengthsOf(drug).findIndex((s) => form === null || productOf(form, s));
135
+ return Math.max(0, at);
136
+ };
137
+ const enter = () => {
138
+ if (!drug || chosen) return;
139
+ const only = onlyOption(drugAt);
140
+ if (only) return choose(only);
141
+ const group = drug.forms.length > 1 && pick.form === null ? "form" : "strength";
142
+ chips(group)[firstFitting(group, formAt, pick.strength)]?.focus();
143
+ };
144
+ const pickForm = (i: number) => {
145
+ if (locked) return;
146
+ if (pick.form === i) {
147
+ setPick({ ...pick, form: null }); // picked again: taken back
148
+ focusNext.current = { group: "form", at: i };
149
+ return;
150
+ }
151
+ if (pick.strength !== null && !productOf(i, pick.strength)) {
152
+ // Greyed (not in the strength picked): the strength goes, and it's the prescriber's to pick again.
153
+ setPick({ drug: drugAt, form: i, strength: null });
154
+ focusNext.current = { group: "strength", at: firstFitting("strength", i, null) };
155
+ return;
156
+ }
157
+ const strengths = drug!.forms[i]!.strengths;
158
+ const product =
159
+ pick.strength !== null ? productOf(i, pick.strength) : strengths.length === 1 ? strengths[0]!.option : null;
160
+ setPick({ ...pick, drug: drugAt, form: i });
161
+ if (product) choose(product);
162
+ else focusNext.current = { group: "strength", at: firstFitting("strength", i, null) };
163
+ };
164
+ const pickStrength = (strength: string) => {
165
+ if (locked) return;
166
+ const at = strengthsOf(drug!).indexOf(strength);
167
+ if (pick.strength === strength) {
168
+ setPick({ ...pick, strength: null }); // picked again: taken back
169
+ focusNext.current = { group: "strength", at };
170
+ return;
171
+ }
172
+ if (drug!.forms.length > 1 && pick.form !== null && !productOf(pick.form, strength)) {
173
+ // Greyed (the form picked doesn't come in it): the form goes, and it's the prescriber's to pick again.
174
+ setPick({ drug: drugAt, form: null, strength });
175
+ focusNext.current = { group: "form", at: firstFitting("form", null, strength) };
176
+ return;
177
+ }
178
+ const forms = formsFor(strength);
179
+ setPick({ ...pick, drug: drugAt, strength });
180
+ if (forms.length === 1) choose(productOf(forms[0]!, strength)!);
181
+ else focusNext.current = { group: "form", at: firstFitting("form", null, strength) };
182
+ };
183
+ useEffect(() => {
184
+ if (!handleRef) return;
185
+ handleRef.current = {
186
+ total: all.length,
187
+ enter,
188
+ focus: (fromTyping) => {
189
+ typing.current = Boolean(fromTyping && onBack);
190
+ list()?.focus();
191
+ return true;
192
+ },
193
+ pick: (index) => {
194
+ if (index >= drugs.length) return false;
195
+ openDrug(index);
196
+ return true;
197
+ },
198
+ };
199
+ return () => {
200
+ handleRef.current = null;
201
+ };
202
+ });
203
+ if (!drug) return null;
204
+ const strengths = strengthsOf(drug);
205
+ // The drug's strengths differ by form (the row can't say one): a form with one strength says it on its chip.
206
+ const strengthByForm = strengths.length > 1;
207
+ // F / S: the next chip in that group after the one focused (the first, from anywhere else).
208
+ const nextChip = (group: Chips) => {
209
+ const buttons = chips(group);
210
+ if (!buttons.length) return false;
211
+ buttons[(buttons.indexOf(document.activeElement as HTMLElement) + 1) % buttons.length]!.focus();
212
+ return true;
213
+ };
214
+
215
+ const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
216
+ if (typing.current && typesBack(e)) return onBack?.(); // not taken: the browser types it in Treatment
217
+ typing.current = false;
218
+ if (e.metaKey || e.ctrlKey) return;
219
+ const digit = digitKey(e);
220
+ if (e.altKey && digit < 0) return;
221
+ const key = e.key.toLowerCase();
222
+ const atList = e.target === e.currentTarget;
223
+ if (digit >= 0 && digit < drugs.length) openDrug(digit);
224
+ else if (key === "d") openDrug((drugAt + 1) % drugs.length);
225
+ else if (vertical(e)) openDrug(Math.max(0, Math.min(drugs.length - 1, drugAt + vertical(e))));
226
+ else if (edge(e)) openDrug(edge(e) === "first" ? 0 : drugs.length - 1);
227
+ else if (e.key === "Tab" && atList && !e.altKey) {
228
+ // The next / previous drug — past the last / first, on out of the list (the browser's Tab).
229
+ const to = drugAt + (e.shiftKey ? -1 : 1);
230
+ if (to < 0 || to >= drugs.length) return;
231
+ openDrug(to);
232
+ } else if (e.key === "Escape" && !atList) list()?.focus();
233
+ else if (e.key === "Escape" && onBack) onBack();
234
+ else if (key === "f" || key === "s") {
235
+ if (!nextChip(key === "f" ? "form" : "strength")) return;
236
+ }
237
+ // Enter on the list is on the open drug. On a chip or a row it's that button's own click.
238
+ else if (e.key === "Enter" && atList) enter();
239
+ else return;
240
+ took(e);
241
+ };
242
+
243
+ return (
244
+ <div
245
+ ref={root}
246
+ style={{ paddingBottom: "0.75em" }}
247
+ onFocus={(e) => {
248
+ setOnList(e.target === list());
249
+ setInChips(Boolean((e.target as Element).closest("[data-chips]")));
250
+ }}
251
+ onBlur={(e) => {
252
+ if (root.current?.contains(e.relatedTarget)) return;
253
+ setOnList(false);
254
+ setInChips(false);
255
+ typing.current = false;
256
+ }}
257
+ >
258
+ <Stack gap="3">
259
+ <OptionList
260
+ label="Pick a treatment"
261
+ disabled={disabled}
262
+ activeKey={String(drugAt)}
263
+ activeSelected={onList}
264
+ onKeyDown={onKeyDown}
265
+ options={drugs.map((d, i) => {
266
+ const only = onlyOption(i);
267
+ return {
268
+ key: String(i),
269
+ label: d.name,
270
+ // Open, its chips say its forms and strengths; closed, how many.
271
+ description: describeTreatmentDrug(d, i !== drugAt) ?? undefined,
272
+ // The row chooses the product, so it's named as the product.
273
+ ariaLabel: only?.displayName,
274
+ direct: Boolean(only),
275
+ loading: Boolean(chosen) && i === drugAt,
276
+ };
277
+ })}
278
+ onSelect={(key) => {
279
+ if (locked) return;
280
+ const only = onlyOption(Number(key));
281
+ if (only) choose(only);
282
+ else openDrug(Number(key));
283
+ }}
284
+ >
285
+ {drug.forms.length > 1 && (
286
+ <div data-chips="form" style={{ display: "contents" }}>
287
+ <ToggleGroup
288
+ label="Form"
289
+ disabled={disabled}
290
+ value={formAt === null ? null : String(formAt)}
291
+ onChange={(value) => pickForm(Number(value))}
292
+ options={drug.forms.map((f, i) => {
293
+ const only = f.strengths.length === 1 ? f.strengths[0]! : null;
294
+ // With the strength picked (or its only one), the chip chooses the product: named as the product.
295
+ const product = view.strength !== null ? productOf(i, view.strength) : (only?.option ?? null);
296
+ return {
297
+ value: String(i),
298
+ label: f.label || "As listed",
299
+ detail: (only && strengthByForm && only.label) || undefined,
300
+ ariaLabel: product?.displayName,
301
+ // Not in the strength picked: greyed, still pickable (it drops the strength).
302
+ muted: view.strength !== null && !product,
303
+ };
304
+ })}
305
+ />
306
+ </div>
307
+ )}
308
+ {strengths.length > 1 && (
309
+ <div data-chips="strength" style={{ display: "contents" }}>
310
+ <ToggleGroup
311
+ label="Strength"
312
+ disabled={disabled}
313
+ value={view.strength === null ? null : String(strengths.indexOf(view.strength))}
314
+ onChange={(value) => pickStrength(strengths[Number(value)]!)}
315
+ options={strengths.map((strength, i) => {
316
+ const forms = formsFor(strength);
317
+ // In one form (the one picked, or the only one with it), the chip chooses the product: named as it.
318
+ const product = forms.length === 1 ? productOf(forms[0]!, strength) : null;
319
+ return {
320
+ value: String(i),
321
+ label: strength || "As listed",
322
+ ariaLabel: product?.displayName,
323
+ // The form picked doesn't come in it: greyed, still pickable (it drops the form).
324
+ muted: forms.length === 0,
325
+ };
326
+ })}
327
+ />
328
+ </div>
329
+ )}
330
+ </OptionList>
331
+ {all.length > drugs.length && (
332
+ <div>
333
+ <Button variant="ghost" onClick={() => setShowAll(true)}>
334
+ Show {all.length - drugs.length} more
335
+ </Button>
336
+ </div>
337
+ )}
338
+ </Stack>
339
+ </div>
340
+ );
341
+ }
342
+
343
+ /** Where a product is among the drugs: its drug, its form, its strength — as picks. Null if it isn't there. */
344
+ function locate(drugs: ReturnType<typeof groupTreatmentOptions<ChangeOption>>, option: ChangeOption) {
345
+ for (const [drug, { forms }] of drugs.entries())
346
+ for (const [form, { strengths }] of forms.entries())
347
+ for (const strength of strengths)
348
+ if (strength.option === option) return { drug, form: forms.length > 1 ? form : null, strength: strength.label };
349
+ return null;
350
+ }
@@ -0,0 +1,23 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ const MIN_SPINNER_MS = 600;
4
+
5
+ /**
6
+ * What's working — e.g. the field whose call is in flight, which shows a spinner — held for at least
7
+ * MIN_SPINNER_MS after it's done: calls often return in ~150ms, and a spinner that flickers past reads as
8
+ * nothing happening.
9
+ */
10
+ export function useHeldActivity(activity: string | null): string | null {
11
+ const [held, setHeld] = useState(activity);
12
+ const [last, setLast] = useState(activity);
13
+ if (activity !== last) {
14
+ setLast(activity);
15
+ if (activity) setHeld(activity);
16
+ }
17
+ useEffect(() => {
18
+ if (activity || !held) return;
19
+ const timer = setTimeout(() => setHeld(null), MIN_SPINNER_MS);
20
+ return () => clearTimeout(timer);
21
+ }, [activity, held]);
22
+ return activity ?? held;
23
+ }