@dimah-s3/react 2.0.0-beta.1 → 2.0.0-beta.10

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 (63) hide show
  1. package/README.md +4 -4
  2. package/dist/api.d.ts +1 -1
  3. package/dist/{chunk-SPUUNLXI.js → chunk-7YPJ65VI.js} +49 -21
  4. package/dist/chunk-7YPJ65VI.js.map +1 -0
  5. package/dist/create-s3-client.d.ts +1 -1
  6. package/dist/engine.d.ts +15 -15
  7. package/dist/engine.d.ts.map +1 -1
  8. package/dist/engine.js +80 -33
  9. package/dist/engine.js.map +1 -1
  10. package/dist/helpers/format-date.d.ts +1 -1
  11. package/dist/helpers/{format-dimah-error.d.ts → format-error.d.ts} +3 -3
  12. package/dist/helpers/format-error.d.ts.map +1 -0
  13. package/dist/helpers/index.d.ts +7 -7
  14. package/dist/helpers/index.d.ts.map +1 -1
  15. package/dist/helpers/throttled-speed.d.ts +1 -1
  16. package/dist/helpers/use-format-speed.d.ts +2 -1
  17. package/dist/helpers/use-format-speed.d.ts.map +1 -1
  18. package/dist/hooks/use-download.d.ts.map +1 -1
  19. package/dist/hooks/use-fetch-download.d.ts.map +1 -1
  20. package/dist/hooks/use-file-upload.d.ts +7 -3
  21. package/dist/hooks/use-file-upload.d.ts.map +1 -1
  22. package/dist/hooks/use-object-list-selection.d.ts.map +1 -1
  23. package/dist/hooks/use-object-list.d.ts +50 -10
  24. package/dist/hooks/use-object-list.d.ts.map +1 -1
  25. package/dist/hooks/use-upload-limit.d.ts +19 -0
  26. package/dist/hooks/use-upload-limit.d.ts.map +1 -0
  27. package/dist/hooks/use-upload.d.ts +11 -9
  28. package/dist/hooks/use-upload.d.ts.map +1 -1
  29. package/dist/index.d.ts +18 -17
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +309 -71
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal/hooks.d.ts +1 -1
  34. package/dist/internal/upload-limits.d.ts +27 -0
  35. package/dist/internal/upload-limits.d.ts.map +1 -0
  36. package/dist/list/entries.d.ts +14 -1
  37. package/dist/list/entries.d.ts.map +1 -1
  38. package/dist/list/memory-object-source.d.ts +8 -3
  39. package/dist/list/memory-object-source.d.ts.map +1 -1
  40. package/dist/list/read-object-list-level.d.ts +3 -1
  41. package/dist/list/read-object-list-level.d.ts.map +1 -1
  42. package/dist/list/types.d.ts +77 -3
  43. package/dist/list/types.d.ts.map +1 -1
  44. package/dist/s3-provider.d.ts +1 -1
  45. package/dist/store/index.d.ts +2 -2
  46. package/dist/translations/index.d.ts +1 -1
  47. package/dist/translations/types.d.ts +19 -1
  48. package/dist/translations/types.d.ts.map +1 -1
  49. package/dist/types/delete.d.ts +7 -4
  50. package/dist/types/delete.d.ts.map +1 -1
  51. package/dist/types/download.d.ts +9 -18
  52. package/dist/types/download.d.ts.map +1 -1
  53. package/dist/types/index.d.ts +5 -5
  54. package/dist/types/upload.d.ts +23 -2
  55. package/dist/types/upload.d.ts.map +1 -1
  56. package/dist/upload/index.d.ts +5 -5
  57. package/package.json +8 -8
  58. package/dist/chunk-SPUUNLXI.js.map +0 -1
  59. package/dist/helpers/format-dimah-error.d.ts.map +0 -1
  60. package/dist/helpers/format-speed.d.ts +0 -10
  61. package/dist/helpers/format-speed.d.ts.map +0 -1
  62. package/dist/helpers/format-upload-progress.d.ts +0 -20
  63. package/dist/helpers/format-upload-progress.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { requireApi, loadRouteCatalog, toClientError, mergeRouteUploadPolicy, resolveRouteUploadPolicy, DEFAULT_MAX_FILES, runBeforeCallback, mapWithConcurrency, abortable, reportOperationOutcome, transferProgress, runStartCallback, notify, runAfterCallback, createObjectListEntries, formatAcceptLabels, formatFileSize, isRawAPIError, toTimestamp, uploadAbortReason, DEFAULT_CONCURRENT_FILES, mergeUploadRequest, resolveUploadRequest, hookFailed, uploadFile } from './chunk-SPUUNLXI.js';
