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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/README.md +35 -8
  2. package/dist/adapters/tailwind.d.ts.map +1 -1
  3. package/dist/adapters/tailwind.js +7 -4
  4. package/dist/adapters/tailwind.js.map +1 -1
  5. package/dist/analytics/PhotonAnalyticsProvider.d.ts +16 -0
  6. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
  7. package/dist/analytics/PhotonAnalyticsProvider.js +57 -0
  8. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
  9. package/dist/analytics/fieldInteraction.d.ts +18 -0
  10. package/dist/analytics/fieldInteraction.d.ts.map +1 -0
  11. package/dist/analytics/fieldInteraction.js +102 -0
  12. package/dist/analytics/fieldInteraction.js.map +1 -0
  13. package/dist/analytics/tracker.d.ts +17 -0
  14. package/dist/analytics/tracker.d.ts.map +1 -0
  15. package/dist/analytics/tracker.js +36 -0
  16. package/dist/analytics/tracker.js.map +1 -0
  17. package/dist/analytics/viewed.d.ts +11 -0
  18. package/dist/analytics/viewed.d.ts.map +1 -0
  19. package/dist/analytics/viewed.js +16 -0
  20. package/dist/analytics/viewed.js.map +1 -0
  21. package/dist/components/PhotonOrder.d.ts.map +1 -1
  22. package/dist/components/PhotonOrder.js +20 -16
  23. package/dist/components/PhotonOrder.js.map +1 -1
  24. package/dist/components/PhotonPatient.d.ts.map +1 -1
  25. package/dist/components/PhotonPatient.js +4 -2
  26. package/dist/components/PhotonPatient.js.map +1 -1
  27. package/dist/components/PhotonPrescription.d.ts +1 -12
  28. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  29. package/dist/components/PhotonPrescription.js +7 -360
  30. package/dist/components/PhotonPrescription.js.map +1 -1
  31. package/dist/components/format.d.ts +2 -2
  32. package/dist/components/format.js +2 -2
  33. package/dist/components/index.d.ts +1 -1
  34. package/dist/components/index.d.ts.map +1 -1
  35. package/dist/components/index.js +1 -1
  36. package/dist/components/index.js.map +1 -1
  37. package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
  38. package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
  39. package/dist/components/order/DraftOrderPrompt.js +26 -0
  40. package/dist/components/order/DraftOrderPrompt.js.map +1 -0
  41. package/dist/components/patient/Benefits.d.ts.map +1 -1
  42. package/dist/components/patient/Benefits.js +2 -1
  43. package/dist/components/patient/Benefits.js.map +1 -1
  44. package/dist/components/patient/Clinical.d.ts +3 -2
  45. package/dist/components/patient/Clinical.d.ts.map +1 -1
  46. package/dist/components/patient/Clinical.js +21 -20
  47. package/dist/components/patient/Clinical.js.map +1 -1
  48. package/dist/components/patient/IntakeForm.d.ts.map +1 -1
  49. package/dist/components/patient/IntakeForm.js +52 -43
  50. package/dist/components/patient/IntakeForm.js.map +1 -1
  51. package/dist/components/patient/Summary.d.ts +1 -1
  52. package/dist/components/patient/Summary.d.ts.map +1 -1
  53. package/dist/components/patient/Summary.js +13 -3
  54. package/dist/components/patient/Summary.js.map +1 -1
  55. package/dist/components/patient/fields.d.ts +1 -2
  56. package/dist/components/patient/fields.d.ts.map +1 -1
  57. package/dist/components/patient/fields.js +2 -1
  58. package/dist/components/patient/fields.js.map +1 -1
  59. package/dist/components/patient/query.d.ts +14 -0
  60. package/dist/components/patient/query.d.ts.map +1 -1
  61. package/dist/components/patient/query.js +5 -0
  62. package/dist/components/patient/query.js.map +1 -1
  63. package/dist/components/prescription/PrescriptionCard.d.ts +45 -0
  64. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
  65. package/dist/components/prescription/PrescriptionCard.js +179 -0
  66. package/dist/components/prescription/PrescriptionCard.js.map +1 -0
  67. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
  68. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
  69. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
  70. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
  71. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
  72. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
  73. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
  74. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
  75. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
  76. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
  77. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
  78. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
  79. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
  80. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
  81. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
  82. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
  83. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
  84. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
  85. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
  86. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
  87. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
  88. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
  89. package/dist/components/{TreatmentPicker.js → prescription/TreatmentSearch/TreatmentPicker.js} +113 -105
  90. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
  91. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
  92. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
  93. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
  94. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
  95. package/dist/components/schemaErrors.d.ts +12 -0
  96. package/dist/components/schemaErrors.d.ts.map +1 -0
  97. package/dist/components/schemaErrors.js +24 -0
  98. package/dist/components/schemaErrors.js.map +1 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +1 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/meta/version.d.ts +5 -0
  104. package/dist/meta/version.d.ts.map +1 -0
  105. package/dist/meta/version.js +5 -0
  106. package/dist/meta/version.js.map +1 -0
  107. package/dist/primitives/PhotonProvider.d.ts +3 -1
  108. package/dist/primitives/PhotonProvider.d.ts.map +1 -1
  109. package/dist/primitives/PhotonProvider.js +23 -11
  110. package/dist/primitives/PhotonProvider.js.map +1 -1
  111. package/dist/primitives/defaults.d.ts.map +1 -1
  112. package/dist/primitives/defaults.js +6 -3
  113. package/dist/primitives/defaults.js.map +1 -1
  114. package/dist/primitives/photonContext.d.ts +3 -0
  115. package/dist/primitives/photonContext.d.ts.map +1 -0
  116. package/dist/primitives/photonContext.js +3 -0
  117. package/dist/primitives/photonContext.js.map +1 -0
  118. package/dist/primitives/types.d.ts +15 -3
  119. package/dist/primitives/types.d.ts.map +1 -1
  120. package/dist/primitives/types.js.map +1 -1
  121. package/dist/primitives/useProvidedPhoton.d.ts +8 -0
  122. package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
  123. package/dist/primitives/useProvidedPhoton.js +8 -0
  124. package/dist/primitives/useProvidedPhoton.js.map +1 -0
  125. package/dist/styles.css +45 -3
  126. package/dist/test-utils/contract.d.ts.map +1 -1
  127. package/dist/test-utils/contract.js +23 -2
  128. package/dist/test-utils/contract.js.map +1 -1
  129. package/package.json +5 -3
  130. package/src/adapters/tailwind.tsx +52 -24
  131. package/src/analytics/PhotonAnalyticsProvider.test.tsx +191 -0
  132. package/src/analytics/PhotonAnalyticsProvider.tsx +96 -0
  133. package/src/analytics/fieldInteraction.test.tsx +184 -0
  134. package/src/analytics/fieldInteraction.tsx +148 -0
  135. package/src/analytics/tracker.test.ts +52 -0
  136. package/src/analytics/tracker.ts +42 -0
  137. package/src/analytics/viewed.ts +27 -0
  138. package/src/components/PhotonOrder.test.tsx +256 -0
  139. package/src/components/PhotonOrder.tsx +45 -30
  140. package/src/components/PhotonPatient.tsx +11 -7
  141. package/src/components/PhotonPrescription.test.tsx +116 -0
  142. package/src/components/PhotonPrescription.tsx +10 -570
  143. package/src/components/format.ts +2 -2
  144. package/src/components/index.ts +1 -1
  145. package/src/components/order/DraftOrderPrompt.test.tsx +80 -0
  146. package/src/components/order/DraftOrderPrompt.tsx +81 -0
  147. package/src/components/patient/Benefits.tsx +21 -13
  148. package/src/components/patient/Clinical.tsx +31 -26
  149. package/src/components/patient/IntakeForm.test.tsx +89 -0
  150. package/src/components/patient/IntakeForm.tsx +168 -136
  151. package/src/components/patient/Summary.test.tsx +106 -0
  152. package/src/components/patient/Summary.tsx +54 -34
  153. package/src/components/patient/fields.tsx +52 -38
  154. package/src/components/patient/query.ts +6 -0
  155. package/src/components/prescription/PrescriptionCard.test.tsx +85 -0
  156. package/src/components/prescription/PrescriptionCard.tsx +347 -0
  157. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +85 -0
  158. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
  159. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +209 -0
  160. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
  161. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +456 -0
  162. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
  163. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
  164. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
  165. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +75 -0
  166. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
  167. package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
  168. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +699 -0
  169. package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
  170. package/src/components/schemaErrors.test.ts +49 -0
  171. package/src/components/schemaErrors.ts +33 -0
  172. package/src/index.ts +2 -0
  173. package/src/meta/version.test.ts +10 -0
  174. package/src/meta/version.ts +4 -0
  175. package/src/primitives/PhotonProvider.tsx +30 -15
  176. package/src/primitives/defaults.tsx +44 -21
  177. package/src/primitives/photonContext.ts +4 -0
  178. package/src/primitives/types.ts +15 -3
  179. package/src/primitives/useProvidedPhoton.ts +21 -0
  180. package/src/styles.css +45 -3
  181. package/src/test-utils/contract.tsx +45 -2
  182. package/dist/components/TreatmentPicker.d.ts +0 -45
  183. package/dist/components/TreatmentPicker.d.ts.map +0 -1
  184. package/dist/components/TreatmentPicker.js.map +0 -1
  185. package/src/components/TreatmentPicker.tsx +0 -350
