@terreno/ui 57.21.0 → 58.0.0-beta.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 (221) hide show
  1. package/.ai/guidelines/core.md +1 -1
  2. package/CHANGELOG.md +89 -0
  3. package/dist/ActionSheet.d.ts +9 -9
  4. package/dist/ActionSheet.d.ts.map +1 -1
  5. package/dist/ActionSheet.js +11 -4
  6. package/dist/ActionSheet.js.map +1 -1
  7. package/dist/AnnouncementNavigator.d.ts +7 -1
  8. package/dist/AnnouncementNavigator.d.ts.map +1 -1
  9. package/dist/AnnouncementNavigator.js +15 -16
  10. package/dist/AnnouncementNavigator.js.map +1 -1
  11. package/dist/Avatar.d.ts.map +1 -1
  12. package/dist/Avatar.js +1 -1
  13. package/dist/Avatar.js.map +1 -1
  14. package/dist/Box.d.ts.map +1 -1
  15. package/dist/Box.js +3 -1
  16. package/dist/Box.js.map +1 -1
  17. package/dist/Common.d.ts +16 -12
  18. package/dist/Common.d.ts.map +1 -1
  19. package/dist/Common.js.map +1 -1
  20. package/dist/ConsentFormScreen.d.ts.map +1 -1
  21. package/dist/ConsentFormScreen.js.map +1 -1
  22. package/dist/ConsentNavigator.d.ts +5 -3
  23. package/dist/ConsentNavigator.d.ts.map +1 -1
  24. package/dist/ConsentNavigator.js +4 -4
  25. package/dist/ConsentNavigator.js.map +1 -1
  26. package/dist/CustomSelectField.js.map +1 -1
  27. package/dist/DataTable.d.ts.map +1 -1
  28. package/dist/DataTable.js +37 -12
  29. package/dist/DataTable.js.map +1 -1
  30. package/dist/DateTimeField.js.map +1 -1
  31. package/dist/DropdownPanel.d.ts +0 -5
  32. package/dist/DropdownPanel.d.ts.map +1 -1
  33. package/dist/DropdownPanel.js +0 -5
  34. package/dist/DropdownPanel.js.map +1 -1
  35. package/dist/FilterAccordion.d.ts.map +1 -1
  36. package/dist/FilterAccordion.js.map +1 -1
  37. package/dist/FilterBoolean.d.ts.map +1 -1
  38. package/dist/FilterBoolean.js.map +1 -1
  39. package/dist/FilterSelectMenu.js +1 -1
  40. package/dist/FilterSelectMenu.js.map +1 -1
  41. package/dist/GPTChat.d.ts.map +1 -1
  42. package/dist/GPTChat.js.map +1 -1
  43. package/dist/Heading.d.ts.map +1 -1
  44. package/dist/Heading.js +6 -12
  45. package/dist/Heading.js.map +1 -1
  46. package/dist/HeightField.d.ts.map +1 -1
  47. package/dist/HeightField.js +1 -1
  48. package/dist/HeightField.js.map +1 -1
  49. package/dist/Hyperlink.d.ts.map +1 -1
  50. package/dist/Hyperlink.js +6 -1
  51. package/dist/Hyperlink.js.map +1 -1
  52. package/dist/Image.d.ts +1 -1
  53. package/dist/MarkdownEditorField.d.ts.map +1 -1
  54. package/dist/MarkdownEditorField.js +1 -1
  55. package/dist/MarkdownEditorField.js.map +1 -1
  56. package/dist/OfflineBanner.d.ts +3 -2
  57. package/dist/OfflineBanner.d.ts.map +1 -1
  58. package/dist/OfflineBanner.js +3 -2
  59. package/dist/OfflineBanner.js.map +1 -1
  60. package/dist/OtpField.d.ts.map +1 -1
  61. package/dist/OtpField.js +6 -3
  62. package/dist/OtpField.js.map +1 -1
  63. package/dist/PickerSelect.d.ts +4 -4
  64. package/dist/PickerSelect.d.ts.map +1 -1
  65. package/dist/PickerSelect.js.map +1 -1
  66. package/dist/ProvisionalConsentSigner.d.ts +3 -2
  67. package/dist/ProvisionalConsentSigner.d.ts.map +1 -1
  68. package/dist/ProvisionalConsentSigner.js +2 -2
  69. package/dist/ProvisionalConsentSigner.js.map +1 -1
  70. package/dist/SidebarNavigation.js +2 -2
  71. package/dist/SidebarNavigation.js.map +1 -1
  72. package/dist/SidebarNavigation.native.js +2 -2
  73. package/dist/SidebarNavigation.native.js.map +1 -1
  74. package/dist/Skeleton.js.map +1 -1
  75. package/dist/Text.d.ts.map +1 -1
  76. package/dist/Text.js +27 -50
  77. package/dist/Text.js.map +1 -1
  78. package/dist/TextField.d.ts.map +1 -1
  79. package/dist/TextField.js.map +1 -1
  80. package/dist/ThumbsUpDownFeedback.d.ts.map +1 -1
  81. package/dist/ThumbsUpDownFeedback.js.map +1 -1
  82. package/dist/ToastNotifications.d.ts.map +1 -1
  83. package/dist/ToastNotifications.js.map +1 -1
  84. package/dist/Tooltip.d.ts.map +1 -1
  85. package/dist/Tooltip.js.map +1 -1
  86. package/dist/Unifier.d.ts +1 -1
  87. package/dist/WebAddressAutocomplete.js.map +1 -1
  88. package/dist/WebDropdownMenu.d.ts +3 -3
  89. package/dist/WebDropdownMenu.d.ts.map +1 -1
  90. package/dist/WebDropdownMenu.js +1 -1
  91. package/dist/WebDropdownMenu.js.map +1 -1
  92. package/dist/announcementPlatform.d.ts +5 -0
  93. package/dist/announcementPlatform.d.ts.map +1 -1
  94. package/dist/announcementPlatform.js +9 -0
  95. package/dist/announcementPlatform.js.map +1 -1
  96. package/dist/asks/AskCard.d.ts +2 -2
  97. package/dist/asks/AskCard.d.ts.map +1 -1
  98. package/dist/dataTableColumnWidths.d.ts +76 -0
  99. package/dist/dataTableColumnWidths.d.ts.map +1 -0
  100. package/dist/dataTableColumnWidths.js +181 -0
  101. package/dist/dataTableColumnWidths.js.map +1 -0
  102. package/dist/index.d.ts +2 -1
  103. package/dist/index.d.ts.map +1 -1
  104. package/dist/index.js.map +1 -1
  105. package/dist/login/LoginScreen.js.map +1 -1
  106. package/dist/requestClient.d.ts +71 -0
  107. package/dist/requestClient.d.ts.map +1 -0
  108. package/dist/requestClient.js +139 -0
  109. package/dist/requestClient.js.map +1 -0
  110. package/dist/security/PasswordCard.d.ts.map +1 -1
  111. package/dist/security/PasswordCard.js.map +1 -1
  112. package/dist/security/TwoFactorSettingsCard.d.ts.map +1 -1
  113. package/dist/security/TwoFactorSettingsCard.js +1 -1
  114. package/dist/security/TwoFactorSettingsCard.js.map +1 -1
  115. package/dist/signUp/SignUpScreen.js.map +1 -1
  116. package/dist/table/Table.d.ts.map +1 -1
  117. package/dist/table/Table.js.map +1 -1
  118. package/dist/table/TableTitle.d.ts.map +1 -1
  119. package/dist/table/TableTitle.js +2 -1
  120. package/dist/table/TableTitle.js.map +1 -1
  121. package/dist/textFontSizes.d.ts +12 -0
  122. package/dist/textFontSizes.d.ts.map +1 -0
  123. package/dist/textFontSizes.js +21 -0
  124. package/dist/textFontSizes.js.map +1 -0
  125. package/dist/useAcknowledgeAnnouncement.d.ts +8 -63
  126. package/dist/useAcknowledgeAnnouncement.d.ts.map +1 -1
  127. package/dist/useAcknowledgeAnnouncement.js +31 -80
  128. package/dist/useAcknowledgeAnnouncement.js.map +1 -1
  129. package/dist/useAnnouncements.d.ts +14 -47
  130. package/dist/useAnnouncements.d.ts.map +1 -1
  131. package/dist/useAnnouncements.js +30 -57
  132. package/dist/useAnnouncements.js.map +1 -1
  133. package/dist/useConsentForms.d.ts +6 -38
  134. package/dist/useConsentForms.d.ts.map +1 -1
  135. package/dist/useConsentForms.js +25 -48
  136. package/dist/useConsentForms.js.map +1 -1
  137. package/dist/useProvisionalConsent.d.ts +7 -58
  138. package/dist/useProvisionalConsent.d.ts.map +1 -1
  139. package/dist/useProvisionalConsent.js +57 -67
  140. package/dist/useProvisionalConsent.js.map +1 -1
  141. package/dist/useSubmitConsent.d.ts +9 -39
  142. package/dist/useSubmitConsent.d.ts.map +1 -1
  143. package/dist/useSubmitConsent.js +10 -39
  144. package/dist/useSubmitConsent.js.map +1 -1
  145. package/package.json +38 -38
  146. package/src/ActionSheet.test.tsx +4 -4
  147. package/src/ActionSheet.tsx +18 -5
  148. package/src/AnnouncementNavigator.test.tsx +215 -315
  149. package/src/AnnouncementNavigator.tsx +25 -20
  150. package/src/Avatar.tsx +2 -9
  151. package/src/Box.test.tsx +3 -3
  152. package/src/Box.tsx +4 -2
  153. package/src/Common.ts +19 -15
  154. package/src/ConsentFormScreen.tsx +2 -1
  155. package/src/ConsentNavigator.test.tsx +166 -242
  156. package/src/ConsentNavigator.tsx +9 -13
  157. package/src/CustomSelectField.tsx +3 -3
  158. package/src/DataTable.test.tsx +69 -1
  159. package/src/DataTable.tsx +72 -19
  160. package/src/DateTimeField.tsx +4 -4
  161. package/src/DropdownPanel.tsx +0 -6
  162. package/src/FilterAccordion.tsx +3 -3
  163. package/src/FilterBoolean.tsx +3 -3
  164. package/src/FilterSelectMenu.tsx +1 -1
  165. package/src/GPTChat.tsx +10 -9
  166. package/src/Heading.tsx +7 -14
  167. package/src/HeightField.tsx +9 -2
  168. package/src/Hyperlink.tsx +6 -3
  169. package/src/Link.test.tsx +2 -2
  170. package/src/MarkdownEditorField.tsx +10 -2
  171. package/src/MarkdownView.test.tsx +10 -6
  172. package/src/Modal.test.tsx +3 -1
  173. package/src/ModalSheet.test.tsx +6 -6
  174. package/src/OfflineBanner.tsx +3 -2
  175. package/src/OtpField.test.tsx +44 -0
  176. package/src/OtpField.tsx +8 -4
  177. package/src/PickerSelect.tsx +3 -2
  178. package/src/ProvisionalConsentSigner.test.tsx +140 -113
  179. package/src/ProvisionalConsentSigner.tsx +5 -4
  180. package/src/SidebarNavigation.native.tsx +2 -2
  181. package/src/SidebarNavigation.tsx +2 -2
  182. package/src/Skeleton.tsx +1 -1
  183. package/src/TapToEdit.test.tsx +2 -2
  184. package/src/Text.test.tsx +1 -1
  185. package/src/Text.tsx +25 -51
  186. package/src/TextField.tsx +2 -1
  187. package/src/ThumbsUpDownFeedback.tsx +3 -3
  188. package/src/ToastNotifications.tsx +3 -2
  189. package/src/ToastNotifications.webModal.test.tsx +4 -1
  190. package/src/Tooltip.tsx +2 -1
  191. package/src/UserInactivity.test.tsx +2 -3
  192. package/src/WebAddressAutocomplete.tsx +3 -3
  193. package/src/WebDropdownMenu.tsx +16 -5
  194. package/src/__snapshots__/DataTable.test.tsx.snap +13 -0
  195. package/src/announcementPlatform.ts +10 -0
  196. package/src/asks/AskCard.test.tsx +14 -12
  197. package/src/asks/AskCard.tsx +2 -2
  198. package/src/bunSetup.ts +42 -0
  199. package/src/dataTableColumnWidths.test.ts +266 -0
  200. package/src/dataTableColumnWidths.ts +272 -0
  201. package/src/index.tsx +9 -2
  202. package/src/login/LoginScreen.tsx +2 -2
  203. package/src/requestClient.test.ts +288 -0
  204. package/src/requestClient.ts +228 -0
  205. package/src/security/PasswordCard.tsx +7 -5
  206. package/src/security/TwoFactorSettingsCard.tsx +10 -3
  207. package/src/signUp/SignUpScreen.tsx +2 -2
  208. package/src/table/Table.tsx +1 -2
  209. package/src/table/TableTitle.tsx +2 -1
  210. package/src/test-utils.tsx +76 -0
  211. package/src/textFontSizes.ts +31 -0
  212. package/src/useAcknowledgeAnnouncement.test.ts +101 -193
  213. package/src/useAcknowledgeAnnouncement.ts +69 -147
  214. package/src/useAnnouncements.test.ts +122 -186
  215. package/src/useAnnouncements.ts +49 -105
  216. package/src/useConsentForms.test.ts +59 -112
  217. package/src/useConsentForms.ts +37 -87
  218. package/src/useProvisionalConsent.test.ts +74 -150
  219. package/src/useProvisionalConsent.ts +79 -125
  220. package/src/useSubmitConsent.test.ts +59 -85
  221. package/src/useSubmitConsent.ts +22 -77
