@photonhealth/react 2.0.0-rc.1 → 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 (185) hide show
  1. package/README.md +35 -8
  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 +16 -0
  6. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
  7. package/dist/analytics/PhotonAnalyticsProvider.js +57 -0
  8. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
  9. package/dist/analytics/fieldInteraction.d.ts +18 -0
  10. package/dist/analytics/fieldInteraction.d.ts.map +1 -0
  11. package/dist/analytics/fieldInteraction.js +102 -0
  12. package/dist/analytics/fieldInteraction.js.map +1 -0
  13. package/dist/analytics/tracker.d.ts +17 -0
  14. package/dist/analytics/tracker.d.ts.map +1 -0
  15. package/dist/analytics/tracker.js +36 -0
  16. package/dist/analytics/tracker.js.map +1 -0
  17. package/dist/analytics/viewed.d.ts +11 -0
  18. package/dist/analytics/viewed.d.ts.map +1 -0
  19. package/dist/analytics/viewed.js +16 -0
  20. package/dist/analytics/viewed.js.map +1 -0
  21. package/dist/components/PhotonOrder.d.ts.map +1 -1
  22. package/dist/components/PhotonOrder.js +20 -16
  23. package/dist/components/PhotonOrder.js.map +1 -1
  24. package/dist/components/PhotonPatient.d.ts.map +1 -1
  25. package/dist/components/PhotonPatient.js +4 -2
  26. package/dist/components/PhotonPatient.js.map +1 -1
  27. package/dist/components/PhotonPrescription.d.ts +1 -12
  28. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  29. package/dist/components/PhotonPrescription.js +7 -360
  30. package/dist/components/PhotonPrescription.js.map +1 -1
  31. package/dist/components/format.d.ts +2 -2
  32. package/dist/components/format.js +2 -2
  33. package/dist/components/index.d.ts +1 -1
  34. package/dist/components/index.d.ts.map +1 -1
  35. package/dist/components/index.js +1 -1
  36. package/dist/components/index.js.map +1 -1
  37. package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
  38. package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
  39. package/dist/components/order/DraftOrderPrompt.js +26 -0
  40. package/dist/components/order/DraftOrderPrompt.js.map +1 -0
  41. package/dist/components/patient/Benefits.d.ts.map +1 -1
  42. package/dist/components/patient/Benefits.js +2 -1
  43. package/dist/components/patient/Benefits.js.map +1 -1
  44. package/dist/components/patient/Clinical.d.ts +3 -2
  45. package/dist/components/patient/Clinical.d.ts.map +1 -1
  46. package/dist/components/patient/Clinical.js +21 -20
  47. package/dist/components/patient/Clinical.js.map +1 -1
  48. package/dist/components/patient/IntakeForm.d.ts.map +1 -1
  49. package/dist/components/patient/IntakeForm.js +52 -43
  50. package/dist/components/patient/IntakeForm.js.map +1 -1
  51. package/dist/components/patient/Summary.d.ts +1 -1
  52. package/dist/components/patient/Summary.d.ts.map +1 -1
  53. package/dist/components/patient/Summary.js +13 -3
  54. package/dist/components/patient/Summary.js.map +1 -1
  55. package/dist/components/patient/fields.d.ts +1 -2
  56. package/dist/components/patient/fields.d.ts.map +1 -1
  57. package/dist/components/patient/fields.js +2 -1
  58. package/dist/components/patient/fields.js.map +1 -1
  59. package/dist/components/patient/query.d.ts +14 -0
  60. package/dist/components/patient/query.d.ts.map +1 -1
  61. package/dist/components/patient/query.js +5 -0
  62. package/dist/components/patient/query.js.map +1 -1
  63. package/dist/components/prescription/PrescriptionCard.d.ts +45 -0
  64. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
  65. package/dist/components/prescription/PrescriptionCard.js +179 -0
  66. package/dist/components/prescription/PrescriptionCard.js.map +1 -0
  67. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
  68. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
  69. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
  70. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
  71. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
  72. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
  73. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
  74. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
  75. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
  76. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
  77. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
  78. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
  79. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
  80. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
  81. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
  82. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
  83. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
  84. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
  85. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
  86. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
  87. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
  88. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
  89. package/dist/components/{TreatmentPicker.js → prescription/TreatmentSearch/TreatmentPicker.js} +113 -105
  90. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
  91. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
  92. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
  93. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
  94. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
  95. package/dist/components/schemaErrors.d.ts +12 -0
  96. package/dist/components/schemaErrors.d.ts.map +1 -0
  97. package/dist/components/schemaErrors.js +24 -0
  98. package/dist/components/schemaErrors.js.map +1 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +1 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/meta/version.d.ts +5 -0
  104. package/dist/meta/version.d.ts.map +1 -0
  105. package/dist/meta/version.js +5 -0
  106. package/dist/meta/version.js.map +1 -0
  107. package/dist/primitives/PhotonProvider.d.ts +3 -1
  108. package/dist/primitives/PhotonProvider.d.ts.map +1 -1
  109. package/dist/primitives/PhotonProvider.js +23 -11
  110. package/dist/primitives/PhotonProvider.js.map +1 -1
  111. package/dist/primitives/defaults.d.ts.map +1 -1
  112. package/dist/primitives/defaults.js +6 -3
  113. package/dist/primitives/defaults.js.map +1 -1
  114. package/dist/primitives/photonContext.d.ts +3 -0
  115. package/dist/primitives/photonContext.d.ts.map +1 -0
  116. package/dist/primitives/photonContext.js +3 -0
  117. package/dist/primitives/photonContext.js.map +1 -0
  118. package/dist/primitives/types.d.ts +15 -3
  119. package/dist/primitives/types.d.ts.map +1 -1
  120. package/dist/primitives/types.js.map +1 -1
  121. package/dist/primitives/useProvidedPhoton.d.ts +8 -0
  122. package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
  123. package/dist/primitives/useProvidedPhoton.js +8 -0
  124. package/dist/primitives/useProvidedPhoton.js.map +1 -0
  125. package/dist/styles.css +45 -3
  126. package/dist/test-utils/contract.d.ts.map +1 -1
  127. package/dist/test-utils/contract.js +23 -2
  128. package/dist/test-utils/contract.js.map +1 -1
  129. package/package.json +5 -3
  130. package/src/adapters/tailwind.tsx +52 -24
  131. package/src/analytics/PhotonAnalyticsProvider.test.tsx +191 -0
  132. package/src/analytics/PhotonAnalyticsProvider.tsx +96 -0
  133. package/src/analytics/fieldInteraction.test.tsx +184 -0
  134. package/src/analytics/fieldInteraction.tsx +148 -0
  135. package/src/analytics/tracker.test.ts +52 -0
  136. package/src/analytics/tracker.ts +42 -0
  137. package/src/analytics/viewed.ts +27 -0
  138. package/src/components/PhotonOrder.test.tsx +256 -0
  139. package/src/components/PhotonOrder.tsx +45 -30
  140. package/src/components/PhotonPatient.tsx +11 -7
  141. package/src/components/PhotonPrescription.test.tsx +116 -0
  142. package/src/components/PhotonPrescription.tsx +10 -570
  143. package/src/components/format.ts +2 -2
  144. package/src/components/index.ts +1 -1
  145. package/src/components/order/DraftOrderPrompt.test.tsx +80 -0
  146. package/src/components/order/DraftOrderPrompt.tsx +81 -0
  147. package/src/components/patient/Benefits.tsx +21 -13
  148. package/src/components/patient/Clinical.tsx +31 -26
  149. package/src/components/patient/IntakeForm.test.tsx +89 -0
  150. package/src/components/patient/IntakeForm.tsx +168 -136
  151. package/src/components/patient/Summary.test.tsx +106 -0
  152. package/src/components/patient/Summary.tsx +54 -34
  153. package/src/components/patient/fields.tsx +52 -38
  154. package/src/components/patient/query.ts +6 -0
  155. package/src/components/prescription/PrescriptionCard.test.tsx +85 -0
  156. package/src/components/prescription/PrescriptionCard.tsx +347 -0
  157. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +85 -0
  158. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
  159. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +209 -0
  160. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
  161. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +456 -0
  162. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
  163. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
  164. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
  165. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +75 -0
  166. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
  167. package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
  168. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +699 -0
  169. package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
  170. package/src/components/schemaErrors.test.ts +49 -0
  171. package/src/components/schemaErrors.ts +33 -0
  172. package/src/index.ts +2 -0
  173. package/src/meta/version.test.ts +10 -0
  174. package/src/meta/version.ts +4 -0
  175. package/src/primitives/PhotonProvider.tsx +30 -15
  176. package/src/primitives/defaults.tsx +44 -21
  177. package/src/primitives/photonContext.ts +4 -0
  178. package/src/primitives/types.ts +15 -3
  179. package/src/primitives/useProvidedPhoton.ts +21 -0
  180. package/src/styles.css +45 -3
  181. package/src/test-utils/contract.tsx +45 -2
  182. package/dist/components/TreatmentPicker.d.ts +0 -45
  183. package/dist/components/TreatmentPicker.d.ts.map +0 -1
  184. package/dist/components/TreatmentPicker.js.map +0 -1
  185. package/src/components/TreatmentPicker.tsx +0 -350
