@prenta/admin 2.9.3 → 2.11.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 (283) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/dist/AdminRoot.d.ts.map +1 -1
  3. package/dist/AdminRoot.js +5 -3
  4. package/dist/AdminRoot.js.map +1 -1
  5. package/dist/__tests__/components/attribution-rows.test.js +1 -1
  6. package/dist/__tests__/components/attribution-rows.test.js.map +1 -1
  7. package/dist/__tests__/components/date-range-picker.test.d.ts +2 -0
  8. package/dist/__tests__/components/date-range-picker.test.d.ts.map +1 -0
  9. package/dist/__tests__/components/date-range-picker.test.js +59 -0
  10. package/dist/__tests__/components/date-range-picker.test.js.map +1 -0
  11. package/dist/__tests__/components/form-build-model.test.d.ts +2 -0
  12. package/dist/__tests__/components/form-build-model.test.d.ts.map +1 -0
  13. package/dist/__tests__/components/form-build-model.test.js +162 -0
  14. package/dist/__tests__/components/form-build-model.test.js.map +1 -0
  15. package/dist/__tests__/components/form-build.test.d.ts +2 -0
  16. package/dist/__tests__/components/form-build.test.d.ts.map +1 -0
  17. package/dist/__tests__/components/form-build.test.js +120 -0
  18. package/dist/__tests__/components/form-build.test.js.map +1 -0
  19. package/dist/__tests__/components/qa-a11y.render.test.js +1 -17
  20. package/dist/__tests__/components/qa-a11y.render.test.js.map +1 -1
  21. package/dist/__tests__/lib/batch-wizard.test.js +2 -0
  22. package/dist/__tests__/lib/batch-wizard.test.js.map +1 -1
  23. package/dist/__tests__/lib/forms-settings-normalize.test.d.ts +2 -0
  24. package/dist/__tests__/lib/forms-settings-normalize.test.d.ts.map +1 -0
  25. package/dist/__tests__/lib/forms-settings-normalize.test.js +16 -0
  26. package/dist/__tests__/lib/forms-settings-normalize.test.js.map +1 -0
  27. package/dist/__tests__/lib/recaptcha.test.d.ts +2 -0
  28. package/dist/__tests__/lib/recaptcha.test.d.ts.map +1 -0
  29. package/dist/__tests__/lib/recaptcha.test.js +57 -0
  30. package/dist/__tests__/lib/recaptcha.test.js.map +1 -0
  31. package/dist/__tests__/views/dashboard.test.js +105 -30
  32. package/dist/__tests__/views/dashboard.test.js.map +1 -1
  33. package/dist/__tests__/views/form-editor.render.test.js +17 -9
  34. package/dist/__tests__/views/form-editor.render.test.js.map +1 -1
  35. package/dist/__tests__/views/form-entries.render.test.js +23 -9
  36. package/dist/__tests__/views/form-entries.render.test.js.map +1 -1
  37. package/dist/__tests__/views/form-submissions.render.test.js +13 -14
  38. package/dist/__tests__/views/form-submissions.render.test.js.map +1 -1
  39. package/dist/__tests__/views/forms-list.render.test.js +139 -16
  40. package/dist/__tests__/views/forms-list.render.test.js.map +1 -1
  41. package/dist/__tests__/views/forms-settings.fixture.d.ts +3 -0
  42. package/dist/__tests__/views/forms-settings.fixture.d.ts.map +1 -0
  43. package/dist/__tests__/views/forms-settings.fixture.js +31 -0
  44. package/dist/__tests__/views/forms-settings.fixture.js.map +1 -0
  45. package/dist/__tests__/views/forms-settings.render.test.d.ts +2 -0
  46. package/dist/__tests__/views/forms-settings.render.test.d.ts.map +1 -0
  47. package/dist/__tests__/views/forms-settings.render.test.js +226 -0
  48. package/dist/__tests__/views/forms-settings.render.test.js.map +1 -0
  49. package/dist/__tests__/views/inbox-format.test.d.ts +2 -0
  50. package/dist/__tests__/views/inbox-format.test.d.ts.map +1 -0
  51. package/dist/__tests__/views/inbox-format.test.js +47 -0
  52. package/dist/__tests__/views/inbox-format.test.js.map +1 -0
  53. package/dist/__tests__/views/jobs-wizard.render.test.js +17 -3
  54. package/dist/__tests__/views/jobs-wizard.render.test.js.map +1 -1
  55. package/dist/__tests__/views/login-captcha.render.test.d.ts +2 -0
  56. package/dist/__tests__/views/login-captcha.render.test.d.ts.map +1 -0
  57. package/dist/__tests__/views/login-captcha.render.test.js +80 -0
  58. package/dist/__tests__/views/login-captcha.render.test.js.map +1 -0
  59. package/dist/__tests__/views/onboarding-block.render.test.js +9 -7
  60. package/dist/__tests__/views/onboarding-block.render.test.js.map +1 -1
  61. package/dist/components/forms/BlocklistDialog.d.ts +19 -0
  62. package/dist/components/forms/BlocklistDialog.d.ts.map +1 -0
  63. package/dist/components/forms/BlocklistDialog.js +225 -0
  64. package/dist/components/forms/BlocklistDialog.js.map +1 -0
  65. package/dist/components/forms/ExportMenu.d.ts +3 -1
  66. package/dist/components/forms/ExportMenu.d.ts.map +1 -1
  67. package/dist/components/forms/ExportMenu.js +2 -2
  68. package/dist/components/forms/ExportMenu.js.map +1 -1
  69. package/dist/components/forms/FieldOptions.d.ts +11 -0
  70. package/dist/components/forms/FieldOptions.d.ts.map +1 -0
  71. package/dist/components/forms/FieldOptions.js +106 -0
  72. package/dist/components/forms/FieldOptions.js.map +1 -0
  73. package/dist/components/forms/FormBuild.d.ts +11 -0
  74. package/dist/components/forms/FormBuild.d.ts.map +1 -0
  75. package/dist/components/forms/FormBuild.js +299 -0
  76. package/dist/components/forms/FormBuild.js.map +1 -0
  77. package/dist/components/forms/FormsListTable.d.ts +14 -0
  78. package/dist/components/forms/FormsListTable.d.ts.map +1 -0
  79. package/dist/components/forms/FormsListTable.js +84 -0
  80. package/dist/components/forms/FormsListTable.js.map +1 -0
  81. package/dist/components/forms/form-build-model.d.ts +74 -0
  82. package/dist/components/forms/form-build-model.d.ts.map +1 -0
  83. package/dist/components/forms/form-build-model.js +297 -0
  84. package/dist/components/forms/form-build-model.js.map +1 -0
  85. package/dist/components/forms/form-build-ui.d.ts +35 -0
  86. package/dist/components/forms/form-build-ui.d.ts.map +1 -0
  87. package/dist/components/forms/form-build-ui.js +59 -0
  88. package/dist/components/forms/form-build-ui.js.map +1 -0
  89. package/dist/components/forms/primitives.d.ts +3 -22
  90. package/dist/components/forms/primitives.d.ts.map +1 -1
  91. package/dist/components/forms/primitives.js +4 -19
  92. package/dist/components/forms/primitives.js.map +1 -1
  93. package/dist/components/ui/Badge.d.ts +1 -1
  94. package/dist/components/ui/Card.d.ts +1 -1
  95. package/dist/components/ui/DateRangePicker.d.ts +7 -0
  96. package/dist/components/ui/DateRangePicker.d.ts.map +1 -0
  97. package/dist/components/ui/DateRangePicker.js +112 -0
  98. package/dist/components/ui/DateRangePicker.js.map +1 -0
  99. package/dist/components/ui/Input.d.ts +1 -1
  100. package/dist/components/ui/Segmented.d.ts +3 -1
  101. package/dist/components/ui/Segmented.d.ts.map +1 -1
  102. package/dist/components/ui/Segmented.js +3 -3
  103. package/dist/components/ui/Segmented.js.map +1 -1
  104. package/dist/components/ui/StatusBadge.d.ts +3 -2
  105. package/dist/components/ui/StatusBadge.d.ts.map +1 -1
  106. package/dist/components/ui/StatusBadge.js +9 -3
  107. package/dist/components/ui/StatusBadge.js.map +1 -1
  108. package/dist/components/ui/Toggle.d.ts +1 -1
  109. package/dist/components/ui/Toggle.d.ts.map +1 -1
  110. package/dist/components/ui/Toggle.js +3 -0
  111. package/dist/components/ui/Toggle.js.map +1 -1
  112. package/dist/components/ui/UnderlineTabs.d.ts +5 -1
  113. package/dist/components/ui/UnderlineTabs.d.ts.map +1 -1
  114. package/dist/components/ui/UnderlineTabs.js +14 -11
  115. package/dist/components/ui/UnderlineTabs.js.map +1 -1
  116. package/dist/layout/Sidebar.js +3 -1
  117. package/dist/layout/Sidebar.js.map +1 -1
  118. package/dist/lib/batch-wizard.d.ts +1 -1
  119. package/dist/lib/batch-wizard.d.ts.map +1 -1
  120. package/dist/lib/batch-wizard.js +2 -2
  121. package/dist/lib/batch-wizard.js.map +1 -1
  122. package/dist/lib/entry-attribution.d.ts +13 -0
  123. package/dist/lib/entry-attribution.d.ts.map +1 -0
  124. package/dist/lib/entry-attribution.js +81 -0
  125. package/dist/lib/entry-attribution.js.map +1 -0
  126. package/dist/lib/forms-service.d.ts +133 -0
  127. package/dist/lib/forms-service.d.ts.map +1 -1
  128. package/dist/lib/forms-service.js +119 -0
  129. package/dist/lib/forms-service.js.map +1 -1
  130. package/dist/lib/job-drawer.d.ts +1 -0
  131. package/dist/lib/job-drawer.d.ts.map +1 -1
  132. package/dist/lib/job-drawer.js +23 -1
  133. package/dist/lib/job-drawer.js.map +1 -1
  134. package/dist/lib/job-view.d.ts +6 -0
  135. package/dist/lib/job-view.d.ts.map +1 -1
  136. package/dist/lib/job-view.js +7 -0
  137. package/dist/lib/job-view.js.map +1 -1
  138. package/dist/lib/recaptcha.d.ts +8 -0
  139. package/dist/lib/recaptcha.d.ts.map +1 -0
  140. package/dist/lib/recaptcha.js +73 -0
  141. package/dist/lib/recaptcha.js.map +1 -0
  142. package/dist/prenta-admin.css +1 -1
  143. package/dist/router/admin-routes.d.ts.map +1 -1
  144. package/dist/router/admin-routes.js +1 -0
  145. package/dist/router/admin-routes.js.map +1 -1
  146. package/dist/views/Dashboard.d.ts.map +1 -1
  147. package/dist/views/Dashboard.js +438 -309
  148. package/dist/views/Dashboard.js.map +1 -1
  149. package/dist/views/FormEditor.d.ts.map +1 -1
  150. package/dist/views/FormEditor.js +68 -13
  151. package/dist/views/FormEditor.js.map +1 -1
  152. package/dist/views/FormEntries.d.ts.map +1 -1
  153. package/dist/views/FormEntries.js +4 -190
  154. package/dist/views/FormEntries.js.map +1 -1
  155. package/dist/views/FormSubmissions.d.ts +1 -1
  156. package/dist/views/FormSubmissions.d.ts.map +1 -1
  157. package/dist/views/FormSubmissions.js +6 -195
  158. package/dist/views/FormSubmissions.js.map +1 -1
  159. package/dist/views/Forms.d.ts +11 -1
  160. package/dist/views/Forms.d.ts.map +1 -1
  161. package/dist/views/Forms.js +141 -93
  162. package/dist/views/Forms.js.map +1 -1
  163. package/dist/views/FormsSettings.d.ts +6 -1
  164. package/dist/views/FormsSettings.d.ts.map +1 -1
  165. package/dist/views/FormsSettings.js +527 -30
  166. package/dist/views/FormsSettings.js.map +1 -1
  167. package/dist/views/Jobs/DrawerReview.d.ts.map +1 -1
  168. package/dist/views/Jobs/DrawerReview.js +8 -7
  169. package/dist/views/Jobs/DrawerReview.js.map +1 -1
  170. package/dist/views/Jobs/NewBatchJob.d.ts.map +1 -1
  171. package/dist/views/Jobs/NewBatchJob.js +2 -1
  172. package/dist/views/Jobs/NewBatchJob.js.map +1 -1
  173. package/dist/views/Login.d.ts.map +1 -1
  174. package/dist/views/Login.js +30 -11
  175. package/dist/views/Login.js.map +1 -1
  176. package/dist/views/SpamFolder.js +1 -1
  177. package/dist/views/SpamFolder.js.map +1 -1
  178. package/dist/views/dashboard/Delta.d.ts +7 -0
  179. package/dist/views/dashboard/Delta.d.ts.map +1 -0
  180. package/dist/views/dashboard/Delta.js +21 -0
  181. package/dist/views/dashboard/Delta.js.map +1 -0
  182. package/dist/views/dashboard/KpiCard.d.ts +22 -0
  183. package/dist/views/dashboard/KpiCard.d.ts.map +1 -0
  184. package/dist/views/dashboard/KpiCard.js +15 -0
  185. package/dist/views/dashboard/KpiCard.js.map +1 -0
  186. package/dist/views/dashboard/Sparkline.d.ts +11 -0
  187. package/dist/views/dashboard/Sparkline.d.ts.map +1 -0
  188. package/dist/views/dashboard/Sparkline.js +15 -0
  189. package/dist/views/dashboard/Sparkline.js.map +1 -0
  190. package/dist/views/dashboard/TrendChart.d.ts +8 -0
  191. package/dist/views/dashboard/TrendChart.d.ts.map +1 -0
  192. package/dist/views/dashboard/TrendChart.js +98 -0
  193. package/dist/views/dashboard/TrendChart.js.map +1 -0
  194. package/dist/views/dashboard/dashboard-date.d.ts +33 -0
  195. package/dist/views/dashboard/dashboard-date.d.ts.map +1 -0
  196. package/dist/views/dashboard/dashboard-date.js +136 -0
  197. package/dist/views/dashboard/dashboard-date.js.map +1 -0
  198. package/dist/views/entries/EntriesInbox.d.ts +8 -0
  199. package/dist/views/entries/EntriesInbox.d.ts.map +1 -0
  200. package/dist/views/entries/EntriesInbox.js +516 -0
  201. package/dist/views/entries/EntriesInbox.js.map +1 -0
  202. package/dist/views/entries/inbox-format.d.ts +27 -0
  203. package/dist/views/entries/inbox-format.d.ts.map +1 -0
  204. package/dist/views/entries/inbox-format.js +119 -0
  205. package/dist/views/entries/inbox-format.js.map +1 -0
  206. package/dist/views/settings/CaptchaStatusCard.js +2 -2
  207. package/dist/views/settings/CaptchaStatusCard.js.map +1 -1
  208. package/package.json +4 -4
  209. package/src/AdminRoot.tsx +7 -3
  210. package/src/__tests__/components/attribution-rows.test.ts +1 -1
  211. package/src/__tests__/components/date-range-picker.test.tsx +69 -0
  212. package/src/__tests__/components/form-build-model.test.ts +200 -0
  213. package/src/__tests__/components/form-build.test.tsx +157 -0
  214. package/src/__tests__/components/qa-a11y.render.test.tsx +1 -29
  215. package/src/__tests__/lib/batch-wizard.test.ts +2 -0
  216. package/src/__tests__/lib/forms-settings-normalize.test.ts +17 -0
  217. package/src/__tests__/lib/recaptcha.test.ts +63 -0
  218. package/src/__tests__/views/dashboard.test.tsx +110 -32
  219. package/src/__tests__/views/form-editor.render.test.tsx +18 -10
  220. package/src/__tests__/views/form-entries.render.test.tsx +27 -9
  221. package/src/__tests__/views/form-submissions.render.test.tsx +15 -14
  222. package/src/__tests__/views/forms-list.render.test.tsx +157 -17
  223. package/src/__tests__/views/forms-settings.fixture.ts +32 -0
  224. package/src/__tests__/views/forms-settings.render.test.tsx +274 -0
  225. package/src/__tests__/views/inbox-format.test.ts +72 -0
  226. package/src/__tests__/views/jobs-wizard.render.test.tsx +18 -3
  227. package/src/__tests__/views/login-captcha.render.test.tsx +94 -0
  228. package/src/__tests__/views/onboarding-block.render.test.tsx +9 -7
  229. package/src/components/forms/BlocklistDialog.tsx +552 -0
  230. package/src/components/forms/ExportMenu.tsx +8 -2
  231. package/src/components/forms/FieldOptions.tsx +629 -0
  232. package/src/components/forms/FormBuild.tsx +900 -0
  233. package/src/components/forms/FormsListTable.tsx +300 -0
  234. package/src/components/forms/form-build-model.ts +365 -0
  235. package/src/components/forms/form-build-ui.tsx +130 -0
  236. package/src/components/forms/primitives.tsx +6 -55
  237. package/src/components/ui/DateRangePicker.tsx +358 -0
  238. package/src/components/ui/Segmented.tsx +9 -2
  239. package/src/components/ui/StatusBadge.tsx +17 -4
  240. package/src/components/ui/Toggle.tsx +3 -0
  241. package/src/components/ui/UnderlineTabs.tsx +20 -9
  242. package/src/layout/Sidebar.tsx +4 -2
  243. package/src/lib/batch-wizard.ts +2 -2
  244. package/src/lib/entry-attribution.ts +94 -0
  245. package/src/lib/forms-service.ts +243 -0
  246. package/src/lib/job-drawer.ts +21 -1
  247. package/src/lib/job-view.ts +7 -0
  248. package/src/lib/recaptcha.ts +84 -0
  249. package/src/router/admin-routes.ts +1 -0
  250. package/src/styles/theme.css +86 -0
  251. package/src/views/Dashboard.tsx +1183 -772
  252. package/src/views/FormEditor.tsx +397 -199
  253. package/src/views/FormEntries.tsx +3 -422
  254. package/src/views/FormSubmissions.tsx +5 -411
  255. package/src/views/Forms.tsx +333 -321
  256. package/src/views/FormsSettings.tsx +1616 -73
  257. package/src/views/Jobs/DrawerReview.tsx +14 -8
  258. package/src/views/Jobs/NewBatchJob.tsx +5 -1
  259. package/src/views/Login.tsx +35 -11
  260. package/src/views/SpamFolder.tsx +2 -2
  261. package/src/views/dashboard/Delta.tsx +44 -0
  262. package/src/views/dashboard/KpiCard.tsx +98 -0
  263. package/src/views/dashboard/Sparkline.tsx +51 -0
  264. package/src/views/dashboard/TrendChart.tsx +246 -0
  265. package/src/views/dashboard/dashboard-date.ts +168 -0
  266. package/src/views/entries/EntriesInbox.tsx +1277 -0
  267. package/src/views/entries/inbox-format.ts +128 -0
  268. package/src/views/settings/CaptchaStatusCard.tsx +2 -2
  269. package/dist/components/forms/EntriesTable.d.ts +0 -29
  270. package/dist/components/forms/EntriesTable.d.ts.map +0 -1
  271. package/dist/components/forms/EntriesTable.js +0 -29
  272. package/dist/components/forms/EntriesTable.js.map +0 -1
  273. package/dist/components/forms/FormEntryDetailPane.d.ts +0 -23
  274. package/dist/components/forms/FormEntryDetailPane.d.ts.map +0 -1
  275. package/dist/components/forms/FormEntryDetailPane.js +0 -208
  276. package/dist/components/forms/FormEntryDetailPane.js.map +0 -1
  277. package/dist/components/ui/PanelSection.d.ts +0 -16
  278. package/dist/components/ui/PanelSection.d.ts.map +0 -1
  279. package/dist/components/ui/PanelSection.js +0 -15
  280. package/dist/components/ui/PanelSection.js.map +0 -1
  281. package/src/components/forms/EntriesTable.tsx +0 -207
  282. package/src/components/forms/FormEntryDetailPane.tsx +0 -402
  283. package/src/components/ui/PanelSection.tsx +0 -53