3
- import { createContext, useContext, useState, useEffect, useCallback, useId, useRef, useMemo, useSyncExternalStore, useLayoutEffect } from 'react';
2
+ import { requireApi, loadRouteCatalog, toClientError, mergeRouteUploadPolicy, resolveRouteUploadPolicy, DEFAULT_MAX_FILES, runBeforeCallback, abortable, reportOperationOutcome, transferProgress, runStartCallback, notify, runAfterCallback, reuseObjectListEntries, formatAcceptLabels, formatFileSize, isRawAPIError, toTimestamp, uploadAbortReason, DEFAULT_CONCURRENT_FILES, mergeUploadRequest, resolveUploadRequest, hookFailed, uploadFile } from './chunk-7YPJ65VI.js';
3
+ import { createContext, useContext, useState, useEffect, useCallback, useId, useLayoutEffect, useSyncExternalStore, useRef, useMemo } from 'react';
4
4
  import { TranslationProvider, useTranslations } from '@fuma-translate/react';
5
5
  import { jsx } from 'react/jsx-runtime';
6
- import { createS3Client as createS3Client$1, parseFileName, fileNameFromKey, s3Error, DELETE_MANY_MAX_KEYS, APIError, normalizeObjectKey, isAPIError, S3_ERROR_CODES, validateFile } from '@dimah-s3/core';
6
+ import { createS3Client as createS3Client$1, parseFileName, fileNameFromKey, s3Error, DELETE_MANY_MAX_KEYS, APIError, normalizeObjectKey, normalizeSearchText, isAPIError, S3_ERROR_CODES, validateFile } from '@dimah-s3/core';
7
7
  import { useDropzone } from 'react-dropzone';
8
8
 
9
9
  var S3Context = createContext(null);
@@ -250,10 +250,85 @@ function createThrottledSpeedUpdater(tracker, intervalMs = 500) {
250
250
  };
251
251
  }
252
252
 
253
+ // src/internal/upload-limits.ts
254
+ var intakes = /* @__PURE__ */ new Map();
255
+ function intakeFor(instanceId) {
256
+ let intake = intakes.get(instanceId);
257
+ if (!intake) {
258
+ intake = { limits: /* @__PURE__ */ new Set(), reserved: 0, listeners: /* @__PURE__ */ new Set() };
259
+ intakes.set(instanceId, intake);
260
+ }
261
+ return intake;
262
+ }
263
+ function prune(instanceId, intake) {
264
+ if (intake.limits.size === 0 && intake.reserved === 0 && intake.listeners.size === 0 && intakes.get(instanceId) === intake) {
265
+ intakes.delete(instanceId);
266
+ }
267
+ }
268
+ function addUploadLimit(instanceId, ref) {
269
+ const intake = intakeFor(instanceId);
270
+ intake.limits.add(ref);
271
+ return () => {
272
+ intake.limits.delete(ref);
273
+ prune(instanceId, intake);
274
+ };
275
+ }
276
+ function reserveUploadSlots(instanceId, count) {
277
+ if (count <= 0) return () => {
278
+ };
279
+ const intake = intakeFor(instanceId);
280
+ intake.reserved += count;
281
+ notify2(intake);
282
+ let released = false;
283
+ return () => {
284
+ if (released) return;
285
+ released = true;
286
+ intake.reserved -= count;
287
+ notify2(intake);
288
+ prune(instanceId, intake);
289
+ };
290
+ }
291
+ function reservedUploadSlots(instanceId) {
292
+ return intakes.get(instanceId)?.reserved ?? 0;
293
+ }
294
+ function subscribeUploadSlots(instanceId, listener) {
295
+ const intake = intakeFor(instanceId);
296
+ intake.listeners.add(listener);
297
+ return () => {
298
+ intake.listeners.delete(listener);
299
+ prune(instanceId, intake);
300
+ };
301
+ }
302
+ function notify2(intake) {
303
+ for (const listener of intake.listeners) listener();
304
+ }
305
+ function freeUploadSlots(instanceId, files) {
306
+ const intake = intakes.get(instanceId);
307
+ let free = Number.POSITIVE_INFINITY;
308
+ if (!intake) return free;
309
+ for (const { current } of intake.limits) {
310
+ if (current) {
311
+ free = Math.min(free, uploadSlotsLeft(current, files, intake.reserved));
312
+ }
313
+ }
314
+ return free;
315
+ }
316
+ function uploadSlotsLeft(limit, files, reserved) {
317
+ let taken = reserved;
318
+ for (const entry of files) {
319
+ if (entry.phase === "error") continue;
320
+ if (entry.phase === "success" && limit.counted?.has(entry.id)) continue;
321
+ taken += 1;
322
+ }
323
+ return Math.max(0, limit.available - taken);
324
+ }
325
+
253
326
  // src/hooks/use-file-upload.ts