@@ -1,29 +1,9 @@
1
- import { useComponents, usePhoton } from "../primitives/index.ts";
1
+ import { AnalyticsWorkflow } from "../analytics/PhotonAnalyticsProvider.tsx";
2
+ import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
2
3
  import { SignedIn } from "./SignedIn.tsx";
3
- import {
4
- classify,
5
- Patient,
6
- Prescription,
7
- type Change,
8
- type ChangeOption,
9
- type PatientInput,
10
- type PatientResult,
11
- type PrescriptionEdits,
12
- type PrescriptionInput,
13
- type PrescriptionRecord,
14
- type PrescriptionResult,
15
- } from "@photonhealth/client";
16
- import { useLatestCallback, useLive, useOnChange } from "../hooks/index.ts";
17
- import { useEffect, useRef, useState, type ReactNode } from "react";
18
- import { useHeldActivity } from "./activity.ts";
19
- import { FEW, searchKeys, SearchResults, useTypeAhead } from "./search.tsx";
20
- import { focusProps, searchProps } from "./flow.ts";
21
- import { NotFound, openFailed, toOpen, useOpened, type Given } from "./open.ts";
22
- import { treatmentHeading } from "./display.ts";
23
- import { dispenseSummary } from "./format.ts";
24
- import { ChangeList } from "./ChangeList.tsx";
25
- import { ScreeningAlerts } from "./ScreeningAlerts.tsx";
26
- import { TreatmentPicker, type TreatmentPickerHandle } from "./TreatmentPicker.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";
27
7
 
