@photonhealth/react 0.0.0-stage → 2.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +111 -2
- package/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +2 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/tailwind.d.ts +3 -0
- package/dist/adapters/tailwind.d.ts.map +1 -0
- package/dist/adapters/tailwind.js +126 -0
- package/dist/adapters/tailwind.js.map +1 -0
- package/dist/analytics/PhotonAnalyticsProvider.d.ts +16 -0
- package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
- package/dist/analytics/PhotonAnalyticsProvider.js +57 -0
- package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
- package/dist/analytics/fieldInteraction.d.ts +18 -0
- package/dist/analytics/fieldInteraction.d.ts.map +1 -0
- package/dist/analytics/fieldInteraction.js +102 -0
- package/dist/analytics/fieldInteraction.js.map +1 -0
- package/dist/analytics/tracker.d.ts +17 -0
- package/dist/analytics/tracker.d.ts.map +1 -0
- package/dist/analytics/tracker.js +36 -0
- package/dist/analytics/tracker.js.map +1 -0
- package/dist/analytics/viewed.d.ts +11 -0
- package/dist/analytics/viewed.d.ts.map +1 -0
- package/dist/analytics/viewed.js +16 -0
- package/dist/analytics/viewed.js.map +1 -0
- package/dist/components/ChangeList.d.ts +21 -0
- package/dist/components/ChangeList.d.ts.map +1 -0
- package/dist/components/ChangeList.js +40 -0
- package/dist/components/ChangeList.js.map +1 -0
- package/dist/components/PhotonOrder.d.ts +46 -0
- package/dist/components/PhotonOrder.d.ts.map +1 -0
- package/dist/components/PhotonOrder.js +274 -0
- package/dist/components/PhotonOrder.js.map +1 -0
- package/dist/components/PhotonPatient.d.ts +48 -0
- package/dist/components/PhotonPatient.d.ts.map +1 -0
- package/dist/components/PhotonPatient.js +85 -0
- package/dist/components/PhotonPatient.js.map +1 -0
- package/dist/components/PhotonPrescription.d.ts +32 -0
- package/dist/components/PhotonPrescription.d.ts.map +1 -0
- package/dist/components/PhotonPrescription.js +11 -0
- package/dist/components/PhotonPrescription.js.map +1 -0
- package/dist/components/ScreeningAlerts.d.ts +6 -0
- package/dist/components/ScreeningAlerts.d.ts.map +1 -0
- package/dist/components/ScreeningAlerts.js +11 -0
- package/dist/components/ScreeningAlerts.js.map +1 -0
- package/dist/components/SignedIn.d.ts +12 -0
- package/dist/components/SignedIn.d.ts.map +1 -0
- package/dist/components/SignedIn.js +84 -0
- package/dist/components/SignedIn.js.map +1 -0
- package/dist/components/activity.d.ts +7 -0
- package/dist/components/activity.d.ts.map +1 -0
- package/dist/components/activity.js +24 -0
- package/dist/components/activity.js.map +1 -0
- package/dist/components/display.d.ts +90 -0
- package/dist/components/display.d.ts.map +1 -0
- package/dist/components/display.js +223 -0
- package/dist/components/display.js.map +1 -0
- package/dist/components/flow.d.ts +35 -0
- package/dist/components/flow.d.ts.map +1 -0
- package/dist/components/flow.js +53 -0
- package/dist/components/flow.js.map +1 -0
- package/dist/components/format.d.ts +26 -0
- package/dist/components/format.d.ts.map +1 -0
- package/dist/components/format.js +61 -0
- package/dist/components/format.js.map +1 -0
- package/dist/components/index.d.ts +6 -0
- package/dist/components/index.d.ts.map +1 -0
- package/dist/components/index.js +6 -0
- package/dist/components/index.js.map +1 -0
- package/dist/components/open.d.ts +47 -0
- package/dist/components/open.d.ts.map +1 -0
- package/dist/components/open.js +73 -0
- package/dist/components/open.js.map +1 -0
- package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
- package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
- package/dist/components/order/DraftOrderPrompt.js +26 -0
- package/dist/components/order/DraftOrderPrompt.js.map +1 -0
- package/dist/components/patient/Benefits.d.ts +25 -0
- package/dist/components/patient/Benefits.d.ts.map +1 -0
- package/dist/components/patient/Benefits.js +48 -0
- package/dist/components/patient/Benefits.js.map +1 -0
- package/dist/components/patient/Clinical.d.ts +56 -0
- package/dist/components/patient/Clinical.d.ts.map +1 -0
- package/dist/components/patient/Clinical.js +118 -0
- package/dist/components/patient/Clinical.js.map +1 -0
- package/dist/components/patient/IntakeForm.d.ts +10 -0
- package/dist/components/patient/IntakeForm.d.ts.map +1 -0
- package/dist/components/patient/IntakeForm.js +333 -0
- package/dist/components/patient/IntakeForm.js.map +1 -0
- package/dist/components/patient/Summary.d.ts +48 -0
- package/dist/components/patient/Summary.d.ts.map +1 -0
- package/dist/components/patient/Summary.js +90 -0
- package/dist/components/patient/Summary.js.map +1 -0
- package/dist/components/patient/fields.d.ts +42 -0
- package/dist/components/patient/fields.d.ts.map +1 -0
- package/dist/components/patient/fields.js +72 -0
- package/dist/components/patient/fields.js.map +1 -0
- package/dist/components/patient/query.d.ts +37 -0
- package/dist/components/patient/query.d.ts.map +1 -0
- package/dist/components/patient/query.js +70 -0
- package/dist/components/patient/query.js.map +1 -0
- package/dist/components/prescription/PrescriptionCard.d.ts +45 -0
- package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionCard.js +179 -0
- package/dist/components/prescription/PrescriptionCard.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js +287 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
- package/dist/components/schemaErrors.d.ts +12 -0
- package/dist/components/schemaErrors.d.ts.map +1 -0
- package/dist/components/schemaErrors.js +24 -0
- package/dist/components/schemaErrors.js.map +1 -0
- package/dist/components/search.d.ts +154 -0
- package/dist/components/search.d.ts.map +1 -0
- package/dist/components/search.js +295 -0
- package/dist/components/search.js.map +1 -0
- package/dist/hooks/index.d.ts +5 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/useLatestCallback.d.ts +7 -0
- package/dist/hooks/useLatestCallback.d.ts.map +1 -0
- package/dist/hooks/useLatestCallback.js +14 -0
- package/dist/hooks/useLatestCallback.js.map +1 -0
- package/dist/hooks/useLive.d.ts +15 -0
- package/dist/hooks/useLive.d.ts.map +1 -0
- package/dist/hooks/useLive.js +6 -0
- package/dist/hooks/useLive.js.map +1 -0
- package/dist/hooks/useOnChange.d.ts +11 -0
- package/dist/hooks/useOnChange.d.ts.map +1 -0
- package/dist/hooks/useOnChange.js +28 -0
- package/dist/hooks/useOnChange.js.map +1 -0
- package/dist/hooks/useSession.d.ts +7 -0
- package/dist/hooks/useSession.d.ts.map +1 -0
- package/dist/hooks/useSession.js +10 -0
- package/dist/hooks/useSession.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/meta/version.d.ts +5 -0
- package/dist/meta/version.d.ts.map +1 -0
- package/dist/meta/version.js +5 -0
- package/dist/meta/version.js.map +1 -0
- package/dist/primitives/PhotonProvider.d.ts +60 -0
- package/dist/primitives/PhotonProvider.d.ts.map +1 -0
- package/dist/primitives/PhotonProvider.js +103 -0
- package/dist/primitives/PhotonProvider.js.map +1 -0
- package/dist/primitives/defaults.d.ts +3 -0
- package/dist/primitives/defaults.d.ts.map +1 -0
- package/dist/primitives/defaults.js +70 -0
- package/dist/primitives/defaults.js.map +1 -0
- package/dist/primitives/icons.d.ts +6 -0
- package/dist/primitives/icons.d.ts.map +1 -0
- package/dist/primitives/icons.js +6 -0
- package/dist/primitives/icons.js.map +1 -0
- package/dist/primitives/index.d.ts +5 -0
- package/dist/primitives/index.d.ts.map +1 -0
- package/dist/primitives/index.js +5 -0
- package/dist/primitives/index.js.map +1 -0
- package/dist/primitives/photonContext.d.ts +3 -0
- package/dist/primitives/photonContext.d.ts.map +1 -0
- package/dist/primitives/photonContext.js +3 -0
- package/dist/primitives/photonContext.js.map +1 -0
- package/dist/primitives/select.d.ts +7 -0
- package/dist/primitives/select.d.ts.map +1 -0
- package/dist/primitives/select.js +16 -0
- package/dist/primitives/select.js.map +1 -0
- package/dist/primitives/types.d.ts +288 -0
- package/dist/primitives/types.d.ts.map +1 -0
- package/dist/primitives/types.js +3 -0
- package/dist/primitives/types.js.map +1 -0
- package/dist/primitives/useProvidedPhoton.d.ts +8 -0
- package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
- package/dist/primitives/useProvidedPhoton.js +8 -0
- package/dist/primitives/useProvidedPhoton.js.map +1 -0
- package/dist/styles.css +653 -0
- package/dist/test-utils/contract.d.ts +17 -0
- package/dist/test-utils/contract.d.ts.map +1 -0
- package/dist/test-utils/contract.js +282 -0
- package/dist/test-utils/contract.js.map +1 -0
- package/package.json +76 -4
- package/src/adapters/index.ts +1 -0
- package/src/adapters/tailwind.tsx +572 -0
- package/src/analytics/PhotonAnalyticsProvider.test.tsx +191 -0
- package/src/analytics/PhotonAnalyticsProvider.tsx +96 -0
- package/src/analytics/fieldInteraction.test.tsx +184 -0
- package/src/analytics/fieldInteraction.tsx +148 -0
- package/src/analytics/tracker.test.ts +52 -0
- package/src/analytics/tracker.ts +42 -0
- package/src/analytics/viewed.ts +27 -0
- package/src/components/ChangeList.tsx +85 -0
- package/src/components/PhotonOrder.test.tsx +256 -0
- package/src/components/PhotonOrder.tsx +508 -0
- package/src/components/PhotonPatient.tsx +188 -0
- package/src/components/PhotonPrescription.test.tsx +116 -0
- package/src/components/PhotonPrescription.tsx +45 -0
- package/src/components/ScreeningAlerts.tsx +28 -0
- package/src/components/SignedIn.tsx +144 -0
- package/src/components/activity.ts +23 -0
- package/src/components/display.ts +278 -0
- package/src/components/flow.ts +67 -0
- package/src/components/format.ts +73 -0
- package/src/components/index.ts +5 -0
- package/src/components/open.ts +100 -0
- package/src/components/order/DraftOrderPrompt.test.tsx +80 -0
- package/src/components/order/DraftOrderPrompt.tsx +81 -0
- package/src/components/patient/Benefits.tsx +133 -0
- package/src/components/patient/Clinical.tsx +215 -0
- package/src/components/patient/IntakeForm.test.tsx +89 -0
- package/src/components/patient/IntakeForm.tsx +564 -0
- package/src/components/patient/Summary.test.tsx +106 -0
- package/src/components/patient/Summary.tsx +330 -0
- package/src/components/patient/fields.tsx +158 -0
- package/src/components/patient/query.ts +83 -0
- package/src/components/prescription/PrescriptionCard.test.tsx +85 -0
- package/src/components/prescription/PrescriptionCard.tsx +347 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +85 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +209 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +456 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
- package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +75 -0
- package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
- package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
- package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +699 -0
- package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
- package/src/components/schemaErrors.test.ts +49 -0
- package/src/components/schemaErrors.ts +33 -0
- package/src/components/search.tsx +377 -0
- package/src/hooks/index.ts +4 -0
- package/src/hooks/useLatestCallback.ts +16 -0
- package/src/hooks/useLive.ts +21 -0
- package/src/hooks/useOnChange.ts +34 -0
- package/src/hooks/useSession.ts +11 -0
- package/src/index.ts +21 -0
- package/src/meta/version.test.ts +10 -0
- package/src/meta/version.ts +4 -0
- package/src/primitives/PhotonProvider.tsx +168 -0
- package/src/primitives/defaults.tsx +432 -0
- package/src/primitives/icons.tsx +37 -0
- package/src/primitives/index.ts +4 -0
- package/src/primitives/photonContext.ts +4 -0
- package/src/primitives/select.ts +15 -0
- package/src/primitives/types.ts +288 -0
- package/src/primitives/useProvidedPhoton.ts +21 -0
- package/src/styles.css +653 -0
- package/src/test-utils/contract.tsx +453 -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
|
+
/** "+13175550147" / "3175550147" → "+1 (317) 555-0147"; 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) 555-0147" → "+13175550147" (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 "./prescription/TreatmentSearch/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,80 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import type { PrescriptionRecord } from "@photonhealth/client";
|
|
3
|
+
import { treatment } from "@photonhealth/client/testing";
|
|
4
|
+
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
6
|
+
import { DraftOrderPrompt } from "./DraftOrderPrompt.tsx";
|
|
7
|
+
|
|
8
|
+
const record = (id: string, fields: Partial<PrescriptionRecord> = {}): PrescriptionRecord => ({
|
|
9
|
+
id,
|
|
10
|
+
prescriber: null,
|
|
11
|
+
fulfillment: null,
|
|
12
|
+
templateId: null,
|
|
13
|
+
patient: { id: "pat_1" },
|
|
14
|
+
treatment: { ...treatment(), templates: null },
|
|
15
|
+
instructions: "Take 1 capsule by mouth three times daily",
|
|
16
|
+
dispense: { quantity: 30, unit: "Capsule", daysSupply: 10, refillsAllowed: 0, dispenseAsWritten: false },
|
|
17
|
+
clinical: null,
|
|
18
|
+
screeningAlerts: [],
|
|
19
|
+
signing: { state: "UNSIGNED", contentHash: "hash_1", message: null, signedAt: null },
|
|
20
|
+
...fields,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const amoxicillin = record("rx_1", {
|
|
24
|
+
treatment: {
|
|
25
|
+
...treatment({ name: "Amoxicillin", prescribableName: "Amoxicillin 500 MG Oral Capsule" }),
|
|
26
|
+
templates: null,
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
const lisinopril = record("rx_2", {
|
|
30
|
+
treatment: { ...treatment({ id: "trt_2", name: "Lisinopril 10 MG Oral Tablet" }), templates: null },
|
|
31
|
+
instructions: "Take 1 tablet by mouth once daily",
|
|
32
|
+
signing: { state: "SIGNED", contentHash: "hash_2", message: null, signedAt: "2026-11-01T00:00:00Z" },
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("DraftOrderPrompt", () => {
|
|
36
|
+
afterEach(() => cleanup());
|
|
37
|
+
|
|
38
|
+
it("shows each prescription on the draft, read-only, and asks whether to continue it", () => {
|
|
39
|
+
render(
|
|
40
|
+
<DraftOrderPrompt
|
|
41
|
+
draft={{ prescriptions: [amoxicillin, lisinopril] }}
|
|
42
|
+
onContinue={vi.fn()}
|
|
43
|
+
onStartNew={vi.fn()}
|
|
44
|
+
/>,
|
|
45
|
+
);
|
|
46
|
+
expect(screen.getByRole("heading", { name: "Amoxicillin" })).toBeTruthy();
|
|
47
|
+
expect(screen.getByRole("region", { name: "Amoxicillin" })).toBeTruthy(); // each card is named by its drug
|
|
48
|
+
expect(screen.getByRole("heading", { name: "Lisinopril" })).toBeTruthy();
|
|
49
|
+
expect(screen.getByText("Take 1 capsule by mouth three times daily")).toBeTruthy();
|
|
50
|
+
expect(screen.getByText("Signed")).toBeTruthy();
|
|
51
|
+
// Nothing to edit, sign or remove until the prescriber decides.
|
|
52
|
+
expect(screen.queryAllByRole("textbox")).toHaveLength(0);
|
|
53
|
+
expect(screen.queryByRole("button", { name: "Add" })).toBeNull();
|
|
54
|
+
expect(screen.queryByRole("button", { name: "Remove prescription" })).toBeNull();
|
|
55
|
+
expect(screen.getByText("Would you like to continue this order?")).toBeTruthy();
|
|
56
|
+
expect(screen.getAllByRole("button").map((b) => b.textContent)).toEqual(["Continue", "Start a new order"]);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("Continue and Start a new order each call their own handler", () => {
|
|
60
|
+
const onContinue = vi.fn();
|
|
61
|
+
const onStartNew = vi.fn();
|
|
62
|
+
render(
|
|
63
|
+
<DraftOrderPrompt draft={{ prescriptions: [amoxicillin] }} onContinue={onContinue} onStartNew={onStartNew} />,
|
|
64
|
+
);
|
|
65
|
+
fireEvent.click(screen.getByRole("button", { name: "Continue" }));
|
|
66
|
+
expect(onContinue).toHaveBeenCalledOnce();
|
|
67
|
+
expect(onStartNew).not.toHaveBeenCalled();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("while a choice is in flight, neither button can be pressed again", async () => {
|
|
71
|
+
let settle!: () => void;
|
|
72
|
+
const onStartNew = vi.fn(() => new Promise<void>((resolve) => (settle = resolve)));
|
|
73
|
+
render(<DraftOrderPrompt draft={{ prescriptions: [amoxicillin] }} onContinue={vi.fn()} onStartNew={onStartNew} />);
|
|
74
|
+
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Start a new order" })));
|
|
75
|
+
expect(screen.getByRole<HTMLButtonElement>("button", { name: /Start a new order/ }).disabled).toBe(true);
|
|
76
|
+
expect(screen.getByRole<HTMLButtonElement>("button", { name: "Continue" }).disabled).toBe(true);
|
|
77
|
+
await act(async () => settle());
|
|
78
|
+
expect(screen.getByRole<HTMLButtonElement>("button", { name: "Continue" }).disabled).toBe(false);
|
|
79
|
+
});
|
|
80
|
+
});
|