@strapi/upload 5.52.3 → 5.54.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 (220) hide show
  1. package/dist/admin/future/components/Drawer.js +6 -3
  2. package/dist/admin/future/components/Drawer.js.map +1 -1
  3. package/dist/admin/future/components/Drawer.mjs +6 -3
  4. package/dist/admin/future/components/Drawer.mjs.map +1 -1
  5. package/dist/admin/future/components/UploadProgressDialog.js +9 -8
  6. package/dist/admin/future/components/UploadProgressDialog.js.map +1 -1
  7. package/dist/admin/future/components/UploadProgressDialog.mjs +9 -8
  8. package/dist/admin/future/components/UploadProgressDialog.mjs.map +1 -1
  9. package/dist/admin/future/pages/Assets/AssetsPage.js +16 -4
  10. package/dist/admin/future/pages/Assets/AssetsPage.js.map +1 -1
  11. package/dist/admin/future/pages/Assets/AssetsPage.mjs +16 -4
  12. package/dist/admin/future/pages/Assets/AssetsPage.mjs.map +1 -1
  13. package/dist/admin/future/pages/Assets/components/AssetActionsMenu.js +5 -0
  14. package/dist/admin/future/pages/Assets/components/AssetActionsMenu.js.map +1 -1
  15. package/dist/admin/future/pages/Assets/components/AssetActionsMenu.mjs +5 -0
  16. package/dist/admin/future/pages/Assets/components/AssetActionsMenu.mjs.map +1 -1
  17. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetCropEditor.js +19 -4
  18. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetCropEditor.js.map +1 -1
  19. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetCropEditor.mjs +19 -4
  20. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetCropEditor.mjs.map +1 -1
  21. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetDetailsDrawer.js +35 -1
  22. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetDetailsDrawer.js.map +1 -1
  23. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetDetailsDrawer.mjs +35 -1
  24. package/dist/admin/future/pages/Assets/components/AssetDetails/AssetDetailsDrawer.mjs.map +1 -1
  25. package/dist/admin/future/pages/Assets/components/AssetsGrid.js +10 -0
  26. package/dist/admin/future/pages/Assets/components/AssetsGrid.js.map +1 -1
  27. package/dist/admin/future/pages/Assets/components/AssetsGrid.mjs +10 -0
  28. package/dist/admin/future/pages/Assets/components/AssetsGrid.mjs.map +1 -1
  29. package/dist/admin/future/pages/Assets/components/AssetsTable.js +9 -0
  30. package/dist/admin/future/pages/Assets/components/AssetsTable.js.map +1 -1
  31. package/dist/admin/future/pages/Assets/components/AssetsTable.mjs +10 -1
  32. package/dist/admin/future/pages/Assets/components/AssetsTable.mjs.map +1 -1
  33. package/dist/admin/future/pages/Assets/components/BulkActionsBar.js +132 -88
  34. package/dist/admin/future/pages/Assets/components/BulkActionsBar.js.map +1 -1
  35. package/dist/admin/future/pages/Assets/components/BulkActionsBar.mjs +135 -91
  36. package/dist/admin/future/pages/Assets/components/BulkActionsBar.mjs.map +1 -1
  37. package/dist/admin/future/pages/Assets/components/Dnd/AssetsDndProvider.js +7 -0
  38. package/dist/admin/future/pages/Assets/components/Dnd/AssetsDndProvider.js.map +1 -1
  39. package/dist/admin/future/pages/Assets/components/Dnd/AssetsDndProvider.mjs +7 -0
  40. package/dist/admin/future/pages/Assets/components/Dnd/AssetsDndProvider.mjs.map +1 -1
  41. package/dist/admin/future/pages/Assets/components/Dnd/DragOverlayChip.js +4 -1
  42. package/dist/admin/future/pages/Assets/components/Dnd/DragOverlayChip.js.map +1 -1
  43. package/dist/admin/future/pages/Assets/components/Dnd/DragOverlayChip.mjs +4 -1
  44. package/dist/admin/future/pages/Assets/components/Dnd/DragOverlayChip.mjs.map +1 -1
  45. package/dist/admin/future/pages/Assets/components/MainAreaContextMenu.js +181 -0
  46. package/dist/admin/future/pages/Assets/components/MainAreaContextMenu.js.map +1 -0
  47. package/dist/admin/future/pages/Assets/components/MainAreaContextMenu.mjs +179 -0
  48. package/dist/admin/future/pages/Assets/components/MainAreaContextMenu.mjs.map +1 -0
  49. package/dist/admin/future/pages/Assets/constants.js +22 -0
  50. package/dist/admin/future/pages/Assets/constants.js.map +1 -1
  51. package/dist/admin/future/pages/Assets/constants.mjs +19 -1
  52. package/dist/admin/future/pages/Assets/constants.mjs.map +1 -1
  53. package/dist/admin/future/pages/Assets/hooks/useInfiniteAssets.js +65 -10
  54. package/dist/admin/future/pages/Assets/hooks/useInfiniteAssets.js.map +1 -1
  55. package/dist/admin/future/pages/Assets/hooks/useInfiniteAssets.mjs +66 -11
  56. package/dist/admin/future/pages/Assets/hooks/useInfiniteAssets.mjs.map +1 -1
  57. package/dist/admin/future/pages/Assets/hooks/useListScrollRestoration.js +111 -0
  58. package/dist/admin/future/pages/Assets/hooks/useListScrollRestoration.js.map +1 -0
  59. package/dist/admin/future/pages/Assets/hooks/useListScrollRestoration.mjs +109 -0
  60. package/dist/admin/future/pages/Assets/hooks/useListScrollRestoration.mjs.map +1 -0
  61. package/dist/admin/future/services/api.js +17 -0
  62. package/dist/admin/future/services/api.js.map +1 -1
  63. package/dist/admin/future/services/api.mjs +18 -1
  64. package/dist/admin/future/services/api.mjs.map +1 -1
  65. package/dist/admin/future/store/uploadProgress.js +31 -22
  66. package/dist/admin/future/store/uploadProgress.js.map +1 -1
  67. package/dist/admin/future/store/uploadProgress.mjs +31 -22
  68. package/dist/admin/future/store/uploadProgress.mjs.map +1 -1
  69. package/dist/admin/index.js +11 -10
  70. package/dist/admin/index.js.map +1 -1
  71. package/dist/admin/index.mjs +11 -10
  72. package/dist/admin/index.mjs.map +1 -1
  73. package/dist/admin/src/future/components/Drawer.d.ts +10 -0
  74. package/dist/admin/src/future/pages/Assets/components/MainAreaContextMenu.d.ts +28 -0
  75. package/dist/admin/src/future/pages/Assets/constants.d.ts +20 -0
  76. package/dist/admin/src/future/pages/Assets/hooks/useInfiniteAssets.d.ts +4 -0
  77. package/dist/admin/src/future/pages/Assets/hooks/useListScrollRestoration.d.ts +15 -0
  78. package/dist/admin/src/future/store/uploadProgress.d.ts +14 -20
  79. package/dist/admin/translations/en.json.js +1 -3
  80. package/dist/admin/translations/en.json.js.map +1 -1
  81. package/dist/admin/translations/en.json.mjs +1 -3
  82. package/dist/admin/translations/en.json.mjs.map +1 -1
  83. package/dist/server/bootstrap.js +11 -0
  84. package/dist/server/bootstrap.js.map +1 -1
  85. package/dist/server/bootstrap.mjs +11 -0
  86. package/dist/server/bootstrap.mjs.map +1 -1
  87. package/dist/server/controllers/admin-upload.js +31 -1
  88. package/dist/server/controllers/admin-upload.js.map +1 -1
  89. package/dist/server/controllers/admin-upload.mjs +31 -1
  90. package/dist/server/controllers/admin-upload.mjs.map +1 -1
  91. package/dist/server/controllers/utils/find-entity-and-check-permissions.js +15 -4
  92. package/dist/server/controllers/utils/find-entity-and-check-permissions.js.map +1 -1
  93. package/dist/server/controllers/utils/find-entity-and-check-permissions.mjs +15 -4
  94. package/dist/server/controllers/utils/find-entity-and-check-permissions.mjs.map +1 -1
  95. package/dist/server/controllers/utils/folders.js +1 -1
  96. package/dist/server/controllers/utils/folders.js.map +1 -1
  97. package/dist/server/controllers/utils/folders.mjs +1 -1
  98. package/dist/server/controllers/utils/folders.mjs.map +1 -1
  99. package/dist/server/mcp/ambient-instance.js +46 -0
  100. package/dist/server/mcp/ambient-instance.js.map +1 -0
  101. package/dist/server/mcp/ambient-instance.mjs +43 -0
  102. package/dist/server/mcp/ambient-instance.mjs.map +1 -0
  103. package/dist/server/mcp/handlers/constants.js +60 -0
  104. package/dist/server/mcp/handlers/constants.js.map +1 -0
  105. package/dist/server/mcp/handlers/constants.mjs +45 -0
  106. package/dist/server/mcp/handlers/constants.mjs.map +1 -0
  107. package/dist/server/mcp/handlers/folder-handlers.js +308 -0
  108. package/dist/server/mcp/handlers/folder-handlers.js.map +1 -0
  109. package/dist/server/mcp/handlers/folder-handlers.mjs +303 -0
  110. package/dist/server/mcp/handlers/folder-handlers.mjs.map +1 -0
  111. package/dist/server/mcp/handlers/read-handlers.js +134 -0
  112. package/dist/server/mcp/handlers/read-handlers.js.map +1 -0
  113. package/dist/server/mcp/handlers/read-handlers.mjs +130 -0
  114. package/dist/server/mcp/handlers/read-handlers.mjs.map +1 -0
  115. package/dist/server/mcp/handlers/write-handlers.js +315 -0
  116. package/dist/server/mcp/handlers/write-handlers.js.map +1 -0
  117. package/dist/server/mcp/handlers/write-handlers.mjs +311 -0
  118. package/dist/server/mcp/handlers/write-handlers.mjs.map +1 -0
  119. package/dist/server/mcp/permissions.js +36 -0
  120. package/dist/server/mcp/permissions.js.map +1 -0
  121. package/dist/server/mcp/permissions.mjs +33 -0
  122. package/dist/server/mcp/permissions.mjs.map +1 -0
  123. package/dist/server/mcp/register-upload-mcp-tools.js +235 -0
  124. package/dist/server/mcp/register-upload-mcp-tools.js.map +1 -0
  125. package/dist/server/mcp/register-upload-mcp-tools.mjs +232 -0
  126. package/dist/server/mcp/register-upload-mcp-tools.mjs.map +1 -0
  127. package/dist/server/mcp/sanitizers/sanitize-media.js +97 -0
  128. package/dist/server/mcp/sanitizers/sanitize-media.js.map +1 -0
  129. package/dist/server/mcp/sanitizers/sanitize-media.mjs +93 -0
  130. package/dist/server/mcp/sanitizers/sanitize-media.mjs.map +1 -0
  131. package/dist/server/mcp/schemas/input-schemas.js +206 -0
  132. package/dist/server/mcp/schemas/input-schemas.js.map +1 -0
  133. package/dist/server/mcp/schemas/input-schemas.mjs +190 -0
  134. package/dist/server/mcp/schemas/input-schemas.mjs.map +1 -0
  135. package/dist/server/mcp/schemas/output-schemas.js +158 -0
  136. package/dist/server/mcp/schemas/output-schemas.js.map +1 -0
  137. package/dist/server/mcp/schemas/output-schemas.mjs +142 -0
  138. package/dist/server/mcp/schemas/output-schemas.mjs.map +1 -0
  139. package/dist/server/mcp/utils.js +14 -0
  140. package/dist/server/mcp/utils.js.map +1 -0
  141. package/dist/server/mcp/utils.mjs +12 -0
  142. package/dist/server/mcp/utils.mjs.map +1 -0
  143. package/dist/server/media-library-default-notice.js +42 -0
  144. package/dist/server/media-library-default-notice.js.map +1 -0
  145. package/dist/server/media-library-default-notice.mjs +40 -0
  146. package/dist/server/media-library-default-notice.mjs.map +1 -0
  147. package/dist/server/register.js +5 -0
  148. package/dist/server/register.js.map +1 -1
  149. package/dist/server/register.mjs +5 -0
  150. package/dist/server/register.mjs.map +1 -1
  151. package/dist/server/services/folder.js.map +1 -1
  152. package/dist/server/services/folder.mjs.map +1 -1
  153. package/dist/server/services/upload.js +34 -10
  154. package/dist/server/services/upload.js.map +1 -1
  155. package/dist/server/services/upload.mjs +34 -10
  156. package/dist/server/services/upload.mjs.map +1 -1
  157. package/dist/server/src/bootstrap.d.ts.map +1 -1
  158. package/dist/server/src/controllers/admin-upload.d.ts +1 -0
  159. package/dist/server/src/controllers/admin-upload.d.ts.map +1 -1
  160. package/dist/server/src/controllers/utils/find-entity-and-check-permissions.d.ts +14 -1
  161. package/dist/server/src/controllers/utils/find-entity-and-check-permissions.d.ts.map +1 -1
  162. package/dist/server/src/controllers/utils/folders.d.ts +2 -1
  163. package/dist/server/src/controllers/utils/folders.d.ts.map +1 -1
  164. package/dist/server/src/index.d.ts +10 -2
  165. package/dist/server/src/index.d.ts.map +1 -1
  166. package/dist/server/src/mcp/ambient-instance.d.ts +65 -0
  167. package/dist/server/src/mcp/ambient-instance.d.ts.map +1 -0
  168. package/dist/server/src/mcp/handlers/constants.d.ts +48 -0
  169. package/dist/server/src/mcp/handlers/constants.d.ts.map +1 -0
  170. package/dist/server/src/mcp/handlers/folder-handlers.d.ts +49 -0
  171. package/dist/server/src/mcp/handlers/folder-handlers.d.ts.map +1 -0
  172. package/dist/server/src/mcp/handlers/index.d.ts +5 -0
  173. package/dist/server/src/mcp/handlers/index.d.ts.map +1 -0
  174. package/dist/server/src/mcp/handlers/read-handlers.d.ts +35 -0
  175. package/dist/server/src/mcp/handlers/read-handlers.d.ts.map +1 -0
  176. package/dist/server/src/mcp/handlers/write-handlers.d.ts +66 -0
  177. package/dist/server/src/mcp/handlers/write-handlers.d.ts.map +1 -0
  178. package/dist/server/src/mcp/index.d.ts +3 -0
  179. package/dist/server/src/mcp/index.d.ts.map +1 -0
  180. package/dist/server/src/mcp/permissions.d.ts +22 -0
  181. package/dist/server/src/mcp/permissions.d.ts.map +1 -0
  182. package/dist/server/src/mcp/register-upload-mcp-tools.d.ts +29 -0
  183. package/dist/server/src/mcp/register-upload-mcp-tools.d.ts.map +1 -0
  184. package/dist/server/src/mcp/sanitizers/sanitize-media.d.ts +63 -0
  185. package/dist/server/src/mcp/sanitizers/sanitize-media.d.ts.map +1 -0
  186. package/dist/server/src/mcp/schemas/index.d.ts +3 -0
  187. package/dist/server/src/mcp/schemas/index.d.ts.map +1 -0
  188. package/dist/server/src/mcp/schemas/input-schemas.d.ts +148 -0
  189. package/dist/server/src/mcp/schemas/input-schemas.d.ts.map +1 -0
  190. package/dist/server/src/mcp/schemas/output-schemas.d.ts +276 -0
  191. package/dist/server/src/mcp/schemas/output-schemas.d.ts.map +1 -0
  192. package/dist/server/src/mcp/types.d.ts +19 -0
  193. package/dist/server/src/mcp/types.d.ts.map +1 -0
  194. package/dist/server/src/mcp/utils.d.ts +4 -0
  195. package/dist/server/src/mcp/utils.d.ts.map +1 -0
  196. package/dist/server/src/media-library-default-notice.d.ts +19 -0
  197. package/dist/server/src/media-library-default-notice.d.ts.map +1 -0
  198. package/dist/server/src/register.d.ts.map +1 -1
  199. package/dist/server/src/services/folder.d.ts +6 -2
  200. package/dist/server/src/services/folder.d.ts.map +1 -1
  201. package/dist/server/src/services/index.d.ts +10 -2
  202. package/dist/server/src/services/index.d.ts.map +1 -1
  203. package/dist/server/src/services/upload.d.ts +10 -1
  204. package/dist/server/src/services/upload.d.ts.map +1 -1
  205. package/dist/server/src/types.d.ts +2 -2
  206. package/dist/server/src/types.d.ts.map +1 -1
  207. package/dist/server/src/utils/index.d.ts +2 -1
  208. package/dist/server/src/utils/index.d.ts.map +1 -1
  209. package/dist/server/utils/index.js +2 -2
  210. package/dist/server/utils/index.js.map +1 -1
  211. package/dist/server/utils/index.mjs +2 -2
  212. package/dist/server/utils/index.mjs.map +1 -1
  213. package/dist/shared/contracts/files.d.ts +22 -0
  214. package/dist/shared/contracts/files.d.ts.map +1 -1
  215. package/package.json +7 -6
  216. package/dist/admin/future/components/BetaNotice.js +0 -72
  217. package/dist/admin/future/components/BetaNotice.js.map +0 -1
  218. package/dist/admin/future/components/BetaNotice.mjs +0 -70
  219. package/dist/admin/future/components/BetaNotice.mjs.map +0 -1
  220. package/dist/admin/src/future/components/BetaNotice.d.ts +0 -11
