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

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 (277) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +111 -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 +126 -0
  10. package/dist/adapters/tailwind.js.map +1 -0
  11. package/dist/analytics/PhotonAnalyticsProvider.d.ts +16 -0
  12. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
  13. package/dist/analytics/PhotonAnalyticsProvider.js +57 -0
  14. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
  15. package/dist/analytics/fieldInteraction.d.ts +18 -0
  16. package/dist/analytics/fieldInteraction.d.ts.map +1 -0
  17. package/dist/analytics/fieldInteraction.js +102 -0
  18. package/dist/analytics/fieldInteraction.js.map +1 -0
  19. package/dist/analytics/tracker.d.ts +17 -0
  20. package/dist/analytics/tracker.d.ts.map +1 -0
  21. package/dist/analytics/tracker.js +36 -0
  22. package/dist/analytics/tracker.js.map +1 -0
  23. package/dist/analytics/viewed.d.ts +11 -0
  24. package/dist/analytics/viewed.d.ts.map +1 -0
  25. package/dist/analytics/viewed.js +16 -0
  26. package/dist/analytics/viewed.js.map +1 -0
  27. package/dist/components/ChangeList.d.ts +21 -0
  28. package/dist/components/ChangeList.d.ts.map +1 -0
  29. package/dist/components/ChangeList.js +40 -0
  30. package/dist/components/ChangeList.js.map +1 -0
  31. package/dist/components/PhotonOrder.d.ts +46 -0
  32. package/dist/components/PhotonOrder.d.ts.map +1 -0
  33. package/dist/components/PhotonOrder.js +274 -0
  34. package/dist/components/PhotonOrder.js.map +1 -0
  35. package/dist/components/PhotonPatient.d.ts +48 -0
  36. package/dist/components/PhotonPatient.d.ts.map +1 -0
  37. package/dist/components/PhotonPatient.js +85 -0
  38. package/dist/components/PhotonPatient.js.map +1 -0
  39. package/dist/components/PhotonPrescription.d.ts +32 -0
  40. package/dist/components/PhotonPrescription.d.ts.map +1 -0
  41. package/dist/components/PhotonPrescription.js +11 -0
  42. package/dist/components/PhotonPrescription.js.map +1 -0
  43. package/dist/components/ScreeningAlerts.d.ts +6 -0
  44. package/dist/components/ScreeningAlerts.d.ts.map +1 -0
  45. package/dist/components/ScreeningAlerts.js +11 -0
  46. package/dist/components/ScreeningAlerts.js.map +1 -0
  47. package/dist/components/SignedIn.d.ts +12 -0
  48. package/dist/components/SignedIn.d.ts.map +1 -0
  49. package/dist/components/SignedIn.js +84 -0
  50. package/dist/components/SignedIn.js.map +1 -0
  51. package/dist/components/activity.d.ts +7 -0
  52. package/dist/components/activity.d.ts.map +1 -0
  53. package/dist/components/activity.js +24 -0
  54. package/dist/components/activity.js.map +1 -0
  55. package/dist/components/display.d.ts +90 -0
  56. package/dist/components/display.d.ts.map +1 -0
  57. package/dist/components/display.js +223 -0
  58. package/dist/components/display.js.map +1 -0
  59. package/dist/components/flow.d.ts +35 -0
  60. package/dist/components/flow.d.ts.map +1 -0
  61. package/dist/components/flow.js +53 -0
  62. package/dist/components/flow.js.map +1 -0
  63. package/dist/components/format.d.ts +26 -0
  64. package/dist/components/format.d.ts.map +1 -0
  65. package/dist/components/format.js +61 -0
  66. package/dist/components/format.js.map +1 -0
  67. package/dist/components/index.d.ts +6 -0
  68. package/dist/components/index.d.ts.map +1 -0
  69. package/dist/components/index.js +6 -0
  70. package/dist/components/index.js.map +1 -0
  71. package/dist/components/open.d.ts +47 -0
  72. package/dist/components/open.d.ts.map +1 -0
  73. package/dist/components/open.js +73 -0
  74. package/dist/components/open.js.map +1 -0
  75. package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
  76. package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
  77. package/dist/components/order/DraftOrderPrompt.js +26 -0
  78. package/dist/components/order/DraftOrderPrompt.js.map +1 -0
  79. package/dist/components/patient/Benefits.d.ts +25 -0
  80. package/dist/components/patient/Benefits.d.ts.map +1 -0
  81. package/dist/components/patient/Benefits.js +48 -0
  82. package/dist/components/patient/Benefits.js.map +1 -0
  83. package/dist/components/patient/Clinical.d.ts +56 -0
  84. package/dist/components/patient/Clinical.d.ts.map +1 -0
  85. package/dist/components/patient/Clinical.js +118 -0
  86. package/dist/components/patient/Clinical.js.map +1 -0
  87. package/dist/components/patient/IntakeForm.d.ts +10 -0
  88. package/dist/components/patient/IntakeForm.d.ts.map +1 -0
  89. package/dist/components/patient/IntakeForm.js +333 -0
  90. package/dist/components/patient/IntakeForm.js.map +1 -0
  91. package/dist/components/patient/Summary.d.ts +48 -0
  92. package/dist/components/patient/Summary.d.ts.map +1 -0
  93. package/dist/components/patient/Summary.js +90 -0
  94. package/dist/components/patient/Summary.js.map +1 -0
  95. package/dist/components/patient/fields.d.ts +42 -0
  96. package/dist/components/patient/fields.d.ts.map +1 -0
  97. package/dist/components/patient/fields.js +72 -0
  98. package/dist/components/patient/fields.js.map +1 -0
  99. package/dist/components/patient/query.d.ts +37 -0
  100. package/dist/components/patient/query.d.ts.map +1 -0
  101. package/dist/components/patient/query.js +70 -0
  102. package/dist/components/patient/query.js.map +1 -0
  103. package/dist/components/prescription/PrescriptionCard.d.ts +45 -0
  104. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
  105. package/dist/components/prescription/PrescriptionCard.js +179 -0
  106. package/dist/components/prescription/PrescriptionCard.js.map +1 -0
  107. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
  108. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
  109. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
  110. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
  111. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
  112. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
  113. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
  114. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
  115. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
  116. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
  117. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
  118. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
  119. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
  120. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
  121. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
  122. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
  123. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
  124. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
  125. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
  126. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
  127. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
  128. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
  129. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js +287 -0
  130. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
  131. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
  132. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
  133. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
  134. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
  135. package/dist/components/schemaErrors.d.ts +12 -0
  136. package/dist/components/schemaErrors.d.ts.map +1 -0
  137. package/dist/components/schemaErrors.js +24 -0
  138. package/dist/components/schemaErrors.js.map +1 -0
  139. package/dist/components/search.d.ts +154 -0
  140. package/dist/components/search.d.ts.map +1 -0
  141. package/dist/components/search.js +295 -0
  142. package/dist/components/search.js.map +1 -0
  143. package/dist/hooks/index.d.ts +5 -0
  144. package/dist/hooks/index.d.ts.map +1 -0
  145. package/dist/hooks/index.js +5 -0
  146. package/dist/hooks/index.js.map +1 -0
  147. package/dist/hooks/useLatestCallback.d.ts +7 -0
  148. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  149. package/dist/hooks/useLatestCallback.js +14 -0
  150. package/dist/hooks/useLatestCallback.js.map +1 -0
  151. package/dist/hooks/useLive.d.ts +15 -0
  152. package/dist/hooks/useLive.d.ts.map +1 -0
  153. package/dist/hooks/useLive.js +6 -0
  154. package/dist/hooks/useLive.js.map +1 -0
  155. package/dist/hooks/useOnChange.d.ts +11 -0
  156. package/dist/hooks/useOnChange.d.ts.map +1 -0
  157. package/dist/hooks/useOnChange.js +28 -0
  158. package/dist/hooks/useOnChange.js.map +1 -0
  159. package/dist/hooks/useSession.d.ts +7 -0
  160. package/dist/hooks/useSession.d.ts.map +1 -0
  161. package/dist/hooks/useSession.js +10 -0
  162. package/dist/hooks/useSession.js.map +1 -0
  163. package/dist/index.d.ts +22 -0
  164. package/dist/index.d.ts.map +1 -0
  165. package/dist/index.js +20 -0
  166. package/dist/index.js.map +1 -0
  167. package/dist/meta/version.d.ts +5 -0
  168. package/dist/meta/version.d.ts.map +1 -0
  169. package/dist/meta/version.js +5 -0
  170. package/dist/meta/version.js.map +1 -0
  171. package/dist/primitives/PhotonProvider.d.ts +60 -0
  172. package/dist/primitives/PhotonProvider.d.ts.map +1 -0
  173. package/dist/primitives/PhotonProvider.js +103 -0
  174. package/dist/primitives/PhotonProvider.js.map +1 -0
  175. package/dist/primitives/defaults.d.ts +3 -0
  176. package/dist/primitives/defaults.d.ts.map +1 -0
  177. package/dist/primitives/defaults.js +70 -0
  178. package/dist/primitives/defaults.js.map +1 -0
  179. package/dist/primitives/icons.d.ts +6 -0
  180. package/dist/primitives/icons.d.ts.map +1 -0
  181. package/dist/primitives/icons.js +6 -0
  182. package/dist/primitives/icons.js.map +1 -0
  183. package/dist/primitives/index.d.ts +5 -0
  184. package/dist/primitives/index.d.ts.map +1 -0
  185. package/dist/primitives/index.js +5 -0
  186. package/dist/primitives/index.js.map +1 -0
  187. package/dist/primitives/photonContext.d.ts +3 -0
  188. package/dist/primitives/photonContext.d.ts.map +1 -0
  189. package/dist/primitives/photonContext.js +3 -0
  190. package/dist/primitives/photonContext.js.map +1 -0
  191. package/dist/primitives/select.d.ts +7 -0
  192. package/dist/primitives/select.d.ts.map +1 -0
  193. package/dist/primitives/select.js +16 -0
  194. package/dist/primitives/select.js.map +1 -0
  195. package/dist/primitives/types.d.ts +288 -0
  196. package/dist/primitives/types.d.ts.map +1 -0
  197. package/dist/primitives/types.js +3 -0
  198. package/dist/primitives/types.js.map +1 -0
  199. package/dist/primitives/useProvidedPhoton.d.ts +8 -0
  200. package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
  201. package/dist/primitives/useProvidedPhoton.js +8 -0
  202. package/dist/primitives/useProvidedPhoton.js.map +1 -0
  203. package/dist/styles.css +653 -0
  204. package/dist/test-utils/contract.d.ts +17 -0
  205. package/dist/test-utils/contract.d.ts.map +1 -0
  206. package/dist/test-utils/contract.js +282 -0
  207. package/dist/test-utils/contract.js.map +1 -0
  208. package/package.json +76 -4
  209. package/src/adapters/index.ts +1 -0
  210. package/src/adapters/tailwind.tsx +572 -0
  211. package/src/analytics/PhotonAnalyticsProvider.test.tsx +191 -0
  212. package/src/analytics/PhotonAnalyticsProvider.tsx +96 -0
  213. package/src/analytics/fieldInteraction.test.tsx +184 -0
  214. package/src/analytics/fieldInteraction.tsx +148 -0
  215. package/src/analytics/tracker.test.ts +52 -0
  216. package/src/analytics/tracker.ts +42 -0
  217. package/src/analytics/viewed.ts +27 -0
  218. package/src/components/ChangeList.tsx +85 -0
  219. package/src/components/PhotonOrder.test.tsx +256 -0
  220. package/src/components/PhotonOrder.tsx +508 -0
  221. package/src/components/PhotonPatient.tsx +188 -0
  222. package/src/components/PhotonPrescription.test.tsx +116 -0
  223. package/src/components/PhotonPrescription.tsx +45 -0
  224. package/src/components/ScreeningAlerts.tsx +28 -0
  225. package/src/components/SignedIn.tsx +144 -0
  226. package/src/components/activity.ts +23 -0
  227. package/src/components/display.ts +278 -0
  228. package/src/components/flow.ts +67 -0
  229. package/src/components/format.ts +73 -0
  230. package/src/components/index.ts +5 -0
  231. package/src/components/open.ts +100 -0
  232. package/src/components/order/DraftOrderPrompt.test.tsx +80 -0
  233. package/src/components/order/DraftOrderPrompt.tsx +81 -0
  234. package/src/components/patient/Benefits.tsx +133 -0
  235. package/src/components/patient/Clinical.tsx +215 -0
  236. package/src/components/patient/IntakeForm.test.tsx +89 -0
  237. package/src/components/patient/IntakeForm.tsx +564 -0
  238. package/src/components/patient/Summary.test.tsx +106 -0
  239. package/src/components/patient/Summary.tsx +330 -0
  240. package/src/components/patient/fields.tsx +158 -0
  241. package/src/components/patient/query.ts +83 -0
  242. package/src/components/prescription/PrescriptionCard.test.tsx +85 -0
  243. package/src/components/prescription/PrescriptionCard.tsx +347 -0
  244. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +85 -0
  245. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
  246. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +209 -0
  247. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
  248. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +456 -0
  249. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
  250. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
  251. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
  252. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +75 -0
  253. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
  254. package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
  255. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +699 -0
  256. package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
  257. package/src/components/schemaErrors.test.ts +49 -0
  258. package/src/components/schemaErrors.ts +33 -0
  259. package/src/components/search.tsx +377 -0
  260. package/src/hooks/index.ts +4 -0
  261. package/src/hooks/useLatestCallback.ts +16 -0
  262. package/src/hooks/useLive.ts +21 -0
  263. package/src/hooks/useOnChange.ts +34 -0
  264. package/src/hooks/useSession.ts +11 -0
  265. package/src/index.ts +21 -0
  266. package/src/meta/version.test.ts +10 -0
  267. package/src/meta/version.ts +4 -0
  268. package/src/primitives/PhotonProvider.tsx +168 -0
  269. package/src/primitives/defaults.tsx +432 -0
  270. package/src/primitives/icons.tsx +37 -0
  271. package/src/primitives/index.ts +4 -0
  272. package/src/primitives/photonContext.ts +4 -0
  273. package/src/primitives/select.ts +15 -0
  274. package/src/primitives/types.ts +288 -0
  275. package/src/primitives/useProvidedPhoton.ts +21 -0
  276. package/src/styles.css +653 -0
  277. package/src/test-utils/contract.tsx +453 -0
