@photonhealth/react 2.0.0-rc.2 → 2.0.0-rc.4

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 +17 -1
  2. package/dist/analytics/PhotonAnalyticsProvider.d.ts +5 -2
  3. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -1
  4. package/dist/analytics/PhotonAnalyticsProvider.js +34 -15
  5. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -1
  6. package/dist/analytics/cardLifecycle.d.ts +10 -0
  7. package/dist/analytics/cardLifecycle.d.ts.map +1 -0
  8. package/dist/analytics/cardLifecycle.js +43 -0
  9. package/dist/analytics/cardLifecycle.js.map +1 -0
  10. package/dist/analytics/lifecycleOutcomes.d.ts +8 -0
  11. package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
  12. package/dist/analytics/lifecycleOutcomes.js +16 -0
  13. package/dist/analytics/lifecycleOutcomes.js.map +1 -0
  14. package/dist/analytics/tracker.d.ts +5 -3
  15. package/dist/analytics/tracker.d.ts.map +1 -1
  16. package/dist/analytics/tracker.js +10 -5
  17. package/dist/analytics/tracker.js.map +1 -1
  18. package/dist/components/PhotonOrder.d.ts +18 -18
  19. package/dist/components/PhotonOrder.d.ts.map +1 -1
  20. package/dist/components/PhotonOrder.js +17 -6
  21. package/dist/components/PhotonOrder.js.map +1 -1
  22. package/dist/components/PhotonPatient.d.ts +7 -35
  23. package/dist/components/PhotonPatient.d.ts.map +1 -1
  24. package/dist/components/PhotonPatient.js +3 -77
  25. package/dist/components/PhotonPatient.js.map +1 -1
  26. package/dist/components/PhotonPrescription.d.ts +14 -14
  27. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  28. package/dist/components/PhotonPrescription.js +0 -1
  29. package/dist/components/PhotonPrescription.js.map +1 -1
  30. package/dist/components/open.d.ts +11 -13
  31. package/dist/components/open.d.ts.map +1 -1
  32. package/dist/components/open.js +7 -2
  33. package/dist/components/open.js.map +1 -1
  34. package/dist/components/patient/PatientCard/PatientCard.d.ts +30 -0
  35. package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
  36. package/dist/components/patient/PatientCard/PatientCard.js +101 -0
  37. package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
  38. package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
  39. package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
  40. package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
  41. package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
  42. package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
  43. package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
  44. package/dist/components/patient/PatientIntakeForm.js +114 -0
  45. package/dist/components/patient/PatientIntakeForm.js.map +1 -0
  46. package/dist/components/patient/PatientSearch.d.ts +12 -0
  47. package/dist/components/patient/PatientSearch.d.ts.map +1 -0
  48. package/dist/components/patient/PatientSearch.js +148 -0
  49. package/dist/components/patient/PatientSearch.js.map +1 -0
  50. package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
  51. package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
  52. package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +5 -5
  53. package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
  54. package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +13 -15
  55. package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
  56. package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +11 -11
  57. package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
  58. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
  59. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
  60. package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
  61. package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
  62. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
  63. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
  64. package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
  65. package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
  66. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
  67. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
  68. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
  69. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
  70. package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
  71. package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
  72. package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
  73. package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
  74. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
  75. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
  76. package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
  77. package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
  78. package/dist/components/patient/fields.d.ts +7 -25
  79. package/dist/components/patient/fields.d.ts.map +1 -1
  80. package/dist/components/patient/fields.js +11 -53
  81. package/dist/components/patient/fields.js.map +1 -1
  82. package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
  83. package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
  84. package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -15
  85. package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
  86. package/dist/components/prescription/PrescriptionCard.d.ts +14 -8
  87. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -1
  88. package/dist/components/prescription/PrescriptionCard.js +10 -3
  89. package/dist/components/prescription/PrescriptionCard.js.map +1 -1
  90. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +6 -6
  91. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -1
  92. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +16 -8
  93. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -1
  94. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +14 -1
  95. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -1
  96. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +25 -7
  97. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -1
  98. package/dist/components/schemaErrors.d.ts +3 -2
  99. package/dist/components/schemaErrors.d.ts.map +1 -1
  100. package/dist/components/schemaErrors.js +2 -1
  101. package/dist/components/schemaErrors.js.map +1 -1
  102. package/dist/components/search.d.ts +1 -1
  103. package/dist/components/search.js +1 -1
  104. package/dist/index.d.ts +1 -1
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +1 -1
  107. package/dist/index.js.map +1 -1
  108. package/dist/meta/version.js +1 -1
  109. package/package.json +5 -2
  110. package/src/analytics/PhotonAnalyticsProvider.test.tsx +0 -1
  111. package/src/analytics/PhotonAnalyticsProvider.tsx +75 -20
  112. package/src/analytics/cardLifecycle.test.tsx +272 -0
  113. package/src/analytics/cardLifecycle.ts +44 -0
  114. package/src/analytics/fieldInteraction.test.tsx +11 -9
  115. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  116. package/src/analytics/lifecycleOutcomes.ts +29 -0
  117. package/src/analytics/tracker.test.ts +1 -1
  118. package/src/analytics/tracker.ts +13 -6
  119. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  120. package/src/components/PhotonOrder.test.tsx +146 -8
  121. package/src/components/PhotonOrder.tsx +37 -26
  122. package/src/components/PhotonPatient.tsx +8 -163
  123. package/src/components/PhotonPrescription.test.tsx +22 -18
  124. package/src/components/PhotonPrescription.tsx +14 -14
  125. package/src/components/ScreeningAlerts.test.tsx +81 -0
  126. package/src/components/open.ts +13 -16
  127. package/src/components/order/DraftOrderPrompt.test.tsx +3 -6
  128. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  129. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  130. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  131. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  132. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  133. package/src/components/patient/PatientSearch.test.tsx +204 -0
  134. package/src/components/patient/PatientSearch.tsx +221 -0
  135. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  136. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +4 -4
  137. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  138. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +23 -23
  139. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  140. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  141. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  142. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  143. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  144. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  145. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  146. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  147. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  148. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  149. package/src/components/patient/fields.tsx +12 -138
  150. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  151. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -21
  152. package/src/components/prescription/PrescriptionCard.test.tsx +175 -12
  153. package/src/components/prescription/PrescriptionCard.tsx +28 -14
  154. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +2 -5
  155. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +3 -6
  156. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +34 -37
  157. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +24 -16
  158. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +166 -41
  159. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +41 -9
  160. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +2 -5
  161. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +3 -7
  162. package/src/components/schemaErrors.ts +3 -2
  163. package/src/components/search.tsx +1 -1
  164. package/src/index.ts +1 -1
  165. package/src/meta/version.test.ts +1 -0
  166. package/src/meta/version.ts +1 -1
  167. package/dist/components/patient/Benefits.d.ts.map +0 -1
  168. package/dist/components/patient/Benefits.js.map +0 -1
  169. package/dist/components/patient/Clinical.d.ts.map +0 -1
  170. package/dist/components/patient/Clinical.js.map +0 -1
  171. package/dist/components/patient/IntakeForm.d.ts +0 -10
  172. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  173. package/dist/components/patient/IntakeForm.js +0 -333
  174. package/dist/components/patient/IntakeForm.js.map +0 -1
  175. package/dist/components/patient/Summary.d.ts +0 -48
  176. package/dist/components/patient/Summary.d.ts.map +0 -1
  177. package/dist/components/patient/Summary.js +0 -90
  178. package/dist/components/patient/Summary.js.map +0 -1
  179. package/dist/components/patient/query.d.ts +0 -37
  180. package/dist/components/patient/query.d.ts.map +0 -1
  181. package/dist/components/patient/query.js.map +0 -1
  182. package/src/components/patient/IntakeForm.test.tsx +0 -89
  183. package/src/components/patient/IntakeForm.tsx +0 -564
  184. package/src/components/patient/Summary.test.tsx +0 -106
  185. package/src/components/patient/Summary.tsx +0 -330
