@prenta/admin 2.14.3 → 2.14.4

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 (76) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/__tests__/lib/fetch-all-pages.test.d.ts +2 -0
  3. package/dist/__tests__/lib/fetch-all-pages.test.d.ts.map +1 -0
  4. package/dist/__tests__/lib/fetch-all-pages.test.js +42 -0
  5. package/dist/__tests__/lib/fetch-all-pages.test.js.map +1 -0
  6. package/dist/__tests__/views/audit-entries.test.d.ts +2 -0
  7. package/dist/__tests__/views/audit-entries.test.d.ts.map +1 -0
  8. package/dist/__tests__/views/audit-entries.test.js +164 -0
  9. package/dist/__tests__/views/audit-entries.test.js.map +1 -0
  10. package/dist/__tests__/views/audit-media.test.d.ts +2 -0
  11. package/dist/__tests__/views/audit-media.test.d.ts.map +1 -0
  12. package/dist/__tests__/views/audit-media.test.js +73 -0
  13. package/dist/__tests__/views/audit-media.test.js.map +1 -0
  14. package/dist/__tests__/views/audit-navigation.test.d.ts +2 -0
  15. package/dist/__tests__/views/audit-navigation.test.d.ts.map +1 -0
  16. package/dist/__tests__/views/audit-navigation.test.js +54 -0
  17. package/dist/__tests__/views/audit-navigation.test.js.map +1 -0
  18. package/dist/__tests__/views/audit-pages.test.d.ts +2 -0
  19. package/dist/__tests__/views/audit-pages.test.d.ts.map +1 -0
  20. package/dist/__tests__/views/audit-pages.test.js +78 -0
  21. package/dist/__tests__/views/audit-pages.test.js.map +1 -0
  22. package/dist/__tests__/views/audit-settings.test.d.ts +2 -0
  23. package/dist/__tests__/views/audit-settings.test.d.ts.map +1 -0
  24. package/dist/__tests__/views/audit-settings.test.js +105 -0
  25. package/dist/__tests__/views/audit-settings.test.js.map +1 -0
  26. package/dist/__tests__/views/dashboard.test.js +7 -0
  27. package/dist/__tests__/views/dashboard.test.js.map +1 -1
  28. package/dist/__tests__/views/pages-list-view.test.js +9 -1
  29. package/dist/__tests__/views/pages-list-view.test.js.map +1 -1
  30. package/dist/lib/fetch-all-pages.d.ts +18 -0
  31. package/dist/lib/fetch-all-pages.d.ts.map +1 -0
  32. package/dist/lib/fetch-all-pages.js +45 -0
  33. package/dist/lib/fetch-all-pages.js.map +1 -0
  34. package/dist/lib/pages-service.d.ts +1 -1
  35. package/dist/lib/pages-service.d.ts.map +1 -1
  36. package/dist/lib/pages-service.js +24 -10
  37. package/dist/lib/pages-service.js.map +1 -1
  38. package/dist/lib/useApiData.d.ts +2 -0
  39. package/dist/lib/useApiData.d.ts.map +1 -1
  40. package/dist/lib/useApiData.js +17 -8
  41. package/dist/lib/useApiData.js.map +1 -1
  42. package/dist/router/index.d.ts.map +1 -1
  43. package/dist/router/index.js +29 -2
  44. package/dist/router/index.js.map +1 -1
  45. package/dist/views/Dashboard.js +1 -1
  46. package/dist/views/Dashboard.js.map +1 -1
  47. package/dist/views/FormsSettings.d.ts.map +1 -1
  48. package/dist/views/FormsSettings.js +10 -3
  49. package/dist/views/FormsSettings.js.map +1 -1
  50. package/dist/views/MediaBrowser.d.ts.map +1 -1
  51. package/dist/views/MediaBrowser.js +11 -7
  52. package/dist/views/MediaBrowser.js.map +1 -1
  53. package/dist/views/Pages/PagesListView.d.ts.map +1 -1
  54. package/dist/views/Pages/PagesListView.js +3 -1
  55. package/dist/views/Pages/PagesListView.js.map +1 -1
  56. package/dist/views/entries/EntriesInbox.d.ts.map +1 -1
  57. package/dist/views/entries/EntriesInbox.js +66 -5
  58. package/dist/views/entries/EntriesInbox.js.map +1 -1
  59. package/package.json +4 -4
  60. package/src/__tests__/lib/fetch-all-pages.test.ts +49 -0
  61. package/src/__tests__/views/audit-entries.test.tsx +182 -0
  62. package/src/__tests__/views/audit-media.test.tsx +88 -0
  63. package/src/__tests__/views/audit-navigation.test.tsx +57 -0
  64. package/src/__tests__/views/audit-pages.test.tsx +81 -0
  65. package/src/__tests__/views/audit-settings.test.tsx +126 -0
  66. package/src/__tests__/views/dashboard.test.tsx +8 -0
  67. package/src/__tests__/views/pages-list-view.test.tsx +10 -1
  68. package/src/lib/fetch-all-pages.ts +55 -0
  69. package/src/lib/pages-service.ts +27 -20
  70. package/src/lib/useApiData.ts +18 -7
  71. package/src/router/index.ts +40 -2
  72. package/src/views/Dashboard.tsx +1 -1
  73. package/src/views/FormsSettings.tsx +11 -4
  74. package/src/views/MediaBrowser.tsx +12 -8
  75. package/src/views/Pages/PagesListView.tsx +3 -1
  76. package/src/views/entries/EntriesInbox.tsx +79 -4
