@photonhealth/react 2.0.0-rc.2 → 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.
Files changed (179) hide show
  1. package/README.md +17 -1
  2. package/dist/analytics/PhotonAnalyticsProvider.d.ts +5 -2
  3. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -1
  4. package/dist/analytics/PhotonAnalyticsProvider.js +34 -15
  5. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -1
  6. package/dist/analytics/cardLifecycle.d.ts +10 -0
  7. package/dist/analytics/cardLifecycle.d.ts.map +1 -0
  8. package/dist/analytics/cardLifecycle.js +43 -0
  9. package/dist/analytics/cardLifecycle.js.map +1 -0
  10. package/dist/analytics/lifecycleOutcomes.d.ts +8 -0
  11. package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
  12. package/dist/analytics/lifecycleOutcomes.js +16 -0
  13. package/dist/analytics/lifecycleOutcomes.js.map +1 -0
  14. package/dist/analytics/tracker.d.ts +5 -3
  15. package/dist/analytics/tracker.d.ts.map +1 -1
  16. package/dist/analytics/tracker.js +10 -5
  17. package/dist/analytics/tracker.js.map +1 -1
  18. package/dist/components/PhotonOrder.d.ts +18 -18
  19. package/dist/components/PhotonOrder.d.ts.map +1 -1
  20. package/dist/components/PhotonOrder.js +17 -6
  21. package/dist/components/PhotonOrder.js.map +1 -1
  22. package/dist/components/PhotonPatient.d.ts +7 -35
  23. package/dist/components/PhotonPatient.d.ts.map +1 -1
  24. package/dist/components/PhotonPatient.js +3 -77
  25. package/dist/components/PhotonPatient.js.map +1 -1
  26. package/dist/components/PhotonPrescription.d.ts +14 -14
  27. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  28. package/dist/components/PhotonPrescription.js +0 -1
  29. package/dist/components/PhotonPrescription.js.map +1 -1
  30. package/dist/components/open.d.ts +11 -13
  31. package/dist/components/open.d.ts.map +1 -1
  32. package/dist/components/open.js +7 -2
  33. package/dist/components/open.js.map +1 -1
  34. package/dist/components/patient/PatientCard/PatientCard.d.ts +30 -0
  35. package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
  36. package/dist/components/patient/PatientCard/PatientCard.js +101 -0
  37. package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
  38. package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
  39. package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
  40. package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
  41. package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
  42. package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
  43. package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
  44. package/dist/components/patient/PatientIntakeForm.js +114 -0
  45. package/dist/components/patient/PatientIntakeForm.js.map +1 -0
  46. package/dist/components/patient/PatientSearch.d.ts +12 -0
  47. package/dist/components/patient/PatientSearch.d.ts.map +1 -0
  48. package/dist/components/patient/PatientSearch.js +148 -0
  49. package/dist/components/patient/PatientSearch.js.map +1 -0
  50. package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
  51. package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
  52. package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +5 -5
  53. package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
  54. package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +13 -15
  55. package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
  56. package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +11 -11
  57. package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
  58. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
  59. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
  60. package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
  61. package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
  62. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
  63. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
  64. package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
  65. package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
  66. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
  67. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
  68. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
  69. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
  70. package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
  71. package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
  72. package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
  73. package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
  74. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
  75. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
  76. package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
  77. package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
  78. package/dist/components/patient/fields.d.ts +7 -25
  79. package/dist/components/patient/fields.d.ts.map +1 -1
  80. package/dist/components/patient/fields.js +11 -53
  81. package/dist/components/patient/fields.js.map +1 -1
  82. package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
  83. package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
  84. package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -15
  85. package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
  86. package/dist/components/prescription/PrescriptionCard.d.ts +14 -8
  87. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -1
  88. package/dist/components/prescription/PrescriptionCard.js +10 -3
  89. package/dist/components/prescription/PrescriptionCard.js.map +1 -1
  90. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +6 -6
  91. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -1
  92. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +6 -6
  93. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -1
  94. package/dist/components/schemaErrors.d.ts +3 -2
  95. package/dist/components/schemaErrors.d.ts.map +1 -1
  96. package/dist/components/schemaErrors.js +2 -1
  97. package/dist/components/schemaErrors.js.map +1 -1
  98. package/dist/components/search.d.ts +1 -1
  99. package/dist/components/search.js +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/meta/version.js +1 -1
  105. package/package.json +5 -2
  106. package/src/analytics/PhotonAnalyticsProvider.test.tsx +0 -1
  107. package/src/analytics/PhotonAnalyticsProvider.tsx +75 -20
  108. package/src/analytics/cardLifecycle.test.tsx +272 -0
  109. package/src/analytics/cardLifecycle.ts +44 -0
  110. package/src/analytics/fieldInteraction.test.tsx +11 -9
  111. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  112. package/src/analytics/lifecycleOutcomes.ts +29 -0
  113. package/src/analytics/tracker.test.ts +1 -1
  114. package/src/analytics/tracker.ts +13 -6
  115. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  116. package/src/components/PhotonOrder.test.tsx +146 -8
  117. package/src/components/PhotonOrder.tsx +37 -26
  118. package/src/components/PhotonPatient.tsx +8 -163
  119. package/src/components/PhotonPrescription.test.tsx +22 -18
  120. package/src/components/PhotonPrescription.tsx +14 -14
  121. package/src/components/ScreeningAlerts.test.tsx +81 -0
  122. package/src/components/open.ts +13 -16
  123. package/src/components/order/DraftOrderPrompt.test.tsx +3 -6
  124. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  125. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  126. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  127. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  128. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  129. package/src/components/patient/PatientSearch.test.tsx +204 -0
  130. package/src/components/patient/PatientSearch.tsx +221 -0
  131. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  132. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +4 -4
  133. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  134. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +23 -23
  135. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  136. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  137. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  138. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  139. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  140. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  141. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  142. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  143. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  144. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  145. package/src/components/patient/fields.tsx +12 -138
  146. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  147. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -21
  148. package/src/components/prescription/PrescriptionCard.test.tsx +174 -12
  149. package/src/components/prescription/PrescriptionCard.tsx +28 -14
  150. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +2 -5
  151. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +3 -6
  152. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +34 -37
  153. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +14 -14
  154. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +2 -5
  155. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +3 -7
  156. package/src/components/schemaErrors.ts +3 -2
  157. package/src/components/search.tsx +1 -1
  158. package/src/index.ts +1 -1
  159. package/src/meta/version.test.ts +1 -0
  160. package/src/meta/version.ts +1 -1
  161. package/dist/components/patient/Benefits.d.ts.map +0 -1
  162. package/dist/components/patient/Benefits.js.map +0 -1
  163. package/dist/components/patient/Clinical.d.ts.map +0 -1
  164. package/dist/components/patient/Clinical.js.map +0 -1
  165. package/dist/components/patient/IntakeForm.d.ts +0 -10
  166. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  167. package/dist/components/patient/IntakeForm.js +0 -333
  168. package/dist/components/patient/IntakeForm.js.map +0 -1
  169. package/dist/components/patient/Summary.d.ts +0 -48
  170. package/dist/components/patient/Summary.d.ts.map +0 -1
  171. package/dist/components/patient/Summary.js +0 -90
  172. package/dist/components/patient/Summary.js.map +0 -1
  173. package/dist/components/patient/query.d.ts +0 -37
  174. package/dist/components/patient/query.d.ts.map +0 -1
  175. package/dist/components/patient/query.js.map +0 -1
  176. package/src/components/patient/IntakeForm.test.tsx +0 -89
  177. package/src/components/patient/IntakeForm.tsx +0 -564
  178. package/src/components/patient/Summary.test.tsx +0 -106
  179. package/src/components/patient/Summary.tsx +0 -330
