@widgetic/file-browser 0.5.47 → 0.5.48

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 (102) hide show
  1. package/dist/actions/dragSelectedToFolder.js +104 -115
  2. package/dist/components/FolderTree.svelte.d.ts +4 -7
  3. package/dist/components/core/Dropzone.svelte +42 -2
  4. package/dist/components/core/FileBrowser.svelte +224 -14
  5. package/dist/components/core/FileUploader.svelte +124 -41
  6. package/dist/components/core/RecentFiles.svelte +54 -16
  7. package/dist/components/core/SearchDropdown.svelte +6 -8
  8. package/dist/components/core/UploadPanel.svelte +7 -0
  9. package/dist/components/core/UploadPanel.svelte.d.ts +4 -0
  10. package/dist/components/core/UploadRow.svelte +9 -4
  11. package/dist/components/core/UploadRow.svelte.d.ts +2 -0
  12. package/dist/components/core/dropzoneClick.d.ts +28 -0
  13. package/dist/components/core/dropzoneClick.js +32 -0
  14. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  15. package/dist/components/ui/DropdownMenu.svelte +1 -1
  16. package/dist/config.js +4 -3
  17. package/dist/i18n/context.js +2 -2
  18. package/dist/i18n/errors.js +2 -1
  19. package/dist/i18n/messages.d.ts +13 -0
  20. package/dist/i18n/messages.js +15 -2
  21. package/dist/i18n/text.js +2 -2
  22. package/dist/mediaLibrary/capabilities.js +4 -3
  23. package/dist/mediaLibrary/context.js +4 -3
  24. package/dist/mediaLibrary/errors.js +46 -35
  25. package/dist/mediaLibrary/normalize.js +45 -42
  26. package/dist/mediaLibrary/paging.js +100 -45
  27. package/dist/mediaLibrary/resolve.js +214 -95
  28. package/dist/mediaLibrary/treeOps.js +40 -20
  29. package/dist/mediaLibrary/urls.js +12 -10
  30. package/dist/mediaLibrary/widgetic.js +140 -54
  31. package/dist/stores/dragStore.js +1 -1
  32. package/dist/stores/fileStore.d.ts +3 -3
  33. package/dist/stores/fileStore.js +44 -37
  34. package/dist/stores/folderCountStore.js +12 -11
  35. package/dist/stores/missingFilesStore.js +3 -3
  36. package/dist/stores/navigationStore.d.ts +1 -1
  37. package/dist/stores/navigationStore.js +217 -178
  38. package/dist/stores/persistentSelectStore.d.ts +1 -1
  39. package/dist/stores/persistentSelectStore.js +117 -94
  40. package/dist/stores/searchStore.js +1 -1
  41. package/dist/stores/uploadApiStore.d.ts +10 -0
  42. package/dist/stores/uploadApiStore.js +7 -7
  43. package/dist/stores/viewportStore.js +4 -4
  44. package/dist/types/index.js +0 -1
  45. package/dist/utils/apiConfig.js +9 -9
  46. package/dist/utils/brandKitLibraryTree.js +57 -42
  47. package/dist/utils/dateUtils.js +11 -9
  48. package/dist/utils/deleteSelectionAction.d.ts +26 -0
  49. package/dist/utils/deleteSelectionAction.js +23 -0
  50. package/dist/utils/dragToFolder/batchMoveResult.js +114 -54
  51. package/dist/utils/dragToFolder/folderDropTarget.js +23 -17
  52. package/dist/utils/dragToFolder/springStep.js +4 -3
  53. package/dist/utils/fileGoneProbe.js +65 -16
  54. package/dist/utils/fileKinds.js +14 -13
  55. package/dist/utils/fileNames.js +7 -7
  56. package/dist/utils/fileOperations.js +440 -332
  57. package/dist/utils/fileTypes.js +19 -14
  58. package/dist/utils/fileUtils.js +85 -31
  59. package/dist/utils/folderUtils.js +5 -4
  60. package/dist/utils/gridLayout.js +7 -7
  61. package/dist/utils/imagePreviewCache.js +26 -15
  62. package/dist/utils/imagePreviewFrame.js +13 -13
  63. package/dist/utils/imagePreviewVisualState.js +5 -4
  64. package/dist/utils/imageTransform.js +27 -14
  65. package/dist/utils/itemMenuCapabilities.js +7 -7
  66. package/dist/utils/libraryTree.js +55 -39
  67. package/dist/utils/pendingUploadDeletes.d.ts +102 -0
  68. package/dist/utils/pendingUploadDeletes.js +400 -0
  69. package/dist/utils/previewKeys.js +1 -1
  70. package/dist/utils/previewListNavigation.js +13 -11
  71. package/dist/utils/previewNavigation.js +10 -7
  72. package/dist/utils/recentFiles.js +16 -6
  73. package/dist/utils/recentFilesLimit.js +2 -2
  74. package/dist/utils/removeItems.d.ts +30 -0
  75. package/dist/utils/removeItems.js +124 -0
  76. package/dist/utils/resolveFileUrl.js +6 -6
  77. package/dist/utils/safeText.js +14 -12
  78. package/dist/utils/searchDropdownPhase.d.ts +14 -3
  79. package/dist/utils/searchDropdownPhase.js +13 -9
  80. package/dist/utils/searchItems.js +30 -14
  81. package/dist/utils/searchNavigation.js +5 -5
  82. package/dist/utils/uploadAuth.d.ts +24 -0
  83. package/dist/utils/uploadAuth.js +140 -0
  84. package/dist/utils/uploadDisplayProgress.js +1 -1
  85. package/dist/utils/uploadLimits.d.ts +76 -0
  86. package/dist/utils/uploadLimits.js +242 -0
  87. package/dist/utils/uploadListReconcile.js +24 -11
  88. package/dist/utils/uploadPanelDismiss.js +1 -1
  89. package/dist/utils/uploadPanelProgress.js +4 -4
  90. package/dist/utils/uploadProgressMath.js +13 -11
  91. package/dist/utils/uploadRefusals.d.ts +42 -0
  92. package/dist/utils/uploadRefusals.js +86 -0
  93. package/dist/utils/uploadResponseMapping.js +9 -8
  94. package/dist/utils/uploadUiHelpers.js +17 -17
  95. package/dist/utils/userUploadsStorage.js +270 -133
  96. package/dist/utils/videoFrame.d.ts +23 -0
  97. package/dist/utils/videoFrame.js +26 -0
  98. package/dist/utils/widgeticDelete.js +103 -28
  99. package/dist/utils/widgeticTusUpload.js +189 -105
  100. package/dist/utils/widgeticUpload.js +133 -59
  101. package/dist/utils/xhrMultipartUpload.js +164 -116
  102. package/package.json +3 -3