@@ -7,6 +7,7 @@ import type {ReactTestInstance, ReactTestRendererJSON} from "react-test-renderer
7
7
 
8
8
  import type {CustomIconProps, IconRegistryMap} from "./Common";
9
9
  import {IconRegistryProvider} from "./IconRegistry";
10
+ import type {TerrenoRequestArgs, TerrenoRequestClient} from "./requestClient";
10
11
  import {ThemeProvider} from "./Theme";
11
12
 
12
13
  // Register a custom icon name for tests. test-utils.tsx is excluded from the
@@ -66,6 +67,81 @@ export const teardownComponentTest = () => {
66
67
  // No-op for compatibility
67
68
  };
68
69
 
70
+ /** Handler for one fake route; return the response payload or throw to fail the request. */
71
+ export type FakeRouteHandler = (
72
+ args: TerrenoRequestArgs,
73
+ pathParams: Record<string, string>
74
+ ) => unknown | Promise<unknown>;
75
+
76
+ export interface FakeRequestClient {
77
+ client: TerrenoRequestClient;
78
+ /** Every request in call order. */
79
+ calls: TerrenoRequestArgs[];
80
+ /** Requests whose method and URL match `route` (for example `"POST /consents/respond"`). */
81
+ callsTo: (route: string) => TerrenoRequestArgs[];
82
+ }
83
+
84
+ /** Error shaped like a failed request: carries the HTTP `status`. */
85
+ export const fakeHttpError = (status: number, title = `HTTP ${status}`): Error =>
86
+ Object.assign(new Error(title), {data: {title}, status});
87
+
88
+ const routePattern = (route: string): {method: string; regex: RegExp; names: string[]} => {
89
+ const [method, path] = route.split(" ");
90
+ const names: string[] = [];
91
+ const source = path
92
+ .split("/")
93
+ .map((segment) => {
94
+ if (segment.startsWith(":")) {
95
+ names.push(segment.slice(1));
96
+ return "([^/]+)";
97
+ }
98
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
99
+ })
100
+ .join("/");
101
+ return {method: method.toUpperCase(), names, regex: new RegExp(`^${source}$`)};
102
+ };
103
+
104
+ const matchRoute = (
105
+ route: string,
106
+ args: TerrenoRequestArgs
107
+ ): Record<string, string> | undefined => {
108
+ const {method, names, regex} = routePattern(route);
109
+ if ((args.method ?? "GET").toUpperCase() !== method) {
110
+ return undefined;
111
+ }
112
+ const match = regex.exec(args.url);
113
+ if (!match) {
114
+ return undefined;
115
+ }
116
+ return Object.fromEntries(names.map((name, index) => [name, match[index + 1] ?? ""]));
117
+ };
118
+
119
+ /**
120
+ * In-memory {@link TerrenoRequestClient}. Routes are `"METHOD /path/:param"` keys; a request
121
+ * with no matching route rejects with a 404 error.
122
+ */
123
+ export const createFakeRequestClient = (
124
+ routes: Record<string, FakeRouteHandler>
125
+ ): FakeRequestClient => {
126
+ const calls: TerrenoRequestArgs[] = [];
127
+ const request = async <T,>(args: TerrenoRequestArgs): Promise<T> => {
128
+ calls.push(args);
129
+ for (const [route, handler] of Object.entries(routes)) {
130
+ const pathParams = matchRoute(route, args);
131
+ if (pathParams) {
132
+ return (await handler(args, pathParams)) as T;
133
+ }
134
+ }
135
+ throw fakeHttpError(404, `No fake route for ${args.method ?? "GET"} ${args.url}`);
136
+ };
137
+ return {
138
+ calls,
139
+ callsTo: (route: string): TerrenoRequestArgs[] =>
140
+ calls.filter((args) => matchRoute(route, args) !== undefined),
141
+ client: {request},
142
+ };
143
+ };
144
+
69
145
  /**
70
146
  * Host element name (e.g. "View") of a test-renderer node. The react-native mock in bunSetup.ts
71
147
  * renders string host types that React's DOM-only JSX typings do not list, so read it as a string.
@@ -0,0 +1,31 @@
1
+ import {Platform} from "react-native";
2
+
3
+ import type {TextSize} from "./Common";
4
+
5
+ interface TextFontSizeAndWeight {
6
+ size: number;
7
+ weight: "regular" | "medium";
8
+ }
9
+
10
+ const fontSizeAndWeightWeb: Record<TextSize, TextFontSizeAndWeight> = {
11
+ "2xl": {size: 48, weight: "medium"},
12
+ lg: {size: 18, weight: "medium"},
13
+ md: {size: 16, weight: "regular"},
14
+ sm: {size: 12, weight: "regular"},
15
+ xl: {size: 20, weight: "medium"},
16
+ };
17
+
18
+ const fontSizeAndWeightMobile: Record<TextSize, TextFontSizeAndWeight> = {
19
+ "2xl": {size: 40, weight: "medium"},
20
+ lg: {size: 16, weight: "medium"},
21
+ md: {size: 14, weight: "regular"},
22
+ sm: {size: 10, weight: "regular"},
23
+ xl: {size: 18, weight: "medium"},
24
+ };
25
+
26
+ /**
27
+ * Font size and weight for each `Text` size on the current platform. Shared by `Text` and by
28
+ * anything that has to predict how wide `Text` will render, such as DataTable auto widths.
29
+ */
30
+ export const textFontSizes: Record<TextSize, TextFontSizeAndWeight> =
31
+ Platform.OS === "web" ? fontSizeAndWeightWeb : fontSizeAndWeightMobile;
@@ -1,223 +1,131 @@
1
- import {describe, expect, it, mock} from "bun:test";
2
- import {renderHook} from "@testing-library/react-native";
3
- import {assert} from "chai";
1
+ import {afterEach, describe, expect, it} from "bun:test";
2
+ import {act, renderHook} from "@testing-library/react-native";
3
+ import Constants from "expo-constants";
4
4
  import {Platform} from "react-native";
