@terreno/ui 57.20.0 → 58.0.0-beta.1

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 (297) hide show
  1. package/.ai/guidelines/core.md +1 -1
  2. package/CHANGELOG.md +93 -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 +71 -39
  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 +6 -6
  31. package/dist/DateTimeField.js.map +1 -1
  32. package/dist/DropdownPanel.d.ts +0 -5
  33. package/dist/DropdownPanel.d.ts.map +1 -1
  34. package/dist/DropdownPanel.js +0 -5
  35. package/dist/DropdownPanel.js.map +1 -1
  36. package/dist/FilterAccordion.d.ts.map +1 -1
  37. package/dist/FilterAccordion.js.map +1 -1
  38. package/dist/FilterBoolean.d.ts.map +1 -1
  39. package/dist/FilterBoolean.js.map +1 -1
  40. package/dist/FilterSelectMenu.js +1 -1
  41. package/dist/FilterSelectMenu.js.map +1 -1
  42. package/dist/GPTChat.d.ts.map +1 -1
  43. package/dist/GPTChat.js.map +1 -1
  44. package/dist/Heading.d.ts.map +1 -1
  45. package/dist/Heading.js +6 -12
  46. package/dist/Heading.js.map +1 -1
  47. package/dist/HeightField.d.ts.map +1 -1
  48. package/dist/HeightField.js +9 -9
  49. package/dist/HeightField.js.map +1 -1
  50. package/dist/Hyperlink.d.ts.map +1 -1
  51. package/dist/Hyperlink.js +6 -1
  52. package/dist/Hyperlink.js.map +1 -1
  53. package/dist/Image.d.ts +1 -1
  54. package/dist/MarkdownEditorField.d.ts.map +1 -1
  55. package/dist/MarkdownEditorField.js +1 -1
  56. package/dist/MarkdownEditorField.js.map +1 -1
  57. package/dist/OfflineBanner.d.ts +3 -2
  58. package/dist/OfflineBanner.d.ts.map +1 -1
  59. package/dist/OfflineBanner.js +3 -2
  60. package/dist/OfflineBanner.js.map +1 -1
  61. package/dist/OtpField.d.ts.map +1 -1
  62. package/dist/OtpField.js +4 -4
  63. package/dist/OtpField.js.map +1 -1
  64. package/dist/PickerSelect.d.ts +4 -4
  65. package/dist/PickerSelect.d.ts.map +1 -1
  66. package/dist/PickerSelect.js +9 -9
  67. package/dist/PickerSelect.js.map +1 -1
  68. package/dist/ProvisionalConsentSigner.d.ts +3 -2
  69. package/dist/ProvisionalConsentSigner.d.ts.map +1 -1
  70. package/dist/ProvisionalConsentSigner.js +2 -2
  71. package/dist/ProvisionalConsentSigner.js.map +1 -1
  72. package/dist/SidebarNavigation.js +2 -2
  73. package/dist/SidebarNavigation.js.map +1 -1
  74. package/dist/SidebarNavigation.native.js +2 -2
  75. package/dist/SidebarNavigation.native.js.map +1 -1
  76. package/dist/Skeleton.js.map +1 -1
  77. package/dist/TapToEdit.d.ts +1 -1
  78. package/dist/TapToEdit.d.ts.map +1 -1
  79. package/dist/TapToEdit.js.map +1 -1
  80. package/dist/Text.d.ts.map +1 -1
  81. package/dist/Text.js +27 -50
  82. package/dist/Text.js.map +1 -1
  83. package/dist/TextField.d.ts.map +1 -1
  84. package/dist/TextField.js +4 -4
  85. package/dist/TextField.js.map +1 -1
  86. package/dist/Theme.d.ts.map +1 -1
  87. package/dist/Theme.js +16 -0
  88. package/dist/Theme.js.map +1 -1
  89. package/dist/ThumbsUpDownFeedback.d.ts.map +1 -1
  90. package/dist/ThumbsUpDownFeedback.js.map +1 -1
  91. package/dist/ToastNotifications.d.ts.map +1 -1
  92. package/dist/ToastNotifications.js.map +1 -1
  93. package/dist/Tooltip.d.ts.map +1 -1
  94. package/dist/Tooltip.js.map +1 -1
  95. package/dist/Unifier.d.ts +1 -1
  96. package/dist/WebAddressAutocomplete.js.map +1 -1
  97. package/dist/WebDropdownMenu.d.ts +3 -3
  98. package/dist/WebDropdownMenu.d.ts.map +1 -1
  99. package/dist/WebDropdownMenu.js +1 -1
  100. package/dist/WebDropdownMenu.js.map +1 -1
  101. package/dist/announcementPlatform.d.ts +5 -0
  102. package/dist/announcementPlatform.d.ts.map +1 -1
  103. package/dist/announcementPlatform.js +9 -0
  104. package/dist/announcementPlatform.js.map +1 -1
  105. package/dist/asks/AskCard.d.ts +2 -2
  106. package/dist/asks/AskCard.d.ts.map +1 -1
  107. package/dist/dataTableColumnWidths.d.ts +76 -0
  108. package/dist/dataTableColumnWidths.d.ts.map +1 -0
  109. package/dist/dataTableColumnWidths.js +181 -0
  110. package/dist/dataTableColumnWidths.js.map +1 -0
  111. package/dist/index.d.ts +2 -1
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js.map +1 -1
  114. package/dist/login/LoginScreen.js.map +1 -1
  115. package/dist/requestClient.d.ts +71 -0
  116. package/dist/requestClient.d.ts.map +1 -0
  117. package/dist/requestClient.js +139 -0
  118. package/dist/requestClient.js.map +1 -0
  119. package/dist/security/PasswordCard.d.ts.map +1 -1
  120. package/dist/security/PasswordCard.js.map +1 -1
  121. package/dist/security/TwoFactorSettingsCard.d.ts.map +1 -1
  122. package/dist/security/TwoFactorSettingsCard.js +1 -1
  123. package/dist/security/TwoFactorSettingsCard.js.map +1 -1
  124. package/dist/signUp/SignUpScreen.js.map +1 -1
  125. package/dist/table/Table.d.ts.map +1 -1
  126. package/dist/table/Table.js.map +1 -1
  127. package/dist/table/TableTitle.d.ts.map +1 -1
  128. package/dist/table/TableTitle.js +2 -1
  129. package/dist/table/TableTitle.js.map +1 -1
  130. package/dist/textFontSizes.d.ts +12 -0
  131. package/dist/textFontSizes.d.ts.map +1 -0
  132. package/dist/textFontSizes.js +21 -0
  133. package/dist/textFontSizes.js.map +1 -0
  134. package/dist/useAcknowledgeAnnouncement.d.ts +8 -63
  135. package/dist/useAcknowledgeAnnouncement.d.ts.map +1 -1
  136. package/dist/useAcknowledgeAnnouncement.js +31 -80
  137. package/dist/useAcknowledgeAnnouncement.js.map +1 -1
  138. package/dist/useAnnouncements.d.ts +14 -47
  139. package/dist/useAnnouncements.d.ts.map +1 -1
  140. package/dist/useAnnouncements.js +30 -57
  141. package/dist/useAnnouncements.js.map +1 -1
  142. package/dist/useConsentForms.d.ts +6 -38
  143. package/dist/useConsentForms.d.ts.map +1 -1
  144. package/dist/useConsentForms.js +25 -48
  145. package/dist/useConsentForms.js.map +1 -1
  146. package/dist/useProvisionalConsent.d.ts +7 -58
  147. package/dist/useProvisionalConsent.d.ts.map +1 -1
  148. package/dist/useProvisionalConsent.js +57 -67
  149. package/dist/useProvisionalConsent.js.map +1 -1
  150. package/dist/useSubmitConsent.d.ts +9 -39
  151. package/dist/useSubmitConsent.d.ts.map +1 -1
  152. package/dist/useSubmitConsent.js +10 -39
  153. package/dist/useSubmitConsent.js.map +1 -1
  154. package/package.json +40 -38
  155. package/src/ActionSheet.test.tsx +13 -13
  156. package/src/ActionSheet.tsx +18 -5
  157. package/src/AddressField.test.tsx +9 -3
  158. package/src/AnnouncementNavigator.test.tsx +219 -319
  159. package/src/AnnouncementNavigator.tsx +25 -20
  160. package/src/Avatar.tsx +2 -9
  161. package/src/Badge.test.tsx +1 -1
  162. package/src/Banner.test.tsx +0 -1
  163. package/src/Box.test.tsx +85 -77
  164. package/src/Box.tsx +4 -2
  165. package/src/Button.test.tsx +11 -6
  166. package/src/Card.test.tsx +2 -2
  167. package/src/Common.ts +79 -44
  168. package/src/ConflictSheet.test.tsx +5 -5
  169. package/src/ConsentFormScreen.test.tsx +3 -1
  170. package/src/ConsentFormScreen.tsx +2 -1
  171. package/src/ConsentNavigator.test.tsx +166 -243
  172. package/src/ConsentNavigator.tsx +9 -13
  173. package/src/CustomSelectField.test.tsx +16 -4
  174. package/src/CustomSelectField.tsx +3 -3
  175. package/src/DataTable.test.tsx +73 -5
  176. package/src/DataTable.tsx +72 -19
  177. package/src/DataTableVirtualizationRegression.test.tsx +1 -0
  178. package/src/DateTimeActionSheet.test.tsx +2 -0
  179. package/src/DateTimeField.test.tsx +3 -12
  180. package/src/DateTimeField.tsx +10 -10
  181. package/src/DismissButton.test.tsx +22 -4
  182. package/src/DropdownPanel.tsx +0 -6
  183. package/src/EmailField.test.tsx +13 -22
  184. package/src/EmojiSelector.test.tsx +2 -2
  185. package/src/ErrorBoundary.test.tsx +5 -3
  186. package/src/Field.test.tsx +20 -44
  187. package/src/FilterAccordion.tsx +3 -3
  188. package/src/FilterBoolean.tsx +3 -3
  189. package/src/FilterSelectMenu.tsx +1 -1
  190. package/src/GPTChat.test.tsx +24 -16
  191. package/src/GPTChat.tsx +10 -9
  192. package/src/Heading.test.tsx +1 -1
  193. package/src/Heading.tsx +7 -14
  194. package/src/HeightField.tsx +17 -10
  195. package/src/Hyperlink.tsx +6 -3
  196. package/src/Icon.test.tsx +2 -2
  197. package/src/Image.test.tsx +1 -1
  198. package/src/Link.test.tsx +13 -6
  199. package/src/MarkdownEditorField.tsx +10 -2
  200. package/src/MarkdownView.test.tsx +10 -6
  201. package/src/MobileAddressAutoComplete.test.tsx +2 -1
  202. package/src/Modal.test.tsx +10 -3
  203. package/src/ModalSheet.test.tsx +11 -10
  204. package/src/MultiselectField.test.tsx +17 -3
  205. package/src/NumberField.test.tsx +14 -14
  206. package/src/NumberPickerActionSheet.test.tsx +1 -1
  207. package/src/OfflineBanner.tsx +3 -2
  208. package/src/OpenAPIContext.test.tsx +4 -4
  209. package/src/OpenAPIRenderRegression.test.tsx +1 -1
  210. package/src/OtpField.tsx +6 -5
  211. package/src/P0RenderRegression.test.tsx +7 -1
  212. package/src/P1RenderRegression.test.tsx +1 -0
  213. package/src/P2ButtonRenderRegression.test.tsx +1 -0
  214. package/src/Page.test.tsx +1 -1
  215. package/src/PhoneNumberField.test.tsx +14 -38
  216. package/src/PickerSelect.tsx +12 -11
  217. package/src/Popover.test.tsx +2 -2
  218. package/src/ProvisionalConsentSigner.test.tsx +140 -113
  219. package/src/ProvisionalConsentSigner.tsx +5 -4
  220. package/src/RadioField.test.tsx +7 -2
  221. package/src/SegmentedControl.test.tsx +21 -12
  222. package/src/SidebarNavigation.native.tsx +2 -2
  223. package/src/SidebarNavigation.test.tsx +18 -6
  224. package/src/SidebarNavigation.tsx +2 -2
  225. package/src/Signature.test.tsx +20 -23
  226. package/src/Skeleton.tsx +1 -1
  227. package/src/Slider.test.tsx +1 -1
  228. package/src/SplitPage.test.tsx +15 -5
  229. package/src/TapToEdit.test.tsx +40 -17
  230. package/src/TapToEdit.tsx +1 -1
  231. package/src/TerrenoFontProvider.test.tsx +1 -1
  232. package/src/Text.test.tsx +4 -4
  233. package/src/Text.tsx +25 -51
  234. package/src/TextField.test.tsx +82 -9
  235. package/src/TextField.tsx +6 -5
  236. package/src/Theme.test.tsx +49 -0
  237. package/src/Theme.tsx +16 -0
  238. package/src/ThumbsUpDownFeedback.tsx +3 -3
  239. package/src/Toast.test.tsx +5 -5
  240. package/src/ToastNotifications.test.tsx +73 -70
  241. package/src/ToastNotifications.tsx +3 -2
  242. package/src/ToastNotifications.webModal.test.tsx +6 -3
  243. package/src/Tooltip.test.tsx +3 -3
  244. package/src/Tooltip.tsx +2 -1
  245. package/src/UnifiedAddressAutoComplete.test.tsx +1 -1
  246. package/src/UserInactivity.test.tsx +1 -0
  247. package/src/WebAddressAutocomplete.test.tsx +12 -12
  248. package/src/WebAddressAutocomplete.tsx +3 -3
  249. package/src/WebDropdownMenu.test.tsx +16 -15
  250. package/src/WebDropdownMenu.tsx +16 -5
  251. package/src/__snapshots__/Card.test.tsx.snap +1 -1
  252. package/src/__snapshots__/DataTable.test.tsx.snap +13 -0
  253. package/src/__snapshots__/DismissButton.test.tsx.snap +3 -3
  254. package/src/__snapshots__/Field.test.tsx.snap +4 -2
  255. package/src/__snapshots__/Heading.test.tsx.snap +1 -1
  256. package/src/__snapshots__/Image.test.tsx.snap +1 -1
  257. package/src/__snapshots__/Page.test.tsx.snap +2 -2
  258. package/src/__snapshots__/Text.test.tsx.snap +1 -1
  259. package/src/announcementPlatform.ts +10 -0
  260. package/src/asks/AskCard.test.tsx +20 -15
  261. package/src/asks/AskCard.tsx +2 -2
  262. package/src/asks/AskFiles.test.tsx +5 -1
  263. package/src/asks/askFileRefs.test.ts +1 -1
  264. package/src/asks/askSummary.test.ts +2 -2
  265. package/src/benchmarks/importTiming.ts +1 -1
  266. package/src/blocks/BlocksView.test.tsx +20 -11
  267. package/src/bunSetup.ts +43 -1
  268. package/src/dataTableColumnWidths.test.ts +266 -0
  269. package/src/dataTableColumnWidths.ts +272 -0
  270. package/src/dataTableFilters.test.tsx +1 -1
  271. package/src/index.tsx +9 -2
  272. package/src/isolated/ListDetailLayout.isolated.tsx +2 -4
  273. package/src/login/LoginScreen.test.tsx +6 -6
  274. package/src/login/LoginScreen.tsx +2 -2
  275. package/src/requestClient.test.ts +288 -0
  276. package/src/requestClient.ts +228 -0
  277. package/src/security/PasswordCard.test.tsx +3 -3
  278. package/src/security/PasswordCard.tsx +7 -5
  279. package/src/security/TwoFactorSettingsCard.tsx +10 -3
  280. package/src/signUp/SignUpScreen.test.tsx +4 -4
  281. package/src/signUp/SignUpScreen.tsx +2 -2
  282. package/src/table/Table.tsx +1 -2
  283. package/src/table/TableTitle.tsx +2 -1
  284. package/src/table/tableContext.test.tsx +5 -5
  285. package/src/test-utils.tsx +132 -1
  286. package/src/testing/reactDomServer.d.ts +7 -0
  287. package/src/textFontSizes.ts +31 -0
  288. package/src/useAcknowledgeAnnouncement.test.ts +101 -193
  289. package/src/useAcknowledgeAnnouncement.ts +69 -147
  290. package/src/useAnnouncements.test.ts +122 -186
  291. package/src/useAnnouncements.ts +49 -105
  292. package/src/useConsentForms.test.ts +59 -112
  293. package/src/useConsentForms.ts +37 -87
  294. package/src/useProvisionalConsent.test.ts +74 -150
  295. package/src/useProvisionalConsent.ts +79 -125
  296. package/src/useSubmitConsent.test.ts +59 -85
  297. package/src/useSubmitConsent.ts +22 -77