@@ -79,8 +79,8 @@
79
79
  import { getFileTypeOf } from '../../utils/fileKinds';
80
80
  import { getFolderIcon } from '../../utils/folderUtils';
81
81
  import { type FileFilterType, FILTER_OPTIONS, getAllowedFileTypes, FILE_TYPES, formatFileTypesForDisplay } from '../../utils/fileTypes';
82
- import { getPathNamesFromIds, deleteItem, renameItem, moveItem, findItemById } from '../../utils/fileOperations';
83
- import { getFileBrowserUploadConfig, setFileBrowserUploadConfig } from '../../stores/uploadApiStore';
82
+ import { getPathNamesFromIds, renameItem, moveItem, findItemById } from '../../utils/fileOperations';
83
+ import { getFileBrowserUploadConfig, setFileBrowserUploadConfig, type FileBrowserUploadConfig } from '../../stores/uploadApiStore';
84
84
  import {
85
85
  loadUserUploads,
86
86
  removePersistedUploads,
@@ -139,6 +139,15 @@
139
139
  import type { MediaLibraryErrorCode, MediaLibraryProvider } from '../../mediaLibrary/types';
140
140
  import { getRenamedFileName, splitFileName } from '../../utils/fileNames';
141
141
  import { escapeSelectionAction } from '../../utils/escapeSelectionAction';
142
+ import { deleteSelectionAction } from '../../utils/deleteSelectionAction';
143
+ import { filesOfItems, putItemsBackInTree, removeItemsFromTree, type RemovedItem } from '../../utils/removeItems';
144
+ import {
145
+ classifyDeleteStatus,
146
+ getPendingUploadDeleteQueue,
147
+ type DeleteProcessor,
148
+ type PendingUploadDelete,
149
+ } from '../../utils/pendingUploadDeletes';
150
+ import { deleteUploadFromWidgeticApi } from '../../utils/widgeticDelete';
142
151
  import { recentFilesLimitForWidth } from '../../utils/recentFilesLimit';
143
152
  import DragGhostStack from '../drag/DragGhostStack.svelte';
144
153
  import {
@@ -803,7 +812,9 @@
803
812
  const token = session?.accessToken || session?.access_token;
804
813
  if (token) {
805
814
  // Scope Dexie only — do not invent an empty apiBasePath upload config.
806
- const { ensureCacheOwnerFromSessionHint, setCacheOwner } = await import('@widgetic/cache-layer');
815
+ const { ensureCacheOwnerFromSessionHint, setCacheOwner } = await import(
816
+ '@widgetic/cache-layer'
817
+ );
807
818
  ensureCacheOwnerFromSessionHint();
808
819
  const payloadPart = token.split('.')[1];
809
820
  if (payloadPart) {
@@ -857,6 +868,8 @@
857
868
  listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
858
869
  apiHydrationSucceeded: true,
859
870
  });
871
+ // What the visitor deleted and the API has not confirmed yet stays off the list
872
+ files = await withoutPendingDeletes(files);
860
873
  await replacePersistedUploads(files);
861
874
  data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
862
875
  basePath = '';
@@ -874,6 +887,8 @@
874
887
  data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
875
888
  basePath = '';
876
889
  }
890
+ // Deletes an earlier visit did not finish (the files left the screen then, the API was not told)
891
+ resumePendingDeletes();
877
892
  if (showLogs) {
878
893
  // console.log('[FileBrowser] Widgetic library mode — user uploads only');
879
894
  }
@@ -1721,6 +1736,13 @@
1721
1736
  selectedItem = null;
1722
1737
  itemsPendingDeletion = [];
1723
1738
  showDeleteConfirmation = false;
1739
+
1740
+ // The Widgetic library (and the demo content) never makes the visitor wait: everything chosen leaves the screen in
1741
+ // one step, and the API is told in the background. A host's media library keeps its own, slower way below.
1742
+ if (!libraryMode) {
1743
+ deleteInTheBackground(itemsToDelete);
1744
+ return;
1745
+ }
1724
1746
 
1725
1747
  // Show initial toast notification
1726
1748
  const initialToastMessage = $t('toast.delete.started', {
@@ -1744,7 +1766,7 @@
1744
1766
  // Process each item for deletion
1745
1767
  for (const item of itemsToDelete) {
1746
1768
  try {
1747
- const success = libraryMode ? await deleteFromLibrary(item) : await deleteItem(item.id);
1769
+ const success = await deleteFromLibrary(item);
1748
1770
  if (success) {
1749
1771
  successCount++;
1750
1772
  deletedItems.push(item.name);
@@ -1827,6 +1849,166 @@
1827
1849
  }, 100); // Small delay to ensure UI updates first
1828
1850
  }
1829
1851
 
1852
+ /**
1853
+ * Opens the delete dialog for everything that is selected: what the Delete button of the selection bar does, and what
1854
+ * the Delete key does when files are selected.
1855
+ */
1856
+ function openDeleteDialogForSelection() {
1857
+ selectedItem = null;
1858
+ // The selection bar acts on everything selected
1859
+ itemsPendingDeletion = [...allSelectedFiles];
1860
+ showDeleteConfirmation = true;
1861
+ }
1862
+
1863
+ // What is needed to put an upload back if the API refuses to delete it: where it sat, by upload id. It is kept while this
1864
+ // File Browser lives; after a reload the next list from the API shows the file again, which comes to the same thing.
1865
+ const takenOffScreen = new Map<string, RemovedItem>();
1866
+ // The uploads the API refused, gathered for a moment so that one toast tells about all of them.
1867
+ let refusedDeleteNames: string[] = [];
1868
+ let refusedDeleteTimer: ReturnType<typeof setTimeout> | null = null;
1869
+
1870
+ /**
1871
+ * Deletes without making the visitor wait (the Widgetic library and the demo content). Every file and folder chosen leaves
1872
+ * the screen in one step and the toast says so. The API is told afterwards, through a queue that is written down in Dexie
1873
+ * first (see pendingUploadDeletes.ts), so a reload or a bad network neither brings the files back nor loses the delete.
1874
+ * When the API refuses for good, the file is put back and the visitor is told.
1875
+ */
1876
+ function deleteInTheBackground(itemsToDelete: FileSystemItem[]) {
1877
+ try {
1878
+ let removedEntries: RemovedItem[] = [];
1879
+ fileStore.update((store) => {
1880
+ const result = removeItemsFromTree(store.root, new Set(itemsToDelete.map((item) => item.id)));
1881
+ removedEntries = result.removed;
1882
+ return { ...store, root: result.root };
1883
+ });
1884
+
1885
+ const removedFiles = filesOfItems(removedEntries.map((entry) => entry.item));
1886
+ const removedFileIds = new Set(removedFiles.map((file) => file.id));
1887
+
1888
+ // Nothing that was removed stays selected, previewed or listed in the local copy
1889
+ removedFileIds.forEach((fileId) => persistentSelectStore.removeSelection(fileId, filter));
1890
+ selectedFiles.update((files) => files.filter((file) => !removedFileIds.has(file.id)));
1891
+ if (previewFile && removedFileIds.has(previewFile.id)) previewFile = null;
1892
+ for (const entry of removedEntries) {
1893
+ if (entry.item.type === 'folder') {
1894
+ // The folder is gone: the view goes back to the root, as it always did after a folder was deleted
1895
+ navigationStore.cleanupPaths(entry.item.id);
1896
+ currentFolder.set([]);
1897
+ currentPath = [];
1898
+ }
1899
+ }
1900
+ persistMyUploadsTree();
1901
+ void removePersistedUploads([...removedFileIds]);
1902
+
1903
+ // The visitor's answer is the screen: just the fact, with nothing about the background
1904
+ if (itemsToDelete.length === 1) {
1905
+ const [onlyItem] = itemsToDelete;
1906
+ showToast(
1907
+ 'success',
1908
+ onlyItem.type === 'folder'
1909
+ ? $t('toast.delete.doneFolder', { name: onlyItem.name })
1910
+ : $t('toast.delete.doneFile', { name: onlyItem.name }),
1911
+ );
1912
+ } else {
1913
+ showToast('success', $t('toast.delete.doneMany', { count: itemsToDelete.length }));
1914
+ }
1915
+
1916
+ // The API: only the Widgetic library has one (the demo content has nobody to tell)
1917
+ const uploadConfig = getFileBrowserUploadConfig();
1918
+ if (!uploadConfig?.accessToken || !uploadConfig.apiBasePath || removedFiles.length === 0) return;
1919
+
1920
+ // Where each upload goes back to if it must: a file that was chosen, where it sat; a file of a folder, the root
1921
+ for (const entry of removedEntries) {
1922
+ if (entry.item.type === 'file') {
1923
+ takenOffScreen.set(entry.item.id, entry);
1924
+ } else {
1925
+ for (const file of filesOfItems([entry.item])) takenOffScreen.set(file.id, { item: file, parentId: null, index: 0 });
1926
+ }
1927
+ }
1928
+ void getPendingUploadDeleteQueue()
1929
+ .enqueue(removedFiles.map((file) => ({ uploadId: file.id, name: file.name })))
1930
+ .then(() => startPendingDeletes(uploadConfig));
1931
+ } catch (error) {
1932
+ console.error('Error deleting items:', error);
1933
+ showToast('error', $t('toast.delete.failedAll'), {
1934
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1935
+ });
1936
+ }
1937
+ }
1938
+
1939
+ /** How the API is asked to delete one upload: with the settings of the page, and a renewed session when it comes to that. */
1940
+ function deleteProcessorFor(uploadConfig: FileBrowserUploadConfig): DeleteProcessor {
1941
+ return async (record) => {
1942
+ try {
1943
+ await deleteUploadFromWidgeticApi(uploadConfig, record.uploadId);
1944
+ return { result: 'ok' };
1945
+ } catch (error) {
1946
+ const status = error instanceof MediaLibraryError ? error.status : undefined;
1947
+ const message = error instanceof Error ? error.message : String(error);
1948
+ const verdict = classifyDeleteStatus(status);
1949
+ return verdict === 'ok' ? { result: 'ok' } : { result: verdict, message };
1950
+ }
1951
+ };
1952
+ }
1953
+
1954
+ /** Sends the deletes that are written down: the ones just chosen, and the ones an earlier visit did not finish. */
1955
+ function startPendingDeletes(uploadConfig: FileBrowserUploadConfig) {
1956
+ void getPendingUploadDeleteQueue().drain(deleteProcessorFor(uploadConfig), {
1957
+ onDeleted: (record) => {
1958
+ takenOffScreen.delete(record.uploadId);
1959
+ },
1960
+ onGaveUp: (record, message) => putBackRefusedUpload(record, message),
1961
+ });
1962
+ }
1963
+
1964
+ /** Finishes the deletes an earlier visit left in the queue: the files were taken off the screen then, the API was not told. */
1965
+ function resumePendingDeletes() {
1966
+ const uploadConfig = getFileBrowserUploadConfig();
1967
+ if (libraryMode || !uploadConfig?.accessToken || !uploadConfig.apiBasePath) return;
1968
+ startPendingDeletes(uploadConfig);
1969
+ }
1970
+
1971
+ /** The API refused for good (or could not be reached for a long time): the file is still in the library, so it comes back. */
1972
+ function putBackRefusedUpload(record: PendingUploadDelete, message: string) {
1973
+ const entry = takenOffScreen.get(record.uploadId);
1974
+ takenOffScreen.delete(record.uploadId);
1975
+ if (entry) {
1976
+ fileStore.update((store) => ({ ...store, root: putItemsBackInTree(store.root, [entry]) }));
1977
+ saveUserUploadsBatch([entry.item]);
1978
+ persistMyUploadsTree();
1979
+ } else {
1980
+ // This visit never took it off the screen (a reload came in between): the list from the API has it
1981
+ void refreshUploadsFromApi();
1982
+ }
1983
+
1984
+ refusedDeleteNames.push(record.name);
1985
+ if (refusedDeleteTimer) clearTimeout(refusedDeleteTimer);
1986
+ refusedDeleteTimer = setTimeout(() => {
1987
+ const names = refusedDeleteNames;
1988
+ refusedDeleteNames = [];
1989
+ refusedDeleteTimer = null;
1990
+ showToast(
1991
+ 'error',
1992
+ names.length === 1
1993
+ ? $t('toast.delete.failedOne', { name: names[0] })
1994
+ : $t('toast.delete.failedMany', { count: names.length }),
1995
+ { description: $t('toast.delete.putBack', { count: names.length }) },
1996
+ );
1997
+ }, 400);
1998
+ if (showLogs) console.log(`[FileBrowser] ${record.name} put back: ${message}`);
1999
+ }
2000
+
2001
+ /** Uploads whose delete is waiting in the queue are not listed: they were taken off the screen, and the API catches up. */
2002
+ async function withoutPendingDeletes(files: FileSystemItem[]): Promise<FileSystemItem[]> {
2003
+ try {
2004
+ const pendingIds = await getPendingUploadDeleteQueue().pendingIds();
2005
+ return pendingIds.size === 0 ? files : files.filter((file) => !pendingIds.has(file.id));
2006
+ } catch (error) {
2007
+ console.warn('[FileBrowser] Could not read the queue of deletes:', error);
2008
+ return files;
2009
+ }
2010
+ }
2011
+
1830
2012
  function isWidgeticLibraryMode(): boolean {
1831
2013
  const uploadConfig = getFileBrowserUploadConfig();
1832
2014
  return Boolean(uploadConfig?.accessToken && uploadConfig?.apiBasePath) || !useDemoContent;
@@ -2065,6 +2247,37 @@
2065
2247
  // modalOpen: $isModalOpen
2066
2248
  // });
2067
2249
 
2250
+ // Delete (or Backspace, which a Mac keyboard labels "delete") with files selected opens the same delete dialog as the
2251
+ // Delete button of the selection bar. It comes before the Backspace handler below, which goes back one folder when
2252
+ // nothing is selected.
2253
+ if (
2254
+ deleteSelectionAction({
2255
+ key: event.key,
2256
+ altKey: event.altKey,
2257
+ shiftKey: event.shiftKey,
2258
+ defaultPrevented: event.defaultPrevented,
2259
+ allowSelecting,
2260
+ canDelete: libraryCapabilities.delete,
2261
+ selectionCount: allSelectedFiles.length,
2262
+ previewOpen: !!previewFile,
2263
+ designSystemModalOpen: $isModalOpen,
2264
+ inputFocused: !!isInputFocused(event),
2265
+ innerUiOpen:
2266
+ filterDropdownOpen ||
2267
+ sortDropdownOpen ||
2268
+ showModal ||
2269
+ showRenameDialog ||
2270
+ showNewFolderDialog ||
2271
+ showMoveDialog ||
2272
+ showDeleteConfirmation,
2273
+ }) === 'open-delete-dialog'
2274
+ ) {
2275
+ event.preventDefault();
2276
+ event.stopPropagation();
2277
+ openDeleteDialogForSelection();
2278
+ return;
2279
+ }
2280
+
2068
2281
  // Backspace key handler
2069
2282
  if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused(event) && !$isModalOpen) {
2070
2283
  event.preventDefault();
@@ -2507,10 +2720,12 @@
2507
2720
  const remoteFiles = await fetchUserUploadsFromApi(uploadConfig, {
2508
2721
  limit: WIDGETIC_UPLOADS_LIST_LIMIT,
2509
2722
  });
2510
- const merged = mergeRemoteUploadList(cached, remoteFiles, {
2511
- listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
2512
- apiHydrationSucceeded: true,
2513
- });
2723
+ const merged = await withoutPendingDeletes(
2724
+ mergeRemoteUploadList(cached, remoteFiles, {
2725
+ listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
2726
+ apiHydrationSucceeded: true,
2727
+ }),
2728
+ );
2514
2729
  await replacePersistedUploads(merged);
2515
2730
  const root = await createUserUploadsFileSystemRoot(merged, $t('library.defaultLabel'));
2516
2731
  data = root;
@@ -3362,12 +3577,7 @@ mainGridClass="app-main-grid"
3362
3577
  compact={isCompactLayout}
3363
3578
  on:send={sendToEditor}
3364
3579
  on:move={(e : any) => handleItemAction(new CustomEvent('action', { detail: { action: 'move', item: e.detail.items[0] } }))}
3365
- on:delete={(e : any) => {
3366
- selectedItem = null;
3367
- // The selection bar acts on everything selected
3368
- itemsPendingDeletion = [...allSelectedFiles];
3369
- showDeleteConfirmation = true;
3370
- }}
3580
+ on:delete={openDeleteDialogForSelection}
3371
3581
  on:rename={(e : any) => handleItemAction(new CustomEvent('action', { detail: { action: 'rename', item: e.detail.item } }))}
3372
3582
  />
3373
3583
  </div>
@@ -27,6 +27,8 @@
27
27
  import { get } from 'svelte/store';
28
28
  import { fileBrowserUploadConfig } from '../../stores/uploadApiStore';
29
29
  import { uploadToWidgeticApi } from '../../utils/widgeticUpload';
30
+ import { extensionOfFileName, extensionsTakenFrom, limitsTakeMimeType, loadUploadLimits, type UploadLimits } from '../../utils/uploadLimits';
31
+ import { planUploads, refusalMessages, typeLabelOfFile, unsupportedTypeReason, type RefusedFile } from '../../utils/uploadRefusals';
30
32
  import { useMediaLibraryContext } from '../../mediaLibrary/context';
31
33
  import { MediaLibraryError, isCancellation, toMediaLibraryError } from '../../mediaLibrary/errors';
32
34
  import { useI18n } from '../../i18n/context';
@@ -65,6 +67,8 @@
65
67
 
66
68
  // Local variables
67
69
  let uploading = false;
70
+ /** What the Widgetic API takes as an upload, once it has said so: `null` until then (and for a media library). */
71
+ let uploadLimits: UploadLimits | null = null;
68
72
  let fileInput: HTMLInputElement;
69
73
  let uploaderRootEl: HTMLDivElement;
70
74
  // show logs
@@ -92,6 +96,8 @@
92
96
  status: 'uploading' | 'complete' | 'failed';
93
97
  previewUrl: string;
94
98
  errorMessage?: string;
99
+ /** False for a failure that trying again cannot fix (the API refuses the file's type or size): no retry is offered. */
100
+ canRetry?: boolean;
95
101
  /** Estimated seconds left; internal (shown via buildActiveRowStatusText) */
96
102
  timeRemainingSeconds?: number;
97
103
  throughputBps?: number;
@@ -108,10 +114,20 @@
108
114
 
109
115
  // Reactive variables
110
116
  $: allowedKinds = allowedKindsOf(filter === 'all' ? allowedTypes : FILE_TYPES[filter as Exclude<FileFilterType, 'all'>]);
111
- $: tooltipTypesText = formatAllowedTypesForDisplay(filter, $t);
112
- $: acceptTypes = filter === 'all'
113
- ? Object.values(FILE_TYPES).flat().join(',')
114
- : FILE_TYPES[filter as Exclude<FileFilterType, 'all'>].join(',');
117
+ // The extensions of the kinds of file this File Browser lists for its filter.
118
+ $: listedTypes = filter === 'all'
119
+ ? Object.values(FILE_TYPES).flat()
120
+ : FILE_TYPES[filter as Exclude<FileFilterType, 'all'>];
121
+ $: acceptTypes = listedTypes.join(',');
122
+ // The same as a set, to ask whether one extension is listed (".jp" is not ".jpg", which a text search would say).
123
+ $: acceptedExtensions = new Set(listedTypes.map((extension) => extension.toLowerCase()));
124
+ // What the file chooser offers and the "?" lists: the types above minus those the Widgetic API is known to refuse (fonts,
125
+ // audio, Word files ...), so a visitor is not invited to pick what cannot be sent. A media library has its own rules.
126
+ $: offeredTypes = library ? listedTypes : extensionsTakenFrom(listedTypes, uploadLimits);
127
+ $: inputAcceptTypes = offeredTypes.join(',');
128
+ $: tooltipTypesText = filter === 'all' && offeredTypes.length < listedTypes.length
129
+ ? $t('fileTypes.allowed', { types: offeredTypes.join($t('list.separator')) })
130
+ : formatAllowedTypesForDisplay(filter, $t);
115
131
  // The kinds of file the uploader takes, as words in the visitor's language: "image, video", "any", "document".
116
132
  $: allowedTypesDisplayText = kindsText(filter, allowedKinds, $t);
117
133
  // With the "all" filter every kind of file is taken, and the sentences of the dropzone do not name a kind ("Upload files").
@@ -192,6 +208,7 @@
192
208
  status: item.status,
193
209
  statusText: statusTextForItem(item),
194
210
  errorMessage: item.errorMessage,
211
+ canRetry: item.canRetry !== false,
195
212
  })
196
213
  );
197
214
 
@@ -242,14 +259,17 @@
242
259
  );
