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

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 (180) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +84 -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 +123 -0
  10. package/dist/adapters/tailwind.js.map +1 -0
  11. package/dist/components/ChangeList.d.ts +21 -0
  12. package/dist/components/ChangeList.d.ts.map +1 -0
  13. package/dist/components/ChangeList.js +40 -0
  14. package/dist/components/ChangeList.js.map +1 -0
  15. package/dist/components/PhotonOrder.d.ts +46 -0
  16. package/dist/components/PhotonOrder.d.ts.map +1 -0
  17. package/dist/components/PhotonOrder.js +270 -0
  18. package/dist/components/PhotonOrder.js.map +1 -0
  19. package/dist/components/PhotonPatient.d.ts +48 -0
  20. package/dist/components/PhotonPatient.d.ts.map +1 -0
  21. package/dist/components/PhotonPatient.js +83 -0
  22. package/dist/components/PhotonPatient.js.map +1 -0
  23. package/dist/components/PhotonPrescription.d.ts +43 -0
  24. package/dist/components/PhotonPrescription.d.ts.map +1 -0
  25. package/dist/components/PhotonPrescription.js +364 -0
  26. package/dist/components/PhotonPrescription.js.map +1 -0
  27. package/dist/components/ScreeningAlerts.d.ts +6 -0
  28. package/dist/components/ScreeningAlerts.d.ts.map +1 -0
  29. package/dist/components/ScreeningAlerts.js +11 -0
  30. package/dist/components/ScreeningAlerts.js.map +1 -0
  31. package/dist/components/SignedIn.d.ts +12 -0
  32. package/dist/components/SignedIn.d.ts.map +1 -0
  33. package/dist/components/SignedIn.js +84 -0
  34. package/dist/components/SignedIn.js.map +1 -0
  35. package/dist/components/TreatmentPicker.d.ts +45 -0
  36. package/dist/components/TreatmentPicker.d.ts.map +1 -0
  37. package/dist/components/TreatmentPicker.js +279 -0
  38. package/dist/components/TreatmentPicker.js.map +1 -0
  39. package/dist/components/activity.d.ts +7 -0
  40. package/dist/components/activity.d.ts.map +1 -0
  41. package/dist/components/activity.js +24 -0
  42. package/dist/components/activity.js.map +1 -0
  43. package/dist/components/display.d.ts +90 -0
  44. package/dist/components/display.d.ts.map +1 -0
  45. package/dist/components/display.js +223 -0
  46. package/dist/components/display.js.map +1 -0
  47. package/dist/components/flow.d.ts +35 -0
  48. package/dist/components/flow.d.ts.map +1 -0
  49. package/dist/components/flow.js +53 -0
  50. package/dist/components/flow.js.map +1 -0
  51. package/dist/components/format.d.ts +26 -0
  52. package/dist/components/format.d.ts.map +1 -0
  53. package/dist/components/format.js +61 -0
  54. package/dist/components/format.js.map +1 -0
  55. package/dist/components/index.d.ts +6 -0
  56. package/dist/components/index.d.ts.map +1 -0
  57. package/dist/components/index.js +6 -0
  58. package/dist/components/index.js.map +1 -0
  59. package/dist/components/open.d.ts +47 -0
  60. package/dist/components/open.d.ts.map +1 -0
  61. package/dist/components/open.js +73 -0
  62. package/dist/components/open.js.map +1 -0
  63. package/dist/components/patient/Benefits.d.ts +25 -0
  64. package/dist/components/patient/Benefits.d.ts.map +1 -0
  65. package/dist/components/patient/Benefits.js +47 -0
  66. package/dist/components/patient/Benefits.js.map +1 -0
  67. package/dist/components/patient/Clinical.d.ts +55 -0
  68. package/dist/components/patient/Clinical.d.ts.map +1 -0
  69. package/dist/components/patient/Clinical.js +117 -0
  70. package/dist/components/patient/Clinical.js.map +1 -0
  71. package/dist/components/patient/IntakeForm.d.ts +10 -0
  72. package/dist/components/patient/IntakeForm.d.ts.map +1 -0
  73. package/dist/components/patient/IntakeForm.js +324 -0
  74. package/dist/components/patient/IntakeForm.js.map +1 -0
  75. package/dist/components/patient/Summary.d.ts +48 -0
  76. package/dist/components/patient/Summary.d.ts.map +1 -0
  77. package/dist/components/patient/Summary.js +80 -0
  78. package/dist/components/patient/Summary.js.map +1 -0
  79. package/dist/components/patient/fields.d.ts +43 -0
  80. package/dist/components/patient/fields.d.ts.map +1 -0
  81. package/dist/components/patient/fields.js +71 -0
  82. package/dist/components/patient/fields.js.map +1 -0
  83. package/dist/components/patient/query.d.ts +23 -0
  84. package/dist/components/patient/query.d.ts.map +1 -0
  85. package/dist/components/patient/query.js +65 -0
  86. package/dist/components/patient/query.js.map +1 -0
  87. package/dist/components/search.d.ts +154 -0
  88. package/dist/components/search.d.ts.map +1 -0
  89. package/dist/components/search.js +295 -0
  90. package/dist/components/search.js.map +1 -0
  91. package/dist/hooks/index.d.ts +5 -0
  92. package/dist/hooks/index.d.ts.map +1 -0
  93. package/dist/hooks/index.js +5 -0
  94. package/dist/hooks/index.js.map +1 -0
  95. package/dist/hooks/useLatestCallback.d.ts +7 -0
  96. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  97. package/dist/hooks/useLatestCallback.js +14 -0
  98. package/dist/hooks/useLatestCallback.js.map +1 -0
  99. package/dist/hooks/useLive.d.ts +15 -0
  100. package/dist/hooks/useLive.d.ts.map +1 -0
  101. package/dist/hooks/useLive.js +6 -0
  102. package/dist/hooks/useLive.js.map +1 -0
  103. package/dist/hooks/useOnChange.d.ts +11 -0
  104. package/dist/hooks/useOnChange.d.ts.map +1 -0
  105. package/dist/hooks/useOnChange.js +28 -0
  106. package/dist/hooks/useOnChange.js.map +1 -0
  107. package/dist/hooks/useSession.d.ts +7 -0
  108. package/dist/hooks/useSession.d.ts.map +1 -0
  109. package/dist/hooks/useSession.js +10 -0
  110. package/dist/hooks/useSession.js.map +1 -0
  111. package/dist/index.d.ts +20 -0
  112. package/dist/index.d.ts.map +1 -0
  113. package/dist/index.js +19 -0
  114. package/dist/index.js.map +1 -0
  115. package/dist/primitives/PhotonProvider.d.ts +58 -0
  116. package/dist/primitives/PhotonProvider.d.ts.map +1 -0
  117. package/dist/primitives/PhotonProvider.js +91 -0
  118. package/dist/primitives/PhotonProvider.js.map +1 -0
  119. package/dist/primitives/defaults.d.ts +3 -0
  120. package/dist/primitives/defaults.d.ts.map +1 -0
  121. package/dist/primitives/defaults.js +67 -0
  122. package/dist/primitives/defaults.js.map +1 -0
  123. package/dist/primitives/icons.d.ts +6 -0
  124. package/dist/primitives/icons.d.ts.map +1 -0
  125. package/dist/primitives/icons.js +6 -0
  126. package/dist/primitives/icons.js.map +1 -0
  127. package/dist/primitives/index.d.ts +5 -0
  128. package/dist/primitives/index.d.ts.map +1 -0
  129. package/dist/primitives/index.js +5 -0
  130. package/dist/primitives/index.js.map +1 -0
  131. package/dist/primitives/select.d.ts +7 -0
  132. package/dist/primitives/select.d.ts.map +1 -0
  133. package/dist/primitives/select.js +16 -0
  134. package/dist/primitives/select.js.map +1 -0
  135. package/dist/primitives/types.d.ts +276 -0
  136. package/dist/primitives/types.d.ts.map +1 -0
  137. package/dist/primitives/types.js +3 -0
  138. package/dist/primitives/types.js.map +1 -0
  139. package/dist/styles.css +611 -0
  140. package/dist/test-utils/contract.d.ts +17 -0
  141. package/dist/test-utils/contract.d.ts.map +1 -0
  142. package/dist/test-utils/contract.js +261 -0
  143. package/dist/test-utils/contract.js.map +1 -0
  144. package/package.json +74 -4
  145. package/src/adapters/index.ts +1 -0
  146. package/src/adapters/tailwind.tsx +544 -0
  147. package/src/components/ChangeList.tsx +85 -0
  148. package/src/components/PhotonOrder.tsx +493 -0
  149. package/src/components/PhotonPatient.tsx +184 -0
  150. package/src/components/PhotonPrescription.tsx +605 -0
  151. package/src/components/ScreeningAlerts.tsx +28 -0
  152. package/src/components/SignedIn.tsx +144 -0
  153. package/src/components/TreatmentPicker.tsx +350 -0
  154. package/src/components/activity.ts +23 -0
  155. package/src/components/display.ts +278 -0
  156. package/src/components/flow.ts +67 -0
  157. package/src/components/format.ts +73 -0
  158. package/src/components/index.ts +5 -0
  159. package/src/components/open.ts +100 -0
  160. package/src/components/patient/Benefits.tsx +125 -0
  161. package/src/components/patient/Clinical.tsx +210 -0
  162. package/src/components/patient/IntakeForm.tsx +532 -0
  163. package/src/components/patient/Summary.tsx +310 -0
  164. package/src/components/patient/fields.tsx +144 -0
  165. package/src/components/patient/query.ts +77 -0
  166. package/src/components/search.tsx +377 -0
  167. package/src/hooks/index.ts +4 -0
  168. package/src/hooks/useLatestCallback.ts +16 -0
  169. package/src/hooks/useLive.ts +21 -0
  170. package/src/hooks/useOnChange.ts +34 -0
  171. package/src/hooks/useSession.ts +11 -0
  172. package/src/index.ts +19 -0
  173. package/src/primitives/PhotonProvider.tsx +153 -0
  174. package/src/primitives/defaults.tsx +409 -0
  175. package/src/primitives/icons.tsx +37 -0
  176. package/src/primitives/index.ts +4 -0
  177. package/src/primitives/select.ts +15 -0
  178. package/src/primitives/types.ts +276 -0
  179. package/src/styles.css +611 -0
  180. package/src/test-utils/contract.tsx +410 -0