@@ -27,6 +27,7 @@
27
27
  * `Page[]` / `PageTag[]` shapes.
28
28
  */
29
29
  import { cmsApi } from './api.js'
30
+ import { fetchAllPages, PaginatedRequestError } from './fetch-all-pages.js'
30
31
 
31
32
  export type PageStatus = 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED'
32
33
 
@@ -155,11 +156,6 @@ interface DocumentApiRow {
155
156
  data: Record<string, unknown> | null
156
157
  }
157
158
 
158
- interface ListEnvelope {
159
- docs: DocumentApiRow[]
160
- total: number
161
- }
162
-
163
159
  interface UserApiRow {
164
160
  id: string
165
161
  name?: string | null
@@ -178,8 +174,12 @@ function initialsFromName(name: string | null | undefined, email: string): strin
178
174
  return (email[0] ?? '?').toUpperCase()
179
175
  }
180
176
 
181
- async function fetchAuthorsMap(): Promise<Map<string, PageAuthor>> {
182
- const res = await cmsApi<{ users: UserApiRow[] } | UserApiRow[]>('/users?pageSize=200')
177
+ async function fetchAuthorsMap(signal?: AbortSignal): Promise<Map<string, PageAuthor>> {
178
+ signal?.throwIfAborted()
179
+ const res = await cmsApi<{ users: UserApiRow[] } | UserApiRow[]>('/users?pageSize=200', {
180
+ signal,
181
+ })
182
+ signal?.throwIfAborted()
183
183
  const list: UserApiRow[] = Array.isArray(res.data)
184
184
  ? res.data
185
185
  : ((res.data as { users?: UserApiRow[] } | null)?.users ?? [])
@@ -237,11 +237,19 @@ function docToTag(d: DocumentApiRow, pageCount: number): PageTag {
237
237
  }
238
238
  }
239
239
 
240
- async function fetchTagDocs(): Promise<DocumentApiRow[]> {
241
- const res = await cmsApi<ListEnvelope>(
242
- `/collections/${PAGE_TAGS_COLLECTION}?pageSize=500&sort=updatedAt&order=desc&pick=${TAG_LIST_PICK}`,
243
- )
244
- return (res.data?.docs ?? []) as DocumentApiRow[]
240
+ async function fetchTagDocs(signal?: AbortSignal): Promise<DocumentApiRow[]> {
241
+ try {
242
+ const res = await fetchAllPages<DocumentApiRow>(
243
+ `/collections/${PAGE_TAGS_COLLECTION}?pageSize=100&sort=updatedAt&order=desc&pick=${TAG_LIST_PICK}`,
244
+ signal,
245
+ )
246
+ return res.docs
247
+ } catch (error) {
248
+ // Tags are optional, but permission, network and server failures are not
249
+ // equivalent to an unregistered tag collection.
250
+ if (error instanceof PaginatedRequestError && error.status === 404) return []
251
+ throw error
252
+ }
245
253
  }
246
254
 
247
255
  // ─── Pages ───────────────────────────────────────────────────────────
@@ -384,19 +392,18 @@ function statusLabel(s: PageStatus): string {
384
392
  * shaping in memory. Tag page counts and the author list are derived from
385
393
  * the full set so they reflect the dataset, not any active filter.
386
394
  */
387
- export async function fetchPagesDataset(): Promise<PagesDataset> {
388
- const authorsMap = await fetchAuthorsMap()
395
+ export async function fetchPagesDataset(signal?: AbortSignal): Promise<PagesDataset> {
396
+ const authorsMap = await fetchAuthorsMap(signal)
389
397
 
390
398
  const [pagesRes, tagDocs] = await Promise.all([
391
- cmsApi<ListEnvelope>(
392
- `/collections/${PAGES_COLLECTION}?pageSize=500&sort=updatedAt&order=desc&pick=${PAGE_LIST_PICK}`,
399
+ fetchAllPages<DocumentApiRow>(
400
+ `/collections/${PAGES_COLLECTION}?pageSize=100&sort=updatedAt&order=desc&pick=${PAGE_LIST_PICK}`,
401
+ signal,
393
402
  ),
394
- fetchTagDocs(),
403
+ fetchTagDocs(signal),
395
404
  ])
396
405
 
397
- const allPages = ((pagesRes.data?.docs ?? []) as DocumentApiRow[]).map((d) =>
398
- docToPage(d, authorsMap),
399
- )
406
+ const allPages = pagesRes.docs.map((d) => docToPage(d, authorsMap))
400
407
 
401
408
  const counts = new Map<string, number>()
402
409
  for (const p of allPages) {
@@ -1,8 +1,11 @@
1
1
  'use client'
2
2
  import { useState, useEffect, useCallback, useRef } from 'react'
3
3
  import { cmsApi } from './api.js'
4
+ import { fetchAllPages } from './fetch-all-pages.js'
4
5
 
5
6
  export interface UseApiDataOptions {
7
+ /** Collect every server page for a locally filtered docs/total dataset. */
8
+ allPages?: boolean
6
9
  maxRetries?: number
7
10
  /** Base delay in ms for exponential backoff (default 1000). Actual delay = base * 2^attempt. */
8
11
  retryBaseMs?: number
@@ -50,10 +53,11 @@ export function useApiData<T>(
50
53
  defaultValue: T | null = null,
51
54
  options: UseApiDataOptions = {},
52
55
  ): UseApiDataResult<T> {
53
- const { maxRetries = 3, retryBaseMs = 1000, cacheMs } = options
56
+ const { maxRetries = 3, retryBaseMs = 1000, cacheMs, allPages = false } = options
57
+ const cacheKey = endpoint && allPages ? `all-pages:${endpoint}` : endpoint
54
58
  // Read the cache synchronously for the initial state so a warm cache
55
59
  // hit paints immediately instead of flashing a loading spinner.
56
- const cachedInitial = endpoint && cacheMs ? readCache<T>(endpoint, cacheMs) : null
60
+ const cachedInitial = cacheKey && cacheMs ? readCache<T>(cacheKey, cacheMs) : null
57
61
  const [data, setData] = useState<T | null>(cachedInitial ? cachedInitial.value : defaultValue)
58
62
  const [loading, setLoading] = useState(endpoint !== null && !cachedInitial)
59
63
  const [error, setError] = useState<string | null>(null)
@@ -71,8 +75,8 @@ export function useApiData<T>(
71
75
 
72
76
  // Cache-first: a fresh cached response short-circuits the network.
73
77
  // `refetch()` passes `forceRefresh` to bypass this.
74
- if (!isRetry && !forceRefresh && cacheMs) {
75
- const hit = readCache<T>(endpoint, cacheMs)
78
+ if (!isRetry && !forceRefresh && cacheMs && cacheKey) {
79
+ const hit = readCache<T>(cacheKey, cacheMs)
76
80
  if (hit) {
77
81
  setData(hit.value)
78
82
  setError(null)
@@ -93,7 +97,14 @@ export function useApiData<T>(
93
97
  setLoading(true)
94
98
  setError(null)
95
99
 
96
- const res = await cmsApi<T>(endpoint, { signal: controller.signal })
100
+ const res = allPages
101
+ ? await fetchAllPages(endpoint, controller.signal)
102
+ .then((data) => ({ data: data as T, error: undefined }))
103
+ .catch((err: unknown) => ({
104
+ data: undefined,
105
+ error: err instanceof Error ? err.message : 'Could not load list',
106
+ }))
107
+ : await cmsApi<T>(endpoint, { signal: controller.signal })
97
108
 
98
109
  if (controller.signal.aborted) return
99
110
 
@@ -112,10 +123,10 @@ export function useApiData<T>(
112
123
  setData(value)
113
124
  setLoading(false)
114
125
  retryCountRef.current = 0
115
- if (cacheMs) responseCache.set(endpoint, { data: value, at: Date.now() })
126
+ if (cacheMs && cacheKey) responseCache.set(cacheKey, { data: value, at: Date.now() })
116
127
  }
117
128
  },
118
- [endpoint, maxRetries, retryBaseMs, cacheMs],
129
+ [endpoint, maxRetries, retryBaseMs, cacheMs, allPages, cacheKey],
119
130
  )
120
131
 
121
132
  const manualRefetch = useCallback(() => {
@@ -90,9 +90,19 @@ export function useAdminRouter(basePath = '/admin', serverPath = '/') {
90
90
  const [currentPath, setCurrentPath] = useState(serverPath)
91
91
  const baseRef = useRef(basePath)
92
92
  baseRef.current = basePath
93
+ const historyIndex = useRef(0)
94
+ const restoringHistory = useRef(false)
95
+ const acceptedUrl = useRef('')
93
96
 
94
97
  useEffect(() => {
95
98
  if (typeof window !== 'undefined') {
99
+ historyIndex.current = window.history.state?.adminHistoryIndex ?? 0
100
+ acceptedUrl.current = window.location.href
101
+ window.history.replaceState(
102
+ { ...window.history.state, adminHistoryIndex: historyIndex.current, __NA: true },
103
+ '',
104
+ window.location.href,
105
+ )
96
106
  // Include the query string so state-bearing URLs (`/pages/new?parent=x`,
97
107
  // `/settings?tab=users`) survive hard reloads. matchRoute strips the
98
108
  // query before matching, so `/?foo=1` still resolves to `/`.
@@ -104,7 +114,29 @@ export function useAdminRouter(basePath = '/admin', serverPath = '/') {
104
114
  }, []) // eslint-disable-line react-hooks/exhaustive-deps
105
115
 
106
116
  useEffect(() => {
107
- function onPopState() {
117
+ function onPopState(event: PopStateEvent) {
118
+ if (restoringHistory.current) {
119
+ restoringHistory.current = false
120
+ return
121
+ }
122
+ if (hasBlockingNavigation() && !window.confirm(NAVIGATION_CONFIRM_MESSAGE)) {
123
+ const targetIndex = event.state?.adminHistoryIndex
124
+ if (typeof targetIndex === 'number' && targetIndex !== historyIndex.current) {
125
+ // Undo the traversal without adding an entry or destroying Forward.
126
+ restoringHistory.current = true
127
+ window.history.go(historyIndex.current - targetIndex)
128
+ } else {
129
+ // Older/unmanaged history entries have no index to traverse back to.
130
+ window.history.replaceState(
131
+ { ...window.history.state, adminHistoryIndex: historyIndex.current, __NA: true },
132
+ '',
133
+ acceptedUrl.current,
134
+ )
135
+ }
136
+ return
137
+ }
138
+ historyIndex.current = event.state?.adminHistoryIndex ?? historyIndex.current
139
+ acceptedUrl.current = window.location.href
108
140
  // Query string included for the same reason as the mount sync above —
109
141
  // back/forward must restore deep-link state, not just the pathname.
110
142
  setCurrentPath(stripBase(window.location.pathname, baseRef.current) + window.location.search)
@@ -129,7 +161,13 @@ export function useAdminRouter(basePath = '/admin', serverPath = '/') {
129
161
  // of running its URL-parsing path (which throws "Invalid URL"). The admin is
130
162
  // a self-contained SPA with its own `popstate` listener, so we deliberately
131
163
  // bypass Next's router/RSC sync on in-admin navigation.
132
- window.history.pushState({ adminPath: normalizedPath, __NA: true }, '', fullUrl)
164
+ historyIndex.current += 1
165
+ window.history.pushState(
166
+ { adminPath: normalizedPath, adminHistoryIndex: historyIndex.current, __NA: true },
167
+ '',
168
+ fullUrl,
169
+ )
170
+ acceptedUrl.current = window.location.href
133
171
  }, [])
134
172
 
135
173
  // Build an absolute (basePath-prefixed) admin URL without navigating. Used
@@ -350,7 +350,7 @@ export function Dashboard({ config, session, onNavigate }: DashboardProps) {
350
350
  // replaceState as a navigation and remounts the admin panel, so an
351
351
  // unconditional write here loops the page.
352
352
  if (nextUrl !== `${window.location.pathname}${window.location.search}`) {
353
- window.history.replaceState(null, '', nextUrl)
353
+ window.history.replaceState(window.history.state, '', nextUrl)
354
354
  }
355
355
  window.localStorage.setItem(
356
356
  userPreferenceKey(session),
@@ -34,6 +34,7 @@ import {
34
34
  type FormsSettingsDocument,
35
35
  } from '../lib/forms-service.js'
36
36
  import { getRecaptchaV3Token } from '../lib/recaptcha.js'
37
+ import { useNavigationBlocker } from '../router/index.js'
37
38
 
38
39
  const TABS = [
39
40
  { id: 'spam', label: 'Spam protection', icon: Shield },
@@ -224,6 +225,7 @@ export function FormsSettings({
224
225
  }, [saved, draft])
225
226
 
226
227
  const dirty = dirtyCount > 0
228
+ const releaseNavigation = useNavigationBlocker(dirty || saving)
227
229
 
228
230
  function tabDirty(id: TabId): number {
229
231
  if (!saved || !draft) return 0
@@ -231,7 +233,7 @@ export function FormsSettings({
231
233
  }
232
234
 
233
235
  function go(next: TabId) {
234
- if (next === tab) return
236
+ if (saving || next === tab) return
235
237
  const pending = tabDirty(tab)
236
238
  if (pending > 0 && saved && draft) {
237
239
  const label = `${pending} unsaved ${pending === 1 ? 'change' : 'changes'}`
@@ -239,6 +241,8 @@ export function FormsSettings({
239
241
  setDraft(restoreSection(saved, draft, tab))
240
242
  }
241
243
  setTab(next)
244
+ // This tab transition already confirmed any discarded work above.
245
+ releaseNavigation()
242
246
  onNavigate?.(`/forms/settings/${next}`)
243
247
  }
244
248
 
@@ -264,7 +268,9 @@ export function FormsSettings({
264
268
  }
265
269
  setFieldErrors({})
266
270
  setSaved(result.data)
267
- setDraft(result.data)
271
+ // Keep edits made after this request began. They remain dirty against
272
+ // the acknowledged server snapshot and can be saved in the next request.
273
+ setDraft((current) => (current === draft ? result.data! : current))
268
274
  setSaveState('saved')
269
275
  }
270
276
 
@@ -322,6 +328,7 @@ export function FormsSettings({
322
328
  return {
323
329
  id: item.id,
324
330
  label: item.label,
331
+ disabled: saving && item.id !== tab,
325
332
  icon: <Icon size={15} strokeWidth={1.75} />,
326
333
  badge:
327
334
  pending > 0 ? (
@@ -848,9 +855,9 @@ export function FormsSettings({
848
855
  <SettingsSaveBar
849
856
  dirty={dirty}
850
857
  count={dirtyCount}
851
- state={saveState}
858
+ state={saveState === 'saved' && dirty ? 'idle' : saveState}
852
859
  invalid={Object.keys(attributionErrors).length}
853
- onDiscard={() => saved && setDraft(saved)}
860
+ onDiscard={() => !saving && saved && setDraft(saved)}
854
861
  onSave={() => void save()}
855
862
  />
856
863
  )}
@@ -203,7 +203,7 @@ export function mediaGridColumns(contentWidth: number): number {
203
203
  function buildMediaApiUrl(folderSel: FolderSelection): string {
204
204
  const base = '/media?pageSize=100'
205
205
  if (folderSel.type === 'smart') {
206
- if (folderSel.smart === 'recent') return `${base}&sort=updatedAt&order=desc&pageSize=20`
206
+ if (folderSel.smart === 'recent') return '/media?pageSize=20&sort=updatedAt&order=desc'
207
207
  if (folderSel.smart === 'uncategorized') return `${base}&folderId=none`
208
208
  if (folderSel.smart === 'trash') return `${base}&trashed=1`
209
209
  return base
@@ -226,7 +226,7 @@ export function MediaBrowser({ onNavigate, currentPath, role, config }: MediaBro
226
226
  const { data, loading, error, refetch } = useApiData<{
227
227
  docs?: MediaItem[]
228
228
  total: number
229
- }>(apiUrl)
229
+ }>(apiUrl, null, { allPages: !(folderSel.type === 'smart' && folderSel.smart === 'recent') })
230
230
 
231
231
  const allData = useApiData<{ docs?: MediaItem[]; total: number }>('/media?pageSize=1')
232
232
  const uncatData = useApiData<{ docs?: MediaItem[]; total: number }>(
@@ -1073,14 +1073,18 @@ export function MediaBrowser({ onNavigate, currentPath, role, config }: MediaBro
1073
1073
  <ImageIcon className="text-muted-foreground h-6 w-6" />
1074
1074
  </div>
1075
1075
  <h2 className="text-foreground mb-1 text-sm font-medium">
1076
- {folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
1077
- ? 'No uncategorized media'
1078
- : folderSel.type === 'folder'
1079
- ? 'No media in this folder'
1080
- : 'No media yet'}
1076
+ {searchQuery.trim() || filterType !== 'all'
1077
+ ? 'No matching media'
1078
+ : folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
1079
+ ? 'No uncategorized media'
1080
+ : folderSel.type === 'folder'
1081
+ ? 'No media in this folder'
1082
+ : 'No media yet'}
1081
1083
  </h2>
1082
1084
  <p className="text-muted-foreground text-sm">
1083
- Upload your first file to get started.
1085
+ {searchQuery.trim() || filterType !== 'all'
1086
+ ? 'Try a different search or file type.'
1087
+ : 'Upload your first file to get started.'}
1084
1088
  </p>
1085
1089
  </div>
1086
1090
  ) : (
@@ -175,9 +175,10 @@ export function PagesListView({ onNavigate, role, config }: PagesListViewProps)
175
175
  // refreshes only on mount and after a mutation (refreshToken bump).
176
176
  useEffect(() => {
177
177
  let cancelled = false
178
+ const controller = new AbortController()
178
179
  setLoading(true)
179
180
  setError(null)
180
- fetchPagesDataset()
181
+ fetchPagesDataset(controller.signal)
181
182
  .then((res) => {
182
183
  if (cancelled) return
183
184
  setDataset(res)
@@ -190,6 +191,7 @@ export function PagesListView({ onNavigate, role, config }: PagesListViewProps)
190
191
  })
191
192
  return () => {
192
193
  cancelled = true
194
+ controller.abort()
193
195
  }
194
196
  }, [refreshToken])
195
197
 
@@ -318,6 +318,13 @@ export function EntriesInbox({
318
318
  const [total, setTotal] = useState(0)
319
319
  const [counts, setCounts] = useState<EntryCounts | null>(null)
320
320
  const [loading, setLoading] = useState(true)
321
+ const [loadingMore, setLoadingMore] = useState(false)
322
+ const [refreshing, setRefreshing] = useState(false)
323
+ const refreshInFlight = useRef(false)
324
+ const [moreError, setMoreError] = useState<string | null>(null)
325
+ const [nextPage, setNextPage] = useState<number | null>(null)
326
+ const moreInFlight = useRef(false)
327
+ const loadedPageCount = useRef(5)
321
328
  const loadRequestRef = useRef(0)
322
329
  const loadedQueryRef = useRef<string | null>(null)
323
330
  // Track operations separately: overlapping writes to one entry must not
@@ -600,7 +607,7 @@ export function EntriesInbox({
600
607
  const search = params.toString()
601
608
  const path = `/forms/entries${search ? `?${search}` : ''}`
602
609
  if (onNavigate) onNavigate(path)
603
- else window.history.replaceState(null, '', path)
610
+ else window.history.replaceState(window.history.state, '', path)
604
611
  },
605
612
  [formId, onNavigate],
606
613
  )
@@ -608,18 +615,27 @@ export function EntriesInbox({
608
615
  const load = useCallback(
609
616
  async (background = false) => {
610
617
  const request = ++loadRequestRef.current
618
+ refreshInFlight.current = true
619
+ setRefreshing(true)
620
+ moreInFlight.current = false
621
+ setLoadingMore(false)
622
+ setMoreError(null)
611
623
  const query = JSON.stringify([filter, scopedFormId, search.trim(), currentUserId])
612
624
  // An event may supersede a foreground load. Until this query has a
613
625
  // successful dataset, its failures must remain foreground errors.
614
626
  const keepRows = background && loadedQueryRef.current === query
615
- if (!keepRows) setLoading(true)
627
+ if (!keepRows) {
628
+ setLoading(true)
629
+ setNextPage(null)
630
+ }
616
631
  setError(null)
617
632
  const params = filterParams(filter, currentUserId)
618
633
  try {
619
634
  const collected: FormSubmission[] = []
620
635
  const seen = new Set<string>()
621
636
  let reported = 0
622
- for (let page = 1; page <= 5; page++) {
637
+ let continuation: number | null = null
638
+ for (let page = 1; page <= loadedPageCount.current; page++) {
623
639
  const result = await fetchEntries({
624
640
  formId: scopedFormId,
625
641
  search: search.trim() || undefined,
@@ -634,6 +650,7 @@ export function EntriesInbox({
634
650
  const fresh = result.entries.filter((entry) => !seen.has(entry.id))
635
651
  for (const entry of fresh) seen.add(entry.id)
636
652
  collected.push(...fresh)
653
+ continuation = collected.length < reported && fresh.length > 0 ? page + 1 : null
637
654
  if (
638
655
  collected.length >= reported ||
639
656
  fresh.length === 0 ||
@@ -646,6 +663,7 @@ export function EntriesInbox({
646
663
  setEntries(applyPendingPatches(collected))
647
664
  loadedQueryRef.current = query
648
665
  setTotal(reported)
666
+ setNextPage(continuation)
649
667
  setChecked((current) =>
650
668
  keepRows ? new Set([...current].filter((id) => seen.has(id))) : new Set(),
651
669
  )
@@ -655,12 +673,53 @@ export function EntriesInbox({
655
673
  if (keepRows) toast.error(message)
656
674
  else setError(message)
657
675
  } finally {
658
- if (request === loadRequestRef.current) setLoading(false)
676
+ if (request === loadRequestRef.current) {
677
+ refreshInFlight.current = false
678
+ setRefreshing(false)
679
+ setLoading(false)
680
+ }
659
681
  }
660
682
  },
661
683
  [filter, scopedFormId, search, currentUserId, applyPendingPatches],
662
684
  )
663
685
 
686
+ async function loadMore() {
687
+ if (nextPage === null || moreInFlight.current || refreshInFlight.current) return
688
+ moreInFlight.current = true
689
+ const generation = ++loadRequestRef.current
690
+ setLoadingMore(true)
691
+ setMoreError(null)
692
+ try {
693
+ const result = await fetchEntries({
694
+ formId: scopedFormId,
695
+ search: search.trim() || undefined,
696
+ page: nextPage,
697
+ pageSize: PAGE_SIZE,
698
+ sortBy: 'submittedAt',
699
+ sortDirection: 'desc',
700
+ ...filterParams(filter, currentUserId),
701
+ })
702
+ if (generation !== loadRequestRef.current) return
703
+ const seen = new Set(entries.map((entry) => entry.id))
704
+ const fresh = result.entries.filter((entry) => !seen.has(entry.id))
705
+ if (fresh.length === 0 && entries.length < result.total) {
706
+ throw new Error('The list changed while loading. Refresh the list and try again.')
707
+ }
708
+ setEntries((current) => applyPendingPatches([...current, ...fresh]))
709
+ loadedPageCount.current = nextPage
710
+ setTotal(result.total)
711
+ setNextPage(entries.length + fresh.length < result.total ? nextPage + 1 : null)
712
+ } catch (err) {
713
+ if (generation === loadRequestRef.current)
714
+ setMoreError(err instanceof Error ? err.message : 'Failed to load more entries')
715
+ } finally {
716
+ if (generation === loadRequestRef.current) {
717
+ moreInFlight.current = false
718
+ setLoadingMore(false)
719
+ }
720
+ }
721
+ }
722
+
664
723
  const loadCounts = useCallback(() => {
665
724
  void fetchEntryCounts({
666
725
  formId: scopedFormId,
@@ -675,6 +734,7 @@ export function EntriesInbox({
675
734
  }, [])
676
735
 
677
736
  useEffect(() => {
737
+ loadedPageCount.current = 5
678
738
  void load()
679
739
  return cancelLoad
680
740
  }, [load, cancelLoad])
@@ -1574,6 +1634,21 @@ export function EntriesInbox({
1574
1634
  )}
1575
1635
  </div>
1576
1636
  <div className="border-bdr text-faint flex shrink-0 items-center gap-2 border-t px-3 py-[7px] text-[11px]">
1637
+ {nextPage !== null && !loading && (
1638
+ <button
1639
+ type="button"
1640
+ className="text-acc underline"
1641
+ disabled={loadingMore || refreshing}
1642
+ onClick={() => void loadMore()}
1643
+ >
1644
+ {loadingMore ? 'Loading more…' : 'Load more entries'}
1645
+ </button>
1646
+ )}
1647
+ {moreError && (
1648
+ <span role="alert" className="text-err">
1649
+ {moreError}
1650
+ </span>
1651
+ )}
1577
1652
  <span>
1578
1653
  Showing{' '}
1579
1654
  <b className="text-sub font-semibold tabular-nums">{visibleEntries.length}</b> of{' '}