243
260
 
244
261
  $: panelFooterDestructive = failedUploadCount > 0;
262
+ // "Retry failed uploads?" is offered only when a try could change something: a file the API refuses for its type or
263
+ // size fails the same way again.
264
+ $: retryableFailedCount = uploadItems.filter((item) => item.status === 'failed' && item.canRetry !== false).length;
245
265
  $: panelFooterAction =
246
- failedUploadCount > 0 && uploadingCount === 0 && completedUploadCount < totalUploadCount;
266
+ retryableFailedCount > 0 && uploadingCount === 0 && completedUploadCount < totalUploadCount;
247
267
 
248
268
  $: panelFooterText = (() => {
249
269
  if (totalUploadCount === 0) return $t('upload.uploading');
250
270
  if (panelFooterAction) return $t('upload.retryFailed');
251
271
  if (totalUploadCount === 1 && uploadingCount === 1) return $t('upload.uploading');
252
- if (totalUploadCount === 1 && failedUploadCount === 1) return $t('upload.retry');
272
+ if (totalUploadCount === 1 && failedUploadCount === 1) return retryableFailedCount === 1 ? $t('upload.retry') : $t('upload.failed');
253
273
  if (totalUploadCount === 1 && completedUploadCount === 1) return $t('upload.complete');
254
274
  if (uploadingCount > 0 && failedUploadCount > 0) {
255
275
  return joinMeta(
@@ -325,7 +345,9 @@
325
345
 
326
346
  isDraggingFolder = false;
327
347
  const extension = getMimeTypeExtension(item.type);
328
- const isInvalid = !acceptTypes.includes(extension);
348
+ // A type the Widgetic API is known to refuse (a font, a sound) shows as not accepted while it is dragged,
349
+ // as it will be when dropped.
350
+ const isInvalid = !acceptTypes.includes(extension) || !limitsTakeMimeType(item.type, library ? null : uploadLimits);
329
351
  return isInvalid;
330
352
  }
331
353
  return false;
@@ -365,24 +387,9 @@
365
387
  }
366
388
 
367
389
  isDraggingFolder = false;
368
- const hasInvalidFiles = Array.from(files).some(file => {
369
- const extension = file.name.split('.').pop()?.toLowerCase();
370
- const fileExtension = extension ? '.' + extension : '';
371
- return !acceptTypes.includes(fileExtension);
372
- });
373
-
374
- if (hasInvalidFiles) {
375
- isDraggingFolder = false;
376
- dragInvalid = true;
377
- setTimeout(() => {
378
- showToast('error', $t('upload.invalidType', { types: allowedTypesDisplayText }));
379
- return;
380
- }, 0);
381
- return;
382
- }
383
-
384
390
  dragInvalid = false;
385
- isDraggingFolder = false;
391
+ // The files this File Browser or the API does not take are left out with a reason (a toast naming them), and the
392
+ // rest are sent: the same as when the files are picked with the file chooser.
386
393
  handleFiles(files);
387
394
  }
388
395
  }