@@ -1,4 +1,4 @@
1
- import { useState, useCallback, createElement, Fragment, useRef, useEffect, useMemo } from 'react';
1
+ import { useState, useRef, useCallback, createElement, Fragment, useEffect, useMemo } from 'react';
2
2
  import { useDispatch, useStore } from 'react-redux';
3
3
  import { uploadApi } from '../../../services/api.mjs';
4
4
  import { useGetAssetsQuery } from '../../../services/assets.mjs';
@@ -8,6 +8,9 @@ import { getRelationId } from '../../../utils/getRelationId.mjs';
8
8
  import { mergeUploadedAssets } from '../utils/mergeUploadedAssets.mjs';
9
9
 
10
10
  const PAGE_SIZE = 20;
11
+ /**
12
+ * How many list views keep their loaded pages in memory.
13
+ */ const MAX_REMEMBERED_LISTS = 10;
11
14
  /**
12
15
  * Concatenates the pages in ascending order, one entry per asset id.
13
16
  *
@@ -25,6 +28,10 @@ const PAGE_SIZE = 20;
25
28
  ...byId.values()
26
29
  ];
27
30
  };
31
+ /**
32
+ * The highest page an accumulator holds — where the list was last read to, and
33
+ * so where to resume from on the way back.
34
+ */ const deepestPage = (pages)=>Object.keys(pages).reduce((deepest, key)=>Math.max(deepest, Number(key)), 1);
28
35
  /**
29
36
  * Keeps one earlier page's `getAssets` query subscribed and reports its results
30
37
  * back up whenever they change.
@@ -62,6 +69,10 @@ const PAGE_SIZE = 20;
62
69
  * The caller MUST render the returned `subscribers` node — that is what keeps
63
70
  * every loaded page subscribed, so `{Asset, LIST}` invalidations keep the whole
64
71
  * list consistent rather than only the current page.
72
+ *
73
+ * Loaded pages survive navigating away and back: each list's accumulator is
74
+ * remembered (LRU, `MAX_REMEMBERED_LISTS`) and restored when its key returns, so
75
+ * stepping into a subfolder and back out keeps the rows the user scrolled for.
65
76
  */ const useInfiniteAssets = ({ folder = null, sort, search, filters, enabled = true } = {})=>{
66
77
  // Derived from the request args themselves, so a new filter can't reach the
67
78
  // API without also invalidating what was accumulated under the old one.
@@ -92,15 +103,30 @@ const PAGE_SIZE = 20;
92
103
  listKey,
93
104
  pages: {}
94
105
  });