@@ -1,6 +1,7 @@
1
- import {describe, expect, it, mock} from "bun:test";
2
- import {renderHook} from "@testing-library/react-native";
1
+ import {describe, expect, it, mock, spyOn} from "bun:test";
2
+ import {act, renderHook, waitFor} from "@testing-library/react-native";
3
3
 
4
+ import {createFakeRequestClient, fakeHttpError} from "./test-utils";
4
5
  import type {ConsentFormPublic} from "./useConsentForms";
5
6
  import {
6
7
  applyConsentVariables,
@@ -8,25 +9,15 @@ import {
8
9
  resolveConsentLocale,
9
10
  useConsentForms,
10
11
  } from "./useConsentForms";
12
+ import {useSubmitConsent} from "./useSubmitConsent";
11
13
 
12
- type ConsentFormsApi = Parameters<typeof useConsentForms>[0];
14
+ const makeForm = (id: string): ConsentFormPublic =>
15
+ ({id, title: `Form ${id}`}) as unknown as ConsentFormPublic;
13
16
 
14
17
  interface GlobalThisWithNavigator {
15
18
  navigator: {language: string} | undefined;
16
19
  }
17
20
 
18
- interface MockQueryDef {
19
- onQueryStarted?: (
20
- _arg: unknown,
21
- helpers: {queryFulfilled: Promise<{data: ConsentFormPublic[]}> | Promise<never>}
22
- ) => Promise<void>;
23
- query: () => string;
24
- }
25
-
26
- interface MockInjectOpts {
27
- endpoints: (build: {query: (def: MockQueryDef) => string}) => Record<string, unknown>;
28
- }
29
-
30
21
  mock.module("expo-localization", () => ({
31
22
  getLocales: () => [{languageTag: "es-ES"}],
32
23
  }));
@@ -102,112 +93,68 @@ describe("detectLocale", () => {
102
93
  });
103
94
 
104
95
  describe("useConsentForms", () => {
105
- const buildApi = (queryResult: {data?: unknown; error?: unknown; isLoading?: boolean}) => {
106
- const refetch = mock(() => {});
107
- const useGetPendingConsentsQuery = mock(() => ({
108
- data: queryResult.data,
109
- error: queryResult.error,
110
- isLoading: queryResult.isLoading ?? false,
111
- refetch,
112
- }));
113
- const api = {
114
- enhanceEndpoints: mock(() => ({
115
- injectEndpoints: mock((opts: MockInjectOpts) => {
116
- // Call endpoint builder to exercise provides/onQueryStarted
117
- const build = {
118
- query: mock((def: MockQueryDef) => {
119
- // Call onQueryStarted with a successful result
120
- if (def.onQueryStarted) {
121
- void def.onQueryStarted(undefined, {
122
- queryFulfilled: Promise.resolve({data: [{id: "1"}]}),
123
- });
124
- }
125
- // Also exercise the URL builder
126
- def.query();
127
- return "pending-query";
128
- }),
129
- };
130
- opts.endpoints(build);
131
- return {useGetPendingConsentsQuery};
132
- }),
133
- })),
134
- };
135
- return {api, refetch};
136
- };
137
-
138
- it("returns an array of forms when response is an array", () => {
139
- const {api} = buildApi({data: [{id: "1", title: "Form 1"} as unknown as ConsentFormPublic]});
140
- const {result} = renderHook(() => useConsentForms(api as unknown as ConsentFormsApi));
141
- expect(result.current.forms).toBeDefined();
142
- expect(Array.isArray(result.current.forms)).toBe(true);
96
+ it("returns forms from a bare array response", async () => {
97
+ const {client, calls} = createFakeRequestClient({
98
+ "GET /consents/pending": () => [makeForm("1")],
99
+ });
100
+ const {result} = renderHook(() => useConsentForms(client));
101
+ expect(result.current.isLoading).toBe(true);
102
+ expect(result.current.forms).toEqual([]);
103
+ await waitFor(() => expect(result.current.forms).toHaveLength(1));
104
+ expect(result.current.isLoading).toBe(false);
105
+ expect(calls[0]?.url).toBe("/consents/pending");
143
106
  });
144
107
 
145
- it("unwraps .data property when response is object shape", () => {
146
- const {api} = buildApi({data: {data: [{id: "2"} as unknown as ConsentFormPublic]}});
147
- const {result} = renderHook(() => useConsentForms(api as unknown as ConsentFormsApi, "/api"));
148
- expect(Array.isArray(result.current.forms)).toBe(true);
108
+ it("unwraps a {data} envelope and prefixes baseUrl", async () => {
109
+ const {client, calls} = createFakeRequestClient({
110
+ "GET /api/consents/pending": () => ({data: [makeForm("2")]}),
111
+ });
112
+ const {result} = renderHook(() => useConsentForms(client, "/api"));
113
+ await waitFor(() => expect(result.current.forms[0]?.id).toBe("2"));
114
+ expect(calls[0]?.url).toBe("/api/consents/pending");
149
115
  });
150
116
 
151
- it("returns empty array when no data is present", () => {
152
- const {api} = buildApi({data: undefined, isLoading: true});
153
- const {result} = renderHook(() => useConsentForms(api as unknown as ConsentFormsApi));
117
+ it("returns an empty array when the envelope has no data", async () => {
118
+ const {client} = createFakeRequestClient({"GET /consents/pending": () => ({})});
119
+ const {result} = renderHook(() => useConsentForms(client));
120
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
154
121
  expect(result.current.forms).toEqual([]);
155
- expect(result.current.isLoading).toBe(true);
156
122
  });
157
123
 
158
- it("calls onQueryStarted with failing query", () => {
159
- const refetch = mock(() => {});
160
- const api = {
161
- enhanceEndpoints: mock(() => ({
162
- injectEndpoints: mock((opts: MockInjectOpts) => {
163
- const build = {
164
- query: mock((def: MockQueryDef) => {
165
- if (def.onQueryStarted) {
166
- void def.onQueryStarted(undefined, {
167
- queryFulfilled: Promise.reject(new Error("failed")),
168
- });
169
- }
170
- return "q";
171
- }),
172
- };
173
- opts.endpoints(build);
174
- return {
175
- useGetPendingConsentsQuery: () => ({
176
- data: undefined,
177
- error: "error",
178
- isLoading: false,
179
- refetch,
180
- }),
181
- };
182
- }),
183
- })),
184
- };
185
- const {result} = renderHook(() => useConsentForms(api as unknown as ConsentFormsApi));
186
- expect(result.current.error).toBe("error");
124
+ it("surfaces request errors and logs a warning", async () => {
125
+ const warn = spyOn(console, "warn").mockImplementation(() => {});
126
+ const failure = fakeHttpError(500);
127
+ const {client} = createFakeRequestClient({
128
+ "GET /consents/pending": () => {
129
+ throw failure;
130
+ },
131
+ });
132
+ const {result} = renderHook(() => useConsentForms(client));
133
+ await waitFor(() => expect(result.current.error).toBe(failure));
134
+ expect(result.current.forms).toEqual([]);
135
+ expect(warn).toHaveBeenCalledWith("[useConsentForms] Failed to fetch pending consent forms", {
136
+ error: failure,
137
+ });
138
+ warn.mockRestore();
187
139
  });
188
140
 
189
- it("injects the pending-consents endpoint only once per (api, baseUrl)", () => {
190
- let injectCallCount = 0;
191
- const refetch = mock(() => {});
192
- const useGetPendingConsentsQuery = mock(() => ({
193
- data: undefined,
194
- error: undefined,
195
- isLoading: false,
196
- refetch,
141
+ it("refetches when a consent submission invalidates pending consents", async () => {
142
+ let forms = [makeForm("1")];
143
+ const {client, callsTo} = createFakeRequestClient({
144
+ "GET /consents/pending": () => forms,
145
+ "POST /consents/respond": () => ({agreed: true}),
146
+ });
147
+ const {result} = renderHook(() => ({
148
+ pending: useConsentForms(client),
149
+ submit: useSubmitConsent(client),
197
150
  }));
198
- const api = {
199
- enhanceEndpoints: () => ({
200
- injectEndpoints: () => {
201
- injectCallCount += 1;
202
- return {useGetPendingConsentsQuery};
203
- },
204
- }),
205
- };
206
- const {rerender} = renderHook(() => useConsentForms(api as unknown as ConsentFormsApi));
207
- rerender(undefined);
208
- rerender(undefined);
209
- // The hook reuses the cached enhanced api after the first render so the
210
- // dev-mode RTK warning about re-injecting endpoints never fires.
211
- expect(injectCallCount).toBe(1);
151
+ await waitFor(() => expect(result.current.pending.forms).toHaveLength(1));
152
+
153
+ forms = [];
154
+ await act(async () => {
155
+ await result.current.submit.submit({agreed: true, consentFormId: "1", locale: "en"});
156
+ });
157
+ await waitFor(() => expect(result.current.pending.forms).toHaveLength(0));
158
+ expect(callsTo("GET /consents/pending")).toHaveLength(2);
212
159
  });
213
160
  });
@@ -1,3 +1,8 @@
1
+ import {getLocales} from "expo-localization";
2
+ import {useCallback} from "react";
3
+
4
+ import {type TerrenoRequestClient, useClientQuery} from "./requestClient";
5
+
1
6
  export interface ConsentFormPublic {
2
7
  id: string;
3
8
  title: string;
@@ -19,45 +24,6 @@ export interface ConsentFormPublic {
19
24
  provisionalSignature?: {signedAt: string; signedByName: string};
20
25
  }
21
26
 
22
- import {getLocales} from "expo-localization";
23
-
24
- interface ConsentFormsResponse {
25
- data?: ConsentFormPublic[];
26
- }
27
-
28
- interface ConsentFormsQueryBuilder {
29
- query: (options: {
30
- onQueryStarted?: (
31
- _arg: unknown,
32
- helpers: {queryFulfilled: Promise<ConsentFormsResponse>}
33
- ) => Promise<void>;
34
- providesTags: string[];
35
- query: () => string;
36
- }) => unknown;
37
- }
38
-
39
- interface ConsentFormsHookState {
40
- data?: ConsentFormPublic[] | ConsentFormsResponse;
41
- error: unknown;
42
- isLoading: boolean;
43
- refetch: () => void | Promise<void>;
44
- }
45
-
46
- interface ConsentFormsEnhancedApi {
47
- useGetPendingConsentsQuery: () => ConsentFormsHookState;
48
- }
49
-
50
- interface ConsentFormsApiWithTags {
51
- injectEndpoints: (options: {
52
- endpoints: (build: ConsentFormsQueryBuilder) => {getPendingConsents: unknown};
53
- overrideExisting: boolean;
54
- }) => ConsentFormsEnhancedApi;
55
- }
56
-
57
- interface ConsentFormsApi {
58
- enhanceEndpoints: (options: {addTagTypes: string[]}) => ConsentFormsApiWithTags;
59
- }
60
-
61
27
  /** Replace `{{name}}` placeholders in consent content; unknown placeholders stay as written. */
62
28
  export const applyConsentVariables = (
63
29
  content: string,
@@ -100,56 +66,40 @@ export const detectLocale = (): string => {
100
66
  return "en";
101
67
  };
102
68
 
103
- /**
104
- * Cache the enhanced api per (api, baseUrl). `injectEndpoints` logs a console
105
- * error in development whenever an endpoint with the same name is re-injected
106
- * (with `overrideExisting: false`), so calling it on every render of every
107
- * consumer would flood the console. WeakMap-by-api lets the GC reclaim entries
108
- * when the api object is unreachable.
109
- */
110
- const enhancedApiCache = new WeakMap<ConsentFormsApi, Map<string, ConsentFormsEnhancedApi>>();
111
-
112
- const getEnhancedApi = (api: ConsentFormsApi, base: string): ConsentFormsEnhancedApi => {
113
- let byBase = enhancedApiCache.get(api);
114
- if (!byBase) {
115
- byBase = new Map();
116
- enhancedApiCache.set(api, byBase);
117
- }
118
- const cached = byBase.get(base);
119
- if (cached) {
120
- return cached;
121
- }
122
- const apiWithConsentTags = api.enhanceEndpoints({addTagTypes: ["PendingConsents"]});
123
- const enhanced = apiWithConsentTags.injectEndpoints({
124
- endpoints: (build) => ({
125
- getPendingConsents: build.query({
126
- async onQueryStarted(_arg: unknown, {queryFulfilled}) {
127
- console.info("[useConsentForms] Fetching pending consent forms");
128
- try {
129
- const result = await queryFulfilled;
130
- console.info("[useConsentForms] Pending consent forms fetched", {
131
- count: result?.data?.length ?? 0,
132
- });
133
- } catch (error) {
134
- console.warn("[useConsentForms] Failed to fetch pending consent forms", {error});
135
- }
136
- },
137
- providesTags: ["PendingConsents"],
138
- query: () => `${base}/consents/pending`,
139
- }),
140
- }),
141
- overrideExisting: false,
142
- });
143
- byBase.set(base, enhanced);
144
- return enhanced;
145
- };
69
+ export interface UseConsentFormsResult {
70
+ error: unknown;
71
+ forms: ConsentFormPublic[];
72
+ isLoading: boolean;
73
+ refetch: () => Promise<void>;
74
+ }
146
75
 
147
- export const useConsentForms = (api: ConsentFormsApi, baseUrl?: string) => {
76
+ /** Fetch the signed-in user's pending consent forms (`GET /consents/pending`). */
77
+ export const useConsentForms = (
78
+ client: TerrenoRequestClient,
79
+ baseUrl?: string
80
+ ): UseConsentFormsResult => {
148
81
  const base = baseUrl || "";
149
- const enhancedApi = getEnhancedApi(api, base);
150
82
 
151
- const {data, isLoading, error, refetch} = enhancedApi.useGetPendingConsentsQuery();
152
- const forms: ConsentFormPublic[] = Array.isArray(data) ? data : (data?.data ?? []);
83
+ const fetchPendingConsents = useCallback(async (): Promise<ConsentFormPublic[]> => {
84
+ console.info("[useConsentForms] Fetching pending consent forms");
85
+ try {
86
+ const result = await client.request<ConsentFormPublic[] | {data?: ConsentFormPublic[]}>({
87
+ url: `${base}/consents/pending`,
88
+ });
89
+ const forms = Array.isArray(result) ? result : (result?.data ?? []);
90
+ console.info("[useConsentForms] Pending consent forms fetched", {count: forms.length});
91
+ return forms;
92
+ } catch (error) {
93
+ console.warn("[useConsentForms] Failed to fetch pending consent forms", {error});
94
+ throw error;
95
+ }
96
+ }, [base, client]);
97
+
98
+ const {data, error, isLoading, refetch} = useClientQuery({
99
+ client,
100
+ fetcher: fetchPendingConsents,
101
+ providesTag: "PendingConsents",
102
+ });
153
103
 
154
- return {error, forms, isLoading, refetch};
104
+ return {error, forms: data ?? [], isLoading, refetch};
155
105
  };
@@ -1,23 +1,13 @@
1
- import {describe, expect, it, mock} from "bun:test";
2
- import {act, renderHook} from "@testing-library/react-native";
1
+ import {describe, expect, it} from "bun:test";
2
+ import {act, renderHook, waitFor} from "@testing-library/react-native";
3
3
 
4
+ import {createFakeRequestClient, fakeHttpError} from "./test-utils";
4
5
  import {
5
- type ProvisionalConsentApi,
6
6
  type ProvisionalConsentStatusRow,
7
7
  provisionalSignerName,
8
8
  useProvisionalConsent,
9
9
  } from "./useProvisionalConsent";
10
10
 
11
- interface CapturedQuery {
12
- providesTags: string[];
13
- query: (userId: string) => string;
14
- }
15
-
16
- interface CapturedMutation {
17
- invalidatesTags: string[];
18
- query: (args: Record<string, unknown>) => {body: unknown; method: string; url: string};
19
- }
20
-
21
11
  const row: ProvisionalConsentStatusRow = {
22
12
  form: {
23
13
  active: true,
@@ -41,126 +31,68 @@ const row: ProvisionalConsentStatusRow = {
41
31
  status: "pending",
42
32
  };
43
33
 
44
- const buildApi = (
45
- state: {data?: unknown; error?: unknown; isLoading?: boolean} = {},
46
- signResult: () => Promise<unknown> = () => Promise.resolve({}),
47
- voidResult: () => Promise<unknown> = () => Promise.resolve({})
48
- ): {
49
- voidedArgs: unknown[];
50
- api: ProvisionalConsentApi;
51
- captured: CapturedQuery[];
52
- capturedMutations: CapturedMutation[];
53
- addTagTypes: string[][];
54
- queriedUserIds: string[];
55
- signedBodies: unknown[];
56
- } => {
57
- const captured: CapturedQuery[] = [];
58
- const capturedMutations: CapturedMutation[] = [];
59
- const addTagTypes: string[][] = [];
60
- const queriedUserIds: string[] = [];
34
+ /** A fake request client: the status route returns `status`, signing and voiding run `signResult` / `voidResult`. */
35
+ const buildClient = ({
36
+ signResult = () => Promise.resolve({}),
37
+ status = {data: []},
38
+ voidResult = () => Promise.resolve({}),
39
+ }: {
40
+ signResult?: () => Promise<unknown>;
41
+ status?: unknown | (() => Promise<unknown>);
42
+ voidResult?: () => Promise<unknown>;
43
+ } = {}) => {
61
44
  const signedBodies: unknown[] = [];
62
45
  const voidedArgs: unknown[] = [];
63
- const api = {
64
- enhanceEndpoints: mock((options: {addTagTypes: string[]}) => {
65
- addTagTypes.push(options.addTagTypes);
66
- return {
67
- injectEndpoints: mock(
68
- (options: {
69
- endpoints: (build: {
70
- mutation: (def: CapturedMutation) => unknown;
71
- query: (def: CapturedQuery) => unknown;
72
- }) => unknown;
73
- }) => {
74
- options.endpoints({
75
- mutation: (def: CapturedMutation) => {
76
- capturedMutations.push(def);
77
- return def;
78
- },
79
- query: (def: CapturedQuery) => {
80
- captured.push(def);
81
- return def;
82
- },
83
- });
84
- return {
85
- useGetConsentStatusQuery: (userId: string) => {
86
- queriedUserIds.push(userId);
87
- return {
88
- data: state.data,
89
- error: state.error,
90
- isLoading: state.isLoading ?? false,
91
- refetch: () => {},
92
- };
93
- },
94
- useSignConsentProvisionallyMutation: () => [
95
- (body: unknown) => {
96
- signedBodies.push(body);
97
- return {unwrap: signResult};
98
- },
99
- {isLoading: false},
100
- ],
101
- useVoidProvisionalConsentMutation: () => [
102
- (args: unknown) => {
103
- voidedArgs.push(args);
104
- return {unwrap: voidResult};
105
- },
106
- {isLoading: false},
107
- ],
108
- };
109
- }
110
- ),
111
- };
112
- }),
113
- } as unknown as ProvisionalConsentApi;
114
- return {addTagTypes, api, captured, capturedMutations, queriedUserIds, signedBodies, voidedArgs};
46
+ const fake = createFakeRequestClient({
47
+ "GET /consent-responses/status": async () =>
48
+ typeof status === "function" ? (status as () => Promise<unknown>)() : status,
49
+ "GET /v2/consent-responses/status": async () => status,
50
+ "POST /consent-responses/:id/void": async (args, params) => {
51
+ voidedArgs.push({reason: (args.body as {reason: string}).reason, responseId: params.id});
52
+ return voidResult();
53
+ },
54
+ "POST /consent-responses/provisional": async (args) => {
55
+ signedBodies.push(args.body);
56
+ return signResult();
57
+ },
58
+ });
59
+ return {...fake, signedBodies, voidedArgs};
115
60
  };
116
61
 
117
62
  describe("useProvisionalConsent", () => {
118
- it("queries the status endpoint for the user under the base URL", () => {
119
- const {api, captured, addTagTypes, queriedUserIds} = buildApi({data: {data: [row]}});
63
+ it("requests the status endpoint for the user and returns the rows", async () => {
64
+ const {client, callsTo} = buildClient({status: {data: [row]}});
120
65
 
121
- const {result} = renderHook(() =>
122
- useProvisionalConsent({api, baseUrl: "/api", userId: "user 1"})
123
- );
66
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "user 1"}));
124
67
 
125
- expect(captured).toHaveLength(1);
126
- expect(captured[0].query("user 1")).toBe("/api/consent-responses/status?userId=user%201");
127
- expect(captured[0].providesTags).toEqual(["ConsentStatus"]);
128
- expect(addTagTypes[0]).toEqual(["ConsentStatus", "PendingConsents"]);
129
- expect(queriedUserIds).toContain("user 1");
130
- expect(result.current.statuses).toEqual([row]);
68
+ expect(result.current.isLoading).toBe(true);
69
+ await waitFor(() => expect(result.current.statuses).toEqual([row]));
131
70
  expect(result.current.isLoading).toBe(false);
71
+ expect(callsTo("GET /consent-responses/status")[0]?.params).toEqual({userId: "user 1"});
132
72
  });
133
73
 
134
- it("injects the endpoint once per api and base URL", () => {
135
- const {api, captured} = buildApi({data: {data: []}});
74
+ it("prefixes the base URL", async () => {
75
+ const {client, callsTo} = buildClient({status: {data: [row]}});
136
76
 
137
- renderHook(() => useProvisionalConsent({api, userId: "a"}));
138
- renderHook(() => useProvisionalConsent({api, userId: "b"}));
139
- renderHook(() => useProvisionalConsent({api, baseUrl: "/v2", userId: "a"}));
77
+ const {result} = renderHook(() => useProvisionalConsent({baseUrl: "/v2", client, userId: "a"}));
140
78
 
141
- expect(captured).toHaveLength(2);
142
- expect(captured[0].query("a")).toBe("/consent-responses/status?userId=a");
143
- expect(captured[1].query("a")).toBe("/v2/consent-responses/status?userId=a");
79
+ await waitFor(() => expect(result.current.statuses).toEqual([row]));
80
+ expect(callsTo("GET /v2/consent-responses/status")).toHaveLength(1);
144
81
  });
145
82
 
146
- it("defines the provisional sign mutation and invalidates statuses and pending consents", () => {
147
- const {api, capturedMutations} = buildApi({data: []});
148
- renderHook(() => useProvisionalConsent({api, baseUrl: "/api", userId: "a"}));
149
-
150
- expect(capturedMutations).toHaveLength(2);
151
- expect(capturedMutations[0].invalidatesTags).toEqual(["ConsentStatus", "PendingConsents"]);
152
- const body = {consentFormId: "form-1", note: "Phone", userId: "a"};
153
- expect(capturedMutations[0].query(body)).toEqual({
154
- body,
155
- method: "POST",
156
- url: "/api/consent-responses/provisional",
157
- });
83
+ it("accepts an unwrapped array response", async () => {
84
+ const {client} = buildClient({status: [row]});
85
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "a"}));
86
+ await waitFor(() => expect(result.current.statuses).toEqual([row]));
158
87
  });
159
88
 
160
- it("signs for the hook's user and unwraps the response envelope", async () => {
89
+ it("signs for the hook's user, unwraps the envelope, and refetches the statuses", async () => {
161
90
  const response = {_id: "response-1", agreedAt: "2026-10-20T15:30:00.000Z"};
162
- const {api, signedBodies} = buildApi({data: []}, () => Promise.resolve({data: response}));
163
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "member-1"}));
91
+ const {client, callsTo, signedBodies} = buildClient({
92
+ signResult: () => Promise.resolve({data: response}),
93
+ });
94
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "member-1"}));
95
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
164
96
 
165
97
  let signed: unknown;
166
98
  await act(async () => {
@@ -172,12 +104,13 @@ describe("useProvisionalConsent", () => {
172
104
  ]);
173
105
  expect(signed).toEqual(response);
174
106
  expect(result.current.isSigning).toBe(false);
107
+ await waitFor(() => expect(callsTo("GET /consent-responses/status").length).toBeGreaterThan(1));
175
108
  });
176
109
 
177
110
  it("returns an already-unwrapped sign response as is", async () => {
178
111
  const response = {_id: "response-2", agreedAt: "2026-10-20T15:30:00.000Z"};
179
- const {api} = buildApi({data: []}, () => Promise.resolve(response));
180
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "member-1"}));
112
+ const {client} = buildClient({signResult: () => Promise.resolve(response)});
113
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "member-1"}));
181
114
 
182
115
  let signed: unknown;
183
116
  await act(async () => {
@@ -187,55 +120,46 @@ describe("useProvisionalConsent", () => {
187
120
  });
188
121
 
189
122
  it("rejects with the server error when signing fails", async () => {
190
- const error = {data: {title: "Consent form is not active"}, status: 400};
191
- const {api} = buildApi({data: []}, () => Promise.reject(error));
192
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "member-1"}));
123
+ const error = fakeHttpError(400, "Consent form is not active");
124
+ const {client} = buildClient({signResult: () => Promise.reject(error)});
125
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "member-1"}));
193
126
 
194
- await expect(result.current.sign({consentFormId: "form-1", note: "Phone"})).rejects.toBe(error);
195
- });
196
-
197
- it("defines the void mutation for a response id", () => {
198
- const {api, capturedMutations} = buildApi({data: []});
199
- renderHook(() => useProvisionalConsent({api, baseUrl: "/api", userId: "a"}));
200
-
201
- expect(capturedMutations[1].invalidatesTags).toEqual(["ConsentStatus", "PendingConsents"]);
202
- expect(capturedMutations[1].query({reason: "Wrong member", responseId: "resp 1"})).toEqual({
203
- body: {reason: "Wrong member"},
204
- method: "POST",
205
- url: "/api/consent-responses/resp%201/void",
127
+ await act(async () => {
128
+ await expect(result.current.sign({consentFormId: "form-1", note: "Phone"})).rejects.toBe(
129
+ error
130
+ );
206
131
  });
207
132
  });
208
133
 
209
- it("voids a signature and unwraps the response", async () => {
134
+ it("voids a signature by response id, unwraps the response, and refetches", async () => {
210
135
  const response = {_id: "response-1", voidedAt: "2026-10-21T09:00:00.000Z"};
211
- const {api, voidedArgs} = buildApi({data: []}, undefined, () =>
212
- Promise.resolve({data: response})
213
- );
214
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "member-1"}));
136
+ const {callsTo, client, voidedArgs} = buildClient({
137
+ voidResult: () => Promise.resolve({data: response}),
138
+ });
139
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "member-1"}));
140
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
215
141
 
216
142
  let voided: unknown;
217
143
  await act(async () => {
218
- voided = await result.current.voidSignature({reason: "Wrong member", responseId: "r1"});
144
+ voided = await result.current.voidSignature({reason: "Wrong member", responseId: "resp 1"});
219
145
  });
220
146
 
221
- expect(voidedArgs).toEqual([{reason: "Wrong member", responseId: "r1"}]);
147
+ expect(voidedArgs).toEqual([{reason: "Wrong member", responseId: "resp%201"}]);
148
+ expect(callsTo("POST /consent-responses/:id/void")[0]?.url).toBe(
149
+ "/consent-responses/resp%201/void"
150
+ );
222
151
  expect(voided).toEqual(response);
223
152
  expect(result.current.isVoiding).toBe(false);
224
153
  });
225
154
 
226
- it("accepts an unwrapped array response", () => {
227
- const {api} = buildApi({data: [row]});
228
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "a"}));
229
- expect(result.current.statuses).toEqual([row]);
230
- });
155
+ it("returns no statuses while loading and passes the load error through", async () => {
156
+ const error = fakeHttpError(405, "Method not allowed");
157
+ const {client} = buildClient({status: () => Promise.reject(error)});
158
+ const {result} = renderHook(() => useProvisionalConsent({client, userId: "a"}));
231
159
 
232
- it("returns no statuses while loading and passes the error through", () => {
233
- const error = {status: 405};
234
- const {api} = buildApi({error, isLoading: true});
235
- const {result} = renderHook(() => useProvisionalConsent({api, userId: "a"}));
236
160
  expect(result.current.statuses).toEqual([]);
237
161
  expect(result.current.isLoading).toBe(true);
238
- expect(result.current.error).toBe(error);
162
+ await waitFor(() => expect(result.current.error).toBe(error));
239
163
  });
240
164
  });
241
165