@@ -0,0 +1,81 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import { describe, expect, it } from "vitest";
3
+ import type { ScreeningAlert } from "@photonhealth/client";
4
+ import { fakeNetworkApiClient } from "@photonhealth/client/testing";
5
+ import { ScreeningAlerts } from "./ScreeningAlerts.tsx";
6
+ import { withPhoton } from "../../test/cards.fixtures.tsx";
7
+
8
+ const amoxicillinAllergy: ScreeningAlert = {
9
+ severity: "MODERATE",
10
+ type: "ALLERGEN",
11
+ description: "May result in an allergic reaction based on a reported history of allergy to amoxicillin.",
12
+ involvedEntities: [{ id: "alg_1", name: "amoxicillin" }],
13
+ };
14
+
15
+ const warfarinInteraction: ScreeningAlert = {
16
+ severity: "MAJOR",
17
+ type: "DRUG",
18
+ description: "Increases the risk of bleeding.",
19
+ involvedEntities: [
20
+ { id: "med_1", name: "warfarin" },
21
+ { id: "med_2", name: "aspirin" },
22
+ ],
23
+ };
24
+
25
+ describe("ScreeningAlerts: what the prescriber reads for each alert", () => {
26
+ it("no alerts: renders nothing", () => {
27
+ const { container } = renderAlerts([]);
28
+ expect(container).toBeEmptyDOMElement();
29
+ });
30
+
31
+ it("titles an alert with its type and severity in lower case", () => {
32
+ renderAlerts([amoxicillinAllergy]);
33
+ expect(screen.getByText("allergen · moderate")).toBeInTheDocument();
34
+ });
35
+
36
+ it("follows the description with the involved names in parentheses, separated by commas", () => {
37
+ renderAlerts([warfarinInteraction]);
38
+ expect(screen.getByText("Increases the risk of bleeding. (warfarin, aspirin)")).toBeInTheDocument();
39
+ });
40
+
41
+ it("shows the description alone when nothing is involved", () => {
42
+ renderAlerts([{ ...warfarinInteraction, involvedEntities: [] }]);
43
+ expect(screen.getByText("Increases the risk of bleeding.")).toBeInTheDocument();
44
+ });
45
+
46
+ it.each([
47
+ ["MINOR", "info"],
48
+ ["MODERATE", "warning"],
49
+ ["MAJOR", "critical"],
50
+ ] as const)("a %s alert is shown in the %s tone", (severity, tone) => {
51
+ renderAlerts([{ ...warfarinInteraction, severity }]);
52
+ expect(toneOfAlertTitled(`drug · ${severity.toLowerCase()}`)).toBe(tone);
53
+ });
54
+
55
+ it("an allergy takes the tone of its severity, the same as any other alert", () => {
56
+ renderAlerts([{ ...amoxicillinAllergy, severity: "MINOR" }]);
57
+ expect(toneOfAlertTitled("allergen · minor")).toBe("info");
58
+ });
59
+
60
+ it("a condition alert is titled as a condition", () => {
61
+ renderAlerts([{ ...warfarinInteraction, type: "CONDITION" }]);
62
+ expect(screen.getByText("condition · major")).toBeInTheDocument();
63
+ });
64
+
65
+ it("shows every alert it is given, in order, repeating identical ones", () => {
66
+ renderAlerts([warfarinInteraction, amoxicillinAllergy, amoxicillinAllergy]);
67
+ expect(alertTitles()).toEqual(["drug · major", "allergen · moderate", "allergen · moderate"]);
68
+ });
69
+ });
70
+
71
+ function renderAlerts(alerts: ScreeningAlert[]) {
72
+ return render(<ScreeningAlerts alerts={alerts} />, { wrapper: withPhoton(fakeNetworkApiClient({}).client) });
73
+ }
74
+
75
+ function toneOfAlertTitled(title: string) {
76
+ return screen.getByText(title).closest("[data-tone]")?.getAttribute("data-tone");
77
+ }
78
+
79
+ function alertTitles() {
80
+ return [...document.querySelectorAll(".prx-alert-title")].map((title) => title.textContent);
81
+ }
@@ -1,14 +1,6 @@
1
1
  import type { Calls } from "@photonhealth/client";