@@ -0,0 +1,278 @@
1
+ import type { Treatment } from "@photonhealth/client";
2
+
3
+ /**
4
+ * How the cards show drug choices — pure functions: order them, group them by drug, form and strength, and
5
+ * name a pick. network-api's options carry the drug in parts (`treatment`: brand, generic, form, route,
6
+ * strength); a name is read only when they don't (equipment, an option without its entity).
7
+ */
8
+ const naturalOrder = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
9
+ const words = (name: string) => name.trim().split(/\s+/).length;
10
+
11
+ /**
12
+ * A change's options in the order a prescriber scans them: closest to what they typed first (exact
13
+ * name, then names starting with it, then the rest), the most general (fewest words) first within
14
+ * each group, then natural order (2.5, 5, 10 MG),
15
+ * and one row per name — the server can return the same name twice ("Penicillins", "penicillin G" /
16
+ * "Penicillin G"), which reads as noise.
17
+ */
18
+ export function orderedOptions<O extends { displayName: string }>(
19
+ change: { options?: O[] | null },
20
+ typed?: string | null,
21
+ ) {
22
+ const q = typed?.trim().toLowerCase() ?? "";
23
+ // Exact → starts with it as a word ("Penicillins", "Omeprazole Oral …") → a combination starting
24
+ // with it ("Omeprazole-Sodium Bicarbonate …") → starts with it ("Penicillinase") → a later word
25
+ // starts with it → merely contains it.
26
+ const escaped = q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27
+ const asWord = new RegExp(`^${escaped}(s|es)?(\\s|$)`);
28
+ const asCombination = new RegExp(`^${escaped}(s|es)?[-/]`);
29
+ const rank = (name: string) => {
30
+ const n = name.toLowerCase();
31
+ if (!q) return 0;
32
+ if (n === q) return 0;
33
+ if (asWord.test(n)) return 1;
34
+ if (asCombination.test(n)) return 2;
35
+ if (n.startsWith(q)) return 3;
36
+ return n.split(/[\s/-]+/).some((w) => w.startsWith(q)) ? 4 : 5;
37
+ };
38
+ const seen = new Set<string>();
39
+ return (change.options ?? [])
40
+ .filter((o) => {
41
+ const key = o.displayName.trim().toLowerCase();
42
+ return seen.has(key) ? false : (seen.add(key), true);
43
+ })
44
+ .sort(
45
+ (a, b) =>
46
+ rank(a.displayName) - rank(b.displayName) ||
47
+ words(a.displayName) - words(b.displayName) || // the general term first ("Penicillins")
48
+ naturalOrder.compare(a.displayName, b.displayName),
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The server offers drug choices as products ("Lisinopril Oral Tablet 10 MG"). A prescriber picks a drug, then
54
+ * its form, then its strength — so group them that way, by the parts each option's `treatment` carries. An
55
+ * option without them is read from its name; one that doesn't parse becomes a drug with one unnamed option —
56
+ * still pickable.
57
+ */
58
+
59
+ interface TreatmentStrength<O> {
60
+ /** "10 mg", "125 mg/5 mL"; "" when there's none. */
61
+ label: string;
62
+ option: O;
63
+ }
64
+ interface TreatmentForm<O> {
65
+ /** "Tablet" — with its route ("Oral tablet") when the drug comes by more than one; "" when there's none. */
66
+ label: string;
67
+ strengths: TreatmentStrength<O>[];
68
+ }
69
+ interface TreatmentDrug<O> {
70
+ /** As the server spells it ("metFORMIN HCl", "Zepbound KwikPen"). */
71
+ name: string;
72
+ /** Its ingredients, when the name doesn't already say them ("Lipitor" → "Atorvastatin Calcium"). */
73
+ generic: string | null;
74
+ /** "Schedule II" for a controlled substance; null otherwise (or not known). */
75
+ schedule: string | null;
76
+ forms: TreatmentForm<O>[];
77
+ }
78
+
79
+ type DrugOption = { displayName: string; treatment?: Treatment | null };
80
+
81
+ // A drug name ends at the first word that starts a dose form or route (RxNorm vocabulary).
82
+ // Release abbreviations count, so "metFORMIN HCl ER Oral Tablet …" groups under "metFORMIN HCl".
83
+ const FORM_WORDS = new Set(
84
+ (
85
+ "Oral Topical Ophthalmic Otic Nasal Injection Injectable Intravenous Intramuscular Subcutaneous " +
86
+ "Transdermal Rectal Vaginal Inhalation Inhalant Sublingual Buccal Cutaneous Prefilled Auto-Injector " +
87
+ "Pen Cartridge Kit Pack Tablet Tablets Capsule Capsules Solution Suspension Cream Ointment Gel Lotion " +
88
+ "Shampoo Foam Patch Powder Spray Aerosol Film Lozenge Troche Suppository Drops Syrup Elixir " +
89
+ "Chewable ODT ER DR XR XL SR CR 12HR 24HR"
90
+ ).split(" "),
91
+ );
92
+ // "10 MG", "1000-62.5 MG", "500 & 500 & 30 MG", "125 MG/5ML", "0.1 %", "100 UNT/ML".
93
+ const STRENGTH = String.raw`(?:\d[\d.,]*(?:-\d[\d.,]*)*\s*(?:&\s*)?)+(?:[A-Za-z]+|%)(?:\/[\d.]*\s*[A-Za-z]+)?`;
94
+ const TRAILING_STRENGTH = new RegExp(String.raw`^(.*?)\s(${STRENGTH})$`);
95
+ const MIDDLE_STRENGTH = new RegExp(String.raw`^(.*?)\s(${STRENGTH})\s(.+)$`);
96
+
97
+ const UNITS: Record<string, string> = {
98
+ MG: "mg",
99
+ MCG: "mcg",
100
+ G: "g",
101
+ ML: "mL",
102
+ L: "L",
103
+ MEQ: "mEq",
104
+ UNT: "units",
105
+ HR: "hr",
106
+ ACTUAT: "actuation",
107
+ };
108
+
109
+ /** "125 MG/5ML" → "125 mg/5 mL". */
110
+ export function formatStrength(strength: string): string {
111
+ return strength
112
+ .replace(/(\d)([A-Za-z])/g, "$1 $2")
113
+ .replace(/[A-Za-z]+/g, (unit) => UNITS[unit.toUpperCase()] ?? unit)
114
+ .replace(/\s+/g, " ")
115
+ .trim();
116
+ }
117
+
118
+ /** "ER (MOD) Oral Tablet Extended Release 24 Hour" → "Oral tablet extended release 24 hour". */
119
+ export function formatForm(form: string): string {
120
+ let words = form.trim().split(/\s+/).filter(Boolean);
121
+ // A leading release abbreviation repeats what "… Extended Release" spells out.
122
+ if (/\bRelease\b/i.test(form)) {
123
+ while (words.length > 1 && (/^(ER|DR|XR|XL|SR|CR)$/.test(words[0]!) || /^\(.*\)$/.test(words[0]!))) {
124
+ words = words.slice(1);
125
+ }
126
+ }
127
+ const text = words.join(" ");
128
+ if (!text) return "";
129
+ return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
130
+ }
131
+
132
+ /** "Lisinopril Oral Tablet 10 MG" → { drug: "Lisinopril", form: "Oral Tablet", strength: "10 MG" }. */
133
+ export function parseTreatmentName(displayName: string): { drug: string; form: string; strength: string } {
134
+ const name = displayName.trim().replace(/\s+/g, " ");
135
+ let rest = name;
136
+ let strength = "";
137
+ let trailingForm = "";
138
+ const trailing = TRAILING_STRENGTH.exec(name);
139
+ const middle = trailing ? null : MIDDLE_STRENGTH.exec(name);
140
+ if (trailing) {
141
+ rest = trailing[1]!;
142
+ strength = trailing[2]!;
143
+ } else if (middle) {
144
+ // RxNorm's own order: "Amoxicillin 500 MG Oral Capsule".
145
+ rest = middle[1]!;
146
+ strength = middle[2]!;
147
+ trailingForm = middle[3]!;
148
+ }
149
+ const words = rest.split(" ");
150
+ const at = words.findIndex((w, i) => i > 0 && FORM_WORDS.has(w));
151
+ const drug = at === -1 ? rest : words.slice(0, at).join(" ");
152
+ const form = [at === -1 ? "" : words.slice(at).join(" "), trailingForm].filter(Boolean).join(" ");
153
+ return { drug, form, strength };
154
+ }
155
+
156
+ /** A product's parts: the treatment's, when it has them; else read from its name. */
157
+ export function treatmentParts(
158
+ name: string,
159
+ treatment?: Treatment | null,
160
+ ): { drug: string; route: string; form: string; strength: string } {
161
+ if (treatment?.form || treatment?.strength) {
162
+ return {
163
+ drug: treatment.brandName ?? parseTreatmentName(name).drug,
164
+ route: treatment.route ?? "",
165
+ form: treatment.form ?? "",
166
+ strength: treatment.strength ?? "",
167
+ };
168
+ }
169
+ return { route: "", ...parseTreatmentName(name) };
170
+ }
171
+
172
+ const squash = (name: string) =>
173
+ name
174
+ .toLowerCase()
175
+ .replace(/\s*[&/-]\s*/g, "-")
176
+ .replace(/\s+/g, " ");
177
+
178
+ /** The ingredients, when the drug's name doesn't start with them: a brand ("Lipitor"), not a generic ("Lisinopril"). */
179
+ export function genericOf(drug: string, treatment?: Treatment | null): string | null {
180
+ const generic = treatment?.genericName?.trim();
181
+ return generic && !squash(drug).startsWith(squash(generic)) ? generic : null;
182
+ }
183
+
184
+ /** "II" → "Schedule II"; null when uncontrolled or not known. */
185
+ export function scheduleOf(treatment?: Treatment | null): string | null {
186
+ const schedule = treatment?.schedule?.trim();
187
+ return schedule && schedule.toUpperCase() !== "UNCONTROLLED" ? `Schedule ${schedule}` : null;
188
+ }
189
+
190
+ /**
191
+ * Group drug options (already in the order to show them — see orderedOptions) by drug, then form,
192
+ * then strength. Drugs keep the order they first appear in; forms go most strengths first (the
193
+ * drug's main form, e.g. tablet before solution); strengths sort naturally (2.5, 5, 10 mg).
194
+ */
195
+ export function groupTreatmentOptions<O extends DrugOption>(options: readonly O[]): TreatmentDrug<O>[] {
196
+ type Entry = { route: string; form: string; strength: string; option: O };
197
+ const drugs = new Map<string, { name: string; generic: string | null; schedule: string | null; entries: Entry[] }>();
198
+ for (const option of options) {
199
+ const { drug, ...parts } = treatmentParts(option.displayName, option.treatment);
200
+ const key = drug.toLowerCase();
201
+ const group = drugs.get(key) ?? {
202
+ name: drug,
203
+ generic: genericOf(drug, option.treatment),
204
+ schedule: scheduleOf(option.treatment),
205
+ entries: [],
206
+ };
207
+ drugs.set(key, group);
208
+ group.entries.push({ ...parts, option });
209
+ }
210
+ return [...drugs.values()].map(({ name, generic, schedule, entries }) => {
211
+ // The route only tells forms apart when the drug comes by more than one ("Oral solution", "Intravenous solution").
212
+ const routes = new Set(entries.map((e) => e.route.toLowerCase()));
213
+ const forms = new Map<string, TreatmentStrength<O>[]>();
214
+ for (const e of entries) {
215
+ const label = formatForm(routes.size > 1 ? `${e.route} ${e.form}` : e.form);
216
+ const strengths = forms.get(label) ?? [];
217
+ forms.set(label, strengths);
218
+ strengths.push({ label: formatStrength(e.strength), option: e.option });
219
+ }
220
+ return {
221
+ name,
222
+ generic,
223
+ schedule,
224
+ forms: [...forms]
225
+ .map(([label, strengths]) => ({
226
+ label,
227
+ strengths: strengths.sort((a, b) => naturalOrder.compare(a.label, b.label)),
228
+ }))
229
+ // The drug's main form (the one with the most strengths) first; ties keep the server's order.
230
+ .sort((a, b) => b.strengths.length - a.strengths.length),
231
+ };
232
+ });
233
+ }
234
+
235
+ /** A drug's strengths across its forms, each once, in natural order (2.5, 5, 10 mg). */
236
+ export function strengthsOf(drug: TreatmentDrug<unknown>): string[] {
237
+ const labels = new Set(drug.forms.flatMap((f) => f.strengths.map((s) => s.label)));
238
+ return [...labels].sort((a, b) => naturalOrder.compare(a, b));
239
+ }
240
+
241
+ /**
242
+ * What a drug's row says under its name: a brand's ingredients, its form and its strength — the one there is
243
+ * ("Oral tablet · 25 mg"), or how many ("2 forms · 3 strengths"; `counts: false` leaves those to an open row's
244
+ * chips) — and a controlled substance's schedule. A strength the drug comes in by more than one form counts once.
245
+ */
246
+ export function describeTreatmentDrug(drug: TreatmentDrug<unknown>, counts = true): string | null {
247
+ const strengths = strengthsOf(drug);
248
+ const [form] = drug.forms;
249
+ const parts = [
250
+ drug.generic,
251
+ drug.forms.length === 1 ? form!.label : counts ? `${drug.forms.length} forms` : null,
252
+ strengths.length === 1 ? strengths[0] : counts ? `${strengths.length} strengths` : null,
253
+ drug.schedule,
254
+ ];
255
+ return parts.filter(Boolean).join(" · ") || null;
256
+ }
257
+
258
+ /**
259
+ * How a picked product heads its prescription: the drug alone over the rest — "Lisinopril Oral Tablet 10 MG" →
260
+ * { title: "Lisinopril", detail: "Oral tablet · 10 mg" }. With the treatment's parts, the detail also says a
261
+ * brand's ingredients and a controlled substance's schedule ("Lipitor" over "Atorvastatin Calcium · Oral
262
+ * tablet · 20 mg"). A name with no form or strength (e.g. a resolved treatment that's only the ingredient) is
263
+ * the title as given.
264
+ */
265
+ export function treatmentHeading(
266
+ displayName: string,
267
+ treatment?: Treatment | null,
268
+ ): { title: string; detail: string | null } {
269
+ const { drug, route, form, strength } = treatmentParts(displayName, treatment);
270
+ const parts = form || strength;
271
+ const detail = [
272
+ genericOf(drug, treatment),
273
+ parts && formatForm([route, form].filter(Boolean).join(" ")),
274
+ parts && formatStrength(strength),
275
+ scheduleOf(treatment),
276
+ ];
277
+ return { title: parts ? drug : displayName.trim(), detail: detail.filter(Boolean).join(" · ") || null };
278
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The card flow: in a view of several cards (PhotonOrder: the patient, each prescription, "Add another",
3
+ * Send), ← → (or h l) move to the previous / next card, and / goes to the search box (`searchProps`: the
4
+ * patient's first name until they're found, then Treatment) — when focus is in the view but not somewhere
5
+ * those keys already mean something (typing, a select, a radio group). Never page-wide: a host's own
6
+ * shortcuts keep working outside the cards. Each card is marked `data-prx-card` (`cardProps`), in order,
7
+ * and marks where focus lands in it (`focusProps`: the drug list while choosing, Treatment while searching,
8
+ * the sig once a drug is set, the patient's first field or edit pencil). A card with nowhere to land (e.g. a
9
+ * signed prescription) is passed over.
10
+ */
11
+ import type { KeyboardEvent } from "react";
12
+ import { took } from "./search.tsx";
13
+
14
+ /** Mark a card in the flow. `display: contents`: the wrapper adds no box, so a host's layout is unchanged. */
15
+ export const cardProps = { "data-prx-card": "", style: { display: "contents" } } as const;
16
+
17
+ /** Mark where focus lands in a card: this element, or the first focusable inside it. */
18
+ export const focusProps = { "data-prx-focus": "", style: { display: "contents" } } as const;
19
+
20
+ /** Mark the view's search box (the first one marked, in order, is where / goes). */
21
+ export const searchProps = { "data-prx-search": "" } as const;
22
+
23
+ /** Where the arrows are already the field's own (a caret, an option, a radio). */
24
+ const OWN_ARROWS =
25
+ 'input, textarea, select, [contenteditable=""], [contenteditable="true"], [role="combobox"], [role="listbox"], [role="radiogroup"], [role="radio"], [role="slider"], [role="tab"]';
26
+ const FOCUSABLE =
27
+ '[tabindex="0"], input:not([type="hidden"]):not(:disabled), textarea:not(:disabled), select:not(:disabled), button:not(:disabled), a[href]';
28
+
29
+ function focusIn(card: Element): HTMLElement | null {
30
+ for (const mark of card.querySelectorAll<HTMLElement>("[data-prx-focus]")) {
31
+ const target = mark.matches(FOCUSABLE) ? mark : mark.querySelector<HTMLElement>(FOCUSABLE);
32
+ if (target) return target;
33
+ }
34
+ return null;
35
+ }
36
+
37
+ /**
38
+ * The flow's onKeyDown, on an element around its cards: ← / → (h / l) focus the previous / next card that has
39
+ * somewhere to land; / focuses the search box.
40
+ */
41
+ export function cardFlowKeys(e: KeyboardEvent<HTMLElement>) {
42
+ if (e.defaultPrevented || e.altKey || e.metaKey || e.ctrlKey) return;
43
+ const from = e.target as HTMLElement;
44
+ if (from.closest(OWN_ARROWS)) return;
45
+ if (e.key === "/") {
46
+ const search = e.currentTarget.querySelector<HTMLElement>(
47
+ "[data-prx-search] input:not(:disabled), [data-prx-search] textarea:not(:disabled)",
48
+ );
49
+ if (search) {
50
+ took(e);
51
+ search.focus();
52
+ }
53
+ return;
54
+ }
55
+ const step = e.key === "ArrowRight" || e.key === "l" ? 1 : e.key === "ArrowLeft" || e.key === "h" ? -1 : 0;
56
+ if (!step || e.shiftKey) return;
57
+ const cards = [...e.currentTarget.querySelectorAll("[data-prx-card]")];
58
+ const at = cards.findIndex((card) => card.contains(from));
59
+ if (at < 0) return;
60
+ for (let i = at + step; i >= 0 && i < cards.length; i += step) {
61
+ const target = focusIn(cards[i]!);
62
+ if (!target) continue;
63
+ took(e);
64
+ target.focus();
65
+ return;
66
+ }
67
+ }
@@ -0,0 +1,73 @@
1
+ /** Display formatting, plus the one normalisation we send back (phone → E.164). */
2
+
3
+ /** "+13174504573" / "3174504573" → "+1 (317) 450-4573"; anything else is shown as given. */
4
+ export function formatPhone(phone: string | null | undefined): string {
5
+ if (!phone) return "";
6
+ const digits = phone.replace(/\D/g, "");
7
+ const us = digits.length === 11 && digits.startsWith("1") ? digits.slice(1) : digits.length === 10 ? digits : null;
8
+ return us ? `+1 (${us.slice(0, 3)}) ${us.slice(3, 6)}-${us.slice(6)}` : phone;
9
+ }
10
+
11
+ /** Native validation for type="tel": a US number, punctuated any common way (+1 optional). */
12
+ export const PHONE_PATTERN = String.raw`\+?1?[\s.\-]*\(?\d{3}\)?[\s.\-]*\d{3}[\s.\-]*\d{4}`;
13
+
14
+ /** "(317) 450-4573" → "+13174504573" (what network-api stores); non-US kept as typed; blank → undefined. */
15
+ export function toE164(phone: string): string | undefined {
16
+ const trimmed = phone.trim();
17
+ if (!trimmed) return undefined;
18
+ const digits = trimmed.replace(/\D/g, "");
19
+ if (digits.length === 10) return `+1${digits}`;
20
+ if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
21
+ return trimmed;
22
+ }
23
+
24
+ /** Whole years old on `today` for an ISO date of birth; null if there's no valid DOB. */
25
+ export function ageOn(dob: string | null | undefined, today: Date = new Date()): number | null {
26
+ const m = dob ? /^(\d{4})-(\d{2})-(\d{2})/.exec(dob) : null;
27
+ if (!m) return null;
28
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
29
+ const hadBirthday = today.getMonth() + 1 > mo || (today.getMonth() + 1 === mo && today.getDate() >= d);
30
+ return today.getFullYear() - y - (hadBirthday ? 0 : 1);
31
+ }
32
+
33
+ /** "1991-07-08" → "07-08-1991". */
34
+ export function formatDate(iso: string | null | undefined): string {
35
+ const m = iso ? /^(\d{4})-(\d{2})-(\d{2})/.exec(iso) : null;
36
+ return m ? `${m[2]}-${m[3]}-${m[1]}` : (iso ?? "");
37
+ }
38
+
39
+ /** "1991-07-08" → "7/8/91" — a date said in passing (a patient's DOB under their name). */
40
+ export function shortDate(iso: string | null | undefined): string {
41
+ const m = iso ? /^\d{2}(\d{2})-(\d{2})-(\d{2})/.exec(iso) : null;
42
+ return m ? `${Number(m[2])}/${Number(m[3])}/${m[1]}` : (iso ?? "");
43
+ }
44
+
45
+ /** "otto sipe" → "Otto Sipe"; a name typed with any capitals is shown as typed ("McDonald", "de la Cruz"). */
46
+ export const displayName = (name: string) =>
47
+ name === name.toLowerCase()
48
+ ? name.replace(/(^|[\s'-])(\p{L})/gu, (_, sep: string, ch: string) => sep + ch.toUpperCase())
49
+ : name;
50
+
51
+ /** "30 tablets · 90 days · 3 refills · DAW" — what's dispensed, said once (a card, a choice, the Sent summary). */
52
+ export function dispenseSummary(rx: {
53
+ dispense?: {
54
+ quantity?: number | null;
55
+ unit?: string | null;
56
+ daysSupply?: number | null;
57
+ refillsAllowed?: number | null;
58
+ dispenseAsWritten?: boolean | null;
59
+ } | null;
60
+ }): string {
61
+ const d = rx.dispense;
62
+ // Countable forms read as plural ("30 tablets"); anything else ("mL") is shown as the server has it.
63
+ const unit =
64
+ d?.unit && /^(tablet|capsule)$/i.test(d.unit) ? d.unit.toLowerCase() + (d.quantity === 1 ? "" : "s") : d?.unit;
65
+ return [
66
+ d?.quantity != null && `${d.quantity} ${unit ?? ""}`.trim(),
67
+ d?.daysSupply != null && `${d.daysSupply} days`,
68
+ d?.refillsAllowed != null && `${d.refillsAllowed} refill${d.refillsAllowed === 1 ? "" : "s"}`,
69
+ d?.dispenseAsWritten && "DAW",
70
+ ]
71
+ .filter(Boolean)
72
+ .join(" · ");
73
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./ChangeList.tsx";
2
+ export { PhotonPatient, type PhotonPatientProps } from "./PhotonPatient.tsx";
3
+ export { PhotonPrescription, type PhotonPrescriptionProps } from "./PhotonPrescription.tsx";
4
+ export * from "./PhotonOrder.tsx";
5
+ export * from "./TreatmentPicker.tsx";
@@ -0,0 +1,100 @@
1
+ import type { Calls } from "@photonhealth/client";
2
+ import { useEffect, useState } from "react";
3
+
4
+ /**
5
+ * What a card is given for one record — any of: its id (`"pat_…"` or `{ id }`: read, `get`), the record's fields
6
+ * with its id (`update(id, fields)`: only those change), or fields without one (`sync`: the server finds,
7
+ * matches or creates). A live object instead is used as given and never comes here. Links give records the same
8
+ * way.
9
+ */
10
+ export type Given<I extends object> = I | string;
11
+
12
+ /**
13
+ * A record given by id that the server doesn't have — network-api opens records only in the prescriber's own
14
+ * organization, so a link from another one lands here too.
15
+ */
16
+ export class NotFound extends Error {
17
+ constructor(what: string, id: string) {
18
+ super(`There's no ${what} ${id} in this organization.`);
19
+ this.name = "NotFound";
20
+ }
21
+ }
22
+
23
+ /** A card's title for a record it couldn't open: not found, or couldn't. */
24
+ export const openFailed = (what: string, error: Error) =>
25
+ error instanceof NotFound ? `${what[0]!.toUpperCase()}${what.slice(1)} not found` : `Couldn't open this ${what}`;
26
+
27
+ /** How a given record opens: `get`, `update` or `sync` — and with what. */
28
+ export function callFor<I extends object>(
29
+ value: Given<I>,
30
+ ): { call: "get"; id: string } | { call: "update"; id: string; fields: Omit<I, "id"> } | { call: "sync"; input: I } {
31
+ if (typeof value === "string") return { call: "get", id: value };
32
+ const { id, ...fields } = value as I & { id?: string };
33
+ if (!id) return { call: "sync", input: value };
34
+ return Object.keys(fields).length ? { call: "update", id, fields: fields as Omit<I, "id"> } : { call: "get", id };
35
+ }
36
+
37
+ /** Open a given record (see `Given`); null when an id has no record. */
38
+ export function openGiven<T, I extends object, R>(
39
+ calls: Calls<T, I, Omit<I, "id">, R>,
40
+ value: Given<I>,
41
+ objectOf: (result: R) => T | null,
42
+ ): Promise<T | null> {
43
+ return shared(calls, JSON.stringify(value), async () => {
44
+ const how = callFor(value);
45
+ if (how.call === "get") return calls.get(how.id);
46
+ return objectOf(await (how.call === "update" ? calls.update(how.id, how.fields) : calls.sync(how.input)));
47
+ });
48
+ }
49
+
50
+ const inFlight = new WeakMap<object, Map<string, Promise<unknown>>>();
51
+
52
+ /**
53
+ * The same open already in flight, shared: React's StrictMode runs an effect twice, and opening from an input
54
+ * writes (a sync). `scope` is what it's opened through (the calls, a photon instance), `key` what it's given.
55
+ */
56
+ export function shared<T>(scope: object, key: string, run: () => Promise<T>): Promise<T> {
57
+ const pending = inFlight.get(scope) ?? new Map<string, Promise<unknown>>();
58
+ inFlight.set(scope, pending);
59
+ const running = pending.get(key);
60
+ if (running) return running as Promise<T>;
61
+ const started = run().finally(() => pending.delete(key));
62
+ pending.set(key, started);
63
+ return started;
64
+ }
65
+
66
+ /** A record given as something to open: an id, or an input with something in it (an empty input is none). */
67
+ export const toOpen = <I extends object>(value: Given<I> | object | null | undefined, isLive: boolean) =>
68
+ !isLive && value && (typeof value === "string" || Object.keys(value).length) ? (value as Given<I>) : null;
69
+
70
+ /**
71
+ * `openGiven` for a card: the object once it's open, or why it couldn't be. Opens again when what it's given
72
+ * changes (by value).
73
+ */
74
+ export function useOpened<T, I extends object, R>(
75
+ calls: Calls<T, I, Omit<I, "id">, R>,
76
+ value: Given<I> | null,
77
+ objectOf: (result: R) => T | null,
78
+ what: string,
79
+ ): { opened: T | null; error: Error | null } {
80
+ const key = JSON.stringify(value);
81
+ const [state, setState] = useState<{ key: string; opened: T | null; error: Error | null }>({
82
+ key: "",
83
+ opened: null,
84
+ error: null,
85
+ });
86
+ useEffect(() => {
87
+ const wanted = JSON.parse(key) as Given<I> | null;
88
+ if (!wanted) return;
89
+ let live = true;
90
+ const id = typeof wanted === "string" ? wanted : ((wanted as { id?: string }).id ?? "");
91
+ openGiven(calls, wanted, objectOf).then(
92
+ (opened) => live && setState({ key, opened, error: opened ? null : new NotFound(what, id) }),
93
+ (error: Error) => live && setState({ key, opened: null, error }),
94
+ );
95
+ return () => {
96
+ live = false;
97
+ };
98
+ }, [calls, key, objectOf, what]);
99
+ return state.key === key ? state : { opened: null, error: null };
100
+ }
@@ -0,0 +1,125 @@
1
+ /** The patient's insurance on file. */
2
+ import { useState } from "react";
3
+ import { useComponents } from "../../primitives/index.ts";
4
+ import { noAutofill } from "./fields.tsx";
5
+
6
+ export type BenefitInput = { id?: string; bin?: string; pcn?: string; groupId?: string; memberId?: string };
7
+
8
+ /** Insurance on file: chips, "Add insurance" (BIN + member id required, PCN / group optional), "No insurance". */
9
+ export function BenefitsSection({
10
+ benefits,
11
+ saving,
12
+ onAdd,
13
+ onRemove,
14
+ onNone,
15
+ }: {
16
+ /** null: not recorded; []: "no insurance" recorded. */
17
+ benefits: { id: string; bin: string; pcn: string | null; groupId: string | null; memberId: string }[] | null;
18
+ saving: boolean;
19
+ onAdd: (benefit: BenefitInput) => void;
20
+ onRemove: (benefit: { id: string }) => void;
21
+ onNone: () => void;
22
+ }) {
23
+ const { Badge, Button, Grid, Input, Row, Stack, Text } = useComponents();
24
+ const [adding, setAdding] = useState(false);
25
+ const [bin, setBin] = useState("");
26
+ const [pcn, setPcn] = useState("");
27
+ const [groupId, setGroupId] = useState("");
28
+ const [memberId, setMemberId] = useState("");
29
+ const none = benefits?.length === 0;
30
+ const plans = benefits ?? [];
31
+ const canSave = Boolean(bin.trim() && memberId.trim());
32
+ const reset = () => {
33
+ setBin("");
34
+ setPcn("");
35
+ setGroupId("");
36
+ setMemberId("");
37
+ setAdding(false);
38
+ };
39
+
40
+ return (
41
+ <Stack gap="2">
42
+ <Row gap="2" justify="between">
43
+ <Row gap="2">
44
+ <strong>Insurance</strong>
45
+ {!adding && (
46
+ <Button
47
+ variant="ghost"
48
+ aria-label="Add insurance"
49
+ title="Add insurance"
50
+ onClick={() => setAdding(true)}
51
+ icon="add"
52
+ />
53
+ )}
54
+ {plans.map((b) => {
55
+ const label = [
56
+ `BIN ${b.bin}`,
57
+ b.pcn && `PCN ${b.pcn}`,
58
+ b.groupId && `Group ${b.groupId}`,
59
+ `Member ${b.memberId}`,
60
+ ]
61
+ .filter(Boolean)
62
+ .join(" · ");
63
+ return (
64
+ <Badge key={b.id} tone="neutral" onRemove={() => onRemove(b)} removeLabel={`Remove ${label}`}>
65
+ {label}
66
+ </Badge>
67
+ );
68
+ })}
69
+ {none && <Badge tone="success">No insurance</Badge>}
70
+ {benefits === null && !adding && <Text tone="tertiary">Not recorded</Text>}
71
+ </Row>
72
+ {!adding && (
73
+ <Row gap="1">
74
+ {!plans.length && !none && (
75
+ <Button variant="ghost" onClick={onNone} aria-label="Mark no insurance">
76
+ Mark none
77
+ </Button>
78
+ )}
79
+ </Row>
80
+ )}
81
+ </Row>
82
+ {adding && (
83
+ // A form, so Enter in any field saves the plan.
84
+ <form
85
+ {...noAutofill}
86
+ onSubmit={(e) => {
87
+ e.preventDefault();
88
+ if (!canSave) return;
89
+ onAdd({
90
+ bin: bin.trim(),
91
+ memberId: memberId.trim(),
92
+ pcn: pcn.trim() || undefined,
93
+ groupId: groupId.trim() || undefined,
94
+ });
95
+ reset();
96
+ }}
97
+ >
98
+ <Stack gap="2">
99
+ <Grid min="72px" gap="2">
100
+ <Input
101
+ label="BIN"
102
+ value={bin}
103
+ onChange={(e) => setBin(e.target.value)}
104
+ inputMode="numeric"
105
+ autoFocus
106
+ {...noAutofill}
107
+ />
108
+ <Input label="PCN" value={pcn} onChange={(e) => setPcn(e.target.value)} {...noAutofill} />
109
+ <Input label="Group" value={groupId} onChange={(e) => setGroupId(e.target.value)} {...noAutofill} />
110
+ <Input label="Member ID" value={memberId} onChange={(e) => setMemberId(e.target.value)} {...noAutofill} />
111
+ </Grid>
112
+ <Row justify="end" gap="2">
113
+ <Button variant="ghost" onClick={reset}>
114
+ Cancel
115
+ </Button>
116
+ <Button type="submit" variant="secondary" loading={saving} disabled={!canSave}>
117
+ Save insurance
118
+ </Button>
119
+ </Row>
120
+ </Stack>
121
+ </form>
122
+ )}
123
+ </Stack>
124
+ );
125
+ }