28
8
  /**
29
9
  * One prescription: free-text drug → the server resolves it (or offers choices) → sig and dispense →
@@ -54,552 +34,12 @@ export interface PhotonPrescriptionProps {
54
34
  onPrescription?: (prescription: Prescription) => void;
55
35
  }
56
36
 
57
- /** What PhotonOrder also gives each of its lines — not part of the public card. */
58
- interface RxLineProps extends PhotonPrescriptionProps {
59
- onRemove?: () => void;
60
- /** Put the cursor in Treatment (a line the prescriber just added). */
61
- autoFocus?: boolean;
62
- /** Put the cursor in Treatment each time this changes (e.g. a patient was just picked). */
63
- focusSignal?: number;
64
- }
65
-
66
37
  export function PhotonPrescription(props: PhotonPrescriptionProps) {
67
38
  return (
68
- <SignedIn>
69
- <RxLine {...props} />
70
- </SignedIn>
71
- );
72
- }
73
-
74
- function StatusBadge({ rx }: { rx: PrescriptionRecord | null }) {
75
- const { Badge } = useComponents();
76
- if (!rx) return null;
77
- if (rx.signing.state === "SIGNED")
78
- return (
79
- <Badge tone="success" icon="check">
80
- Signed
81
- </Badge>
82
- );
83
- if (rx.signing.state === "INVALIDATED_SIGN") return <Badge tone="warning">Changed since signing</Badge>;
84
- // No tag for screening: its alerts are listed above the sig. Nor for nothing found: network-api doesn't screen
85
- // allergies without an RxNorm id (and doesn't say which), so "No alerts" could read as a clinical check that
86
- // didn't happen (docs/api-gaps.md).
87
- return null;
88
- }
89
-
90
- const prescriptionOf = (r: PrescriptionResult) => r.prescription;
91
- const patientOf = (r: PatientResult) => r.patient;
92
- const num = (value: string) => (value.trim() === "" ? undefined : Number(value));
93
-
94
- /** PhotonPrescription, with PhotonOrder's extras (internal: the package index exports only PhotonPrescription). */
95
- export function RxLine({
96
- patient,
97
- prescription,
98
- locked,
99
- onSigned,
100
- onPrescription,
101
- onRemove,
102
- autoFocus,
103
- focusSignal,
104
- }: RxLineProps) {
105
- const { Alert, Button, Card, CardBody, CardFooter, CardHeader, Checkbox, Grid, Input, Select, Stack, Textarea } =
106
- useComponents();
107
- const ph = usePhoton();
108
- // A new line when the host gives no prescription (and none to open).
109
- const shared = prescription instanceof Prescription ? prescription : null;
110
- const given = toOpen<PrescriptionInput>(prescription, Boolean(shared));
111
- const [own] = useState(() => (shared || given ? null : ph.prescription()));
112
- const { opened, error: rxError } = useOpened(ph.prescription, given, prescriptionOf, "prescription");
113
- // Who it's for, opened the same way; its id once it has a record.
114
- const sharedPatient = patient instanceof Patient ? patient : null;
115
- const { opened: openedPatient, error: patientError } = useOpened(
116
- ph.patient,
117
- toOpen<PatientInput>(patient, Boolean(sharedPatient)),
118
- patientOf,
119
- "patient",
120
- );
121
- const patientSnap = useLive(sharedPatient ?? openedPatient);
122
- // Not given: leave it (a line from an order has its own). Given: its id once it has one; null clears it.
123
- const patientId = patient === undefined ? undefined : patient === null ? null : patientSnap?.state?.id;
124
- const openError = rxError ?? patientError;
125
- const live = shared ?? opened ?? own;
126
- const snap = useLive(live);
127
- useOnChange(live, (rx) => rx.state, onPrescription);
128
- const signedHere = useRef(new Set<string>()); // onSigned: once per prescription
129
- useEffect(() => {
130
- if (live && patientId !== undefined)
131
- void live.sync({ patient: patientId ? { id: patientId } : null }).catch(() => {});
132
- }, [live, patientId]);
133
-
134
- const rx = snap?.state ?? null;
135
- const changes = classify(snap?.changes ?? { applied: [], unapplied: [] });
136
- const [signing, setSigning] = useState(false);
137
- const busy = signing || snap?.status === "saving" || snap?.status === "loading";
138
- // Sign is per prescription, and a signed one is final here: no edits (any change would void the
139
- // signature). A different drug or sig is a new line.
140
- const readOnly = Boolean(locked) || Boolean(live?.signed);
141
- // Sign is offered once the server left nothing open. Screening alerts don't stop it: signing is the
142
- // prescriber's acknowledgement of what they show (network-api can't acknowledge an alert yet).
143
- const canSign = Boolean(rx) && changes.settled;
144
- // The field whose change sent the call in flight shows a spinner — nowhere else, so nothing opens and
145
- // closes while the prescriber works (held briefly, so it doesn't flicker).
146
- const [sentFrom, setSentFrom] = useState<string | null>(null);
147
- const working = snap?.status === "saving" || snap?.status === "loading";
148
- if (sentFrom && !working) setSentFrom(null); // answered: a later call (e.g. signing) isn't that field's
149
- const spinning = useHeldActivity(sentFrom);
150
-
151
- const [treatment, setTreatment] = useState(rx?.treatment.name ?? "");
152
- const [instructions, setInstructions] = useState(rx?.instructions ?? "");
153
- const [quantity, setQuantity] = useState(rx?.dispense?.quantity?.toString() ?? "");
154
- const [unit, setUnit] = useState(rx?.dispense?.unit ?? "");
155
- const [daysSupply, setDaysSupply] = useState(rx?.dispense?.daysSupply?.toString() ?? "");
156
- const [refills, setRefills] = useState(rx?.dispense?.refillsAllowed?.toString() ?? "");
157
- const [daw, setDaw] = useState(rx?.dispense?.dispenseAsWritten ?? false);
158
- // Fields edited but not yet saved. A server copy (a save's response, a hydrate) never overwrites
159
- // them — otherwise a response landing mid-typing replaces what the prescriber is entering.
160
- const [dirty, setDirty] = useState<ReadonlySet<string>>(new Set());
161
- const edit = (field: string) => {
162
- setDirty((d) => (d.has(field) ? d : new Set(d).add(field)));
163
- setTouched((t) => (t.has(field) ? t : new Set(t).add(field)));
164
- };
165
- // On a line started here, a sig / dispense value the prescriber never entered came from the server —
166
- // a default, or copied from another of the patient's prescriptions (docs/api-gaps.md). Say so.
167
- const [touched, setTouched] = useState<ReadonlySet<string>>(new Set());
168
- // Decided once: the workflow passes this line's own prescription back as `prescription` once it drafts.
169
- const [startedHere] = useState(!shared?.state && !(typeof given === "string" || (given && given.id)));
170
- const prefilled = (field: string, value: string) =>
171
- startedHere && value.trim() !== "" && !touched.has(field) ? "Prefilled" : undefined;
172
- // A value the server filled in (e.g. sig "Take as directed", quantity 30) is selected on focus, so
173
- // typing replaces it instead of appending to it.
174
- const selectServerValue = (field: string) => (e: { currentTarget: HTMLInputElement | HTMLTextAreaElement }) => {
175
- if (!dirty.has(field)) e.currentTarget.select();
176
- };
177
- const clean = (field: string) =>
178
- setDirty((d) => {
179
- if (!d.has(field)) return d;
180
- const next = new Set(d);
181
- next.delete(field);
182
- return next;
183
- });
184
-
185
- // Only send free-text medication when it actually changed (see submitTreatment).
186
- const [sentTreatment, setSentTreatment] = useState(rx?.treatment.name ?? "");
187
- // When the server's copy changes (a hydrate, a chosen option, signing), show its version.
188
- // Adjusted during render, keyed on id + contentHash — React's pattern for deriving state from props.
189
- const serverKey = rx ? `${rx.id}:${rx.signing.contentHash}:${rx.signing.state}` : null;
190
- const [syncedKey, setSyncedKey] = useState(serverKey);
191
- if (rx && serverKey !== syncedKey) {
192
- setSyncedKey(serverKey);
193
- const shownName = live?.name ?? rx.treatment.name;
194
- setTreatment(shownName);
195
- setSentTreatment(shownName); // what's shown was the pick — leaving the field mustn't re-send it as text
196
- if (!dirty.has("instructions")) setInstructions(rx.instructions ?? "");
197
- if (!dirty.has("quantity")) setQuantity(rx.dispense?.quantity?.toString() ?? "");
198
- if (!dirty.has("unit")) setUnit(rx.dispense?.unit ?? "");
199
- if (!dirty.has("daysSupply")) setDaysSupply(rx.dispense?.daysSupply?.toString() ?? "");
200
- if (!dirty.has("refills")) setRefills(rx.dispense?.refillsAllowed?.toString() ?? "");
201
- setDaw(rx.dispense?.dispenseAsWritten ?? false);
202
- }
203
-
204
- // A line without a record shows what's entered on it — e.g. given as props (a drug, a sig): once per object.
205
- // Those are the host's or the prescriber's own, not prefilled.
206
- const [filledFrom, setFilledFrom] = useState<Prescription | null>(null);
207
- if (live && live !== filledFrom) {
208
- setFilledFrom(live);
209
- const { treatment: drug, instructions: sig, dispense: d } = rx ? {} : live.entered;
210
- const text = live.name ?? drug?.name;
211
- if (!rx && text) {
212
- setTreatment(text);
213
- setSentTreatment(text); // already sent: leaving the field mustn't send it again
214
- }
215
- const shown: [field: string, value: string | undefined, set: (value: string) => void][] = [
216
- ["instructions", sig, setInstructions],
217
- ["quantity", d?.quantity?.toString(), setQuantity],
218
- ["unit", d?.unit, setUnit],
219
- ["daysSupply", d?.daysSupply?.toString(), setDaysSupply],
220
- ["refills", d?.refillsAllowed?.toString(), setRefills],
221
- ];
222
- const restored = shown.filter(([, value]) => value);
223
- for (const [, value, set] of restored) set(value!);
224
- if (d?.dispenseAsWritten) setDaw(true);
225
- if (restored.length) setTouched((t) => new Set([...t, ...restored.map(([field]) => field)]));
226
- }
227
-
228
- const save = (edits: PrescriptionEdits, from?: string) => {
229
- if (readOnly || !live) return;
230
- // Its id known: update that prescription; before, sync what's known.
231
- void (live.id ? live.update(edits) : live.sync(edits)).catch(() => {}); // a failure lands on the object (snap.error)
232
- if (from && live.busy) setSentFrom(from);
233
- };
234
- // Only send free-text medication when it actually changed. Otherwise clicking one of the server's
235
- // choices blurs this field first, re-sends the same text, and the "saving" state swallows the click.
236
- const pick = snap?.pick ?? null;
237
- const [shownPick, setShownPick] = useState(pick?.id ?? null);
238
- if ((pick?.id ?? null) !== shownPick) {
239
- setShownPick(pick?.id ?? null);
240
- // The pick's name — never its id (a drug given by id alone is named once it's drafted).
241
- const name = pick && live?.name;
242
- if (name) {
243
- setTreatment(name);
244
- setSentTreatment(name);
245
- }
246
- }
247
- const picker = useRef<TreatmentPickerHandle | null>(null);
248
- // A drug chosen, until the server answers: the picker stays as it was picked (a spinner on the drug's row), and
249
- // the directions and dispense wait — a moment to see what was picked before the form changes under it.
250
- const [choosing, setChoosing] = useState<{ change: Change; option: ChangeOption } | null>(null);
251
- const chooseDrug = (change: Change) => (option: ChangeOption) => {
252
- if (!live) return;
253
- setChoosing({ change, option });
254
- void live
255
- .choose(option)
256
- .catch(() => {}) // a failure lands on the object (snap.error)
257
- .finally(() => setChoosing(null));
258
- };
259
- // The Input building block takes no ref, so focus reaches its field through a wrapper.
260
- const searchBox = useRef<HTMLDivElement>(null);
261
- useEffect(() => {
262
- if (focusSignal) searchBox.current?.querySelector("input")?.focus();
263
- }, [focusSignal]);
264
- const submitTreatment = () => {
265
- const text = treatment.trim();
266
- if (!text || text === sentTreatment || text === rx?.treatment.name) return;
267
- setSentTreatment(text);
268
- save({ treatment: { name: text } }, "treatment");
269
- };
270
- // Type-ahead: once there are 3+ characters, the medication text is sent when typing pauses — before the
271
- // record it's a lookup (the object aborts the one for older text), and the server's choices render live
272
- // below. Enter / blur send at once; unchanged text is never re-sent (so a wait that ends after them is a no-op).
273
- // Not two, as a patient's name: two letters of a drug match thousands of products.
274
- const typeAhead = useTypeAhead(submitTreatment, { minChars: 3 });
275
- // Patch only the field that changed (network-api merges a partial dispense); sending the whole
276
- // block from the screen could write stale values over newer ones.
277
- const dispense = (field: string, patch: NonNullable<PrescriptionEdits["dispense"]>) => {
278
- clean(field);
279
- save({ dispense: patch }, field);
280
- };
281
-
282
- // The title is the resolved treatment — not what the provider is typing (or an unresolved choice).
283
- const drugChoices = changes.needsChoice.filter((c) => c.key.startsWith("treatment"));
284
- const otherChoices = changes.needsChoice.filter((c) => !c.key.startsWith("treatment"));
285
- const treatmentPending = drugChoices.length > 0;
286
- // Choosing among the drugs: the picker's up — the server's choices, or the one chosen while it saves.
287
- const pickerUp = treatmentPending || Boolean(choosing);
288
- const resolvedName = (rx ? !treatmentPending : pick) && !choosing ? (live?.name ?? null) : null;
289
- // Sig / dispense can be filled once a drug is picked (and its choice has saved) — before a patient too (kept
290
- // until the line attaches).
291
- const fieldsOpen = Boolean(rx || pick) && !choosing;
292
- // "Lisinopril 10 mg tablet" over "Oral tablet · 10 mg" — the picked product, said once.
293
- const heading = resolvedName ? treatmentHeading(resolvedName, live?.treatment) : null;
294
- // The units the picked drug is dispensed in (a lookup's option says them; a stored prescription doesn't, so a
295
- // reopened one types its unit). The prescription's own unit stays listed, even when it isn't one of them.
296
- const units = live?.treatment?.recommendedDispenseUnits ?? [];
297
- const listedUnit = units.find((u) => u.toLowerCase() === unit.trim().toLowerCase());
298
- const unitOptions = [...units, ...(unit.trim() && !listedUnit ? [unit] : [])].map((u) => ({ value: u, label: u }));
299
- // The first of them is the unit until the prescriber picks another — never left blank (like a server default,
300
- // marked Prefilled). Saved once per drug: a response without it shows it again, but doesn't send it again.
301
- const unitsFor = units.join("|");
302
- const unitSavedFor = useRef<string | null>(null);
303
- const fillUnit = useLatestCallback(() => {
304
- if (readOnly || !fieldsOpen || !units.length || unit.trim()) return;
305
- setUnit(units[0]!);
306
- if (unitSavedFor.current === unitsFor) return;
307
- unitSavedFor.current = unitsFor;
308
- dispense("unit", { unit: units[0]! });
309
- });
310
- useEffect(() => fillUnit(), [unitsFor, unit, fieldsOpen, fillUnit]);
311
- // The Treatment field is for finding a drug: shown until one is picked. A different drug is a new line.
312
- const searching = !fieldsOpen || pickerUp;
313
- // A few drugs for what's typed, and the prescriber is still in Treatment: focus goes to the first, ready to
314
- // pick — typing carries on in Treatment (search.tsx). Once per answer.
315
- const choicesFor = drugChoices[0]
316
- ? `${drugChoices[0].inputText}|${drugChoices[0].options.map((o) => o.displayName).join("|")}`
317
- : null;
318
- const focusedFor = useRef<string | null>(null);
319
- const focusFew = useLatestCallback(() => {
320
- const field = searchBox.current?.querySelector("input");
321
- const answered = treatment.trim() === sentTreatment && !busy && !typeAhead.waiting();
322
- if (!choicesFor || !answered || !field || document.activeElement !== field) return;
323
- if (focusedFor.current === choicesFor || (picker.current?.total ?? FEW) >= FEW) return;
324
- focusedFor.current = choicesFor;
325
- picker.current!.focus(true);
326
- });
327
- useEffect(() => focusFew(), [choicesFor, busy, focusFew]);
328
-
329
- // A failed call: shown where the drug list drops down (under Treatment), with the card's other messages — and so
330
- // is a prescription this line stands in for that the server doesn't have (an order link's `rx=`), until it's filled.
331
- const missing = live?.missing && !rx ? new NotFound("prescription", live.missing) : null;
332
- const opening = openError ?? missing;
333
- const error = snap?.error ?? opening;
334
- const failure = error && (
335
- <Alert
336
- tone="critical"
337
- title={
338
- !snap?.error && opening
339
- ? openFailed(opening === patientError ? "patient" : "prescription", opening)
340
- : snap?.error?.kind === "refused" && !rx
341
- ? "Can't start a new prescription"
342
- : "Couldn't save this prescription"
343
- }
344
- description={error.message}
345
- />
346
- );
347
-
348
- return (
349
- <Card divided>
350
- <CardHeader
351
- title={heading?.title ?? "Prescription"}
352
- // The product in parts — a brand's ingredients, its form · strength, a controlled substance's schedule —
353
- // with no NDC / RxNorm stand-ins.
354
- description={heading?.detail}
355
- // The card's one action, top right: take the line off (a different drug is a new line). Its status tag
356
- // sits with what it describes — the instructions on a saved prescription, Sign on one being written.
357
- action={
358
- !locked &&
359
- onRemove && (
360
- <Button
361
- variant="ghost"
362
- size="sm"
363
- tone="critical"
364
- icon="trash"
365
- aria-label="Remove prescription"
366
- title="Remove prescription"
367
- onClick={onRemove}
368
- />
369
- )
370
- }
371
- />
372
- <CardBody>
373
- <Stack gap="4">
374
- {readOnly ? (
375
- <>
376
- {failure}
377
- <ReadOnlyRx rx={rx} status={<StatusBadge rx={rx} />} />
378
- <ScreeningAlerts alerts={openAlerts(rx)} />
379
- </>
380
- ) : (
381
- <>
382
- {/* Where the card flow (← / →) lands: the drug list while choosing, Treatment while searching, else the sig. */}
383
- {searching && (
384
- <div ref={searchBox} {...searchProps} {...(pickerUp ? {} : focusProps)}>
385
- <Input
386
- label="Treatment"
387
- autoFocus={autoFocus}
388
- value={treatment}
389
- onChange={(e) => {
390
- setTreatment(e.target.value);
391
- typeAhead.typed("treatment", e.target.value);
392
- }}
393
- onBlur={submitTreatment}
394
- loading={spinning === "treatment"}
395
- onKeyDown={(e) => {
396
- const choices = treatmentPending ? picker.current : null;
397
- // A search field over the drugs (searchKeys); and Enter is on the open drug when the
398
- // choices are for what's typed (chosen if it's one product, else on to its chips).
399
- const answered = treatment.trim() === sentTreatment && !busy;
400
- if (searchKeys(e, choices, answered)) return;
401
- if (e.key === "Enter" && choices && treatment.trim() === sentTreatment) choices.enter();
402
- else if (e.key === "Enter") submitTreatment();
403
- else return;
404
- e.preventDefault();
405
- }}
406
- />
407
- </div>
408
- )}
409
- {/* Which drug? — grouped by drug / form / strength. Any other pending choice renders as usual. */}
410
- {pickerUp && (
411
- <div {...focusProps}>
412
- {(choosing ? [choosing.change] : drugChoices).map((change) => (
413
- <TreatmentPicker
414
- key={change.key}
415
- change={change}
416
- onChoose={chooseDrug(change)}
417
- chosen={choosing?.option ?? null}
418
- busy={busy}
419
- handleRef={picker}
420
- onBack={() => searchBox.current?.querySelector("input")?.focus()}
421
- />
422
- ))}
423
- </div>
424
- )}
425
- {/* Where the drug list drops down: what failed, what the server said, what screening found. */}
426
- {failure}
427
- <ChangeList
428
- changes={{ ...changes, needsChoice: otherChoices }}
429
- onChoose={(o) => void live?.choose(o).catch(() => {})}
430
- busy={busy}
431
- />
432
- {/* The patient has several open prescriptions: this line continues the one picked. */}
433
- {snap?.drafts && (
434
- <SearchResults
435
- label="Continue a draft"
436
- busy={busy}
437
- results={snap.drafts.map((d) => ({
438
- key: d.id,
439
- label: d.treatment.name,
440
- description: [d.instructions, dispenseSummary(d)].filter(Boolean).join(" · ") || undefined,
441
- }))}
442
- onPick={(id) => void live?.continueDraft(id).catch(() => {})}
443
- />
444
- )}
445
- {/* What screening found (an allergy, an interaction, a condition) — read before the directions. */}
446
- <ScreeningAlerts alerts={openAlerts(rx)} />
447
- {/* Once a drug is set: the directions first, then quantity / unit / days / refills, then DAW. */}
448
- {fieldsOpen && (
449
- <>
450
- <div {...(searching ? {} : focusProps)}>
451
- <Textarea
452
- label="Directions (sig)"
453
- rows={2}
454
- value={instructions}
455
- onFocus={selectServerValue("instructions")}
456
- helper={prefilled("instructions", instructions)}
457
- onChange={(e) => {
458
- setInstructions(e.target.value);
459
- edit("instructions");
460
- }}
461
- onBlur={() => {
462
- if (!dirty.has("instructions")) return;
463
- clean("instructions");
464
- if (instructions !== (rx?.instructions ?? "")) save({ instructions }, "instructions");
465
- }}
466
- />
467
- </div>
468
- <Grid min="64px" gap="2">
469
- <Input
470
- label="Quantity"
471
- inputMode="decimal"
472
- value={quantity}
473
- onFocus={selectServerValue("quantity")}
474
- helper={prefilled("quantity", quantity)}
475
- onChange={(e) => {
476
- setQuantity(e.target.value);
477
- edit("quantity");
478
- }}
479
- onBlur={() => dirty.has("quantity") && dispense("quantity", { quantity: num(quantity) })}
480
- loading={spinning === "quantity"}
481
- />
482
- {units.length > 0 ? (
483
- <Select
484
- label="Unit"
485
- options={unitOptions}
486
- value={listedUnit ?? (unit || null)}
487
- helper={prefilled("unit", unit)}
488
- onChange={(value) => {
489
- setUnit(value);
490
- edit("unit");
491
- dispense("unit", { unit: value });
492
- }}
493
- />
494
- ) : (
495
- <Input
496
- label="Unit"
497
- value={unit}
498
- onFocus={selectServerValue("unit")}
499
- helper={prefilled("unit", unit)}
500
- onChange={(e) => {
501
- setUnit(e.target.value);
502
- edit("unit");
503
- }}
504
- onBlur={() => dirty.has("unit") && dispense("unit", { unit: unit || undefined })}
505
- loading={spinning === "unit"}
506
- />
507
- )}
508
- <Input
509
- label="Days supply"
510
- inputMode="numeric"
511
- value={daysSupply}
512
- onFocus={selectServerValue("daysSupply")}
513
- helper={prefilled("daysSupply", daysSupply)}
514
- onChange={(e) => {
515
- setDaysSupply(e.target.value);
516
- edit("daysSupply");
517
- }}
518
- onBlur={() => dirty.has("daysSupply") && dispense("daysSupply", { daysSupply: num(daysSupply) })}
519
- loading={spinning === "daysSupply"}
520
- />
521
- <Input
522
- label="Refills"
523
- inputMode="numeric"
524
- value={refills}
525
- onFocus={selectServerValue("refills")}
526
- helper={prefilled("refills", refills)}
527
- onChange={(e) => {
528
- setRefills(e.target.value);
529
- edit("refills");
530
- }}
531
- onBlur={() => dirty.has("refills") && dispense("refills", { refillsAllowed: num(refills) })}
532
- loading={spinning === "refills"}
533
- />
534
- </Grid>
535
- <Checkbox
536
- label="Dispense as written"
537
- checked={daw}
538
- onChange={(checked) => {
539
- setDaw(checked);
540
- dispense("daw", { dispenseAsWritten: checked });
541
- }}
542
- />
543
- </>
544
- )}
545
- </>
546
- )}
547
- </Stack>
548
- </CardBody>
549
- {!locked && rx && !live?.signed && (
550
- <CardFooter start={<StatusBadge rx={rx} />}>
551
- {rx && (
552
- <Button
553
- variant="secondary" // Send is the page's one primary action
554
- // Not disabled while saving: clicking Sign leaves a field, which saves it — the sign waits
555
- // for that save (a disabled button would swallow the click).
556
- loading={signing}
557
- disabled={snap?.status === "loading" || !canSign}
558
- onClick={() => {
559
- if (!live) return;
560
- setSigning(true);
561
- void live
562
- .sign()
563
- .then(() => {
564
- if (!live.signed || !live.id || signedHere.current.has(live.id)) return;
565
- signedHere.current.add(live.id);
566
- onSigned?.(live);
567
- })
568
- .catch(() => {}) // a refusal or failure lands on the object (snap.error)
569
- .finally(() => setSigning(false));
570
- }}
571
- >
572
- Sign
573
- </Button>
574
- )}
575
- </CardFooter>
576
- )}
577
- </Card>
578
- );
579
- }
580
-
581
- /** A saved prescription: its instructions — with its status tag at the end of that line — then what's dispensed. */
582
- function ReadOnlyRx({ rx, status }: { rx: PrescriptionRecord | null; status: ReactNode }) {
583
- const { Row, Stack, Text } = useComponents();
584
- // Locked before there's anything in it: say so, rather than an empty card.
585
- if (!rx) return <Text tone="tertiary">No prescription</Text>;
586
- const dispense = dispenseSummary(rx);
587
- const first = rx.instructions ? (
588
- <span>{rx.instructions}</span>
589
- ) : dispense ? (
590
- <Text tone="secondary">{dispense}</Text>
591
- ) : null;
592
- return (
593
- <Stack gap="1">
594
- <Row gap="2" justify="between">
595
- {first ?? <span />}
596
- {status}
597
- </Row>
598
- {rx.instructions && dispense && <Text tone="secondary">{dispense}</Text>}
599
- </Stack>
39
+ <AnalyticsWorkflow card="PhotonPrescription" viewedProperties={viewedPropertiesFromCardProps(props)}>
40
+ <SignedIn>
41
+ <PrescriptionCard {...props} />
42
+ </SignedIn>
43
+ </AnalyticsWorkflow>
600
44
  );
601
45
  }