5
5
 
6
- import {useAcknowledgeAnnouncement} from "./useAcknowledgeAnnouncement";
7
-
8
- type AcknowledgeApi = Parameters<typeof useAcknowledgeAnnouncement>[0];
6
+ // Drive the preload's shared expo-constants mock (src/bunSetup.ts) instead of replacing the
7
+ // module: Bun's mock.module is process-global, so a second registration leaks into siblings.
8
+ const constantsState = Constants as unknown as {
9
+ expoConfig: {extra: {buildNumber?: number | string}};
10
+ };
9
11
 
10
- interface MockMutationDef {
11
- query: (args: {announcementId: string; platform?: string}) => {
12
- body?: {action?: string; platform?: string};
13
- method: string;
14
- url: string;
15
- };
16
- }
12
+ import {createFakeRequestClient, fakeHttpError} from "./test-utils";
13
+ import {useAcknowledgeAnnouncement} from "./useAcknowledgeAnnouncement";
17
14
 
18
- interface MockInjectOpts {
19
- endpoints: (build: {mutation: (def: MockMutationDef) => string}) => Record<string, unknown>;
20
- }
15
+ const buildClient = (): ReturnType<typeof createFakeRequestClient> =>
16
+ createFakeRequestClient({
17
+ "POST /api/announcements/:id/acknowledge": () => ({acknowledged: true}),
18
+ "POST /api/announcements/:id/click": () => ({recorded: true}),
19
+ "POST /api/announcements/:id/impression": () => ({recorded: true}),
20
+ });
21
21
 
