@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,377 @@
1
+ /**
2
+ * Every search on the cards works one way — patients, drugs, allergies, medications, diagnoses, and the
3
+ * server's other choices:
4
+ *
5
+ * - Type-ahead (`useTypeAhead`): once a field has the caller's `minChars` (each search says its own: the
6
+ * patient search 2, drugs and clinical entries 3) and typing pauses, it searches; each
7
+ * keystroke cancels the search waiting, and the live object aborts one in flight. Leaving the field (or
8
+ * Enter) sends at once. Patients and drugs search without writing; for allergies, meds and diagnoses a
9
+ * search is an add — a unique match is the entry (see ClinicalList).
10
+ * - Results (`SearchResults`): the first five, then "Show N more". In the list, 1–9 and 0 pick one (of those shown),
11
+ * ↑ ↓ (or K J) move, Home / End (or g / G) go to the first / last, and Esc goes back to the field that searched
12
+ * (← → and h l are the card flow's, / its search box: flow.ts).
13
+ * The one picked reads as selected while its call runs. Pressing one isn't leaving the field: the field
14
+ * doesn't send or open more of the form under the pointer (`pointing`).
15
+ * - A few results (fewer than five) for what's typed, for a patient or a drug: focus goes to the first, ready to
16
+ * pick (`focus(true)`). Typing carries on: until a key acts on the list, one that types (a character,
17
+ * Backspace) goes back to the field and types there (`typesBack`).
18
+ * - From the field (`searchKeys`): Option/Alt + 1–9 / 0 picks one (plain digits stay text: "amoxicillin 500"),
19
+ * ↓ moves into the list, and Tab does when there are only a few results and they answer what's typed.
20
+ * - The field whose call is in flight shows the spinner — nowhere else.
21
+ */
22
+ import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
23
+ import { useLatestCallback } from "../hooks/index.ts";
24
+ import { useComponents } from "../primitives/index.ts";
25
+ import { CHOICE_ACTION, type ChoiceListProps } from "../primitives/types.ts";
26
+
27
+ /** A search waits until typing has paused this long. */
28
+ const PAUSE_MS = 300;
29
+ /** Results shown before "Show N more". */
30
+ export const SHOWN = 5;
31
+ /** Fewer results than this are few enough that focus goes to them (more: keep narrowing). */
32
+ export const FEW = 5;
33
+
34
+ export interface TypeAhead<F extends string> {
35
+ /** `field` changed to `text`: the search waiting is dropped, and (`minChars`+) a new one waits for a pause. */
36
+ typed: (field: F, text: string) => void;
37
+ /** Too little to search on — under `minChars` once trimmed. */
38
+ tooShort: (text: string) => boolean;
39
+ /** Drop the search waiting — e.g. leaving the field sends now instead. */
40
+ cancel: () => void;
41
+ /** A search is waiting for typing to pause. */
42
+ waiting: () => boolean;
43
+ }
44
+
45
+ /** Type-ahead for a card's search fields: `search(field)` runs once `minChars` are typed and typing pauses. */
46
+ export function useTypeAhead<F extends string>(
47
+ search: (field: F) => void,
48
+ { minChars }: { minChars: number },
49
+ ): TypeAhead<F> {
50
+ const latest = useLatestCallback(search);
51
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
52
+ const cancel = () => {
53
+ if (timer.current) clearTimeout(timer.current);
54
+ timer.current = null;
55
+ };
56
+ useEffect(() => cancel, []);
57
+ const tooShort = (text: string) => text.trim().length < minChars;
58
+ return {
59
+ typed: (field, text) => {
60
+ cancel();
61
+ if (tooShort(text)) return;
62
+ timer.current = setTimeout(() => {
63
+ timer.current = null;
64
+ latest(field);
65
+ }, PAUSE_MS);
66
+ },
67
+ tooShort,
68
+ cancel,
69
+ waiting: () => timer.current !== null,
70
+ };
71
+ }
72
+
73
+ // Whether a pointer is pressed anywhere on the page (one listener for every card).
74
+ let pressing = false;
75
+ let pressEnded: (() => void)[] = [];
76
+ if (typeof document !== "undefined") {
77
+ document.addEventListener("pointerdown", () => (pressing = true), true);
78
+ const end = () => {
79
+ pressing = false;
80
+ const queued = pressEnded;
81
+ pressEnded = [];
82
+ setTimeout(() => queued.forEach((run) => run())); // after the press's click
83
+ };
84
+ document.addEventListener("pointerup", end, true);
85
+ document.addEventListener("pointercancel", end, true);
86
+ }
87
+
88
+ /**
89
+ * Run `fn` now — or, if a press took focus from a field, once that press (and its click) is done. Leaving a
90
+ * field can close it or open more of the form; doing that mid-press moves whatever was pressed out from
91
+ * under the pointer, and the click lands somewhere else.
92
+ */
93
+ export function afterPress(fn: () => void) {
94
+ if (pressing) pressEnded.push(fn);
95
+ else fn();
96
+ }
97
+
98
+ /**
99
+ * 1–9 then 0 as a 0-based index (0 is the tenth), or -1. By physical key first: Option + 1 on a Mac reports
100
+ * key "¡". Plain digits also match by key, for keyboards whose number row isn't Digit1…
101
+ */
102
+ export function digitKey(e: { key: string; code: string; altKey: boolean }): number {
103
+ const code = /^(?:Digit|Numpad)([0-9])$/.exec(e.code)?.[1];
104
+ const key = !e.altKey && /^[0-9]$/.test(e.key) ? e.key : undefined;
105
+ const digit = code ?? key;
106
+ return digit ? (Number(digit) + 9) % 10 : -1;
107
+ }
108
+
109
+ /**
110
+ * A key a card acts on stops there: handled, it's not also a host page's shortcut (a host's own `j` or `/`).
111
+ * Keys the cards don't use pass through untouched.
112
+ */
113
+ export function took(e: { preventDefault(): void; stopPropagation(): void }) {
114
+ e.preventDefault();
115
+ e.stopPropagation();
116
+ }
117
+
118
+ /** In a list: Home or g is the first item, End or G the last; null for any other key. */
119
+ export function edge(e: { key: string; altKey: boolean; metaKey: boolean; ctrlKey: boolean }): "first" | "last" | null {
120
+ if (e.altKey || e.metaKey || e.ctrlKey) return null;
121
+ return e.key === "Home" || e.key === "g" ? "first" : e.key === "End" || e.key === "G" ? "last" : null;
122
+ }
123
+
124
+ /**
125
+ * A key that types — a character, Backspace, Delete. In a list focus was put in for the prescriber (a few results
126
+ * came back), it goes back to the field instead: the list sends focus there and lets the key through, so the
127
+ * browser types it in the field.
128
+ */
129
+ export function typesBack(e: { key: string; altKey: boolean; metaKey: boolean; ctrlKey: boolean }): boolean {
130
+ if (e.altKey || e.metaKey || e.ctrlKey) return false;
131
+ return e.key.length === 1 || e.key === "Backspace" || e.key === "Delete";
132
+ }
133
+
134
+ /** In a list: ↓ or J is the next item (1), ↑ or K the previous (-1); 0 for any other key. */
135
+ export function vertical(e: { key: string; altKey: boolean; metaKey: boolean; ctrlKey: boolean }): number {
136
+ if (e.altKey || e.metaKey || e.ctrlKey) return 0;
137
+ return e.key === "ArrowDown" || e.key === "j" ? 1 : e.key === "ArrowUp" || e.key === "k" ? -1 : 0;
138
+ }
139
+
140
+ /** How a search field reaches its results (`SearchResults`, or the drug picker). */
141
+ export interface SearchHandle {
142
+ /** How many results there are, shown or not. */
143
+ total: number;
144
+ /**
145
+ * Put focus on the first result; false if there's none. `typing`: the field put it there (a few results came
146
+ * back) — keys that type go back to it until one acts on the list.
147
+ */
148
+ focus: (typing?: boolean) => boolean;
149
+ /** Pick the result at this index (0-based) — the drug picker opens it; false if there's none shown there. */
150
+ pick: (index: number) => boolean;
151
+ /** A result is being pressed: the field's blur is the press, not the prescriber leaving it. */
152
+ pointing?: () => boolean;
153
+ /**
154
+ * Set when the field keeps the cursor (`inField`). The keys then move a highlight rather than focus, so
155
+ * the prescriber can carry on typing at any point — which is what a search box that takes a name, a date
156
+ * or a phone has to allow. `activeId` is the highlighted option's DOM id, for `aria-activedescendant`.
157
+ */
158
+ inField?: true;
159
+ /** Move the highlight by `step`, wrapping at the ends; false when there is nothing to move. */
160
+ move?: (step: number) => boolean;
161
+ /** Take the highlighted row; false when nothing is highlighted. */
162
+ accept?: () => boolean;
163
+ /** Drop the highlight; false when there was none. */
164
+ clear?: () => boolean;
165
+ activeId?: string | null;
166
+ }
167
+
168
+ /**
169
+ * A search field's keys (its onKeyDown): Option/Alt + 1–9 / 0 picks a result, ↓ moves into them, and Tab does
170
+ * when they're few and `answered` (they're for what's in the field now). True when it took the key.
171
+ *
172
+ * A field that keeps the cursor (`inField`) takes only ↑ ↓, Return and Esc, and never gives up focus — no
173
+ * j / k, no digits, no Tab into the list: every one of those is a character someone may be typing, and a
174
+ * field that takes a name, a date or a phone can't quietly swallow them.
175
+ */
176
+ export function searchKeys(e: KeyboardEvent, results: SearchHandle | null | undefined, answered: boolean): boolean {
177
+ if (!results?.total) return false;
178
+ if (results.inField) {
179
+ if (e.altKey || e.metaKey || e.ctrlKey) return false;
180
+ const step = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
181
+ const took_ =
182
+ step !== 0
183
+ ? results.move?.(step)
184
+ : e.key === "Enter"
185
+ ? results.accept?.()
186
+ : e.key === "Escape"
187
+ ? results.clear?.()
188
+ : false;
189
+ if (took_) took(e);
190
+ return Boolean(took_);
191
+ }
192
+ const digit = e.altKey ? digitKey(e) : -1;
193
+ const handled =
194
+ digit >= 0
195
+ ? results.pick(digit)
196
+ : e.key === "ArrowDown"
197
+ ? results.focus()
198
+ : e.key === "Tab" && !e.shiftKey && answered && results.total < FEW && results.focus();
199
+ if (handled) took(e);
200
+ return handled;
201
+ }
202
+
203
+ /**
204
+ * A search's results: the first five, then "Show N more". In the list, 1–9 / 0 picks one and ↑ ↓ (or K J) move. `busy`: the
205
+ * object is working — the result picked reads as selected until it's done, and another pick waits for it.
206
+ */
207
+ export function SearchResults({
208
+ label,
209
+ results,
210
+ onPick,
211
+ busy,
212
+ disabled,
213
+ handleRef,
214
+ onBack,
215
+ action,
216
+ inField,
217
+ onActive,
218
+ }: {
219
+ label: string;
220
+ results: ChoiceListProps["choices"];
221
+ onPick: (key: string) => void;
222
+ busy?: boolean;
223
+ disabled?: boolean;
224
+ handleRef?: { current: SearchHandle | null };
225
+ /** Esc in the list: back to the field that searched. */
226
+ onBack?: () => void;
227
+ /**
228
+ * The way out of the list, after the results — the patient card's "Add new patient". It renders as the
229
+ * last row, so ↓ carries on into it from the last result and ↑ comes back.
230
+ */
231
+ action?: ChoiceListProps["action"];
232
+ /**
233
+ * The field below keeps the cursor: the rows become options it highlights, so typing, Backspace and
234
+ * Delete always reach the field — the prescriber can narrow or start over without first coming back.
235
+ */
236
+ inField?: boolean;
237
+ /** With `inField`: the highlighted option's DOM id, for the field's `aria-activedescendant`. */
238
+ onActive?: (id: string | null) => void;
239
+ }) {
240
+ const { Button, ChoiceList, Stack } = useComponents();
241
+ const listId = useId();
242
+ const [showAll, setShowAll] = useState(false);
243
+ /** Where the keys are, when the field keeps the cursor. Null until ↓ or an answer puts it somewhere. */
244
+ const [active, setActive] = useState<string | null>(null);
245
+ useEffect(() => {
246
+ onActive?.(active ? `${listId}-${active}` : null);
247
+ }, [active, listId, onActive]);
248
+ const shown = showAll ? results : results.slice(0, SHOWN);
249
+ const list = useRef<HTMLDivElement>(null);
250
+ const pointing = useRef(false);
251
+ // Focus was put here for the prescriber, mid-typing: keys that type go back to the field (typesBack).
252
+ const typing = useRef(false);
253
+ const buttons = () => [...(list.current?.querySelectorAll<HTMLElement>("button:not(:disabled)") ?? [])];
254
+ // The pick, while its call runs (it starts at once: the object goes busy as it's picked).
255
+ const [picked, setPicked] = useState<{ key: string; started: boolean } | null>(null);
256
+ if (picked && busy && !picked.started) setPicked({ ...picked, started: true });
257
+ if (picked?.started && !busy) setPicked(null);
258
+ const pickKey = (key: string) => {
259
+ if (disabled || (picked && busy)) return;
260
+ setPicked({ key, started: false });
261
+ onPick(key);
262
+ };
263
+ const pick = (index: number) => {
264
+ const result = !disabled ? shown[index] : undefined;
265
+ if (result) pickKey(result.key);
266
+ return Boolean(result);
267
+ };
268
+ /** Every row the keys run through, in order: the results shown, then the way out. */
269
+ const keys = [...shown.map((r) => r.key), ...(action ? [CHOICE_ACTION] : [])];
270
+ const take = (key: string | null) => {
271
+ if (!key) return false;
272
+ if (key === CHOICE_ACTION) action?.onChoose();
273
+ else pickKey(key);
274
+ return true;
275
+ };
276
+ useEffect(() => {
277
+ if (!handleRef) return;
278
+ handleRef.current = {
279
+ // The action counts: with nobody matching it's the only row, and ↓ from the field must still reach it.
280
+ total: results.length + (action ? 1 : 0),
281
+ focus: (fromTyping) => {
282
+ if (inField) {
283
+ // The cursor stays where it is; the first row is simply where the keys now are.
284
+ setActive(keys[0] ?? null);
285
+ return keys.length > 0;
286
+ }
287
+ const first = buttons()[0];
288
+ typing.current = Boolean(fromTyping && first && onBack);
289
+ first?.focus();
290
+ return Boolean(first);
291
+ },
292
+ pick,
293
+ pointing: () => pointing.current,
294
+ ...(inField
295
+ ? {
296
+ inField: true as const,
297
+ // The ends are ends: leaning on ↓ parks on the last row and stops, rather than looping round
298
+ // to the top where Return would take someone else entirely. ↓ is the way in.
299
+ move: (step: number) => {
300
+ if (!keys.length) return false;
301
+ const at = active ? keys.indexOf(active) : -1;
302
+ if (at < 0) {
303
+ if (step < 0) return false;
304
+ setActive(keys[0]!);
305
+ return true;
306
+ }
307
+ const next = Math.max(0, Math.min(keys.length - 1, at + step));
308
+ if (next === at) return true; // at the end: taken, so the page doesn't scroll instead
309
+ setActive(keys[next]!);
310
+ return true;
311
+ },
312
+ accept: () => (disabled ? false : take(active)),
313
+ clear: () => {
314
+ if (active === null) return false;
315
+ setActive(null);
316
+ return true;
317
+ },
318
+ activeId: active ? `${listId}-${active}` : null,
319
+ }
320
+ : {}),
321
+ };
322
+ return () => {
323
+ handleRef.current = null;
324
+ };
325
+ });
326
+
327
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
328
+ if (typing.current && typesBack(e)) return onBack?.(); // not taken: the browser types it in the field
329
+ typing.current = false;
330
+ if (e.metaKey || e.ctrlKey) return;
331
+ const digit = digitKey(e);
332
+ const all = buttons();
333
+ const at = all.indexOf(e.target as HTMLElement);
334
+ if (digit >= 0) {
335
+ if (!pick(digit)) return;
336
+ } else if (vertical(e) && at >= 0) {
337
+ all[Math.max(0, Math.min(all.length - 1, at + vertical(e)))]?.focus();
338
+ } else if (edge(e) && at >= 0) {
339
+ all[edge(e) === "first" ? 0 : all.length - 1]?.focus();
340
+ } else if (e.key === "Escape" && onBack) {
341
+ onBack();
342
+ } else return;
343
+ took(e);
344
+ };
345
+
346
+ return (
347
+ <Stack gap="1">
348
+ <div
349
+ ref={list}
350
+ onKeyDown={onKeyDown}
351
+ onBlur={(e) => !list.current?.contains(e.relatedTarget) && (typing.current = false)}
352
+ onPointerDown={() => {
353
+ // Until the press ends: the field it leaves mustn't send, or open rows that move the list under it.
354
+ pointing.current = true;
355
+ window.addEventListener("pointerup", () => setTimeout(() => (pointing.current = false)), { once: true });
356
+ }}
357
+ >
358
+ <ChoiceList
359
+ label={label}
360
+ choices={shown}
361
+ onChoose={pickKey}
362
+ disabled={disabled}
363
+ pendingKey={picked && busy ? picked.key : null}
364
+ action={action}
365
+ {...(inField ? { activeKey: keys.includes(active ?? "") ? active : null, id: listId } : {})}
366
+ />
367
+ </div>
368
+ {results.length > shown.length && (
369
+ <div>
370
+ <Button variant="ghost" onClick={() => setShowAll(true)}>
371
+ Show {results.length - shown.length} more
372
+ </Button>
373
+ </div>
374
+ )}
375
+ </Stack>
376
+ );
377
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./useLatestCallback.ts";
2
+ export * from "./useLive.ts";
3
+ export * from "./useOnChange.ts";
4
+ export * from "./useSession.ts";
@@ -0,0 +1,16 @@
1
+ import { useCallback, useLayoutEffect, useRef } from "react";
2
+
3
+ /**
4
+ * A stable function that always calls the latest `fn` — for handing host callbacks
5
+ * (onChange, …) to core objects created once. The ref is updated after
6
+ * render, never during it (react-hooks/refs).
7
+ */
8
+ export function useLatestCallback<A extends unknown[], R>(
9
+ fn: ((...args: A) => R) | undefined,
10
+ ): (...args: A) => R | undefined {
11
+ const ref = useRef(fn);
12
+ useLayoutEffect(() => {
13
+ ref.current = fn;
14
+ });
15
+ return useCallback((...args: A) => ref.current?.(...args), []);
16
+ }
@@ -0,0 +1,21 @@
1
+ import type { AnySnapshot, LiveObject } from "@photonhealth/client";
2
+ import { useSyncExternalStore } from "react";
3
+
4
+ interface Live<S> {
5
+ subscribe(listener: () => void): () => void;
6
+ readonly snapshot: S;
7
+ }
8
+
9
+ const noSubscribe = () => () => {};
10
+
11
+ /**
12
+ * Bind a live object from @photonhealth/client (a Patient, Prescription or Order): re-renders when anything
13
+ * changes it — this component, another card, an order's response. Returns its snapshot
14
+ * `{ state, status, error }`, or null without an object.
15
+ */
16
+ export function useLive<S>(obj: Live<S> | null | undefined): S | null;
17
+ /** Any of the three (e.g. an inspector over every object): the snapshot, typed as any of theirs. */
18
+ export function useLive(obj: LiveObject | null | undefined): AnySnapshot | null;
19
+ export function useLive(obj: Live<unknown> | null | undefined): unknown {
20
+ return useSyncExternalStore(obj ? obj.subscribe : noSubscribe, () => obj?.snapshot ?? null);
21
+ }
@@ -0,0 +1,34 @@
1
+ import { useEffect, useState } from "react";
2
+ import { useLatestCallback } from "./useLatestCallback.ts";
3
+
4
+ interface Live {
5
+ subscribe(listener: () => void): () => void;
6
+ }
7
+
8
+ /**
9
+ * A card's record event: call `fire(obj)` with its live object once it has a record (`select` returns
10
+ * something), then each time that record changes from the backend — compared by value, so a save that
11
+ * brings back the same record, or a saving / idle flip, doesn't count.
12
+ */
13
+ export function useOnChange<T extends Live>(
14
+ obj: T | null | undefined,
15
+ select: (obj: T) => unknown,
16
+ fire: ((obj: T) => void) | undefined,
17
+ ) {
18
+ const call = useLatestCallback(fire);
19
+ const pick = useLatestCallback(select);
20
+ // What was last reported for each object — so an effect that runs again (React's StrictMode mounts
21
+ // twice in development) doesn't report the same record twice.
22
+ const [reported] = useState(() => new WeakMap<T, string>());
23
+ useEffect(() => {
24
+ if (!obj) return;
25
+ const report = () => {
26
+ const key = JSON.stringify(pick(obj) ?? null);
27
+ if (key === (reported.get(obj) ?? "null")) return;
28
+ reported.set(obj, key);
29
+ call(obj);
30
+ };
31
+ report();
32
+ return obj.subscribe(report);
33
+ }, [obj, call, pick, reported]);
34
+ }
@@ -0,0 +1,11 @@
1
+ import type { SessionSnapshot } from "@photonhealth/client";
2
+ import { usePhoton } from "../primitives/index.ts";
3
+ import { useLive } from "./useLive.ts";
4
+
5
+ /**
6
+ * The prescriber's sign-in, for the host's own chrome (their name, their organization) — when the provider signs
7
+ * in (`clientId`). Null when the host signs in itself. Signing in is `usePhoton().session.signIn()`.
8
+ */
9
+ export function useSession(): SessionSnapshot | null {
10
+ return useLive(usePhoton().session);
11
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @photonhealth/react — Photon Rx for React. No design-system dependency:
3
+ * the cards render through a small set of building blocks that default to
4
+ * unstyled, page-inheriting HTML, and can be mapped to any design system.
5
+ *
6
+ * <PhotonProvider clientId="…" components={myComponents?}> — signs the prescriber in, then the cards call
7
+ * <PhotonProvider client={photon({ environment, auth })}> — or a client of the host's own
8
+ *
9
+ * primitives/ PhotonComponents (the building-block interface), defaultComponents, PhotonProvider
10
+ * hooks/ useLive (bind a live object)
11
+ * components/ PhotonOrder, PhotonPatient, PhotonPrescription — bound to @photonhealth/client's live objects (ids or objects in,
12
+ * events out)
13
+ *
14
+ * Optional: import "@photonhealth/react/styles.css" for structural styles that inherit the page.
15
+ */
16
+ export * from "./primitives/index.ts";
17
+ export { useLive, useSession } from "./hooks/index.ts";
18
+ export { PhotonOrder, PhotonPatient, PhotonPrescription } from "./components/index.ts";
19
+ export type { PhotonOrderProps, PhotonPatientProps, PhotonPrescriptionProps } from "./components/index.ts";
@@ -0,0 +1,153 @@
1
+ import { photon, type Photon, type PhotonEnvironment, type PhotonError } from "@photonhealth/client";
2
+ import { createContext, useContext, useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from "react";
3
+ import { useLatestCallback } from "../hooks/useLatestCallback.ts";
4
+ import { defaultComponents } from "./defaults.tsx";
5
+ import type { PhotonComponents } from "./types.ts";
6
+
7
+ const ComponentsContext = createContext<PhotonComponents>(defaultComponents);
8
+ const PhotonContext = createContext<Photon | null>(null);
9
+
10
+ /** What `onAuth` reports: network-api took the instance's token, or why not. */
11
+ export type PhotonAuthCheck = { ok: true; error: null } | { ok: false; error: PhotonError };
12
+
13
+ /**
14
+ * One ping per instance and sign-in, however many providers or renders ask (StrictMode runs effects twice). A new
15
+ * sign-in (`who`) is checked again, and so is one whose check failed when it's tried again (`attempt`).
16
+ */
17
+ const checks = new WeakMap<Photon, { who: unknown; attempt: number; check: Promise<PhotonAuthCheck> }>();
18
+ const checkAuth = (ph: Photon, who: unknown, attempt: number) => {
19
+ let known = checks.get(ph);
20
+ if (!known || known.who !== who || known.attempt !== attempt) {
21
+ const check = ph.ping().then(
22
+ (): PhotonAuthCheck => ({ ok: true, error: null }),
23
+ (error: PhotonError): PhotonAuthCheck => ({ ok: false, error }),
24
+ );
25
+ checks.set(ph, (known = { who, attempt, check }));
26
+ }
27
+ return known.check;
28
+ };
29
+
30
+ /**
31
+ * Why the sign-in's check failed — network-api refused the token (`unauthorized`), or couldn't be reached or answer —
32
+ * for the cards to say so; `retry` checks again (`checking` until it's answered).
33
+ */
34
+ interface CheckFailure {
35
+ error: PhotonError;
36
+ checking: boolean;
37
+ retry: () => void;
38
+ }
39
+ const CheckFailureContext = createContext<CheckFailure | null>(null);
40
+ /** The organization the cards are for, when the host names one. */
41
+ const OrganizationContext = createContext<string | null>(null);
42
+
43
+ /**
44
+ * One provider for Photon Rx components — and their sign-in: everything inside it can make web calls.
45
+ * clientId sign the prescriber in here (core's session: Auth0, PKCE, renewed tokens). Opportunistic: a
46
+ * sign-in coming back from Auth0 is finished and a stored one renewed, on load; otherwise the
47
+ * first card in the page offers "Sign in" (a click; never an unasked redirect).
48
+ * environment with `clientId`: which Photon environment — production (`photon`) unless said.
49
+ * organization sign in straight to this Photon organization (no picker); signed in to another, the first card
50
+ * offers to sign in to this one.
51
+ * client or a Photon client of the host's own (`photon({ environment, auth })` — e.g. `{ getToken }`
52
+ * when the host signs in itself).
53
+ * components optional — map any building blocks to your design system; the rest are unstyled defaults.
54
+ * onAuth optional — once signed in, whether network-api takes the token (one ping per instance).
55
+ *
56
+ * At any level of the page: a provider without a client inherits its parent's, and providers with the same
57
+ * `clientId` share one sign-in.
58
+ */
59
+ export function PhotonProvider({
60
+ client,
61
+ clientId,
62
+ environment = "photon",
63
+ organization,
64
+ components,
65
+ onAuth,
66
+ children,
67
+ }: {
68
+ /** A Photon client of the host's own. Optional: a nested provider inherits its parent's. */
69
+ client?: Photon;
70
+ /** Sign the prescriber in with this Auth0 client (public, not a secret). */
71
+ clientId?: string;
72
+ /** With `clientId`: the Photon environment. Production unless said. */
73
+ environment?: PhotonEnvironment;
74
+ /** Sign in straight to this organization (`org_…`), skipping Auth0's picker. Optional: inherited. */
75
+ organization?: string;
76
+ components?: Partial<PhotonComponents>;
77
+ onAuth?: (auth: PhotonAuthCheck) => void;
78
+ children: ReactNode;
79
+ }) {
80
+ const outerComponents = useContext(ComponentsContext);
81
+ const outerPhoton = useContext(PhotonContext);
82
+ const outerFailure = useContext(CheckFailureContext);
83
+ const outerOrganization = useContext(OrganizationContext);
84
+ const blocks = useMemo(
85
+ () => (components ? { ...outerComponents, ...components } : outerComponents),
86
+ [outerComponents, components],
87
+ );
88
+ // Its links (`usePhoton().frame(…)`) carry the client id and the organization, so an embed signs straight in.
89
+ const made = useMemo(
90
+ () => (!client && clientId ? photon({ environment, auth: { clientId }, organization }) : null),
91
+ [client, clientId, environment, organization],
92
+ );
93
+ const own = client ?? made;
94
+
95
+ // Sign-in, opportunistically: once per page however many providers share it.
96
+ const session = own?.session ?? null;
97
+ useEffect(() => void session?.start(), [session]);
98
+ const signedIn = useSyncExternalStore(session?.subscribe ?? noSubscribe, () =>
99
+ session ? (session.status === "signed-in" ? session.user : null) : true,
100
+ );
101
+
102
+ // Once signed in: does network-api take the token? Refused or unreachable, the cards say so (and offer to sign in
103
+ // again, or to try again).
104
+ const [failed, setFailed] = useState<PhotonError | null>(null);
105
+ const [attempt, setAttempt] = useState(0);
106
+ const [checked, setChecked] = useState(0);
107
+ const report = useLatestCallback(onAuth);
108
+ const listening = Boolean(onAuth) || Boolean(session);
109
+ useEffect(() => {
110
+ if (!own || !listening || !signedIn) return;
111
+ let live = true;
112
+ void checkAuth(own, signedIn, attempt).then((auth) => {
113
+ if (!live) return;
114
+ setFailed(auth.error);
115
+ setChecked(attempt);
116
+ report(auth);
117
+ });
118
+ return () => {
119
+ live = false;
120
+ };
121
+ }, [own, listening, signedIn, attempt, report]);
122
+ const failure = useMemo(
123
+ () => (failed ? { error: failed, checking: checked !== attempt, retry: () => setAttempt((n) => n + 1) } : null),
124
+ [failed, checked, attempt],
125
+ );
126
+
127
+ return (
128
+ <PhotonContext.Provider value={own ?? outerPhoton}>
129
+ <CheckFailureContext.Provider value={own ? failure : outerFailure}>
130
+ <OrganizationContext.Provider value={organization ?? outerOrganization}>
131
+ <ComponentsContext.Provider value={blocks}>{children}</ComponentsContext.Provider>
132
+ </OrganizationContext.Provider>
133
+ </CheckFailureContext.Provider>
134
+ </PhotonContext.Provider>
135
+ );
136
+ }
137
+
138
+ const noSubscribe = () => () => {};
139
+
140
+ export const useComponents = () => useContext(ComponentsContext);
141
+
142
+ /** The photon instance PhotonProvider was given (or made) — for a host's own calls next to the cards. */
143
+ export function usePhoton(): Photon {
144
+ const ph = useContext(PhotonContext);
145
+ if (!ph) throw new Error("Wrap Photon Rx components in <PhotonProvider clientId={…}> (or client={…}).");
146
+ return ph;
147
+ }
148
+
149
+ /** Why the sign-in's check failed, if it did (refused, or Photon unreachable) — for the cards. */
150
+ export const useCheckFailure = () => useContext(CheckFailureContext);
151
+
152
+ /** The organization the provider names, if it does — for the cards (signing in, and checking the sign-in's). */
153
+ export const useOrganization = () => useContext(OrganizationContext);