@photonhealth/react 0.0.0-stage → 2.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +111 -2
- package/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +2 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/tailwind.d.ts +3 -0
- package/dist/adapters/tailwind.d.ts.map +1 -0
- package/dist/adapters/tailwind.js +126 -0
- package/dist/adapters/tailwind.js.map +1 -0
- package/dist/analytics/PhotonAnalyticsProvider.d.ts +16 -0
- package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
- package/dist/analytics/PhotonAnalyticsProvider.js +57 -0
- package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
- package/dist/analytics/fieldInteraction.d.ts +18 -0
- package/dist/analytics/fieldInteraction.d.ts.map +1 -0
- package/dist/analytics/fieldInteraction.js +102 -0
- package/dist/analytics/fieldInteraction.js.map +1 -0
- package/dist/analytics/tracker.d.ts +17 -0
- package/dist/analytics/tracker.d.ts.map +1 -0
- package/dist/analytics/tracker.js +36 -0
- package/dist/analytics/tracker.js.map +1 -0
- package/dist/analytics/viewed.d.ts +11 -0
- package/dist/analytics/viewed.d.ts.map +1 -0
- package/dist/analytics/viewed.js +16 -0
- package/dist/analytics/viewed.js.map +1 -0
- package/dist/components/ChangeList.d.ts +21 -0
- package/dist/components/ChangeList.d.ts.map +1 -0
- package/dist/components/ChangeList.js +40 -0
- package/dist/components/ChangeList.js.map +1 -0
- package/dist/components/PhotonOrder.d.ts +46 -0
- package/dist/components/PhotonOrder.d.ts.map +1 -0
- package/dist/components/PhotonOrder.js +274 -0
- package/dist/components/PhotonOrder.js.map +1 -0
- package/dist/components/PhotonPatient.d.ts +48 -0
- package/dist/components/PhotonPatient.d.ts.map +1 -0
- package/dist/components/PhotonPatient.js +85 -0
- package/dist/components/PhotonPatient.js.map +1 -0
- package/dist/components/PhotonPrescription.d.ts +32 -0
- package/dist/components/PhotonPrescription.d.ts.map +1 -0
- package/dist/components/PhotonPrescription.js +11 -0
- package/dist/components/PhotonPrescription.js.map +1 -0
- package/dist/components/ScreeningAlerts.d.ts +6 -0
- package/dist/components/ScreeningAlerts.d.ts.map +1 -0
- package/dist/components/ScreeningAlerts.js +11 -0
- package/dist/components/ScreeningAlerts.js.map +1 -0
- package/dist/components/SignedIn.d.ts +12 -0
- package/dist/components/SignedIn.d.ts.map +1 -0
- package/dist/components/SignedIn.js +84 -0
- package/dist/components/SignedIn.js.map +1 -0
- package/dist/components/activity.d.ts +7 -0
- package/dist/components/activity.d.ts.map +1 -0
- package/dist/components/activity.js +24 -0
- package/dist/components/activity.js.map +1 -0
- package/dist/components/display.d.ts +90 -0
- package/dist/components/display.d.ts.map +1 -0
- package/dist/components/display.js +223 -0
- package/dist/components/display.js.map +1 -0
- package/dist/components/flow.d.ts +35 -0
- package/dist/components/flow.d.ts.map +1 -0
- package/dist/components/flow.js +53 -0
- package/dist/components/flow.js.map +1 -0
- package/dist/components/format.d.ts +26 -0
- package/dist/components/format.d.ts.map +1 -0
- package/dist/components/format.js +61 -0
- package/dist/components/format.js.map +1 -0
- package/dist/components/index.d.ts +6 -0
- package/dist/components/index.d.ts.map +1 -0
- package/dist/components/index.js +6 -0
- package/dist/components/index.js.map +1 -0
- package/dist/components/open.d.ts +47 -0
- package/dist/components/open.d.ts.map +1 -0
- package/dist/components/open.js +73 -0
- package/dist/components/open.js.map +1 -0
- package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
- package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
- package/dist/components/order/DraftOrderPrompt.js +26 -0
- package/dist/components/order/DraftOrderPrompt.js.map +1 -0
- package/dist/components/patient/Benefits.d.ts +25 -0
- package/dist/components/patient/Benefits.d.ts.map +1 -0
- package/dist/components/patient/Benefits.js +48 -0
- package/dist/components/patient/Benefits.js.map +1 -0
- package/dist/components/patient/Clinical.d.ts +56 -0
- package/dist/components/patient/Clinical.d.ts.map +1 -0
- package/dist/components/patient/Clinical.js +118 -0
- package/dist/components/patient/Clinical.js.map +1 -0
- package/dist/components/patient/IntakeForm.d.ts +10 -0
- package/dist/components/patient/IntakeForm.d.ts.map +1 -0
- package/dist/components/patient/IntakeForm.js +333 -0
- package/dist/components/patient/IntakeForm.js.map +1 -0
- package/dist/components/patient/Summary.d.ts +48 -0
- package/dist/components/patient/Summary.d.ts.map +1 -0
- package/dist/components/patient/Summary.js +90 -0
- package/dist/components/patient/Summary.js.map +1 -0
- package/dist/components/patient/fields.d.ts +42 -0
- package/dist/components/patient/fields.d.ts.map +1 -0
- package/dist/components/patient/fields.js +72 -0
- package/dist/components/patient/fields.js.map +1 -0
- package/dist/components/patient/query.d.ts +37 -0
- package/dist/components/patient/query.d.ts.map +1 -0
- package/dist/components/patient/query.js +70 -0
- package/dist/components/patient/query.js.map +1 -0
- package/dist/components/prescription/PrescriptionCard.d.ts +45 -0
- package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionCard.js +179 -0
- package/dist/components/prescription/PrescriptionCard.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
- package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
- package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
- package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js +287 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
- package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
- package/dist/components/schemaErrors.d.ts +12 -0
- package/dist/components/schemaErrors.d.ts.map +1 -0
- package/dist/components/schemaErrors.js +24 -0
- package/dist/components/schemaErrors.js.map +1 -0
- package/dist/components/search.d.ts +154 -0
- package/dist/components/search.d.ts.map +1 -0
- package/dist/components/search.js +295 -0
- package/dist/components/search.js.map +1 -0
- package/dist/hooks/index.d.ts +5 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/useLatestCallback.d.ts +7 -0
- package/dist/hooks/useLatestCallback.d.ts.map +1 -0
- package/dist/hooks/useLatestCallback.js +14 -0
- package/dist/hooks/useLatestCallback.js.map +1 -0
- package/dist/hooks/useLive.d.ts +15 -0
- package/dist/hooks/useLive.d.ts.map +1 -0
- package/dist/hooks/useLive.js +6 -0
- package/dist/hooks/useLive.js.map +1 -0
- package/dist/hooks/useOnChange.d.ts +11 -0
- package/dist/hooks/useOnChange.d.ts.map +1 -0
- package/dist/hooks/useOnChange.js +28 -0
- package/dist/hooks/useOnChange.js.map +1 -0
- package/dist/hooks/useSession.d.ts +7 -0
- package/dist/hooks/useSession.d.ts.map +1 -0
- package/dist/hooks/useSession.js +10 -0
- package/dist/hooks/useSession.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/meta/version.d.ts +5 -0
- package/dist/meta/version.d.ts.map +1 -0
- package/dist/meta/version.js +5 -0
- package/dist/meta/version.js.map +1 -0
- package/dist/primitives/PhotonProvider.d.ts +60 -0
- package/dist/primitives/PhotonProvider.d.ts.map +1 -0
- package/dist/primitives/PhotonProvider.js +103 -0
- package/dist/primitives/PhotonProvider.js.map +1 -0
- package/dist/primitives/defaults.d.ts +3 -0
- package/dist/primitives/defaults.d.ts.map +1 -0
- package/dist/primitives/defaults.js +70 -0
- package/dist/primitives/defaults.js.map +1 -0
- package/dist/primitives/icons.d.ts +6 -0
- package/dist/primitives/icons.d.ts.map +1 -0
- package/dist/primitives/icons.js +6 -0
- package/dist/primitives/icons.js.map +1 -0
- package/dist/primitives/index.d.ts +5 -0
- package/dist/primitives/index.d.ts.map +1 -0
- package/dist/primitives/index.js +5 -0
- package/dist/primitives/index.js.map +1 -0
- package/dist/primitives/photonContext.d.ts +3 -0
- package/dist/primitives/photonContext.d.ts.map +1 -0
- package/dist/primitives/photonContext.js +3 -0
- package/dist/primitives/photonContext.js.map +1 -0
- package/dist/primitives/select.d.ts +7 -0
- package/dist/primitives/select.d.ts.map +1 -0
- package/dist/primitives/select.js +16 -0
- package/dist/primitives/select.js.map +1 -0
- package/dist/primitives/types.d.ts +288 -0
- package/dist/primitives/types.d.ts.map +1 -0
- package/dist/primitives/types.js +3 -0
- package/dist/primitives/types.js.map +1 -0
- package/dist/primitives/useProvidedPhoton.d.ts +8 -0
- package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
- package/dist/primitives/useProvidedPhoton.js +8 -0
- package/dist/primitives/useProvidedPhoton.js.map +1 -0
- package/dist/styles.css +653 -0
- package/dist/test-utils/contract.d.ts +17 -0
- package/dist/test-utils/contract.d.ts.map +1 -0
- package/dist/test-utils/contract.js +282 -0
- package/dist/test-utils/contract.js.map +1 -0
- package/package.json +76 -4
- package/src/adapters/index.ts +1 -0
- package/src/adapters/tailwind.tsx +572 -0
- package/src/analytics/PhotonAnalyticsProvider.test.tsx +191 -0
- package/src/analytics/PhotonAnalyticsProvider.tsx +96 -0
- package/src/analytics/fieldInteraction.test.tsx +184 -0
- package/src/analytics/fieldInteraction.tsx +148 -0
- package/src/analytics/tracker.test.ts +52 -0
- package/src/analytics/tracker.ts +42 -0
- package/src/analytics/viewed.ts +27 -0
- package/src/components/ChangeList.tsx +85 -0
- package/src/components/PhotonOrder.test.tsx +256 -0
- package/src/components/PhotonOrder.tsx +508 -0
- package/src/components/PhotonPatient.tsx +188 -0
- package/src/components/PhotonPrescription.test.tsx +116 -0
- package/src/components/PhotonPrescription.tsx +45 -0
- package/src/components/ScreeningAlerts.tsx +28 -0
- package/src/components/SignedIn.tsx +144 -0
- package/src/components/activity.ts +23 -0
- package/src/components/display.ts +278 -0
- package/src/components/flow.ts +67 -0
- package/src/components/format.ts +73 -0
- package/src/components/index.ts +5 -0
- package/src/components/open.ts +100 -0
- package/src/components/order/DraftOrderPrompt.test.tsx +80 -0
- package/src/components/order/DraftOrderPrompt.tsx +81 -0
- package/src/components/patient/Benefits.tsx +133 -0
- package/src/components/patient/Clinical.tsx +215 -0
- package/src/components/patient/IntakeForm.test.tsx +89 -0
- package/src/components/patient/IntakeForm.tsx +564 -0
- package/src/components/patient/Summary.test.tsx +106 -0
- package/src/components/patient/Summary.tsx +330 -0
- package/src/components/patient/fields.tsx +158 -0
- package/src/components/patient/query.ts +83 -0
- package/src/components/prescription/PrescriptionCard.test.tsx +85 -0
- package/src/components/prescription/PrescriptionCard.tsx +347 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +85 -0
- package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +209 -0
- package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +456 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
- package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
- package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +75 -0
- package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
- package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
- package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +699 -0
- package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
- package/src/components/schemaErrors.test.ts +49 -0
- package/src/components/schemaErrors.ts +33 -0
- package/src/components/search.tsx +377 -0
- package/src/hooks/index.ts +4 -0
- package/src/hooks/useLatestCallback.ts +16 -0
- package/src/hooks/useLive.ts +21 -0
- package/src/hooks/useOnChange.ts +34 -0
- package/src/hooks/useSession.ts +11 -0
- package/src/index.ts +21 -0
- package/src/meta/version.test.ts +10 -0
- package/src/meta/version.ts +4 -0
- package/src/primitives/PhotonProvider.tsx +168 -0
- package/src/primitives/defaults.tsx +432 -0
- package/src/primitives/icons.tsx +37 -0
- package/src/primitives/index.ts +4 -0
- package/src/primitives/photonContext.ts +4 -0
- package/src/primitives/select.ts +15 -0
- package/src/primitives/types.ts +288 -0
- package/src/primitives/useProvidedPhoton.ts +21 -0
- package/src/styles.css +653 -0
- package/src/test-utils/contract.tsx +453 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { render, waitFor } from "@testing-library/react";
|
|
3
|
+
import { StrictMode, type ReactNode } from "react";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
5
|
+
import { environmentUrls, type Photon } from "@photonhealth/client";
|
|
6
|
+
import { fakeNetworkApiClient, noMatch, photonOver } from "@photonhealth/client/testing";
|
|
7
|
+
import { PhotonAnalyticsProvider, PhotonOrder, PhotonPatient, PhotonProvider, PhotonPrescription } from "../index.ts";
|
|
8
|
+
import { reactPackage } from "../meta/version.ts";
|
|
9
|
+
import { typeIdentity } from "../../test/cards.fixtures.tsx";
|
|
10
|
+
import { recordAnalytics, type RecordedAnalytics, unmountAndRestoreFetch } from "../../test/analytics.fixtures.tsx";
|
|
11
|
+
|
|
12
|
+
const jwt = (claims: Record<string, unknown>) => `x.${btoa(JSON.stringify(claims)).replace(/=+$/, "")}.y`;
|
|
13
|
+
const token = jwt({ sub: "auth0|prescriber_1", org_id: "org_1" });
|
|
14
|
+
|
|
15
|
+
const photonWithHostToken = (): Photon => {
|
|
16
|
+
const { client } = fakeNetworkApiClient({
|
|
17
|
+
Ping: () => ({ ping: "pong" }),
|
|
18
|
+
Me: () => ({
|
|
19
|
+
me: {
|
|
20
|
+
__typename: "User",
|
|
21
|
+
id: "usr_prescriber_1",
|
|
22
|
+
name: { first: "Ada", last: "Lovelace" },
|
|
23
|
+
organization: { __typename: "Organization", id: "org_1", name: "Acme Clinic" },
|
|
24
|
+
permissions: [],
|
|
25
|
+
},
|
|
26
|
+
}),
|
|
27
|
+
SyncPatient: noMatch,
|
|
28
|
+
});
|
|
29
|
+
return photonOver(client, environmentUrls("boson"), {
|
|
30
|
+
analytics: { url: "https://analytics-api.boson.health", token: async () => token, clientName: "photon-rx" },
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
let fetchSpy: ReturnType<typeof vi.fn>;
|
|
35
|
+
const analyticsRequests = () =>
|
|
36
|
+
fetchSpy.mock.calls.map(([url, init]) => ({
|
|
37
|
+
url: url as string,
|
|
38
|
+
headers: (init as RequestInit).headers as Record<string, string>,
|
|
39
|
+
body: JSON.parse((init as RequestInit).body as string) as {
|
|
40
|
+
event: string;
|
|
41
|
+
userId: string;
|
|
42
|
+
properties: Record<string, unknown>;
|
|
43
|
+
},
|
|
44
|
+
raw: (init as RequestInit).body as string,
|
|
45
|
+
}));
|
|
46
|
+
const viewedRequests = () => analyticsRequests().filter((s) => s.body.event === "Prescribe Workflow Viewed");
|
|
47
|
+
|
|
48
|
+
let analytics: RecordedAnalytics;
|
|
49
|
+
beforeEach(() => {
|
|
50
|
+
analytics = recordAnalytics();
|
|
51
|
+
fetchSpy = analytics.fetchSpy;
|
|
52
|
+
});
|
|
53
|
+
afterEach(unmountAndRestoreFetch);
|
|
54
|
+
|
|
55
|
+
const inProvider = (ph: Photon, children: ReactNode, disableAnalytics?: boolean) => (
|
|
56
|
+
<PhotonProvider client={ph} disableAnalytics={disableAnalytics}>
|
|
57
|
+
{children}
|
|
58
|
+
</PhotonProvider>
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
describe("analytics: on by default", () => {
|
|
62
|
+
it("sends Prescribe Workflow Viewed once a card mounts, with the common properties, the token and the usr_ id", async () => {
|
|
63
|
+
render(inProvider(photonWithHostToken(), <PhotonOrder />));
|
|
64
|
+
await analytics.expectEventLog(["Prescribe Workflow Viewed", "Field Interaction patientSearch focus"]);
|
|
65
|
+
const [viewed] = viewedRequests();
|
|
66
|
+
expect(viewed!.url).toBe("https://analytics-api.boson.health/event");
|
|
67
|
+
expect(viewed!.headers).toMatchObject({
|
|
68
|
+
"x-photon-auth-token": token,
|
|
69
|
+
"x-photon-auth-token-type": "auth0",
|
|
70
|
+
});
|
|
71
|
+
expect(viewed!.body.userId).toBe("usr_prescriber_1");
|
|
72
|
+
expect(viewed!.body.properties).toMatchObject({
|
|
73
|
+
providerId: "usr_prescriber_1",
|
|
74
|
+
orgId: "org_1",
|
|
75
|
+
environment: "boson",
|
|
76
|
+
sessionId: expect.any(String),
|
|
77
|
+
integration: "react",
|
|
78
|
+
packageName: "@photonhealth/react",
|
|
79
|
+
packageVersion: reactPackage.version,
|
|
80
|
+
clientVersion: expect.any(String),
|
|
81
|
+
clientName: "photon-rx",
|
|
82
|
+
category: "elementViewed",
|
|
83
|
+
timestamp: expect.any(String),
|
|
84
|
+
card: "PhotonOrder",
|
|
85
|
+
hasPatientPrefill: false,
|
|
86
|
+
numTemplateIds: 0,
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("once per mounted workflow: StrictMode's double mount and PhotonOrder's own cards send no more", async () => {
|
|
91
|
+
render(<StrictMode>{inProvider(photonWithHostToken(), <PhotonOrder />)}</StrictMode>);
|
|
92
|
+
await analytics.expectEventLog(["Prescribe Workflow Viewed", "Field Interaction patientSearch focus"]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("each top-level card is its own workflow, with its own sessionId", async () => {
|
|
96
|
+
render(
|
|
97
|
+
inProvider(
|
|
98
|
+
photonWithHostToken(),
|
|
99
|
+
<>
|
|
100
|
+
<PhotonPatient />
|
|
101
|
+
<PhotonPrescription />
|
|
102
|
+
</>,
|
|
103
|
+
),
|
|
104
|
+
);
|
|
105
|
+
await analytics.expectEventLog([
|
|
106
|
+
"Field Interaction patientSearch focus",
|
|
107
|
+
"Prescribe Workflow Viewed",
|
|
108
|
+
"Prescribe Workflow Viewed",
|
|
109
|
+
]);
|
|
110
|
+
const [a, b] = viewedRequests().map((s) => s.body.properties);
|
|
111
|
+
expect([a!.card, b!.card]).toEqual(["PhotonPatient", "PhotonPrescription"]);
|
|
112
|
+
expect(a!.sessionId).not.toBe(b!.sessionId);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("counts what a card was given, never what it held", async () => {
|
|
116
|
+
const order = { patient: { id: "pat_1" }, prescriptions: { add: [{ templateId: "tmp_1" }, { id: "rx_1" }] } };
|
|
117
|
+
render(inProvider(photonWithHostToken(), <PhotonOrder order={order} fixed />));
|
|
118
|
+
await analytics.expectEventLog(["Prescribe Workflow Viewed"]);
|
|
119
|
+
expect(viewedRequests()[0]!.body.properties).toMatchObject({
|
|
120
|
+
hasOrderPrefill: true,
|
|
121
|
+
hasPatientPrefill: true,
|
|
122
|
+
numTemplateIds: 1,
|
|
123
|
+
numPrescriptionIds: 1,
|
|
124
|
+
fixed: true,
|
|
125
|
+
});
|
|
126
|
+
for (const { raw } of analyticsRequests()) expect(raw).not.toMatch(/pat_1|tmp_1|rx_1/);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("analytics: the host's settings", () => {
|
|
131
|
+
it("disableAnalytics sends nothing", async () => {
|
|
132
|
+
render(
|
|
133
|
+
<PhotonProvider client={photonWithHostToken()} disableAnalytics>
|
|
134
|
+
<PhotonOrder />
|
|
135
|
+
</PhotonProvider>,
|
|
136
|
+
);
|
|
137
|
+
await analytics.expectEventLog([]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("nested providers inherit it", async () => {
|
|
141
|
+
const ph = photonWithHostToken();
|
|
142
|
+
render(
|
|
143
|
+
<PhotonProvider client={ph} disableAnalytics>
|
|
144
|
+
<PhotonProvider>
|
|
145
|
+
<PhotonOrder />
|
|
146
|
+
</PhotonProvider>
|
|
147
|
+
</PhotonProvider>,
|
|
148
|
+
);
|
|
149
|
+
await analytics.expectEventLog([]);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("disableAnalytics={false} sends as usual", async () => {
|
|
153
|
+
render(inProvider(photonWithHostToken(), <PhotonOrder />, false));
|
|
154
|
+
await analytics.expectEventLog(["Prescribe Workflow Viewed", "Field Interaction patientSearch focus"]);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("PhotonAnalyticsProvider's properties go on every event, and win", async () => {
|
|
158
|
+
render(
|
|
159
|
+
inProvider(
|
|
160
|
+
photonWithHostToken(),
|
|
161
|
+
<PhotonAnalyticsProvider properties={{ integration: "web-app", hostFlag: true }}>
|
|
162
|
+
<PhotonOrder />
|
|
163
|
+
</PhotonAnalyticsProvider>,
|
|
164
|
+
),
|
|
165
|
+
);
|
|
166
|
+
await analytics.expectEventLog(["Prescribe Workflow Viewed", "Field Interaction patientSearch focus"]);
|
|
167
|
+
for (const { body } of analyticsRequests())
|
|
168
|
+
expect(body.properties, body.event).toMatchObject({ integration: "web-app", hostFlag: true });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("a failed send never reaches the prescriber", async () => {
|
|
172
|
+
fetchSpy.mockRejectedValue(new TypeError("Failed to fetch"));
|
|
173
|
+
const { findByLabelText } = render(inProvider(photonWithHostToken(), <PhotonPatient />));
|
|
174
|
+
await waitFor(() => expect(fetchSpy).toHaveBeenCalled());
|
|
175
|
+
expect(await findByLabelText("Find patient")).toBeTruthy();
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe("analytics: no PHI", () => {
|
|
180
|
+
it("nothing typed is ever sent", async () => {
|
|
181
|
+
render(inProvider(photonWithHostToken(), <PhotonPatient />));
|
|
182
|
+
await typeIdentity("Ada", "Zzyzxquist", "1990-01-01");
|
|
183
|
+
await analytics.expectEventLog([
|
|
184
|
+
"Field Interaction patientSearch focus",
|
|
185
|
+
"Prescribe Workflow Viewed",
|
|
186
|
+
"Field Interaction patientSearch change",
|
|
187
|
+
"Field Interaction patientSearch blur",
|
|
188
|
+
]);
|
|
189
|
+
for (const { raw } of analyticsRequests()) expect(raw).not.toMatch(/Zzyzxquist|1990-01-01/);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
|
|
2
|
+
import { PhotonContext } from "../primitives/photonContext.ts";
|
|
3
|
+
import { reactPackage } from "../meta/version.ts";
|
|
4
|
+
import { trackerFor, type AnalyticsProperties } from "./tracker.ts";
|
|
5
|
+
|
|
6
|
+
interface AnalyticsSettings {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
hostProperties: AnalyticsProperties;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const AnalyticsContext = createContext<AnalyticsSettings>({ enabled: true, hostProperties: {} });
|
|
12
|
+
|
|
13
|
+
export function PhotonAnalyticsProvider({
|
|
14
|
+
enabled,
|
|
15
|
+
properties,
|
|
16
|
+
children,
|
|
17
|
+
}: {
|
|
18
|
+
enabled?: boolean;
|
|
19
|
+
properties?: AnalyticsProperties;
|
|
20
|
+
children: ReactNode;
|
|
21
|
+
}) {
|
|
22
|
+
const outer = useContext(AnalyticsContext);
|
|
23
|
+
const merged = useMemo(
|
|
24
|
+
() => ({
|
|
25
|
+
enabled: enabled ?? outer.enabled,
|
|
26
|
+
hostProperties: properties ? { ...outer.hostProperties, ...properties } : outer.hostProperties,
|
|
27
|
+
}),
|
|
28
|
+
[outer, enabled, properties],
|
|
29
|
+
);
|
|
30
|
+
return <AnalyticsContext.Provider value={merged}>{children}</AnalyticsContext.Provider>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type Category = "elementViewed" | "fieldInteraction" | "ctaClicked";
|
|
34
|
+
|
|
35
|
+
interface Workflow {
|
|
36
|
+
sessionId: string;
|
|
37
|
+
card: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const WorkflowContext = createContext<Workflow | null>(null);
|
|
41
|
+
|
|
42
|
+
const sessionsWithViewedSent = new Set<string>(); // StrictMode mounts each workflow twice
|
|
43
|
+
|
|
44
|
+
const newSessionId = () =>
|
|
45
|
+
globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
46
|
+
|
|
47
|
+
export function AnalyticsWorkflow({
|
|
48
|
+
card,
|
|
49
|
+
viewedProperties,
|
|
50
|
+
children,
|
|
51
|
+
}: {
|
|
52
|
+
card: string;
|
|
53
|
+
viewedProperties: AnalyticsProperties;
|
|
54
|
+
children: ReactNode;
|
|
55
|
+
}) {
|
|
56
|
+
const outerWorkflow = useContext(WorkflowContext);
|
|
57
|
+
const [workflow] = useState<Workflow>(() => ({ sessionId: newSessionId(), card }));
|
|
58
|
+
const track = useTrackIn(outerWorkflow ?? workflow);
|
|
59
|
+
const viewedPropertiesKey = JSON.stringify(viewedProperties);
|
|
60
|
+
useEffect(() => {
|
|
61
|
+
if (outerWorkflow || sessionsWithViewedSent.has(workflow.sessionId)) return;
|
|
62
|
+
sessionsWithViewedSent.add(workflow.sessionId);
|
|
63
|
+
track("Prescribe Workflow Viewed", "elementViewed", { card, ...JSON.parse(viewedPropertiesKey) });
|
|
64
|
+
}, [outerWorkflow, workflow, track, card, viewedPropertiesKey]);
|
|
65
|
+
if (outerWorkflow) return <>{children}</>;
|
|
66
|
+
return <WorkflowContext.Provider value={workflow}>{children}</WorkflowContext.Provider>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function useTrack() {
|
|
70
|
+
return useTrackIn(useContext(WorkflowContext));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function useTrackIn(workflow: Workflow | null) {
|
|
74
|
+
const ph = useContext(PhotonContext);
|
|
75
|
+
const settings = useContext(AnalyticsContext);
|
|
76
|
+
return useMemo(
|
|
77
|
+
() =>
|
|
78
|
+
(event: string, category: Category, properties: AnalyticsProperties = {}) => {
|
|
79
|
+
if (!ph || !settings.enabled) return;
|
|
80
|
+
trackerFor(ph).track({
|
|
81
|
+
event,
|
|
82
|
+
properties: {
|
|
83
|
+
sessionId: workflow?.sessionId ?? null,
|
|
84
|
+
integration: "react",
|
|
85
|
+
packageName: reactPackage.name,
|
|
86
|
+
packageVersion: reactPackage.version,
|
|
87
|
+
category,
|
|
88
|
+
timestamp: new Date().toISOString(),
|
|
89
|
+
...properties,
|
|
90
|
+
...settings.hostProperties,
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
[ph, settings, workflow],
|
|
95
|
+
);
|
|
96
|
+
}
|
|
@@ -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
|
+
});
|