22
22
  describe("useAcknowledgeAnnouncement", () => {
23
- const buildApi = () => {
24
- const acknowledgeUnwrap = mock(async () => ({acknowledged: true}));
25
- const impressionUnwrap = mock(async () => ({recorded: true}));
26
- const clickUnwrap = mock(async () => ({recorded: true}));
27
- const acknowledgeMutation = mock(() => ({unwrap: acknowledgeUnwrap}));
28
- const impressionMutation = mock(() => ({unwrap: impressionUnwrap}));
29
- const clickMutation = mock(() => ({unwrap: clickUnwrap}));
30
- let clickQueryDef: MockMutationDef | undefined;
31
- let acknowledgeQueryDef: MockMutationDef | undefined;
32
- const api = {
33
- enhanceEndpoints: mock(() => ({
34
- injectEndpoints: mock((opts: MockInjectOpts) => {
35
- const build = {
36
- mutation: mock((def: MockMutationDef) => {
37
- const result = def.query({announcementId: "a1", platform: "ios"});
38
- expect(result.method).toBe("POST");
39
- expect(result.url).toContain("/announcements/a1/");
40
- if (result.url.includes("/click")) {
41
- clickQueryDef = def;
42
- }
43
- if (result.url.includes("/acknowledge")) {
44
- acknowledgeQueryDef = def;
45
- }
46
- return "mutation";
47
- }),
48
- };
49
- opts.endpoints(build);
50
- return {
51
- useAcknowledgeAnnouncementMutation: () => [
52
- acknowledgeMutation,
53
- {error: undefined, isLoading: false},
54
- ],
55
- useRecordAnnouncementClickMutation: () => [
56
- clickMutation,
57
- {error: undefined, isLoading: false},
58
- ],
59
- useRecordAnnouncementImpressionMutation: () => [
60
- impressionMutation,
61
- {error: undefined, isLoading: false},
62
- ],
63
- };
64
- }),
65
- })),
66
- };
67
- return {
68
- acknowledgeMutation,
69
- acknowledgeQueryDef: () => acknowledgeQueryDef,
70
- api,
71
- clickMutation,
72
- clickQueryDef: () => clickQueryDef,
73
- impressionMutation,
74
- };
75
- };
23
+ const originalOS = Platform.OS;
24
+
25
+ afterEach(() => {
26
+ constantsState.expoConfig.extra.buildNumber = undefined;
27
+ Platform.OS = originalOS;
28
+ });
76
29
 
77
30
  it("acknowledges and records impressions", async () => {
78
- const {api, acknowledgeMutation, impressionMutation} = buildApi();
79
- const {result} = renderHook(() =>
80
- useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi, "/api")
81
- );
82
- await result.current.acknowledge("announcement-1");
83
- await result.current.recordImpression("announcement-1");
84
- expect(acknowledgeMutation).toHaveBeenCalled();
85
- expect(impressionMutation).toHaveBeenCalled();
31
+ const {client, callsTo} = buildClient();
32
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client, "/api"));
33
+ await act(async () => {
34
+ await result.current.acknowledge("announcement-1");
35
+ await result.current.recordImpression("announcement-1");
36
+ });
37
+ expect(callsTo("POST /api/announcements/announcement-1/acknowledge")).toHaveLength(1);
38
+ expect(callsTo("POST /api/announcements/announcement-1/impression")).toHaveLength(1);
39
+ expect(result.current.isSubmitting).toBe(false);
86
40
  });