@@ -0,0 +1,238 @@
1
+ import type { Prescription, PrescriptionEdits, PrescriptionRecord, PrescriptionTemplate } from "@photonhealth/client";
2
+ import { useLatestCallback } from "../../../hooks/index.ts";
3
+ import { useComponents } from "../../../primitives/index.ts";
4
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
5
+ import { schemaErrors } from "../../schemaErrors.ts";
6
+ import { DirectionsInput } from "./DirectionsInput.tsx";
7
+ import { DispenseInputs, type DispenseField, type DispensePatch } from "./DispenseInputs.tsx";
8
+ import { PrescriptionDetailsSchema } from "./PrescriptionDetailsSchema.ts";
9
+ import { TemplatePicker } from "./TemplatePicker.tsx";
10
+
11
+ export interface PrescriptionDetailsFormProps {
12
+ live: Prescription | null;
13
+ rx: PrescriptionRecord | null;
14
+ /** Once a drug is set. Kept mounted while closed, so what's typed survives a drug being chosen. */
15
+ open: boolean;
16
+ /** Where the card flow (← / →) lands, when Treatment isn't. */
17
+ focusable: boolean;
18
+ /**
19
+ * The draft's templates: those with a name or directions are offered as templates; the recommended
20
+ * ones' units are the units offered.
21
+ */
22
+ templates: readonly PrescriptionTemplate[];
23
+ /** The field whose save is in flight. */
24
+ spinning: string | null;
25
+ save: (edits: PrescriptionEdits, from?: string) => void;
26
+ /** Beside Add: the prescription's status (e.g. changed since signing). */
27
+ status?: ReactNode;
28
+ /** Add, once every field is valid: the card signs it. */
29
+ onAdd: () => void;
30
+ /** The add is in flight. */
31
+ adding: boolean;
32
+ addDisabled: boolean;
33
+ }
34
+
35
+ export function PrescriptionDetailsForm({
36
+ live,
37
+ rx,
38
+ open,
39
+ focusable,
40
+ templates,
41
+ spinning,
42
+ save,
43
+ status,
44
+ onAdd,
45
+ adding,
46
+ addDisabled,
47
+ }: PrescriptionDetailsFormProps) {
48
+ const { Button, CardBody, CardFooter, Stack } = useComponents();
49
+ const [instructions, setInstructions] = useState(rx?.instructions ?? "");
50
+ const [quantity, setQuantity] = useState(rx?.dispense?.quantity?.toString() ?? "");
51
+ const [unit, setUnit] = useState(rx?.dispense?.unit ?? "");
52
+ const [daysSupply, setDaysSupply] = useState(rx?.dispense?.daysSupply?.toString() ?? "");
53
+ const [refills, setRefills] = useState(rx?.dispense?.refillsAllowed?.toString() ?? "");
54
+ const [daw, setDaw] = useState(rx?.dispense?.dispenseAsWritten ?? false);
55
+ // Fields edited but not yet saved. A server copy (a save's response, a hydrate) never overwrites
56
+ // them — otherwise a response landing mid-typing replaces what the prescriber is entering.
57
+ const [dirty, setDirty] = useState<ReadonlySet<string>>(new Set());
58
+ const edit = (field: string) => setDirty((d) => (d.has(field) ? d : new Set(d).add(field)));
59
+ const clean = (field: string) =>
60
+ setDirty((d) => {
61
+ if (!d.has(field)) return d;
62
+ const next = new Set(d);
63
+ next.delete(field);
64
+ return next;
65
+ });
66
+
67
+ // When the server's copy changes (a hydrate, a chosen option, signing), show its version.
68
+ // Adjusted during render, keyed on id + contentHash — React's pattern for deriving state from props.
69
+ const serverKey = rx ? `${rx.id}:${rx.signing.contentHash}:${rx.signing.state}` : null;
70
+ const [syncedKey, setSyncedKey] = useState(serverKey);
71
+ if (rx && serverKey !== syncedKey) {
72
+ setSyncedKey(serverKey);
73
+ if (!dirty.has("instructions")) setInstructions(rx.instructions ?? "");
74
+ if (!dirty.has("quantity")) setQuantity(rx.dispense?.quantity?.toString() ?? "");
75
+ if (!dirty.has("unit")) setUnit(rx.dispense?.unit ?? "");
76
+ if (!dirty.has("daysSupply")) setDaysSupply(rx.dispense?.daysSupply?.toString() ?? "");
77
+ if (!dirty.has("refills")) setRefills(rx.dispense?.refillsAllowed?.toString() ?? "");
78
+ setDaw(rx.dispense?.dispenseAsWritten ?? false);
79
+ }
80
+
81
+ // A line without a record shows what's entered on it — e.g. given as props (a sig): once per object.
82
+ const [filledFrom, setFilledFrom] = useState<Prescription | null>(null);
83
+ if (live && live !== filledFrom) {
84
+ setFilledFrom(live);
85
+ const { instructions: sig, dispense: d } = rx ? {} : live.entered;
86
+ const shown: [value: string | undefined, set: (value: string) => void][] = [
87
+ [sig, setInstructions],
88
+ [d?.quantity?.toString(), setQuantity],
89
+ [d?.unit, setUnit],
90
+ [d?.daysSupply?.toString(), setDaysSupply],
91
+ [d?.refillsAllowed?.toString(), setRefills],
92
+ ];
93
+ for (const [value, set] of shown) if (value) set(value);
94
+ if (d?.dispenseAsWritten) setDaw(true);
95
+ }
96
+
97
+ // What's wrong with the fields: shown once Add is clicked (and following the values from then on), and never sent.
98
+ const [showErrors, setShowErrors] = useState(false);
99
+ const errors = schemaErrors(PrescriptionDetailsSchema, { instructions, quantity, daysSupply });
100
+ const shown = showErrors ? errors : {};
101
+ const invalid = (field: string) => field in errors;
102
+
103
+ // Patch only the field that changed (network-api merges a partial dispense); sending the whole
104
+ // block from the screen could write stale values over newer ones.
105
+ const dispense = (field: string, patch: DispensePatch) => {
106
+ clean(field);
107
+ if (patch.dispenseAsWritten !== undefined) setDaw(patch.dispenseAsWritten);
108
+ if (!invalid(field)) save({ dispense: patch }, field);
109
+ };
110
+
111
+ // Memoized so typing doesn't hand DirectionsInput new options, which would reopen them.
112
+ const choosableTemplates = useMemo(
113
+ () => templates.filter((template) => template.name || template.instructions),
114
+ [templates],
115
+ );
116
+ // The picked drug's own templates say its units before the draft's templates load
117
+ const pickedTemplates = live?.treatment?.templates;
118
+ const units = useMemo(
119
+ () => recommendedUnits([...templates, ...(pickedTemplates ?? [])]),
120
+ [templates, pickedTemplates],
121
+ );
122
+ // The first of them is the unit until the prescriber picks another — never left blank. Saved once per drug: a response without it shows it again, but doesn't send it again.
123
+ const unitsFor = units.join("|");
124
+ const unitSavedFor = useRef<string | null>(null);
125
+ const fillUnit = useLatestCallback(() => {
126
+ if (!open || !units.length || unit.trim()) return;
127
+ setUnit(units[0]!);
128
+ if (unitSavedFor.current === unitsFor) return;
129
+ unitSavedFor.current = unitsFor;
130
+ dispense("unit", { unit: units[0]! });
131
+ });
132
+ useEffect(() => fillUnit(), [unitsFor, unit, open, fillUnit]);
133
+
134
+ // A template overwrites the fields it sets and leaves the rest alone, saved together in one call.
135
+ const chooseTemplate = (template: PrescriptionTemplate) => {
136
+ const chosen: [field: string, value: string, set: (value: string) => void][] = [];
137
+ if (template.instructions !== null) chosen.push(["instructions", template.instructions, setInstructions]);
138
+ const d = template.dispense;
139
+ if (d?.quantity != null) chosen.push(["quantity", d.quantity.toString(), setQuantity]);
140
+ if (d?.unit != null) chosen.push(["unit", d.unit, setUnit]);
141
+ if (d?.daysSupply != null) chosen.push(["daysSupply", d.daysSupply.toString(), setDaysSupply]);
142
+ if (d?.refillsAllowed != null) chosen.push(["refills", d.refillsAllowed.toString(), setRefills]);
143
+ for (const [field, value, set] of chosen) {
144
+ set(value);
145
+ clean(field);
146
+ }
147
+ if (d?.dispenseAsWritten != null) setDaw(d.dispenseAsWritten);
148
+
149
+ const dispensePatch: DispensePatch = {
150
+ ...(d?.quantity != null && { quantity: d.quantity }),
151
+ ...(d?.unit != null && { unit: d.unit }),
152
+ ...(d?.daysSupply != null && { daysSupply: d.daysSupply }),
153
+ ...(d?.refillsAllowed != null && { refillsAllowed: d.refillsAllowed }),
154
+ ...(d?.dispenseAsWritten != null && { dispenseAsWritten: d.dispenseAsWritten }),
155
+ };
156
+ const edits: PrescriptionEdits = {
157
+ ...(template.instructions !== null &&
158
+ template.instructions !== (rx?.instructions ?? "") && { instructions: template.instructions }),
159
+ ...(Object.keys(dispensePatch).length > 0 && { dispense: dispensePatch }),
160
+ };
161
+ if (Object.keys(edits).length > 0) save(edits, "instructions");
162
+ };
163
+
164
+ if (!open) return null;
165
+ const setters: Record<DispenseField, (value: string) => void> = {
166
+ quantity: setQuantity,
167
+ unit: setUnit,
168
+ daysSupply: setDaysSupply,
169
+ refills: setRefills,
170
+ };
171
+ const dispenseValues = { quantity, unit, daysSupply, refills, dispenseAsWritten: daw };
172
+ const dispenseFields = Object.keys(setters) as DispenseField[];
173
+ return (
174
+ <>
175
+ <CardBody>
176
+ <Stack gap="4">
177
+ <TemplatePicker
178
+ templates={choosableTemplates}
179
+ hasDirections={instructions.trim() !== ""}
180
+ onChoose={chooseTemplate}
181
+ />
182
+ <DirectionsInput
183
+ value={instructions}
184
+ errorMessage={shown.instructions}
185
+ edited={dirty.has("instructions")}
186
+ focusable={focusable}
187
+ onEdit={(value) => {
188
+ setInstructions(value);
189
+ edit("instructions");
190
+ }}
191
+ onCommit={() => {
192
+ clean("instructions");
193
+ if (!invalid("instructions") && instructions !== (rx?.instructions ?? ""))
194
+ save({ instructions }, "instructions");
195
+ }}
196
+ />
197
+ <DispenseInputs
198
+ values={dispenseValues}
199
+ errors={shown}
200
+ units={units}
201
+ edited={new Set(dispenseFields.filter((field) => dirty.has(field)))}
202
+ spinning={spinning}
203
+ onEdit={(field, value) => {
204
+ setters[field](value);
205
+ edit(field);
206
+ }}
207
+ save={dispense}
208
+ />
209
+ </Stack>
210
+ </CardBody>
211
+ <CardFooter start={status}>
212
+ <Button
213
+ variant="secondary" // Send is the page's one primary action
214
+ // Not disabled while saving: clicking Add leaves a field, which saves it — the sign waits
215
+ // for that save (a disabled button would swallow the click).
216
+ loading={adding}
217
+ disabled={addDisabled}
218
+ onClick={() => {
219
+ setShowErrors(true);
220
+ if (Object.keys(errors).length === 0) onAdd();
221
+ }}
222
+ >
223
+ Add
224
+ </Button>
225
+ </CardFooter>
226
+ </>
227
+ );
228
+ }
229
+
230
+ // The units the recommended templates set — a recommended sig's, then the unit-only ones — in the server's order.
231
+ const recommendedUnits = (templates: readonly PrescriptionTemplate[]): string[] => [
232
+ ...new Set(
233
+ templates
234
+ .filter((template) => template.source === "RECOMMENDED")
235
+ .map((template) => template.dispense?.unit)
236
+ .filter((unit): unit is string => Boolean(unit)),
237
+ ),
238
+ ];
@@ -0,0 +1,63 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { schemaErrors } from "../../schemaErrors.ts";
3
+ import { PrescriptionDetailsSchema, type PrescriptionDetails } from "./PrescriptionDetailsSchema.ts";
4
+
5
+ const errorsOf = (inputs: PrescriptionDetails) => schemaErrors(PrescriptionDetailsSchema, inputs);
6
+
7
+ const valid = { instructions: "Take 1 capsule by mouth 3 times per day", quantity: "30", daysSupply: "10" };
8
+
9
+ describe("PrescriptionDetailsSchema", () => {
10
+ it("accepts directions, quantity and days supply that are filled in", () => {
11
+ expect(PrescriptionDetailsSchema.safeParse(valid).success).toBe(true);
12
+ });
13
+
14
+ it("parses values by trimming directions, converting text to numbers", () => {
15
+ expect(PrescriptionDetailsSchema.parse({ instructions: " test ", quantity: " 2.5 ", daysSupply: "7" })).toEqual({
16
+ instructions: "test",
17
+ quantity: 2.5,
18
+ daysSupply: 7,
19
+ });
20
+ });
21
+ });
22
+
23
+ describe("PrescriptionDetailsSchema errors", () => {
24
+ it("has no errors when every field is valid", () => {
25
+ expect(errorsOf(valid)).toEqual({});
26
+ });
27
+
28
+ it("says each empty field is required", () => {
29
+ expect(errorsOf({ instructions: "", quantity: "", daysSupply: "" })).toEqual({
30
+ instructions: "Required",
31
+ quantity: "Required",
32
+ daysSupply: "Required",
33
+ });
34
+ });
35
+
36
+ it.each([
37
+ ["instructions", " "],
38
+ ["quantity", " "],
39
+ ["daysSupply", " "],
40
+ ] as const)("counts %s of only spaces as empty", (field, value) => {
41
+ expect(errorsOf({ ...valid, [field]: value })).toEqual({ [field]: "Required" });
42
+ });
43
+
44
+ it.each([
45
+ ["quantity", "abc", "Must be a number"],
46
+ ["quantity", "12abc", "Must be a number"],
47
+ ["quantity", "0", "Must be greater than 0"],
48
+ ["quantity", "-5", "Must be greater than 0"],
49
+ ["daysSupply", "abc", "Must be a number"],
50
+ ["daysSupply", "0", "Must be greater than 0"],
51
+ ["daysSupply", "-1", "Must be greater than 0"],
52
+ ] as const)("says %s of %j: %s", (field, value, message) => {
53
+ expect(errorsOf({ ...valid, [field]: value })).toEqual({ [field]: message });
54
+ });
55
+
56
+ it.each([
57
+ ["quantity", "2.5"],
58
+ ["quantity", "0.5"],
59
+ ["daysSupply", "90"],
60
+ ] as const)("accepts %s of %j", (field, value) => {
61
+ expect(errorsOf({ ...valid, [field]: value })).toEqual({});
62
+ });
63
+ });
@@ -0,0 +1,15 @@
1
+ import { z } from "zod";
2
+
3
+ const textToNumber = z
4
+ .string()
5
+ .trim()
6
+ .min(1, "Required")
7
+ .pipe(z.coerce.number<string>({ error: "Must be a number" }).gt(0, "Must be greater than 0"));
8
+
9
+ export const PrescriptionDetailsSchema = z.object({
10
+ instructions: z.string().trim().min(1, "Required"),
11
+ quantity: textToNumber,
12
+ daysSupply: textToNumber,
13
+ });
14
+
15
+ export type PrescriptionDetails = z.input<typeof PrescriptionDetailsSchema>;
@@ -0,0 +1,75 @@
1
+ // @vitest-environment jsdom
2
+ import type { PrescriptionTemplate } from "@photonhealth/client";
3
+ import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+ import { TemplatePicker, type TemplatePickerProps } from "./TemplatePicker.tsx";
6
+
7
+ const sig = (instructions: string): PrescriptionTemplate => ({
8
+ id: null,
9
+ source: "RECOMMENDED",
10
+ name: null,
11
+ instructions,
12
+ dispense: null,
13
+ });
14
+
15
+ const options = () => screen.queryByRole("list", { name: "Templates" });
16
+
17
+ const renderPicker = (props: Partial<TemplatePickerProps> = {}) => {
18
+ const all: TemplatePickerProps = { templates: [], hasDirections: false, onChoose: vi.fn(), ...props };
19
+ render(<TemplatePicker {...all} />);
20
+ return all;
21
+ };
22
+
23
+ describe("TemplatePicker", () => {
24
+ afterEach(() => cleanup());
25
+
26
+ it("renders an expanded list for a new draft", () => {
27
+ renderPicker({ templates: [sig("Take 1 capsule by mouth daily"), sig("Take 2 capsules by mouth daily")] });
28
+ const offered = within(options()!)
29
+ .getAllByRole("button")
30
+ .map((button) => button.textContent);
31
+ expect(offered).toEqual(["Take 1 capsule by mouth daily", "Take 2 capsules by mouth daily"]);
32
+ });
33
+
34
+ it("names a catalog template, with its directions under the name", () => {
35
+ renderPicker({
36
+ templates: [
37
+ { ...sig("Take 1 capsule by mouth twice daily"), id: "tmp_1", source: "ORG_CATALOG", name: "Sinusitis" },
38
+ ],
39
+ });
40
+ const option = within(options()!).getByRole("button");
41
+ expect(option.textContent).toContain("Sinusitis");
42
+ expect(option.textContent).toContain("Take 1 capsule by mouth twice daily");
43
+ });
44
+
45
+ it("renders a collapsed list when the prescription already has directions", () => {
46
+ renderPicker({ hasDirections: true, templates: [sig("Take 1 capsule by mouth daily")] });
47
+ expect(screen.getByRole("button", { name: "Templates" }).getAttribute("aria-expanded")).toBe("false");
48
+ expect(options()).toBeNull();
49
+ });
50
+
51
+ it("renders nothing when there are no templates", () => {
52
+ renderPicker();
53
+ expect(screen.queryByRole("button", { name: "Templates" })).toBeNull();
54
+ });
55
+
56
+ it("hands off the template I choose", () => {
57
+ const chosen = sig("Take 2 capsules by mouth daily");
58
+ const { onChoose } = renderPicker({ templates: [sig("Take 1 capsule by mouth daily"), chosen] });
59
+ fireEvent.click(screen.getByRole("button", { name: "Take 2 capsules by mouth daily" }));
60
+ expect(onChoose).toHaveBeenCalledExactlyOnceWith(chosen);
61
+ });
62
+
63
+ it("collapses the list once I choose one", () => {
64
+ renderPicker({ templates: [sig("Take 1 capsule by mouth daily")] });
65
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
66
+ expect(options()).toBeNull();
67
+ });
68
+
69
+ it("expands the list when the toggle is clicked", () => {
70
+ renderPicker({ templates: [sig("Take 1 capsule by mouth daily")] });
71
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
72
+ fireEvent.click(screen.getByRole("button", { name: "Templates" }));
73
+ expect(options()).not.toBeNull();
74
+ });
75
+ });
@@ -0,0 +1,41 @@
1
+ import type { PrescriptionTemplate } from "@photonhealth/client";
2
+ import { useState } from "react";
3
+ import { useComponents } from "../../../primitives/index.ts";
4
+
5
+ /** The templates a prescription's directions and dispense can be filled from. */
6
+ export interface TemplatePickerProps {
7
+ /** Each has a name, directions, or both. */
8
+ templates: readonly PrescriptionTemplate[];
9
+ /** The prescription already has directions, so the templates start closed. */
10
+ hasDirections: boolean;
11
+ onChoose: (template: PrescriptionTemplate) => void;
12
+ }
13
+
14
+ export function TemplatePicker({ templates, hasDirections, onChoose }: TemplatePickerProps) {
15
+ const { ChoiceList, Disclosure } = useComponents();
16
+ // Each new set of templates opens, unless someone already entered directions (e.g. an existing draft's).
17
+ // Choosing one closes them, and the toggle opens them again.
18
+ const [open, setOpen] = useState(!hasDirections);
19
+ const [shownTemplates, setShownTemplates] = useState(templates);
20
+ if (templates !== shownTemplates) {
21
+ setShownTemplates(templates);
22
+ setOpen(!hasDirections);
23
+ }
24
+ if (templates.length === 0) return null;
25
+ return (
26
+ <Disclosure summary="Templates" open={open} onOpenChange={setOpen}>
27
+ <ChoiceList
28
+ label="Templates"
29
+ choices={templates.map((template, index) => ({
30
+ key: String(index),
31
+ label: template.name ?? template.instructions ?? "",
32
+ description: (template.name && template.instructions) ?? undefined,
33
+ }))}
34
+ onChoose={(key) => {
35
+ setOpen(false);
36
+ onChoose(templates[Number(key)]!);
37
+ }}
38
+ />
39
+ </Disclosure>
40
+ );
41
+ }