602
-
603
- /** What screening found, until it's signed: the signature acknowledges them. */
604
- const openAlerts = (rx: PrescriptionRecord | null) =>
605
- rx?.signing.state === "SIGNED" ? [] : (rx?.screeningAlerts ?? []);
@@ -1,6 +1,6 @@
1
1
  /** Display formatting, plus the one normalisation we send back (phone → E.164). */
2
2
 
3
- /** "+13174504573" / "3174504573" → "+1 (317) 450-4573"; anything else is shown as given. */
3
+ /** "+13175550147" / "3175550147" → "+1 (317) 555-0147"; anything else is shown as given. */
4
4
  export function formatPhone(phone: string | null | undefined): string {
5
5
  if (!phone) return "";
6
6
  const digits = phone.replace(/\D/g, "");
@@ -11,7 +11,7 @@ export function formatPhone(phone: string | null | undefined): string {
11
11
  /** Native validation for type="tel": a US number, punctuated any common way (+1 optional). */
12
12
  export const PHONE_PATTERN = String.raw`\+?1?[\s.\-]*\(?\d{3}\)?[\s.\-]*\d{3}[\s.\-]*\d{4}`;
13
13
 
14
- /** "(317) 450-4573" → "+13174504573" (what network-api stores); non-US kept as typed; blank → undefined. */
14
+ /** "(317) 555-0147" → "+13175550147" (what network-api stores); non-US kept as typed; blank → undefined. */
15
15
  export function toE164(phone: string): string | undefined {
16
16
  const trimmed = phone.trim();
17
17
  if (!trimmed) return undefined;
@@ -2,4 +2,4 @@ export * from "./ChangeList.tsx";
2
2
  export { PhotonPatient, type PhotonPatientProps } from "./PhotonPatient.tsx";
3
3
  export { PhotonPrescription, type PhotonPrescriptionProps } from "./PhotonPrescription.tsx";
4
4
  export * from "./PhotonOrder.tsx";
5
- export * from "./TreatmentPicker.tsx";
5
+ export * from "./prescription/TreatmentSearch/TreatmentPicker.tsx";