2
2
  import { useEffect, useState } from "react";
3
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
4
  /**
13
5
  * A record given by id that the server doesn't have — network-api opens records only in the prescriber's own
14
6
  * organization, so a link from another one lands here too.
@@ -24,9 +16,14 @@ export class NotFound extends Error {
24
16
  export const openFailed = (what: string, error: Error) =>
25
17
  error instanceof NotFound ? `${what[0]!.toUpperCase()}${what.slice(1)} not found` : `Couldn't open this ${what}`;
26
18
 
27
- /** How a given record opens: `get`, `update` or `sync` — and with what. */
19
+ /**
20
+ * How a record a card is given (an id, or an input) opens: `get`, `update` or `sync` — and with what. Its id
21
+ * (`"pat_…"` or `{ id }`) is read (`get`); the record's fields with its id update it (`update(id, fields)`: only
22
+ * those change); fields without one sync (`sync`: the server finds, matches or creates). A live object is used as
23
+ * given and never comes here. Links give records the same way.
24
+ */
28
25
  export function callFor<I extends object>(
29
- value: Given<I>,
26
+ value: I | string,
30
27
  ): { call: "get"; id: string } | { call: "update"; id: string; fields: Omit<I, "id"> } | { call: "sync"; input: I } {
31
28
  if (typeof value === "string") return { call: "get", id: value };
32
29
  const { id, ...fields } = value as I & { id?: string };
@@ -34,10 +31,10 @@ export function callFor<I extends object>(
34
31
  return Object.keys(fields).length ? { call: "update", id, fields: fields as Omit<I, "id"> } : { call: "get", id };
35
32
  }
36
33
 
37
- /** Open a given record (see `Given`); null when an id has no record. */
34
+ /** Open a given record (see `callFor`); null when an id has no record. */
38
35
  export function openGiven<T, I extends object, R>(
39
36
  calls: Calls<T, I, Omit<I, "id">, R>,
40
- value: Given<I>,
37
+ value: I | string,
41
38
  objectOf: (result: R) => T | null,
42
39
  ): Promise<T | null> {
43
40
  return shared(calls, JSON.stringify(value), async () => {
@@ -64,8 +61,8 @@ export function shared<T>(scope: object, key: string, run: () => Promise<T>): Pr
64
61
  }
65
62
 
66
63
  /** 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;
64
+ export const toOpen = <I extends object>(value: I | string | object | null | undefined, isLive: boolean) =>
65
+ !isLive && value && (typeof value === "string" || Object.keys(value).length) ? (value as I | string) : null;
69
66
 
70
67
  /**
71
68
  * `openGiven` for a card: the object once it's open, or why it couldn't be. Opens again when what it's given
@@ -73,7 +70,7 @@ export const toOpen = <I extends object>(value: Given<I> | object | null | undef
73
70
  */
74
71
  export function useOpened<T, I extends object, R>(
75
72
  calls: Calls<T, I, Omit<I, "id">, R>,
76
- value: Given<I> | null,
73
+ value: I | string | null,
77
74
  objectOf: (result: R) => T | null,
78
75
  what: string,
79
76
  ): { opened: T | null; error: Error | null } {
@@ -84,7 +81,7 @@ export function useOpened<T, I extends object, R>(
84
81
  error: null,
85
82
  });
86
83
  useEffect(() => {
87
- const wanted = JSON.parse(key) as Given<I> | null;
84
+ const wanted = JSON.parse(key) as I | string | null;
88
85
  if (!wanted) return;
89
86
  let live = true;
90
87
  const id = typeof wanted === "string" ? wanted : ((wanted as { id?: string }).id ?? "");
@@ -1,8 +1,7 @@
1
- // @vitest-environment jsdom
2
1
  import type { PrescriptionRecord } from "@photonhealth/client";
3
2
  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";
3
+ import { act, fireEvent, render, screen } from "@testing-library/react";
4
+ import { describe, expect, it, vi } from "vitest";
6
5
  import { DraftOrderPrompt } from "./DraftOrderPrompt.tsx";
7
6
 
8
7
  const record = (id: string, fields: Partial<PrescriptionRecord> = {}): PrescriptionRecord => ({
@@ -33,8 +32,6 @@ const lisinopril = record("rx_2", {
33
32
  });
34
33
 
35
34
  describe("DraftOrderPrompt", () => {
36
- afterEach(() => cleanup());
37
-
38
35
  it("shows each prescription on the draft, read-only, and asks whether to continue it", () => {
39
36
  render(
40
37
  <DraftOrderPrompt
@@ -50,7 +47,7 @@ describe("DraftOrderPrompt", () => {
50
47
  expect(screen.getByText("Signed")).toBeTruthy();
51
48
  // Nothing to edit, sign or remove until the prescriber decides.
52
49
  expect(screen.queryAllByRole("textbox")).toHaveLength(0);
53
- expect(screen.queryByRole("button", { name: "Add" })).toBeNull();
50
+ expect(screen.queryByRole("button", { name: "Sign" })).toBeNull();
54
51
  expect(screen.queryByRole("button", { name: "Remove prescription" })).toBeNull();
55
52
  expect(screen.getByText("Would you like to continue this order?")).toBeTruthy();
56
53
  expect(screen.getAllByRole("button").map((b) => b.textContent)).toEqual(["Continue", "Start a new order"]);
@@ -0,0 +1,255 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import { describe, expect, it } from "vitest";
3
+ import userEvent, { type UserEvent } from "@testing-library/user-event";
4
+ import { ambiguous, fakeNetworkApiClient, noMatch, payload, photonOver } from "@photonhealth/client/testing";
5
+ import { PatientCard } from "./PatientCard.tsx";
6
+ import { patient, withPhoton } from "../../../../test/cards.fixtures.tsx";
7
+
8
+ type PatientCardProps = Parameters<typeof PatientCard>[0];
9
+ type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
10
+
11
+ const fakePatientGrace = {
12
+ ...patient,
13
+ id: "pat_2",
14
+ demographic: { ...patient.demographic, name: { ...patient.demographic.name, first: "Grace", last: "Hopper" } },
15
+ };
16
+
17
+ /**
18
+ * A fake network-api that answers each patient read and update by id from `patientsById` (an id not there has
19
+ * no record), plus any other calls in `script`.
20
+ */
21
+ const fakeServer = (patientsById: Record<string, unknown> = { pat_1: patient }, script: NetworkScript = {}) => {
22
+ const byId = (vars: { id: string }) => payload("patient", "PatientPayload", patientsById[vars.id] ?? null);
23
+ return fakeNetworkApiClient({ GetPatient: byId, UpdatePatient: byId, ...script });
24
+ };
25
+
26
+ /** Time for any call a render would repeat to go out. */
27
+ const settle = () => new Promise((done) => setTimeout(done, 100));
28
+
29
+ /** PatientCard over `fakeServer`, with a `user` to type and click as a prescriber would. */
30
+ const renderPatientCard = (props: PatientCardProps, patientsById?: Record<string, unknown>, script?: NetworkScript) => {
31
+ const { client, names } = fakeServer(patientsById, script);
32
+ const user = userEvent.setup();
33
+ return { ...render(<PatientCard {...props} />, { wrapper: withPhoton(client) }), callNames: names, user };
34
+ };
35
+
36
+ const findPatientSearchComponent = () => screen.findByLabelText("Find patient");
37
+
38
+ const findPatientSummaryComponent = (name = /Ada Lovelace/) => screen.findByRole("heading", { name });
39
+
40
+ describe("PatientCard", () => {
41
+ describe("initial display for patient reference with clear ID", () => {
42
+ it("nothing passed: shows PatientSearch", async () => {
43
+ renderPatientCard({});
44
+ expect(await findPatientSearchComponent()).toBeInTheDocument();
45
+ });
46
+
47
+ it("an empty object: shows PatientSearch", async () => {
48
+ renderPatientCard({ patient: {} });
49
+ expect(await findPatientSearchComponent()).toBeInTheDocument();
50
+ });
51
+
52
+ it("a live Patient with a record: shows its summary", async () => {
53
+ const { client } = fakeServer();
54
+ const live = (await photonOver(client).patient.get("pat_1"))!;
55
+ render(<PatientCard patient={live} />, { wrapper: withPhoton(client) });
56
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
57
+ });
58
+
59
+ it("an id: shows PatientSummary for patient with that id", async () => {
60
+ renderPatientCard({ patient: "pat_1" });
61
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
62
+ });
63
+
64
+ it("an id as { id }: shows PatientSummary, the same as the id alone", async () => {
65
+ renderPatientCard({ patient: { id: "pat_1" } });
66
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
67
+ });
68
+
69
+ it("an id that doesn't exist: shows PatientSearch, saying the patient wasn't found", async () => {
70
+ renderPatientCard({ patient: "pat_missing" });
71
+ expect(await findPatientSearchComponent()).toBeInTheDocument();
72
+ expect(screen.getByText("Patient not found")).toBeInTheDocument();
73
+ });
74
+
75
+ it("an id that doesn't exist, read-only: says the patient wasn't found, with no search", async () => {
76
+ renderPatientCard({ patient: "pat_missing", readOnly: true });
77
+ expect(await screen.findByText("Patient not found")).toBeInTheDocument();
78
+ expect(screen.queryByLabelText("Find patient")).not.toBeInTheDocument();
79
+ });
80
+
81
+ it("an id the server fails to read: says the patient couldn't be opened", async () => {
82
+ renderPatientCard({ patient: "pat_1" }, undefined, {
83
+ GetPatient: () => {
84
+ throw new Error("network-api is down");
85
+ },
86
+ });
87
+ expect(await screen.findByText("Couldn't open this patient")).toBeInTheDocument();
88
+ expect(screen.queryByLabelText("Find patient")).not.toBeInTheDocument();
89
+ });
90
+
91
+ it("an id with fields: updates the patient once, shows PatientSummary", async () => {
92
+ // The server reads Ada as she is (born 1/1/90), and answers the update with the date of birth it was given.
93
+ const updated = { ...patient, demographic: { ...patient.demographic, dateOfBirth: "1991-02-03" } };
94
+ const { callNames } = renderPatientCard(
95
+ { patient: { id: "pat_1", demographic: { dateOfBirth: "1991-02-03" } } },
96
+ undefined,
97
+ {
98
+ UpdatePatient: () => payload("patient", "PatientPayload", updated),
99
+ },
100
+ );
101
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
102
+ expect(await screen.findByText(/2\/3\/91/)).toBeInTheDocument();
103
+ expect(screen.queryByText(/1\/1\/90/)).not.toBeInTheDocument();
104
+ await settle();
105
+ expect(callNames().filter((name) => name === "UpdatePatient")).toHaveLength(1);
106
+ });
107
+ });
108
+
109
+ // Without a patient ID, we attempt to upsert a patient record using the other provided fields.
110
+ // TODO: update implementation it so that any case besides an exact match shows PatientSearch
111
+ describe("initial display for patient reference with no ID", () => {
112
+ it("fields that match a patient: shows its summary", async () => {
113
+ renderPatientCard({ patient: { demographic: { name: { first: "Ada", last: "Lovelace" } } } }, undefined, {
114
+ SyncPatient: () => payload("patient", "PatientPayload", patient),
115
+ });
116
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
117
+ });
118
+
119
+ // TODO: update implementation it so that any case besides an exact match shows PatientSearch
120
+ it("a name or date of birth that match no one: shows PatientIntakeForm, filled in with the provided fields", async () => {
121
+ renderPatientCard({ patient: { demographic: { name: { first: "Grace", last: "Hopper" } } } }, undefined, {
122
+ SyncPatient: noMatch,
123
+ });
124
+ expect(await screen.findByLabelText("First name")).toHaveValue("Grace");
125
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
126
+ expect(screen.getByRole("button", { name: "Save patient" })).toBeInTheDocument();
127
+ });
128
+
129
+ // TODO: update implementation it so that any case besides an exact match shows PatientSearch
130
+ it("a phone or email that match no one: shows an empty PatientSearch", async () => {
131
+ renderPatientCard({ patient: { contact: { phone: "+15555550100" } } }, undefined, { SyncPatient: noMatch });
132
+ expect(await findPatientSearchComponent()).toHaveValue("");
133
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
134
+ });
135
+
136
+ // TODO: update implementation it so that any case besides an exact match shows PatientSearch
137
+ it("a phone or email that match multiple candidates: shows an empty PatientSearch, without the candidates", async () => {
138
+ renderPatientCard({ patient: { contact: { phone: "+15555550100" } } }, undefined, {
139
+ SyncPatient: () =>
140
+ ambiguous([
141
+ { id: "pat_1", firstName: "Ada", lastName: "Lovelace", dateOfBirth: "1990-01-01" },
142
+ { id: "pat_2", firstName: "Ada", lastName: "Byron", dateOfBirth: "1990-01-01" },
143
+ ]),
144
+ });
145
+ expect(await findPatientSearchComponent()).toHaveValue("");
146
+ await settle();
147
+ expect(screen.queryByText("Ada Lovelace")).not.toBeInTheDocument();
148
+ });
149
+ });
150
+
151
+ describe("how display changes when the patient prop changes", () => {
152
+ it("nothing, then an id, then nothing again: shows PatientSearch, then PatientSummary, then PatientSearch", async () => {
153
+ const view = renderPatientCard({});
154
+ await findPatientSearchComponent();
155
+ view.rerender(<PatientCard patient="pat_1" />);
156
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
157
+ view.rerender(<PatientCard />);
158
+ expect(await findPatientSearchComponent()).toBeInTheDocument();
159
+ });
160
+
161
+ it("an id, then another id: shows the second patient's summary", async () => {
162
+ const view = renderPatientCard({ patient: "pat_1" }, { pat_1: patient, pat_2: fakePatientGrace });
163
+ await findPatientSummaryComponent();
164
+ view.rerender(<PatientCard patient="pat_2" />);
165
+ expect(await findPatientSummaryComponent(/Grace Hopper/)).toBeInTheDocument();
166
+ expect(screen.queryByRole("heading", { name: /Ada Lovelace/ })).not.toBeInTheDocument();
167
+ });
168
+
169
+ it("an id that doesn't exist, then one that does: shows PatientSummary for the id", async () => {
170
+ const view = renderPatientCard({ patient: "pat_missing" });
171
+ await findPatientSearchComponent();
172
+ view.rerender(<PatientCard patient="pat_1" />);
173
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
174
+ expect(screen.queryByText("Patient not found")).not.toBeInTheDocument();
175
+ });
176
+
177
+ it("fields without an id that match no one, then an id: shows PatientSummary for the id", async () => {
178
+ const view = renderPatientCard(
179
+ { patient: { demographic: { name: { first: "Grace", last: "Hopper" } } } },
180
+ undefined,
181
+ {
182
+ SyncPatient: noMatch,
183
+ },
184
+ );
185
+ await screen.findByLabelText("First name");
186
+ view.rerender(<PatientCard patient="pat_1" />);
187
+ expect(await findPatientSummaryComponent()).toBeInTheDocument();
188
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
189
+ });
190
+ });
191
+
192
+ describe("transitioning between display components", () => {
193
+ /** starts at PatientSearch, types Grace Hopper, chooses Add new patient, fills in the rest of PatientIntakeForm and saves. */
194
+ const addGraceHopper = async (user: UserEvent) => {
195
+ await user.type(await findPatientSearchComponent(), "Grace Hopper");
196
+ await user.click(await screen.findByText("Add new patient"));
197
+ await user.type(await screen.findByLabelText("Date of birth"), "1906-12-09");
198
+ await user.selectOptions(screen.getByRole("combobox", { name: "Sex" }), "FEMALE");
199
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
200
+ };
201
+
202
+ it("Add new patient from PatientSearch: shows PatientIntakeForm, filled in with what was typed", async () => {
203
+ const { user } = renderPatientCard({}, undefined, { SyncPatient: noMatch });
204
+ await user.type(await findPatientSearchComponent(), "Grace Hopper");
205
+ await user.click(await screen.findByText("Add new patient"));
206
+ expect(await screen.findByLabelText("First name")).toHaveValue("Grace");
207
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
208
+ expect(screen.queryByLabelText("Find patient")).not.toBeInTheDocument();
209
+ });
210
+
211
+ it("Save on PatientIntakeForm, and the server successfully adds the patient: shows PatientSummary for them", async () => {
212
+ const { user } = renderPatientCard({}, undefined, {
213
+ // Searching finds no one; Save (a sync with a sex) adds Grace.
214
+ SyncPatient: (vars: { demographic?: { sex?: string } }) =>
215
+ vars.demographic?.sex ? payload("patient", "PatientPayload", fakePatientGrace) : noMatch(),
216
+ });
217
+ await addGraceHopper(user);
218
+ expect(await findPatientSummaryComponent(/Grace Hopper/)).toBeInTheDocument();
219
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
220
+ });
221
+
222
+ it("Save on PatientIntakeForm, and the server fails to add the patient: stays on PatientIntakeForm, as filled in", async () => {
223
+ const { user } = renderPatientCard({}, undefined, {
224
+ // Searching finds no one; Save (a sync with a sex) fails.
225
+ SyncPatient: (vars: { demographic?: { sex?: string } }) => {
226
+ if (vars.demographic?.sex) throw new Error("network-api is down");
227
+ return noMatch();
228
+ },
229
+ });
230
+ await addGraceHopper(user);
231
+ expect(await screen.findByText("network-api is down")).toBeInTheDocument();
232
+ expect(screen.getByLabelText("First name")).toHaveValue("Grace");
233
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
234
+ expect(screen.queryByLabelText("Find patient")).not.toBeInTheDocument();
235
+ });
236
+
237
+ // PatientCard remembers that the prescriber chose "Add new patient", and what they typed, so it can show
238
+ // PatientIntakeForm. Saving the patiient doesn't clear that: once the patient has a record, PatientSummary simply wins.
239
+ // So when "Change patient" swaps in a new blank patient, a card that kept that memory might open PatientIntakeForm again,
240
+ // filled in with the patient just added, instead of starting a fresh search for the next one.
241
+ // TODO: revisit code implementation so that this weird case can't happen
242
+ it("Change patient after adding a patient: shows PatientSearch, not the added patient's PatientIntakeForm", async () => {
243
+ const { user } = renderPatientCard({}, undefined, {
244
+ // Searching finds no one; Save (a sync with a sex) adds Grace.
245
+ SyncPatient: (vars: { demographic?: { sex?: string } }) =>
246
+ vars.demographic?.sex ? payload("patient", "PatientPayload", fakePatientGrace) : noMatch(),
247
+ });
248
+ await addGraceHopper(user);
249
+ await findPatientSummaryComponent(/Grace Hopper/);
250
+ await user.click(screen.getByRole("button", { name: "Change patient" }));
251
+ expect(await findPatientSearchComponent()).toBeInTheDocument();
252
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
253
+ });
254
+ });
255
+ });
@@ -0,0 +1,177 @@
1
+ import { useComponents } from "../../../primitives/index.ts";
2
+ import { classify, type ChangeOption, type Patient, type PatientInput } from "@photonhealth/client";
3
+ import { useLive, useOnChange } from "../../../hooks/index.ts";
4
+ import { useState } from "react";
5
+ import { openFailed, type NotFound } from "../../open.ts";
6
+ import type { PhotonPatientProps } from "../../PhotonPatient.tsx";
7
+ import { PatientIntakeForm } from "../PatientIntakeForm.tsx";
8
+ import { PatientSearch } from "../PatientSearch.tsx";
9
+ import { PatientSummary } from "../PatientSummary/PatientSummary.tsx";
10
+ import { usePatientToShow } from "./usePatientToShow.ts";
11
+ import { useSavePatientAndSendEvent } from "../../../analytics/cardLifecycle.ts";
12
+
13
+ type PatientClinicalInput = NonNullable<PatientInput["clinical"]>;
14
+
15
+ /** A stable key per live object: a different patient object gets a fresh form. */
16
+ const objectKeys = new WeakMap<object, number>();
17
+ let nextKey = 0;
18
+ const keyOf = (obj: object) => {
19
+ if (!objectKeys.has(obj)) objectKeys.set(obj, ++nextKey);
20
+ return objectKeys.get(obj)!;
21
+ };
22
+
23
+ /** What PatientCard renders, in the order its body checks for each. */
24
+ export enum PatientCardState {
25
+ /** The patient couldn't be opened for a reason other than not found: an error alert. */
26
+ FAILED_TO_OPEN = "failedToOpen",
27
+ /** No live patient yet, or no snapshot of it: the "Loading…" card. */
28
+ LOADING = "loading",
29
+ /** The patient has a record: PatientSummary. */
30
+ SUMMARY = "summary",
31
+ /** The patient has no record yet: PatientSearch, to match any existing records. */
32
+ SEARCH = "search",
33
+ /** The patient has no record yet, and user is adding the patient to Photon: PatientIntakeForm. */
34
+ INTAKE_FORM = "intakeForm",
35
+ }
36
+
37
+ /** Which state PatientCard is in, from what usePatientToShow and useLive give it. */
38
+ const getPatientCardState = ({
39
+ failedToOpen,
40
+ patient,
41
+ snap,
42
+ adding,
43
+ }: {
44
+ failedToOpen: Error | null;
45
+ patient: Patient | null;
46
+ snap: Patient["snapshot"] | null;
47
+ /** Whether the prescriber is adding a new patient rather than finding one (see `startsAdding`). */
48
+ adding: boolean;
49
+ }): PatientCardState => {
50
+ if (failedToOpen) return PatientCardState.FAILED_TO_OPEN;
51
+ if (!patient || !snap) return PatientCardState.LOADING;
52
+ if (snap.state) return PatientCardState.SUMMARY;
53
+ return adding ? PatientCardState.INTAKE_FORM : PatientCardState.SEARCH;
54
+ };
55
+
56
+ /**
57
+ * Whether a patient without a record starts on PatientIntakeForm rather than PatientSearch: when it already has
58
+ * a name or date of birth (e.g. a host's details the server hasn't matched), there's nothing left to search for.
59
+ */
60
+ const startsAdding = (patient: Patient) => {
61
+ const demographic = patient.known.demographic;
62
+ return Boolean(demographic?.name?.first || demographic?.name?.last || demographic?.dateOfBirth);
63
+ };
64
+
65
+ /**
66
+ * PhotonPatient, and what only PhotonOrder gives it: read-only and no "Change patient" (a sent order), no "Change
67
+ * patient" (an order handed off to it), and the server's request for a way to reach the patient (its reason),
68
+ * which opens the contact fields. Internal: the package index exports only PhotonPatient.
69
+ */
70
+ export function PatientCard({
71
+ patient: patientProp,
72
+ onPatient,
73
+ readOnly,
74
+ hideChangePatient,
75
+ addressRequest,
76
+ notFound: notFoundInOrder,
77
+ }: PhotonPatientProps & {
78
+ /** Nothing to edit, and no "Change patient" (a sent order's patient). */
79
+ readOnly?: boolean;
80
+ /** No "Change patient", but still editable (an order handed off to PhotonOrder). */
81
+ hideChangePatient?: boolean;
82
+ addressRequest?: string | null;
83
+ /** The patient it was given by id isn't there (PhotonOrder's): said in the form, with the matches. */
84
+ notFound?: NotFound | null;
85
+ }) {
86
+ const { Alert, Card, CardHeader } = useComponents();
87
+ const { patient, notFound, failedToOpen, startOver } = usePatientToShow(patientProp, { readOnly });
88
+ const snap = useLive(patient);
89
+ useOnChange(patient, (p) => p.state, onPatient);
90
+ const savePatientAndSendEvent = useSavePatientAndSendEvent();
91
+ // Finding someone and adding them are two different jobs, so the card does one at a time. Decided once per patient
92
+ // object: "Add new patient" switches to adding, with what was typed; a different patient object starts over.
93
+ const [intake, setIntake] = useState<{ patient: Patient; adding: boolean; query: string | null } | null>(null);
94
+ const intakeForPatient = intake?.patient === patient ? intake : null;
95
+ if (patient && !intakeForPatient) setIntake({ patient, adding: startsAdding(patient), query: null });
96
+ const adding = intakeForPatient?.adding ?? (patient ? startsAdding(patient) : false);
97
+ const state = getPatientCardState({ failedToOpen, patient, snap, adding });
98
+
99
+ if (state === PatientCardState.FAILED_TO_OPEN)
100
+ return <Alert tone="critical" title={openFailed("patient", failedToOpen!)} description={failedToOpen!.message} />;
101
+ if (state === PatientCardState.LOADING) {
102
+ return (
103
+ <Card divided>
104
+ <CardHeader title="Patient" description="Loading…" />
105
+ </Card>
106
+ );
107
+ }
108
+
109
+ // Past LOADING, getPatientCardState guarantees both are set.
110
+ const livePatient = patient!;
111
+ const snapshot = snap!;
112
+ const changes = classify(snapshot.changes);
113
+ const update = (input: Omit<PatientInput, "id">) =>
114
+ void savePatientAndSendEvent(livePatient, () => livePatient.update(input)).catch(() => {}); // failures land on the object
115
+ const patchClinical = (clinical: PatientClinicalInput) => update({ clinical });
116
+ const choose = (option: ChangeOption) =>
117
+ void savePatientAndSendEvent(livePatient, () => livePatient.choose(option)).catch(() => {});
118
+
119
+ if (state === PatientCardState.SUMMARY) {
120
+ const record = snapshot.state!;
121
+ return (
122
+ <PatientSummary
123
+ key={record.id}
124
+ patient={record}
125
+ saving={snapshot.status === "saving"}
126
+ changes={changes}
127
+ error={snapshot.error}
128
+ onChoose={choose}
129
+ onAddAllergy={(name) => patchClinical({ allergies: { add: [{ name }] } })}
130
+ onConfirmNone={(list) => patchClinical({ [list]: { none: true } })}
131
+ onRemoveAllergy={(a) => patchClinical({ allergies: { remove: [{ id: a.id }] } })}
132
+ onRemoveMedication={(m) => patchClinical({ medications: { remove: [{ id: m.id, status: m.status }] } })}
133
+ onAddDiagnosis={(diagnosis) => patchClinical({ diagnoses: { add: [diagnosis] } })}
134
+ onRemoveDiagnosis={(d) => patchClinical({ diagnoses: { remove: [{ id: d.id }] } })}
135
+ onAddBenefit={(b) => update({ benefits: { add: [b] } })}
136
+ onRemoveBenefit={(b) => update({ benefits: { remove: [{ id: b.id }] } })}
137
+ onConfirmNoBenefits={() => update({ benefits: { none: true } })}
138
+ onAddMedication={(name) => patchClinical({ medications: { add: [{ name, status: "ACTIVE" }] } })}
139
+ onSaveDetails={(input) =>
140
+ savePatientAndSendEvent(livePatient, () => livePatient.update(input)).then(
141
+ () => true,
142
+ () => false, // the failure lands on the object, and the card shows it
143
+ )
144
+ }
145
+ addressRequest={readOnly ? null : (addressRequest ?? null)}
146
+ readOnly={readOnly}
147
+ onChangePatient={
148
+ readOnly || hideChangePatient
149
+ ? undefined
150
+ : () => {
151
+ onPatient?.(null); // given a patient, the host decides what's next
152
+ startOver();
153
+ }
154
+ }
155
+ />
156
+ );
157
+ }
158
+
159
+ // SEARCH or INTAKE_FORM. An id that was not found: said with the search, or on the form, for someone else.
160
+ const notFoundError = notFoundInOrder ?? notFound;
161
+ const notice = notFoundError && { title: openFailed("patient", notFoundError), description: notFoundError.message };
162
+ // A different patient object (e.g. after "Change patient") starts a fresh search or form.
163
+ if (state === PatientCardState.SEARCH) {
164
+ return (
165
+ <PatientSearch
166
+ key={keyOf(livePatient)}
167
+ patient={livePatient}
168
+ notice={notice}
169
+ onAddNew={(query) => setIntake({ patient: livePatient, adding: true, query })}
170
+ />
171
+ );
172
+ }
173
+
174
+ return (
175
+ <PatientIntakeForm key={keyOf(livePatient)} patient={livePatient} query={intakeForPatient?.query} notice={notice} />
176
+ );
177
+ }
@@ -0,0 +1,44 @@
1
+ import { Patient, type PatientInput, type PatientResult } from "@photonhealth/client";
2
+ import { useState } from "react";
3
+ import { usePhoton } from "../../../primitives/index.ts";
4
+ import { NotFound, toOpen, useOpened } from "../../open.ts";
5
+ import type { PhotonPatientProps } from "../../PhotonPatient.tsx";
6
+
7
+ // At module level, not inline: useOpened re-runs its server call when this function changes.
8
+ const patientOf = (result: PatientResult) => result.patient;
9
+
10
+ /**
11
+ * Which live Patient a patient card shows, from its `patient` prop:
12
+ * - the host's live `Patient`, if it passed one;
13
+ * - otherwise a blank patient the card made to find or add someone, if it has one for this prop — made when the
14
+ * prop has nothing to open, when its id isn't found, or on "Change patient" (`startOver`);
15
+ * - otherwise the one opened from the prop's id or fields (`null` while it opens).
16
+ *
17
+ * A blank patient belongs to the prop value it was made for, so when the host passes something else the card
18
+ * shows that instead, and passing nothing again gives a fresh blank patient.
19
+ */
20
+ export function usePatientToShow(patientProp: PhotonPatientProps["patient"], { readOnly = false } = {}) {
21
+ const ph = usePhoton();
22
+ const hostPatient = patientProp instanceof Patient ? patientProp : null;
23
+ const patientToOpen = toOpen<PatientInput>(patientProp, Boolean(hostPatient));
24
+ // Hooks run on every render, before any return (React's rule). With a host patient there's nothing to open.
25
+ const { opened: openedPatient, error: openError } = useOpened(ph.patient, patientToOpen, patientOf, "patient");
26
+ const [blank, setBlank] = useState<{ forProp: string; patient: Patient } | null>(null);
27
+
28
+ // The host's live Patient: shown as is. "Change patient" is the host's to handle (the card calls onPatient(null)).
29
+ if (hostPatient) return { patient: hostPatient, notFound: null, failedToOpen: null, startOver: () => {} };
30
+
31
+ const propKey = JSON.stringify(patientToOpen);
32
+ const startOver = () => setBlank({ forProp: propKey, patient: ph.patient() });
33
+ const blankPatient = blank?.forProp === propKey ? blank.patient : null;
34
+ // An id the server doesn't have: the card asks for someone to find or add instead, saying why. A read-only card
35
+ // can't add anyone, so it shows the error instead.
36
+ const notFound = openError instanceof NotFound && !readOnly ? openError : null;
37
+ // Any other failure to open: the card shows it.
38
+ const failedToOpen = openError && !notFound ? openError : null;
39
+
40
+ // Nothing to open, or not found: a blank patient to find or add someone.
41
+ if (!blankPatient && (!patientToOpen || notFound)) startOver();
42
+
43
+ return { patient: blankPatient ?? openedPatient, notFound, failedToOpen, startOver };
44
+ }