87
41
 
88
42
  it("uses the client platform for impressions", async () => {
89
- const originalOS = Platform.OS;
90
43
  Platform.OS = "ios";
91
- const {api, impressionMutation} = buildApi();
92
- const {result} = renderHook(() => useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi));
93
- await result.current.recordImpression("announcement-1");
94
- expect(impressionMutation).toHaveBeenCalledWith({
95
- announcementId: "announcement-1",
96
- platform: "ios",
44
+ const {client, calls} = buildClient();
45
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client, "/api"));
46
+ await act(async () => {
47
+ await result.current.recordImpression("announcement-1");
97
48
  });
98
- Platform.OS = originalOS;
49
+ expect(calls).toEqual([
50
+ {
51
+ body: {platform: "ios"},
52
+ method: "POST",
53
+ url: "/api/announcements/announcement-1/impression",
54
+ },
55
+ ]);
99
56
  });
100
57
 
101
58
  it("records primary-action clicks with platform and build version in the query", async () => {
102
- const constantsState = {
103
- expoConfig: {
104
- extra: {
105
- buildNumber: 42,
106
- },
107
- },
108
- };
109
- mock.module("expo-constants", () => ({
110
- default: constantsState,
111
- }));
112
-
113
- const originalOS = Platform.OS;
59
+ constantsState.expoConfig.extra.buildNumber = 42;
114
60
  Platform.OS = "web";
115
-
116
- const {api, clickMutation, clickQueryDef} = buildApi();
117
- const {result} = renderHook(() =>
118
- useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi, "/api")
119
- );
120
-
121
- await result.current.recordClick("announcement-42");
122
-
123
- assert.strictEqual(clickMutation.mock.calls.length, 1);
124
- assert.deepEqual(clickMutation.mock.calls[0], [{announcementId: "announcement-42"}]);
125
-
126
- const clickDef = clickQueryDef();
127
- assert.ok(clickDef);
128
- const queryResult = clickDef.query({announcementId: "announcement-42"});
129
- assert.strictEqual(queryResult.method, "POST");
130
- assert.strictEqual(
131
- queryResult.url,
132
- "/api/announcements/announcement-42/click?platform=web&version=42"
133
- );
134
- assert.deepEqual(queryResult.body, {action: "primaryAction", platform: "web"});
135
-
136
- Platform.OS = originalOS;
137
- mock.module("expo-constants", () => ({
138
- default: {expoConfig: {extra: {buildNumber: undefined}}},
139
- }));
61
+ const {client, calls} = buildClient();
62
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client, "/api"));
63
+ await act(async () => {
64
+ await result.current.recordClick("announcement-42");
65
+ });
66
+ expect(calls).toEqual([
67
+ {
68
+ body: {action: "primaryAction", platform: "web"},
69
+ method: "POST",
70
+ params: {platform: "web", version: 42},
71
+ url: "/api/announcements/announcement-42/click",
72
+ },
73
+ ]);
140
74
  });