@@ -1,94 +1,1637 @@
1
1
  'use client'
2
2
 
3
- import { useState } from 'react'
4
- import {
5
- DEFAULT_ATTRIBUTION_WINDOWS,
6
- validateAttributionWindows,
7
- type AttributionWindows,
8
- } from '@prenta/core/forms/attribution-settings'
3
+ /**
4
+ * Forms → Form Settings. Five tabs from the form-settings handoff, saved as
5
+ * one `formsSettings` global. Per-form editors still override these defaults.
6
+ */
7
+ import { useEffect, useMemo, useState, type ReactNode } from 'react'
8
+ import { AlertCircle, Check, Clock, FileText, Lock, Mail, Send, Shield, Target } from 'lucide-react'
9
+ import { toast } from 'sonner'
9
10
  import { Breadcrumb } from '../components/ui/Breadcrumb.js'
10
- import { PageHeader } from '../components/ui/PageHeader.js'
11
+ import { Button } from '../components/ui/Button.js'
12
+ import { Toggle } from '../components/ui/Toggle.js'
11
13
  import { UnderlineTabs } from '../components/ui/UnderlineTabs.js'
12
- import { UnsavedBar } from '../components/ui/UnsavedBar.js'
14
+ import {
15
+ BlocklistDialog,
16
+ BlocklistSummary,
17
+ type BlocklistKind,
18
+ } from '../components/forms/BlocklistDialog.js'
19
+ import { LONG_TAIL_CLICK_IDS, TOP_TIER_CLICK_IDS } from '@prenta/core/forms/attribution'
20
+ import { validateAttributionWindows } from '@prenta/core/forms/attribution-settings'
21
+ import {
22
+ fetchFormCaptchaSettings,
23
+ saveFormCaptchaSettings,
24
+ setLoginCaptcha,
25
+ fetchConsentConfig,
26
+ fetchEmailSummary,
27
+ fetchFormsSettings,
28
+ fetchRetentionPreview,
29
+ fetchSpamAiStats,
30
+ saveFormsSettings,
31
+ sendFormEmailTest,
32
+ downloadEntriesExport,
33
+ type FormCaptchaSettings,
34
+ type FormsSettingsDocument,
35
+ } from '../lib/forms-service.js'
36
+ import { getRecaptchaV3Token } from '../lib/recaptcha.js'
13
37
 
