@photonhealth/react 2.0.0-rc.1 → 2.0.0-rc.3
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/README.md +52 -9
- package/dist/adapters/tailwind.d.ts.map +1 -1
- package/dist/adapters/tailwind.js +7 -4
- package/dist/adapters/tailwind.js.map +1 -1
- package/dist/analytics/PhotonAnalyticsProvider.d.ts +19 -0
- package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
- package/dist/analytics/PhotonAnalyticsProvider.js +76 -0
- package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
- package/dist/analytics/cardLifecycle.d.ts +10 -0
- package/dist/analytics/cardLifecycle.d.ts.map +1 -0
- package/dist/analytics/cardLifecycle.js +43 -0
- package/dist/analytics/cardLifecycle.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/lifecycleOutcomes.d.ts +8 -0
- package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
- package/dist/analytics/lifecycleOutcomes.js +16 -0
- package/dist/analytics/lifecycleOutcomes.js.map +1 -0
- package/dist/analytics/tracker.d.ts +19 -0
- package/dist/analytics/tracker.d.ts.map +1 -0
- package/dist/analytics/tracker.js +41 -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/PhotonOrder.d.ts +18 -18
- package/dist/components/PhotonOrder.d.ts.map +1 -1
- package/dist/components/PhotonOrder.js +34 -19
- package/dist/components/PhotonOrder.js.map +1 -1
- package/dist/components/PhotonPatient.d.ts +7 -35
- package/dist/components/PhotonPatient.d.ts.map +1 -1
- package/dist/components/PhotonPatient.js +6 -78
- package/dist/components/PhotonPatient.js.map +1 -1
- package/dist/components/PhotonPrescription.d.ts +15 -26
- package/dist/components/PhotonPrescription.d.ts.map +1 -1
- package/dist/components/PhotonPrescription.js +6 -360
- package/dist/components/PhotonPrescription.js.map +1 -1
- package/dist/components/format.d.ts +2 -2
- package/dist/components/format.js +2 -2
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/open.d.ts +11 -13
- package/dist/components/open.d.ts.map +1 -1
- package/dist/components/open.js +7 -2
- package/dist/components/open.js.map +1 -1
- 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/PatientCard/PatientCard.d.ts +30 -0
- package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
- package/dist/components/patient/PatientCard/PatientCard.js +101 -0
- package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
- package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
- package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
- package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
- package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
- package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
- package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
- package/dist/components/patient/PatientIntakeForm.js +114 -0
- package/dist/components/patient/PatientIntakeForm.js.map +1 -0
- package/dist/components/patient/PatientSearch.d.ts +12 -0
- package/dist/components/patient/PatientSearch.d.ts.map +1 -0
- package/dist/components/patient/PatientSearch.js +148 -0
- package/dist/components/patient/PatientSearch.js.map +1 -0
- package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
- package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
- package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +6 -5
- package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
- package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +15 -16
- package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
- package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +29 -28
- package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
- package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
- package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
- package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
- package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
- package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
- package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
- package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
- package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
- package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
- package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
- package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
- package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
- package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
- package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
- package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
- package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
- package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
- package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
- package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
- package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
- package/dist/components/patient/fields.d.ts +7 -26
- package/dist/components/patient/fields.d.ts.map +1 -1
- package/dist/components/patient/fields.js +11 -52
- package/dist/components/patient/fields.js.map +1 -1
- package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
- package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
- package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -10
- package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
- package/dist/components/prescription/PrescriptionCard.d.ts +51 -0
- package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionCard.js +186 -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/{TreatmentPicker.js → prescription/TreatmentSearch/TreatmentPicker.js} +113 -105
- 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 +13 -0
- package/dist/components/schemaErrors.d.ts.map +1 -0
- package/dist/components/schemaErrors.js +25 -0
- package/dist/components/schemaErrors.js.map +1 -0
- package/dist/components/search.d.ts +1 -1
- package/dist/components/search.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- 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 +3 -1
- package/dist/primitives/PhotonProvider.d.ts.map +1 -1
- package/dist/primitives/PhotonProvider.js +23 -11
- package/dist/primitives/PhotonProvider.js.map +1 -1
- package/dist/primitives/defaults.d.ts.map +1 -1
- package/dist/primitives/defaults.js +6 -3
- package/dist/primitives/defaults.js.map +1 -1
- 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/types.d.ts +15 -3
- package/dist/primitives/types.d.ts.map +1 -1
- package/dist/primitives/types.js.map +1 -1
- 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 +45 -3
- package/dist/test-utils/contract.d.ts.map +1 -1
- package/dist/test-utils/contract.js +23 -2
- package/dist/test-utils/contract.js.map +1 -1
- package/package.json +8 -3
- package/src/adapters/tailwind.tsx +52 -24
- package/src/analytics/PhotonAnalyticsProvider.test.tsx +190 -0
- package/src/analytics/PhotonAnalyticsProvider.tsx +151 -0
- package/src/analytics/cardLifecycle.test.tsx +272 -0
- package/src/analytics/cardLifecycle.ts +44 -0
- package/src/analytics/fieldInteraction.test.tsx +186 -0
- package/src/analytics/fieldInteraction.tsx +148 -0
- package/src/analytics/lifecycleOutcomes.test.ts +78 -0
- package/src/analytics/lifecycleOutcomes.ts +29 -0
- package/src/analytics/tracker.test.ts +52 -0
- package/src/analytics/tracker.ts +49 -0
- package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
- package/src/analytics/viewed.ts +27 -0
- package/src/components/PhotonOrder.test.tsx +394 -0
- package/src/components/PhotonOrder.tsx +79 -53
- package/src/components/PhotonPatient.tsx +15 -166
- package/src/components/PhotonPrescription.test.tsx +120 -0
- package/src/components/PhotonPrescription.tsx +23 -583
- package/src/components/ScreeningAlerts.test.tsx +81 -0
- package/src/components/format.ts +2 -2
- package/src/components/index.ts +1 -1
- package/src/components/open.ts +13 -16
- package/src/components/order/DraftOrderPrompt.test.tsx +77 -0
- package/src/components/order/DraftOrderPrompt.tsx +81 -0
- package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
- package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
- package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
- package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
- package/src/components/patient/PatientIntakeForm.tsx +222 -0
- package/src/components/patient/PatientSearch.test.tsx +204 -0
- package/src/components/patient/PatientSearch.tsx +221 -0
- package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
- package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +24 -16
- package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
- package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +53 -48
- package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
- package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
- package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
- package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
- package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
- package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
- package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
- package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
- package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
- package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
- package/src/components/patient/fields.tsx +12 -124
- package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
- package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -15
- package/src/components/prescription/PrescriptionCard.test.tsx +247 -0
- package/src/components/prescription/PrescriptionCard.tsx +361 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +82 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +206 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +453 -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 +72 -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 +695 -0
- package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
- package/src/components/schemaErrors.test.ts +49 -0
- package/src/components/schemaErrors.ts +34 -0
- package/src/components/search.tsx +1 -1
- package/src/index.ts +2 -0
- package/src/meta/version.test.ts +11 -0
- package/src/meta/version.ts +4 -0
- package/src/primitives/PhotonProvider.tsx +30 -15
- package/src/primitives/defaults.tsx +44 -21
- package/src/primitives/photonContext.ts +4 -0
- package/src/primitives/types.ts +15 -3
- package/src/primitives/useProvidedPhoton.ts +21 -0
- package/src/styles.css +45 -3
- package/src/test-utils/contract.tsx +45 -2
- package/dist/components/TreatmentPicker.d.ts +0 -45
- package/dist/components/TreatmentPicker.d.ts.map +0 -1
- package/dist/components/TreatmentPicker.js.map +0 -1
- package/dist/components/patient/Benefits.d.ts.map +0 -1
- package/dist/components/patient/Benefits.js.map +0 -1
- package/dist/components/patient/Clinical.d.ts.map +0 -1
- package/dist/components/patient/Clinical.js.map +0 -1
- package/dist/components/patient/IntakeForm.d.ts +0 -10
- package/dist/components/patient/IntakeForm.d.ts.map +0 -1
- package/dist/components/patient/IntakeForm.js +0 -324
- package/dist/components/patient/IntakeForm.js.map +0 -1
- package/dist/components/patient/Summary.d.ts +0 -48
- package/dist/components/patient/Summary.d.ts.map +0 -1
- package/dist/components/patient/Summary.js +0 -80
- package/dist/components/patient/Summary.js.map +0 -1
- package/dist/components/patient/query.d.ts +0 -23
- package/dist/components/patient/query.d.ts.map +0 -1
- package/dist/components/patient/query.js.map +0 -1
- package/src/components/TreatmentPicker.tsx +0 -350
- package/src/components/patient/IntakeForm.tsx +0 -532
- package/src/components/patient/Summary.tsx +0 -310
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/** PhotonPatient before a record, adding them: the fields network-api needs, and what the server says about them. */
|
|
2
|
+
import { useComponents } from "../../primitives/index.ts";
|
|
3
|
+
import { classify, type Patient, type Sex } from "@photonhealth/client";
|
|
4
|
+
import { useLive } from "../../hooks/index.ts";
|
|
5
|
+
import { useEffect, useId, useRef, useState, type SubmitEvent } from "react";
|
|
6
|
+
import { ChangeList } from "../ChangeList.tsx";
|
|
7
|
+
import { formatPhone, PHONE_PATTERN, toE164 } from "../format.ts";
|
|
8
|
+
|
|
9
|
+
import { IDENTITY_KEYS, noAutofill, SEX_OPTIONS } from "./fields.tsx";
|
|
10
|
+
import { focusProps } from "../flow.ts";
|
|
11
|
+
import { parsePatientSearchQuery } from "./parsePatientSearchQuery.ts";
|
|
12
|
+
import { TrackedField, useFieldInteractions } from "../../analytics/fieldInteraction.tsx";
|
|
13
|
+
import { useSavePatientAndSendEvent } from "../../analytics/cardLifecycle.ts";
|
|
14
|
+
|
|
15
|
+
type Field = "first" | "last" | "dob" | "sex";
|
|
16
|
+
|
|
17
|
+
export function PatientIntakeForm({
|
|
18
|
+
patient,
|
|
19
|
+
query,
|
|
20
|
+
notice,
|
|
21
|
+
}: {
|
|
22
|
+
patient: Patient;
|
|
23
|
+
/**
|
|
24
|
+
* What was typed in PatientSearch before "Add new patient": split into the fields, so nothing is retyped and the
|
|
25
|
+
* prescriber can see, and correct, how it was read. Without one, the fields start from what the patient already
|
|
26
|
+
* has (e.g. a host's details the server hasn't matched yet).
|
|
27
|
+
*/
|
|
28
|
+
query?: string | null;
|
|
29
|
+
/** Why someone else is being added (e.g. the patient given by id isn't there). */
|
|
30
|
+
notice?: { title: string; description: string } | null;
|
|
31
|
+
}) {
|
|
32
|
+
const { Alert, Badge, Button, Card, CardBody, CardFooter, CardHeader, Grid, Input, Select, Spinner, Stack } =
|
|
33
|
+
useComponents();
|
|
34
|
+
const snap = useLive(patient)!;
|
|
35
|
+
const formId = useId();
|
|
36
|
+
const savePatientAndSendEvent = useSavePatientAndSendEvent();
|
|
37
|
+
const known = patient.known;
|
|
38
|
+
const typed = query != null ? parsePatientSearchQuery(query) : null;
|
|
39
|
+
const [first, setFirst] = useState((typed ? typed.name?.first : known.demographic?.name?.first) ?? "");
|
|
40
|
+
const [last, setLast] = useState((typed ? typed.name?.last : known.demographic?.name?.last) ?? "");
|
|
41
|
+
const [dob, setDob] = useState((typed ? typed.dateOfBirth : known.demographic?.dateOfBirth) ?? "");
|
|
42
|
+
const [sex, setSex] = useState<Sex | null>(known.demographic?.sex ?? null);
|
|
43
|
+
const sexPicked = useFieldInteractions("new_patient_form")("sex", { isOptional: false, hasValue: Boolean(sex) });
|
|
44
|
+
const [email, setEmail] = useState(typed?.email ?? known.contact?.email ?? "");
|
|
45
|
+
const knownPhone = typed?.phone ?? known.contact?.phone;
|
|
46
|
+
const [phone, setPhone] = useState(knownPhone ? formatPhone(knownPhone) : "");
|
|
47
|
+
/** Which of the four network-api needs were empty when Save was last pressed. */
|
|
48
|
+
const [missing, setMissing] = useState<Field[]>([]);
|
|
49
|
+
/** What a required field says while Save is waiting on it. The server names all four at once; we don't. */
|
|
50
|
+
const gap = (field: Field) =>
|
|
51
|
+
missing.includes(field) ? { invalid: true, errorMessage: "Needed to add a patient" } : {};
|
|
52
|
+
|
|
53
|
+
const busy = snap.status === "loading" || snap.status === "saving";
|
|
54
|
+
// What the server still needs to add the patient (name, DOB, sex) is what this form asks for next — not an
|
|
55
|
+
// error. Once the prescriber has filled all four, anything it still rejects about them is shown.
|
|
56
|
+
const identityFilled = Boolean(first.trim() && last.trim() && dob && sex);
|
|
57
|
+
const changes = classify({
|
|
58
|
+
...snap.changes,
|
|
59
|
+
unapplied: snap.changes.unapplied.filter((c) => identityFilled || !IDENTITY_KEYS.includes(c.key)),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/** Everything known on the form. Phone / email ride along once they're valid; the browser shows why otherwise. */
|
|
63
|
+
const form = () => {
|
|
64
|
+
const validPhone = new RegExp(`^(?:${PHONE_PATTERN})$`).test(phone.trim());
|
|
65
|
+
const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
|
|
66
|
+
const demographic = {
|
|
67
|
+
name: { first, last },
|
|
68
|
+
dateOfBirth: dob,
|
|
69
|
+
...(sex ? { sex } : {}),
|
|
70
|
+
};
|
|
71
|
+
const contact = {
|
|
72
|
+
...(validPhone ? { phone: toE164(phone) } : {}),
|
|
73
|
+
...(validEmail ? { email: email.trim() } : {}),
|
|
74
|
+
};
|
|
75
|
+
return { demographic, contact };
|
|
76
|
+
};
|
|
77
|
+
/** Send everything known: the server may find or add the patient. The object adds it to what it sent before. */
|
|
78
|
+
const send = () => void savePatientAndSendEvent(patient, () => patient.sync(form())).catch(() => {}); // failures land on the object
|
|
79
|
+
|
|
80
|
+
/** A field changed: keep it. Answering what Save asked for puts it right at once. */
|
|
81
|
+
const type = (field: Field | null, set: (value: string) => void) => (e: { target: { value: string } }) => {
|
|
82
|
+
set(e.target.value);
|
|
83
|
+
if (field && e.target.value.trim()) setMissing((m) => m.filter((f) => f !== field));
|
|
84
|
+
};
|
|
85
|
+
const submit = (e: SubmitEvent) => {
|
|
86
|
+
e.preventDefault();
|
|
87
|
+
save();
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Add them. network-api creates a patient only with a first name, a last name, a date of birth and a sex
|
|
92
|
+
* (`Sex` has UNKNOWN, so there is always an answer), and the schema says nothing about which of them a
|
|
93
|
+
* payload is short of — so the form checks before it sends, rather than Save failing with a rejection
|
|
94
|
+
* naming every field at once.
|
|
95
|
+
*
|
|
96
|
+
* The server still decides what this means: it may find the patient instead of adding them, or come back
|
|
97
|
+
* with people it might be. Only this press asks it.
|
|
98
|
+
*/
|
|
99
|
+
const REQUIRED: [Field, boolean][] = [
|
|
100
|
+
["first", Boolean(first.trim())],
|
|
101
|
+
["last", Boolean(last.trim())],
|
|
102
|
+
["dob", Boolean(dob)],
|
|
103
|
+
["sex", Boolean(sex)],
|
|
104
|
+
];
|
|
105
|
+
const save = () => {
|
|
106
|
+
const empty = REQUIRED.filter(([, filled]) => !filled).map(([field]) => field);
|
|
107
|
+
setMissing(empty);
|
|
108
|
+
if (empty.length) return; // the fields say which; the cursor goes to the first of them (below)
|
|
109
|
+
send();
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// Sex is the one thing a search never fills in, and the one network-api needs to create, so that's where focus
|
|
113
|
+
// goes: the form is filled in and the deliberate act is choosing it.
|
|
114
|
+
const sexField = useRef<HTMLDivElement | null>(null);
|
|
115
|
+
const fields = useRef<HTMLFormElement | null>(null);
|
|
116
|
+
// Save pressed with gaps: the cursor goes to the first field it is waiting on, so answering starts there.
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
if (!missing.length) return;
|
|
119
|
+
fields.current?.querySelector<HTMLElement>('[aria-invalid="true"], [data-invalid]')?.focus();
|
|
120
|
+
}, [missing]);
|
|
121
|
+
// Once the form is up, the cursor goes to Sex (the Select is a building block, so by where it lands).
|
|
122
|
+
const landed = useRef(false);
|
|
123
|
+
useEffect(() => {
|
|
124
|
+
if (landed.current || !sexField.current) return;
|
|
125
|
+
landed.current = true;
|
|
126
|
+
sexField.current.querySelector<HTMLElement>("input, select, button")?.focus();
|
|
127
|
+
}, []);
|
|
128
|
+
|
|
129
|
+
return (
|
|
130
|
+
<Card divided>
|
|
131
|
+
<CardHeader title="Patient" />
|
|
132
|
+
<CardBody>
|
|
133
|
+
<form {...noAutofill} ref={fields} id={formId} onSubmit={submit}>
|
|
134
|
+
<Stack gap="3">
|
|
135
|
+
<Grid min="200px" gap="3">
|
|
136
|
+
<div {...focusProps}>
|
|
137
|
+
<TrackedField formName="new_patient_form" fieldName="firstName" isOptional={false}>
|
|
138
|
+
<Input
|
|
139
|
+
{...gap("first")}
|
|
140
|
+
label="First name"
|
|
141
|
+
value={first}
|
|
142
|
+
onChange={type("first", setFirst)}
|
|
143
|
+
autoFocus
|
|
144
|
+
{...noAutofill}
|
|
145
|
+
/>
|
|
146
|
+
</TrackedField>
|
|
147
|
+
</div>
|
|
148
|
+
<TrackedField formName="new_patient_form" fieldName="lastName" isOptional={false}>
|
|
149
|
+
<Input
|
|
150
|
+
{...gap("last")}
|
|
151
|
+
label="Last name"
|
|
152
|
+
value={last}
|
|
153
|
+
onChange={type("last", setLast)}
|
|
154
|
+
{...noAutofill}
|
|
155
|
+
/>
|
|
156
|
+
</TrackedField>
|
|
157
|
+
<TrackedField formName="new_patient_form" fieldName="dateOfBirth" isOptional={false}>
|
|
158
|
+
<Input
|
|
159
|
+
{...gap("dob")}
|
|
160
|
+
label="Date of birth"
|
|
161
|
+
type="date"
|
|
162
|
+
{...noAutofill}
|
|
163
|
+
value={dob}
|
|
164
|
+
onChange={type("dob", setDob)}
|
|
165
|
+
/>
|
|
166
|
+
</TrackedField>
|
|
167
|
+
<div ref={sexField} onFocus={sexPicked.onFocus} onBlur={sexPicked.onBlur}>
|
|
168
|
+
<Select
|
|
169
|
+
{...gap("sex")}
|
|
170
|
+
label="Sex"
|
|
171
|
+
placeholder="Select…"
|
|
172
|
+
options={SEX_OPTIONS}
|
|
173
|
+
value={sex}
|
|
174
|
+
onChange={(next) => {
|
|
175
|
+
sexPicked.onChange(true);
|
|
176
|
+
setSex(next);
|
|
177
|
+
setMissing((m) => m.filter((f) => f !== "sex"));
|
|
178
|
+
}}
|
|
179
|
+
/>
|
|
180
|
+
</div>
|
|
181
|
+
<TrackedField formName="new_patient_form" fieldName="phone" isOptional>
|
|
182
|
+
<Input
|
|
183
|
+
label="Phone"
|
|
184
|
+
helper="The patient is texted their order link here, so a mobile number."
|
|
185
|
+
type="tel"
|
|
186
|
+
inputMode="tel"
|
|
187
|
+
pattern={PHONE_PATTERN}
|
|
188
|
+
value={phone}
|
|
189
|
+
onChange={type(null, setPhone)}
|
|
190
|
+
onBlur={() => setPhone(formatPhone(phone))}
|
|
191
|
+
{...noAutofill}
|
|
192
|
+
/>
|
|
193
|
+
</TrackedField>
|
|
194
|
+
<TrackedField formName="new_patient_form" fieldName="email" isOptional>
|
|
195
|
+
<Input
|
|
196
|
+
label="Email"
|
|
197
|
+
type="email"
|
|
198
|
+
inputMode="email"
|
|
199
|
+
value={email}
|
|
200
|
+
onChange={type(null, setEmail)}
|
|
201
|
+
{...noAutofill}
|
|
202
|
+
/>
|
|
203
|
+
</TrackedField>
|
|
204
|
+
</Grid>
|
|
205
|
+
|
|
206
|
+
{/* Why someone else is being added, what the server said, and what failed. */}
|
|
207
|
+
{notice && <Alert tone="critical" title={notice.title} description={notice.description} />}
|
|
208
|
+
<ChangeList changes={changes} />
|
|
209
|
+
{snap.error && <Badge tone="critical">{snap.error.message}</Badge>}
|
|
210
|
+
</Stack>
|
|
211
|
+
</form>
|
|
212
|
+
</CardBody>
|
|
213
|
+
{/* Adding a patient is a deliberate act, so it takes a press. Until this, nothing has been sent and nobody
|
|
214
|
+
has been created — the prescriber can still fix every field above, or walk away. */}
|
|
215
|
+
<CardFooter start={busy ? <Spinner label="Adding…" /> : undefined}>
|
|
216
|
+
<Button type="submit" form={formId} loading={busy}>
|
|
217
|
+
Save patient
|
|
218
|
+
</Button>
|
|
219
|
+
</CardFooter>
|
|
220
|
+
</Card>
|
|
221
|
+
);
|
|
222
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { render, screen, waitFor } from "@testing-library/react";
|
|
2
|
+
import userEvent from "@testing-library/user-event";
|
|
3
|
+
import { describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { ambiguous, change, fakeNetworkApiClient, noMatch, payload, photonOver } from "@photonhealth/client/testing";
|
|
5
|
+
import { PatientSearch } from "./PatientSearch.tsx";
|
|
6
|
+
import { patient, withPhoton } from "../../../test/cards.fixtures.tsx";
|
|
7
|
+
|
|
8
|
+
// PatientSearch's own logic: what triggers a search, what the results show, and what choosing does. How the list
|
|
9
|
+
// renders and moves under the keys is SearchResults'; how the server's messages render is ChangeList's.
|
|
10
|
+
|
|
11
|
+
type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
|
|
12
|
+
type Candidate = Parameters<typeof ambiguous>[0][number];
|
|
13
|
+
|
|
14
|
+
/** A patient a search can return: Ada Lovelace (pat_1), with any fields overridden. */
|
|
15
|
+
const fakeCandidate = (overrides: Partial<Candidate> = {}): Candidate => ({
|
|
16
|
+
id: "pat_1",
|
|
17
|
+
firstName: "Ada",
|
|
18
|
+
lastName: "Lovelace",
|
|
19
|
+
dateOfBirth: "1990-01-01",
|
|
20
|
+
...overrides,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A network-api whose patient search returns `matchesByName`: the candidates for the first or last name searched for
|
|
25
|
+
* (nobody, when a name isn't there). Picking a candidate reads Ada.
|
|
26
|
+
*/
|
|
27
|
+
const fakeServer = (matchesByName: Record<string, Candidate[]> = {}, script: NetworkScript = {}) =>
|
|
28
|
+
fakeNetworkApiClient({
|
|
29
|
+
SyncPatient: (vars: { demographic?: { name?: { first?: string; last?: string } } }) => {
|
|
30
|
+
const name = vars.demographic?.name;
|
|
31
|
+
const found = matchesByName[name?.first ?? name?.last ?? ""];
|
|
32
|
+
return found ? ambiguous(found) : noMatch();
|
|
33
|
+
},
|
|
34
|
+
GetPatient: () => payload("patient", "PatientPayload", patient),
|
|
35
|
+
...script,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const renderPatientSearch = ({
|
|
39
|
+
matchesByName,
|
|
40
|
+
script,
|
|
41
|
+
notice,
|
|
42
|
+
}: {
|
|
43
|
+
matchesByName?: Record<string, Candidate[]>;
|
|
44
|
+
script?: NetworkScript;
|
|
45
|
+
notice?: { title: string; description: string };
|
|
46
|
+
} = {}) => {
|
|
47
|
+
const { client } = fakeServer(matchesByName, script);
|
|
48
|
+
const live = photonOver(client).patient();
|
|
49
|
+
const onAddNew = vi.fn();
|
|
50
|
+
const user = userEvent.setup();
|
|
51
|
+
render(<PatientSearch patient={live} notice={notice} onAddNew={onAddNew} />, { wrapper: withPhoton(client) });
|
|
52
|
+
return { live, onAddNew, user, field: screen.getByLabelText("Find patient") };
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** The search results: named "Matching patients" or "No matching patients". */
|
|
56
|
+
const SEARCH_RESULTS = /^(Matching|No matching) patients$/;
|
|
57
|
+
const findSearchResults = (name: string | RegExp = SEARCH_RESULTS) => screen.findByRole("listbox", { name });
|
|
58
|
+
const querySearchResults = () => screen.queryByRole("listbox", { name: SEARCH_RESULTS });
|
|
59
|
+
|
|
60
|
+
/** Longer than the type-ahead's pause: time for a search request to be sent and its response to come back. */
|
|
61
|
+
const pause = () => new Promise((done) => setTimeout(done, 500));
|
|
62
|
+
|
|
63
|
+
describe("PatientSearch", () => {
|
|
64
|
+
describe("searching", () => {
|
|
65
|
+
it("before anything is typed: no results", () => {
|
|
66
|
+
renderPatientSearch();
|
|
67
|
+
expect(querySearchResults()).not.toBeInTheDocument();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("two or more characters typed: searches once typing pauses, and shows the results", async () => {
|
|
71
|
+
const { user, field } = renderPatientSearch({ matchesByName: { Ada: [fakeCandidate()] } });
|
|
72
|
+
await user.type(field, "Ada");
|
|
73
|
+
expect(await findSearchResults("Matching patients")).toBeInTheDocument();
|
|
74
|
+
expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("one character typed: doesn't search while typing", async () => {
|
|
78
|
+
const { user, field } = renderPatientSearch({ matchesByName: { A: [fakeCandidate()] } });
|
|
79
|
+
await user.type(field, "A");
|
|
80
|
+
await pause();
|
|
81
|
+
expect(querySearchResults()).not.toBeInTheDocument();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("one character, then Return: searches it now", async () => {
|
|
85
|
+
const { user, field } = renderPatientSearch({ matchesByName: { A: [fakeCandidate()] } });
|
|
86
|
+
await user.type(field, "A{Enter}");
|
|
87
|
+
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("one character, then leaving the field: searches it now", async () => {
|
|
91
|
+
const { user, field } = renderPatientSearch({ matchesByName: { A: [fakeCandidate()] } });
|
|
92
|
+
await user.type(field, "A");
|
|
93
|
+
await user.tab();
|
|
94
|
+
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("two characters, then Backspace both: shows the results, then removes them", async () => {
|
|
98
|
+
const { user, field } = renderPatientSearch({ matchesByName: { Ada: [fakeCandidate()] } });
|
|
99
|
+
await user.type(field, "Ada");
|
|
100
|
+
await findSearchResults();
|
|
101
|
+
await user.type(field, "{Backspace}{Backspace}");
|
|
102
|
+
expect(querySearchResults()).not.toBeInTheDocument();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("one word that matches no first name: searched again as a last name", async () => {
|
|
106
|
+
// network-api matches first and last names separately: Lovelace is only ever a last name here.
|
|
107
|
+
const { user, field } = renderPatientSearch({
|
|
108
|
+
script: {
|
|
109
|
+
SyncPatient: (vars: { demographic?: { name?: { last?: string } } }) =>
|
|
110
|
+
vars.demographic?.name?.last === "Lovelace" ? ambiguous([fakeCandidate()]) : noMatch(),
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
await user.type(field, "Lovelace");
|
|
114
|
+
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe("displaying results", () => {
|
|
119
|
+
it("no results: displays no results, warns that that spelling has to be exact, and offers Add new patient", async () => {
|
|
120
|
+
const { user, field } = renderPatientSearch();
|
|
121
|
+
await user.type(field, "Zqx");
|
|
122
|
+
expect(await findSearchResults("No matching patients")).toBeInTheDocument();
|
|
123
|
+
expect(screen.getByText("Spelling has to be exact.")).toBeInTheDocument();
|
|
124
|
+
expect(screen.getByText("Add new patient")).toBeInTheDocument();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("fewer than 5 results: the first is highlighted, the cursor stays in the field, and offers Add new patient", async () => {
|
|
128
|
+
const { user, field } = renderPatientSearch({
|
|
129
|
+
matchesByName: { Ada: [fakeCandidate(), fakeCandidate({ id: "pat_2", lastName: "Lovelace2" })] },
|
|
130
|
+
});
|
|
131
|
+
await user.type(field, "Ada");
|
|
132
|
+
await waitFor(() => expect(field).toHaveAttribute("aria-activedescendant"));
|
|
133
|
+
expect(field).toHaveFocus();
|
|
134
|
+
expect(screen.getByText("Add new patient")).toBeInTheDocument();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("5 or more results: nothing is highlighted, and offers Add new patient", async () => {
|
|
138
|
+
const { user, field } = renderPatientSearch({
|
|
139
|
+
matchesByName: { Ada: [1, 2, 3, 4, 5].map((n) => fakeCandidate({ id: `pat_${n}`, lastName: `Lovelace${n}` })) },
|
|
140
|
+
});
|
|
141
|
+
await user.type(field, "Ada");
|
|
142
|
+
await findSearchResults();
|
|
143
|
+
await pause();
|
|
144
|
+
expect(field).not.toHaveAttribute("aria-activedescendant");
|
|
145
|
+
expect(screen.getByText("Add new patient")).toBeInTheDocument();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("a search that fails: says why", async () => {
|
|
149
|
+
const { user, field } = renderPatientSearch({
|
|
150
|
+
script: {
|
|
151
|
+
SyncPatient: () => {
|
|
152
|
+
throw new Error("network-api is down");
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
await user.type(field, "Ada");
|
|
157
|
+
expect(await screen.findByText("network-api is down")).toBeInTheDocument();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// TODO: Leaving this test in to document the weird behavior around displaying PatientSearch or PatientIntakeForm
|
|
161
|
+
// depending on initial input to PatientCard
|
|
162
|
+
// We should replace it with a test that confirms we don't show any weird server messages
|
|
163
|
+
it("the server's messages: shown, except that name, date of birth or sex are still needed", async () => {
|
|
164
|
+
const needs = (key: string, reason: string) =>
|
|
165
|
+
change({ key, label: key, status: "REJECTED", severity: "BLOCKING", reason });
|
|
166
|
+
const { client } = fakeServer(
|
|
167
|
+
{},
|
|
168
|
+
{
|
|
169
|
+
SyncPatient: () =>
|
|
170
|
+
payload("patient", "PatientPayload", null, {
|
|
171
|
+
changes: [
|
|
172
|
+
needs("demographic.dateOfBirth", "Date of birth is needed"),
|
|
173
|
+
needs("contact.phone", "Phone isn't valid"),
|
|
174
|
+
],
|
|
175
|
+
}),
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
// A patient the server has already said this about (e.g. details a host passed).
|
|
179
|
+
const live = photonOver(client).patient();
|
|
180
|
+
await live.sync({ contact: { phone: "1" } }).catch(() => {});
|
|
181
|
+
render(<PatientSearch patient={live} onAddNew={vi.fn()} />, { wrapper: withPhoton(client) });
|
|
182
|
+
expect(await screen.findByText(/Phone isn't valid/)).toBeInTheDocument();
|
|
183
|
+
expect(screen.queryByText(/Date of birth is needed/)).not.toBeInTheDocument();
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe("choosing", () => {
|
|
188
|
+
// TODO: pins behavior, want to replace this with something else
|
|
189
|
+
// once we remove the client from the react components
|
|
190
|
+
it("a result: the patient becomes that one", async () => {
|
|
191
|
+
const { user, field, live } = renderPatientSearch({ matchesByName: { Ada: [fakeCandidate()] } });
|
|
192
|
+
await user.type(field, "Ada");
|
|
193
|
+
await user.click(await screen.findByText("Ada Lovelace"));
|
|
194
|
+
await waitFor(() => expect(live.id).toBe("pat_1"));
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("Add new patient: hands over what was typed", async () => {
|
|
198
|
+
const { user, field, onAddNew } = renderPatientSearch();
|
|
199
|
+
await user.type(field, "Grace Hopper");
|
|
200
|
+
await user.click(await screen.findByText("Add new patient"));
|
|
201
|
+
expect(onAddNew).toHaveBeenCalledWith("Grace Hopper");
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
});
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/** PhotonPatient before a record, finding them: one field that searches as it's typed in, and who they might be. */
|
|
2
|
+
import { useComponents } from "../../primitives/index.ts";
|
|
3
|
+
import { classify, type Patient } from "@photonhealth/client";
|
|
4
|
+
import { useLatestCallback, useLive } from "../../hooks/index.ts";
|
|
5
|
+
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
|
|
6
|
+
import { useHeldActivity } from "../activity.ts";
|
|
7
|
+
import { ChangeList } from "../ChangeList.tsx";
|
|
8
|
+
import { formatDate } from "../format.ts";
|
|
9
|
+
import { FEW, searchKeys, SearchResults, useTypeAhead, type SearchHandle } from "../search.tsx";
|
|
10
|
+
import { focusProps, searchProps } from "../flow.ts";
|
|
11
|
+
import { IDENTITY_KEYS, noAutofill } from "./fields.tsx";
|
|
12
|
+
import { parsePatientSearchQuery, type ParsedPatientSearchQuery } from "./parsePatientSearchQuery.ts";
|
|
13
|
+
import { TrackedField } from "../../analytics/fieldInteraction.tsx";
|
|
14
|
+
|
|
15
|
+
/** query as patient input */
|
|
16
|
+
const toSearchInput = ({ phone, email, ...demographic }: ParsedPatientSearchQuery) => ({
|
|
17
|
+
demographic,
|
|
18
|
+
contact: { ...(phone ? { phone } : {}), ...(email ? { email } : {}) },
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
/** Whether a query says anything the server can match on. */
|
|
22
|
+
const isSearchable = (q: ParsedPatientSearchQuery) =>
|
|
23
|
+
Boolean(q.name?.first || q.name?.last || q.dateOfBirth || q.phone || q.email);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One word could be either name. It goes as a first name; if nothing comes back, it's worth asking again
|
|
27
|
+
* as a last name — "Lovelace" is as likely as "Ada".
|
|
28
|
+
*/
|
|
29
|
+
const searchBoth = (q: ParsedPatientSearchQuery): ParsedPatientSearchQuery | null =>
|
|
30
|
+
q.name?.first && !q.name.last && !q.dateOfBirth && !q.phone && !q.email ? { name: { last: q.name.first } } : null;
|
|
31
|
+
|
|
32
|
+
export function PatientSearch({
|
|
33
|
+
patient,
|
|
34
|
+
notice,
|
|
35
|
+
onAddNew,
|
|
36
|
+
}: {
|
|
37
|
+
patient: Patient;
|
|
38
|
+
/** Why someone else is being found (e.g. the patient given by id isn't there): shown with the matches. */
|
|
39
|
+
notice?: { title: string; description: string } | null;
|
|
40
|
+
/** "Add new patient": none of these. Gets what was typed, to fill PatientIntakeForm from. */
|
|
41
|
+
onAddNew: (query: string) => void;
|
|
42
|
+
}) {
|
|
43
|
+
const { Alert, Badge, Card, CardBody, CardHeader, Input, Stack } = useComponents();
|
|
44
|
+
const snap = useLive(patient)!;
|
|
45
|
+
const [query, setQuery] = useState("");
|
|
46
|
+
/** What the matches below answer — the query as it was typed when the search went out. */
|
|
47
|
+
const [searched, setSearched] = useState<string | null>(null);
|
|
48
|
+
/** The row the keys are on, by DOM id: the field says so with `aria-activedescendant`. */
|
|
49
|
+
const [activeId, setActiveId] = useState<string | null>(null);
|
|
50
|
+
const busy = snap.status === "loading" || snap.status === "saving";
|
|
51
|
+
const candidates = snap.candidates;
|
|
52
|
+
// What the server says. While searching, nothing about the patient's name, date of birth or sex is missing yet:
|
|
53
|
+
// the search only lists who it might be.
|
|
54
|
+
const changes = classify({
|
|
55
|
+
...snap.changes,
|
|
56
|
+
unapplied: snap.changes.unapplied.filter((c) => !IDENTITY_KEYS.includes(c.key)),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// The field shows a spinner while its search is out (held briefly, so it doesn't flicker).
|
|
60
|
+
const [searching, setSearching] = useState(false);
|
|
61
|
+
if (searching && !busy) setSearching(false); // answered
|
|
62
|
+
const spinning = useHeldActivity(searching ? "query" : null) === "query";
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The search, answered. Only ever `search`: it can't create, and it can't change whoever it finds. One word
|
|
66
|
+
* could be either name, so if it draws a blank as a first name it's asked again as a last name — "Lovelace"
|
|
67
|
+
* is as likely to be typed as "Ada".
|
|
68
|
+
*/
|
|
69
|
+
const runSearch = useLatestCallback(() => {
|
|
70
|
+
const text = query.trim();
|
|
71
|
+
const parsed = parsePatientSearchQuery(text);
|
|
72
|
+
if (!isSearchable(parsed)) return;
|
|
73
|
+
setSearching(true);
|
|
74
|
+
void (async () => {
|
|
75
|
+
try {
|
|
76
|
+
await patient.search(toSearchInput(parsed));
|
|
77
|
+
const alsoLast = searchBoth(parsed);
|
|
78
|
+
if (alsoLast && patient.snapshot.candidates.length === 0) await patient.search(toSearchInput(alsoLast));
|
|
79
|
+
} catch {
|
|
80
|
+
// failures land on the object
|
|
81
|
+
}
|
|
82
|
+
setSearched(text);
|
|
83
|
+
})();
|
|
84
|
+
});
|
|
85
|
+
// Two characters: network-api matches "a first/last name prefix of 2+ characters" (`AmbiguousPatientMatch`),
|
|
86
|
+
// and short surnames are real — Ng, Wu, Li. Not one: that would match thousands, and the server returns at
|
|
87
|
+
// most twenty candidates, so it would hand back an arbitrary slice — a list without your patient in it reads
|
|
88
|
+
// as "not here", which is how a duplicate gets made.
|
|
89
|
+
const typeAhead = useTypeAhead<"query">(() => runSearch(), { minChars: 2 });
|
|
90
|
+
|
|
91
|
+
// A few matches listed: they're the next thing to look at.
|
|
92
|
+
const few = candidates.length > 0 && candidates.length < FEW;
|
|
93
|
+
const answered = () => !typeAhead.waiting() && !busy && searched === query.trim();
|
|
94
|
+
/** The search is answered, and nobody came back. Not the same as nobody being there. */
|
|
95
|
+
const answeredNothing =
|
|
96
|
+
searched !== null && searched === query.trim() && candidates.length === 0 && !busy && !typeAhead.waiting();
|
|
97
|
+
const matches = useRef<SearchHandle | null>(null);
|
|
98
|
+
// The search field: Esc in the matches goes back to it.
|
|
99
|
+
const field = useRef<HTMLInputElement | null>(null);
|
|
100
|
+
|
|
101
|
+
// The field is a search field over the matches (searchKeys): ↑ ↓ move a highlight, Return takes it. Return
|
|
102
|
+
// with nothing to take searches now, rather than after the pause.
|
|
103
|
+
const onKeyDown = (e: KeyboardEvent) => {
|
|
104
|
+
if (searchKeys(e, matches.current, answered())) return;
|
|
105
|
+
if (e.key !== "Enter") return;
|
|
106
|
+
e.preventDefault();
|
|
107
|
+
typeAhead.cancel();
|
|
108
|
+
runSearch();
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// A few matches for what's being typed, and the prescriber is still in the field: focus goes to the first,
|
|
112
|
+
// ready to pick — typing carries on in the field (search.tsx). Once per answer.
|
|
113
|
+
const matchesFor = candidates.map((c) => c.id).join();
|
|
114
|
+
const focusedFor = useRef<string | null>(null);
|
|
115
|
+
const focusFew = useLatestCallback(() => {
|
|
116
|
+
if (!few || !answered() || !field.current || document.activeElement !== field.current) return;
|
|
117
|
+
if (focusedFor.current === matchesFor) return;
|
|
118
|
+
focusedFor.current = matchesFor;
|
|
119
|
+
matches.current?.focus(true);
|
|
120
|
+
});
|
|
121
|
+
// Also on `searched`: the matches can land before the card has noted which query they answer, and until
|
|
122
|
+
// it has, they aren't an answer to move to.
|
|
123
|
+
useEffect(() => focusFew(), [matchesFor, busy, searched, focusFew]);
|
|
124
|
+
|
|
125
|
+
return (
|
|
126
|
+
<Card divided>
|
|
127
|
+
<CardHeader title="Patient" />
|
|
128
|
+
<CardBody>
|
|
129
|
+
<Stack gap="3">
|
|
130
|
+
<div
|
|
131
|
+
{...focusProps}
|
|
132
|
+
{...searchProps}
|
|
133
|
+
onFocus={(e) => {
|
|
134
|
+
if (e.target instanceof HTMLInputElement) field.current = e.target;
|
|
135
|
+
}}
|
|
136
|
+
>
|
|
137
|
+
<TrackedField formName="find_patient" fieldName="patientSearch" isOptional={false}>
|
|
138
|
+
<Input
|
|
139
|
+
label="Find patient"
|
|
140
|
+
placeholder="Name, date of birth, phone or email"
|
|
141
|
+
value={query}
|
|
142
|
+
onChange={(e) => {
|
|
143
|
+
setQuery(e.target.value);
|
|
144
|
+
typeAhead.typed("query", e.target.value);
|
|
145
|
+
// Too little left to search on: the matches on screen answer a query that isn't there any more,
|
|
146
|
+
// so they go, and the card is back where it started — including what it has already moved the
|
|
147
|
+
// cursor to, or typing the same name again would land nowhere.
|
|
148
|
+
if (typeAhead.tooShort(e.target.value)) {
|
|
149
|
+
setSearched(null);
|
|
150
|
+
focusedFor.current = null;
|
|
151
|
+
}
|
|
152
|
+
}}
|
|
153
|
+
onBlur={() => {
|
|
154
|
+
// Leaving asks now rather than after the pause — a search, never a sync: it can't create anyone
|
|
155
|
+
// and it can't change whoever it finds.
|
|
156
|
+
typeAhead.cancel();
|
|
157
|
+
if (query.trim() !== searched) runSearch();
|
|
158
|
+
}}
|
|
159
|
+
onKeyDown={onKeyDown}
|
|
160
|
+
loading={spinning}
|
|
161
|
+
role="combobox"
|
|
162
|
+
aria-expanded={searched !== null}
|
|
163
|
+
aria-autocomplete="list"
|
|
164
|
+
aria-activedescendant={activeId ?? undefined}
|
|
165
|
+
autoFocus
|
|
166
|
+
{...noAutofill}
|
|
167
|
+
/>
|
|
168
|
+
</TrackedField>
|
|
169
|
+
</div>
|
|
170
|
+
|
|
171
|
+
{/* Nothing came back. That the list is empty needs no saying — the prescriber can see it. What they can't
|
|
172
|
+
see is that matching has no tolerance for a typo, so an empty list is not "they aren't here", and adding
|
|
173
|
+
someone already on file is how a duplicate is made. This stands in for a gap: network-api doesn't match
|
|
174
|
+
names fuzzily yet, and when it does an empty list means what it looks like and these words should go. */}
|
|
175
|
+
{answeredNothing && (
|
|
176
|
+
<Alert
|
|
177
|
+
title="Spelling has to be exact."
|
|
178
|
+
description="Try another spelling, fewer letters, or a date of birth."
|
|
179
|
+
/>
|
|
180
|
+
)}
|
|
181
|
+
|
|
182
|
+
{/* Never disabled while a search runs: typing searches, and Tab may have just put focus here. Shown for
|
|
183
|
+
every answered search: with nobody matching, "Add new patient" is the only row — still a row, still
|
|
184
|
+
reached by ↓ from the field, still taken with Return. */}
|
|
185
|
+
{searched !== null && (
|
|
186
|
+
<SearchResults
|
|
187
|
+
label={candidates.length > 0 ? "Matching patients" : "No matching patients"}
|
|
188
|
+
results={candidates.map((m) => ({
|
|
189
|
+
key: m.id,
|
|
190
|
+
label: [m.firstName, m.lastName].filter(Boolean).join(" "),
|
|
191
|
+
meta: m.dateOfBirth ? formatDate(m.dateOfBirth) : undefined,
|
|
192
|
+
}))}
|
|
193
|
+
onPick={(id) => void patient.pick(id).catch(() => {})}
|
|
194
|
+
busy={busy}
|
|
195
|
+
handleRef={matches}
|
|
196
|
+
onBack={() => field.current?.focus()}
|
|
197
|
+
// The cursor stays in the field: ↑ ↓ move a highlight, Return takes it, and a letter or a Backspace
|
|
198
|
+
// always lands in the field — the prescriber can narrow or start over mid-list.
|
|
199
|
+
inField
|
|
200
|
+
onActive={setActiveId}
|
|
201
|
+
// The last row: ↓ past the final match lands on it, and Return takes it.
|
|
202
|
+
action={{
|
|
203
|
+
label: "Add new patient",
|
|
204
|
+
icon: "add",
|
|
205
|
+
onChoose: () => {
|
|
206
|
+
typeAhead.cancel();
|
|
207
|
+
onAddNew(query);
|
|
208
|
+
},
|
|
209
|
+
}}
|
|
210
|
+
/>
|
|
211
|
+
)}
|
|
212
|
+
|
|
213
|
+
{/* With the matches: why someone else is being found, what the server said, and what failed. */}
|
|
214
|
+
{notice && <Alert tone="critical" title={notice.title} description={notice.description} />}
|
|
215
|
+
<ChangeList changes={changes} />
|
|
216
|
+
{snap.error && <Badge tone="critical">{snap.error.message}</Badge>}
|
|
217
|
+
</Stack>
|
|
218
|
+
</CardBody>
|
|
219
|
+
</Card>
|
|
220
|
+
);
|
|
221
|
+
}
|