@photonhealth/react 2.0.0-rc.1 → 2.0.0-rc.3

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 (272) hide show
  1. package/README.md +52 -9
  2. package/dist/adapters/tailwind.d.ts.map +1 -1
  3. package/dist/adapters/tailwind.js +7 -4
  4. package/dist/adapters/tailwind.js.map +1 -1
  5. package/dist/analytics/PhotonAnalyticsProvider.d.ts +19 -0
  6. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
  7. package/dist/analytics/PhotonAnalyticsProvider.js +76 -0
  8. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
  9. package/dist/analytics/cardLifecycle.d.ts +10 -0
  10. package/dist/analytics/cardLifecycle.d.ts.map +1 -0
  11. package/dist/analytics/cardLifecycle.js +43 -0
  12. package/dist/analytics/cardLifecycle.js.map +1 -0
  13. package/dist/analytics/fieldInteraction.d.ts +18 -0
  14. package/dist/analytics/fieldInteraction.d.ts.map +1 -0
  15. package/dist/analytics/fieldInteraction.js +102 -0
  16. package/dist/analytics/fieldInteraction.js.map +1 -0
  17. package/dist/analytics/lifecycleOutcomes.d.ts +8 -0
  18. package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
  19. package/dist/analytics/lifecycleOutcomes.js +16 -0
  20. package/dist/analytics/lifecycleOutcomes.js.map +1 -0
  21. package/dist/analytics/tracker.d.ts +19 -0
  22. package/dist/analytics/tracker.d.ts.map +1 -0
  23. package/dist/analytics/tracker.js +41 -0
  24. package/dist/analytics/tracker.js.map +1 -0
  25. package/dist/analytics/viewed.d.ts +11 -0
  26. package/dist/analytics/viewed.d.ts.map +1 -0
  27. package/dist/analytics/viewed.js +16 -0
  28. package/dist/analytics/viewed.js.map +1 -0
  29. package/dist/components/PhotonOrder.d.ts +18 -18
  30. package/dist/components/PhotonOrder.d.ts.map +1 -1
  31. package/dist/components/PhotonOrder.js +34 -19
  32. package/dist/components/PhotonOrder.js.map +1 -1
  33. package/dist/components/PhotonPatient.d.ts +7 -35
  34. package/dist/components/PhotonPatient.d.ts.map +1 -1
  35. package/dist/components/PhotonPatient.js +6 -78
  36. package/dist/components/PhotonPatient.js.map +1 -1
  37. package/dist/components/PhotonPrescription.d.ts +15 -26
  38. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  39. package/dist/components/PhotonPrescription.js +6 -360
  40. package/dist/components/PhotonPrescription.js.map +1 -1
  41. package/dist/components/format.d.ts +2 -2
  42. package/dist/components/format.js +2 -2
  43. package/dist/components/index.d.ts +1 -1
  44. package/dist/components/index.d.ts.map +1 -1
  45. package/dist/components/index.js +1 -1
  46. package/dist/components/index.js.map +1 -1
  47. package/dist/components/open.d.ts +11 -13
  48. package/dist/components/open.d.ts.map +1 -1
  49. package/dist/components/open.js +7 -2
  50. package/dist/components/open.js.map +1 -1
  51. package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
  52. package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
  53. package/dist/components/order/DraftOrderPrompt.js +26 -0
  54. package/dist/components/order/DraftOrderPrompt.js.map +1 -0
  55. package/dist/components/patient/PatientCard/PatientCard.d.ts +30 -0
  56. package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
  57. package/dist/components/patient/PatientCard/PatientCard.js +101 -0
  58. package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
  59. package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
  60. package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
  61. package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
  62. package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
  63. package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
  64. package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
  65. package/dist/components/patient/PatientIntakeForm.js +114 -0
  66. package/dist/components/patient/PatientIntakeForm.js.map +1 -0
  67. package/dist/components/patient/PatientSearch.d.ts +12 -0
  68. package/dist/components/patient/PatientSearch.d.ts.map +1 -0
  69. package/dist/components/patient/PatientSearch.js +148 -0
  70. package/dist/components/patient/PatientSearch.js.map +1 -0
  71. package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
  72. package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
  73. package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +6 -5
  74. package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
  75. package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +15 -16
  76. package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
  77. package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +29 -28
  78. package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
  79. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
  80. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
  81. package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
  82. package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
  83. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
  84. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
  85. package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
  86. package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
  87. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
  88. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
  89. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
  90. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
  91. package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
  92. package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
  93. package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
  94. package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
  95. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
  96. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
  97. package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
  98. package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
  99. package/dist/components/patient/fields.d.ts +7 -26
  100. package/dist/components/patient/fields.d.ts.map +1 -1
  101. package/dist/components/patient/fields.js +11 -52
  102. package/dist/components/patient/fields.js.map +1 -1
  103. package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
  104. package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
  105. package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -10
  106. package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
  107. package/dist/components/prescription/PrescriptionCard.d.ts +51 -0
  108. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
  109. package/dist/components/prescription/PrescriptionCard.js +186 -0
  110. package/dist/components/prescription/PrescriptionCard.js.map +1 -0
  111. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
  112. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
  113. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
  114. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
  115. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
  116. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
  117. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
  118. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
  119. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
  120. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
  121. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
  122. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
  123. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
  124. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
  125. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
  126. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
  127. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
  128. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
  129. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
  130. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
  131. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
  132. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
  133. package/dist/components/{TreatmentPicker.js → prescription/TreatmentSearch/TreatmentPicker.js} +113 -105
  134. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
  135. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
  136. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
  137. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
  138. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
  139. package/dist/components/schemaErrors.d.ts +13 -0
  140. package/dist/components/schemaErrors.d.ts.map +1 -0
  141. package/dist/components/schemaErrors.js +25 -0
  142. package/dist/components/schemaErrors.js.map +1 -0
  143. package/dist/components/search.d.ts +1 -1
  144. package/dist/components/search.js +1 -1
  145. package/dist/index.d.ts +2 -0
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +1 -0
  148. package/dist/index.js.map +1 -1
  149. package/dist/meta/version.d.ts +5 -0
  150. package/dist/meta/version.d.ts.map +1 -0
  151. package/dist/meta/version.js +5 -0
  152. package/dist/meta/version.js.map +1 -0
  153. package/dist/primitives/PhotonProvider.d.ts +3 -1
  154. package/dist/primitives/PhotonProvider.d.ts.map +1 -1
  155. package/dist/primitives/PhotonProvider.js +23 -11
  156. package/dist/primitives/PhotonProvider.js.map +1 -1
  157. package/dist/primitives/defaults.d.ts.map +1 -1
  158. package/dist/primitives/defaults.js +6 -3
  159. package/dist/primitives/defaults.js.map +1 -1
  160. package/dist/primitives/photonContext.d.ts +3 -0
  161. package/dist/primitives/photonContext.d.ts.map +1 -0
  162. package/dist/primitives/photonContext.js +3 -0
  163. package/dist/primitives/photonContext.js.map +1 -0
  164. package/dist/primitives/types.d.ts +15 -3
  165. package/dist/primitives/types.d.ts.map +1 -1
  166. package/dist/primitives/types.js.map +1 -1
  167. package/dist/primitives/useProvidedPhoton.d.ts +8 -0
  168. package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
  169. package/dist/primitives/useProvidedPhoton.js +8 -0
  170. package/dist/primitives/useProvidedPhoton.js.map +1 -0
  171. package/dist/styles.css +45 -3
  172. package/dist/test-utils/contract.d.ts.map +1 -1
  173. package/dist/test-utils/contract.js +23 -2
  174. package/dist/test-utils/contract.js.map +1 -1
  175. package/package.json +8 -3
  176. package/src/adapters/tailwind.tsx +52 -24
  177. package/src/analytics/PhotonAnalyticsProvider.test.tsx +190 -0
  178. package/src/analytics/PhotonAnalyticsProvider.tsx +151 -0
  179. package/src/analytics/cardLifecycle.test.tsx +272 -0
  180. package/src/analytics/cardLifecycle.ts +44 -0
  181. package/src/analytics/fieldInteraction.test.tsx +186 -0
  182. package/src/analytics/fieldInteraction.tsx +148 -0
  183. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  184. package/src/analytics/lifecycleOutcomes.ts +29 -0
  185. package/src/analytics/tracker.test.ts +52 -0
  186. package/src/analytics/tracker.ts +49 -0
  187. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  188. package/src/analytics/viewed.ts +27 -0
  189. package/src/components/PhotonOrder.test.tsx +394 -0
  190. package/src/components/PhotonOrder.tsx +79 -53
  191. package/src/components/PhotonPatient.tsx +15 -166
  192. package/src/components/PhotonPrescription.test.tsx +120 -0
  193. package/src/components/PhotonPrescription.tsx +23 -583
  194. package/src/components/ScreeningAlerts.test.tsx +81 -0
  195. package/src/components/format.ts +2 -2
  196. package/src/components/index.ts +1 -1
  197. package/src/components/open.ts +13 -16
  198. package/src/components/order/DraftOrderPrompt.test.tsx +77 -0
  199. package/src/components/order/DraftOrderPrompt.tsx +81 -0
  200. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  201. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  202. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  203. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  204. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  205. package/src/components/patient/PatientSearch.test.tsx +204 -0
  206. package/src/components/patient/PatientSearch.tsx +221 -0
  207. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  208. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +24 -16
  209. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  210. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +53 -48
  211. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  212. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  213. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  214. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  215. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  216. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  217. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  218. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  219. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  220. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  221. package/src/components/patient/fields.tsx +12 -124
  222. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  223. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -15
  224. package/src/components/prescription/PrescriptionCard.test.tsx +247 -0
  225. package/src/components/prescription/PrescriptionCard.tsx +361 -0
  226. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +82 -0
  227. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
  228. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +206 -0
  229. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
  230. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +453 -0
  231. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
  232. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
  233. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
  234. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +72 -0
  235. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
  236. package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
  237. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +695 -0
  238. package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
  239. package/src/components/schemaErrors.test.ts +49 -0
  240. package/src/components/schemaErrors.ts +34 -0
  241. package/src/components/search.tsx +1 -1
  242. package/src/index.ts +2 -0
  243. package/src/meta/version.test.ts +11 -0
  244. package/src/meta/version.ts +4 -0
  245. package/src/primitives/PhotonProvider.tsx +30 -15
  246. package/src/primitives/defaults.tsx +44 -21
  247. package/src/primitives/photonContext.ts +4 -0
  248. package/src/primitives/types.ts +15 -3
  249. package/src/primitives/useProvidedPhoton.ts +21 -0
  250. package/src/styles.css +45 -3
  251. package/src/test-utils/contract.tsx +45 -2
  252. package/dist/components/TreatmentPicker.d.ts +0 -45
  253. package/dist/components/TreatmentPicker.d.ts.map +0 -1
  254. package/dist/components/TreatmentPicker.js.map +0 -1
  255. package/dist/components/patient/Benefits.d.ts.map +0 -1
  256. package/dist/components/patient/Benefits.js.map +0 -1
  257. package/dist/components/patient/Clinical.d.ts.map +0 -1
  258. package/dist/components/patient/Clinical.js.map +0 -1
  259. package/dist/components/patient/IntakeForm.d.ts +0 -10
  260. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  261. package/dist/components/patient/IntakeForm.js +0 -324
  262. package/dist/components/patient/IntakeForm.js.map +0 -1
  263. package/dist/components/patient/Summary.d.ts +0 -48
  264. package/dist/components/patient/Summary.d.ts.map +0 -1
  265. package/dist/components/patient/Summary.js +0 -80
  266. package/dist/components/patient/Summary.js.map +0 -1
  267. package/dist/components/patient/query.d.ts +0 -23
  268. package/dist/components/patient/query.d.ts.map +0 -1
  269. package/dist/components/patient/query.js.map +0 -1
  270. package/src/components/TreatmentPicker.tsx +0 -350
  271. package/src/components/patient/IntakeForm.tsx +0 -532
  272. package/src/components/patient/Summary.tsx +0 -310