@@ -0,0 +1,184 @@
1
+ // @vitest-environment jsdom
2
+ import { render, screen, waitFor } from "@testing-library/react";
3
+ import userEvent from "@testing-library/user-event";
4
+ import { useState } from "react";
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+ import { fakeNetworkApiClient } from "@photonhealth/client/testing";
7
+ import { TrackedField, useFieldInteractions } from "./fieldInteraction.tsx";
8
+ import {
9
+ edited,
10
+ meAsPrescriber,
11
+ recordAnalytics,
12
+ type RecordedAnalytics,
13
+ unmountAndRestoreFetch,
14
+ visitedWithoutEditing,
15
+ withAnalytics,
16
+ } from "../../test/analytics.fixtures.tsx";
17
+
18
+ function QuantityAndStrength({ showQuantity = true }: { showQuantity?: boolean }) {
19
+ const fieldInteraction = useFieldInteractions("add_prescription_form");
20
+ const [quantity, setQuantity] = useState("");
21
+ const [strength, setStrength] = useState<string | null>(null);
22
+ const strengthPicked = fieldInteraction("strength", { isOptional: false, hasValue: strength !== null });
23
+ const pickStrength = (picked: string) => {
24
+ strengthPicked.onChange(true);
25
+ setStrength(picked);
26
+ };
27
+ return (
28
+ <>
29
+ {showQuantity && (
30
+ <TrackedField formName="add_prescription_form" fieldName="dispenseQuantity" isOptional={false}>
31
+ <input aria-label="Quantity" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
32
+ </TrackedField>
33
+ )}
34
+ <div role="group" aria-label="Strength" onFocus={strengthPicked.onFocus} onBlur={strengthPicked.onBlur}>
35
+ <button onClick={() => pickStrength("10 mg")}>10 mg</button>
36
+ <button onClick={() => pickStrength("20 mg")}>20 mg</button>
37
+ </div>
38
+ <input aria-label="Elsewhere" />
39
+ </>
40
+ );
41
+ }
42
+
43
+ function TreatmentWithStrengthChips() {
44
+ const fieldInteraction = useFieldInteractions("add_prescription_form");
45
+ const treatment = fieldInteraction("treatment", { isOptional: false });
46
+ const strengthPicked = fieldInteraction("strength", { isOptional: false });
47
+ return (
48
+ <>
49
+ <div style={{ display: "contents" }} {...treatment}>
50
+ <input aria-label="Treatment" />
51
+ <button>Amoxicillin</button>
52
+ <div role="group" aria-label="Strength" onFocus={strengthPicked.onFocus} onBlur={strengthPicked.onBlur}>
53
+ <button onClick={() => strengthPicked.onChange(true)}>500 mg</button>
54
+ </div>
55
+ </div>
56
+ <input aria-label="Elsewhere" />
57
+ </>
58
+ );
59
+ }
60
+
61
+ const renderWithAnalytics = (ui: React.ReactElement, options: { disableAnalytics?: boolean } = {}) =>
62
+ render(ui, { wrapper: withAnalytics(fakeNetworkApiClient(meAsPrescriber).client, options) });
63
+
64
+ let analytics: RecordedAnalytics;
65
+ beforeEach(() => {
66
+ analytics = recordAnalytics();
67
+ });
68
+ afterEach(async () => {
69
+ await unmountAndRestoreFetch();
70
+ vi.restoreAllMocks();
71
+ });
72
+
73
+ describe("useFieldInteractions", () => {
74
+ it("focus, typing and leaving a field send exactly focus, one change and blur", async () => {
75
+ renderWithAnalytics(<QuantityAndStrength />);
76
+ await userEvent.click(screen.getByLabelText("Quantity"));
77
+ await userEvent.keyboard("30");
78
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
79
+
80
+ await analytics.expectEventLog([...edited("dispenseQuantity")]);
81
+ expect(analytics.sentFor("dispenseQuantity")).toEqual([
82
+ expect.objectContaining({
83
+ category: "fieldInteraction",
84
+ formName: "add_prescription_form",
85
+ fieldName: "dispenseQuantity",
86
+ interaction: "focus",
87
+ hasValue: false,
88
+ isOptional: false,
89
+ }),
90
+ expect.objectContaining({ interaction: "change", hasValue: true }),
91
+ expect.objectContaining({ interaction: "blur", hasValue: true, changed: true }),
92
+ ]);
93
+ });
94
+
95
+ it("blur says how long the field had focus, and whether it was changed", async () => {
96
+ const now = vi.spyOn(Date, "now").mockReturnValue(1_000);
97
+ renderWithAnalytics(<QuantityAndStrength />);
98
+ await userEvent.click(screen.getByLabelText("Quantity"));
99
+ now.mockReturnValue(3_500);
100
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
101
+
102
+ await analytics.expectEventLog([...visitedWithoutEditing("dispenseQuantity")]);
103
+ expect(analytics.sentFor("dispenseQuantity")[1]).toMatchObject({ durationMs: 2_500, changed: false });
104
+ });
105
+
106
+ it("each focus is its own session: a change in the next one is sent again", async () => {
107
+ renderWithAnalytics(<QuantityAndStrength />);
108
+ const quantity = screen.getByLabelText("Quantity");
109
+ await userEvent.click(quantity);
110
+ await userEvent.keyboard("3");
111
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
112
+ await userEvent.click(quantity);
113
+ await userEvent.keyboard("0");
114
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
115
+
116
+ await analytics.expectEventLog([...edited("dispenseQuantity"), ...edited("dispenseQuantity")]);
117
+ });
118
+
119
+ it("a picker is one field: moving between its options sends no blur, and picking sends change", async () => {
120
+ renderWithAnalytics(<QuantityAndStrength />);
121
+ await userEvent.click(screen.getByRole("button", { name: "10 mg" }));
122
+ await userEvent.tab();
123
+ await userEvent.click(screen.getByRole("button", { name: "20 mg" }));
124
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
125
+
126
+ await analytics.expectEventLog([...edited("strength")]);
127
+ expect(analytics.sentFor("strength").map((sent) => sent.hasValue)).toEqual([false, true, true]);
128
+ });
129
+
130
+ it("a field removed while it has focus still sends its blur", async () => {
131
+ const { rerender } = renderWithAnalytics(<QuantityAndStrength />);
132
+ await userEvent.click(screen.getByLabelText("Quantity"));
133
+ await userEvent.keyboard("12");
134
+ rerender(<QuantityAndStrength showQuantity={false} />);
135
+
136
+ await analytics.expectEventLog([...edited("dispenseQuantity")]);
137
+ expect(analytics.sentFor("dispenseQuantity")[2]).toMatchObject({ hasValue: true, changed: true });
138
+ });
139
+
140
+ it("never sends what was typed", async () => {
141
+ renderWithAnalytics(<QuantityAndStrength />);
142
+ await userEvent.click(screen.getByLabelText("Quantity"));
143
+ await userEvent.keyboard("987654");
144
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
145
+
146
+ await analytics.expectEventLog([...edited("dispenseQuantity")]);
147
+ for (const body of analytics.bodies()) expect(body).not.toContain("987654");
148
+ });
149
+
150
+ it("sends nothing with analytics off", async () => {
151
+ renderWithAnalytics(<QuantityAndStrength />, { disableAnalytics: true });
152
+ await userEvent.click(screen.getByLabelText("Quantity"));
153
+ await userEvent.keyboard("30");
154
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
155
+
156
+ await analytics.expectEventLog([]);
157
+ });
158
+
159
+ it("outside a PhotonProvider, the field still works and nothing is sent", async () => {
160
+ render(<QuantityAndStrength />);
161
+ await userEvent.click(screen.getByLabelText("Quantity"));
162
+ await userEvent.keyboard("30");
163
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
164
+
165
+ await waitFor(() => expect(screen.getByLabelText<HTMLInputElement>("Quantity").value).toBe("30"));
166
+ await analytics.expectEventLog([]);
167
+ });
168
+
169
+ it("moving within a field is one visit, and a field inside it takes focus for itself", async () => {
170
+ renderWithAnalytics(<TreatmentWithStrengthChips />);
171
+ await userEvent.click(screen.getByLabelText("Treatment"));
172
+ await userEvent.keyboard("amo");
173
+ await userEvent.click(screen.getByRole("button", { name: "Amoxicillin" }));
174
+ await userEvent.click(screen.getByRole("button", { name: "500 mg" }));
175
+ await userEvent.click(screen.getByLabelText("Treatment"));
176
+ await userEvent.click(screen.getByLabelText("Elsewhere"));
177
+
178
+ await analytics.expectEventLog([
179
+ ...edited("treatment"),
180
+ ...edited("strength"),
181
+ ...visitedWithoutEditing("treatment"),
182
+ ]);
183
+ });
184
+ });
@@ -0,0 +1,148 @@
1
+ import { useEffect, useState, type ChangeEvent, type FocusEvent, type ReactNode } from "react";
2
+ import { useTrack } from "./PhotonAnalyticsProvider.tsx";
3
+
4
+ export type FormName = "find_patient" | "new_patient_form" | "update_patient_form" | "add_prescription_form";
5
+
6
+ type Interaction = "focus" | "change" | "blur";
7
+
8
+ export interface FieldInteractionOptions {
9
+ isOptional: boolean;
10
+ hasValue?: boolean;
11
+ }
12
+
13
+ export interface FieldInteractionHandlers {
14
+ onFocus: (event: FocusEvent<Element>) => void;
15
+ onChange: (changedTo: unknown) => void;
16
+ onBlur: (event: FocusEvent<Element>) => void;
17
+ }
18
+
19
+ interface FocusedField {
20
+ owner: object;
21
+ fieldName: string;
22
+ element: Element;
23
+ focusedAt: number;
24
+ changed: boolean;
25
+ hasValue: boolean;
26
+ send: (interaction: Interaction, hasValue: boolean, blurProperties?: BlurProperties) => void;
27
+ }
28
+
29
+ interface BlurProperties {
30
+ durationMs: number;
31
+ changed: boolean;
32
+ }
33
+
34
+ let focusedField: FocusedField | null = null;
35
+ const focusEventsClaimedByInnerField = new WeakSet<Event>();
36
+
37
+ function endFocusedField(hasValue?: boolean) {
38
+ const ended = focusedField;
39
+ if (!ended) return;
40
+ focusedField = null;
41
+ ended.send("blur", hasValue ?? ended.hasValue, {
42
+ durationMs: Math.max(0, Date.now() - ended.focusedAt),
43
+ changed: ended.changed,
44
+ });
45
+ }
46
+
47
+ function endFocusedFieldIfFocusLeft(owner: object) {
48
+ if (focusedField?.owner !== owner) return;
49
+ const { element } = focusedField;
50
+ if (!element.isConnected || !element.contains(element.ownerDocument.activeElement)) endFocusedField();
51
+ }
52
+
53
+ export function useFieldInteractions(formName: FormName) {
54
+ const track = useTrack();
55
+ const [owner] = useState(() => ({}));
56
+
57
+ useEffect(() => endFocusedFieldIfFocusLeft(owner));
58
+ useEffect(
59
+ () => () => {
60
+ setTimeout(() => endFocusedFieldIfFocusLeft(owner));
61
+ },
62
+ [owner],
63
+ );
64
+
65
+ return function fieldInteraction(fieldName: string, options: FieldInteractionOptions): FieldInteractionHandlers {
66
+ const send = (interaction: Interaction, hasValue: boolean, blurProperties?: BlurProperties) =>
67
+ track("Field Interaction", "fieldInteraction", {
68
+ formName,
69
+ fieldName,
70
+ interaction,
71
+ hasValue,
72
+ isOptional: options.isOptional,
73
+ ...blurProperties,
74
+ });
75
+ const isThisFieldFocused = () => focusedField?.owner === owner && focusedField.fieldName === fieldName;
76
+
77
+ return {
78
+ onFocus: (event) => {
79
+ if (focusEventsClaimedByInnerField.has(event.nativeEvent)) return;
80
+ focusEventsClaimedByInnerField.add(event.nativeEvent);
81
+ if (isThisFieldFocused()) return;
82
+ endFocusedField();
83
+ const hasValue = options.hasValue ?? holdsValue(event.currentTarget);
84
+ focusedField = {
85
+ owner,
86
+ fieldName,
87
+ element: event.currentTarget,
88
+ focusedAt: Date.now(),
89
+ changed: false,
90
+ hasValue,
91
+ send,
92
+ };
93
+ send("focus", hasValue);
94
+ },
95
+ onChange: (changedTo) => {
96
+ const hasValue = hasValueAfterChange(changedTo, options.hasValue);
97
+ if (!isThisFieldFocused()) return send("change", hasValue);
98
+ focusedField!.hasValue = hasValue;
99
+ if (focusedField!.changed) return;
100
+ focusedField!.changed = true;
101
+ send("change", hasValue);
102
+ },
103
+ onBlur: (event) => {
104
+ if (!focusMovedWithin(event) && isThisFieldFocused())
105
+ endFocusedField(options.hasValue ?? holdsValue(event.currentTarget));
106
+ },
107
+ };
108
+ };
109
+ }
110
+
111
+ export function TrackedField({
112
+ formName,
113
+ fieldName,
114
+ isOptional,
115
+ hasValue,
116
+ children,
117
+ }: FieldInteractionOptions & { formName: FormName; fieldName: string; children: ReactNode }) {
118
+ const handlers = useFieldInteractions(formName)(fieldName, { isOptional, hasValue });
119
+ return (
120
+ <div style={{ display: "contents" }} {...handlers}>
121
+ {children}
122
+ </div>
123
+ );
124
+ }
125
+
126
+ function focusMovedWithin(event: FocusEvent<Element>) {
127
+ const other = event.relatedTarget;
128
+ return other instanceof Node && other !== event.currentTarget && event.currentTarget.contains(other);
129
+ }
130
+
131
+ function hasValueAfterChange(changedTo: unknown, declared: boolean | undefined): boolean {
132
+ if (typeof changedTo === "boolean") return changedTo;
133
+ const event = changedTo as Partial<ChangeEvent<Element>> | undefined;
134
+ if (event?.currentTarget instanceof Element) return holdsValue(event.currentTarget);
135
+ return declared ?? true;
136
+ }
137
+
138
+ function holdsValue(element: Element): boolean {
139
+ if (element instanceof HTMLInputElement && (element.type === "checkbox" || element.type === "radio"))
140
+ return element.checked;
141
+ if (
142
+ element instanceof HTMLInputElement ||
143
+ element instanceof HTMLTextAreaElement ||
144
+ element instanceof HTMLSelectElement
145
+ )
146
+ return element.value.trim() !== "";
147
+ return [...element.querySelectorAll("input, textarea, select")].some(holdsValue);
148
+ }
@@ -0,0 +1,52 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { environmentUrls, type Photon } from "@photonhealth/client";
3
+ import { fakeNetworkApiClient, photonOver } from "@photonhealth/client/testing";
4
+ import { MAX_QUEUED_EVENTS, Tracker } from "./tracker.ts";
5
+
6
+ // Sending — the token, providerId, analytics-api — is @photonhealth/client's (`ph.analytics.track`, its
7
+ // test/analytics.test.ts). The Tracker only holds events until the sign-in is accepted.
8
+
9
+ const photonWithTrackSpy = () => {
10
+ const ph = photonOver(fakeNetworkApiClient({}).client, environmentUrls("boson"), {
11
+ analytics: { url: "https://analytics-api.boson.health", token: async () => "tok", clientName: null },
12
+ });
13
+ const track = vi.spyOn(ph.analytics!, "track").mockResolvedValue();
14
+ return { ph, track };
15
+ };
16
+
17
+ const event = (n: number) => `Event ${String.fromCharCode(65 + (n % 26))}`;
18
+
19
+ describe("Tracker", () => {
20
+ it("holds events until the sign-in is accepted, then hands them to ph.analytics.track in order", async () => {
21
+ const { ph, track } = photonWithTrackSpy();
22
+ const tracker = new Tracker(ph);
23
+ tracker.track({ event: "Event A", properties: { n: 1 } });
24
+ tracker.track({ event: "Event B", properties: {} });
25
+ await new Promise((r) => setTimeout(r, 10));
26
+ expect(track).not.toHaveBeenCalled();
27
+ tracker.setReady(true);
28
+ expect(track.mock.calls).toEqual([
29
+ ["Event A", { n: 1 }],
30
+ ["Event B", {}],
31
+ ]);
32
+ tracker.track({ event: "Event C", properties: {} });
33
+ expect(track).toHaveBeenLastCalledWith("Event C", {});
34
+ });
35
+
36
+ it(`keeps at most ${MAX_QUEUED_EVENTS} while waiting`, () => {
37
+ const { ph, track } = photonWithTrackSpy();
38
+ const tracker = new Tracker(ph);
39
+ for (let i = 0; i < MAX_QUEUED_EVENTS + 10; i++) tracker.track({ event: event(i), properties: { i } });
40
+ tracker.setReady(true);
41
+ expect(track).toHaveBeenCalledTimes(MAX_QUEUED_EVENTS);
42
+ expect(track.mock.calls[0]).toEqual([event(0), { i: 0 }]);
43
+ });
44
+
45
+ it("holds nothing for an instance with nowhere to send", () => {
46
+ const ph: Photon = photonOver(fakeNetworkApiClient({}).client);
47
+ expect(ph.analytics).toBeNull();
48
+ const tracker = new Tracker(ph);
49
+ tracker.track({ event: "Event A", properties: {} });
50
+ expect(() => tracker.setReady(true)).not.toThrow();
51
+ });
52
+ });
@@ -0,0 +1,42 @@
1
+ import type { AnalyticsProperties, Photon } from "@photonhealth/client";
2
+
3
+ export type { AnalyticsProperties };
4
+
5
+ export interface QueuedEvent {
6
+ event: string;
7
+ properties: AnalyticsProperties;
8
+ }
9
+
10
+ export const MAX_QUEUED_EVENTS = 50;
11
+
12
+ /** Holds the cards' events until the prescriber's sign-in is accepted, then sends them with `ph.analytics.track`. */
13
+ export class Tracker {
14
+ #ready = false;
15
+ #queue: QueuedEvent[] = [];
16
+
17
+ constructor(private readonly ph: Photon) {}
18
+
19
+ setReady(ready: boolean) {
20
+ this.#ready = ready;
21
+ if (ready) this.#flush();
22
+ }
23
+
24
+ track(queued: QueuedEvent) {
25
+ if (!this.ph.analytics) return;
26
+ if (this.#queue.length >= MAX_QUEUED_EVENTS) return;
27
+ this.#queue.push(queued);
28
+ if (this.#ready) this.#flush();
29
+ }
30
+
31
+ #flush() {
32
+ for (const { event, properties } of this.#queue.splice(0)) void this.ph.analytics?.track(event, properties);
33
+ }
34
+ }
35
+
36
+ const trackersByPhoton = new WeakMap<Photon, Tracker>();
37
+
38
+ export function trackerFor(ph: Photon): Tracker {
39
+ let tracker = trackersByPhoton.get(ph);
40
+ if (!tracker) trackersByPhoton.set(ph, (tracker = new Tracker(ph)));
41
+ return tracker;
42
+ }
@@ -0,0 +1,27 @@
1
+ import type { AnalyticsProperties } from "./tracker.ts";
2
+
3
+ interface CardProps {
4
+ order?: unknown;
5
+ patient?: unknown;
6
+ prescription?: unknown;
7
+ locked?: boolean;
8
+ fixed?: boolean;
9
+ }
10
+
11
+ export function viewedPropertiesFromCardProps(props: CardProps): AnalyticsProperties {
12
+ const order = asObject(props.order);
13
+ const linesToAdd = asObject(order?.prescriptions)?.add;
14
+ const lines = Array.isArray(linesToAdd) ? linesToAdd.map(asObject) : [];
15
+ return {
16
+ hasOrderPrefill: props.order != null,
17
+ hasPatientPrefill: props.patient != null || order?.patient != null,
18
+ hasPrescriptionPrefill: props.prescription != null,
19
+ numTemplateIds: lines.filter((line) => typeof line?.templateId === "string").length,
20
+ numPrescriptionIds: lines.filter((line) => typeof line?.id === "string").length,
21
+ locked: Boolean(props.locked),
22
+ fixed: Boolean(props.fixed),
23
+ };
24
+ }
25
+
26
+ const asObject = (value: unknown): Record<string, unknown> | null =>
27
+ value && typeof value === "object" ? (value as Record<string, unknown>) : null;