95
- // Derived rather than read straight from state: the render that discovers
96
- // the key change still reaches the query below, and a list with no page 1
97
- // must never be requested at page 2.
98
- const page = pageState.queryKey === queryKey ? pageState.page : 1;
99
- if (pageState.queryKey !== queryKey) {
106
+ // Each list's loaded pages, kept across navigation away from it.
107
+ const memoryRef = useRef(new Map());
108
+ const isNewList = pageState.queryKey !== queryKey;
109
+ const remembered = isNewList ? memoryRef.current.get(queryKey) : undefined;
110
+ // Derived rather than read from state: the render that discovers the key
111
+ // change still reaches the query below, and a list with no page 1 must never
112
+ // be requested at page 2. A remembered list always holds page 1, so resuming
113
+ // at its deepest page can't skip one.
114
+ let page;
115
+ if (!isNewList) {
116
+ page = pageState.page;
117
+ } else if (remembered) {
118
+ page = deepestPage(remembered.pages);
119
+ } else {
120
+ page = 1;
121
+ }
122
+ if (isNewList) {
100
123
  setPageState({
101
124
  queryKey,
102
- page: 1
125
+ page
103
126
  });
127
+ if (remembered) {
128
+ setAccumulated(remembered);
129
+ }
104
130
  }
105
131
  const { currentData, isLoading, isFetching, error, startedTimeStamp, fulfilledTimeStamp } = useGetAssetsQuery({
106
132
  ...queryArgs,
@@ -113,7 +139,8 @@ const PAGE_SIZE = 20;
113
139
  // `currentData` is only ever the payload for the args just passed, so it
114
140
  // belongs to this key at this page — nothing to infer. Its reference is
115
141
  // stable per cache entry, so this settles after one extra render.
116
- if (currentData && (!isSameQuery || accumulated.pages[page] !== currentData.results)) {
142
+ if (// A restore already set the accumulator from memory; don't overwrite it.
143
+ !remembered && currentData && (!isSameQuery || accumulated.pages[page] !== currentData.results)) {
117
144
  setAccumulated(isSameQuery ? {
118
145
  ...accumulated,
119
146
  pages: {
@@ -161,6 +188,29 @@ const PAGE_SIZE = 20;
161
188
  page: earlierPage,
162
189
  onRefreshed: handlePageRefreshed
163
190
  })));
191
+ // Remember what this list has read, so leaving it isn't forgetting it. Filed
192
+ // under `accumulated.queryKey`, not the live `queryKey`: the accumulator names
193
+ // the list it belongs to, so an entry still describing the list being left
194
+ // can't be misfiled under the one being entered.
195
+ useEffect(()=>{
196
+ if (Object.keys(accumulated.pages).length === 0) {
197
+ return;
198
+ }
199
+ const memory = memoryRef.current;
200
+ // Delete before set so the entry moves to the end. Map iterates in
201
+ // insertion order, so the first key is the least recently used.
202
+ memory.delete(accumulated.queryKey);
203
+ memory.set(accumulated.queryKey, accumulated);
204
+ while(memory.size > MAX_REMEMBERED_LISTS){
205
+ const oldest = memory.keys().next();
206
+ if (oldest.done) {
207
+ break;
208
+ }
209
+ memory.delete(oldest.value);
210
+ }
211
+ }, [
212
+ accumulated
213
+ ]);
164
214
  // Drop the left folder's cached `getAssets` pages when the folder changes.
165
215
  //
166
216
  // RTK Query 1.9.7 leaves a query's store subscription in place when its last
@@ -170,8 +220,9 @@ const PAGE_SIZE = 20;
170
220
  // next `{Asset, LIST}` invalidation (an upload in the new folder) refetch the
171
221
  // *previous* folder's pages: one bogus `/upload/files` request per loaded
172
222
  // page. There is no public per-entry unsubscribe, so evict the left folder's
173
- // entries outright returning reloads from page 1, which the accumulator
174
- // already does on a list change.
223
+ // entries outright. Returning then re-reads every page it had loaded, but the
224
+ // rows come straight back from the accumulator memory above — so those
225
+ // requests refresh a list already on screen rather than being waited on.
175
226
  const dispatch = useDispatch();
176
227
  const store = useStore();
177
228
  const prevFolderRef = useRef(folder);
@@ -250,6 +301,10 @@ const PAGE_SIZE = 20;
250
301
  listAnsweredAfter
251
302
  ]);
252
303
  const isFetchingMore = isFetching && page > 1;
304
+ // A restored list already has rows on screen, so re-reading its current page
305
+ // is a background refresh — reporting it as loading would swap those rows for
306
+ // a spinner. Only an empty list has nothing better to show.
307
+ const isLoadingList = isChangingList || isLoading && assets.length === 0;
253
308
  const fetchNextPage = useCallback(()=>{
254
309
  setPageState((prev)=>({
255
310
  queryKey,
@@ -277,7 +332,7 @@ const PAGE_SIZE = 20;
277
332
  // Falls back to the accumulated total so a consumer showing the count
278
333
  // doesn't flash zero mid-transition, matching the possibly stale `assets`.
279
334
  pagination: currentData?.pagination ?? accumulated.pagination,
280
- isLoading: isLoading || isChangingList,
335
+ isLoading: isLoadingList,
281
336
  isFetchingMore,
282
337
  hasNextPage,
283
338
  fetchNextPage,
@@ -1 +1 @@
1
- {"version":3,"file":"useInfiniteAssets.mjs","sources":["../../../../../../admin/src/future/pages/Assets/hooks/useInfiniteAssets.ts"],"sourcesContent":["import { createElement, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { useDispatch, useStore } from 'react-redux';\n\nimport { uploadApi } from '../../../services/api';\nimport { useGetAssetsQuery } from '../../../services/assets';\nimport { useTypedSelector } from '../../../store/hooks';\nimport { selectCompletedUploads } from '../../../store/uploadProgress';\nimport { getRelationId } from '../../../utils/getRelationId';\nimport { mergeUploadedAssets } from '../utils/mergeUploadedAssets';\n\nimport type { File, Pagination } from '../../../../../../shared/contracts/files';\n\nconst PAGE_SIZE = 20;\n\ninterface UseInfiniteAssetsOptions {\n folder?: number | null;\n sort?: string;\n search?: string;\n /** Extra `filters[$and]` entries for the files query. */\n filters?: Record<string, unknown>[];\n /** Structural switch: an `is [folder]`-only type badge means no file can match. */\n enabled?: boolean;\n}\n\ninterface QueryArgs {\n folder: number | null;\n sort?: string;\n search?: string;\n filters?: Record<string, unknown>[];\n}\n\n/**\n * Everything loaded for one query identity.\n *\n * `queryKey` lags the live key while a new query is in flight — that lag is\n * what keeps the previous results on screen across a search change.\n */\ninterface Accumulated {\n queryKey: string;\n listKey: string;\n pages: Record<number, File[]>;\n pagination?: Pagination;\n}\n\ninterface PageState {\n queryKey: string;\n page: number;\n}\n\ntype PageRefreshedHandler = (page: number, results: File[]) => void;\n\n/**\n * Concatenates the pages in ascending order, one entry per asset id.\n *\n * `Map.set` keeps the first insertion position but takes the latest value, so\n * an asset that moved between pages after a mutation holds its place and shows\n * fresh data instead of rendering twice under a duplicate key.\n */\nconst flattenPages = (pages: Record<number, File[]>): File[] => {\n const byId = new Map<number, File>();\n\n for (const page of Object.keys(pages)\n .map(Number)\n .sort((a, b) => a - b)) {\n for (const asset of pages[page]) {\n byId.set(asset.id, asset);\n }\n }\n\n return [...byId.values()];\n};\n\n/**\n * Keeps one earlier page's `getAssets` query subscribed and reports its results\n * back up whenever they change.\n *\n * The hook itself only subscribes the current (latest) page. Without these, a\n * mutation invalidating `{Asset, LIST}` refetches that page alone and earlier\n * pages stay frozen — a rename or delete on an earlier page never reaches the\n * list until a folder/sort/search change. One subscriber per earlier\n * page keeps them all subscribed so the invalidation refetches the whole list.\n * Renders nothing; it exists only for the subscription + `onRefreshed` report.\n */\nconst PageSubscriber = ({\n queryArgs,\n page,\n onRefreshed,\n}: {\n queryArgs: QueryArgs;\n page: number;\n onRefreshed: PageRefreshedHandler;\n}) => {\n const { currentData } = useGetAssetsQuery({ ...queryArgs, page, pageSize: PAGE_SIZE });\n const results = currentData?.results;\n\n useEffect(() => {\n if (results) {\n onRefreshed(page, results);\n }\n // `results` is a stable reference per cache entry, so this only re-reports\n // when a refetch actually replaces the page's data. Reporting the same\n // reference the accumulator already holds is a no-op (see `onRefreshed`).\n }, [results, page, onRefreshed]);\n\n return null;\n};\n\n/**\n * Infinite scroll over `/upload/files`, keeping one accumulated slot per page.\n *\n * The caller MUST render the returned `subscribers` node — that is what keeps\n * every loaded page subscribed, so `{Asset, LIST}` invalidations keep the whole\n * list consistent rather than only the current page.\n */\nconst useInfiniteAssets = ({\n folder = null,\n sort,\n search,\n filters,\n enabled = true,\n}: UseInfiniteAssetsOptions = {}) => {\n // Derived from the request args themselves, so a new filter can't reach the\n // API without also invalidating what was accumulated under the old one.\n const queryArgs: QueryArgs = { folder, sort, search, filters };\n const queryKey = JSON.stringify(queryArgs);\n // Identifies the list being viewed, ignoring the search term. Folder, sort\n // and filter changes are single committed actions, so one clean reset per\n // change is honest. Search is committed per keystroke on a 300ms debounce,\n // and blanking the list on each one would strobe as the user types.\n // The cost: through the search window the previous rows stay rendered and\n // `hasNextPage` is false, so the list reads as complete until page 1 lands.\n const listKey = JSON.stringify({ folder, sort, filters });\n\n const [pageState, setPageState] = useState<PageState>({ queryKey, page: 1 });\n const [accumulated, setAccumulated] = useState<Accumulated>({ queryKey, listKey, pages: {} });\n\n // Derived rather than read straight from state: the render that discovers\n // the key change still reaches the query below, and a list with no page 1\n // must never be requested at page 2.\n const page = pageState.queryKey === queryKey ? pageState.page : 1;\n\n if (pageState.queryKey !== queryKey) {\n setPageState({ queryKey, page: 1 });\n }\n\n const { currentData, isLoading, isFetching, error, startedTimeStamp, fulfilledTimeStamp } =\n useGetAssetsQuery(\n {\n ...queryArgs,\n page,\n pageSize: PAGE_SIZE,\n },\n { skip: !enabled }\n );\n\n const isSameQuery = accumulated.queryKey === queryKey;\n\n // `currentData` is only ever the payload for the args just passed, so it\n // belongs to this key at this page — nothing to infer. Its reference is\n // stable per cache entry, so this settles after one extra render.\n if (currentData && (!isSameQuery || accumulated.pages[page] !== currentData.results)) {\n setAccumulated(\n isSameQuery\n ? {\n ...accumulated,\n pages: { ...accumulated.pages, [page]: currentData.results },\n pagination: currentData.pagination,\n }\n : {\n queryKey,\n listKey,\n pages: { [page]: currentData.results },\n pagination: currentData.pagination,\n }\n );\n }\n\n // Merges a refetched earlier page back into the accumulator. Ignores reports\n // for a superseded query, and no-ops when the reference is unchanged so a\n // subscriber re-reporting its already-stored page can't loop.\n const handlePageRefreshed = useCallback<PageRefreshedHandler>(\n (refreshedPage, results) => {\n setAccumulated((prev) => {\n if (prev.queryKey !== queryKey || prev.pages[refreshedPage] === results) {\n return prev;\n }\n\n return { ...prev, pages: { ...prev.pages, [refreshedPage]: results } };\n });\n },\n [queryKey]\n );\n\n // One subscriber per earlier page (the current page is already subscribed by\n // the query above). Keyed by queryKey so a folder/sort/search change remounts\n // them against the new args instead of reusing a stale cache entry.\n // `createElement` rather than JSX so this stays a plain `.ts` hook file.\n const subscribers = createElement(\n Fragment,\n null,\n Array.from({ length: Math.max(0, page - 1) }, (_, index) => index + 1).map((earlierPage) =>\n createElement(PageSubscriber, {\n key: `${queryKey}:${earlierPage}`,\n queryArgs,\n page: earlierPage,\n onRefreshed: handlePageRefreshed,\n })\n )\n );\n\n // Drop the left folder's cached `getAssets` pages when the folder changes.\n //\n // RTK Query 1.9.7 leaves a query's store subscription in place when its last\n // subscriber unmounts while a refetch is still in flight — e.g. a delete\n // invalidates `{Asset, LIST}`, every loaded page starts refetching, and the\n // user navigates away before those settle. Those stale subscriptions make the\n // next `{Asset, LIST}` invalidation (an upload in the new folder) refetch the\n // *previous* folder's pages: one bogus `/upload/files` request per loaded\n // page. There is no public per-entry unsubscribe, so evict the left folder's\n // entries outright — returning reloads from page 1, which the accumulator\n // already does on a list change.\n const dispatch = useDispatch();\n const store = useStore();\n const prevFolderRef = useRef(folder);\n useEffect(() => {\n const prevFolder = prevFolderRef.current;\n prevFolderRef.current = folder;\n if (prevFolder === folder) {\n return;\n }\n\n const apiState = (store.getState() as Record<string, { queries?: Record<string, unknown> }>)[\n uploadApi.reducerPath\n ];\n const removeQueryResult = (\n uploadApi as unknown as {\n internalActions: {\n removeQueryResult: (payload: { queryCacheKey: string }) => { type: string };\n };\n }\n ).internalActions.removeQueryResult;\n\n Object.keys(apiState?.queries ?? {}).forEach((cacheKey) => {\n if (!cacheKey.startsWith('getAssets(')) {\n return;\n }\n let args: { folder?: number | null };\n try {\n args = JSON.parse(cacheKey.slice('getAssets('.length, -1));\n } catch {\n return;\n }\n if (args.folder === prevFolder) {\n dispatch(removeQueryResult({ queryCacheKey: cacheKey }));\n }\n });\n }, [folder, dispatch, store]);\n\n // Until the new list's first page lands the accumulator still holds the\n // previous folder. Reported as loading so the page shows a spinner instead\n // of the outgoing folder's assets under the incoming folder's header.\n const isChangingList = accumulated.listKey !== listKey;\n\n const loadedAssets = useMemo(\n () => (isChangingList ? [] : flattenPages(accumulated.pages)),\n [isChangingList, accumulated.pages]\n );\n\n // Deliberately the live value, not the stale-tolerant one below: paging must\n // never be driven by a total that belongs to the previous query.\n const hasNextPage = currentData ? page < currentData.pagination.pageCount : false;\n\n const completedUploads = useTypedSelector(selectCompletedUploads);\n\n // Only an unfiltered, unsearched list can place an upload locally: deciding\n // whether an asset satisfies a filter means reimplementing the server's\n // filter semantics client-side. Filtered views still refresh on the\n // end-of-batch invalidation, as they did before.\n const canPlaceUploads = !search && (filters?.length ?? 0) === 0;\n\n // When the loaded data came back from a request that started after a given\n // upload — i.e. the server had already stored it when asked. Past that point\n // the list is the authority on whether the asset is there at all, so bridging\n // must stop: otherwise a later delete or move, which refetches without it,\n // would have it re-inserted.\n const listAnsweredAfter =\n fulfilledTimeStamp !== undefined &&\n startedTimeStamp !== undefined &&\n // A refetch in flight leaves `fulfilledTimeStamp` on the previous response,\n // which predates this request — so only settled data counts.\n fulfilledTimeStamp > startedTimeStamp\n ? startedTimeStamp\n : undefined;\n\n const assets = useMemo(() => {\n if (!canPlaceUploads || completedUploads.length === 0) {\n return loadedAssets;\n }\n\n const bridging = completedUploads.filter(\n ({ asset, completedAt }) =>\n getRelationId(asset.folder) === folder &&\n (listAnsweredAfter === undefined || completedAt > listAnsweredAfter)\n );\n\n return mergeUploadedAssets({\n assets: loadedAssets,\n uploaded: bridging.map(({ asset }) => asset),\n sort,\n hasNextPage,\n });\n }, [\n canPlaceUploads,\n completedUploads,\n loadedAssets,\n folder,\n sort,\n hasNextPage,\n listAnsweredAfter,\n ]);\n const isFetchingMore = isFetching && page > 1;\n\n const fetchNextPage = useCallback(() => {\n setPageState((prev) => ({\n queryKey,\n page: (prev.queryKey === queryKey ? prev.page : 1) + 1,\n }));\n }, [queryKey]);\n\n if (!enabled) {\n return {\n assets: [] as File[],\n // No list to keep fresh while disabled, so nothing to subscribe.\n subscribers: null,\n pagination: undefined,\n isLoading: false,\n isFetchingMore: false,\n hasNextPage: false,\n fetchNextPage,\n error: undefined,\n };\n }\n\n return {\n assets,\n subscribers,\n // Falls back to the accumulated total so a consumer showing the count\n // doesn't flash zero mid-transition, matching the possibly stale `assets`.\n pagination: currentData?.pagination ?? accumulated.pagination,\n isLoading: isLoading || isChangingList,\n isFetchingMore,\n hasNextPage,\n fetchNextPage,\n error,\n };\n};\n\nexport { useInfiniteAssets };\nexport { PAGE_SIZE };\n"],"names":["PAGE_SIZE","flattenPages","pages","byId","Map","page","Object","keys","map","Number","sort","a","b","asset","set","id","values","PageSubscriber","queryArgs","onRefreshed","currentData","useGetAssetsQuery","pageSize","results","useEffect","useInfiniteAssets","folder","search","filters","enabled","queryKey","JSON","stringify","listKey","pageState","setPageState","useState","accumulated","setAccumulated","isLoading","isFetching","error","startedTimeStamp","fulfilledTimeStamp","skip","isSameQuery","pagination","handlePageRefreshed","useCallback","refreshedPage","prev","subscribers","createElement","Fragment","Array","from","length","Math","max","_","index","earlierPage","key","dispatch","useDispatch","store","useStore","prevFolderRef","useRef","prevFolder","current","apiState","getState","uploadApi","reducerPath","removeQueryResult","internalActions","queries","forEach","cacheKey","startsWith","args","parse","slice","queryCacheKey","isChangingList","loadedAssets","useMemo","hasNextPage","pageCount","completedUploads","useTypedSelector","selectCompletedUploads","canPlaceUploads","listAnsweredAfter","undefined","assets","bridging","filter","completedAt","getRelationId","mergeUploadedAssets","uploaded","isFetchingMore","fetchNextPage"],"mappings":";;;;;;;;;AAaA,MAAMA,SAAAA,GAAY;AAuClB;;;;;;IAOA,MAAMC,eAAe,CAACC,KAAAA,GAAAA;AACpB,IAAA,MAAMC,OAAO,IAAIC,GAAAA,EAAAA;AAEjB,IAAA,KAAK,MAAMC,IAAAA,IAAQC,MAAAA,CAAOC,IAAI,CAACL,KAAAA,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C,cAAAA;AACxBkB,QAAAA,cAAAA;AACAf,QAAAA,WAAAA;AACAgB,QAAAA,aAAAA;AACA/D,QAAAA;AACF,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"useInfiniteAssets.mjs","sources":["../../../../../../admin/src/future/pages/Assets/hooks/useInfiniteAssets.ts"],"sourcesContent":["import { createElement, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { useDispatch, useStore } from 'react-redux';\n\nimport { uploadApi } from '../../../services/api';\nimport { useGetAssetsQuery } from '../../../services/assets';\nimport { useTypedSelector } from '../../../store/hooks';\nimport { selectCompletedUploads } from '../../../store/uploadProgress';\nimport { getRelationId } from '../../../utils/getRelationId';\nimport { mergeUploadedAssets } from '../utils/mergeUploadedAssets';\n\nimport type { File, Pagination } from '../../../../../../shared/contracts/files';\n\nconst PAGE_SIZE = 20;\n\n/**\n * How many list views keep their loaded pages in memory.\n */\nconst MAX_REMEMBERED_LISTS = 10;\n\ninterface UseInfiniteAssetsOptions {\n folder?: number | null;\n sort?: string;\n search?: string;\n /** Extra `filters[$and]` entries for the files query. */\n filters?: Record<string, unknown>[];\n /** Structural switch: an `is [folder]`-only type badge means no file can match. */\n enabled?: boolean;\n}\n\ninterface QueryArgs {\n folder: number | null;\n sort?: string;\n search?: string;\n filters?: Record<string, unknown>[];\n}\n\n/**\n * Everything loaded for one query identity.\n *\n * `queryKey` lags the live key while a new query is in flight — that lag is\n * what keeps the previous results on screen across a search change.\n */\ninterface Accumulated {\n queryKey: string;\n listKey: string;\n pages: Record<number, File[]>;\n pagination?: Pagination;\n}\n\ninterface PageState {\n queryKey: string;\n page: number;\n}\n\ntype PageRefreshedHandler = (page: number, results: File[]) => void;\n\n/**\n * Concatenates the pages in ascending order, one entry per asset id.\n *\n * `Map.set` keeps the first insertion position but takes the latest value, so\n * an asset that moved between pages after a mutation holds its place and shows\n * fresh data instead of rendering twice under a duplicate key.\n */\nconst flattenPages = (pages: Record<number, File[]>): File[] => {\n const byId = new Map<number, File>();\n\n for (const page of Object.keys(pages)\n .map(Number)\n .sort((a, b) => a - b)) {\n for (const asset of pages[page]) {\n byId.set(asset.id, asset);\n }\n }\n\n return [...byId.values()];\n};\n\n/**\n * The highest page an accumulator holds — where the list was last read to, and\n * so where to resume from on the way back.\n */\nconst deepestPage = (pages: Record<number, File[]>): number =>\n Object.keys(pages).reduce((deepest, key) => Math.max(deepest, Number(key)), 1);\n\n/**\n * Keeps one earlier page's `getAssets` query subscribed and reports its results\n * back up whenever they change.\n *\n * The hook itself only subscribes the current (latest) page. Without these, a\n * mutation invalidating `{Asset, LIST}` refetches that page alone and earlier\n * pages stay frozen — a rename or delete on an earlier page never reaches the\n * list until a folder/sort/search change. One subscriber per earlier\n * page keeps them all subscribed so the invalidation refetches the whole list.\n * Renders nothing; it exists only for the subscription + `onRefreshed` report.\n */\nconst PageSubscriber = ({\n queryArgs,\n page,\n onRefreshed,\n}: {\n queryArgs: QueryArgs;\n page: number;\n onRefreshed: PageRefreshedHandler;\n}) => {\n const { currentData } = useGetAssetsQuery({ ...queryArgs, page, pageSize: PAGE_SIZE });\n const results = currentData?.results;\n\n useEffect(() => {\n if (results) {\n onRefreshed(page, results);\n }\n // `results` is a stable reference per cache entry, so this only re-reports\n // when a refetch actually replaces the page's data. Reporting the same\n // reference the accumulator already holds is a no-op (see `onRefreshed`).\n }, [results, page, onRefreshed]);\n\n return null;\n};\n\n/**\n * Infinite scroll over `/upload/files`, keeping one accumulated slot per page.\n *\n * The caller MUST render the returned `subscribers` node — that is what keeps\n * every loaded page subscribed, so `{Asset, LIST}` invalidations keep the whole\n * list consistent rather than only the current page.\n *\n * Loaded pages survive navigating away and back: each list's accumulator is\n * remembered (LRU, `MAX_REMEMBERED_LISTS`) and restored when its key returns, so\n * stepping into a subfolder and back out keeps the rows the user scrolled for.\n */\nconst useInfiniteAssets = ({\n folder = null,\n sort,\n search,\n filters,\n enabled = true,\n}: UseInfiniteAssetsOptions = {}) => {\n // Derived from the request args themselves, so a new filter can't reach the\n // API without also invalidating what was accumulated under the old one.\n const queryArgs: QueryArgs = { folder, sort, search, filters };\n const queryKey = JSON.stringify(queryArgs);\n // Identifies the list being viewed, ignoring the search term. Folder, sort\n // and filter changes are single committed actions, so one clean reset per\n // change is honest. Search is committed per keystroke on a 300ms debounce,\n // and blanking the list on each one would strobe as the user types.\n // The cost: through the search window the previous rows stay rendered and\n // `hasNextPage` is false, so the list reads as complete until page 1 lands.\n const listKey = JSON.stringify({ folder, sort, filters });\n\n const [pageState, setPageState] = useState<PageState>({ queryKey, page: 1 });\n const [accumulated, setAccumulated] = useState<Accumulated>({ queryKey, listKey, pages: {} });\n\n // Each list's loaded pages, kept across navigation away from it.\n const memoryRef = useRef(new Map<string, Accumulated>());\n\n const isNewList = pageState.queryKey !== queryKey;\n\n const remembered = isNewList ? memoryRef.current.get(queryKey) : undefined;\n\n // Derived rather than read from state: the render that discovers the key\n // change still reaches the query below, and a list with no page 1 must never\n // be requested at page 2. A remembered list always holds page 1, so resuming\n // at its deepest page can't skip one.\n let page: number;\n if (!isNewList) {\n page = pageState.page;\n } else if (remembered) {\n page = deepestPage(remembered.pages);\n } else {\n page = 1;\n }\n\n if (isNewList) {\n setPageState({ queryKey, page });\n\n if (remembered) {\n setAccumulated(remembered);\n }\n }\n\n const { currentData, isLoading, isFetching, error, startedTimeStamp, fulfilledTimeStamp } =\n useGetAssetsQuery(\n {\n ...queryArgs,\n page,\n pageSize: PAGE_SIZE,\n },\n { skip: !enabled }\n );\n\n const isSameQuery = accumulated.queryKey === queryKey;\n\n // `currentData` is only ever the payload for the args just passed, so it\n // belongs to this key at this page — nothing to infer. Its reference is\n // stable per cache entry, so this settles after one extra render.\n if (\n // A restore already set the accumulator from memory; don't overwrite it.\n !remembered &&\n currentData &&\n (!isSameQuery || accumulated.pages[page] !== currentData.results)\n ) {\n setAccumulated(\n isSameQuery\n ? {\n ...accumulated,\n pages: { ...accumulated.pages, [page]: currentData.results },\n pagination: currentData.pagination,\n }\n : {\n queryKey,\n listKey,\n pages: { [page]: currentData.results },\n pagination: currentData.pagination,\n }\n );\n }\n\n // Merges a refetched earlier page back into the accumulator. Ignores reports\n // for a superseded query, and no-ops when the reference is unchanged so a\n // subscriber re-reporting its already-stored page can't loop.\n const handlePageRefreshed = useCallback<PageRefreshedHandler>(\n (refreshedPage, results) => {\n setAccumulated((prev) => {\n if (prev.queryKey !== queryKey || prev.pages[refreshedPage] === results) {\n return prev;\n }\n\n return { ...prev, pages: { ...prev.pages, [refreshedPage]: results } };\n });\n },\n [queryKey]\n );\n\n // One subscriber per earlier page (the current page is already subscribed by\n // the query above). Keyed by queryKey so a folder/sort/search change remounts\n // them against the new args instead of reusing a stale cache entry.\n // `createElement` rather than JSX so this stays a plain `.ts` hook file.\n const subscribers = createElement(\n Fragment,\n null,\n Array.from({ length: Math.max(0, page - 1) }, (_, index) => index + 1).map((earlierPage) =>\n createElement(PageSubscriber, {\n key: `${queryKey}:${earlierPage}`,\n queryArgs,\n page: earlierPage,\n onRefreshed: handlePageRefreshed,\n })\n )\n );\n\n // Remember what this list has read, so leaving it isn't forgetting it. Filed\n // under `accumulated.queryKey`, not the live `queryKey`: the accumulator names\n // the list it belongs to, so an entry still describing the list being left\n // can't be misfiled under the one being entered.\n useEffect(() => {\n if (Object.keys(accumulated.pages).length === 0) {\n return;\n }\n\n const memory = memoryRef.current;\n // Delete before set so the entry moves to the end. Map iterates in\n // insertion order, so the first key is the least recently used.\n memory.delete(accumulated.queryKey);\n memory.set(accumulated.queryKey, accumulated);\n\n while (memory.size > MAX_REMEMBERED_LISTS) {\n const oldest = memory.keys().next();\n\n if (oldest.done) {\n break;\n }\n\n memory.delete(oldest.value);\n }\n }, [accumulated]);\n\n // Drop the left folder's cached `getAssets` pages when the folder changes.\n //\n // RTK Query 1.9.7 leaves a query's store subscription in place when its last\n // subscriber unmounts while a refetch is still in flight — e.g. a delete\n // invalidates `{Asset, LIST}`, every loaded page starts refetching, and the\n // user navigates away before those settle. Those stale subscriptions make the\n // next `{Asset, LIST}` invalidation (an upload in the new folder) refetch the\n // *previous* folder's pages: one bogus `/upload/files` request per loaded\n // page. There is no public per-entry unsubscribe, so evict the left folder's\n // entries outright. Returning then re-reads every page it had loaded, but the\n // rows come straight back from the accumulator memory above — so those\n // requests refresh a list already on screen rather than being waited on.\n const dispatch = useDispatch();\n const store = useStore();\n const prevFolderRef = useRef(folder);\n useEffect(() => {\n const prevFolder = prevFolderRef.current;\n prevFolderRef.current = folder;\n if (prevFolder === folder) {\n return;\n }\n\n const apiState = (store.getState() as Record<string, { queries?: Record<string, unknown> }>)[\n uploadApi.reducerPath\n ];\n const removeQueryResult = (\n uploadApi as unknown as {\n internalActions: {\n removeQueryResult: (payload: { queryCacheKey: string }) => { type: string };\n };\n }\n ).internalActions.removeQueryResult;\n\n Object.keys(apiState?.queries ?? {}).forEach((cacheKey) => {\n if (!cacheKey.startsWith('getAssets(')) {\n return;\n }\n let args: { folder?: number | null };\n try {\n args = JSON.parse(cacheKey.slice('getAssets('.length, -1));\n } catch {\n return;\n }\n if (args.folder === prevFolder) {\n dispatch(removeQueryResult({ queryCacheKey: cacheKey }));\n }\n });\n }, [folder, dispatch, store]);\n\n // Until the new list's first page lands the accumulator still holds the\n // previous folder. Reported as loading so the page shows a spinner instead\n // of the outgoing folder's assets under the incoming folder's header.\n const isChangingList = accumulated.listKey !== listKey;\n\n const loadedAssets = useMemo(\n () => (isChangingList ? [] : flattenPages(accumulated.pages)),\n [isChangingList, accumulated.pages]\n );\n\n // Deliberately the live value, not the stale-tolerant one below: paging must\n // never be driven by a total that belongs to the previous query.\n const hasNextPage = currentData ? page < currentData.pagination.pageCount : false;\n\n const completedUploads = useTypedSelector(selectCompletedUploads);\n\n // Only an unfiltered, unsearched list can place an upload locally: deciding\n // whether an asset satisfies a filter means reimplementing the server's\n // filter semantics client-side. Filtered views still refresh on the\n // end-of-batch invalidation, as they did before.\n const canPlaceUploads = !search && (filters?.length ?? 0) === 0;\n\n // When the loaded data came back from a request that started after a given\n // upload — i.e. the server had already stored it when asked. Past that point\n // the list is the authority on whether the asset is there at all, so bridging\n // must stop: otherwise a later delete or move, which refetches without it,\n // would have it re-inserted.\n const listAnsweredAfter =\n fulfilledTimeStamp !== undefined &&\n startedTimeStamp !== undefined &&\n // A refetch in flight leaves `fulfilledTimeStamp` on the previous response,\n // which predates this request — so only settled data counts.\n fulfilledTimeStamp > startedTimeStamp\n ? startedTimeStamp\n : undefined;\n\n const assets = useMemo(() => {\n if (!canPlaceUploads || completedUploads.length === 0) {\n return loadedAssets;\n }\n\n const bridging = completedUploads.filter(\n ({ asset, completedAt }) =>\n getRelationId(asset.folder) === folder &&\n (listAnsweredAfter === undefined || completedAt > listAnsweredAfter)\n );\n\n return mergeUploadedAssets({\n assets: loadedAssets,\n uploaded: bridging.map(({ asset }) => asset),\n sort,\n hasNextPage,\n });\n }, [\n canPlaceUploads,\n completedUploads,\n loadedAssets,\n folder,\n sort,\n hasNextPage,\n listAnsweredAfter,\n ]);\n const isFetchingMore = isFetching && page > 1;\n\n // A restored list already has rows on screen, so re-reading its current page\n // is a background refresh — reporting it as loading would swap those rows for\n // a spinner. Only an empty list has nothing better to show.\n const isLoadingList = isChangingList || (isLoading && assets.length === 0);\n\n const fetchNextPage = useCallback(() => {\n setPageState((prev) => ({\n queryKey,\n page: (prev.queryKey === queryKey ? prev.page : 1) + 1,\n }));\n }, [queryKey]);\n\n if (!enabled) {\n return {\n assets: [] as File[],\n // No list to keep fresh while disabled, so nothing to subscribe.\n subscribers: null,\n pagination: undefined,\n isLoading: false,\n isFetchingMore: false,\n hasNextPage: false,\n fetchNextPage,\n error: undefined,\n };\n }\n\n return {\n assets,\n subscribers,\n // Falls back to the accumulated total so a consumer showing the count\n // doesn't flash zero mid-transition, matching the possibly stale `assets`.\n pagination: currentData?.pagination ?? accumulated.pagination,\n isLoading: isLoadingList,\n isFetchingMore,\n hasNextPage,\n fetchNextPage,\n error,\n };\n};\n\nexport { useInfiniteAssets };\nexport { PAGE_SIZE };\n"],"names":["PAGE_SIZE","MAX_REMEMBERED_LISTS","flattenPages","pages","byId","Map","page","Object","keys","map","Number","sort","a","b","asset","set","id","values","deepestPage","reduce","deepest","key","Math","max","PageSubscriber","queryArgs","onRefreshed","currentData","useGetAssetsQuery","pageSize","results","useEffect","useInfiniteAssets","folder","search","filters","enabled","queryKey","JSON","stringify","listKey","pageState","setPageState","useState","accumulated","setAccumulated","memoryRef","useRef","isNewList","remembered","current","get","undefined","isLoading","isFetching","error","startedTimeStamp","fulfilledTimeStamp","skip","isSameQuery","pagination","handlePageRefreshed","useCallback","refreshedPage","prev","subscribers","createElement","Fragment","Array","from","length","_","index","earlierPage","memory","delete","size","oldest","next","done","value","dispatch","useDispatch","store","useStore","prevFolderRef","prevFolder","apiState","getState","uploadApi","reducerPath","removeQueryResult","internalActions","queries","forEach","cacheKey","startsWith","args","parse","slice","queryCacheKey","isChangingList","loadedAssets","useMemo","hasNextPage","pageCount","completedUploads","useTypedSelector","selectCompletedUploads","canPlaceUploads","listAnsweredAfter","assets","bridging","filter","completedAt","getRelationId","mergeUploadedAssets","uploaded","isFetchingMore","isLoadingList","fetchNextPage"],"mappings":";;;;;;;;;AAaA,MAAMA,SAAAA,GAAY;AAElB;;AAEC,IACD,MAAMC,oBAAAA,GAAuB,EAAA;AAuC7B;;;;;;IAOA,MAAMC,eAAe,CAACC,KAAAA,GAAAA;AACpB,IAAA,MAAMC,OAAO,IAAIC,GAAAA,EAAAA;AAEjB,IAAA,KAAK,MAAMC,IAAAA,IAAQC,MAAAA,CAAOC,IAAI,CAACL,KAAAA,CAAAA,CAC5BM,GAAG,CAACC,MAAAA,CAAAA,CACJC,IAAI,CAAC,CAACC,CAAAA,EAAGC,CAAAA,GAAMD,IAAIC,CAAAA,CAAAA,CAAI;AACxB,QAAA,KAAK,MAAMC,KAAAA,IAASX,KAAK,CAACG,KAAK,CAAE;AAC/BF,YAAAA,IAAAA,CAAKW,GAAG,CAACD,KAAAA,CAAME,EAAE,EA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C7DP,SAAAA,EAAWkE,aAAAA;AACXD,QAAAA,cAAAA;AACAd,QAAAA,WAAAA;AACAgB,QAAAA,aAAAA;AACAjE,QAAAA;AACF,KAAA;AACF;;;;"}
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+
5
+ /**
6
+ * The admin layout marks the element that scrolls the main column (see
7
+ * `Layouts.Root`). The media library has no scroll container of its own, so the
8
+ * offset to save and restore belongs to that ancestor.
9
+ */ const SCROLL_ROOT_SELECTOR = '[data-strapi-main-content]';
10
+ /**
11
+ * How long a restore keeps retrying after the list key changes.
12
+ *
13
+ * A returning list usually comes back from memory in one commit, so the first
14
+ * attempt lands. When it doesn't — pages still loading, so the content isn't yet
15
+ * tall enough to scroll that far — later commits retry. Past this window the
16
+ * offset is dropped rather than yanked out from under someone already reading.
17
+ */ const RESTORE_WINDOW_MS = 2000;
18
+ /**
19
+ * How many list offsets to keep. Matches `MAX_REMEMBERED_LISTS` in
20
+ * `useInfiniteAssets`: the two are keyed identically, so they should forget on
21
+ * the same terms.
22
+ */ const MAX_REMEMBERED_OFFSETS = 10;
23
+ /**
24
+ * Remembers where each list was scrolled to and puts it back on return.
25
+ *
26
+ * `key` fingerprints the list on screen (folder, search, sort, filters). While
27
+ * it holds steady the current offset is recorded; when it changes the incoming
28
+ * key's saved offset is restored, or the list is sent to the top if it has none
29
+ * — a first visit, or one whose entry has been dropped.
30
+ *
31
+ * Returns a callback ref to place on any element inside the scrolling column;
32
+ * it only locates that column, it is never scrolled itself.
33
+ *
34
+ * Restoring a *position* only helps if the rows that filled it come back too —
35
+ * that is `useInfiniteAssets`' job.
36
+ */ const useListScrollRestoration = (key)=>{
37
+ const offsetsRef = React.useRef(new Map());
38
+ const containerRef = React.useRef(null);
39
+ const detachRef = React.useRef(null);
40
+ // The key offsets are currently filed under. In a ref because the scroll
41
+ // listener is attached once and must read the current value.
42
+ const keyRef = React.useRef(key);
43
+ const pendingRef = React.useRef(null);
44
+ const anchorRef = React.useCallback((node)=>{
45
+ detachRef.current?.();
46
+ detachRef.current = null;
47
+ containerRef.current = null;
48
+ const container = node?.closest(SCROLL_ROOT_SELECTOR);
49
+ if (!container) {
50
+ return;
51
+ }
52
+ const handleScroll = ()=>{
53
+ const offsets = offsetsRef.current;
54
+ // Delete before set so the entry moves to the end. Map iterates in
55
+ // insertion order, so the first key is the least recently scrolled.
56
+ offsets.delete(keyRef.current);
57
+ offsets.set(keyRef.current, container.scrollTop);
58
+ while(offsets.size > MAX_REMEMBERED_OFFSETS){
59
+ const oldest = offsets.keys().next().value;
60
+ if (oldest === undefined) {
61
+ break;
62
+ }
63
+ offsets.delete(oldest);
64
+ }
65
+ };
66
+ container.addEventListener('scroll', handleScroll, {
67
+ passive: true
68
+ });
69
+ containerRef.current = container;
70
+ detachRef.current = ()=>container.removeEventListener('scroll', handleScroll);
71
+ }, []);
72
+ React.useEffect(()=>()=>detachRef.current?.(), []);
73
+ // Runs on every commit, not just when `key` changes: a restore the first
74
+ // commit was too short to satisfy must be retried as the rows arrive, and
75
+ // there is no state to key that off. Layout phase so the list is never
76
+ // painted at the wrong offset.
77
+ React.useLayoutEffect(()=>{
78
+ const container = containerRef.current;
79
+ if (!container) {
80
+ return;
81
+ }
82
+ if (keyRef.current !== key) {
83
+ keyRef.current = key;
84
+ pendingRef.current = {
85
+ top: offsetsRef.current.get(key) ?? 0,
86
+ deadline: Date.now() + RESTORE_WINDOW_MS
87
+ };
88
+ }
89
+ const pending = pendingRef.current;
90
+ if (!pending) {
91
+ return;
92
+ }
93
+ // Before the assignment, not alongside it: past the window the offset has to
94
+ // be dropped rather than applied one final time to a list the user has since
95
+ // scrolled themselves.
96
+ if (Date.now() > pending.deadline) {
97
+ pendingRef.current = null;
98
+ return;
99
+ }
100
+ container.scrollTop = pending.top;
101
+ // The browser clamps to the content that exists now, so a target the list
102
+ // isn't tall enough for yet stays pending for the next commit.
103
+ if (container.scrollTop >= pending.top) {
104
+ pendingRef.current = null;
105
+ }
106
+ });
107
+ return anchorRef;
108
+ };
109
+
110
+ exports.useListScrollRestoration = useListScrollRestoration;
111
+ //# sourceMappingURL=useListScrollRestoration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useListScrollRestoration.js","sources":["../../../../../../admin/src/future/pages/Assets/hooks/useListScrollRestoration.ts"],"sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';\n\n/**\n * The admin layout marks the element that scrolls the main column (see\n * `Layouts.Root`). The media library has no scroll container of its own, so the\n * offset to save and restore belongs to that ancestor.\n */\nconst SCROLL_ROOT_SELECTOR = '[data-strapi-main-content]';\n\n/**\n * How long a restore keeps retrying after the list key changes.\n *\n * A returning list usually comes back from memory in one commit, so the first\n * attempt lands. When it doesn't — pages still loading, so the content isn't yet\n * tall enough to scroll that far — later commits retry. Past this window the\n * offset is dropped rather than yanked out from under someone already reading.\n */\nconst RESTORE_WINDOW_MS = 2000;\n\n/**\n * How many list offsets to keep. Matches `MAX_REMEMBERED_LISTS` in\n * `useInfiniteAssets`: the two are keyed identically, so they should forget on\n * the same terms.\n */\nconst MAX_REMEMBERED_OFFSETS = 10;\n\ninterface PendingRestore {\n top: number;\n deadline: number;\n}\n\n/**\n * Remembers where each list was scrolled to and puts it back on return.\n *\n * `key` fingerprints the list on screen (folder, search, sort, filters). While\n * it holds steady the current offset is recorded; when it changes the incoming\n * key's saved offset is restored, or the list is sent to the top if it has none\n * — a first visit, or one whose entry has been dropped.\n *\n * Returns a callback ref to place on any element inside the scrolling column;\n * it only locates that column, it is never scrolled itself.\n *\n * Restoring a *position* only helps if the rows that filled it come back too —\n * that is `useInfiniteAssets`' job.\n */\nexport const useListScrollRestoration = (key: string) => {\n const offsetsRef = useRef(new Map<string, number>());\n const containerRef = useRef<HTMLElement | null>(null);\n const detachRef = useRef<(() => void) | null>(null);\n // The key offsets are currently filed under. In a ref because the scroll\n // listener is attached once and must read the current value.\n const keyRef = useRef(key);\n const pendingRef = useRef<PendingRestore | null>(null);\n\n const anchorRef = useCallback((node: HTMLElement | null) => {\n detachRef.current?.();\n detachRef.current = null;\n containerRef.current = null;\n\n const container = node?.closest<HTMLElement>(SCROLL_ROOT_SELECTOR);\n\n if (!container) {\n return;\n }\n\n const handleScroll = () => {\n const offsets = offsetsRef.current;\n\n // Delete before set so the entry moves to the end. Map iterates in\n // insertion order, so the first key is the least recently scrolled.\n offsets.delete(keyRef.current);\n offsets.set(keyRef.current, container.scrollTop);\n\n while (offsets.size > MAX_REMEMBERED_OFFSETS) {\n const oldest = offsets.keys().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n offsets.delete(oldest);\n }\n };\n\n container.addEventListener('scroll', handleScroll, { passive: true });\n containerRef.current = container;\n detachRef.current = () => container.removeEventListener('scroll', handleScroll);\n }, []);\n\n useEffect(() => () => detachRef.current?.(), []);\n\n // Runs on every commit, not just when `key` changes: a restore the first\n // commit was too short to satisfy must be retried as the rows arrive, and\n // there is no state to key that off. Layout phase so the list is never\n // painted at the wrong offset.\n useLayoutEffect(() => {\n const container = containerRef.current;\n\n if (!container) {\n return;\n }\n\n if (keyRef.current !== key) {\n keyRef.current = key;\n pendingRef.current = {\n top: offsetsRef.current.get(key) ?? 0,\n deadline: Date.now() + RESTORE_WINDOW_MS,\n };\n }\n\n const pending = pendingRef.current;\n\n if (!pending) {\n return;\n }\n\n // Before the assignment, not alongside it: past the window the offset has to\n // be dropped rather than applied one final time to a list the user has since\n // scrolled themselves.\n if (Date.now() > pending.deadline) {\n pendingRef.current = null;\n return;\n }\n\n container.scrollTop = pending.top;\n\n // The browser clamps to the content that exists now, so a target the list\n // isn't tall enough for yet stays pending for the next commit.\n if (container.scrollTop >= pending.top) {\n pendingRef.current = null;\n }\n });\n\n return anchorRef;\n};\n"],"names":["SCROLL_ROOT_SELECTOR","RESTORE_WINDOW_MS","MAX_REMEMBERED_OFFSETS","useListScrollRestoration","key","offsetsRef","useRef","Map","containerRef","detachRef","keyRef","pendingRef","anchorRef","useCallback","node","current","container","closest","handleScroll","offsets","delete","set","scrollTop","size","oldest","keys","next","value","undefined","addEventListener","passive","removeEventListener","useEffect","useLayoutEffect","top","get","deadline","Date","now","pending"],"mappings":";;;;AAEA;;;;AAIC,IACD,MAAMA,oBAAAA,GAAuB,4BAAA;AAE7B;;;;;;;AAOC,IACD,MAAMC,iBAAAA,GAAoB,IAAA;AAE1B;;;;AAIC,IACD,MAAMC,sBAAAA,GAAyB,EAAA;AAO/B;;;;;;;;;;;;;IAcO,MAAMC,wBAAAA,GAA2B,CAACC,GAAAA,GAAAA;IACvC,MAAMC,UAAAA,GAAaC,aAAO,IAAIC,GAAAA,EAAAA,CAAAA;AAC9B,IAAA,MAAMC,eAAeF,YAAAA,CAA2B,IAAA,CAAA;AAChD,IAAA,MAAMG,YAAYH,YAAAA,CAA4B,IAAA,CAAA;;;AAG9C,IAAA,MAAMI,SAASJ,YAAAA,CAAOF,GAAAA,CAAAA;AACtB,IAAA,MAAMO,aAAaL,YAAAA,CAA8B,IAAA,CAAA;IAEjD,MAAMM,SAAAA,GAAYC,kBAAY,CAACC,IAAAA,GAAAA;AAC7BL,QAAAA,SAAAA,CAAUM,OAAO,IAAA;AACjBN,QAAAA,SAAAA,CAAUM,OAAO,GAAG,IAAA;AACpBP,QAAAA,YAAAA,CAAaO,OAAO,GAAG,IAAA;QAEvB,MAAMC,SAAAA,GAAYF,MAAMG,OAAAA,CAAqBjB,oBAAAA,CAAAA;AAE7C,QAAA,IAAI,CAACgB,SAAAA,EAAW;AACd,YAAA;AACF,QAAA;AAEA,QAAA,MAAME,YAAAA,GAAe,IAAA;YACnB,MAAMC,OAAAA,GAAUd,WAAWU,OAAO;;;YAIlCI,OAAAA,CAAQC,MAAM,CAACV,MAAAA,CAAOK,OAAO,CAAA;AAC7BI,YAAAA,OAAAA,CAAQE,GAAG,CAACX,MAAAA,CAAOK,OAAO,EAAEC,UAAUM,SAAS,CAAA;YAE/C,MAAOH,OAAAA,CAAQI,IAAI,GAAGrB,sBAAAA,CAAwB;AAC5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AAA,CAAQH,QAAQ,EAAE;AACjCzB,YAAAA,UAAAA,CAAWI,OAAO,GAAG,IAAA;AACrB,YAAA;AACF,QAAA;QAEAC,SAAAA,CAAUM,SAAS,GAAGiB,OAAAA,CAAQL,GAAG;;;AAIjC,QAAA,IAAIlB,SAAAA,CAAUM,SAAS,IAAIiB,OAAAA,CAAQL,GAAG,EAAE;AACtCvB,YAAAA,UAAAA,CAAWI,OAAO,GAAG,IAAA;AACvB,QAAA;AACF,IAAA,CAAA,CAAA;IAEA,OAAOH,SAAAA;AACT;;;;"}
@@ -0,0 +1,109 @@
1
+ import { useRef, useCallback, useEffect, useLayoutEffect } from 'react';
2
+
3
+ /**
4
+ * The admin layout marks the element that scrolls the main column (see
5
+ * `Layouts.Root`). The media library has no scroll container of its own, so the
6
+ * offset to save and restore belongs to that ancestor.
7
+ */ const SCROLL_ROOT_SELECTOR = '[data-strapi-main-content]';
8
+ /**
9
+ * How long a restore keeps retrying after the list key changes.
10
+ *
11
+ * A returning list usually comes back from memory in one commit, so the first
12
+ * attempt lands. When it doesn't — pages still loading, so the content isn't yet
13
+ * tall enough to scroll that far — later commits retry. Past this window the
14
+ * offset is dropped rather than yanked out from under someone already reading.
15
+ */ const RESTORE_WINDOW_MS = 2000;
16
+ /**
17
+ * How many list offsets to keep. Matches `MAX_REMEMBERED_LISTS` in
18
+ * `useInfiniteAssets`: the two are keyed identically, so they should forget on
19
+ * the same terms.
20
+ */ const MAX_REMEMBERED_OFFSETS = 10;
21
+ /**
22
+ * Remembers where each list was scrolled to and puts it back on return.
23
+ *
24
+ * `key` fingerprints the list on screen (folder, search, sort, filters). While
25
+ * it holds steady the current offset is recorded; when it changes the incoming
26
+ * key's saved offset is restored, or the list is sent to the top if it has none
27
+ * — a first visit, or one whose entry has been dropped.
28
+ *
29
+ * Returns a callback ref to place on any element inside the scrolling column;
30
+ * it only locates that column, it is never scrolled itself.
31
+ *
32
+ * Restoring a *position* only helps if the rows that filled it come back too —
33
+ * that is `useInfiniteAssets`' job.
34
+ */ const useListScrollRestoration = (key)=>{
35
+ const offsetsRef = useRef(new Map());
36
+ const containerRef = useRef(null);
37
+ const detachRef = useRef(null);
38
+ // The key offsets are currently filed under. In a ref because the scroll
39
+ // listener is attached once and must read the current value.
40
+ const keyRef = useRef(key);
41
+ const pendingRef = useRef(null);
42
+ const anchorRef = useCallback((node)=>{
43
+ detachRef.current?.();
44
+ detachRef.current = null;
45
+ containerRef.current = null;
46
+ const container = node?.closest(SCROLL_ROOT_SELECTOR);
47
+ if (!container) {
48
+ return;
49
+ }
50
+ const handleScroll = ()=>{
51
+ const offsets = offsetsRef.current;
52
+ // Delete before set so the entry moves to the end. Map iterates in
53
+ // insertion order, so the first key is the least recently scrolled.
54
+ offsets.delete(keyRef.current);
55
+ offsets.set(keyRef.current, container.scrollTop);
56
+ while(offsets.size > MAX_REMEMBERED_OFFSETS){
57
+ const oldest = offsets.keys().next().value;
58
+ if (oldest === undefined) {
59
+ break;
60
+ }
61
+ offsets.delete(oldest);
62
+ }
63
+ };
64
+ container.addEventListener('scroll', handleScroll, {
65
+ passive: true
66
+ });
67
+ containerRef.current = container;
68
+ detachRef.current = ()=>container.removeEventListener('scroll', handleScroll);
69
+ }, []);
70
+ useEffect(()=>()=>detachRef.current?.(), []);
71
+ // Runs on every commit, not just when `key` changes: a restore the first
72
+ // commit was too short to satisfy must be retried as the rows arrive, and
73
+ // there is no state to key that off. Layout phase so the list is never
74
+ // painted at the wrong offset.
75
+ useLayoutEffect(()=>{
76
+ const container = containerRef.current;
77
+ if (!container) {
78
+ return;
79
+ }
80
+ if (keyRef.current !== key) {
81
+ keyRef.current = key;
82
+ pendingRef.current = {
83
+ top: offsetsRef.current.get(key) ?? 0,
84
+ deadline: Date.now() + RESTORE_WINDOW_MS
85
+ };
86
+ }
87
+ const pending = pendingRef.current;
88
+ if (!pending) {
89
+ return;
90
+ }
91
+ // Before the assignment, not alongside it: past the window the offset has to
92
+ // be dropped rather than applied one final time to a list the user has since
93
+ // scrolled themselves.
94
+ if (Date.now() > pending.deadline) {
95
+ pendingRef.current = null;
96
+ return;
97
+ }
98
+ container.scrollTop = pending.top;
99
+ // The browser clamps to the content that exists now, so a target the list
100
+ // isn't tall enough for yet stays pending for the next commit.
101
+ if (container.scrollTop >= pending.top) {
102
+ pendingRef.current = null;
103
+ }
104
+ });
105
+ return anchorRef;
106
+ };
107
+
108
+ export { useListScrollRestoration };
109
+ //# sourceMappingURL=useListScrollRestoration.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useListScrollRestoration.mjs","sources":["../../../../../../admin/src/future/pages/Assets/hooks/useListScrollRestoration.ts"],"sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';\n\n/**\n * The admin layout marks the element that scrolls the main column (see\n * `Layouts.Root`). The media library has no scroll container of its own, so the\n * offset to save and restore belongs to that ancestor.\n */\nconst SCROLL_ROOT_SELECTOR = '[data-strapi-main-content]';\n\n/**\n * How long a restore keeps retrying after the list key changes.\n *\n * A returning list usually comes back from memory in one commit, so the first\n * attempt lands. When it doesn't — pages still loading, so the content isn't yet\n * tall enough to scroll that far — later commits retry. Past this window the\n * offset is dropped rather than yanked out from under someone already reading.\n */\nconst RESTORE_WINDOW_MS = 2000;\n\n/**\n * How many list offsets to keep. Matches `MAX_REMEMBERED_LISTS` in\n * `useInfiniteAssets`: the two are keyed identically, so they should forget on\n * the same terms.\n */\nconst MAX_REMEMBERED_OFFSETS = 10;\n\ninterface PendingRestore {\n top: number;\n deadline: number;\n}\n\n/**\n * Remembers where each list was scrolled to and puts it back on return.\n *\n * `key` fingerprints the list on screen (folder, search, sort, filters). While\n * it holds steady the current offset is recorded; when it changes the incoming\n * key's saved offset is restored, or the list is sent to the top if it has none\n * — a first visit, or one whose entry has been dropped.\n *\n * Returns a callback ref to place on any element inside the scrolling column;\n * it only locates that column, it is never scrolled itself.\n *\n * Restoring a *position* only helps if the rows that filled it come back too —\n * that is `useInfiniteAssets`' job.\n */\nexport const useListScrollRestoration = (key: string) => {\n const offsetsRef = useRef(new Map<string, number>());\n const containerRef = useRef<HTMLElement | null>(null);\n const detachRef = useRef<(() => void) | null>(null);\n // The key offsets are currently filed under. In a ref because the scroll\n // listener is attached once and must read the current value.\n const keyRef = useRef(key);\n const pendingRef = useRef<PendingRestore | null>(null);\n\n const anchorRef = useCallback((node: HTMLElement | null) => {\n detachRef.current?.();\n detachRef.current = null;\n containerRef.current = null;\n\n const container = node?.closest<HTMLElement>(SCROLL_ROOT_SELECTOR);\n\n if (!container) {\n return;\n }\n\n const handleScroll = () => {\n const offsets = offsetsRef.current;\n\n // Delete before set so the entry moves to the end. Map iterates in\n // insertion order, so the first key is the least recently scrolled.\n offsets.delete(keyRef.current);\n offsets.set(keyRef.current, container.scrollTop);\n\n while (offsets.size > MAX_REMEMBERED_OFFSETS) {\n const oldest = offsets.keys().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n offsets.delete(oldest);\n }\n };\n\n container.addEventListener('scroll', handleScroll, { passive: true });\n containerRef.current = container;\n detachRef.current = () => container.removeEventListener('scroll', handleScroll);\n }, []);\n\n useEffect(() => () => detachRef.current?.(), []);\n\n // Runs on every commit, not just when `key` changes: a restore the first\n // commit was too short to satisfy must be retried as the rows arrive, and\n // there is no state to key that off. Layout phase so the list is never\n // painted at the wrong offset.\n useLayoutEffect(() => {\n const container = containerRef.current;\n\n if (!container) {\n return;\n }\n\n if (keyRef.current !== key) {\n keyRef.current = key;\n pendingRef.current = {\n top: offsetsRef.current.get(key) ?? 0,\n deadline: Date.now() + RESTORE_WINDOW_MS,\n };\n }\n\n const pending = pendingRef.current;\n\n if (!pending) {\n return;\n }\n\n // Before the assignment, not alongside it: past the window the offset has to\n // be dropped rather than applied one final time to a list the user has since\n // scrolled themselves.\n if (Date.now() > pending.deadline) {\n pendingRef.current = null;\n return;\n }\n\n container.scrollTop = pending.top;\n\n // The browser clamps to the content that exists now, so a target the list\n // isn't tall enough for yet stays pending for the next commit.\n if (container.scrollTop >= pending.top) {\n pendingRef.current = null;\n }\n });\n\n return anchorRef;\n};\n"],"names":["SCROLL_ROOT_SELECTOR","RESTORE_WINDOW_MS","MAX_REMEMBERED_OFFSETS","useListScrollRestoration","key","offsetsRef","useRef","Map","containerRef","detachRef","keyRef","pendingRef","anchorRef","useCallback","node","current","container","closest","handleScroll","offsets","delete","set","scrollTop","size","oldest","keys","next","value","undefined","addEventListener","passive","removeEventListener","useEffect","useLayoutEffect","top","get","deadline","Date","now","pending"],"mappings":";;AAEA;;;;AAIC,IACD,MAAMA,oBAAAA,GAAuB,4BAAA;AAE7B;;;;;;;AAOC,IACD,MAAMC,iBAAAA,GAAoB,IAAA;AAE1B;;;;AAIC,IACD,MAAMC,sBAAAA,GAAyB,EAAA;AAO/B;;;;;;;;;;;;;IAcO,MAAMC,wBAAAA,GAA2B,CAACC,GAAAA,GAAAA;IACvC,MAAMC,UAAAA,GAAaC,OAAO,IAAIC,GAAAA,EAAAA,CAAAA;AAC9B,IAAA,MAAMC,eAAeF,MAAAA,CAA2B,IAAA,CAAA;AAChD,IAAA,MAAMG,YAAYH,MAAAA,CAA4B,IAAA,CAAA;;;AAG9C,IAAA,MAAMI,SAASJ,MAAAA,CAAOF,GAAAA,CAAAA;AACtB,IAAA,MAAMO,aAAaL,MAAAA,CAA8B,IAAA,CAAA;IAEjD,MAAMM,SAAAA,GAAYC,YAAY,CAACC,IAAAA,GAAAA;AAC7BL,QAAAA,SAAAA,CAAUM,OAAO,IAAA;AACjBN,QAAAA,SAAAA,CAAUM,OAAO,GAAG,IAAA;AACpBP,QAAAA,YAAAA,CAAaO,OAAO,GAAG,IAAA;QAEvB,MAAMC,SAAAA,GAAYF,MAAMG,OAAAA,CAAqBjB,oBAAAA,CAAAA;AAE7C,QAAA,IAAI,CAACgB,SAAAA,EAAW;AACd,YAAA;AACF,QAAA;AAEA,QAAA,MAAME,YAAAA,GAAe,IAAA;YACnB,MAAMC,OAAAA,GAAUd,WAAWU,OAAO;;;YAIlCI,OAAAA,C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,GAAKrC;AACzB,aAAA;AACF,QAAA;QAEA,MAAMsC,OAAAA,GAAU5B,WAAWI,OAAO;AAElC,QAAA,IAAI,CAACwB,OAAAA,EAAS;AACZ,YAAA;AACF,QAAA;;;;AAKA,QAAA,IAAIF,IAAAA,CAAKC,GAAG,EAAA,GAAKC,OAAAA,CAAQH,QAAQ,EAAE;AACjCzB,YAAAA,UAAAA,CAAWI,OAAO,GAAG,IAAA;AACrB,YAAA;AACF,QAAA;QAEAC,SAAAA,CAAUM,SAAS,GAAGiB,OAAAA,CAAQL,GAAG;;;AAIjC,QAAA,IAAIlB,SAAAA,CAAUM,SAAS,IAAIiB,OAAAA,CAAQL,GAAG,EAAE;AACtCvB,YAAAA,UAAAA,CAAWI,OAAO,GAAG,IAAA;AACvB,QAAA;AACF,IAAA,CAAA,CAAA;IAEA,OAAOH,SAAAA;AACT;;;;"}
@@ -345,6 +345,23 @@ const trackPoolRun = (uploadId, run)=>{
345
345
  }));
346
346
  break;
347
347
  }
348
+ case 'file:progress':
349
+ {
350
+ const payload = parsed;
351
+ // No usable Content-Length on the remote: leave the row indeterminate
352
+ if (payload.totalBytes === null) {
353
+ break;
354
+ }
355
+ // Already throttled server-side (~5 frames a second per file), so no batching
356
+ // here. `size` rides along because the row is still at 0 — see `setFileProgress`.
357
+ dispatch(uploadProgress.setFileProgress({
358
+ index,
359
+ bytes: payload.loadedBytes,
360
+ size: payload.totalBytes,
361
+ uploadId
362
+ }));
363
+ break;
364
+ }
348
365
  case 'file:uploading':
349
366
  {
350
367
  const payload = parsed;