@terreno/ui 0.30.0 → 56.0.0-beta.0

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 (118) hide show
  1. package/dist/ActionSheet.d.ts +1 -1
  2. package/dist/Avatar.js +1 -4
  3. package/dist/Avatar.js.map +1 -1
  4. package/dist/Box.js +45 -9
  5. package/dist/Box.js.map +1 -1
  6. package/dist/Common.d.ts +21 -0
  7. package/dist/Common.js.map +1 -1
  8. package/dist/ConflictSheet.d.ts +53 -0
  9. package/dist/ConflictSheet.js +132 -0
  10. package/dist/ConflictSheet.js.map +1 -0
  11. package/dist/DateTimeActionSheet.d.ts +2 -1
  12. package/dist/DecimalRangeActionSheet.d.ts +1 -1
  13. package/dist/EmojiSelector.d.ts +1 -1
  14. package/dist/ErrorPage.d.ts +1 -1
  15. package/dist/HeightActionSheet.d.ts +1 -1
  16. package/dist/Hyperlink.d.ts +2 -1
  17. package/dist/Hyperlink.js +2 -1
  18. package/dist/Hyperlink.js.map +1 -1
  19. package/dist/Image.d.ts +1 -1
  20. package/dist/ImageBackground.d.ts +1 -1
  21. package/dist/MobileAddressAutoComplete.d.ts +1 -1
  22. package/dist/NumberPickerActionSheet.d.ts +1 -1
  23. package/dist/Page.d.ts +3 -3
  24. package/dist/PickerSelect.d.ts +1 -1
  25. package/dist/SidebarNavigation.js +1 -1
  26. package/dist/SidebarNavigation.js.map +1 -1
  27. package/dist/SidebarNavigation.native.js +1 -1
  28. package/dist/SidebarNavigation.native.js.map +1 -1
  29. package/dist/SplitPage.d.ts +1 -1
  30. package/dist/SplitPage.js +1 -4
  31. package/dist/SplitPage.js.map +1 -1
  32. package/dist/SplitPage.native.d.ts +1 -1
  33. package/dist/SyncStatusBanner.d.ts +46 -0
  34. package/dist/SyncStatusBanner.js +29 -0
  35. package/dist/SyncStatusBanner.js.map +1 -0
  36. package/dist/Theme.d.ts +1 -1
  37. package/dist/Toast.d.ts +9 -1
  38. package/dist/Toast.js +20 -7
  39. package/dist/Toast.js.map +1 -1
  40. package/dist/ToastNotifications.js +23 -1
  41. package/dist/ToastNotifications.js.map +1 -1
  42. package/dist/UnifiedAddressAutoComplete.d.ts +1 -1
  43. package/dist/Unifier.js +1 -1
  44. package/dist/Unifier.js.map +1 -1
  45. package/dist/conflictFieldDiff.d.ts +14 -0
  46. package/dist/conflictFieldDiff.js +62 -0
  47. package/dist/conflictFieldDiff.js.map +1 -0
  48. package/dist/icons/OfflineIcon.d.ts +1 -1
  49. package/dist/icons/OnlineIcon.d.ts +1 -1
  50. package/dist/icons/OutOfficeIcon.d.ts +1 -1
  51. package/dist/index.d.ts +5 -2
  52. package/dist/index.js +5 -2
  53. package/dist/index.js.map +1 -1
  54. package/dist/pdfHtmlTemplate.d.ts +30 -0
  55. package/dist/pdfHtmlTemplate.js +170 -0
  56. package/dist/pdfHtmlTemplate.js.map +1 -0
  57. package/dist/table/TableTitle.js +1 -3
  58. package/dist/table/TableTitle.js.map +1 -1
  59. package/dist/useAppLaunchOrForeground.d.ts +9 -0
  60. package/dist/useAppLaunchOrForeground.js +27 -0
  61. package/dist/useAppLaunchOrForeground.js.map +1 -0
  62. package/package.json +44 -37
  63. package/src/Box.test.tsx +39 -9
  64. package/src/Box.tsx +46 -7
  65. package/src/Common.ts +21 -3
  66. package/src/ConflictSheet.test.tsx +461 -0
  67. package/src/ConflictSheet.tsx +399 -0
  68. package/src/DataTable.test.tsx +15 -21
  69. package/src/Hyperlink.tsx +1 -1
  70. package/src/SidebarNavigation.native.tsx +1 -1
  71. package/src/SidebarNavigation.tsx +1 -1
  72. package/src/SyncStatusBanner.test.tsx +204 -0
  73. package/src/SyncStatusBanner.tsx +148 -0
  74. package/src/TapToEdit.test.tsx +8 -14
  75. package/src/TerrenoProvider.test.tsx +3 -4
  76. package/src/Toast.test.tsx +60 -0
  77. package/src/Toast.tsx +46 -1
  78. package/src/ToastNotifications.test.tsx +82 -0
  79. package/src/ToastNotifications.tsx +25 -1
  80. package/src/Tooltip.test.tsx +1 -0
  81. package/src/Unifier.ts +1 -1
  82. package/src/__snapshots__/AiSuggestionBox.test.tsx.snap +0 -3
  83. package/src/__snapshots__/Body.test.tsx.snap +0 -16
  84. package/src/__snapshots__/Box.test.tsx.snap +4 -13
  85. package/src/__snapshots__/Page.test.tsx.snap +0 -84
  86. package/src/__snapshots__/SplitPage.test.tsx.snap +24 -120
  87. package/src/__snapshots__/TapToEdit.test.tsx.snap +5 -16
  88. package/src/__snapshots__/Toast.test.tsx.snap +4 -2
  89. package/src/bunSetup.ts +19 -0
  90. package/src/conflictFieldDiff.test.ts +26 -0
  91. package/src/conflictFieldDiff.ts +78 -0
  92. package/src/index.tsx +5 -2
  93. package/src/login/__snapshots__/LoginScreen.test.tsx.snap +0 -9
  94. package/src/pdfHtmlTemplate.ts +219 -0
  95. package/src/signUp/__snapshots__/OAuthButtons.test.tsx.snap +0 -1
  96. package/src/signUp/__snapshots__/PasswordRequirements.test.tsx.snap +2 -16
  97. package/src/signUp/__snapshots__/SignUpScreen.test.tsx.snap +1 -17
  98. package/src/signUp/__snapshots__/Swiper.test.tsx.snap +0 -1
  99. package/src/table/__snapshots__/Table.test.tsx.snap +22 -87
  100. package/src/table/__snapshots__/TableHeader.test.tsx.snap +10 -50
  101. package/src/table/__snapshots__/TableHeaderCell.test.tsx.snap +10 -84
  102. package/src/table/__snapshots__/TableRow.test.tsx.snap +12 -77
  103. package/src/useAppLaunchOrForeground.test.tsx +54 -0
  104. package/src/useAppLaunchOrForeground.ts +30 -0
  105. package/dist/ConsentHistory.d.ts +0 -9
  106. package/dist/ConsentHistory.js +0 -70
  107. package/dist/ConsentHistory.js.map +0 -1
  108. package/dist/generateConsentHistoryPdf.d.ts +0 -2
  109. package/dist/generateConsentHistoryPdf.js +0 -185
  110. package/dist/generateConsentHistoryPdf.js.map +0 -1
  111. package/dist/useConsentHistory.d.ts +0 -63
  112. package/dist/useConsentHistory.js +0 -40
  113. package/dist/useConsentHistory.js.map +0 -1
  114. package/src/ConsentHistory.test.tsx +0 -161
  115. package/src/ConsentHistory.tsx +0 -249
  116. package/src/generateConsentHistoryPdf.ts +0 -211
  117. package/src/useConsentHistory.test.ts +0 -106
  118. package/src/useConsentHistory.ts +0 -94