141
75
 
142
- it("omits version from click URL when build number is not finite", async () => {
143
- mock.module("expo-constants", () => ({
144
- default: {expoConfig: {extra: {buildNumber: undefined}}},
145
- }));
146
-
147
- const originalOS = Platform.OS;
76
+ it("omits version from click params when build number is not finite", async () => {
148
77
  Platform.OS = "android";
149
-
150
- const {api, clickQueryDef} = buildApi();
151
- renderHook(() => useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi, "/api"));
152
-
153
- const clickDef = clickQueryDef();
154
- assert.ok(clickDef);
155
- const queryResult = clickDef.query({announcementId: "announcement-1"});
156
- assert.strictEqual(queryResult.url, "/api/announcements/announcement-1/click?platform=android");
157
- assert.deepEqual(queryResult.body, {action: "primaryAction", platform: "android"});
158
-
159
- Platform.OS = originalOS;
78
+ const {client, calls} = buildClient();
79
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client, "/api"));
80
+ await act(async () => {
81
+ await result.current.recordClick("announcement-1");
82
+ });
83
+ expect(calls[0]?.params).toEqual({platform: "android"});
84
+ expect(calls[0]?.body).toEqual({action: "primaryAction", platform: "android"});
160
85
  });
161
86
 
162
87
  it("posts acknowledge with platform and build version in the query", async () => {
163
- const constantsState = {
164
- expoConfig: {
165
- extra: {
166
- buildNumber: 42,
167
- },
168
- },
169
- };
170
- mock.module("expo-constants", () => ({
171
- default: constantsState,
172
- }));
173
-
174
- const originalOS = Platform.OS;
88
+ constantsState.expoConfig.extra.buildNumber = 42;
175
89
  Platform.OS = "ios";
176
-
177
- const {api, acknowledgeMutation, acknowledgeQueryDef} = buildApi();
178
- const {result} = renderHook(() =>
179
- useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi, "/api")
180
- );
181
-
182
- await result.current.acknowledge("announcement-42");
183
-
184
- assert.strictEqual(acknowledgeMutation.mock.calls.length, 1);
185
- assert.deepEqual(acknowledgeMutation.mock.calls[0], [{announcementId: "announcement-42"}]);
186
-
187
- const acknowledgeDef = acknowledgeQueryDef();
188
- assert.ok(acknowledgeDef);
189
- const queryResult = acknowledgeDef.query({announcementId: "announcement-42"});
190
- assert.strictEqual(queryResult.method, "POST");
191
- assert.strictEqual(
192
- queryResult.url,
193
- "/api/announcements/announcement-42/acknowledge?platform=ios&version=42"
194
- );
195
-
196
- Platform.OS = originalOS;
197
- mock.module("expo-constants", () => ({
198
- default: {expoConfig: {extra: {buildNumber: undefined}}},
199
- }));
90
+ const {client, calls} = buildClient();
91
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client, "/api"));
92
+ await act(async () => {
93
+ await result.current.acknowledge("announcement-42");
94
+ });
95
+ expect(calls).toEqual([
96
+ {
97
+ method: "POST",
98
+ params: {platform: "ios", version: 42},
99
+ url: "/api/announcements/announcement-42/acknowledge",
100
+ },
101
+ ]);
200
102
  });
201
103
 
202
- it("omits version from acknowledge URL when build number is not finite", async () => {
203
- mock.module("expo-constants", () => ({
204
- default: {expoConfig: {extra: {buildNumber: undefined}}},
205
- }));
206
-
207
- const originalOS = Platform.OS;
104
+ it("omits version from acknowledge params when build number is not finite", async () => {
105
+ constantsState.expoConfig.extra.buildNumber = "invalid";
208
106
  Platform.OS = "web";
107
+ const {client, calls} = createFakeRequestClient({
108
+ "POST /announcements/:id/acknowledge": () => ({acknowledged: true}),
109
+ });
110
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client));
111
+ await act(async () => {
112
+ await result.current.acknowledge("announcement-1");
113
+ });
114
+ expect(calls[0]?.url).toBe("/announcements/announcement-1/acknowledge");
115
+ expect(calls[0]?.params).toEqual({platform: "web"});
116
+ });
209
117
 