@@ -615,7 +622,7 @@
615
622
  formData.append('path', path);
616
623
  formData.append('folderId', currentFolderId);
617
624
 
618
- let response: { success: boolean; file?: any; error?: string };
625
+ let response: { success: boolean; file?: any; error?: string; status?: number };
619
626
 
620
627
  if (library) {
621
628
  // The host's media library stores the file. It reports progress as a number from 0 to 100.
@@ -839,6 +846,9 @@
839
846
  // Close progress overlay so the file grid is visible again (black dim was the upload overlay)
840
847
  scheduleUploadDrawerDismiss();
841
848
  } else {
849
+ // What the row says, and whether trying again can change anything
850
+ const failure = describeFailedUpload(response, normalizedFile);
851
+
842
852
  // Update the upload item to failed
843
853
  uploadItems = uploadItems.map((item) =>
844
854
  item.id === uploadId
@@ -847,7 +857,8 @@
847
857
  displayProgress: 0,
848
858
  status: 'failed',
849
859
  uploadPhase: undefined,
850
- errorMessage: response.error || $t('libraryError.uploadFailed'),
860
+ errorMessage: failure.errorMessage,
861
+ canRetry: failure.canRetry,
851
862
  timeRemainingSeconds: undefined,
852
863
  }
853
864
  : item,
@@ -906,26 +917,45 @@
906
917
  * Handles the upload of multiple files
907
918
  * @param files The files to upload
908
919
  */
909
- async function handleFiles(files: FileList) {
910
- // open the uploads overlay with the drawer open
911
- isUploadsModalOpen = true;
912
-
913
- // set the uploading state to true
920
+ async function handleFiles(files: FileList | File[]) {
921
+ // set the uploading state to true (the dropzone shows "Uploading…" while the session is checked)
914
922
  uploading = true;
915
-
923
+
916
924
  // prepare an array to store the files that were skipped
917
925
  let skippedFiles: string[] = [];
918
926
 
919
927
  // try to upload the files
920
928
  try {
921
- // Process each file
922
- for (const file of files) {
923
- const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
924
- if (!acceptTypes.includes(fileExtension)) {
925
- console.error(`File type not allowed: ${file.name}`);
926
- dispatch('error', { message: `File type not allowed: ${file.name}. Please use ${kindsText(filter, allowedKinds, translateEnglish)} files only.` });
927
- continue;
929
+ const pickedFiles = Array.from(files, (pickedFile) => normalizeFileMimeType(pickedFile));
930
+
931
+ // Before the first file is sent: is the session still good, and what does the API take? The answer decides, up
932
+ // front, which files go on (a font the API would refuse with a 415 is explained now, not after the wait). A session
933
+ // that is out of date is renewed by this very call, so the files that follow are sent with a good one.
934
+ const uploadConfig = library ? null : get(fileBrowserUploadConfig);
935
+ let limits = library ? null : uploadLimits;
936
+ if (uploadConfig?.accessToken && uploadConfig.apiBasePath) {
937
+ const answer = await loadUploadLimits(uploadConfig);
938
+ if (answer.sessionRefused) {
939
+ showToast('error', $t('upload.sessionExpired'));
940
+ return;
928
941
  }
942
+ limits = answer.limits ?? limits;
943
+ uploadLimits = limits;
944
+ }
945
+
946
+ const plan = planUploads(pickedFiles, {
947
+ takesExtension: (extension) => extension !== '' && acceptedExtensions.has(extension),
948
+ limits,
949
+ });
950
+ reportRefusedFiles(plan.refused);
951
+ if (plan.accepted.length === 0) return;
952
+
953
+ // open the uploads overlay with the drawer open
954
+ isUploadsModalOpen = true;
955
+
956
+ // Process each file that goes on
957
+ for (const file of plan.accepted) {
958
+ const fileExtension = extensionOfFileName(file.name);
929
959
 
930
960
  if (restrictDuplicateNames && isDuplicate(file.name, fileExtension)) {
931
961
  if(showLogs) console.log(`Skipping duplicate file: ${file.name}`);
@@ -948,6 +978,55 @@
948
978
  } catch (error) {
949
979
  console.error('Upload failed:', error);
950
980
  dispatch('error', { message: error instanceof Error ? error.message : 'Upload failed' });
981
+ } finally {
982
+ // Nothing is being sent (every file was left out, or the session is gone): the dropzone is ready for the next pick.
983
+ if (!uploadItems.some((item) => item.status === 'uploading')) uploading = false;
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Tells the visitor which files were left out before anything was sent, and why: a toast per reason that names the
989
+ * file (or counts them) and says what is wrong ("BLMelody-Bold.otf" was not uploaded: .otf files are not supported).
990
+ * The files are not queued, so no row of the upload panel fails for them and nothing offers to retry them.
991
+ */
992
+ function reportRefusedFiles(refused: RefusedFile[]) {
993
+ if (refused.length === 0) return;
994
+
995
+ // With a filter set (only images, say) the reason is the filter's sentence; with every kind taken it is the type's.
996
+ const filterReason = filter === 'all' ? null : $t('upload.invalidType', { types: allowedTypesDisplayText });
997
+ for (const message of refusalMessages(refused, $t, filterReason)) {
998
+ showToast('error', message);
999
+ }
1000
+
1001
+ for (const { file, refusal } of refused) {
1002
+ console.warn(`[FileUploader] Not uploaded: ${file.name} (${refusal.reason}${refusal.reason === 'unsupportedType' ? `, ${refusal.mimeType || 'no type'}` : ''})`);
1003
+ // The host is told about the files its own filter did not take, as it always has been. The message of an `error`
1004
+ // event is for the page's developer: English, whatever the visitor's language.
1005
+ if (refusal.reason === 'filter') {
1006
+ dispatch('error', { message: `File type not allowed: ${file.name}. Please use ${kindsText(filter, allowedKinds, translateEnglish)} files only.`, file: file.name });
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ /**
1012
+ * What the row of a failed upload says, and whether trying again can change anything. A session that stayed refused after
1013
+ * it was renewed (401) is said in the visitor's words. A file the API refuses for what it is (415 its type, 413 its size)
1014
+ * can never go through, so its row names the reason and offers no retry.
1015
+ */
1016
+ function describeFailedUpload(response: { error?: string; status?: number }, file: File): { errorMessage: string; canRetry: boolean } {
1017
+ if (response.status === 401) return { errorMessage: $t('upload.sessionExpired'), canRetry: true };
1018
+ if (response.status === 415) return { errorMessage: unsupportedTypeReason([typeLabelOfFile(file)], $t), canRetry: false };
1019
+ return { errorMessage: response.error || $t('libraryError.uploadFailed'), canRetry: response.status !== 413 };
1020
+ }
1021
+
1022
+ /** Reads what the Widgetic API takes, so the file chooser, the "?" and the drag over say the same as the drop will. */
1023
+ async function refreshUploadLimits() {
1024
+ const uploadConfig = library ? null : get(fileBrowserUploadConfig);
1025
+ if (!uploadConfig?.accessToken || !uploadConfig.apiBasePath) return;
1026
+ try {
1027
+ uploadLimits = (await loadUploadLimits(uploadConfig)).limits ?? uploadLimits;
1028
+ } catch (error) {
1029
+ console.warn('[FileUploader] Could not read the upload limits:', error);
951
1030
  }
952
1031
  }
953
1032
 
@@ -1073,7 +1152,7 @@
1073
1152
 
1074
1153
  // Function to retry all failed uploads
1075
1154
  function retryAllFailedUploads() {
1076
- const failedUploads = uploadItems.filter(item => item.status === 'failed');
1155
+ const failedUploads = uploadItems.filter(item => item.status === 'failed' && item.canRetry !== false);
1077
1156
  failedUploads.forEach(item => handleRetryUpload(item.id));
1078
1157
  }
1079
1158
 
@@ -1122,6 +1201,9 @@
1122
1201
  onMount(() => {
1123
1202
  // if(showLogs) console.log('FileUploader mounted');
1124
1203
 
1204
+ // Learn what the Widgetic API takes (in the background: the uploader works while it is read).
1205
+ void refreshUploadLimits();
1206
+
1125
1207
  // Get parent element for portal
1126
1208
  if (!portalTarget && uploaderRootEl && uploaderRootEl.parentElement) {
1127
1209
  portalTarget = uploaderRootEl.parentElement;
@@ -1167,6 +1249,7 @@
1167
1249
  footerText={panelFooterText}
1168
1250
  footerDestructive={panelFooterDestructive}
1169
1251
  footerAction={panelFooterAction}
1252
+ summaryCanRetry={retryableFailedCount > 0}
1170
1253
  expanded={!isUploadsDrawerCollapsed}
1171
1254
  onToggleExpand={toggleDrawerCollapse}
1172
1255
  onSummaryCancel={() => {
@@ -1190,7 +1273,7 @@
1190
1273
  onchange={handleFileSelect}
1191
1274
  multiple
1192
1275
  class="upload-input hidden"
1193
- accept={acceptTypes}
1276
+ accept={inputAcceptTypes}
1194
1277
  />
1195
1278
 
1196
1279
  <Dropzone