@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,188 @@
1
+ import { useComponents, usePhoton } from "../primitives/index.ts";
2
+ import { AnalyticsWorkflow } from "../analytics/PhotonAnalyticsProvider.tsx";
3
+ import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
4
+ import { SignedIn } from "./SignedIn.tsx";
5
+ import { classify, Patient, type ChangeOption, type PatientInput, type PatientResult } from "@photonhealth/client";
6
+ import { useLive, useOnChange } from "../hooks/index.ts";
7
+ import { useState } from "react";
8
+ import { NotFound, openFailed, toOpen, useOpened, type Given } from "./open.ts";
9
+ import { ChangeList } from "./ChangeList.tsx";
10
+ import { PatientIntakeForm } from "./patient/IntakeForm.tsx";
11
+ import { diagnosisRef, withoutInline } from "./patient/Clinical.tsx";
12
+ import { PatientSummary } from "./patient/Summary.tsx";
13
+
14
+ type PatientClinicalInput = NonNullable<PatientInput["clinical"]>;
15
+
16
+ /**
17
+ * "Who is this patient?" — standalone or inside PhotonOrder. Bound to a live Patient from @photonhealth/client:
18
+ * the one given (`patient`), one opened from what's given (get / update / sync, see `Given`), or a new one to
19
+ * find or add. Before it has a record, every field the prescriber leaves is synced — the server decides: the
20
+ * patient (found, or added), patients it might be (pick one), or what it still needs. Once it has one, edits
21
+ * update it.
22
+ */
23
+ export interface PhotonPatientProps {
24
+ /**
25
+ * The patient: a live Patient (used as given; anything else holding it sees the same changes), its id
26
+ * (`"pat_…"` or `{ id }`: read), its id with fields (that patient updated), or what's known of them without
27
+ * one (synced: found, matched or added).
28
+ */
29
+ patient?: Patient | Given<PatientInput> | null;
30
+ /**
31
+ * The card's patient, once it has a record (found, picked, added, or opened with) and each time that record
32
+ * changes from the backend. `null` on "Change patient": a card given `patient` leaves what's next to the
33
+ * host (pass it a new one); otherwise it starts over itself.
34
+ */
35
+ onPatient?: (patient: Patient | null) => void;
36
+ /** Read-only (e.g. on a sent order): nothing to edit, and no "Change patient". */
37
+ locked?: boolean;
38
+ /**
39
+ * The patient is fixed — e.g. beside the host's own view of them: no "Change patient", but still editable.
40
+ * (An embed whose link names the patient by id is fixed.)
41
+ */
42
+ fixed?: boolean;
43
+ }
44
+
45
+ /** A patient card. */
46
+ export function PhotonPatient(props: PhotonPatientProps) {
47
+ return (
48
+ <AnalyticsWorkflow card="PhotonPatient" viewedProperties={viewedPropertiesFromCardProps(props)}>
49
+ <SignedIn>
50
+ <PatientCard {...props} />
51
+ </SignedIn>
52
+ </AnalyticsWorkflow>
53
+ );
54
+ }
55
+
56
+ /** A stable key per live object: a different patient object gets a fresh form. */
57
+ const objectKeys = new WeakMap<object, number>();
58
+ let nextKey = 0;
59
+ const keyOf = (obj: object) => {
60
+ if (!objectKeys.has(obj)) objectKeys.set(obj, ++nextKey);
61
+ return objectKeys.get(obj)!;
62
+ };
63
+
64
+ const patientOf = (r: PatientResult) => r.patient;
65
+
66
+ /**
67
+ * PhotonPatient, and what only PhotonOrder gives it: the server's request for a way to reach the patient (its
68
+ * reason), which opens the contact fields. Internal: the package index exports only PhotonPatient.
69
+ */
70
+ export function PatientCard({
71
+ patient,
72
+ onPatient,
73
+ locked,
74
+ fixed,
75
+ addressRequest,
76
+ notFound,
77
+ }: PhotonPatientProps & {
78
+ addressRequest?: string | null;
79
+ /** The patient it was given by id isn't there (PhotonOrder's): said in the form, with the matches. */
80
+ notFound?: NotFound | null;
81
+ }) {
82
+ const { Alert, Card, CardHeader } = useComponents();
83
+ const ph = usePhoton();
84
+ // A new patient to find or add when the host gives none (and none to open) — and after "Change patient",
85
+ // when the host didn't give one.
86
+ const shared = patient instanceof Patient ? patient : null;
87
+ const given = toOpen<PatientInput>(patient, Boolean(shared));
88
+ const [own, setOwn] = useState<Patient | null>(() => (shared || given ? null : ph.patient()));
89
+ const { opened, error: openError } = useOpened(ph.patient, given, patientOf, "patient");
90
+ // Given by id and not there: someone to find or add instead, the reason said in the form — where its matches,
91
+ // and anything else the server says, show. (Read-only, there's nothing to find: just the reason.)
92
+ const missing = openError instanceof NotFound && !locked ? openError : null;
93
+ // One patient object, always: the one given, the one opened from what's given, or the card's own — made once
94
+ // there's none to show (nothing given, "Change patient", or an id the server doesn't have).
95
+ if (missing && !own && !shared) setOwn(ph.patient());
96
+ // The host gives another patient: that one, not the card's own.
97
+ const givenKey = JSON.stringify(given);
98
+ const [ownFor, setOwnFor] = useState(givenKey);
99
+ if (givenKey !== ownFor) {
100
+ setOwnFor(givenKey);
101
+ if (given && own) setOwn(null);
102
+ }
103
+ const live = shared ?? own ?? opened;
104
+ const snap = useLive(live);
105
+ const record = snap?.state ?? null;
106
+ useOnChange(live, (p) => p.state, onPatient);
107
+
108
+ if (openError && !missing)
109
+ return <Alert tone="critical" title={openFailed("patient", openError)} description={openError.message} />;
110
+ if (!live || !snap) {
111
+ return (
112
+ <Card divided>
113
+ <CardHeader title="Patient" description="Loading…" />
114
+ </Card>
115
+ );
116
+ }
117
+
118
+ const changes = classify(snap.changes);
119
+ const update = (input: Omit<PatientInput, "id">) => void live.update(input).catch(() => {}); // failures land on the object
120
+ const patchClinical = (clinical: PatientClinicalInput) => update({ clinical });
121
+ const choose = (option: ChangeOption) => void live.choose(option).catch(() => {});
122
+
123
+ if (record) {
124
+ const messages = withoutInline(changes);
125
+ const hasMessages =
126
+ messages.needsChoice.length + messages.blocking.length + messages.advisories.length > 0 || Boolean(snap.error);
127
+ return (
128
+ <PatientSummary
129
+ key={record.id}
130
+ patient={record}
131
+ pickedNames={snap.pickedNames}
132
+ saving={snap.status === "saving"}
133
+ changes={
134
+ // Only when there's something to say — the card has no body otherwise.
135
+ hasMessages && (
136
+ <>
137
+ <ChangeList changes={messages} onChoose={choose} busy={snap.status === "saving"} />
138
+ {/* A failed save must never be silent (e.g. a rejected clinical patch). */}
139
+ {snap.error && <Alert tone="critical" title="Couldn't save" description={snap.error.message} />}
140
+ </>
141
+ )
142
+ }
143
+ choices={changes.needsChoice}
144
+ problems={changes.blocking}
145
+ onChoose={choose}
146
+ onAddAllergy={(name) => patchClinical({ allergies: { add: [{ name }] } })}
147
+ onConfirmNone={(list) => patchClinical({ [list]: { none: true } })}
148
+ onRemoveAllergy={(a) => patchClinical({ allergies: { remove: [{ id: a.id }] } })}
149
+ onRemoveMedication={(m) => patchClinical({ medications: { remove: [{ id: m.id, status: m.status }] } })}
150
+ onAddDiagnosis={(text) => patchClinical({ diagnoses: { add: [diagnosisRef(text)] } })}
151
+ onRemoveDiagnosis={(d) => patchClinical({ diagnoses: { remove: [{ id: d.id }] } })}
152
+ onAddBenefit={(b) => update({ benefits: { add: [b] } })}
153
+ onRemoveBenefit={(b) => update({ benefits: { remove: [{ id: b.id }] } })}
154
+ onConfirmNoBenefits={() => update({ benefits: { none: true } })}
155
+ onAddMedication={(name) => patchClinical({ medications: { add: [{ name, status: "ACTIVE" }] } })}
156
+ onSaveContact={(contact) => update({ contact })}
157
+ onSaveDetails={(details) => update({ demographic: details })}
158
+ addressRequest={locked ? null : (addressRequest ?? null)}
159
+ readOnly={locked}
160
+ onChangePatient={
161
+ locked || fixed
162
+ ? undefined
163
+ : () => {
164
+ onPatient?.(null); // given a patient, the host decides what's next
165
+ if (!shared) setOwn(ph.patient());
166
+ }
167
+ }
168
+ />
169
+ );
170
+ }
171
+
172
+ // A different patient object (e.g. after "Change patient") starts a fresh form.
173
+ const why = notFound ?? missing;
174
+ return (
175
+ <PatientIntakeForm
176
+ key={keyOf(live)}
177
+ patient={live}
178
+ notice={why && { title: openFailed("patient", why), description: why.message }}
179
+ />
180
+ );
181
+ }
182
+
183
+ /**
184
+ * Find or add the patient. Each field the prescriber leaves (and Enter) sends everything known so far to the
185
+ * live Patient — one query that searches and syncs. The server decides: the patient, patients it might be
186
+ * (listed to pick from), or what it still needs (shown; an address only when it asks). Fields left, not
187
+ * keystrokes: a query with enough to add a patient adds them.
188
+ */
@@ -0,0 +1,116 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, render, screen, waitFor, within } from "@testing-library/react";
3
+ import userEvent from "@testing-library/user-event";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { fakeNetworkApiClient, payload } from "@photonhealth/client/testing";
6
+ import { PhotonPrescription } from "../index.ts";
7
+ import { fakeNetworkApi, patient } from "../../test/cards.fixtures.tsx";
8
+ import {
9
+ edited,
10
+ leaveField,
11
+ meAsPrescriber,
12
+ recordAnalytics,
13
+ type RecordedAnalytics,
14
+ typeInto,
15
+ unmountAndRestoreFetch,
16
+ withAnalytics,
17
+ } from "../../test/analytics.fixtures.tsx";
18
+
19
+ // The card as a workflow: its analytics. The card itself is tested in prescription/PrescriptionCard.test.tsx.
20
+
21
+ afterEach(cleanup);
22
+
23
+ const settledDrugRow = (row: RegExp) =>
24
+ waitFor(() => {
25
+ const button = screen.getByRole<HTMLButtonElement>("button", { name: row });
26
+ expect(button.disabled).toBe(false);
27
+ return button;
28
+ });
29
+
30
+ const clickDrugRowOnceSettled = async (row: RegExp) => {
31
+ await userEvent.click(await settledDrugRow(row));
32
+ };
33
+
34
+ describe("PhotonPrescription: Field Interaction", () => {
35
+ let analytics: RecordedAnalytics;
36
+ beforeEach(() => {
37
+ analytics = recordAnalytics();
38
+ });
39
+ afterEach(unmountAndRestoreFetch);
40
+
41
+ it("searching Treatment and picking a one-product drug from its list is one visit: focus, change, blur", async () => {
42
+ const { client } = fakeNetworkApiClient({
43
+ ...meAsPrescriber,
44
+ GetPatient: () => payload("patient", "PatientPayload", patient),
45
+ ...fakeNetworkApi({
46
+ prescriptions: {
47
+ amo: [
48
+ ["Amondys", "Injection", "45 MG"],
49
+ ["Amoxicillin", "Capsule", "500 MG"],
50
+ ["Amoxicillin", "Tablet", "875 MG"],
51
+ ],
52
+ },
53
+ }),
54
+ });
55
+ render(<PhotonPrescription patient="pat_1" />, { wrapper: withAnalytics(client) });
56
+
57
+ await userEvent.click(await screen.findByLabelText("Treatment"));
58
+ await userEvent.keyboard("Amo");
59
+ await clickDrugRowOnceSettled(/^Amondys/);
60
+ await screen.findByLabelText("Directions (sig)");
61
+ leaveField();
62
+
63
+ await analytics.expectEventLog(["Prescribe Workflow Viewed", ...edited("treatment")]);
64
+ expect(analytics.sentFor("treatment").at(-1)).toMatchObject({ hasValue: true, changed: true });
65
+ });
66
+
67
+ it("each field sends focus, one change and blur with its documented name, and nothing typed", async () => {
68
+ const { client } = fakeNetworkApiClient({
69
+ ...meAsPrescriber,
70
+ GetPatient: () => payload("patient", "PatientPayload", patient),
71
+ ...fakeNetworkApi({
72
+ prescriptions: {
73
+ amox: [
74
+ ["Amoxicillin", "Capsule", "250 MG"],
75
+ ["Amoxicillin", "Capsule", "500 MG"],
76
+ ["Amoxicillin", "Tablet", "875 MG"],
77
+ ],
78
+ },
79
+ }),
80
+ });
81
+ render(<PhotonPrescription patient="pat_1" />, { wrapper: withAnalytics(client) });
82
+
83
+ await userEvent.click(await screen.findByLabelText("Treatment"));
84
+ await userEvent.keyboard("amox");
85
+ await clickDrugRowOnceSettled(/^Amoxicillin/);
86
+ await userEvent.click(within(await screen.findByRole("group", { name: "Form" })).getByText("Capsule"));
87
+ await userEvent.click(within(screen.getByRole("group", { name: "Strength" })).getByText("500 mg"));
88
+ await screen.findByLabelText("Directions (sig)");
89
+ await typeInto("Directions (sig)", "Zqx once daily");
90
+ await typeInto("Quantity", "14");
91
+ await typeInto("Unit", "Zqxunit");
92
+ await typeInto("Days supply", "7");
93
+ await typeInto("Refills", "1");
94
+ await userEvent.click(screen.getByRole("checkbox", { name: "Dispense as written" }));
95
+ leaveField();
96
+
97
+ await analytics.expectEventLog([
98
+ "Prescribe Workflow Viewed",
99
+ ...edited("treatment"),
100
+ ...edited("form"),
101
+ ...edited("strength"),
102
+ ...edited("instructions"),
103
+ ...edited("dispenseQuantity"),
104
+ ...edited("dispenseUnit"),
105
+ ...edited("daysSupply"),
106
+ ...edited("refills"),
107
+ ...edited("dispenseAsWritten"),
108
+ ]);
109
+ expect(new Set(analytics.fieldInteractions().map((sent) => sent.formName))).toEqual(
110
+ new Set(["add_prescription_form"]),
111
+ );
112
+ expect(analytics.sentFor("daysSupply").map((sent) => sent.isOptional)).toEqual([true, true, true]);
113
+ expect(analytics.sentFor("instructions").at(-1)).toMatchObject({ durationMs: expect.any(Number), changed: true });
114
+ for (const body of analytics.bodies()) expect(body).not.toMatch(/amox|Zqx|"14"/);
115
+ });
116
+ });
@@ -0,0 +1,45 @@
1
+ import { AnalyticsWorkflow } from "../analytics/PhotonAnalyticsProvider.tsx";
2
+ import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
3
+ import { SignedIn } from "./SignedIn.tsx";
4
+ import { type Patient, type Prescription, type PatientInput, type PrescriptionInput } from "@photonhealth/client";
5
+ import { PrescriptionCard } from "./prescription/PrescriptionCard.tsx";
6
+ import { type Given } from "./open.ts";
7
+
8
+ /**
9
+ * One prescription: free-text drug → the server resolves it (or offers choices) → sig and dispense →
10
+ * screening → Sign. Standalone or inside PhotonOrder. Bound to a live Prescription from @photonhealth/client: the
11
+ * one given (`prescription` — a line before its record, or an existing one), one opened from its id and / or an
12
+ * input (get / sync / update), or else a new line. The rules are the object's; this renders it.
13
+ */
14
+ export interface PhotonPrescriptionProps {
15
+ /**
16
+ * The prescription: a live Prescription (used as given; anything else holding it sees the same changes), its
17
+ * id (`"rx_…"` or `{ id }`: read), its id with fields (that prescription updated), or fields without one
18
+ * (synced — e.g. `{ templateId }` or `{ treatment: { name } }`).
19
+ */
20
+ prescription?: Prescription | Given<PrescriptionInput> | null;
21
+ /**
22
+ * Who it's for — given as a patient card's `patient` is. Until it's known, a new line only looks drugs up
23
+ * (a line from an order already knows).
24
+ */
25
+ patient?: Patient | Given<PatientInput> | null;
26
+ /** Read-only (e.g. on a finalized order). A signed prescription is always read-only. */
27
+ locked?: boolean;
28
+ /** The prescriber signed it on this card — once per prescription. */
29
+ onSigned?: (prescription: Prescription) => void;
30
+ /**
31
+ * The card's prescription, once it has a record and each time that record changes from the backend
32
+ * (created, saved, signed).
33
+ */
34
+ onPrescription?: (prescription: Prescription) => void;
35
+ }
36
+
37
+ export function PhotonPrescription(props: PhotonPrescriptionProps) {
38
+ return (
39
+ <AnalyticsWorkflow card="PhotonPrescription" viewedProperties={viewedPropertiesFromCardProps(props)}>
40
+ <SignedIn>
41
+ <PrescriptionCard {...props} />
42
+ </SignedIn>
43
+ </AnalyticsWorkflow>
44
+ );
45
+ }
@@ -0,0 +1,28 @@
1
+ import { useComponents } from "../primitives/index.ts";
2
+ import type { ScreeningAlert } from "@photonhealth/client";
3
+
4
+ const toneOf = (severity: ScreeningAlert["severity"]) =>
5
+ severity === "MINOR" ? "info" : severity === "MODERATE" ? "warning" : "critical";
6
+
7
+ /** What screening found, each in its severity's tone. Shown until acknowledged (signed, or sent); they never block. */
8
+ export function ScreeningAlerts({ alerts }: { alerts: readonly ScreeningAlert[] }) {
9
+ const { Alert, Stack } = useComponents();
10
+ if (!alerts.length) return null;
11
+ return (
12
+ <Stack gap="2">
13
+ {alerts.map((a, i) => (
14
+ <Alert
15
+ key={i}
16
+ tone={toneOf(a.severity)}
17
+ title={`${a.type.toLowerCase()} · ${a.severity.toLowerCase()}`}
18
+ description={
19
+ <>
20
+ {a.description}
21
+ {a.involvedEntities.length > 0 && ` (${a.involvedEntities.map((e) => e.name).join(", ")})`}
22
+ </>
23
+ }
24
+ />
25
+ ))}
26
+ </Stack>
27
+ );
28
+ }
@@ -0,0 +1,144 @@
1
+ import type { PhotonError, Session } from "@photonhealth/client";
2
+ import { useLayoutEffect, useState, useSyncExternalStore, type ReactNode } from "react";
3
+ import { useLive } from "../hooks/index.ts";
4
+ import { useCheckFailure, useComponents, useOrganization, usePhoton } from "../primitives/index.ts";
5
+
6
+ /**
7
+ * A card, once its calls can go out: signed in (to an organization) and accepted by network-api — or at once, when
8
+ * the host signs in itself. Until then, the first card in the page offers "Sign in to <Env>" ("Sign in to Photon"
9
+ * in production; a click: a redirect to Auth0, or a popup inside an iframe) and the rest render nothing; if that
10
+ * card goes, the next one offers it. When network-api can't be reached (or can't answer), it says so and offers
11
+ * "Try again" instead.
12
+ */
13
+ export function SignedIn({ children }: { children: ReactNode }) {
14
+ const ph = usePhoton();
15
+ const session = ph.session;
16
+ const snap = useLive(session);
17
+ const failure = useCheckFailure();
18
+ const refused = failure?.error.kind === "unauthorized" ? failure.error : null;
19
+ const unreachable = failure && !refused ? failure : null;
20
+ const organization = useOrganization();
21
+ const user = snap?.status === "signed-in" ? snap.user : null;
22
+ // Signed in to an organization — the one the provider names, when it names one.
23
+ const elsewhere = Boolean(user?.organization && organization && user.organization !== organization);
24
+ const ready = !session || (user?.organization && !elsewhere && !failure);
25
+ const first = useFirstCard(session, !ready);
26
+ if (ready) return <>{children}</>;
27
+ if (!session || !snap || snap.status === "starting" || !first) return null;
28
+ if (unreachable) return <Unreachable failure={unreachable} network={ph.environment} />;
29
+ const problem: { title: string; error: PhotonError | null } | null = refused
30
+ ? { title: "Photon didn't accept this sign-in", error: refused }
31
+ : user && !user.organization
32
+ ? { title: "No organization on this sign-in", error: null }
33
+ : elsewhere
34
+ ? { title: `Signed in to another organization (${user!.organization})`, error: null }
35
+ : snap.error
36
+ ? { title: "Sign-in failed", error: snap.error }
37
+ : null;
38
+ return (
39
+ <SignIn
40
+ session={session}
41
+ environment={ph.environment?.name ?? "photon"}
42
+ organization={organization}
43
+ signingIn={snap.status === "signing-in"}
44
+ problem={problem}
45
+ />
46
+ );
47
+ }
48
+
49
+ function SignIn({
50
+ session,
51
+ environment,
52
+ organization,
53
+ signingIn,
54
+ problem,
55
+ }: {
56
+ session: Session;
57
+ environment: string;
58
+ organization: string | null;
59
+ signingIn: boolean;
60
+ problem: { title: string; error: PhotonError | null } | null;
61
+ }) {
62
+ const { Alert, Button, Card, CardBody, Row, Stack } = useComponents();
63
+ return (
64
+ <Card>
65
+ <CardBody>
66
+ <Stack gap="3">
67
+ {problem && <Alert tone="critical" title={problem.title} description={problem.error?.message} />}
68
+ <Row>
69
+ <Button loading={signingIn} onClick={() => void session.signIn(organization ? { organization } : {})}>
70
+ Sign in to {environment[0]!.toUpperCase() + environment.slice(1)}
71
+ </Button>
72
+ </Row>
73
+ </Stack>
74
+ </CardBody>
75
+ </Card>
76
+ );
77
+ }
78
+
79
+ /** network-api didn't answer the sign-in's check (offline, DNS, CORS, a 5xx) — nothing a new sign-in fixes. */
80
+ function Unreachable({
81
+ failure: { error, checking, retry },
82
+ network,
83
+ }: {
84
+ failure: NonNullable<ReturnType<typeof useCheckFailure>>;
85
+ network: { networkApiUrl: string } | null;
86
+ }) {
87
+ const { Alert, Button, Card, CardBody, Row, Stack } = useComponents();
88
+ const host = network ? new URL(network.networkApiUrl).host : null;
89
+ return (
90
+ <Card>
91
+ <CardBody>
92
+ <Stack gap="3">
93
+ <Alert
94
+ tone="critical"
95
+ title="Can't reach the Photon network"
96
+ description={
97
+ error.kind === "network"
98
+ ? `${host ?? "network-api"} didn't respond. Check your connection, then try again.`
99
+ : error.message
100
+ }
101
+ />
102
+ <Row>
103
+ <Button loading={checking} onClick={retry}>
104
+ Try again
105
+ </Button>
106
+ </Row>
107
+ </Stack>
108
+ </CardBody>
109
+ </Card>
110
+ );
111
+ }
112
+
113
+ // ---- which card offers sign-in: the first one in the page, per sign-in ----
114
+
115
+ const lines = new WeakMap<Session, { cards: symbol[]; listeners: Set<() => void> }>();
116
+ const lineOf = (session: Session) => {
117
+ let line = lines.get(session);
118
+ if (!line) lines.set(session, (line = { cards: [], listeners: new Set() }));
119
+ return line;
120
+ };
121
+
122
+ /** Whether this card is first in line (cards join as they mount, in the order the page lays them out). */
123
+ function useFirstCard(session: Session | null, waiting: boolean): boolean {
124
+ const [me] = useState(() => Symbol("card"));
125
+ useLayoutEffect(() => {
126
+ if (!session || !waiting) return;
127
+ const line = lineOf(session);
128
+ line.cards.push(me);
129
+ line.listeners.forEach((l) => l());
130
+ return () => {
131
+ line.cards = line.cards.filter((card) => card !== me);
132
+ line.listeners.forEach((l) => l());
133
+ };
134
+ }, [session, waiting, me]);
135
+ return useSyncExternalStore(
136
+ (listener) => {
137
+ if (!session) return () => {};
138
+ const line = lineOf(session);
139
+ line.listeners.add(listener);
140
+ return () => line.listeners.delete(listener);
141
+ },
142
+ () => (session ? lineOf(session).cards[0] === me : false),
143
+ );
144
+ }
@@ -0,0 +1,23 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ const MIN_SPINNER_MS = 600;
4
+
5
+ /**
6
+ * What's working — e.g. the field whose call is in flight, which shows a spinner — held for at least
7
+ * MIN_SPINNER_MS after it's done: calls often return in ~150ms, and a spinner that flickers past reads as
8
+ * nothing happening.
9
+ */
10
+ export function useHeldActivity(activity: string | null): string | null {
11
+ const [held, setHeld] = useState(activity);
12
+ const [last, setLast] = useState(activity);
13
+ if (activity !== last) {
14
+ setLast(activity);
15
+ if (activity) setHeld(activity);
16
+ }
17
+ useEffect(() => {
18
+ if (activity || !held) return;
19
+ const timer = setTimeout(() => setHeld(null), MIN_SPINNER_MS);
20
+ return () => clearTimeout(timer);
21
+ }, [activity, held]);
22
+ return activity ?? held;
23
+ }