210
- const {api, acknowledgeQueryDef} = buildApi();
211
- renderHook(() => useAcknowledgeAnnouncement(api as unknown as AcknowledgeApi, "/api"));
212
-
213
- const acknowledgeDef = acknowledgeQueryDef();
214
- assert.ok(acknowledgeDef);
215
- const queryResult = acknowledgeDef.query({announcementId: "announcement-1"});
216
- assert.strictEqual(
217
- queryResult.url,
218
- "/api/announcements/announcement-1/acknowledge?platform=web"
219
- );
220
-
221
- Platform.OS = originalOS;
118
+ it("exposes the failing request error", async () => {
119
+ const failure = fakeHttpError(500);
120
+ const {client} = createFakeRequestClient({
121
+ "POST /announcements/:id/click": () => {
122
+ throw failure;
123
+ },
124
+ });
125
+ const {result} = renderHook(() => useAcknowledgeAnnouncement(client));
126
+ await act(async () => {
127
+ await result.current.recordClick("announcement-1").catch(() => {});
128
+ });
129
+ expect(result.current.error).toBe(failure);
222
130
  });
223
131
  });
@@ -1,157 +1,79 @@
1
- import {useCallback, useRef} from "react";
1
+ import {useCallback} from "react";
2
2
 
3
- import {getAnnouncementBuildVersion} from "./announcementBuildVersion";
4
- import {getAnnouncementPlatform} from "./announcementPlatform";
3
+ import {buildAnnouncementParams, getAnnouncementPlatform} from "./announcementPlatform";
4
+ import {invalidateClientTags, type TerrenoRequestClient, useClientMutation} from "./requestClient";
5
5
 