14
38
  const TABS = [
15
- { id: 'spam', label: 'Spam protection' },
16
- { id: 'defaults', label: 'Defaults' },
17
- { id: 'retention', label: 'Retention' },
18
- { id: 'attribution', label: 'Attribution' },
19
- { id: 'email', label: 'Email delivery' },
39
+ { id: 'spam', label: 'Spam protection', icon: Shield },
40
+ { id: 'defaults', label: 'Defaults', icon: FileText },
41
+ { id: 'retention', label: 'Retention', icon: Clock },
42
+ { id: 'attribution', label: 'Attribution', icon: Target },
43
+ { id: 'email', label: 'Email delivery', icon: Mail },
44
+ ] as const
45
+
46
+ type TabId = (typeof TABS)[number]['id']
47
+
48
+ /** Turn on in the change that ships the retention job (F-04). */
49
+ const RETENTION_APPLIED = false
50
+
51
+ const CLICK_COPY: Record<string, string> = {
52
+ gclid: 'Google Ads',
53
+ fbclid: 'Meta',
54
+ msclkid: 'Microsoft Ads',
55
+ ttclid: 'TikTok Ads',
56
+ li_fat_id: 'LinkedIn Ads',
57
+ dclid: 'Google Display',
58
+ twclid: 'X Ads',
59
+ rdt_cid: 'Reddit Ads',
60
+ }
61
+
62
+ const CAMPAIGN_FIELDS: Array<[string, string]> = [
63
+ ['source', 'utm_source, or the referring site'],
64
+ ['medium', 'utm_medium, e.g. cpc, email'],
65
+ ['campaign', 'utm_campaign'],
66
+ ['term', 'utm_term (paid keyword)'],
67
+ ['content', 'utm_content (ad or link variant)'],
68
+ ['channel', 'paid, search_organic, social, email, ai, referral or direct'],
69
+ ['referrerName', 'Friendly name, e.g. ChatGPT, Google'],
70
+ ]
71
+
72
+ const VISIT_FIELDS: Array<[string, string]> = [
73
+ ['landingPage', 'First page they arrived on'],
74
+ ['referrer', 'External site that sent them'],
75
+ ['deviceType', 'desktop, tablet or mobile'],
76
+ ['pageViews', 'Pages viewed this session'],
77
+ ['sessionStart', 'When the session began'],
78
+ ['firstTouchAt', 'When the first touch was recorded'],
79
+ ['lastTouchAt', 'When the last touch was recorded'],
20
80
  ]
21
81
 
22
- export function FormsSettings() {
23
- const [tab, setTab] = useState('attribution')
24
- const [saved, setSaved] = useState<AttributionWindows>(DEFAULT_ATTRIBUTION_WINDOWS)
25
- const [draft, setDraft] = useState<AttributionWindows>(DEFAULT_ATTRIBUTION_WINDOWS)
26
- const [message, setMessage] = useState<string | null>(null)
27
- const dirty = JSON.stringify(draft) !== JSON.stringify(saved)
28
- const validation = validateAttributionWindows(draft)
29
-
30
- function save() {
31
- if (!validation.ok) {
32
- setMessage(validation.message)
82
+ const EXTRA_IDS = [...new Set(LONG_TAIL_CLICK_IDS.map((id) => id.toLowerCase()))]
83
+
84
+ function diffCount(left: object, right: object): number {
85
+ const a = left as Record<string, unknown>
86
+ const b = right as Record<string, unknown>
87
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)])
88
+ let count = 0
89
+ for (const key of keys) {
90
+ if (JSON.stringify(a[key]) !== JSON.stringify(b[key])) count += 1
91
+ }
92
+ return count
93
+ }
94
+
95
+ function sectionChanges(
96
+ saved: FormsSettingsDocument,
97
+ draft: FormsSettingsDocument,
98
+ id: TabId,
99
+ ): number {
100
+ if (id === 'spam') {
101
+ const { rateLimit: savedRate, ...savedRest } = saved.spam
102
+ const { rateLimit: draftRate, ...draftRest } = draft.spam
103
+ return diffCount(savedRest, draftRest) + diffCount(savedRate, draftRate)
104
+ }
105
+ if (id === 'defaults') return diffCount(saved.defaults, draft.defaults)
106
+ if (id === 'retention') return diffCount(saved.retention, draft.retention)
107
+ if (id === 'attribution') {
108
+ return JSON.stringify(saved.attribution) === JSON.stringify(draft.attribution) ? 0 : 1
109
+ }
110
+ return 0
111
+ }
112
+
113
+ function restoreSection(
114
+ saved: FormsSettingsDocument,
115
+ draft: FormsSettingsDocument,
116
+ id: TabId,
117
+ ): FormsSettingsDocument {
118
+ if (id === 'spam') return { ...draft, spam: saved.spam }
119
+ if (id === 'defaults') return { ...draft, defaults: saved.defaults }
120
+ if (id === 'retention') return { ...draft, retention: saved.retention }
121
+ if (id === 'attribution') return { ...draft, attribution: saved.attribution }
122
+ return draft
123
+ }
124
+
125
+ const KEEP_LABEL: Record<number, string> = {
126
+ 730: '2 years',
127
+ 365: '1 year',
128
+ 180: '6 months',
129
+ 90: '90 days',
130
+ }
131
+
132
+ const STRICTNESS: Record<FormsSettingsDocument['spam']['ai']['strictness'], string> = {
133
+ relaxed: 'Only flags obvious junk. Fewer mistakes, some spam gets through.',
134
+ balanced: 'Flags scams, bulk outreach and off-topic pitches. A good starting point.',
135
+ strict:
136
+ 'Also flags sales pitches, guest-post requests and vague one-liners. Check Spam more often.',
137
+ }
138
+
139
+ function tabFromPath(path: string): TabId {
140
+ const segment = path.split('?')[0]?.split('/').filter(Boolean)[2]
141
+ return TABS.some((tab) => tab.id === segment) ? (segment as TabId) : 'spam'
142
+ }
143
+
144
+ export interface FormsSettingsProps {
145
+ currentPath?: string
146
+ onNavigate?: (path: string) => void
147
+ role?: string | null
148
+ }
149
+
150
+ export function FormsSettings({
151
+ currentPath = '/forms/settings/spam',
152
+ onNavigate,
153
+ role,
154
+ }: FormsSettingsProps) {
155
+ const readOnly = !!role && role !== 'OWNER' && role !== 'ADMIN'
156
+ const routeTab = tabFromPath(currentPath)
157
+ const [tab, setTab] = useState<TabId>(routeTab)
158
+ useEffect(() => {
159
+ setTab(routeTab)
160
+ }, [routeTab])
161
+ const [saved, setSaved] = useState<FormsSettingsDocument | null>(null)
162
+ const [draft, setDraft] = useState<FormsSettingsDocument | null>(null)
163
+ const [error, setError] = useState<string | null>(null)
164
+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})
165
+ const [saving, setSaving] = useState(false)
166
+ const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
167
+ const [blocklistKind, setBlocklistKind] = useState<BlocklistKind | null>(null)
168
+ const [captchaSettings, setCaptchaSettings] = useState<FormCaptchaSettings | null>(null)
169
+ const captcha = captchaSettings ? captchaSettings.provider !== 'none' : null
170
+ const [aiStats, setAiStats] = useState({ reviewed: 0, flagged: 0, corrected: 0 })
171
+ const [email, setEmail] = useState<Awaited<ReturnType<typeof fetchEmailSummary>> | null>(null)
172
+ const [consent, setConsent] = useState({ installed: false, bannerEnabled: false })
173
+ const [purgeCount, setPurgeCount] = useState(0)
174
+
175
+ useEffect(() => {
176
+ let cancelled = false
177
+ void fetchFormsSettings()
178
+ .then((doc) => {
179
+ if (cancelled) return
180
+ setSaved(doc)
181
+ setDraft(doc)
182
+ })
183
+ .catch((err: unknown) => {
184
+ if (!cancelled)
185
+ setError(err instanceof Error ? err.message : 'Could not load form settings')
186
+ })
187
+ void fetchFormCaptchaSettings().then(setCaptchaSettings)
188
+ void fetchSpamAiStats().then(setAiStats)
189
+ void fetchEmailSummary().then(setEmail)
190
+ void fetchConsentConfig().then(setConsent)
191
+ return () => {
192
+ cancelled = true
193
+ }
194
+ }, [])
195
+
196
+ const entryDays = draft?.retention?.entryDays
197
+ useEffect(() => {
198
+ if (entryDays == null) {
199
+ setPurgeCount(0)
33
200
  return
34
201
  }
35
- setSaved(draft)
36
- setMessage('Saved')
202
+ void fetchRetentionPreview(entryDays).then((preview) => setPurgeCount(preview.entries))
203
+ }, [entryDays])
204
+
205
+ const attributionErrors = useMemo(() => {
206
+ if (!draft?.attribution.record) return {} as Record<string, string>
207
+ const result = validateAttributionWindows(draft.attribution)
208
+ if (result.ok) return {}
209
+ const bag =
210
+ result.errors ??
211
+ ({ [result.field]: result.message } as Partial<
212
+ Record<'firstTouchDays' | 'lastTouchHours', string>
213
+ >)
214
+ const errors: Record<string, string> = {}
215
+ for (const [field, message] of Object.entries(bag)) {
216
+ if (message) errors[`attribution.${field}`] = message
217
+ }
218
+ return errors
219
+ }, [draft])
220
+
221
+ const dirtyCount = useMemo(() => {
222
+ if (!saved || !draft) return 0
223
+ return TABS.reduce((sum, item) => sum + sectionChanges(saved, draft, item.id), 0)
224
+ }, [saved, draft])
225
+
226
+ const dirty = dirtyCount > 0
227
+
228
+ function tabDirty(id: TabId): number {
229
+ if (!saved || !draft) return 0
230
+ return sectionChanges(saved, draft, id)
231
+ }
232
+
233
+ function go(next: TabId) {
234
+ if (next === tab) return
235
+ const pending = tabDirty(tab)
236
+ if (pending > 0 && saved && draft) {
237
+ const label = `${pending} unsaved ${pending === 1 ? 'change' : 'changes'}`
238
+ if (!window.confirm(`You have ${label} on this tab. Discard them?`)) return
239
+ setDraft(restoreSection(saved, draft, tab))
240
+ }
241
+ setTab(next)
242
+ onNavigate?.(`/forms/settings/${next}`)
243
+ }
244
+
245
+ async function save() {
246
+ if (!draft || readOnly || saving) return
247
+ if (Object.keys(attributionErrors).length > 0) {
248
+ setFieldErrors(attributionErrors)
249
+ setSaveState('idle')
250
+ return
251
+ }
252
+ setSaving(true)
253
+ setSaveState('saving')
254
+ const result = await saveFormsSettings(draft)
255
+ setSaving(false)
256
+ if (result.fields && Object.keys(result.fields).length > 0) {
257
+ setFieldErrors(result.fields)
258
+ setSaveState('error')
259
+ return
260
+ }
261
+ if (result.error || !result.data) {
262
+ setSaveState('error')
263
+ return
264
+ }
265
+ setFieldErrors({})
266
+ setSaved(result.data)
267
+ setDraft(result.data)
268
+ setSaveState('saved')
269
+ }
270
+
271
+ useEffect(() => {
272
+ if (saveState !== 'saved') return
273
+ const timer = window.setTimeout(() => setSaveState('idle'), 1600)
274
+ return () => window.clearTimeout(timer)
275
+ }, [saveState])
276
+
277
+ useEffect(() => {
278
+ function onKey(event: KeyboardEvent) {
279
+ if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 's') return
280
+ event.preventDefault()
281
+ void save()
282
+ }
283
+ window.addEventListener('keydown', onKey)
284
+ return () => window.removeEventListener('keydown', onKey)
285
+ })
286
+
287
+ if (error) {
288
+ return (
289
+ <p className="text-err p-6" role="alert">
290
+ {error}
291
+ </p>
292
+ )
293
+ }
294
+ if (!draft) {
295
+ return (
296
+ <p className="text-sub p-6" role="status">
297
+ Loading form settings…
298
+ </p>
299
+ )
37
300
  }