@@ -1,249 +0,0 @@
1
- import {DateTime} from "luxon";
2
- import React, {useCallback, useState} from "react";
3
- import {Image, Pressable} from "react-native";
4
-
5
- import {Badge} from "./Badge";
6
- import {Box} from "./Box";
7
- import {Button} from "./Button";
8
- import {Card} from "./Card";
9
- import {generateConsentHistoryPdf} from "./generateConsentHistoryPdf";
10
- import {Icon} from "./Icon";
11
- import {IconButton} from "./IconButton";
12
- import {MarkdownView} from "./MarkdownView";
13
- import {Page} from "./Page";
14
- import {Spinner} from "./Spinner";
15
- import {Text} from "./Text";
16
- import type {ConsentHistoryEntry} from "./useConsentHistory";
17
- import {useConsentHistory} from "./useConsentHistory";
18
-
19
- interface ConsentHistoryProps {
20
- api: Parameters<typeof useConsentHistory>[0];
21
- baseUrl?: string;
22
- title?: string;
23
- }
24
-
25
- const formatDate = (value: unknown): string => {
26
- if (!value) {
27
- return "";
28
- }
29
- const dt = DateTime.fromISO(String(value));
30
- if (!dt.isValid) {
31
- return String(value);
32
- }
33
- return dt.toLocaleString(DateTime.DATETIME_MED);
34
- };
35
-
36
- const ConsentHistoryItem: React.FC<{entry: ConsentHistoryEntry}> = ({entry}) => {
37
- const [expanded, setExpanded] = useState(false);
38
- const [isDownloading, setIsDownloading] = useState(false);
39
-
40
- const toggle = useCallback(() => {
41
- setExpanded((prev) => !prev);
42
- }, []);
43
-
44
- const handleDownload = useCallback(async () => {
45
- setIsDownloading(true);
46
- try {
47
- await generateConsentHistoryPdf(entry);
48
- } catch (err) {
49
- console.error("Failed to generate PDF", err);
50
- } finally {
51
- setIsDownloading(false);
52
- }
53
- }, [entry]);
54
-
55
- const formTitle = entry.form?.title ?? "Unknown Form";
56
- const formType = entry.form?.type ?? "";
57
-
58
- const checkboxEntries =
59
- entry.checkboxValues && typeof entry.checkboxValues === "object"
60
- ? Object.entries(entry.checkboxValues)
61
- : [];
62
-
63
- return (
64
- <Card padding={0} testID={`consent-history-item-${entry._id}`}>
65
- <Pressable onPress={toggle} testID={`consent-history-item-toggle-${entry._id}`}>
66
- <Box direction="row" gap={3} padding={4}>
67
- <Box flex="grow" gap={1}>
68
- <Box alignItems="center" direction="row" gap={2}>
69
- <Text bold size="md">
70
- {formTitle}
71
- </Text>
72
- {formType ? <Badge status="neutral" value={formType} /> : null}
73
- </Box>
74
- <Box alignItems="center" direction="row" gap={2}>
75
- <Badge
76
- status={entry.agreed ? "success" : "error"}
77
- value={entry.agreed ? "Agreed" : "Declined"}
78
- />
79
- <Text color="secondaryDark" size="sm">
80
- {formatDate(entry.agreedAt)}
81
- </Text>
82
- </Box>
83
- </Box>
84
- <Box alignItems="center" justifyContent="center">
85
- <Icon
86
- color="secondaryDark"
87
- iconName={expanded ? "chevron-up" : "chevron-down"}
88
- size="sm"
89
- />
90
- </Box>
91
- </Box>
92
- </Pressable>
93
-
94
- {expanded && (
95
- <Box gap={3} padding={4} testID={`consent-history-item-details-${entry._id}`}>
96
- <Box alignItems="center" direction="row" justifyContent="between">
97
- <Box color="disabled" flex="grow" height={1} />
98
- <Box marginLeft={2}>
99
- <IconButton
100
- accessibilityLabel="Download PDF"
101
- iconName="download"
102
- loading={isDownloading}
103
- onClick={handleDownload}
104
- testID={`consent-history-download-${entry._id}`}
105
- tooltipText="Download PDF"
106
- />
107
- </Box>
108
- </Box>
109
-
110
- {entry.form?.version !== undefined && (
111
- <Box alignItems="center" direction="row" gap={2}>
112
- <Text color="secondaryDark" size="sm">
113
- Version:
114
- </Text>
115
- <Text size="sm">{entry.form.version}</Text>
116
- </Box>
117
- )}
118
-
119
- {entry.locale && (
120
- <Box alignItems="center" direction="row" gap={2}>
121
- <Text color="secondaryDark" size="sm">
122
- Locale:
123
- </Text>
124
- <Text size="sm">{entry.locale}</Text>
125
- </Box>
126
- )}
127
-
128
- {entry.signedAt && (
129
- <Box alignItems="center" direction="row" gap={2}>
130
- <Text color="secondaryDark" size="sm">
131
- Signed:
132
- </Text>
133
- <Text size="sm">{formatDate(entry.signedAt)}</Text>
134
- </Box>
135
- )}
136
-
137
- {entry.ipAddress && (
138
- <Box alignItems="center" direction="row" gap={2}>
139
- <Text color="secondaryDark" size="sm">
140
- IP Address:
141
- </Text>
142
- <Text size="sm">{entry.ipAddress}</Text>
143
- </Box>
144
- )}
145
-
146
- {checkboxEntries.length > 0 && (
147
- <Box gap={2}>
148
- <Text bold color="secondaryDark" size="sm">
149
- Checkboxes
150
- </Text>
151
- {checkboxEntries.map(([index, checked]) => {
152
- const label = entry.form?.checkboxes?.[Number(index)]?.label;
153
- return (
154
- <Box alignItems="center" direction="row" gap={2} key={index}>
155
- <Badge
156
- status={checked ? "success" : "neutral"}
157
- value={checked ? "Yes" : "No"}
158
- />
159
- <Text size="sm">{label ?? `Checkbox ${index}`}</Text>
160
- </Box>
161
- );
162
- })}
163
- </Box>
164
- )}
165
-
166
- {entry.signature && (
167
- <Box gap={2}>
168
- <Text bold color="secondaryDark" size="sm">
169
- Signature
170
- </Text>
171
- <Box border="default" padding={2} rounding="sm">
172
- <Image
173
- accessibilityLabel="Your signature"
174
- accessible
175
- resizeMode="contain"
176
- source={{uri: entry.signature}}
177
- style={{height: 80, width: "100%"}}
178
- testID={`consent-history-signature-${entry._id}`}
179
- />
180
- </Box>
181
- </Box>
182
- )}
183
-
184
- {entry.contentSnapshot && (
185
- <Box gap={2}>
186
- <Text bold color="secondaryDark" size="sm">
187
- Form Content
188
- </Text>
189
- <Box border="default" padding={3} rounding="sm">
190
- <MarkdownView>{entry.contentSnapshot}</MarkdownView>
191
- </Box>
192
- </Box>
193
- )}
194
- </Box>
195
- )}
196
- </Card>
197
- );
198
- };
199
-
200
- export const ConsentHistory: React.FC<ConsentHistoryProps> = ({
201
- api,
202
- baseUrl,
203
- title = "My Consents",
204
- }) => {
205
- const {entries, isLoading, error, refetch} = useConsentHistory(api, baseUrl);
206
-
207
- if (isLoading) {
208
- return (
209
- <Page maxWidth={800} title={title}>
210
- <Box alignItems="center" justifyContent="center" padding={6}>
211
- <Spinner />
212
- </Box>
213
- </Page>
214
- );
215
- }
216
-
217
- if (error) {
218
- return (
219
- <Page maxWidth={800} title={title}>
220
- <Box alignItems="center" direction="column" gap={3} padding={6}>
221
- <Text color="error" size="lg">
222
- Failed to load consent history
223
- </Text>
224
- <Button onClick={refetch} text="Retry" />
225
- </Box>
226
- </Page>
227
- );
228
- }
229
-
230
- if (entries.length === 0) {
231
- return (
232
- <Page maxWidth={800} title={title}>
233
- <Box alignItems="center" padding={6}>
234
- <Text color="secondaryDark">No consent records found.</Text>
235
- </Box>
236
- </Page>
237
- );
238
- }
239
-
240
- return (
241
- <Page maxWidth={800} scroll title={title}>
242
- <Box gap={3} padding={4} testID="consent-history-list">
243
- {entries.map((entry) => (
244
- <ConsentHistoryItem entry={entry} key={entry._id} />
245
- ))}
246
- </Box>
247
- </Page>
248
- );
249
- };
@@ -1,211 +0,0 @@
1
- import {jsPDF} from "jspdf";
2
- import {DateTime} from "luxon";
3
-
4
- import type {ConsentHistoryEntry} from "./useConsentHistory";
5
-
6
- const PAGE_WIDTH = 210;
7
- const MARGIN_LEFT = 20;
8
- const MARGIN_RIGHT = 20;
9
- const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
10
- const PAGE_HEIGHT = 297;
11
- const MARGIN_BOTTOM = 20;
12
-
13
- const formatDate = (value: unknown): string => {
14
- if (!value) {
15
- return "";
16
- }
17
- const dt = DateTime.fromISO(String(value));
18
- if (!dt.isValid) {
19
- return String(value);
20
- }
21
- return dt.toLocaleString(DateTime.DATETIME_FULL);
22
- };
23
-
24
- const ensureSpace = (doc: jsPDF, y: number, needed: number): number => {
25
- if (y + needed > PAGE_HEIGHT - MARGIN_BOTTOM) {
26
- doc.addPage();
27
- return 20;
28
- }
29
- return y;
30
- };
31
-
32
- export const generateConsentHistoryPdf = async (entry: ConsentHistoryEntry): Promise<void> => {
33
- const doc = new jsPDF({format: "a4", orientation: "portrait", unit: "mm"});
34
-
35
- const formTitle = entry.form?.title ?? "Unknown Form";
36
- const formSlug = entry.form?.slug ?? "";
37
- const formType = entry.form?.type ?? "";
38
- const formVersion = entry.form?.version ?? entry.formVersionSnapshot;
39
-
40
- let y = 20;
41
-
42
- // Title
43
- doc.setFontSize(18);
44
- doc.setFont("helvetica", "bold");
45
- doc.text("Consent Record", MARGIN_LEFT, y);
46
- y += 10;
47
-
48
- // Form title
49
- doc.setFontSize(14);
50
- doc.setFont("helvetica", "normal");
51
- doc.text(formTitle, MARGIN_LEFT, y);
52
- y += 10;
53
-
54
- // Separator
55
- doc.setDrawColor(200, 200, 200);
56
- doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
57
- y += 8;
58
-
59
- // Helper to add a labeled field
60
- const addField = (label: string, value: string) => {
61
- y = ensureSpace(doc, y, 8);
62
- doc.setFontSize(9);
63
- doc.setFont("helvetica", "bold");
64
- doc.setTextColor(100, 100, 100);
65
- doc.text(label, MARGIN_LEFT, y);
66
- doc.setFont("helvetica", "normal");
67
- doc.setTextColor(0, 0, 0);
68
- doc.setFontSize(10);
69
- doc.text(value, MARGIN_LEFT + 45, y);
70
- y += 6;
71
- };
72
-
73
- // Response Details
74
- doc.setFontSize(12);
75
- doc.setFont("helvetica", "bold");
76
- doc.setTextColor(0, 0, 0);
77
- doc.text("Response Details", MARGIN_LEFT, y);
78
- y += 8;
79
-
80
- if (formSlug) {
81
- addField("Form Slug:", formSlug);
82
- }
83
- if (formType) {
84
- addField("Form Type:", formType);
85
- }
86
- if (formVersion !== undefined) {
87
- addField("Form Version:", String(formVersion));
88
- }
89
- addField("Decision:", entry.agreed ? "Agreed" : "Declined");
90
- if (entry.agreedAt) {
91
- addField("Agreed At:", formatDate(entry.agreedAt));
92
- }
93
- if (entry.locale) {
94
- addField("Locale:", entry.locale);
95
- }
96
-
97
- y += 4;
98
-
99
- // Checkbox Values
100
- const checkboxEntries =
101
- entry.checkboxValues && typeof entry.checkboxValues === "object"
102
- ? Object.entries(entry.checkboxValues)
103
- : [];
104
-
105
- if (checkboxEntries.length > 0) {
106
- y = ensureSpace(doc, y, 12 + checkboxEntries.length * 6);
107
- doc.setFontSize(12);
108
- doc.setFont("helvetica", "bold");
109
- doc.setTextColor(0, 0, 0);
110
- doc.text("Checkbox Responses", MARGIN_LEFT, y);
111
- y += 8;
112
-
113
- for (const [index, checked] of checkboxEntries) {
114
- y = ensureSpace(doc, y, 6);
115
- doc.setFontSize(10);
116
- doc.setFont("helvetica", "normal");
117
- const label = entry.form?.checkboxes?.[Number(index)]?.label;
118
- const checkmark = checked ? "[x]" : "[ ]";
119
- doc.text(`${checkmark} ${label ?? `Checkbox ${index}`}`, MARGIN_LEFT + 4, y);
120
- y += 6;
121
- }
122
- y += 4;
123
- }
124
-
125
- // Audit Trail
126
- const hasAuditTrail = entry.ipAddress || entry.userAgent || entry.formVersionSnapshot;
127
-
128
- if (hasAuditTrail) {
129
- y = ensureSpace(doc, y, 20);
130
- doc.setFontSize(12);
131
- doc.setFont("helvetica", "bold");
132
- doc.setTextColor(0, 0, 0);
133
- doc.text("Audit Trail", MARGIN_LEFT, y);
134
- y += 8;
135
-
136
- if (entry.ipAddress) {
137
- addField("IP Address:", entry.ipAddress);
138
- }
139
- if (entry.userAgent) {
140
- addField("User Agent:", entry.userAgent);
141
- }
142
- if (entry.formVersionSnapshot !== undefined) {
143
- addField("Form Version:", String(entry.formVersionSnapshot));
144
- }
145
- if (entry.signedAt) {
146
- addField("Signed At:", formatDate(entry.signedAt));
147
- }
148
- y += 4;
149
- }
150
-
151
- // Signature
152
- if (entry.signature) {
153
- y = ensureSpace(doc, y, 50);
154
- doc.setFontSize(12);
155
- doc.setFont("helvetica", "bold");
156
- doc.setTextColor(0, 0, 0);
157
- doc.text("Signature", MARGIN_LEFT, y);
158
- y += 6;
159
-
160
- try {
161
- const format = entry.signature.includes("image/png") ? "PNG" : "JPEG";
162
- doc.addImage(entry.signature, format, MARGIN_LEFT, y, 80, 30);
163
- y += 34;
164
- } catch {
165
- doc.setFontSize(10);
166
- doc.setFont("helvetica", "italic");
167
- doc.text("(Signature image could not be embedded)", MARGIN_LEFT, y);
168
- y += 6;
169
- }
170
- y += 4;
171
- }
172
-
173
- // Content Snapshot
174
- if (entry.contentSnapshot) {
175
- y = ensureSpace(doc, y, 20);
176
- doc.setFontSize(12);
177
- doc.setFont("helvetica", "bold");
178
- doc.setTextColor(0, 0, 0);
179
- doc.text("Content Snapshot", MARGIN_LEFT, y);
180
- y += 8;
181
-
182
- doc.setFontSize(9);
183
- doc.setFont("helvetica", "normal");
184
- doc.setTextColor(50, 50, 50);
185
-
186
- const lines = doc.splitTextToSize(entry.contentSnapshot, CONTENT_WIDTH);
187
- for (const line of lines) {
188
- y = ensureSpace(doc, y, 5);
189
- doc.text(line, MARGIN_LEFT, y);
190
- y += 4;
191
- }
192
- }
193
-
194
- // Footer
195
- y = ensureSpace(doc, y, 20);
196
- y += 8;
197
- doc.setDrawColor(200, 200, 200);
198
- doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
199
- y += 6;
200
- doc.setFontSize(8);
201
- doc.setFont("helvetica", "italic");
202
- doc.setTextColor(150, 150, 150);
203
- doc.text(`Generated ${DateTime.now().toLocaleString(DateTime.DATETIME_FULL)}`, MARGIN_LEFT, y);
204
- if (entry._id) {
205
- doc.text(`Response ID: ${entry._id}`, PAGE_WIDTH - MARGIN_RIGHT, y, {align: "right"});
206
- }
207
-
208
- // Download
209
- const filename = `consent-${formSlug || "response"}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
210
- doc.save(filename);
211
- };
@@ -1,106 +0,0 @@
1
- import {describe, expect, it, mock} from "bun:test";
2
- import {renderHook} from "@testing-library/react-native";
3
-
4
- import type {ConsentHistoryEntry} from "./useConsentHistory";
5
- import {useConsentHistory} from "./useConsentHistory";
6
-
7
- type ConsentHistoryApi = Parameters<typeof useConsentHistory>[0];
8
-
9
- interface MockQueryDef {
10
- query: () => string;
11
- providesTags: string[];
12
- }
13
-
14
- interface MockInjectOpts {
15
- endpoints: (build: {query: (def: MockQueryDef) => string}) => Record<string, unknown>;
16
- }
17
-
18
- describe("useConsentHistory", () => {
19
- const buildApi = (queryResult: {data?: unknown; error?: unknown; isLoading?: boolean}) => {
20
- const refetch = mock(() => {});
21
- const useGetMyConsentsQuery = mock(() => ({
22
- data: queryResult.data,
23
- error: queryResult.error,
24
- isLoading: queryResult.isLoading ?? false,
25
- refetch,
26
- }));
27
- const api = {
28
- enhanceEndpoints: mock((opts: {addTagTypes: string[]}) => {
29
- expect(opts.addTagTypes).toContain("MyConsents");
30
- return {
31
- injectEndpoints: mock((injectOpts: MockInjectOpts) => {
32
- const build = {
33
- query: mock((def: MockQueryDef) => {
34
- // Exercise the URL builder so the closure captures `base`
35
- const url = def.query();
36
- expect(url).toContain("/consents/my");
37
- return "my-consents-query";
38
- }),
39
- };
40
- injectOpts.endpoints(build);
41
- return {useGetMyConsentsQuery};
42
- }),
43
- };
44
- }),
45
- };
46
- return {api, refetch};
47
- };
48
-
49
- it("returns an array of entries when response is an array", () => {
50
- const {api} = buildApi({
51
- data: [{_id: "1", agreed: true} as unknown as ConsentHistoryEntry],
52
- });
53
- const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
54
- expect(Array.isArray(result.current.entries)).toBe(true);
55
- expect(result.current.entries).toHaveLength(1);
56
- });
57
-
58
- it("unwraps .data property when response is object shape", () => {
59
- const {api} = buildApi({
60
- data: {data: [{_id: "2", agreed: false} as unknown as ConsentHistoryEntry]},
61
- });
62
- const {result} = renderHook(() =>
63
- useConsentHistory(api as unknown as ConsentHistoryApi, "/api")
64
- );
65
- expect(Array.isArray(result.current.entries)).toBe(true);
66
- expect(result.current.entries).toHaveLength(1);
67
- });
68
-
69
- it("returns empty array when no data is present", () => {
70
- const {api} = buildApi({data: undefined, isLoading: true});
71
- const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
72
- expect(result.current.entries).toEqual([]);
73
- expect(result.current.isLoading).toBe(true);
74
- });
75
-
76
- it("surfaces error from the query hook", () => {
77
- const {api} = buildApi({data: undefined, error: "boom"});
78
- const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
79
- expect(result.current.error).toBe("boom");
80
- });
81
-
82
- it("injects the my-consents endpoint only once per (api, baseUrl)", () => {
83
- let injectCallCount = 0;
84
- const refetch = mock(() => {});
85
- const useGetMyConsentsQuery = mock(() => ({
86
- data: undefined,
87
- error: undefined,
88
- isLoading: false,
89
- refetch,
90
- }));
91
- const api = {
92
- enhanceEndpoints: () => ({
93
- injectEndpoints: () => {
94
- injectCallCount += 1;
95
- return {useGetMyConsentsQuery};
96
- },
97
- }),
98
- };
99
- const {rerender} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
100
- rerender(undefined);
101
- rerender(undefined);
102
- // The hook reuses the cached enhanced api after the first render so the
103
- // dev-mode RTK warning about re-injecting endpoints never fires.
104
- expect(injectCallCount).toBe(1);
105
- });
106
- });
@@ -1,94 +0,0 @@
1
- export interface ConsentHistoryEntry {
2
- _id: string;
3
- agreed: boolean;
4
- agreedAt: string;
5
- checkboxValues?: Record<string, boolean>;
6
- contentSnapshot?: string;
7
- form: {
8
- captureSignature: boolean;
9
- checkboxes: Array<{label: string; required: boolean; confirmationPrompt?: string}>;
10
- slug: string;
11
- title: string;
12
- type: string;
13
- version: number;
14
- } | null;
15
- formVersionSnapshot?: number;
16
- ipAddress?: string;
17
- locale?: string;
18
- signature?: string;
19
- signedAt?: string;
20
- userAgent?: string;
21
- }
22
-
23
- interface ConsentHistoryResponse {
24
- data?: ConsentHistoryEntry[];
25
- }
26
-
27
- interface ConsentHistoryQueryBuilder {
28
- query: (options: {providesTags: string[]; query: () => string}) => unknown;
29
- }
30
-
31
- interface ConsentHistoryHookState {
32
- data?: ConsentHistoryEntry[] | ConsentHistoryResponse;
33
- error: unknown;
34
- isLoading: boolean;
35
- refetch: () => void | Promise<void>;
36
- }
37
-
38
- interface ConsentHistoryEnhancedApi {
39
- useGetMyConsentsQuery: () => ConsentHistoryHookState;
40
- }
41
-
42
- interface ConsentHistoryApiWithTags {
43
- injectEndpoints: (options: {
44
- endpoints: (build: ConsentHistoryQueryBuilder) => {getMyConsents: unknown};
45
- overrideExisting: boolean;
46
- }) => ConsentHistoryEnhancedApi;
47
- }
48
-
49
- interface ConsentHistoryApi {
50
- enhanceEndpoints: (options: {addTagTypes: string[]}) => ConsentHistoryApiWithTags;
51
- }
52
-
53
- /**
54
- * Cache the enhanced api per (api, baseUrl). `injectEndpoints` logs a console
55
- * error in development whenever an endpoint with the same name is re-injected
56
- * (with `overrideExisting: false`), so calling it on every render of every
57
- * consumer would flood the console. WeakMap-by-api lets the GC reclaim entries
58
- * when the api object is unreachable.
59
- */
60
- const enhancedApiCache = new WeakMap<ConsentHistoryApi, Map<string, ConsentHistoryEnhancedApi>>();
61
-
62
- const getEnhancedApi = (api: ConsentHistoryApi, base: string): ConsentHistoryEnhancedApi => {
63
- let byBase = enhancedApiCache.get(api);
64
- if (!byBase) {
65
- byBase = new Map();
66
- enhancedApiCache.set(api, byBase);
67
- }
68
- const cached = byBase.get(base);
69
- if (cached) {
70
- return cached;
71
- }
72
- const apiWithConsentTags = api.enhanceEndpoints({addTagTypes: ["MyConsents"]});
73
- const enhanced = apiWithConsentTags.injectEndpoints({
74
- endpoints: (build) => ({
75
- getMyConsents: build.query({
76
- providesTags: ["MyConsents"],
77
- query: () => `${base}/consents/my`,
78
- }),
79
- }),
80
- overrideExisting: false,
81
- });
82
- byBase.set(base, enhanced);
83
- return enhanced;
84
- };
85
-
86
- export const useConsentHistory = (api: ConsentHistoryApi, baseUrl?: string) => {
87
- const base = baseUrl || "";
88
- const enhancedApi = getEnhancedApi(api, base);
89
-
90
- const {data, isLoading, error, refetch} = enhancedApi.useGetMyConsentsQuery();
91
- const entries: ConsentHistoryEntry[] = Array.isArray(data) ? data : (data?.data ?? []);
92
-
93
- return {entries, error, isLoading, refetch};
94
- };