254
- function useFileUpload(options) {
327
+ function useFileUpload(options, instanceId) {
255
328
  const contextApi = useContext(S3Context);
256
- const [queue] = useState(() => createUploadQueue(options, contextApi));
329
+ const [queue] = useState(
330
+ () => createUploadQueue(options, contextApi, instanceId)
331
+ );
257
332
  const snapshot = useSyncExternalStore(
258
333
  queue.subscribe,
259
334
  queue.getSnapshot,
@@ -288,7 +363,7 @@ var ACTIVE_PHASES = /* @__PURE__ */ new Set([
288
363
  "uploading",
289
364
  "finalizing"
290
365
  ]);
291
- function createUploadQueue(initialOptions, initialContextApi) {
366
+ function createUploadQueue(initialOptions, initialContextApi, instanceId) {
292
367
  const listeners = /* @__PURE__ */ new Set();
293
368
  const tasks = /* @__PURE__ */ new Map();
294
369
  const waiting = [];
@@ -448,7 +523,7 @@ function createUploadQueue(initialOptions, initialContextApi) {
448
523
  return { status: "error", file, error: toClientError(error) };
449
524
  }
450
525
  }
451
- async function prepare(api, files, options, call, signal) {
526
+ async function prepare(api, files, maxFiles, options, signal) {
452
527
  let pending = files;
453
528
  try {
454
529
  let catalog;
@@ -467,10 +542,6 @@ function createUploadQueue(initialOptions, initialContextApi) {
467
542
  multipart: options.multipart
468
543
  }
469
544
  );
470
- const maxFiles = Math.min(
471
- options.maxFiles ?? DEFAULT_MAX_FILES,
472
- call.maxFiles ?? Number.POSITIVE_INFINITY
473
- );
474
545
  const accepted = [];
475
546
  const rejected = [];
476
547
  for (const file of files) {
@@ -510,7 +581,7 @@ function createUploadQueue(initialOptions, initialContextApi) {
510
581
  }
511
582
  }
512
583
  function enqueue(entries, call, options, replace) {
513
- if (replace && !options.queue) {
584
+ if (replace && !queues(call, options)) {
514
585
  for (const task of tasks.values()) {
515
586
  abortTask(task, uploadAbortReason("cancel"));
516
587
  }
@@ -522,10 +593,11 @@ function createUploadQueue(initialOptions, initialContextApi) {
522
593
  function upload(input, call = {}) {
523
594
  return startCall([...input], call, []);
524
595
  }
525
- function retry(id) {
596
+ function retry(ids) {
597
+ const wanted = ids === void 0 ? null : new Set(typeof ids === "string" ? [ids] : ids);
526
598
  const failed = snapshot.files.filter(
527
- (entry) => entry.phase === "error" && (id === void 0 || entry.id === id)
528
- );
599
+ (entry) => entry.phase === "error" && (wanted?.has(entry.id) ?? true)
600
+ ).slice(0, freeUploadSlots(instanceId, snapshot.files));
529
601
  if (failed.length === 0) return Promise.resolve(batchResult([]));
530
602
  const calls = Map.groupBy(
531
603
  failed,
@@ -546,7 +618,7 @@ function createUploadQueue(initialOptions, initialContextApi) {
546
618
  const api = requireApi(options.api ?? latest.contextApi, "useUpload");
547
619
  if (files.length === 0) return settle(batchResult([]));
548
620
  const controller = new AbortController();
549
- if (!options.queue && retried.length === 0) {
621
+ if (!queues(call, options) && retried.length === 0) {
550
622
  const reason = uploadAbortReason("cancel");
551
623
  for (const pending of preparingCalls) pending.abort(reason);
552
624
  }
@@ -557,10 +629,26 @@ function createUploadQueue(initialOptions, initialContextApi) {
557
629
  );
558
630
  preparingCalls.add(controller);
559
631
  commit({ preparing: snapshot.preparing + 1 });
632
+ const maxFiles = Math.min(
633
+ options.maxFiles ?? DEFAULT_MAX_FILES,
634
+ call.maxFiles ?? Number.POSITIVE_INFINITY,
635
+ retried.length === 0 ? freeUploadSlots(instanceId, snapshot.files) : Number.POSITIVE_INFINITY
636
+ );
637
+ const release = reserveUploadSlots(
638
+ instanceId,
639
+ retried.length === 0 ? Math.min(files.length, maxFiles) : 0
640
+ );
560
641
  let prepared;
561
642
  try {
562
- prepared = await prepare(api, files, options, call, controller.signal);
643
+ prepared = await prepare(
644
+ api,
645
+ files,
646
+ maxFiles,
647
+ options,
648
+ controller.signal
649
+ );
563
650
  } finally {
651
+ release();
564
652
  preparingCalls.delete(controller);
565
653
  for (const id of previous.keys()) retrying.delete(id);
566
654
  commit({ preparing: snapshot.preparing - 1 });
@@ -747,6 +835,9 @@ function createUploadQueue(initialOptions, initialContextApi) {
747
835
  dispose
748
836
  };
749
837
  }
838
+ function queues(call, options) {
839
+ return call.queue ?? options.queue ?? false;
840
+ }
750
841
  function createEntry(file) {
751
842
  return {
752
843
  id: crypto.randomUUID(),
@@ -1082,7 +1173,7 @@ function useUpload(options) {
1082
1173
  maxFileSize: options.maxFileSize,
1083
1174
  multipart: options.multipart
1084
1175
  });
1085
- const engine = useFileUpload(options);
1176
+ const engine = useFileUpload(options, instanceId);
1086
1177
  const { upload, retry: retryFiles } = engine;
1087
1178
  const catalogStatusRef = useLiveRef(routePolicy.status);
1088
1179
  const handleFiles = useCallback(
@@ -1093,9 +1184,9 @@ function useUpload(options) {
1093
1184
  [catalogStatusRef, reloadCatalog, upload]
1094
1185
  );
1095
1186
  const retry = useCallback(
1096
- (id) => {
1187
+ (ids) => {
1097
1188
  if (catalogStatusRef.current === "error") reloadCatalog();
1098
- return retryFiles(id);
1189
+ return retryFiles(ids);
1099
1190
  },
1100
1191
  [catalogStatusRef, reloadCatalog, retryFiles]
1101
1192
  );
@@ -1141,6 +1232,24 @@ function toFileArray(files) {
1141
1232
  if (files instanceof File) return [files];
1142
1233
  return Array.from(files);
1143
1234
  }
1235
+ function useUploadLimit(upload, limit) {
1236
+ const { instanceId, files } = upload;
1237
+ const [ref] = useState(() => ({ current: limit }));
1238
+ useLayoutEffect(() => {
1239
+ ref.current = limit;
1240
+ });
1241
+ useLayoutEffect(() => addUploadLimit(instanceId, ref), [instanceId, ref]);
1242
+ const subscribe = useCallback(
1243
+ (listener) => subscribeUploadSlots(instanceId, listener),
1244
+ [instanceId]
1245
+ );
1246
+ const reserved = useSyncExternalStore(
1247
+ subscribe,
1248
+ () => reservedUploadSlots(instanceId),
1249
+ () => 0
1250
+ );
1251
+ return limit ? uploadSlotsLeft(limit, files, reserved) : null;
1252
+ }
1144
1253
  var REVOKE_DELAY_MS = 3e4;
1145
1254
  function startBrowserDownload(url) {
1146
1255
  clickLink(url);
@@ -1191,7 +1300,6 @@ function clickLink(href, fileName) {
1191
1300
  }
1192
1301
 
1193
1302
  // src/hooks/use-download.ts
1194
- var PRESIGN_MANY_CONCURRENCY = 4;
1195
1303
  function useDownload(options) {
1196
1304
  const instanceId = useId();
1197
1305
  const contextApi = useContext(S3Context);
@@ -1235,27 +1343,6 @@ function useDownload(options) {
1235
1343
  },
1236
1344
  [optionsRef, resolveApi, sign]
1237
1345
  );
1238
- const presignMany = useCallback(
1239
- async (files) => {
1240
- const outcomes = await mapWithConcurrency(
1241
- files,
1242
- PRESIGN_MANY_CONCURRENCY,
1243
- ({ key, ...request }) => presign2(key, request)
1244
- );
1245
- const result = { signed: [], failed: [], blocked: [] };
1246
- for (const outcome of outcomes) {
1247
- if (outcome.status === "success") {
1248
- result.signed.push(outcome.data);
1249
- } else if (outcome.status === "error") {
1250
- result.failed.push({ key: outcome.key, error: outcome.error });
1251
- } else {
1252
- result.blocked.push(outcome.key);
1253
- }
1254
- }
1255
- return result;
1256
- },
1257
- [presign2]
1258
- );
1259
1346
  const navigate = useCallback(
1260
1347
  async (call, fileName) => {
1261
1348
  const { key, signal } = call;
@@ -1312,7 +1399,6 @@ function useDownload(options) {
1312
1399
  isPending: pendingKeys.length > 0,
1313
1400
  download,
1314
1401
  presign: presign2,
1315
- presignMany,
1316
1402
  cancel,
1317
1403
  reset
1318
1404
  };
@@ -1893,8 +1979,10 @@ var EMPTY_SNAPSHOT = {
1893
1979
  folders: [],
1894
1980
  nextCursor: null,
1895
1981
  usage: null,
1982
+ total: null,
1896
1983
  pageCount: 0
1897
1984
  };
1985
+ var NO_SCOPES = [];
1898
1986
  var INITIAL_STATE = {
1899
1987
  snapshot: EMPTY_SNAPSHOT,
1900
1988
  pending: null,
@@ -1926,22 +2014,36 @@ function useObjectList(options) {
1926
2014
  () => options.defaultSearch ?? "",
1927
2015
  options.onSearchChange
1928
2016
  );
2017
+ const [searchScope, setSearchScope] = useControllableState(
2018
+ options.searchScope,
2019
+ () => options.defaultSearchScope ?? "folder",
2020
+ options.onSearchScopeChange
2021
+ );
2022
+ const searchParentRef = useRef(parent);
2023
+ useLayoutEffect(() => {
2024
+ if (searchParentRef.current === parent) return;
2025
+ searchParentRef.current = parent;
2026
+ setSearchValue("");
2027
+ }, [parent, setSearchValue]);
1929
2028
  const queryKey = JSON.stringify(options.queryKey ?? []);
1930
- const trimmedSearch = search.trim();
2029
+ const trimmedSearch = normalizeSearchText(search) === "" ? "" : search.trim();
1931
2030
  const request = useMemo(() => {
1932
2031
  const scope = JSON.stringify([queryKey, parent]);
1933
2032
  return {
1934
2033
  key: JSON.stringify([
1935
2034
  scope,
1936
2035
  sort ? `${sort.field}:${sort.direction}` : "",
1937
- trimmedSearch
2036
+ trimmedSearch,
2037
+ // The scope matters only while something is searched.
2038
+ trimmedSearch ? searchScope : ""
1938
2039
  ]),
1939
2040
  scope,
1940
2041
  parent,
1941
2042
  sort,
1942
- search: trimmedSearch
2043
+ search: trimmedSearch,
2044
+ searchScope
1943
2045
  };
1944
- }, [parent, queryKey, sort, trimmedSearch]);
2046
+ }, [parent, queryKey, searchScope, sort, trimmedSearch]);
1945
2047
  const requestRef = useLiveRef(request);
1946
2048
  const trailRef = useLiveRef(trail);
1947
2049
  const [state, setState] = useState(INITIAL_STATE);
@@ -1976,6 +2078,7 @@ function useObjectList(options) {
1976
2078
  parent: target.parent,
1977
2079
  sort: target.sort,
1978
2080
  search: target.search,
2081
+ searchScope: target.searchScope,
1979
2082
  signal: controller.signal
1980
2083
  };
1981
2084
  try {
@@ -2001,13 +2104,19 @@ function useObjectList(options) {
2001
2104
  const pageTarget = mode === "refresh" ? Math.max(1, current.snapshot.pageCount) : 1;
2002
2105
  const items2 = [];
2003
2106
  let folders2 = [];
2107
+ let serverTrail;
2004
2108
  let usage = null;
2109
+ let total = null;
2005
2110
  let cursor = null;
2006
2111
  let pageCount = 0;
2007
2112
  do {
2008
2113
  const page = await opts.query({ ...input, cursor });
2009
2114
  if (!isCurrent()) return;
2010
- if (pageCount === 0) folders2 = page.folders ?? [];
2115
+ if (pageCount === 0) {
2116
+ folders2 = page.folders ?? [];
2117
+ if (page.trail) serverTrail = page.trail;
2118
+ if (target.search && page.total != null) total = page.total;
2119
+ }
2011
2120
  for (const item of page.items) items2.push(item);
2012
2121
  usage = page.usage ?? usage;
2013
2122
  cursor = page.nextCursor || null;
@@ -2023,9 +2132,14 @@ function useObjectList(options) {
2023
2132
  folders: folders2,
2024
2133
  nextCursor: cursor,
2025
2134
  usage,
2135
+ total,
2026
2136
  pageCount
2027
2137
  }
2028
2138
  }));
2139
+ if (serverTrail && (target.parent === null ? serverTrail.length === 0 : serverTrail.at(-1)?.id === target.parent)) {
2140
+ trailRef.current = serverTrail;
2141
+ setTrailState(serverTrail);
2142
+ }
2029
2143
  } catch (err) {
2030
2144
  if (!isCurrent()) return;
2031
2145
  const error = toClientError(err);
@@ -2037,7 +2151,7 @@ function useObjectList(options) {
2037
2151
  }));
2038
2152
  }
2039
2153
  },
2040
- [optionsRef, requestRef, update]
2154
+ [optionsRef, requestRef, trailRef, update]
2041
2155
  );
2042
2156
  useEffect(() => {
2043
2157
  if (!enabled) return;
@@ -2071,9 +2185,14 @@ function useObjectList(options) {
2071
2185
  );
2072
2186
  const openFolder = useCallback(
2073
2187
  (folder) => {
2188
+ const { location, ...opened } = folder;
2189
+ if (location) {
2190
+ navigate([...location.map(plainFolder), opened]);
2191
+ return;
2192
+ }
2074
2193
  const current = trailRef.current;
2075
2194
  const index = current.findIndex((entry) => entry.id === folder.id);
2076
- navigate(index >= 0 ? current.slice(0, index + 1) : [...current, folder]);
2195
+ navigate(index >= 0 ? current.slice(0, index + 1) : [...current, opened]);
2077
2196
  },
2078
2197
  [navigate, trailRef]
2079
2198
  );
@@ -2144,17 +2263,101 @@ function useObjectList(options) {
2144
2263
  }
2145
2264
  } : draft
2146
2265
  );
2266
+ const now = requestRef.current;
2267
+ if (now.scope === scope && namesNeedReload(now)) await run("refresh");
2147
2268
  return folder;
2148
2269
  },
2149
- [optionsRef, requestRef, update]
2270
+ [optionsRef, requestRef, run, update]
2271
+ );
2272
+ const settleRename = useCallback(
2273
+ async (scope, replaced) => {
2274
+ if (requestRef.current.scope !== scope) return;
2275
+ if (!replaced || namesNeedReload(requestRef.current)) {
2276
+ await run("refresh");
2277
+ }
2278
+ },
2279
+ [requestRef, run]
2150
2280
  );
2151
- const setSort = useCallback(
2152
- (next) => setSortValue(next),
2153
- [setSortValue]
2281
+ const renameFile = useCallback(
2282
+ async (item, name) => {
2283
+ const rename = optionsRef.current.renameFile;
2284
+ if (!rename) {
2285
+ throw new Error("[dimah-s3] The source has no renameFile.");
2286
+ }
2287
+ const { getFile: read, getKey: keyOf } = optionsRef.current;
2288
+ if ((read ? read(item).name : keyOf(item)) === name) return item;
2289
+ const key = keyOf(item);
2290
+ const { scope } = requestRef.current;
2291
+ let next;
2292
+ try {
2293
+ next = await rename({ item, name });
2294
+ } catch (err) {
2295
+ throw toClientError(err);
2296
+ }
2297
+ if (next) {
2298
+ const replacement = next;
2299
+ update((draft) => {
2300
+ if (draft.snapshot.scope !== scope) return draft;
2301
+ const idOf = optionsRef.current.getKey;
2302
+ return {
2303
+ ...draft,
2304
+ snapshot: {
2305
+ ...draft.snapshot,
2306
+ items: draft.snapshot.items.map(
2307
+ (current) => idOf(current) === key ? replacement : current
2308
+ )
2309
+ }
2310
+ };
2311
+ });
2312
+ }
2313
+ await settleRename(scope, next != null);
2314
+ return next;
2315
+ },
2316
+ [optionsRef, requestRef, settleRename, update]
2154
2317
  );
2155
- const setSearch = useCallback(
2156
- (next) => setSearchValue(next),
2157
- [setSearchValue]
2318
+ const renameFolder = useCallback(
2319
+ async (folder, name) => {
2320
+ const rename = optionsRef.current.renameFolder;
2321
+ if (!rename) {
2322
+ throw new Error("[dimah-s3] The source has no renameFolder.");
2323
+ }
2324
+ if (folder.name === name) return folder;
2325
+ const { scope } = requestRef.current;
2326
+ let next;
2327
+ try {
2328
+ next = await rename({ folder, name });
2329
+ } catch (err) {
2330
+ throw toClientError(err);
2331
+ }
2332
+ if (next) {
2333
+ const replacement = next;
2334
+ update((draft) => {
2335
+ if (draft.snapshot.scope !== scope) return draft;
2336
+ return {
2337
+ ...draft,
2338
+ snapshot: {
2339
+ ...draft.snapshot,
2340
+ folders: draft.snapshot.folders.map(
2341
+ (current) => current.id === folder.id ? replacement : current
2342
+ )
2343
+ }
2344
+ };
2345
+ });
2346
+ const currentTrail = trailRef.current;
2347
+ if (currentTrail.some(
2348
+ (entry) => entry.id === folder.id && entry.name !== replacement.name
2349
+ )) {
2350
+ const renamedTrail = currentTrail.map(
2351
+ (entry) => entry.id === folder.id ? { ...entry, name: replacement.name } : entry
2352
+ );
2353
+ trailRef.current = renamedTrail;
2354
+ setTrailState(renamedTrail);
2355
+ }
2356
+ }
2357
+ await settleRename(scope, next != null);
2358
+ return next;
2359
+ },
2360
+ [optionsRef, requestRef, settleRename, trailRef, update]
2158
2361
  );
2159
2362
  const { getKey, getFile: readFile } = options;
2160
2363
  const getFile = useMemo(
@@ -2175,10 +2378,7 @@ function useObjectList(options) {
2175
2378
  pending,
2176
2379
  failure
2177
2380
  });
2178
- const entries = useMemo(
2179
- () => createObjectListEntries(folders, items, getKey, getFile),
2180
- [folders, getFile, getKey, items]
2181
- );
2381
+ const entries = useReusedEntries(folders, items, getKey, getFile);
2182
2382
  const nextCursor = fresh ? snapshot.nextCursor : null;
2183
2383
  return {
2184
2384
  entries,
@@ -2188,6 +2388,10 @@ function useObjectList(options) {
2188
2388
  parent,
2189
2389
  sort,
2190
2390
  search,
2391
+ isSearching: trimmedSearch !== "",
2392
+ searchScope,
2393
+ searchScopes: options.searchScopes ?? NO_SCOPES,
2394
+ total: fresh && trimmedSearch ? snapshot.total : null,
2191
2395
  usage: visible ? snapshot.usage : null,
2192
2396
  error: fresh ? failure?.error ?? null : null,
2193
2397
  status,
@@ -2202,17 +2406,29 @@ function useObjectList(options) {
2202
2406
  openFolder,
2203
2407
  navigate,
2204
2408
  goUp,
2205
- setSort,
2206
- setSearch,
2409
+ setSort: setSortValue,
2410
+ setSearch: setSearchValue,
2411
+ setSearchScope,
2207
2412
  setItems,
2208
2413
  setFolders,
2209
2414
  removeItems,
2210
2415
  getKey,
2211
2416
  getFile,
2212
2417
  uploadOptions: options.uploadOptions,
2213
- createFolder: options.createFolder ? createFolder : void 0
2418
+ createFolder: options.createFolder ? createFolder : void 0,
2419
+ renameFile: options.renameFile ? renameFile : void 0,
2420
+ renameFolder: options.renameFolder ? renameFolder : void 0
2214
2421
  };
2215
2422
  }
2423
+ function useReusedEntries(folders, items, getKey, getFile) {
2424
+ const [cache, setCache] = useState(
2425
+ () => reuseObjectListEntries(null, folders, items, getKey, getFile)
2426
+ );
2427
+ if (cache.folders === folders && cache.items === items) return cache.entries;
2428
+ const next = reuseObjectListEntries(cache, folders, items, getKey, getFile);
2429
+ setCache(next);
2430
+ return next.entries;
2431
+ }
2216
2432
  function readStatus({
2217
2433
  enabled,
2218
2434
  fresh,
@@ -2228,6 +2444,12 @@ function readStatus({
2228
2444
  if (pending === "refresh") return hasRows ? "refreshing" : "loading";
2229
2445
  return failure ? "error" : "ready";
2230
2446
  }
2447
+ function namesNeedReload(request) {
2448
+ return request.sort?.field === "name" || request.search !== "";
2449
+ }
2450
+ function plainFolder(folder) {
2451
+ return { id: folder.id, name: folder.name };
2452
+ }
2231
2453
  function sortsEqual(a, b) {
2232
2454
  return a === b || a?.field === b?.field && a?.direction === b?.direction;
2233
2455
  }
@@ -2257,15 +2479,23 @@ function useObjectListSelection(list, options = {}) {
2257
2479
  selected: /* @__PURE__ */ new Map(),
2258
2480
  anchor: null
2259
2481
  }));
2482
+ const loaded = useMemo(
2483
+ () => new Map(list.entries.map((entry) => [entry.key, entry])),
2484
+ [list.entries]
2485
+ );
2260
2486
  let state = stored;
2261
2487
  if (stored.scope !== scope) {
2262
2488
  state = { scope, selected: /* @__PURE__ */ new Map(), anchor: null };
2263
2489
  setStored(state);
2490
+ } else if (!persist && hasMissing(stored.selected, loaded)) {
2491
+ state = {
2492
+ ...stored,
2493
+ selected: new Map(
2494
+ [...stored.selected].filter(([key]) => loaded.has(key))
2495
+ )
2496
+ };
2497
+ setStored(state);
2264
2498
  }
2265
- const loaded = useMemo(
2266
- () => new Map(list.entries.map((entry) => [entry.key, entry])),
2267
- [list.entries]
2268
- );
2269
2499
  const selectable = useMemo(
2270
2500
  () => list.entries.filter((entry) => canSelect(entry)),
2271
2501
  [canSelect, list.entries]
@@ -2418,6 +2648,12 @@ function useObjectListSelection(list, options = {}) {
2418
2648
  clear
2419
2649
  };
2420
2650
  }
2651
+ function hasMissing(selected, loaded) {
2652
+ for (const key of selected.keys()) {
2653
+ if (!loaded.has(key)) return true;
2654
+ }
2655
+ return false;
2656
+ }
2421
2657
  function toKeys(keys) {
2422
2658
  return typeof keys === "string" ? [keys] : keys;
2423
2659
  }
@@ -2478,8 +2714,8 @@ function numberFormat(locale) {
2478
2714
  return format;
2479
2715
  }
2480
2716
 
2481
- // src/helpers/format-dimah-error.tsx
2482
- function useFormatDimahError() {
2717
+ // src/helpers/format-error.tsx
2718
+ function useFormatError() {
2483
2719
  const t = useTranslations();
2484
2720
  const formatFileSize2 = useFormatFileSize();
2485
2721
  const formatNumber = useFormatNumber();
@@ -2599,6 +2835,8 @@ function useFormatDimahError() {
2599
2835
  });
2600
2836
  case "FOLDER_INVALID":
2601
2837
  return t("Folder name is invalid", { note: "API error" });
2838
+ case "FOLDER_NOT_FOUND":
2839
+ return t("Folder not found", { note: "API error" });
2602
2840
  case "FOLDER_EXISTS":
2603
2841
  return t("A folder with this name already exists", {
2604
2842
  note: "API error"
@@ -2717,6 +2955,6 @@ function dateFormat(locale, options = DEFAULT_DATE_OPTIONS) {
2717
2955
  return format;
2718
2956
  }
2719
2957
 
2720
- export { S3Provider, createS3Client, useApi, useDelete, useDownload, useFetchDownload, useFormatAcceptLabels, useFormatDate, useFormatDimahError, useFormatEta, useFormatFileSize, useFormatNumber, useFormatSpeed, useObjectList, useObjectListSelection, useObjectUrl, useRouteUploadPolicy, useUpload };
2958
+ export { S3Provider, createS3Client, useApi, useDelete, useDownload, useFetchDownload, useFormatAcceptLabels, useFormatDate, useFormatError, useFormatEta, useFormatFileSize, useFormatNumber, useFormatSpeed, useObjectList, useObjectListSelection, useObjectUrl, useRouteUploadPolicy, useUpload, useUploadLimit };
2721
2959
  //# sourceMappingURL=index.js.map
2722
2960
  //# sourceMappingURL=index.js.map