@@ -1,564 +0,0 @@
1
- /** PhotonPatient before a record: the fields a prescriber fills to find or add the patient, and the candidates. */
2
- import { useComponents } from "../../primitives/index.ts";
3
- import { asksForAddress, classify, type Patient, type Sex } from "@photonhealth/client";
4
- import { useLatestCallback, useLive } from "../../hooks/index.ts";
5
- import { useEffect, useId, useRef, useState, type KeyboardEvent, type SubmitEvent } from "react";
6
- import { useHeldActivity } from "../activity.ts";
7
- import { ChangeList } from "../ChangeList.tsx";
8
- import { formatDate, formatPhone, PHONE_PATTERN, toE164 } from "../format.ts";
9
- import { FEW, searchKeys, SearchResults, useTypeAhead, type SearchHandle } from "../search.tsx";
10
-
11
- import { noAutofill, SEX_OPTIONS } from "./fields.tsx";
12
- import { focusProps, searchProps } from "../flow.ts";
13
- import { isSearchable, parseQuery, searchBoth, toSearchInput } from "./query.ts";
14
- import { TrackedField, useFieldInteractions } from "../../analytics/fieldInteraction.tsx";
15
-
16
- const IDENTITY_KEYS = ["demographic.name.first", "demographic.name.last", "demographic.dateOfBirth", "demographic.sex"];
17
-
18
- type Field = "query" | "first" | "last" | "dob" | "sex" | "phone" | "email" | "address";
19
-
20
- export function PatientIntakeForm({
21
- patient,
22
- notice,
23
- }: {
24
- patient: Patient;
25
- /** Why someone else is being found (e.g. the patient given by id isn't there): with the matches, where answers go. */
26
- notice?: { title: string; description: string } | null;
27
- }) {
28
- const { Alert, Badge, Button, Card, CardBody, CardFooter, CardHeader, Grid, Input, Select, Spinner, Stack } =
29
- useComponents();
30
- const snap = useLive(patient)!;
31
- const formId = useId();
32
- // Starts from what's already been sent — e.g. a host's details the server hasn't matched yet — to edit on.
33
- const known = patient.known;
34
- const [first, setFirst] = useState(known.demographic?.name?.first ?? "");
35
- const [last, setLast] = useState(known.demographic?.name?.last ?? "");
36
- const [dob, setDob] = useState(known.demographic?.dateOfBirth ?? "");
37
- const [sex, setSex] = useState<Sex | null>(known.demographic?.sex ?? null);
38
- const sexPicked = useFieldInteractions("new_patient_form")("sex", { isOptional: false, hasValue: Boolean(sex) });
39
- const [email, setEmail] = useState(known.contact?.email ?? "");
40
- const [phone, setPhone] = useState(known.contact?.phone ? formatPhone(known.contact.phone) : "");
41
- const [street1, setStreet1] = useState(known.contact?.address?.street1 ?? "");
42
- const [street2, setStreet2] = useState(known.contact?.address?.street2 ?? "");
43
- const [city, setCity] = useState(known.contact?.address?.city ?? "");
44
- const [state, setState] = useState(known.contact?.address?.state ?? "");
45
- const [postalCode, setPostalCode] = useState(known.contact?.address?.postalCode ?? "");
46
- /**
47
- * Finding someone and adding them are two different jobs, so the card does one at a time. Searching is
48
- * one field and never writes (`search` goes without `sex`, which is what network-api needs to create).
49
- * "Create a new patient" is the prescriber saying none of these — it opens the form, filled in from what
50
- * they typed. Details handed in that the server hasn't matched start there, as they always did.
51
- */
52
- const [mode, setMode] = useState<"search" | "create">(() =>
53
- known.demographic?.name?.first || known.demographic?.name?.last || known.demographic?.dateOfBirth
54
- ? "create"
55
- : "search",
56
- );
57
- const [query, setQuery] = useState("");
58
- const creating = mode === "create";
59
- /** What the matches below answer — the query as it was typed when the search went out. */
60
- const [searched, setSearched] = useState<string | null>(null);
61
- /** The row the keys are on, by DOM id: the field says so with `aria-activedescendant`. */
62
- const [activeId, setActiveId] = useState<string | null>(null);
63
- /** Which of the four network-api needs were empty when Save was last pressed. */
64
- const [missing, setMissing] = useState<Field[]>([]);
65
- /** What a required field says while Save is waiting on it. The server names all four at once; we don't. */
66
- const gap = (field: Field) =>
67
- missing.includes(field) ? { invalid: true, errorMessage: "Needed to add a patient" } : {};
68
-
69
- const busy = snap.status === "loading" || snap.status === "saving";
70
- const candidates = snap.candidates;
71
- const addressComplete = Boolean(street1.trim() && city.trim() && state.trim() && postalCode.trim());
72
- const asksAddress = asksForAddress(snap.changes, snap.error?.message);
73
- // What the server still needs to add the patient (name, DOB, sex) is what this form asks for next — not an
74
- // error. Once the prescriber has filled all four, anything it still rejects about them is shown.
75
- const identityFilled = Boolean(first.trim() && last.trim() && dob && sex);
76
- const changes = classify({
77
- ...snap.changes,
78
- unapplied: snap.changes.unapplied.filter((c) => identityFilled || !IDENTITY_KEYS.includes(c.key)),
79
- });
80
-
81
- /** Everything known on the form. Phone / email ride along once they're valid; the browser shows why otherwise. */
82
- const form = (overrides: { sex?: Sex | null } = {}) => {
83
- const chosenSex = overrides.sex !== undefined ? overrides.sex : sex;
84
- const validPhone = new RegExp(`^(?:${PHONE_PATTERN})$`).test(phone.trim());
85
- const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
86
- const demographic = {
87
- name: { first, last },
88
- dateOfBirth: dob,
89
- ...(chosenSex ? { sex: chosenSex } : {}),
90
- };
91
- const contact = {
92
- ...(validPhone ? { phone: toE164(phone) } : {}),
93
- ...(validEmail ? { email: email.trim() } : {}),
94
- ...(addressComplete
95
- ? {
96
- address: {
97
- street1: street1.trim(),
98
- street2: street2.trim() || undefined,
99
- city: city.trim(),
100
- state: state.trim().toUpperCase(),
101
- postalCode: postalCode.trim(),
102
- country: "US",
103
- },
104
- }
105
- : {}),
106
- };
107
- return { demographic, contact };
108
- };
109
- // What the list of matches answers: the form as it was last sent — and whether typing sent it (a search), not
110
- // leaving a field.
111
- const sent = useRef<string | null>(null);
112
- const typedSearch = useRef(false);
113
- // The field whose change or exit sent the call in flight shows the spinner (held briefly, so it doesn't flicker).
114
- const [sentFrom, setSentFrom] = useState<Field | null>(null);
115
- if (sentFrom && !busy) setSentFrom(null); // answered
116
- const spinning = useHeldActivity(sentFrom);
117
- /**
118
- * Send everything known — `sync` (a field left: the server may find or add the patient) or `search` (typing:
119
- * it only lists who it might be). The object adds it to what it sent before; the same query isn't sent twice.
120
- */
121
- const send = (from: Field, kind: "sync" | "search" = "sync", overrides: { sex?: Sex | null } = {}) => {
122
- const input = form(overrides);
123
- sent.current = JSON.stringify(input);
124
- typedSearch.current = kind === "search";
125
- void (kind === "sync" ? patient.sync(input) : patient.search(input)).catch(() => {}); // failures land on the object
126
- if (patient.busy) setSentFrom(from);
127
- };
128
- /**
129
- * The one search field, answered. Only ever `search`: it can't create, and it can't change whoever it
130
- * finds. One word could be either name, so if it draws a blank as a first name it's asked again as a
131
- * last name — "Lovelace" is as likely to be typed as "Ada".
132
- */
133
- const runSearch = useLatestCallback(() => {
134
- const text = query.trim();
135
- const parsed = parseQuery(text);
136
- if (!isSearchable(parsed)) return;
137
- typedSearch.current = true;
138
- setSentFrom("query");
139
- void (async () => {
140
- try {
141
- await patient.search(toSearchInput(parsed));
142
- const alsoLast = searchBoth(parsed);
143
- if (alsoLast && patient.snapshot.candidates.length === 0) await patient.search(toSearchInput(alsoLast));
144
- } catch {
145
- // failures land on the object
146
- }
147
- setSearched(text);
148
- })();
149
- });
150
- // Two characters: network-api matches "a first/last name prefix of 2+ characters" (`AmbiguousPatientMatch`),
151
- // and short surnames are real — Ng, Wu, Li. Not one: that would match thousands, and the server returns at
152
- // most twenty candidates, so it would hand back an arbitrary slice — a list without your patient in it reads
153
- // as "not here", which is how a duplicate gets made.
154
- const typeAhead = useTypeAhead<Field>((field) => (field === "query" ? runSearch() : send(field, "search")), {
155
- minChars: 2,
156
- });
157
- /** A field changed: keep it, and search once typing pauses. */
158
- const type = (field: Field, set: (value: string) => void) => (e: { target: { value: string } }) => {
159
- set(e.target.value);
160
- // Answering what Save asked for puts it right at once: an error about a field you have just filled in
161
- // is the thing this whole screen is meant to stop doing.
162
- if (e.target.value.trim()) setMissing((m) => m.filter((f) => f !== field));
163
- // While adding, there is nobody to look up — the prescriber has already said this is someone new.
164
- if (!creating) typeAhead.typed(field, e.target.value);
165
- };
166
-
167
- // Rows open one at a time, as fields are left: first / last → DOB / sex → phone / email. Once open, a row
168
- // stays open. Fields it started with (a patient given that isn't matched yet) count as left: their rows are open.
169
- const [visited, setVisited] = useState<ReadonlySet<string>>(
170
- () =>
171
- new Set(
172
- Object.entries({ first, last, dob, sex, email, phone })
173
- .filter(([, value]) => value)
174
- .map(([field]) => field),
175
- ),
176
- );
177
- const visit = (field: string) => setVisited((v) => (v.has(field) ? v : new Set(v).add(field)));
178
- const bothLeft = (a: string, b: string) => visited.has(a) && visited.has(b);
179
- // Searching opened rows one at a time as the server narrowed things down. Adding is a form: it shows
180
- // what it needs, all of it, so the prescriber can see what Save is waiting on.
181
- const rows = creating ? 3 : bothLeft("dob", "sex") ? 3 : bothLeft("first", "last") ? 2 : 1;
182
- // A few matches listed: they're the next thing to look at.
183
- const few = candidates.length > 0 && candidates.length < FEW;
184
- /** The search is answered, and nobody came back. Not the same as nobody being there. */
185
- const answeredNothing =
186
- mode === "search" &&
187
- searched !== null &&
188
- searched === query.trim() &&
189
- candidates.length === 0 &&
190
- !busy &&
191
- !typeAhead.waiting();
192
- const matches = useRef<SearchHandle | null>(null);
193
- // The field last typed in: Esc in the matches goes back to it.
194
- const lastField = useRef<HTMLInputElement | null>(null);
195
- // Each field is a search field over the matches (searchKeys): Tab goes to the first when a few answer
196
- // what's typed. Otherwise — many matches, none, or the answer not back yet — Tab goes on to narrow them
197
- // down: the field is marked on Tab's keydown, not only on blur, so the next row renders within the same
198
- // keystroke and Tab moves into it instead of skipping ahead.
199
- const onKeys = (e: KeyboardEvent, field: Field) => {
200
- const answered =
201
- !typeAhead.waiting() &&
202
- !busy &&
203
- (field === "query" ? searched === query.trim() : sent.current === JSON.stringify(form()));
204
- if (searchKeys(e, matches.current, answered)) return;
205
- if (e.key === "Tab" && !e.shiftKey && field !== "query") visit(field);
206
- };
207
- // A few matches for what's being typed (a search, not a field left), and the prescriber is still in the field:
208
- // focus goes to the first, ready to pick — typing carries on in the field (search.tsx). Once per answer; moving
209
- // there isn't leaving the field.
210
- const moving = useRef(false);
211
- const matchesFor = candidates.map((c) => c.id).join();
212
- const focusedFor = useRef<string | null>(null);
213
- const focusFew = useLatestCallback(() => {
214
- const field = lastField.current;
215
- const answered =
216
- !typeAhead.waiting() &&
217
- !busy &&
218
- (mode === "search" ? searched === query.trim() : sent.current === JSON.stringify(form()));
219
- if (!few || !answered || !typedSearch.current || !field || document.activeElement !== field) return;
220
- if (focusedFor.current === matchesFor) return;
221
- focusedFor.current = matchesFor;
222
- moving.current = true;
223
- matches.current?.focus(true);
224
- moving.current = false;
225
- });
226
- // Also on `searched`: the matches can land before the card has noted which query they answer, and until
227
- // it has, they aren't an answer to move to.
228
- useEffect(() => focusFew(), [matchesFor, busy, searched, focusFew]);
229
- const leaveField = (field: Field) => {
230
- if (moving.current) return;
231
- typeAhead.cancel();
232
- if (matches.current?.pointing?.()) return; // a match is being picked: that's what's next
233
- if (!few) visit(field);
234
- // Adding a patient is its own act: nothing goes to the server until Save. Moving between fields can't
235
- // create anyone, and can't change whoever a half-finished name happens to resemble.
236
- if (!creating) send(field);
237
- };
238
- const submit = (e: SubmitEvent) => {
239
- e.preventDefault();
240
- typeAhead.cancel();
241
- if (creating) return save();
242
- send("address");
243
- };
244
-
245
- /**
246
- * Add them. network-api creates a patient only with a first name, a last name, a date of birth and a sex
247
- * (`Sex` has UNKNOWN, so there is always an answer), and the schema says nothing about which of them a
248
- * payload is short of — so the form checks before it sends, rather than Save failing with a rejection
249
- * naming every field at once.
250
- *
251
- * The server still decides what this means: it may find the patient instead of adding them, or come back
252
- * with people it might be. Only this press asks it.
253
- */
254
- const REQUIRED: [Field, boolean][] = [
255
- ["first", Boolean(first.trim())],
256
- ["last", Boolean(last.trim())],
257
- ["dob", Boolean(dob)],
258
- ["sex", Boolean(sex)],
259
- ];
260
- const save = () => {
261
- const empty = REQUIRED.filter(([, filled]) => !filled).map(([field]) => field);
262
- setMissing(empty);
263
- if (empty.length) return; // the fields say which; the cursor goes to the first of them (below)
264
- send("sex");
265
- };
266
-
267
- /**
268
- * None of these: add them instead. What was typed is split into the fields, so nothing is retyped and
269
- * the prescriber can see — and correct — how it was read. Sex is the one thing still missing, and the
270
- * one network-api needs to create, so that's where focus goes: the form is filled in and the deliberate
271
- * act is choosing it.
272
- */
273
- const sexField = useRef<HTMLDivElement | null>(null);
274
- const fields = useRef<HTMLFormElement | null>(null);
275
- // Save pressed with gaps: the cursor goes to the first field it is waiting on, so answering starts there.
276
- useEffect(() => {
277
- if (!missing.length) return;
278
- fields.current?.querySelector<HTMLElement>('[aria-invalid="true"], [data-invalid]')?.focus();
279
- }, [missing]);
280
- const startCreate = () => {
281
- typeAhead.cancel();
282
- const parsed = parseQuery(query);
283
- setFirst(parsed.name?.first ?? "");
284
- setLast(parsed.name?.last ?? "");
285
- setDob(parsed.dateOfBirth ?? "");
286
- if (parsed.phone) setPhone(formatPhone(parsed.phone));
287
- if (parsed.email) setEmail(parsed.email);
288
- setVisited(new Set(["first", "last", "dob", ...(parsed.phone || parsed.email ? ["sex"] : [])]));
289
- setMode("create");
290
- };
291
- // Once the form is up, the cursor goes to Sex (the Select is a building block, so by where it lands).
292
- const landed = useRef(false);
293
- useEffect(() => {
294
- if (!creating || landed.current || !sexField.current) return;
295
- landed.current = true;
296
- sexField.current.querySelector<HTMLElement>("input, select, button")?.focus();
297
- }, [creating]);
298
-
299
- return (
300
- <Card divided>
301
- <CardHeader title="Patient" />
302
- <CardBody>
303
- <form
304
- {...noAutofill}
305
- ref={fields}
306
- id={formId}
307
- onSubmit={submit}
308
- onFocus={(e) => {
309
- if (e.target instanceof HTMLInputElement) lastField.current = e.target;
310
- }}
311
- >
312
- <Stack gap="3">
313
- {mode === "search" && (
314
- <div {...focusProps} {...searchProps}>
315
- <TrackedField formName="find_patient" fieldName="patientSearch" isOptional={false}>
316
- <Input
317
- label="Find patient"
318
- placeholder="Name, date of birth, phone or email"
319
- value={query}
320
- onChange={(e) => {
321
- setQuery(e.target.value);
322
- typeAhead.typed("query", e.target.value);
323
- // Too little left to search on: the matches on screen answer a query that isn't there
324
- // any more, so they go, and the card is back where it started — including what it has
325
- // already moved the cursor to, or typing the same name again would land nowhere.
326
- if (typeAhead.tooShort(e.target.value)) {
327
- setSearched(null);
328
- focusedFor.current = null;
329
- }
330
- }}
331
- onBlur={() => {
332
- // Leaving asks now rather than after the pause — a search, never a sync: it can't
333
- // create anyone and it can't change whoever it finds.
334
- typeAhead.cancel();
335
- if (query.trim() !== searched) runSearch();
336
- }}
337
- onKeyDown={(e) => onKeys(e, "query")}
338
- loading={spinning === "query"}
339
- role="combobox"
340
- aria-expanded={searched !== null}
341
- aria-autocomplete="list"
342
- aria-activedescendant={activeId ?? undefined}
343
- autoFocus
344
- {...noAutofill}
345
- />
346
- </TrackedField>
347
- </div>
348
- )}
349
- {creating && (
350
- <Grid min="200px" gap="3">
351
- <div {...focusProps}>
352
- <TrackedField formName="new_patient_form" fieldName="firstName" isOptional={false}>
353
- <Input
354
- {...gap("first")}
355
- label="First name"
356
- value={first}
357
- onChange={type("first", setFirst)}
358
- onBlur={() => leaveField("first")}
359
- onKeyDown={(e) => onKeys(e, "first")}
360
- loading={spinning === "first"}
361
- autoFocus
362
- {...noAutofill}
363
- />
364
- </TrackedField>
365
- </div>
366
- <TrackedField formName="new_patient_form" fieldName="lastName" isOptional={false}>
367
- <Input
368
- {...gap("last")}
369
- label="Last name"
370
- value={last}
371
- onChange={type("last", setLast)}
372
- onBlur={() => leaveField("last")}
373
- onKeyDown={(e) => onKeys(e, "last")}
374
- loading={spinning === "last"}
375
- {...noAutofill}
376
- />
377
- </TrackedField>
378
- {rows >= 2 && (
379
- <>
380
- <TrackedField formName="new_patient_form" fieldName="dateOfBirth" isOptional={false}>
381
- <Input
382
- {...gap("dob")}
383
- label="Date of birth"
384
- type="date"
385
- {...noAutofill}
386
- value={dob}
387
- onChange={type("dob", setDob)}
388
- onBlur={() => leaveField("dob")}
389
- onKeyDown={(e) => onKeys(e, "dob")}
390
- loading={spinning === "dob"}
391
- />
392
- </TrackedField>
393
- <div
394
- ref={sexField}
395
- onFocus={sexPicked.onFocus}
396
- onBlur={(e) => {
397
- sexPicked.onBlur(e);
398
- if (!e.currentTarget.contains(e.relatedTarget as Node | null)) visit("sex");
399
- }}
400
- onKeyDown={(e) => onKeys(e, "sex")}
401
- >
402
- <Select
403
- {...gap("sex")}
404
- label="Sex"
405
- placeholder="Select…"
406
- options={SEX_OPTIONS}
407
- value={sex}
408
- onChange={(next) => {
409
- sexPicked.onChange(true);
410
- setSex(next);
411
- visit("sex");
412
- setMissing((m) => m.filter((f) => f !== "sex"));
413
- }}
414
- />
415
- </div>
416
- {rows >= 3 && (
417
- <>
418
- <TrackedField formName="new_patient_form" fieldName="phone" isOptional>
419
- <Input
420
- label="Phone"
421
- helper="The patient is texted their order link here, so a mobile number."
422
- type="tel"
423
- inputMode="tel"
424
- pattern={PHONE_PATTERN}
425
- value={phone}
426
- onChange={type("phone", setPhone)}
427
- onBlur={() => {
428
- setPhone(formatPhone(phone));
429
- leaveField("phone");
430
- }}
431
- onKeyDown={(e) => onKeys(e, "phone")}
432
- loading={spinning === "phone"}
433
- {...noAutofill}
434
- />
435
- </TrackedField>
436
- <TrackedField formName="new_patient_form" fieldName="email" isOptional>
437
- <Input
438
- label="Email"
439
- type="email"
440
- inputMode="email"
441
- value={email}
442
- onChange={type("email", setEmail)}
443
- onBlur={() => leaveField("email")}
444
- onKeyDown={(e) => onKeys(e, "email")}
445
- loading={spinning === "email"}
446
- {...noAutofill}
447
- />
448
- </TrackedField>
449
- </>
450
- )}
451
- </>
452
- )}
453
- </Grid>
454
- )}
455
-
456
- {/* Nothing came back. That the list is empty needs no saying — the prescriber can see it. What
457
- they can't see is that matching has no tolerance for a typo, so an empty list is not "they
458
- aren't here", and adding someone already on file is how a duplicate is made. This stands in
459
- for a gap: network-api doesn't match names fuzzily yet, and when it does
460
- an empty list means what it looks like and these words should go. */}
461
- {mode === "search" && answeredNothing && (
462
- <Alert
463
- title="Spelling has to be exact."
464
- description="Try another spelling, fewer letters, or a date of birth."
465
- />
466
- )}
467
-
468
- {/* Never disabled while a search runs: typing searches, and Tab may have just put focus here.
469
- Shown for every answered search: with nobody matching, "Add new patient" is the only row —
470
- still a row, still reached by ↓ from the field, still taken with Return. */}
471
- {mode === "search" && searched !== null && (
472
- <SearchResults
473
- label={candidates.length > 0 ? "Matching patients" : "No matching patients"}
474
- results={candidates.map((m) => ({
475
- key: m.id,
476
- label: [m.firstName, m.lastName].filter(Boolean).join(" "),
477
- meta: m.dateOfBirth ? formatDate(m.dateOfBirth) : undefined,
478
- }))}
479
- onPick={(id) => void patient.pick(id).catch(() => {})}
480
- busy={busy}
481
- handleRef={matches}
482
- onBack={() => lastField.current?.focus()}
483
- // The cursor stays in the field: ↑ ↓ move a highlight, Return takes it, and a letter or a
484
- // Backspace always lands in the field — the prescriber can narrow or start over mid-list.
485
- inField
486
- onActive={setActiveId}
487
- // The last row: ↓ past the final match lands on it, and Return takes it.
488
- action={{ label: "Add new patient", icon: "add", onChoose: startCreate }}
489
- />
490
- )}
491
-
492
- {/* With the matches: why someone else is being found, what the server said, and what failed. */}
493
- {notice && <Alert tone="critical" title={notice.title} description={notice.description} />}
494
- <ChangeList changes={changes} />
495
- {snap.error && !asksForAddress(null, snap.error.message) && (
496
- <Badge tone="critical">{snap.error.message}</Badge>
497
- )}
498
-
499
- {asksAddress && (
500
- // The server asked for an address: leaving any of these fields sends again.
501
- <div onBlur={() => addressComplete && send("address")}>
502
- <Stack gap="2">
503
- {snap.error && asksForAddress(null, snap.error.message) && (
504
- <Alert tone="warning" title="Address needed" description={snap.error.message} />
505
- )}
506
- <Grid min="120px" gap="3">
507
- <TrackedField formName="new_patient_form" fieldName="address_street1" isOptional={false}>
508
- <Input
509
- label="Street"
510
- value={street1}
511
- onChange={(e) => setStreet1(e.target.value)}
512
- {...noAutofill}
513
- />
514
- </TrackedField>
515
- <TrackedField formName="new_patient_form" fieldName="address_street2" isOptional>
516
- <Input
517
- label="Apt / suite"
518
- value={street2}
519
- onChange={(e) => setStreet2(e.target.value)}
520
- {...noAutofill}
521
- />
522
- </TrackedField>
523
- </Grid>
524
- <Grid min="120px" gap="3">
525
- <TrackedField formName="new_patient_form" fieldName="address_city" isOptional={false}>
526
- <Input label="City" value={city} onChange={(e) => setCity(e.target.value)} {...noAutofill} />
527
- </TrackedField>
528
- <TrackedField formName="new_patient_form" fieldName="address_state" isOptional={false}>
529
- <Input
530
- label="State"
531
- value={state}
532
- onChange={(e) => setState(e.target.value)}
533
- maxLength={2}
534
- {...noAutofill}
535
- />
536
- </TrackedField>
537
- <TrackedField formName="new_patient_form" fieldName="address_zip" isOptional={false}>
538
- <Input
539
- label="ZIP"
540
- value={postalCode}
541
- onChange={(e) => setPostalCode(e.target.value)}
542
- inputMode="numeric"
543
- {...noAutofill}
544
- />
545
- </TrackedField>
546
- </Grid>
547
- </Stack>
548
- </div>
549
- )}
550
- </Stack>
551
- </form>
552
- </CardBody>
553
- {creating && (
554
- /* Adding a patient is a deliberate act, so it takes a press. Until this, nothing has been sent and
555
- nobody has been created — the prescriber can still fix every field above, or walk away. */
556
- <CardFooter start={busy ? <Spinner label="Adding…" /> : undefined}>
557
- <Button type="submit" form={formId} loading={busy}>
558
- Save patient
559
- </Button>
560
- </CardFooter>
561
- )}
562
- </Card>
563
- );
564
- }
@@ -1,106 +0,0 @@
1
- // @vitest-environment jsdom
2
- import { fireEvent, render, screen } 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 { PhotonPatient } from "../../index.ts";
7
- import { 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
- let analytics: RecordedAnalytics;
20
- beforeEach(() => {
21
- analytics = recordAnalytics();
22
- });
23
- afterEach(unmountAndRestoreFetch);
24
-
25
- const editPatient = async () => {
26
- render(<PhotonPatient patient="pat_1" />, {
27
- wrapper: withAnalytics(
28
- fakeNetworkApiClient({
29
- ...meAsPrescriber,
30
- GetPatient: () => payload("patient", "PatientPayload", patient),
31
- UpdatePatient: () => payload("patient", "PatientPayload", patient),
32
- }).client,
33
- ),
34
- });
35
- await userEvent.click(await screen.findByRole("button", { name: "Edit patient" }));
36
- };
37
-
38
- describe("PatientSummary: Field Interaction", () => {
39
- it("editing a patient: each field visited sends focus, one change and blur as update_patient_form", async () => {
40
- await editPatient();
41
- await typeInto("First name", "Zqx");
42
- await typeInto("Last name", "Zqx");
43
- await userEvent.click(screen.getByLabelText("Date of birth"));
44
- fireEvent.change(screen.getByLabelText("Date of birth"), { target: { value: "1991-02-03" } });
45
- leaveField();
46
- await userEvent.selectOptions(screen.getByRole("combobox", { name: "Sex" }), "FEMALE");
47
- leaveField();
48
- await typeInto("Phone", "5555550100");
49
- await typeInto("Email", "zqx@example.com");
50
- await typeInto("Street", "Zqx");
51
- await typeInto("Apt / suite", "Zqx");
52
- await typeInto("City", "Zqx");
53
- await typeInto("State", "{Backspace}Q");
54
- await typeInto("ZIP", "99999");
55
- for (const addLabel of ["Add allergy", "Add medication", "Add diagnosis"]) {
56
- await userEvent.click(screen.getByRole("button", { name: addLabel }));
57
- await userEvent.keyboard("Zqxentry");
58
- leaveField();
59
- }
60
- await userEvent.click(screen.getByRole("button", { name: "Add insurance" }));
61
- await userEvent.keyboard("987654");
62
- await userEvent.tab();
63
- await userEvent.keyboard("ZQXPCN");
64
- leaveField();
65
-
66
- const fields = {
67
- firstName: false,
68
- lastName: false,
69
- dateOfBirth: false,
70
- sex: false,
71
- phone: true,
72
- email: true,
73
- address_street1: true,
74
- address_street2: true,
75
- address_city: true,
76
- address_state: true,
77
- address_zip: true,
78
- allergies: true,
79
- medications: true,
80
- diagnoses: true,
81
- insurance: true,
82
- };
83
- await analytics.expectEventLog([
84
- "Prescribe Workflow Viewed",
85
- ...edited("firstName"),
86
- ...edited("lastName"),
87
- ...edited("dateOfBirth"),
88
- ...edited("sex"),
89
- ...edited("phone"),
90
- ...edited("email"),
91
- ...edited("address_street1"),
92
- ...edited("address_street2"),
93
- ...edited("address_city"),
94
- ...edited("address_state"),
95
- ...edited("address_zip"),
96
- ...edited("allergies"),
97
- ...edited("medications"),
98
- ...edited("diagnoses"),
99
- ...edited("insurance"),
100
- ]);
101
- const sent = analytics.fieldInteractions();
102
- expect(new Set(sent.map((s) => s.formName))).toEqual(new Set(["update_patient_form"]));
103
- expect(Object.fromEntries(sent.map((s) => [s.fieldName, s.isOptional]))).toEqual(fields);
104
- for (const body of analytics.bodies()) expect(body).not.toMatch(/Zqx|1991|5555550100|99999|987654|FEMALE/i);
105
- });
106
- });