38
301
 
39
302
  return (
40
- <div className="flex flex-col gap-4 p-6">
41
- <PageHeader
42
- flush
43
- title="Form Settings"
44
- subtitle="Site-wide defaults for every form."
45
- breadcrumb={
46
- <Breadcrumb
47
- items={[
48
- { label: 'Dashboard', path: '/' },
49
- { label: 'Forms', path: '/forms' },
50
- { label: 'Form Settings' },
51
- ]}
52
- />
53
- }
303
+ <div className="flex h-full min-h-0 flex-col overflow-x-hidden overflow-y-auto">
304
+ <header className="px-7 pt-5">
305
+ <Breadcrumb items={[{ label: 'Forms', path: '/forms' }, { label: 'Settings' }]} />
306
+ <h1 className="text-txt m-0 mt-2 text-[21px] font-bold tracking-[-0.5px]">Form settings</h1>
307
+ <p className="text-sub mt-1 max-w-[620px] text-[13px]">
308
+ Rules that apply to every form: how spam is caught, what new forms start with, how long
309
+ submissions are kept, and where visitors came from.
310
+ </p>
311
+ </header>
312
+ <UnderlineTabs
313
+ className="mx-7 mt-4"
314
+ label="Form settings tabs"
315
+ value={tab}
316
+ onChange={(id) => go(id as TabId)}
317
+ tabs={TABS.map((item) => {
318
+ const Icon = item.icon
319
+ const pending = tabDirty(item.id)
320
+ return {
321
+ id: item.id,
322
+ label: item.label,
323
+ icon: <Icon size={15} strokeWidth={1.75} />,
324
+ badge:
325
+ pending > 0 ? (
326
+ <i
327
+ className="bg-warn ml-1 inline-block h-1.5 w-1.5 rounded-full"
328
+ aria-label="unsaved"
329
+ />
330
+ ) : undefined,
331
+ }
332
+ })}
54
333
  />
55
- <UnderlineTabs tabs={TABS} value={tab} onChange={setTab} label="Form settings" />
56
- {tab === 'attribution' ? (
57
- <div className="flex max-w-md flex-col gap-4">
58
- <label className="flex flex-col gap-1 text-base">
59
- First touch (days)
60
- <input
61
- type="number"
62
- value={draft.firstTouchDays}
63
- onChange={(event) =>
64
- setDraft({ ...draft, firstTouchDays: Number(event.target.value) })
65
- }
66
- className="border-border rounded-md border px-3 py-2"
67
- />
68
- </label>
69
- <label className="flex flex-col gap-1 text-base">
70
- Last touch (hours)
71
- <input
72
- type="number"
73
- value={draft.lastTouchHours}
74
- onChange={(event) =>
75
- setDraft({ ...draft, lastTouchHours: Number(event.target.value) })
76
- }
77
- className="border-border rounded-md border px-3 py-2"
334
+ <div className="mx-auto flex w-full max-w-[836px] flex-col gap-4 px-7 py-5 pb-28">
335
+ {readOnly ? (
336
+ <p className="border-bdr bg-card text-sub flex items-center gap-2.5 rounded-[10px] border px-3.5 py-2.5 text-[13px]">
337
+ <Lock size={16} className="text-faint shrink-0" aria-hidden />
338
+ You have view-only access to form settings. Ask an admin to make changes.
339
+ </p>
340
+ ) : null}
341
+ <fieldset disabled={readOnly} className="m-0 flex min-w-0 flex-col gap-4 border-0 p-0">
342
+ {tab === 'spam' ? (
343
+ <>
344
+ <Card
345
+ title="Spam protection"
346
+ description="Checks run on every submission before it reaches your inbox."
347
+ >
348
+ <Row
349
+ label="Honeypot field"
350
+ help="A hidden field people never see. Bots fill it in and get caught."
351
+ >
352
+ <Toggle
353
+ checked={draft.spam.honeypot}
354
+ onCheckedChange={(honeypot) =>
355
+ setDraft({ ...draft, spam: { ...draft.spam, honeypot } })
356
+ }
357
+ aria-label="Honeypot field"
358
+ />
359
+ </Row>
360
+ <Row label="CAPTCHA" help={captchaHelp(captchaSettings)}>
361
+ <span
362
+ className={`rounded-pill px-2 py-0.5 text-[12px] font-semibold ${captcha ? 'bg-suc-l text-suc' : 'bg-warn-l text-warn'}`}
363
+ >
364
+ {captcha ? 'Active' : 'Not set up'}
365
+ </span>
366
+ <select
367
+ aria-label="CAPTCHA"
368
+ disabled={captcha === false}
369
+ value={draft.spam.captchaScope}
370
+ onChange={(event) =>
371
+ setDraft({
372
+ ...draft,
373
+ spam: {
374
+ ...draft.spam,
375
+ captchaScope: event.target
376
+ .value as FormsSettingsDocument['spam']['captchaScope'],
377
+ },
378
+ })
379
+ }
380
+ className="border-bdr bg-card text-txt h-9 rounded-[8px] border px-2.5 text-[13px] disabled:opacity-45"
381
+ >
382
+ <option value="all">On all forms</option>
383
+ <option value="per">Choose per form</option>
384
+ <option value="off">Off</option>
385
+ </select>
386
+ </Row>
387
+ {captchaSettings ? (
388
+ <RecaptchaKeys
389
+ settings={captchaSettings}
390
+ readOnly={readOnly}
391
+ onSaved={setCaptchaSettings}
392
+ />
393
+ ) : null}
394
+ <Row label="Submission limit" help="Stops one visitor from flooding a form.">
395
+ <input
396
+ aria-label="Submission limit"
397
+ type="number"
398
+ min={1}
399
+ value={draft.spam.rateLimit.max}
400
+ onChange={(event) =>
401
+ setDraft({
402
+ ...draft,
403
+ spam: {
404
+ ...draft.spam,
405
+ rateLimit: { ...draft.spam.rateLimit, max: Number(event.target.value) },
406
+ },
407
+ })
408
+ }
409
+ className="border-bdr bg-card h-9 w-[72px] rounded-[8px] border px-2.5 text-right text-[13px] tabular-nums"
410
+ />
411
+ <span className="text-sub text-[13px]">per visitor every</span>
412
+ <select
413
+ aria-label="Submission window"
414
+ value={draft.spam.rateLimit.window}
415
+ onChange={(event) =>
416
+ setDraft({
417
+ ...draft,
418
+ spam: {
419
+ ...draft.spam,
420
+ rateLimit: {
421
+ ...draft.spam.rateLimit,
422
+ window: event.target
423
+ .value as FormsSettingsDocument['spam']['rateLimit']['window'],
424
+ },
425
+ },
426
+ })
427
+ }
428
+ className="border-bdr bg-card h-9 rounded-[8px] border px-2.5 text-[13px]"
429
+ >
430
+ <option value="1m">minute</option>
431
+ <option value="10m">10 minutes</option>
432
+ <option value="1h">hour</option>
433
+ <option value="1d">day</option>
434
+ </select>
435
+ </Row>
436
+ <Row
437
+ label="Too-fast submissions"
438
+ help="People take a few seconds to fill in a form. Anything quicker is treated as a bot."
439
+ >
440
+ <span className="text-sub text-[13px]">Flag if sent in under</span>
441
+ <input
442
+ aria-label="Minimum seconds"
443
+ type="number"
444
+ min={0}
445
+ value={draft.spam.minSeconds}
446
+ onChange={(event) =>
447
+ setDraft({
448
+ ...draft,
449
+ spam: { ...draft.spam, minSeconds: Number(event.target.value) },
450
+ })
451
+ }
452
+ className="border-bdr bg-card h-9 w-[72px] rounded-[8px] border px-2.5 text-right text-[13px] tabular-nums"
453
+ />
454
+ <span className="text-sub text-[13px]">seconds</span>
455
+ </Row>
456
+ <Row
457
+ label="Blocked words & email domains"
458
+ help="Entries that contain a blocked word, or come from a blocked domain, go straight to Spam."
459
+ >
460
+ <BlocklistSummary
461
+ value={draft.spam.blocklist}
462
+ disabled={readOnly}
463
+ onManage={setBlocklistKind}
464
+ />
465
+ </Row>
466
+ <Row label="When spam is caught">
467
+ <div
468
+ className="flex flex-col gap-2"
469
+ role="radiogroup"
470
+ aria-label="When spam is caught"
471
+ >
472
+ <RadioCard
473
+ name="spam-action"
474
+ checked={draft.spam.action === 'quarantine'}
475
+ title="Move to Spam"
476
+ help="Kept out of your inbox. Review and restore anything flagged by mistake."
477
+ onChange={() =>
478
+ setDraft({ ...draft, spam: { ...draft.spam, action: 'quarantine' } })
479
+ }
480
+ />
481
+ <RadioCard
482
+ name="spam-action"
483
+ checked={draft.spam.action === 'discard'}
484
+ title="Discard"
485
+ help="Never saved. Notifications aren't sent and nothing can be recovered."
486
+ onChange={() =>
487
+ setDraft({ ...draft, spam: { ...draft.spam, action: 'discard' } })
488
+ }
489
+ />
490
+ </div>
491
+ </Row>
492
+ </Card>
493
+ <Card
494
+ title="AI spam review"
495
+ description="Reads entries that get past the checks above and moves likely spam to the Spam folder. It never deletes anything."
496
+ >
497
+ <p
498
+ className="bg-bg text-sub mx-5 mt-3.5 rounded-[9px] px-3 py-2.5 text-[12.5px]"
499
+ role="note"
500
+ >
501
+ AI spam review isn&apos;t running yet. These choices are saved for when it does.
502
+ </p>
503
+ <p
504
+ className={`mx-5 mt-3.5 mb-1 rounded-[10px] px-3 py-2 text-[13px] ${draft.spam.ai.on ? 'bg-acc-l text-txt' : 'bg-bg text-sub'}`}
505
+ >
506
+ <b>{draft.spam.ai.on ? 'On' : 'Off'}</b>
507
+ {draft.spam.ai.on
508
+ ? ` · Uses the AI provider from Settings → AI. Last 30 days: ${aiStats.reviewed} reviewed · ${aiStats.flagged} flagged · ${aiStats.corrected} marked Not spam.`
509
+ : ' · Only the checks above run. Entries that look human-written reach your inbox.'}
510
+ </p>
511
+ <Row
512
+ label="Review entries with AI"
513
+ help="Runs last, so most bots are caught for free before AI is used."
514
+ >
515
+ <Toggle
516
+ checked={draft.spam.ai.on}
517
+ onCheckedChange={(on) =>
518
+ setDraft({ ...draft, spam: { ...draft.spam, ai: { ...draft.spam.ai, on } } })
519
+ }
520
+ aria-label="Review entries with AI"
521
+ />
522
+ </Row>
523
+ <fieldset
524
+ disabled={!draft.spam.ai.on}
525
+ className="m-0 min-w-0 border-0 p-0 disabled:opacity-45"
526
+ >
527
+ <Row label="How strict" help={STRICTNESS[draft.spam.ai.strictness]}>
528
+ <div
529
+ role="radiogroup"
530
+ aria-label="How strict"
531
+ className="bg-bg flex rounded-[9px] p-[3px]"
532
+ >
533
+ {(['relaxed', 'balanced', 'strict'] as const).map((level) => (
534
+ <button
535
+ key={level}
536
+ type="button"
537
+ role="radio"
538
+ aria-checked={draft.spam.ai.strictness === level}
539
+ onClick={() =>
540
+ setDraft({
541
+ ...draft,
542
+ spam: { ...draft.spam, ai: { ...draft.spam.ai, strictness: level } },
543
+ })
544
+ }
545
+ className={`rounded-[7px] px-2.5 py-[5px] text-[12.5px] font-medium capitalize ${draft.spam.ai.strictness === level ? 'bg-card text-txt shadow-shd' : 'text-sub'}`}
546
+ >
547
+ {level}
548
+ </button>
549
+ ))}
550
+ </div>
551
+ </Row>
552
+ <Row
553
+ label="Hold notifications for flagged entries"
554
+ help="Your team isn't emailed about entries AI moves to Spam."
555
+ >
556
+ <Toggle
557
+ checked={draft.spam.ai.holdNotifications}
558
+ onCheckedChange={(holdNotifications) =>
559
+ setDraft({
560
+ ...draft,
561
+ spam: { ...draft.spam, ai: { ...draft.spam.ai, holdNotifications } },
562
+ })
563
+ }
564
+ aria-label="Hold notifications for flagged entries"
565
+ />
566
+ </Row>
567
+ <Row
568
+ label="Learn from your corrections"
569
+ help="When you mark something Not spam, similar entries are let through next time."
570
+ >
571
+ <Toggle
572
+ checked={draft.spam.ai.learnFromCorrections}
573
+ onCheckedChange={(learnFromCorrections) =>
574
+ setDraft({
575
+ ...draft,
576
+ spam: { ...draft.spam, ai: { ...draft.spam.ai, learnFromCorrections } },
577
+ })
578
+ }
579
+ aria-label="Learn from your corrections"
580
+ />
581
+ </Row>
582
+ </fieldset>
583
+ </Card>
584
+ </>
585
+ ) : null}
586
+ {tab === 'defaults' ? (
587
+ <Card
588
+ title="Defaults for new forms"
589
+ description="Starting values when someone creates a form. Each form can change them afterwards."
590
+ >
591
+ <Row label="Notify these addresses" help="Who gets an email for each new submission.">
592
+ <input
593
+ aria-label="Notify these addresses"
594
+ value={draft.defaults.recipients.join(', ')}
595
+ onChange={(event) =>
596
+ setDraft({
597
+ ...draft,
598
+ defaults: {
599
+ ...draft.defaults,
600
+ recipients: event.target.value
601
+ .split(',')
602
+ .map((item) => item.trim())
603
+ .filter(Boolean),
604
+ },
605
+ })
606
+ }
607
+ className="border-bdr bg-card h-9 w-full max-w-sm rounded-[8px] border px-2.5 text-[13px]"
608
+ />
609
+ </Row>
610
+ {fieldErrors['defaults.recipients'] ? (
611
+ <p className="text-err px-5 text-[12px]" role="alert">
612
+ {fieldErrors['defaults.recipients']}
613
+ </p>
614
+ ) : null}
615
+ <Row
616
+ label="Reply goes to the person who filled in the form"
617
+ help="Hitting Reply on a notification answers the submitter directly."
618
+ >
619
+ <Toggle
620
+ checked={draft.defaults.replyToSubmitter}
621
+ onCheckedChange={(replyToSubmitter) =>
622
+ setDraft({ ...draft, defaults: { ...draft.defaults, replyToSubmitter } })
623
+ }
624
+ aria-label="Reply goes to the person who filled in the form"
625
+ />
626
+ </Row>
627
+ <Row label="Thank-you message" help="Shown on the page after someone submits.">
628
+ <textarea
629
+ aria-label="Thank-you message"
630
+ value={draft.defaults.successMessage}
631
+ onChange={(event) =>
632
+ setDraft({
633
+ ...draft,
634
+ defaults: { ...draft.defaults, successMessage: event.target.value },
635
+ })
636
+ }
637
+ className="border-bdr bg-card min-h-[72px] w-full max-w-sm resize-y rounded-[8px] border px-2.5 py-2 text-[13px]"
638
+ />
639
+ </Row>
640
+ {fieldErrors['defaults.successMessage'] ? (
641
+ <p className="text-err px-5 text-[12px]" role="alert">
642
+ {fieldErrors['defaults.successMessage']}
643
+ </p>
644
+ ) : null}
645
+ <Row
646
+ label="Send a confirmation email"
647
+ help="An automatic we-got-it email to the person who submitted."
648
+ >
649
+ <Toggle
650
+ checked={draft.defaults.confirmationEmail}
651
+ onCheckedChange={(confirmationEmail) =>
652
+ setDraft({ ...draft, defaults: { ...draft.defaults, confirmationEmail } })
653
+ }
654
+ aria-label="Send a confirmation email"
655
+ />
656
+ </Row>
657
+ </Card>
658
+ ) : null}
659
+ {tab === 'retention' ? (
660
+ <Card
661
+ title="Data retention"
662
+ description="How long submissions and logs are kept before they're permanently deleted."
663
+ >
664
+ {RETENTION_APPLIED ? null : (
665
+ <p
666
+ className="bg-bg text-sub mx-5 mt-3.5 rounded-[9px] px-3 py-2.5 text-[12.5px]"
667
+ role="note"
668
+ >
669
+ These choices are saved but not applied yet. Nothing is deleted on this schedule
670
+ until the retention job ships.
671
+ </p>
672
+ )}
673
+ <Row label="Keep entries" help="Starred entries are always kept.">
674
+ <DaySelect
675
+ ariaLabel="Keep entries"
676
+ value={draft.retention.entryDays}
677
+ options={[
678
+ [null, 'Forever'],
679
+ [730, '2 years'],
680
+ [365, '1 year'],
681
+ [180, '6 months'],
682
+ [90, '90 days'],
683
+ ]}
684
+ onChange={(entryDays) =>
685
+ setDraft({ ...draft, retention: { ...draft.retention, entryDays } })
686
+ }
687
+ />
688
+ </Row>
689
+ {RETENTION_APPLIED && draft.retention.entryDays != null && purgeCount > 0 ? (
690
+ <p
691
+ className="bg-bg text-sub mx-5 mb-4 rounded-[9px] px-3 py-2.5 text-[12.5px]"
692
+ role="note"
693
+ >
694
+ {purgeCount} entries older than{' '}
695
+ <b>{(KEEP_LABEL[draft.retention.entryDays] ?? 'this window').toLowerCase()}</b>{' '}
696
+ will be deleted tonight and can't be recovered.{' '}
697
+ <button
698
+ type="button"
699
+ className="text-acc font-semibold"
700
+ onClick={() => void downloadEntriesExport({ format: 'csv' })}
701
+ >
702
+ Export a copy first
703
+ </button>
704
+ .
705
+ </p>
706
+ ) : null}
707
+ <Row label="Empty Spam after">
708
+ <DaySelect
709
+ ariaLabel="Empty Spam after"
710
+ value={draft.retention.spamDays}
711
+ options={[
712
+ [7, '7 days'],
713
+ [30, '30 days'],
714
+ [90, '90 days'],
715
+ ]}
716
+ onChange={(spamDays) =>
717
+ setDraft({
718
+ ...draft,
719
+ retention: { ...draft.retention, spamDays: spamDays as 7 | 30 | 90 },
720
+ })
721
+ }
722
+ />
723
+ </Row>
724
+ <Row label="Delete archived entries after">
725
+ <DaySelect
726
+ ariaLabel="Delete archived entries after"
727
+ value={draft.retention.archivedDays}
728
+ options={[
729
+ [null, 'Never'],
730
+ [90, '90 days'],
731
+ [365, '1 year'],
732
+ ]}
733
+ onChange={(archivedDays) =>
734
+ setDraft({ ...draft, retention: { ...draft.retention, archivedDays } })
735
+ }
736
+ />
737
+ </Row>
738
+ <Row
739
+ label="Keep the SMTP log for"
740
+ help="Delivery history for notifications, confirmations, and webhooks."
741
+ >
742
+ <DaySelect
743
+ ariaLabel="Keep the SMTP log for"
744
+ value={draft.retention.deliveryLogDays}
745
+ options={[
746
+ [30, '30 days'],
747
+ [90, '90 days'],
748
+ [365, '1 year'],
749
+ ]}
750
+ onChange={(deliveryLogDays) =>
751
+ setDraft({
752
+ ...draft,
753
+ retention: {
754
+ ...draft.retention,
755
+ deliveryLogDays: deliveryLogDays as 30 | 90 | 365,
756
+ },
757
+ })
758
+ }
759
+ />
760
+ </Row>
761
+ <Row
762
+ label="Visitor IP addresses"
763
+ help="Used for spam checks. Shortening hides the last part of the address."
764
+ >
765
+ <div
766
+ role="radiogroup"
767
+ aria-label="Visitor IP addresses"
768
+ className="bg-bg flex rounded-[9px] p-[3px]"
769
+ >
770
+ {(
771
+ [
772
+ ['full', 'Store'],
773
+ ['anon', 'Shorten'],
774
+ ['none', "Don't store"],
775
+ ] as const
776
+ ).map(([id, label]) => (
777
+ <button
778
+ key={id}
779
+ type="button"
780
+ role="radio"
781
+ aria-checked={draft.retention.ipStorage === id}
782
+ onClick={() =>
783
+ setDraft({ ...draft, retention: { ...draft.retention, ipStorage: id } })
784
+ }
785
+ className={`rounded-[7px] px-2.5 py-[5px] text-[12.5px] font-medium ${draft.retention.ipStorage === id ? 'bg-card text-txt shadow-shd' : 'text-sub'}`}
786
+ >
787
+ {label}
788
+ </button>
789
+ ))}
790
+ </div>
791
+ </Row>
792
+ <Row
793
+ label="Delete uploaded files with their entry"
794
+ help="Removes attachments from Media when an entry is deleted."
795
+ >
796
+ <Toggle
797
+ checked={draft.retention.deleteFilesWithEntry}
798
+ onCheckedChange={(deleteFilesWithEntry) =>
799
+ setDraft({ ...draft, retention: { ...draft.retention, deleteFilesWithEntry } })
800
+ }
801
+ aria-label="Delete uploaded files with their entry"
802
+ />
803
+ </Row>
804
+ </Card>
805
+ ) : null}
806
+ {tab === 'attribution' ? (
807
+ <AttributionTab
808
+ draft={draft}
809
+ setDraft={setDraft}
810
+ banner={consent.installed && consent.bannerEnabled}
811
+ errors={attributionErrors}
812
+ onOpenPrivacy={() => onNavigate?.('/settings')}
78
813
  />
79
- </label>
80
- {!validation.ok ? <p className="text-destructive text-sm">{validation.message}</p> : null}
81
- {message ? <p className="text-muted-foreground text-sm">{message}</p> : null}
82
- </div>
814
+ ) : null}
815
+ {tab === 'email' ? (
816
+ <EmailDelivery email={email} onChange={setEmail} onNavigate={onNavigate} />
817
+ ) : null}
818
+ </fieldset>
819
+ <BlocklistDialog
820
+ open={blocklistKind !== null}
821
+ initialTab={blocklistKind ?? 'words'}
822
+ value={draft.spam.blocklist}
823
+ onChange={(blocklist) => setDraft({ ...draft, spam: { ...draft.spam, blocklist } })}
824
+ onClose={() => setBlocklistKind(null)}
825
+ />
826
+ </div>
827
+ {readOnly ? null : (
828
+ <SettingsSaveBar
829
+ dirty={dirty}
830
+ count={dirtyCount}
831
+ state={saveState}
832
+ invalid={Object.keys(attributionErrors).length}
833
+ onDiscard={() => saved && setDraft(saved)}
834
+ onSave={() => void save()}
835
+ />
836
+ )}
837
+ </div>
838
+ )
839
+ }
840
+
841
+ const EMAIL_PROVIDER_LABEL: Record<string, string> = {
842
+ resend: 'Resend',
843
+ smtpcom: 'SMTP.com',
844
+ ses: 'Amazon SES',
845
+ smtp: 'SMTP server',
846
+ }
847
+
848
+ function emailProviderLabel(provider: string | undefined): string {
849
+ if (!provider) return '—'
850
+ return EMAIL_PROVIDER_LABEL[provider] ?? provider
851
+ }
852
+
853
+ function emailTestDate(iso: string): string {
854
+ const day = iso.slice(0, 10)
855
+ const date = new Date(`${day}T00:00:00Z`)
856
+ if (Number.isNaN(date.getTime())) return day
857
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
858
+ }
859
+
860
+ function EmailDelivery({
861
+ email,
862
+ onChange,
863
+ onNavigate,
864
+ }: {
865
+ email: {
866
+ configured: boolean
867
+ provider?: string
868
+ from?: string
869
+ lastTest?: { ok: boolean; at: string } | null
870
+ } | null
871
+ onChange: (
872
+ next: {
873
+ configured: boolean
874
+ provider?: string
875
+ from?: string
876
+ lastTest?: { ok: boolean; at: string } | null
877
+ } | null,
878
+ ) => void
879
+ onNavigate?: (path: string) => void
880
+ }) {
881
+ const [sending, setSending] = useState(false)
882
+
883
+ async function sendTest() {
884
+ setSending(true)
885
+ const result = await sendFormEmailTest()
886
+ setSending(false)
887
+ if (result.error || !result.sentTo) {
888
+ toast.error(result.error ?? 'Test send failed')
889
+ if (email) {
890
+ onChange({ ...email, lastTest: { ok: false, at: new Date().toISOString() } })
891
+ }
892
+ return
893
+ }
894
+ toast.success(`Test email sent to ${result.sentTo}`)
895
+ if (email) {
896
+ onChange({ ...email, lastTest: { ok: true, at: new Date().toISOString() } })
897
+ }
898
+ }
899
+
900
+ return (
901
+ <Card
902
+ title="Email delivery"
903
+ description="The account that sends notifications and confirmation emails. Shared with invites and password resets."
904
+ >
905
+ {email?.configured ? (
906
+ <dl className="border-bdr grid grid-cols-1 border-b min-[641px]:grid-cols-3">
907
+ {(
908
+ [
909
+ ['Provider', emailProviderLabel(email.provider), 'text-txt'],
910
+ ['Sends from', email.from ?? '—', 'text-txt'],
911
+ [
912
+ 'Last test',
913
+ email.lastTest
914
+ ? `${email.lastTest.ok ? 'Passed' : 'Failed'} · ${emailTestDate(email.lastTest.at)}`
915
+ : 'Not tested',
916
+ email.lastTest ? (email.lastTest.ok ? 'text-suc' : 'text-err') : 'text-sub',
917
+ ],
918
+ ] as const
919
+ ).map(([label, value, tone]) => (
920
+ <div
921
+ key={label}
922
+ className="border-bdr min-w-0 px-5 py-3.5 max-[640px]:[&:not(:first-child)]:border-t min-[641px]:[&:not(:first-child)]:border-l"
923
+ >
924
+ <dt className="text-faint text-[11px] font-semibold tracking-[0.4px] uppercase">
925
+ {label}
926
+ </dt>
927
+ <dd className={`m-0 mt-0.5 truncate text-[13px] font-medium ${tone}`}>{value}</dd>
928
+ </div>
929
+ ))}
930
+ </dl>
83
931
  ) : (
84
- <p className="text-muted-foreground text-base">Settings for {tab}.</p>
932
+ <p className="text-sub m-0 px-5 py-4 text-[13px]">
933
+ Email isn't set up yet. Notifications won't send.
934
+ </p>
85
935
  )}
86
- <UnsavedBar
87
- dirty={dirty}
88
- onDiscard={() => setDraft(saved)}
89
- onSave={save}
90
- label="Unsaved changes"
936
+ <div className="flex flex-wrap justify-end gap-2 px-5 py-3">
937
+ {email?.configured ? (
938
+ <>
939
+ <Button
940
+ type="button"
941
+ variant="secondary"
942
+ leftIcon={<Mail size={14} strokeWidth={1.75} aria-hidden />}
943
+ onClick={() => onNavigate?.('/forms/deliveries')}
944
+ >
945
+ SMTP log
946
+ </Button>
947
+ <Button
948
+ type="button"
949
+ variant="secondary"
950
+ loading={sending}
951
+ leftIcon={<Send size={14} strokeWidth={1.75} aria-hidden />}
952
+ onClick={() => void sendTest()}
953
+ >
954
+ Send test email
955
+ </Button>
956
+ <Button type="button" onClick={() => onNavigate?.('/settings?tab=email')}>
957
+ SMTP settings
958
+ </Button>
959
+ </>
960
+ ) : (
961
+ <Button type="button" onClick={() => onNavigate?.('/settings?tab=email')}>
962
+ Set up email
963
+ </Button>
964
+ )}
965
+ </div>
966
+ </Card>
967
+ )
968
+ }
969
+
970
+ function SettingsSaveBar({
971
+ dirty,
972
+ count,
973
+ state,
974
+ invalid,
975
+ onDiscard,
976
+ onSave,
977
+ }: {
978
+ dirty: boolean
979
+ count: number
980
+ state: 'idle' | 'saving' | 'saved' | 'error'
981
+ invalid: number
982
+ onDiscard: () => void
983
+ onSave: () => void
984
+ }) {
985
+ const show = dirty || state === 'saving' || state === 'saved' || state === 'error'
986
+ if (!show) return null
987
+ const saving = state === 'saving'
988
+ const label =
989
+ state === 'saving'
990
+ ? 'Saving…'
991
+ : state === 'saved'
992
+ ? 'Changes saved'
993
+ : state === 'error'
994
+ ? "Couldn't save. Check your connection and try again."
995
+ : invalid > 0
996
+ ? `Fix ${invalid} ${invalid === 1 ? 'error' : 'errors'} to save`
997
+ : `${count} unsaved ${count === 1 ? 'change' : 'changes'}`
998
+ const tone =
999
+ state === 'saved'
1000
+ ? 'bg-suc text-white'
1001
+ : state === 'error'
1002
+ ? 'bg-err text-white'
1003
+ : 'bg-txt text-bg'
1004
+ return (
1005
+ <div
1006
+ role={state === 'error' ? 'alert' : 'region'}
1007
+ aria-label="Unsaved changes"
1008
+ aria-live="polite"
1009
+ className={`rounded-12 sticky bottom-4 z-[var(--z-bar)] ml-auto flex w-[min(560px,calc(100%-56px))] items-center gap-2.5 py-2.5 pr-2.5 pl-4 text-[13px] font-[550] shadow-[0_10px_30px_rgba(0,0,0,0.22)] ${tone}`}
1010
+ >
1011
+ <span className="flex min-w-0 flex-1 items-center gap-2">
1012
+ {state === 'saved' ? <Check size={16} aria-hidden /> : null}
1013
+ {invalid > 0 && state === 'idle' ? <AlertCircle size={15} aria-hidden /> : null}
1014
+ {label}
1015
+ </span>
1016
+ {state === 'saved' ? null : (
1017
+ <>
1018
+ <button
1019
+ type="button"
1020
+ onClick={onDiscard}
1021
+ disabled={saving}
1022
+ className="h-8 rounded-[8px] border border-transparent bg-transparent px-3 disabled:opacity-50"
1023
+ >
1024
+ Discard
1025
+ </button>
1026
+ <button
1027
+ type="button"
1028
+ onClick={onSave}
1029
+ disabled={saving || invalid > 0}
1030
+ className={`h-8 rounded-[8px] px-3 font-semibold disabled:opacity-50 ${state === 'error' ? 'text-err bg-white' : 'bg-acc text-acc-on'}`}
1031
+ >
1032
+ {state === 'error' ? 'Try again' : 'Save changes'}
1033
+ </button>
1034
+ </>
1035
+ )}
1036
+ </div>
1037
+ )
1038
+ }
1039
+
1040
+ function AttributionTab({
1041
+ draft,
1042
+ setDraft,
1043
+ banner,
1044
+ errors,
1045
+ onOpenPrivacy,
1046
+ }: {
1047
+ draft: FormsSettingsDocument
1048
+ setDraft: (next: FormsSettingsDocument) => void
1049
+ banner: boolean
1050
+ errors: Record<string, string>
1051
+ onOpenPrivacy: () => void
1052
+ }) {
1053
+ const off = !draft.attribution.record
1054
+ const firstError = off ? undefined : errors['attribution.firstTouchDays']
1055
+ const lastError = off ? undefined : errors['attribution.lastTouchHours']
1056
+ const clickFields = TOP_TIER_CLICK_IDS.map(
1057
+ (key) => [key, CLICK_COPY[key] ?? key] as [string, string],
1058
+ )
1059
+ return (
1060
+ <>
1061
+ <Card
1062
+ title="Capture"
1063
+ description="Record where each visitor came from and attach it to their submission. Works on every form automatically."
1064
+ >
1065
+ <AttributionStatus
1066
+ record={draft.attribution.record}
1067
+ requireConsent={draft.attribution.requireConsent}
1068
+ banner={banner}
1069
+ onOpenPrivacy={onOpenPrivacy}
1070
+ />
1071
+ <Row
1072
+ label="Record attribution"
1073
+ help="Saves campaign, visit, and ad click details with every submission."
1074
+ >
1075
+ <Toggle
1076
+ checked={draft.attribution.record}
1077
+ onCheckedChange={(record) =>
1078
+ setDraft({ ...draft, attribution: { ...draft.attribution, record } })
1079
+ }
1080
+ aria-label="Record attribution"
1081
+ />
1082
+ </Row>
1083
+ <Row
1084
+ label="Require consent"
1085
+ help="Wait until the visitor accepts analytics cookies before recording anything."
1086
+ >
1087
+ <Toggle
1088
+ checked={draft.attribution.requireConsent}
1089
+ disabled={off}
1090
+ onCheckedChange={(requireConsent) =>
1091
+ setDraft({ ...draft, attribution: { ...draft.attribution, requireConsent } })
1092
+ }
1093
+ aria-label="Require consent"
1094
+ />
1095
+ </Row>
1096
+ </Card>
1097
+ <Card
1098
+ title="Memory"
1099
+ description="How long a visit is remembered on the visitor's device before it stops counting."
1100
+ >
1101
+ <WindowRow
1102
+ id="at-first"
1103
+ label="First touch"
1104
+ help="What originally brought them here. Kept until it expires, even if they come back another way."
1105
+ unit="days"
1106
+ range="1–365"
1107
+ value={draft.attribution.firstTouchDays}
1108
+ disabled={off}
1109
+ error={firstError}
1110
+ onChange={(firstTouchDays) =>
1111
+ setDraft({ ...draft, attribution: { ...draft.attribution, firstTouchDays } })
1112
+ }
1113
+ />
1114
+ <WindowRow
1115
+ id="at-last"
1116
+ label="Last touch"
1117
+ help="What brought them back for the visit that converted. Must be shorter than first touch."
1118
+ unit="hours"
1119
+ range="1–168"
1120
+ value={draft.attribution.lastTouchHours}
1121
+ disabled={off}
1122
+ error={lastError}
1123
+ onChange={(lastTouchHours) =>
1124
+ setDraft({ ...draft, attribution: { ...draft.attribution, lastTouchHours } })
1125
+ }
1126
+ />
1127
+ {off ? (
1128
+ <p className="text-faint m-0 px-5 pt-1 pb-3.5 text-[12px]">
1129
+ Turn on Record attribution to change these.
1130
+ </p>
1131
+ ) : null}
1132
+ </Card>
1133
+ <Card
1134
+ title="Fields on every submission"
1135
+ description="Read only. These are the names used in entry details, exports, notification emails, and webhooks."
1136
+ >
1137
+ <div className="flex flex-col gap-3.5 px-5 pt-1.5 pb-4">
1138
+ <FieldGroup
1139
+ title="Campaign"
1140
+ subtitle="From UTM tags, or worked out from the referrer"
1141
+ fields={CAMPAIGN_FIELDS}
1142
+ />
1143
+ <FieldGroup
1144
+ title="Visit"
1145
+ subtitle="The visit that led to the submission"
1146
+ fields={VISIT_FIELDS}
1147
+ />
1148
+ <FieldGroup
1149
+ title="Ad click IDs"
1150
+ subtitle="Empty when the visitor didn't click an ad"
1151
+ fields={clickFields}
1152
+ />
1153
+ <p className="text-sub m-0 text-[12px] leading-[1.6]">
1154
+ Other ad networks are kept under <code className="font-mono">extraIds</code>:{' '}
1155
+ {EXTRA_IDS.map((key) => (
1156
+ <code
1157
+ key={key}
1158
+ className="border-bdr bg-bg mx-0.5 rounded-[5px] border px-1 font-mono text-[11.5px] whitespace-nowrap"
1159
+ >
1160
+ {key}
1161
+ </code>
1162
+ ))}
1163
+ </p>
1164
+ </div>
1165
+ <div className="border-bdr text-sub flex flex-wrap items-center gap-1.5 border-t px-5 py-3 text-[12px]">
1166
+ <span>Appears in</span>
1167
+ {['Entry details', 'CSV & Excel export', 'Notification email', 'Webhook payload'].map(
1168
+ (label) => (
1169
+ <span
1170
+ key={label}
1171
+ className="border-bdr bg-bg text-txt rounded-full border px-2 py-px text-[11.5px] font-semibold whitespace-nowrap"
1172
+ >
1173
+ {label}
1174
+ </span>
1175
+ ),
1176
+ )}
1177
+ </div>
1178
+ </Card>
1179
+ </>
1180
+ )
1181
+ }
1182
+
1183
+ function AttributionStatus({
1184
+ record,
1185
+ requireConsent,
1186
+ banner,
1187
+ onOpenPrivacy,
1188
+ }: {
1189
+ record: boolean
1190
+ requireConsent: boolean
1191
+ banner: boolean
1192
+ onOpenPrivacy: () => void
1193
+ }) {
1194
+ if (!record) {
1195
+ return (
1196
+ <p
1197
+ className="border-bdr bg-bg text-sub mx-5 mt-3.5 rounded-[10px] border px-3.5 py-3 text-[12.5px]"
1198
+ role="status"
1199
+ >
1200
+ <b className="text-txt mb-0.5 block text-[13px]">Off</b>
1201
+ New submissions save without campaign or visit details. Existing entries keep theirs.
1202
+ </p>
1203
+ )
1204
+ }
1205
+ if (requireConsent && !banner) {
1206
+ return (
1207
+ <p
1208
+ className="border-warn bg-warn-l text-txt mx-5 mt-3.5 rounded-[10px] border px-3.5 py-3 text-[12.5px]"
1209
+ role="status"
1210
+ >
1211
+ <b className="mb-0.5 block text-[13px]">New visits aren&apos;t being recorded</b>
1212
+ Require consent is on, but this site has no consent banner, so no visitor can say yes.{' '}
1213
+ <button type="button" className="font-semibold underline" onClick={onOpenPrivacy}>
1214
+ Add a consent banner
1215
+ </button>{' '}
1216
+ or turn off Require consent.
1217
+ </p>
1218
+ )
1219
+ }
1220
+ if (requireConsent) {
1221
+ return (
1222
+ <p
1223
+ className="border-info bg-info-l text-txt mx-5 mt-3.5 rounded-[10px] border px-3.5 py-3 text-[12.5px]"
1224
+ role="status"
1225
+ >
1226
+ <b className="mb-0.5 block text-[13px]">Recording after consent</b>
1227
+ Visits are saved once the visitor accepts analytics cookies in your consent banner.
1228
+ </p>
1229
+ )
1230
+ }
1231
+ return (
1232
+ <p
1233
+ className="border-suc bg-suc-l text-txt mx-5 mt-3.5 rounded-[10px] border px-3.5 py-3 text-[12.5px]"
1234
+ role="status"
1235
+ >
1236
+ <b className="mb-0.5 block text-[13px]">Recording</b>
1237
+ Every form saves where the visitor came from with each submission.
1238
+ </p>
1239
+ )
1240
+ }
1241
+
1242
+ function WindowRow({
1243
+ id,
1244
+ label,
1245
+ help,
1246
+ unit,
1247
+ range,
1248
+ value,
1249
+ disabled,
1250
+ error,
1251
+ onChange,
1252
+ }: {
1253
+ id: string
1254
+ label: string
1255
+ help: string
1256
+ unit: string
1257
+ range: string
1258
+ value: number
1259
+ disabled: boolean
1260
+ error?: string
1261
+ onChange: (value: number) => void
1262
+ }) {
1263
+ return (
1264
+ <Row label={label} help={help}>
1265
+ <input
1266
+ id={id}
1267
+ aria-label={label}
1268
+ inputMode="numeric"
1269
+ disabled={disabled}
1270
+ value={value}
1271
+ aria-invalid={error ? true : undefined}
1272
+ aria-describedby={error ? `${id}-e` : `${id}-r`}
1273
+ onChange={(event) => onChange(Number(event.target.value.replace(/\D/g, '') || 0))}
1274
+ className="border-bdr bg-card h-9 w-[84px] rounded-[8px] border px-2.5 text-right text-[13px] tabular-nums disabled:opacity-55"
91
1275
  />
1276
+ <span className="text-sub text-[12.5px]">{unit}</span>
1277
+ <span id={`${id}-r`} className="text-faint text-[11.5px] whitespace-nowrap">
1278
+ {range}
1279
+ </span>
1280
+ {error ? (
1281
+ <span
1282
+ id={`${id}-e`}
1283
+ role="alert"
1284
+ className="text-err flex basis-full items-center justify-end gap-1 text-right text-[12px] font-medium"
1285
+ >
1286
+ <AlertCircle size={13} aria-hidden />
1287
+ {error}
1288
+ </span>
1289
+ ) : null}
1290
+ </Row>
1291
+ )
1292
+ }
1293
+
1294
+ function FieldGroup({
1295
+ title,
1296
+ subtitle,
1297
+ fields,
1298
+ }: {
1299
+ title: string
1300
+ subtitle: string
1301
+ fields: Array<[string, string]>
1302
+ }) {
1303
+ return (
1304
+ <div>
1305
+ <div className="text-faint mb-2 flex items-baseline gap-2 text-[11px] font-bold tracking-[0.5px] uppercase">
1306
+ {title}
1307
+ <small className="text-[11.5px] font-medium tracking-normal normal-case">{subtitle}</small>
1308
+ </div>
1309
+ <div className="grid grid-cols-2 gap-1.5 min-[760px]:grid-cols-3">
1310
+ {fields.map(([key, description]) => (
1311
+ <div
1312
+ key={key}
1313
+ title={description}
1314
+ className="border-bdr bg-bg min-w-0 rounded-[8px] border px-2.5 py-[7px]"
1315
+ >
1316
+ <code className="text-txt block truncate font-mono text-[12px] font-medium">{key}</code>
1317
+ <span className="text-sub block truncate text-[11.5px]">{description}</span>
1318
+ </div>
1319
+ ))}
1320
+ </div>
1321
+ </div>
1322
+ )
1323
+ }
1324
+
1325
+ const CAPTCHA_PROVIDER_LABELS: Record<FormCaptchaSettings['provider'], string> = {
1326
+ recaptcha: 'Google reCAPTCHA v3',
1327
+ turnstile: 'Cloudflare Turnstile',
1328
+ none: 'Google reCAPTCHA v3',
1329
+ }
1330
+
1331
+ function captchaHelp(settings: FormCaptchaSettings | null): string {
1332
+ if (settings?.source === 'env') {
1333
+ return `${CAPTCHA_PROVIDER_LABELS[settings.provider]}, set by environment variables.`
1334
+ }
1335
+ return 'Google reCAPTCHA v3. Invisible to visitors: each submission gets a score.'
1336
+ }
1337
+
1338
+ const keyInputClass =
1339
+ 'border-bdr bg-card text-txt h-9 w-full max-w-[340px] rounded-[8px] border px-2.5 font-mono text-[12.5px] disabled:opacity-55'
1340
+
1341
+ /**
1342
+ * The reCAPTCHA v3 keys. Saved on their own, not with the page's save bar,
1343
+ * because the secret is write-only and never part of the settings document.
1344
+ */
1345
+ function RecaptchaKeys({
1346
+ settings,
1347
+ readOnly,
1348
+ onSaved,
1349
+ }: {
1350
+ settings: FormCaptchaSettings
1351
+ readOnly: boolean
1352
+ onSaved: (next: FormCaptchaSettings) => void
1353
+ }) {
1354
+ const [siteKey, setSiteKey] = useState(settings.siteKey)
1355
+ const [secretKey, setSecretKey] = useState('')
1356
+ const [threshold, setThreshold] = useState(String(settings.scoreThreshold))
1357
+ const [errors, setErrors] = useState<Record<string, string>>({})
1358
+ const [busy, setBusy] = useState<'save' | 'remove' | 'login' | null>(null)
1359
+
1360
+ useEffect(() => {
1361
+ setSiteKey(settings.siteKey)
1362
+ setThreshold(String(settings.scoreThreshold))
1363
+ }, [settings.siteKey, settings.scoreThreshold])
1364
+
1365
+ if (settings.envOverride) {
1366
+ return (
1367
+ <Row
1368
+ label="reCAPTCHA keys"
1369
+ help="RECAPTCHA_* or TURNSTILE_* environment variables are set, so keys entered here aren't used. Remove those variables to manage keys here."
1370
+ >
1371
+ <span className="text-sub text-[12.5px]">Managed by your deployment</span>
1372
+ </Row>
1373
+ )
1374
+ }
1375
+
1376
+ const dirty =
1377
+ siteKey.trim() !== settings.siteKey ||
1378
+ secretKey.trim() !== '' ||
1379
+ Number(threshold) !== settings.scoreThreshold
1380
+
1381
+ async function save(clear = false) {
1382
+ setBusy(clear ? 'remove' : 'save')
1383
+ setErrors({})
1384
+ const res = await saveFormCaptchaSettings(
1385
+ clear
1386
+ ? { clear: true }
1387
+ : {
1388
+ siteKey: siteKey.trim(),
1389
+ ...(secretKey.trim() ? { secretKey: secretKey.trim() } : {}),
1390
+ scoreThreshold: Number(threshold),
1391
+ },
1392
+ )
1393
+ setBusy(null)
1394
+ if (res.data) {
1395
+ setSecretKey('')
1396
+ onSaved(res.data)
1397
+ toast.success(clear ? 'reCAPTCHA keys removed' : 'reCAPTCHA keys saved')
1398
+ return
1399
+ }
1400
+ if (res.fields) setErrors(res.fields)
1401
+ else toast.error(res.error ?? 'Could not save the reCAPTCHA keys')
1402
+ }
1403
+
1404
+ async function toggleLogin(enabled: boolean) {
1405
+ setBusy('login')
1406
+ let token: string | undefined
1407
+ if (enabled) {
1408
+ try {
1409
+ token = await getRecaptchaV3Token(settings.siteKey, 'login')
1410
+ } catch {
1411
+ setBusy(null)
1412
+ toast.error(
1413
+ "reCAPTCHA didn't load with this site key. Check that this domain is added in the reCAPTCHA admin console.",
1414
+ )
1415
+ return
1416
+ }
1417
+ }
1418
+ const res = await setLoginCaptcha({ enabled, token })
1419
+ setBusy(null)
1420
+ if (res.data) {
1421
+ onSaved(res.data)
1422
+ toast.success(enabled ? 'Admin login protected' : 'Admin login protection off')
1423
+ } else {
1424
+ toast.error(res.error ?? 'Could not change login protection')
1425
+ }
1426
+ }
1427
+
1428
+ const hasKeys = settings.source === 'admin' && settings.hasSecret
1429
+ const loginLocked = readOnly || settings.loginDisabledByEnv || !hasKeys || dirty
1430
+ const loginHelp = settings.loginDisabledByEnv
1431
+ ? 'CAPTCHA_LOGIN=off is set, so sign-ins aren’t checked.'
1432
+ : !hasKeys
1433
+ ? 'Save keys first. Sign-ins are then checked with the same keys.'
1434
+ : dirty
1435
+ ? 'Save your key changes first.'
1436
+ : 'Checks sign-ins with these keys. Turning it on runs a test on this domain first.'
1437
+
1438
+ const fieldError = (key: string) =>
1439
+ errors[key] ? (
1440
+ <span
1441
+ id={`recaptcha-${key}-e`}
1442
+ role="alert"
1443
+ className="text-err flex basis-full items-center justify-end gap-1 text-right text-[12px] font-medium"
1444
+ >
1445
+ <AlertCircle size={13} aria-hidden />
1446
+ {errors[key]}
1447
+ </span>
1448
+ ) : null
1449
+
1450
+ return (
1451
+ <>
1452
+ <Row
1453
+ label="reCAPTCHA site key"
1454
+ help="From the reCAPTCHA admin console. Choose reCAPTCHA v3 and add your site's domains."
1455
+ >
1456
+ <input
1457
+ aria-label="reCAPTCHA site key"
1458
+ value={siteKey}
1459
+ disabled={readOnly}
1460
+ autoComplete="off"
1461
+ spellCheck={false}
1462
+ aria-invalid={errors.siteKey ? true : undefined}
1463
+ aria-describedby={errors.siteKey ? 'recaptcha-siteKey-e' : undefined}
1464
+ onChange={(event) => setSiteKey(event.target.value)}
1465
+ className={keyInputClass}
1466
+ />
1467
+ {fieldError('siteKey')}
1468
+ </Row>
1469
+ <Row
1470
+ label="reCAPTCHA secret key"
1471
+ help={
1472
+ settings.hasSecret
1473
+ ? 'Saved and encrypted. Leave blank to keep it.'
1474
+ : 'Stored encrypted. It never leaves the server.'
1475
+ }
1476
+ >
1477
+ <input
1478
+ aria-label="reCAPTCHA secret key"
1479
+ type="password"
1480
+ value={secretKey}
1481
+ disabled={readOnly}
1482
+ autoComplete="new-password"
1483
+ spellCheck={false}
1484
+ placeholder={settings.secretLast4 ? `•••• ${settings.secretLast4}` : ''}
1485
+ aria-invalid={errors.secretKey ? true : undefined}
1486
+ aria-describedby={errors.secretKey ? 'recaptcha-secretKey-e' : undefined}
1487
+ onChange={(event) => setSecretKey(event.target.value)}
1488
+ className={keyInputClass}
1489
+ />
1490
+ {fieldError('secretKey')}
1491
+ </Row>
1492
+ <Row
1493
+ label="Score threshold"
1494
+ help="Submissions scoring below this are rejected. 0 is likely a bot, 1 likely a person; Google suggests 0.5."
1495
+ >
1496
+ <input
1497
+ aria-label="Score threshold"
1498
+ type="number"
1499
+ min={0}
1500
+ max={1}
1501
+ step={0.1}
1502
+ value={threshold}
1503
+ disabled={readOnly}
1504
+ aria-invalid={errors.scoreThreshold ? true : undefined}
1505
+ aria-describedby={errors.scoreThreshold ? 'recaptcha-scoreThreshold-e' : undefined}
1506
+ onChange={(event) => setThreshold(event.target.value)}
1507
+ className="border-bdr bg-card h-9 w-[84px] rounded-[8px] border px-2.5 text-right text-[13px] tabular-nums disabled:opacity-55"
1508
+ />
1509
+ {fieldError('scoreThreshold')}
1510
+ </Row>
1511
+ {readOnly ? null : (
1512
+ <div className="border-bdr flex flex-wrap justify-end gap-2 border-b px-5 py-3">
1513
+ {settings.source === 'admin' ? (
1514
+ <Button
1515
+ type="button"
1516
+ variant="danger"
1517
+ size="sm"
1518
+ loading={busy === 'remove'}
1519
+ disabled={busy !== null}
1520
+ onClick={() => void save(true)}
1521
+ >
1522
+ Remove keys
1523
+ </Button>
1524
+ ) : null}
1525
+ <Button
1526
+ type="button"
1527
+ size="sm"
1528
+ loading={busy === 'save'}
1529
+ disabled={busy !== null || !dirty}
1530
+ onClick={() => void save()}
1531
+ >
1532
+ Save keys
1533
+ </Button>
1534
+ </div>
1535
+ )}
1536
+ <Row label="Protect the admin login" help={loginHelp}>
1537
+ <Toggle
1538
+ checked={settings.protectLogin}
1539
+ disabled={loginLocked || busy !== null}
1540
+ onCheckedChange={(enabled) => void toggleLogin(enabled)}
1541
+ aria-label="Protect the admin login"
1542
+ />
1543
+ </Row>
1544
+ </>
1545
+ )
1546
+ }
1547
+
1548
+ function Card({
1549
+ title,
1550
+ description,
1551
+ children,
1552
+ }: {
1553
+ title: string
1554
+ description: string
1555
+ children: ReactNode
1556
+ }) {
1557
+ const id = title.replace(/\s+/g, '-').toLowerCase()
1558
+ return (
1559
+ <section
1560
+ aria-labelledby={id}
1561
+ className="border-bdr bg-card shadow-shd overflow-hidden rounded-[12px] border"
1562
+ >
1563
+ <header className="border-bdr border-b px-5 py-4">
1564
+ <h2 id={id} className="text-txt m-0 text-[15px] font-semibold">
1565
+ {title}
1566
+ </h2>
1567
+ <p className="text-sub m-0 mt-1 text-[12.5px]">{description}</p>
1568
+ </header>
1569
+ {children}
1570
+ </section>
1571
+ )
1572
+ }
1573
+
1574
+ function Row({ label, help, children }: { label: string; help?: string; children: ReactNode }) {
1575
+ return (
1576
+ <div className="border-bdr grid items-center gap-5 border-b px-5 py-[15px] last:border-b-0 md:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)]">
1577
+ <div>
1578
+ <div className="text-txt text-[13px] font-semibold">{label}</div>
1579
+ {help ? <p className="text-sub m-0 mt-1 text-[12px] leading-[1.45]">{help}</p> : null}
1580
+ </div>
1581
+ <div className="flex flex-wrap items-center justify-end gap-2">{children}</div>
92
1582
  </div>
93
1583
  )
94
1584
  }
1585
+
1586
+ function RadioCard({
1587
+ name,
1588
+ checked,
1589
+ title,
1590
+ help,
1591
+ onChange,
1592
+ }: {
1593
+ name: string
1594
+ checked: boolean
1595
+ title: string
1596
+ help: string
1597
+ onChange: () => void
1598
+ }) {
1599
+ return (
1600
+ <label
1601
+ className={`block cursor-pointer rounded-[9px] border px-3 py-2.5 ${checked ? 'border-acc bg-acc-l' : 'border-bdr'}`}
1602
+ >
1603
+ <input type="radio" name={name} checked={checked} onChange={onChange} className="sr-only" />
1604
+ <span className="text-txt block text-[13px] font-semibold">{title}</span>
1605
+ <span className="text-sub block text-[12px]">{help}</span>
1606
+ </label>
1607
+ )
1608
+ }
1609
+
1610
+ function DaySelect({
1611
+ ariaLabel,
1612
+ value,
1613
+ options,
1614
+ onChange,
1615
+ }: {
1616
+ ariaLabel: string
1617
+ value: number | null
1618
+ options: Array<[number | null, string]>
1619
+ onChange: (value: number | null) => void
1620
+ }) {
1621
+ return (
1622
+ <select
1623
+ aria-label={ariaLabel}
1624
+ value={value == null ? 'null' : String(value)}
1625
+ onChange={(event) =>
1626
+ onChange(event.target.value === 'null' ? null : Number(event.target.value))
1627
+ }
1628
+ className="border-bdr bg-card text-txt h-9 rounded-[8px] border px-2.5 text-[13px]"
1629
+ >
1630
+ {options.map(([option, label]) => (
1631
+ <option key={label} value={option == null ? 'null' : String(option)}>
1632
+ {label}
1633
+ </option>
1634
+ ))}
1635
+ </select>
1636
+ )
1637
+ }