@@ -0,0 +1,177 @@
1
+ import { useComponents } from "../../../primitives/index.ts";
2
+ import { classify, type ChangeOption, type Patient, type PatientInput } from "@photonhealth/client";
3
+ import { useLive, useOnChange } from "../../../hooks/index.ts";
4
+ import { useState } from "react";
5
+ import { openFailed, type NotFound } from "../../open.ts";
6
+ import type { PhotonPatientProps } from "../../PhotonPatient.tsx";
7
+ import { PatientIntakeForm } from "../PatientIntakeForm.tsx";
8
+ import { PatientSearch } from "../PatientSearch.tsx";
9
+ import { PatientSummary } from "../PatientSummary/PatientSummary.tsx";
10
+ import { usePatientToShow } from "./usePatientToShow.ts";
11
+ import { useSavePatientAndSendEvent } from "../../../analytics/cardLifecycle.ts";
12
+
13
+ type PatientClinicalInput = NonNullable<PatientInput["clinical"]>;
14
+
15
+ /** A stable key per live object: a different patient object gets a fresh form. */
16
+ const objectKeys = new WeakMap<object, number>();
17
+ let nextKey = 0;
18
+ const keyOf = (obj: object) => {
19
+ if (!objectKeys.has(obj)) objectKeys.set(obj, ++nextKey);
20
+ return objectKeys.get(obj)!;
21
+ };
22
+
23
+ /** What PatientCard renders, in the order its body checks for each. */
24
+ export enum PatientCardState {
25
+ /** The patient couldn't be opened for a reason other than not found: an error alert. */
26
+ FAILED_TO_OPEN = "failedToOpen",
27
+ /** No live patient yet, or no snapshot of it: the "Loading…" card. */
28
+ LOADING = "loading",
29
+ /** The patient has a record: PatientSummary. */
30
+ SUMMARY = "summary",
31
+ /** The patient has no record yet: PatientSearch, to match any existing records. */
32
+ SEARCH = "search",
33
+ /** The patient has no record yet, and user is adding the patient to Photon: PatientIntakeForm. */
34
+ INTAKE_FORM = "intakeForm",
35
+ }
36
+
37
+ /** Which state PatientCard is in, from what usePatientToShow and useLive give it. */
38
+ const getPatientCardState = ({
39
+ failedToOpen,
40
+ patient,
41
+ snap,
42
+ adding,
43
+ }: {
44
+ failedToOpen: Error | null;
45
+ patient: Patient | null;
46
+ snap: Patient["snapshot"] | null;
47
+ /** Whether the prescriber is adding a new patient rather than finding one (see `startsAdding`). */
48
+ adding: boolean;
49
+ }): PatientCardState => {
50
+ if (failedToOpen) return PatientCardState.FAILED_TO_OPEN;
51
+ if (!patient || !snap) return PatientCardState.LOADING;
52
+ if (snap.state) return PatientCardState.SUMMARY;
53
+ return adding ? PatientCardState.INTAKE_FORM : PatientCardState.SEARCH;
54
+ };
55
+
56
+ /**
57
+ * Whether a patient without a record starts on PatientIntakeForm rather than PatientSearch: when it already has
58
+ * a name or date of birth (e.g. a host's details the server hasn't matched), there's nothing left to search for.
59
+ */
60
+ const startsAdding = (patient: Patient) => {
61
+ const demographic = patient.known.demographic;
62
+ return Boolean(demographic?.name?.first || demographic?.name?.last || demographic?.dateOfBirth);
63
+ };
64
+
65
+ /**
66
+ * PhotonPatient, and what only PhotonOrder gives it: read-only and no "Change patient" (a sent order), no "Change
67
+ * patient" (an order handed off to it), and the server's request for a way to reach the patient (its reason),
68
+ * which opens the contact fields. Internal: the package index exports only PhotonPatient.
69
+ */
70
+ export function PatientCard({
71
+ patient: patientProp,
72
+ onPatient,
73
+ readOnly,
74
+ hideChangePatient,
75
+ addressRequest,
76
+ notFound: notFoundInOrder,
77
+ }: PhotonPatientProps & {
78
+ /** Nothing to edit, and no "Change patient" (a sent order's patient). */
79
+ readOnly?: boolean;
80
+ /** No "Change patient", but still editable (an order handed off to PhotonOrder). */
81
+ hideChangePatient?: boolean;
82
+ addressRequest?: string | null;
83
+ /** The patient it was given by id isn't there (PhotonOrder's): said in the form, with the matches. */
84
+ notFound?: NotFound | null;
85
+ }) {
86
+ const { Alert, Card, CardHeader } = useComponents();
87
+ const { patient, notFound, failedToOpen, startOver } = usePatientToShow(patientProp, { readOnly });
88
+ const snap = useLive(patient);
89
+ useOnChange(patient, (p) => p.state, onPatient);
90
+ const savePatientAndSendEvent = useSavePatientAndSendEvent();
91
+ // Finding someone and adding them are two different jobs, so the card does one at a time. Decided once per patient
92
+ // object: "Add new patient" switches to adding, with what was typed; a different patient object starts over.
93
+ const [intake, setIntake] = useState<{ patient: Patient; adding: boolean; query: string | null } | null>(null);
94
+ const intakeForPatient = intake?.patient === patient ? intake : null;
95
+ if (patient && !intakeForPatient) setIntake({ patient, adding: startsAdding(patient), query: null });
96
+ const adding = intakeForPatient?.adding ?? (patient ? startsAdding(patient) : false);
97
+ const state = getPatientCardState({ failedToOpen, patient, snap, adding });
98
+
99
+ if (state === PatientCardState.FAILED_TO_OPEN)
100
+ return <Alert tone="critical" title={openFailed("patient", failedToOpen!)} description={failedToOpen!.message} />;
101
+ if (state === PatientCardState.LOADING) {
102
+ return (
103
+ <Card divided>
104
+ <CardHeader title="Patient" description="Loading…" />
105
+ </Card>
106
+ );
107
+ }
108
+
109
+ // Past LOADING, getPatientCardState guarantees both are set.
110
+ const livePatient = patient!;
111
+ const snapshot = snap!;
112
+ const changes = classify(snapshot.changes);
113
+ const update = (input: Omit<PatientInput, "id">) =>
114
+ void savePatientAndSendEvent(livePatient, () => livePatient.update(input)).catch(() => {}); // failures land on the object
115
+ const patchClinical = (clinical: PatientClinicalInput) => update({ clinical });
116
+ const choose = (option: ChangeOption) =>
117
+ void savePatientAndSendEvent(livePatient, () => livePatient.choose(option)).catch(() => {});
118
+
119
+ if (state === PatientCardState.SUMMARY) {
120
+ const record = snapshot.state!;
121
+ return (
122
+ <PatientSummary
123
+ key={record.id}
124
+ patient={record}
125
+ saving={snapshot.status === "saving"}
126
+ changes={changes}
127
+ error={snapshot.error}
128
+ onChoose={choose}
129
+ onAddAllergy={(name) => patchClinical({ allergies: { add: [{ name }] } })}
130
+ onConfirmNone={(list) => patchClinical({ [list]: { none: true } })}
131
+ onRemoveAllergy={(a) => patchClinical({ allergies: { remove: [{ id: a.id }] } })}
132
+ onRemoveMedication={(m) => patchClinical({ medications: { remove: [{ id: m.id, status: m.status }] } })}
133
+ onAddDiagnosis={(diagnosis) => patchClinical({ diagnoses: { add: [diagnosis] } })}
134
+ onRemoveDiagnosis={(d) => patchClinical({ diagnoses: { remove: [{ id: d.id }] } })}
135
+ onAddBenefit={(b) => update({ benefits: { add: [b] } })}
136
+ onRemoveBenefit={(b) => update({ benefits: { remove: [{ id: b.id }] } })}
137
+ onConfirmNoBenefits={() => update({ benefits: { none: true } })}
138
+ onAddMedication={(name) => patchClinical({ medications: { add: [{ name, status: "ACTIVE" }] } })}
139
+ onSaveDetails={(input) =>
140
+ savePatientAndSendEvent(livePatient, () => livePatient.update(input)).then(
141
+ () => true,
142
+ () => false, // the failure lands on the object, and the card shows it
143
+ )
144
+ }
145
+ addressRequest={readOnly ? null : (addressRequest ?? null)}
146
+ readOnly={readOnly}
147
+ onChangePatient={
148
+ readOnly || hideChangePatient
149
+ ? undefined
150
+ : () => {
151
+ onPatient?.(null); // given a patient, the host decides what's next
152
+ startOver();
153
+ }
154
+ }
155
+ />
156
+ );
157
+ }
158
+
159
+ // SEARCH or INTAKE_FORM. An id that was not found: said with the search, or on the form, for someone else.
160
+ const notFoundError = notFoundInOrder ?? notFound;
161
+ const notice = notFoundError && { title: openFailed("patient", notFoundError), description: notFoundError.message };
162
+ // A different patient object (e.g. after "Change patient") starts a fresh search or form.
163
+ if (state === PatientCardState.SEARCH) {
164
+ return (
165
+ <PatientSearch
166
+ key={keyOf(livePatient)}
167
+ patient={livePatient}
168
+ notice={notice}
169
+ onAddNew={(query) => setIntake({ patient: livePatient, adding: true, query })}
170
+ />
171
+ );
172
+ }
173
+
174
+ return (
175
+ <PatientIntakeForm key={keyOf(livePatient)} patient={livePatient} query={intakeForPatient?.query} notice={notice} />
176
+ );
177
+ }
@@ -0,0 +1,44 @@
1
+ import { Patient, type PatientInput, type PatientResult } from "@photonhealth/client";
2
+ import { useState } from "react";
3
+ import { usePhoton } from "../../../primitives/index.ts";
4
+ import { NotFound, toOpen, useOpened } from "../../open.ts";
5
+ import type { PhotonPatientProps } from "../../PhotonPatient.tsx";
6
+
7
+ // At module level, not inline: useOpened re-runs its server call when this function changes.
8
+ const patientOf = (result: PatientResult) => result.patient;
9
+
10
+ /**
11
+ * Which live Patient a patient card shows, from its `patient` prop:
12
+ * - the host's live `Patient`, if it passed one;
13
+ * - otherwise a blank patient the card made to find or add someone, if it has one for this prop — made when the
14
+ * prop has nothing to open, when its id isn't found, or on "Change patient" (`startOver`);
15
+ * - otherwise the one opened from the prop's id or fields (`null` while it opens).
16
+ *
17
+ * A blank patient belongs to the prop value it was made for, so when the host passes something else the card
18
+ * shows that instead, and passing nothing again gives a fresh blank patient.
19
+ */
20
+ export function usePatientToShow(patientProp: PhotonPatientProps["patient"], { readOnly = false } = {}) {
21
+ const ph = usePhoton();
22
+ const hostPatient = patientProp instanceof Patient ? patientProp : null;
23
+ const patientToOpen = toOpen<PatientInput>(patientProp, Boolean(hostPatient));
24
+ // Hooks run on every render, before any return (React's rule). With a host patient there's nothing to open.
25
+ const { opened: openedPatient, error: openError } = useOpened(ph.patient, patientToOpen, patientOf, "patient");
26
+ const [blank, setBlank] = useState<{ forProp: string; patient: Patient } | null>(null);
27
+
28
+ // The host's live Patient: shown as is. "Change patient" is the host's to handle (the card calls onPatient(null)).
29
+ if (hostPatient) return { patient: hostPatient, notFound: null, failedToOpen: null, startOver: () => {} };
30
+
31
+ const propKey = JSON.stringify(patientToOpen);
32
+ const startOver = () => setBlank({ forProp: propKey, patient: ph.patient() });
33
+ const blankPatient = blank?.forProp === propKey ? blank.patient : null;
34
+ // An id the server doesn't have: the card asks for someone to find or add instead, saying why. A read-only card
35
+ // can't add anyone, so it shows the error instead.
36
+ const notFound = openError instanceof NotFound && !readOnly ? openError : null;
37
+ // Any other failure to open: the card shows it.
38
+ const failedToOpen = openError && !notFound ? openError : null;
39
+
40
+ // Nothing to open, or not found: a blank patient to find or add someone.
41
+ if (!blankPatient && (!patientToOpen || notFound)) startOver();
42
+
43
+ return { patient: blankPatient ?? openedPatient, notFound, failedToOpen, startOver };
44
+ }
@@ -0,0 +1,262 @@
1
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
2
+ import userEvent from "@testing-library/user-event";
3
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
4
+ import { change, fakeNetworkApiClient, noMatch, payload, photonOver } from "@photonhealth/client/testing";
5
+ import type { Patient } from "@photonhealth/client";
6
+ import { PhotonPatient } from "../../index.ts";
7
+ import { PatientIntakeForm } from "./PatientIntakeForm.tsx";
8
+ import { patient as ada, withPhoton } from "../../../test/cards.fixtures.tsx";
9
+ import {
10
+ buildEditedEventsFor,
11
+ leaveField,
12
+ meAsPrescriber,
13
+ recordAnalytics,
14
+ type RecordedAnalytics,
15
+ typeInto,
16
+ unmountAndRestoreFetch,
17
+ visitedWithoutEditing,
18
+ withAnalytics,
19
+ } from "../../../test/analytics.fixtures.tsx";
20
+
21
+ type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
22
+ type SyncVars = { demographic?: { sex?: string }; contact?: { phone?: string; email?: string } };
23
+
24
+ /** A server message about one field: rejected, so the patient can't be added until it's answered. */
25
+ const rejected = (key: string, reason: string) =>
26
+ change({ key, label: key, status: "REJECTED", severity: "BLOCKING", reason });
27
+
28
+ /**
29
+ * PatientIntakeForm on its own, over a fake network-api that finds no one unless `script` says otherwise.
30
+ * `hostDetails` are what a host passed to PhotonPatient: synced before the form opens, so the patient already has
31
+ * what the server said about them.
32
+ * `sent` collects every SyncPatient's variables, to check what Save sends.
33
+ */
34
+ const renderIntakeForm = async ({
35
+ query,
36
+ script = {},
37
+ hostDetails,
38
+ }: {
39
+ query?: string;
40
+ script?: NetworkScript;
41
+ hostDetails?: Parameters<Patient["sync"]>[0];
42
+ } = {}) => {
43
+ const sent: SyncVars[] = [];
44
+ const answer = (script.SyncPatient ?? noMatch) as (vars: SyncVars) => unknown;
45
+ const { client } = fakeNetworkApiClient({
46
+ ...script,
47
+ SyncPatient: (vars: SyncVars) => {
48
+ sent.push(vars);
49
+ return answer(vars);
50
+ },
51
+ });
52
+ const live = photonOver(client).patient();
53
+ if (hostDetails) await live.sync(hostDetails).catch(() => {});
54
+ const user = userEvent.setup();
55
+ render(<PatientIntakeForm patient={live} query={query} />, { wrapper: withPhoton(client) });
56
+ return { live, user, lastSent: () => sent.at(-1) };
57
+ };
58
+
59
+ const sexField = () => screen.getByRole("combobox", { name: "Sex" });
60
+ const NEEDED = "Needed to add a patient";
61
+
62
+ describe("PatientIntakeForm", () => {
63
+ describe("initial values", () => {
64
+ it("text typed in PatientSearch: fills in first name, last name, date of birth, phone and email from that text", async () => {
65
+ await renderIntakeForm({ query: "Grace Hopper 12/09/1906 4155550172 grace@example.com" });
66
+ expect(screen.getByLabelText("First name")).toHaveValue("Grace");
67
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
68
+ expect(screen.getByLabelText("Date of birth")).toHaveValue("1906-12-09");
69
+ expect(screen.getByLabelText("Phone")).toHaveValue("+1 (415) 555-0172");
70
+ expect(screen.getByLabelText("Email")).toHaveValue("grace@example.com");
71
+ });
72
+
73
+ it("nothing typed in PatientSearch: fills in the fields from the details the patient already has (e.g. details a host passed)", async () => {
74
+ await renderIntakeForm({
75
+ hostDetails: { demographic: { name: { first: "Grace", last: "Hopper" }, sex: "FEMALE" } },
76
+ });
77
+ expect(screen.getByLabelText("First name")).toHaveValue("Grace");
78
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
79
+ expect(sexField()).toHaveValue("FEMALE");
80
+ });
81
+
82
+ it("nothing typed in PatientSearch and no details from a host: every field starts empty", async () => {
83
+ await renderIntakeForm();
84
+ for (const label of ["First name", "Last name", "Date of birth", "Phone", "Email"]) {
85
+ expect(screen.getByLabelText(label)).toHaveValue("");
86
+ }
87
+ expect(sexField()).toHaveValue("");
88
+ });
89
+
90
+ // TODO: Fix the UX here
91
+ // The cursor should be on whatever the first empty required input is
92
+ it("once PatientIntakeForm opens: cursor starts on the Sex field, even when first name, last name and date of birth are empty", async () => {
93
+ // Nothing typed and no host details: first name, last name and date of birth are all empty.
94
+ await renderIntakeForm();
95
+ expect(screen.getByLabelText("First name")).toHaveValue("");
96
+ await waitFor(() => expect(sexField()).toHaveFocus());
97
+ });
98
+ });
99
+
100
+ // TODO: Need a separate, more rigorously tested util (probably Zod schema)
101
+ // for patient input validation
102
+ describe("saving", () => {
103
+ it("Save with required fields empty: each empty required field shows a validation error message", async () => {
104
+ const { user } = await renderIntakeForm({ query: "Grace" });
105
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
106
+ // Last name, date of birth and sex are empty; first name was typed.
107
+ expect(screen.getAllByText(NEEDED)).toHaveLength(3);
108
+ expect(screen.getByLabelText("Last name")).toHaveAttribute("aria-invalid", "true");
109
+ });
110
+
111
+ // Pins today's behavior. The form means to move the cursor to the first field Save is waiting on, but it
112
+ // looks for the first element marked invalid, and with the default building blocks that's the field's
113
+ // wrapper <div>, which can't take focus.
114
+ // TODO: focus the first invalid input, not its wrapper
115
+ it("Save with required fields empty: the cursor stays on the Save button", async () => {
116
+ const { user } = await renderIntakeForm({ query: "Grace" });
117
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
118
+ expect(screen.getByRole("button", { name: "Save patient" })).toHaveFocus();
119
+ });
120
+
121
+ it("after Save, typing into an empty required field: removes the validation error message from that field", async () => {
122
+ const { user } = await renderIntakeForm({ query: "Grace" });
123
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
124
+ await user.type(screen.getByLabelText("Last name"), "Hopper");
125
+ expect(screen.getAllByText(NEEDED)).toHaveLength(2);
126
+ });
127
+
128
+ it("Save with first name, last name, date of birth and sex filled in: the patient is added", async () => {
129
+ const { user, live } = await renderIntakeForm({
130
+ query: "Ada Lovelace 1990-01-01",
131
+ script: { SyncPatient: () => payload("patient", "PatientPayload", ada) },
132
+ });
133
+ await user.selectOptions(sexField(), "FEMALE");
134
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
135
+ await waitFor(() => expect(live.id).toBe("pat_1"));
136
+ expect(screen.queryByText(NEEDED)).not.toBeInTheDocument();
137
+ });
138
+
139
+ // TODO: abstract patient validation to a separate util
140
+ // so we can remove this test
141
+ it("Save with a phone number: the phone number is sent in E.164 format", async () => {
142
+ const { user, lastSent } = await renderIntakeForm({ query: "Grace Hopper 1906-12-09" });
143
+ await user.type(screen.getByLabelText("Phone"), "415-555-0172");
144
+ await user.selectOptions(sexField(), "FEMALE");
145
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
146
+ await waitFor(() => expect(lastSent()?.contact).toEqual({ phone: "+14155550172" }));
147
+ });
148
+
149
+ // Pins today's behavior.
150
+ // TODO: we shouldn't show the browser's own validation
151
+ it("Save with an email that isn't valid: the browser's own validation stops Save, so the patient isn't added", async () => {
152
+ const { user, live } = await renderIntakeForm({
153
+ query: "Ada Lovelace 1990-01-01",
154
+ script: { SyncPatient: () => payload("patient", "PatientPayload", ada) },
155
+ });
156
+ await user.type(screen.getByLabelText("Email"), "not-an-email");
157
+ await user.selectOptions(sexField(), "FEMALE");
158
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
159
+ await new Promise((done) => setTimeout(done, 100));
160
+ expect(live.id).toBeNull();
161
+ });
162
+ });
163
+
164
+ // TODO: Replace this test after implementing more rigorous frontend validation
165
+ // If we still get a server message, add tests for how to display them
166
+ describe("server messages", () => {
167
+ it('the server\'s "still needed" messages for name, date of birth and sex: hidden until all four fields are filled in', async () => {
168
+ const { user } = await renderIntakeForm({
169
+ script: {
170
+ SyncPatient: () =>
171
+ payload("patient", "PatientPayload", null, {
172
+ changes: [
173
+ rejected("demographic.dateOfBirth", "Date of birth is needed"),
174
+ rejected("contact.phone", "Phone isn't valid"),
175
+ ],
176
+ }),
177
+ },
178
+ hostDetails: { contact: { phone: "1" } },
179
+ });
180
+ // Other messages show straight away.
181
+ expect(await screen.findByText(/Phone isn't valid/)).toBeInTheDocument();
182
+ expect(screen.queryByText(/Date of birth is needed/)).not.toBeInTheDocument();
183
+ await user.type(screen.getByLabelText("First name"), "Grace");
184
+ await user.type(screen.getByLabelText("Last name"), "Hopper");
185
+ await user.type(screen.getByLabelText("Date of birth"), "1906-12-09");
186
+ await user.selectOptions(sexField(), "FEMALE");
187
+ expect(screen.getByText(/Date of birth is needed/)).toBeInTheDocument();
188
+ });
189
+ });
190
+ });
191
+
192
+ const renderPatientCard = () =>
193
+ render(<PhotonPatient />, {
194
+ wrapper: withAnalytics(fakeNetworkApiClient({ ...meAsPrescriber, SyncPatient: noMatch }).client),
195
+ });
196
+
197
+ describe("PatientIntakeForm: Field Interaction", () => {
198
+ let analytics: RecordedAnalytics;
199
+ beforeEach(() => {
200
+ analytics = recordAnalytics();
201
+ });
202
+ afterEach(unmountAndRestoreFetch);
203
+
204
+ it("typing in PatientSearch's Find patient field: sends focus, one change and blur events for find_patient's patientSearch field, without what was typed", async () => {
205
+ renderPatientCard();
206
+ await typeInto("Find patient", "Zqxfirst Zqxlast");
207
+
208
+ await analytics.expectEventLog([
209
+ "Field Interaction patientSearch focus",
210
+ "Prescribe Workflow Viewed",
211
+ "Field Interaction patientSearch change",
212
+ "Field Interaction patientSearch blur",
213
+ ]);
214
+ expect(analytics.sentFor("patientSearch")).toEqual([
215
+ expect.objectContaining({ formName: "find_patient", hasValue: false, isOptional: false }),
216
+ expect.objectContaining({ hasValue: true }),
217
+ expect.objectContaining({ hasValue: true, changed: true, durationMs: expect.any(Number) }),
218
+ ]);
219
+ for (const body of analytics.bodies()) expect(body).not.toMatch(/Zqx/i);
220
+ });
221
+
222
+ it("adding a patient: each field visited sends focus, one change and blur events for new_patient_form, without what was typed", async () => {
223
+ renderPatientCard();
224
+ await typeInto("Find patient", "Zqxfirst Zqxlast");
225
+ await userEvent.click(await screen.findByRole("option", { name: /Add new patient/ }));
226
+ await typeInto("First name", "Zqxa");
227
+ await typeInto("Last name", "Zqxb");
228
+ await userEvent.click(screen.getByLabelText("Date of birth"));
229
+ fireEvent.change(screen.getByLabelText("Date of birth"), { target: { value: "1990-01-01" } });
230
+ leaveField();
231
+ await userEvent.selectOptions(screen.getByRole("combobox", { name: "Sex" }), "FEMALE");
232
+ leaveField();
233
+ await typeInto("Phone", "5555550100");
234
+ await typeInto("Email", "zqx@example.com");
235
+
236
+ await analytics.expectEventLog([
237
+ "Field Interaction patientSearch focus",
238
+ "Prescribe Workflow Viewed",
239
+ "Field Interaction patientSearch change",
240
+ "Field Interaction patientSearch blur",
241
+ ...visitedWithoutEditing("firstName"),
242
+ ...visitedWithoutEditing("sex"),
243
+ ...buildEditedEventsFor("firstName"),
244
+ ...buildEditedEventsFor("lastName"),
245
+ ...buildEditedEventsFor("dateOfBirth"),
246
+ ...buildEditedEventsFor("sex"),
247
+ ...buildEditedEventsFor("phone"),
248
+ ...buildEditedEventsFor("email"),
249
+ ]);
250
+ const sent = analytics.fieldInteractions().filter((s) => s.fieldName !== "patientSearch");
251
+ expect(new Set(sent.map((s) => s.formName))).toEqual(new Set(["new_patient_form"]));
252
+ expect(Object.fromEntries(sent.map((s) => [s.fieldName, s.isOptional]))).toEqual({
253
+ firstName: false,
254
+ lastName: false,
255
+ dateOfBirth: false,
256
+ sex: false,
257
+ phone: true,
258
+ email: true,
259
+ });
260
+ for (const body of analytics.bodies()) expect(body).not.toMatch(/Zqx|1990|5555550100|FEMALE/i);
261
+ });
262
+ });