6
- interface AcknowledgeAnnouncementMutationResult {
7
- unwrap: () => Promise<unknown>;
8
- }
9
-
10
- interface AcknowledgeAnnouncementMutationHookState {
6
+ export interface UseAcknowledgeAnnouncementResult {
7
+ /** Acknowledge an announcement; the pending announcement refetches on success. */
8
+ acknowledge: (announcementId: string) => Promise<void>;
11
9
  error: unknown;
12
- isLoading: boolean;
13
- }
14
-
15
- interface AcknowledgeAnnouncementMutationBuilder {
16
- mutation: (options: {
17
- invalidatesTags: string[];
18
- query: (args: {announcementId: string; platform?: string}) => {
19
- body?: {action?: string; platform?: string};
20
- method: "POST";
21
- url: string;
22
- };
23
- }) => unknown;
24
- }
25
-
26
- interface AcknowledgeAnnouncementEnhancedApi {
27
- useAcknowledgeAnnouncementMutation: () => [
28
- (args: {announcementId: string; platform?: string}) => AcknowledgeAnnouncementMutationResult,
29
- AcknowledgeAnnouncementMutationHookState,
30
- ];
31
- useRecordAnnouncementClickMutation: () => [
32
- (args: {announcementId: string}) => AcknowledgeAnnouncementMutationResult,
33
- AcknowledgeAnnouncementMutationHookState,
34
- ];
35
- useRecordAnnouncementImpressionMutation: () => [
36
- (args: {announcementId: string; platform?: string}) => AcknowledgeAnnouncementMutationResult,
37
- AcknowledgeAnnouncementMutationHookState,
38
- ];
39
- }
40
-
41
- interface AcknowledgeAnnouncementApiWithTags {
42
- injectEndpoints: (options: {
43
- endpoints: (build: AcknowledgeAnnouncementMutationBuilder) => {
44
- acknowledgeAnnouncement: unknown;
45
- recordAnnouncementClick: unknown;
46
- recordAnnouncementImpression: unknown;
47
- };
48
- overrideExisting: boolean;
49
- }) => AcknowledgeAnnouncementEnhancedApi;
50
- }
51
-
52
- interface AcknowledgeAnnouncementApi {
53
- enhanceEndpoints: (options: {addTagTypes: string[]}) => AcknowledgeAnnouncementApiWithTags;
10
+ isAcknowledging: boolean;
11
+ isRecordingClick: boolean;
12
+ isRecordingImpression: boolean;
13
+ isSubmitting: boolean;
14
+ /** Record a primary-action click. */
15
+ recordClick: (announcementId: string) => Promise<void>;
16
+ /** Record that the announcement was shown (also dismisses non-acknowledgement ones). */
17
+ recordImpression: (announcementId: string) => Promise<void>;
54
18
  }
55
19
 
56
- const enhancedApiCache = new WeakMap<
57
- AcknowledgeAnnouncementApi,
58
- Map<string, AcknowledgeAnnouncementEnhancedApi>
59
- >();
60
-
61
- const buildAnnouncementEventUrl = (
62
- base: string,
63
- announcementId: string,
64
- action: "acknowledge" | "click"
65
- ): string => {
66
- const platform = getAnnouncementPlatform();
67
- const version = getAnnouncementBuildVersion();
68
- const versionParam = version === undefined ? "" : `&version=${version}`;
69
- return `${base}/announcements/${announcementId}/${action}?platform=${platform}${versionParam}`;
70
- };
71
-
72
- const getEnhancedApi = (
73
- api: AcknowledgeAnnouncementApi,
74
- base: string
75
- ): AcknowledgeAnnouncementEnhancedApi => {
76
- let byBase = enhancedApiCache.get(api);
77
- if (!byBase) {
78
- byBase = new Map();
79
- enhancedApiCache.set(api, byBase);
80
- }
81
- const cached = byBase.get(base);
82
- if (cached) {
83
- return cached;
84
- }
85
- const apiWithTags = api.enhanceEndpoints({addTagTypes: ["PendingAnnouncements"]});
86
- const enhanced = apiWithTags.injectEndpoints({
87
- endpoints: (build) => ({
88
- acknowledgeAnnouncement: build.mutation({
89
- invalidatesTags: ["PendingAnnouncements"],
90
- query: ({announcementId}: {announcementId: string}) => ({
91
- method: "POST",
92
- url: buildAnnouncementEventUrl(base, announcementId, "acknowledge"),
93
- }),
94
- }),
95
- recordAnnouncementClick: build.mutation({
96
- invalidatesTags: [],
97
- query: ({announcementId}: {announcementId: string}) => ({
98
- body: {
99
- action: "primaryAction",
100
- platform: getAnnouncementPlatform(),
101
- },
102
- method: "POST",
103
- url: buildAnnouncementEventUrl(base, announcementId, "click"),
104
- }),
105
- }),
106
- recordAnnouncementImpression: build.mutation({
107
- invalidatesTags: [],
108
- query: ({announcementId, platform}: {announcementId: string; platform?: string}) => ({
109
- body: platform ? {platform} : undefined,
110
- method: "POST",
111
- url: `${base}/announcements/${announcementId}/impression`,
112
- }),
113
- }),
114
- }),
115
- overrideExisting: false,
116
- });
117
- byBase.set(base, enhanced);
118
- return enhanced;
119
- };
120
-
121
- export const useAcknowledgeAnnouncement = (api: AcknowledgeAnnouncementApi, baseUrl?: string) => {
20
+ /** Announcement event requests: acknowledge, primary-action click, and impression. */
21
+ export const useAcknowledgeAnnouncement = (
22
+ client: TerrenoRequestClient,
23
+ baseUrl?: string
24
+ ): UseAcknowledgeAnnouncementResult => {
122
25
  const base = baseUrl || "";
123
- const enhancedApi = getEnhancedApi(api, base);
124
-
125
- const [acknowledgeMutation, {isLoading: isAcknowledging, error: acknowledgeError}] =
126
- enhancedApi.useAcknowledgeAnnouncementMutation();
127
- const [clickMutation, {isLoading: isRecordingClick, error: clickError}] =
128
- enhancedApi.useRecordAnnouncementClickMutation();
129
- const [impressionMutation, {isLoading: isRecordingImpression, error: impressionError}] =
130
- enhancedApi.useRecordAnnouncementImpressionMutation();
131
-
132
- const acknowledgeMutationRef = useRef(acknowledgeMutation);
133
- acknowledgeMutationRef.current = acknowledgeMutation;
134
- const clickMutationRef = useRef(clickMutation);
135
- clickMutationRef.current = clickMutation;
136
- const impressionMutationRef = useRef(impressionMutation);
137
- impressionMutationRef.current = impressionMutation;
138
-
139
- const acknowledge = useCallback(async (announcementId: string): Promise<void> => {
140
- await acknowledgeMutationRef.current({announcementId}).unwrap();
141
- }, []);
142
-
143
- const recordClick = useCallback(async (announcementId: string): Promise<void> => {
144
- await clickMutationRef.current({announcementId}).unwrap();
145
- }, []);
146
26
 
147
- const recordImpression = useCallback(async (announcementId: string): Promise<void> => {
148
- await impressionMutationRef
149
- .current({
150
- announcementId,
151
- platform: getAnnouncementPlatform(),
152
- })
153
- .unwrap();
154
- }, []);
27
+ const runAcknowledge = useCallback(
28
+ async (announcementId: string): Promise<void> => {
29
+ await client.request({
30
+ method: "POST",
31
+ params: buildAnnouncementParams(),
32
+ url: `${base}/announcements/${announcementId}/acknowledge`,
33
+ });
34
+ invalidateClientTags({client, tags: ["PendingAnnouncements"]});
35
+ },
36
+ [base, client]
37
+ );
38
+
39
+ const runClick = useCallback(
40
+ async (announcementId: string): Promise<void> => {
41
+ await client.request({
42
+ body: {action: "primaryAction", platform: getAnnouncementPlatform()},
43
+ method: "POST",
44
+ params: buildAnnouncementParams(),
45
+ url: `${base}/announcements/${announcementId}/click`,
46
+ });
47
+ },
48
+ [base, client]
49
+ );
50
+
51
+ const runImpression = useCallback(
52
+ async (announcementId: string): Promise<void> => {
53
+ await client.request({
54
+ body: {platform: getAnnouncementPlatform()},
55
+ method: "POST",
56
+ url: `${base}/announcements/${announcementId}/impression`,
57
+ });
58
+ },
59
+ [base, client]
60
+ );
61
+
62
+ const {
63
+ error: acknowledgeError,
64
+ isLoading: isAcknowledging,
65
+ mutate: acknowledge,
66
+ } = useClientMutation({run: runAcknowledge});
67
+ const {
68
+ error: clickError,
69
+ isLoading: isRecordingClick,
70
+ mutate: recordClick,
71
+ } = useClientMutation({run: runClick});
72
+ const {
73
+ error: impressionError,
74
+ isLoading: isRecordingImpression,
75
+ mutate: recordImpression,
76
+ } = useClientMutation({run: runImpression});
155
77
 
156
78
  return {
157
79
  acknowledge,