@widgetic/file-browser 0.5.47 → 0.5.49

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 (34) hide show
  1. package/dist/components/core/Dropzone.svelte +42 -2
  2. package/dist/components/core/FileBrowser.svelte +221 -13
  3. package/dist/components/core/FileUploader.svelte +124 -41
  4. package/dist/components/core/RecentFiles.svelte +54 -16
  5. package/dist/components/core/SearchDropdown.svelte +6 -8
  6. package/dist/components/core/UploadPanel.svelte +7 -0
  7. package/dist/components/core/UploadPanel.svelte.d.ts +4 -0
  8. package/dist/components/core/UploadRow.svelte +9 -4
  9. package/dist/components/core/UploadRow.svelte.d.ts +2 -0
  10. package/dist/components/core/dropzoneClick.d.ts +28 -0
  11. package/dist/components/core/dropzoneClick.js +31 -0
  12. package/dist/components/ui/DropdownMenu.svelte +1 -1
  13. package/dist/i18n/messages.d.ts +13 -0
  14. package/dist/i18n/messages.js +13 -0
  15. package/dist/stores/uploadApiStore.d.ts +10 -0
  16. package/dist/utils/deleteSelectionAction.d.ts +26 -0
  17. package/dist/utils/deleteSelectionAction.js +23 -0
  18. package/dist/utils/pendingUploadDeletes.d.ts +102 -0
  19. package/dist/utils/pendingUploadDeletes.js +224 -0
  20. package/dist/utils/removeItems.d.ts +30 -0
  21. package/dist/utils/removeItems.js +92 -0
  22. package/dist/utils/searchDropdownPhase.d.ts +14 -3
  23. package/dist/utils/searchDropdownPhase.js +12 -8
  24. package/dist/utils/uploadAuth.d.ts +24 -0
  25. package/dist/utils/uploadAuth.js +65 -0
  26. package/dist/utils/uploadLimits.d.ts +76 -0
  27. package/dist/utils/uploadLimits.js +170 -0
  28. package/dist/utils/uploadRefusals.d.ts +42 -0
  29. package/dist/utils/uploadRefusals.js +70 -0
  30. package/dist/utils/videoFrame.d.ts +23 -0
  31. package/dist/utils/videoFrame.js +26 -0
  32. package/dist/utils/widgeticDelete.js +5 -3
  33. package/dist/utils/widgeticUpload.js +10 -4
  34. package/package.json +3 -3
@@ -6,6 +6,7 @@
6
6
  import { IconCloudUpload, IconHelp } from '@widgetic/design-system/icons';
7
7
  import { useI18n } from '../../i18n/context';
8
8
  import { splitAround } from '../../i18n/text';
9
+ import { canBrowseFromZone, shouldBrowseFromZoneClick } from './dropzoneClick';
9
10
 
10
11
  export type DropzoneState = 'idle' | 'hover' | 'drag-valid' | 'drag-invalid';
11
12
 
@@ -37,6 +38,23 @@
37
38
  const dragInvalid = $derived(state === 'drag-invalid');
38
39
  const dragValid = $derived(state === 'drag-valid');
39
40
 
41
+ // The whole zone opens the file chooser, not only the button in it (see dropzoneClick.ts for which clicks count)
42
+ const zoneOpensChooser = $derived(canBrowseFromZone(state, showInitialUploading));
43
+
44
+ function handleZoneClick(event: MouseEvent) {
45
+ try {
46
+ const shouldBrowse = shouldBrowseFromZoneClick({
47
+ target: event.target as Element | null,
48
+ zone: event.currentTarget as Element,
49
+ state,
50
+ showInitialUploading
51
+ });
52
+ if (shouldBrowse) onBrowse();
53
+ } catch (error) {
54
+ console.error('[Dropzone] Could not open the file chooser from the zone', error);
55
+ }
56
+ }
57
+
40
58
  // What the zone says when the dragged file cannot be taken (a folder, or a kind the zone does not accept)
41
59
  const invalidMessage = $derived(
42
60
  isDraggingFolder
@@ -61,7 +79,25 @@
61
79
  });
62
80
  </script>
63
81
 
64
- <div class={[zoneClasses, { 'h-14': compact, 'h-28': !compact, 'px-4': compact, 'p-4': !compact }]}>
82
+ <!--
83
+ The zone is a mouse target as a whole; the button inside it stays the one control for the keyboard and for screen readers
84
+ (a second role="button" on the zone would nest one control in another), so the zone itself has no key handler.
85
+ -->
86
+ <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
87
+ <div
88
+ class={[
89
+ zoneClasses,
90
+ {
91
+ 'h-14': compact,
92
+ 'h-28': !compact,
93
+ 'px-4': compact,
94
+ 'p-4': !compact,
95
+ 'cursor-pointer': zoneOpensChooser
96
+ }
97
+ ]}
98
+ data-fb-dropzone
99
+ onclick={handleZoneClick}
100
+ >
65
101
  <div class={outlineClasses} aria-hidden="true"></div>
66
102
 
67
103
  <div
@@ -128,7 +164,11 @@
128
164
  {/if}
129
165
  </div>
130
166
 
131
- <div class="absolute end-4 top-4 z-[2]">
167
+ <!--
168
+ Figma Dropzone: the 16 px "?" sits 12 px from the top and the end of the zone (Compact: 12 px from the end, centred in
169
+ the height). The button around it is 32 px, so its box starts 12 - (32 - 16) / 2 = 4 px from those edges.
170
+ -->
171
+ <div class={['absolute end-1 z-[2]', compact ? 'top-1/2 -translate-y-1/2' : 'top-1']}>
132
172
  <HintTooltip content={tooltipTypesText} side="top" sideOffset={8} contentClass="max-w-[250px]">
133
173
  {#snippet trigger({ props })}
134
174
  <IconButton
@@ -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 {
@@ -857,6 +866,8 @@
857
866
  listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
858
867
  apiHydrationSucceeded: true,
859
868
  });
869
+ // What the visitor deleted and the API has not confirmed yet stays off the list
870
+ files = await withoutPendingDeletes(files);
860
871
  await replacePersistedUploads(files);
861
872
  data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
862
873
  basePath = '';
@@ -874,6 +885,8 @@
874
885
  data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
875
886
  basePath = '';
876
887
  }
888
+ // Deletes an earlier visit did not finish (the files left the screen then, the API was not told)
889
+ resumePendingDeletes();
877
890
  if (showLogs) {
878
891
  // console.log('[FileBrowser] Widgetic library mode — user uploads only');
879
892
  }
@@ -1721,6 +1734,13 @@
1721
1734
  selectedItem = null;
1722
1735
  itemsPendingDeletion = [];
1723
1736
  showDeleteConfirmation = false;
1737
+
1738
+ // The Widgetic library (and the demo content) never makes the visitor wait: everything chosen leaves the screen in
1739
+ // one step, and the API is told in the background. A host's media library keeps its own, slower way below.
1740
+ if (!libraryMode) {
1741
+ deleteInTheBackground(itemsToDelete);
1742
+ return;
1743
+ }
1724
1744
 
1725
1745
  // Show initial toast notification
1726
1746
  const initialToastMessage = $t('toast.delete.started', {
@@ -1744,7 +1764,7 @@
1744
1764
  // Process each item for deletion
1745
1765
  for (const item of itemsToDelete) {
1746
1766
  try {
1747
- const success = libraryMode ? await deleteFromLibrary(item) : await deleteItem(item.id);
1767
+ const success = await deleteFromLibrary(item);
1748
1768
  if (success) {
1749
1769
  successCount++;
1750
1770
  deletedItems.push(item.name);
@@ -1827,6 +1847,166 @@
1827
1847
  }, 100); // Small delay to ensure UI updates first
1828
1848
  }
1829
1849
 
1850
+ /**
1851
+ * Opens the delete dialog for everything that is selected: what the Delete button of the selection bar does, and what
1852
+ * the Delete key does when files are selected.
1853
+ */
1854
+ function openDeleteDialogForSelection() {
1855
+ selectedItem = null;
1856
+ // The selection bar acts on everything selected
1857
+ itemsPendingDeletion = [...allSelectedFiles];
1858
+ showDeleteConfirmation = true;
1859
+ }
1860
+
1861
+ // 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
1862
+ // File Browser lives; after a reload the next list from the API shows the file again, which comes to the same thing.
1863
+ const takenOffScreen = new Map<string, RemovedItem>();
1864
+ // The uploads the API refused, gathered for a moment so that one toast tells about all of them.
1865
+ let refusedDeleteNames: string[] = [];
1866
+ let refusedDeleteTimer: ReturnType<typeof setTimeout> | null = null;
1867
+
1868
+ /**
1869
+ * Deletes without making the visitor wait (the Widgetic library and the demo content). Every file and folder chosen leaves
1870
+ * the screen in one step and the toast says so. The API is told afterwards, through a queue that is written down in Dexie
1871
+ * first (see pendingUploadDeletes.ts), so a reload or a bad network neither brings the files back nor loses the delete.
1872
+ * When the API refuses for good, the file is put back and the visitor is told.
1873
+ */
1874
+ function deleteInTheBackground(itemsToDelete: FileSystemItem[]) {
1875
+ try {
1876
+ let removedEntries: RemovedItem[] = [];
1877
+ fileStore.update((store) => {
1878
+ const result = removeItemsFromTree(store.root, new Set(itemsToDelete.map((item) => item.id)));
1879
+ removedEntries = result.removed;
1880
+ return { ...store, root: result.root };
1881
+ });
1882
+
1883
+ const removedFiles = filesOfItems(removedEntries.map((entry) => entry.item));
1884
+ const removedFileIds = new Set(removedFiles.map((file) => file.id));
1885
+
1886
+ // Nothing that was removed stays selected, previewed or listed in the local copy
1887
+ removedFileIds.forEach((fileId) => persistentSelectStore.removeSelection(fileId, filter));
1888
+ selectedFiles.update((files) => files.filter((file) => !removedFileIds.has(file.id)));
1889
+ if (previewFile && removedFileIds.has(previewFile.id)) previewFile = null;
1890
+ for (const entry of removedEntries) {
1891
+ if (entry.item.type === 'folder') {
1892
+ // The folder is gone: the view goes back to the root, as it always did after a folder was deleted
1893
+ navigationStore.cleanupPaths(entry.item.id);
1894
+ currentFolder.set([]);
1895
+ currentPath = [];
1896
+ }
1897
+ }
1898
+ persistMyUploadsTree();
1899
+ void removePersistedUploads([...removedFileIds]);
1900
+
1901
+ // The visitor's answer is the screen: just the fact, with nothing about the background
1902
+ if (itemsToDelete.length === 1) {
1903
+ const [onlyItem] = itemsToDelete;
1904
+ showToast(
1905
+ 'success',
1906
+ onlyItem.type === 'folder'
1907
+ ? $t('toast.delete.doneFolder', { name: onlyItem.name })
1908
+ : $t('toast.delete.doneFile', { name: onlyItem.name }),
1909
+ );
1910
+ } else {
1911
+ showToast('success', $t('toast.delete.doneMany', { count: itemsToDelete.length }));
1912
+ }
1913
+
1914
+ // The API: only the Widgetic library has one (the demo content has nobody to tell)
1915
+ const uploadConfig = getFileBrowserUploadConfig();
1916
+ if (!uploadConfig?.accessToken || !uploadConfig.apiBasePath || removedFiles.length === 0) return;
1917
+
1918
+ // Where each upload goes back to if it must: a file that was chosen, where it sat; a file of a folder, the root
1919
+ for (const entry of removedEntries) {
1920
+ if (entry.item.type === 'file') {
1921
+ takenOffScreen.set(entry.item.id, entry);
1922
+ } else {
1923
+ for (const file of filesOfItems([entry.item])) takenOffScreen.set(file.id, { item: file, parentId: null, index: 0 });
1924
+ }
1925
+ }
1926
+ void getPendingUploadDeleteQueue()
1927
+ .enqueue(removedFiles.map((file) => ({ uploadId: file.id, name: file.name })))
1928
+ .then(() => startPendingDeletes(uploadConfig));
1929
+ } catch (error) {
1930
+ console.error('Error deleting items:', error);
1931
+ showToast('error', $t('toast.delete.failedAll'), {
1932
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1933
+ });
1934
+ }
1935
+ }
1936
+
1937
+ /** How the API is asked to delete one upload: with the settings of the page, and a renewed session when it comes to that. */
1938
+ function deleteProcessorFor(uploadConfig: FileBrowserUploadConfig): DeleteProcessor {
1939
+ return async (record) => {
1940
+ try {
1941
+ await deleteUploadFromWidgeticApi(uploadConfig, record.uploadId);
1942
+ return { result: 'ok' };
1943
+ } catch (error) {
1944
+ const status = error instanceof MediaLibraryError ? error.status : undefined;
1945
+ const message = error instanceof Error ? error.message : String(error);
1946
+ const verdict = classifyDeleteStatus(status);
1947
+ return verdict === 'ok' ? { result: 'ok' } : { result: verdict, message };
1948
+ }
1949
+ };
1950
+ }
1951
+
1952
+ /** Sends the deletes that are written down: the ones just chosen, and the ones an earlier visit did not finish. */
1953
+ function startPendingDeletes(uploadConfig: FileBrowserUploadConfig) {
1954
+ void getPendingUploadDeleteQueue().drain(deleteProcessorFor(uploadConfig), {
1955
+ onDeleted: (record) => {
1956
+ takenOffScreen.delete(record.uploadId);
1957
+ },
1958
+ onGaveUp: (record, message) => putBackRefusedUpload(record, message),
1959
+ });
1960
+ }
1961
+
1962
+ /** Finishes the deletes an earlier visit left in the queue: the files were taken off the screen then, the API was not told. */
1963
+ function resumePendingDeletes() {
1964
+ const uploadConfig = getFileBrowserUploadConfig();
1965
+ if (libraryMode || !uploadConfig?.accessToken || !uploadConfig.apiBasePath) return;
1966
+ startPendingDeletes(uploadConfig);
1967
+ }
1968
+
1969
+ /** 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. */
1970
+ function putBackRefusedUpload(record: PendingUploadDelete, message: string) {
1971
+ const entry = takenOffScreen.get(record.uploadId);
1972
+ takenOffScreen.delete(record.uploadId);
1973
+ if (entry) {
1974
+ fileStore.update((store) => ({ ...store, root: putItemsBackInTree(store.root, [entry]) }));
1975
+ saveUserUploadsBatch([entry.item]);
1976
+ persistMyUploadsTree();
1977
+ } else {
1978
+ // This visit never took it off the screen (a reload came in between): the list from the API has it
1979
+ void refreshUploadsFromApi();
1980
+ }
1981
+
1982
+ refusedDeleteNames.push(record.name);
1983
+ if (refusedDeleteTimer) clearTimeout(refusedDeleteTimer);
1984
+ refusedDeleteTimer = setTimeout(() => {
1985
+ const names = refusedDeleteNames;
1986
+ refusedDeleteNames = [];
1987
+ refusedDeleteTimer = null;
1988
+ showToast(
1989
+ 'error',
1990
+ names.length === 1
1991
+ ? $t('toast.delete.failedOne', { name: names[0] })
1992
+ : $t('toast.delete.failedMany', { count: names.length }),
1993
+ { description: $t('toast.delete.putBack', { count: names.length }) },
1994
+ );
1995
+ }, 400);
1996
+ if (showLogs) console.log(`[FileBrowser] ${record.name} put back: ${message}`);
1997
+ }
1998
+
1999
+ /** Uploads whose delete is waiting in the queue are not listed: they were taken off the screen, and the API catches up. */
2000
+ async function withoutPendingDeletes(files: FileSystemItem[]): Promise<FileSystemItem[]> {
2001
+ try {
2002
+ const pendingIds = await getPendingUploadDeleteQueue().pendingIds();
2003
+ return pendingIds.size === 0 ? files : files.filter((file) => !pendingIds.has(file.id));
2004
+ } catch (error) {
2005
+ console.warn('[FileBrowser] Could not read the queue of deletes:', error);
2006
+ return files;
2007
+ }
2008
+ }
2009
+
1830
2010
  function isWidgeticLibraryMode(): boolean {
1831
2011
  const uploadConfig = getFileBrowserUploadConfig();
1832
2012
  return Boolean(uploadConfig?.accessToken && uploadConfig?.apiBasePath) || !useDemoContent;
@@ -2065,6 +2245,37 @@
2065
2245
  // modalOpen: $isModalOpen
2066
2246
  // });
2067
2247
 
2248
+ // Delete (or Backspace, which a Mac keyboard labels "delete") with files selected opens the same delete dialog as the
2249
+ // Delete button of the selection bar. It comes before the Backspace handler below, which goes back one folder when
2250
+ // nothing is selected.
2251
+ if (
2252
+ deleteSelectionAction({
2253
+ key: event.key,
2254
+ altKey: event.altKey,
2255
+ shiftKey: event.shiftKey,
2256
+ defaultPrevented: event.defaultPrevented,
2257
+ allowSelecting,
2258
+ canDelete: libraryCapabilities.delete,
2259
+ selectionCount: allSelectedFiles.length,
2260
+ previewOpen: !!previewFile,
2261
+ designSystemModalOpen: $isModalOpen,
2262
+ inputFocused: !!isInputFocused(event),
2263
+ innerUiOpen:
2264
+ filterDropdownOpen ||
2265
+ sortDropdownOpen ||
2266
+ showModal ||
2267
+ showRenameDialog ||
2268
+ showNewFolderDialog ||
2269
+ showMoveDialog ||
2270
+ showDeleteConfirmation,
2271
+ }) === 'open-delete-dialog'
2272
+ ) {
2273
+ event.preventDefault();
2274
+ event.stopPropagation();
2275
+ openDeleteDialogForSelection();
2276
+ return;
2277
+ }
2278
+
2068
2279
  // Backspace key handler
2069
2280
  if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused(event) && !$isModalOpen) {
2070
2281
  event.preventDefault();
@@ -2507,10 +2718,12 @@
2507
2718
  const remoteFiles = await fetchUserUploadsFromApi(uploadConfig, {
2508
2719
  limit: WIDGETIC_UPLOADS_LIST_LIMIT,
2509
2720
  });
2510
- const merged = mergeRemoteUploadList(cached, remoteFiles, {
2511
- listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
2512
- apiHydrationSucceeded: true,
2513
- });
2721
+ const merged = await withoutPendingDeletes(
2722
+ mergeRemoteUploadList(cached, remoteFiles, {
2723
+ listLimit: WIDGETIC_UPLOADS_LIST_LIMIT,
2724
+ apiHydrationSucceeded: true,
2725
+ }),
2726
+ );
2514
2727
  await replacePersistedUploads(merged);
2515
2728
  const root = await createUserUploadsFileSystemRoot(merged, $t('library.defaultLabel'));
2516
2729
  data = root;
@@ -3362,12 +3575,7 @@ mainGridClass="app-main-grid"
3362
3575
  compact={isCompactLayout}
3363
3576
  on:send={sendToEditor}
3364
3577
  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
- }}
3578
+ on:delete={openDeleteDialogForSelection}
3371
3579
  on:rename={(e : any) => handleItemAction(new CustomEvent('action', { detail: { action: 'rename', item: e.detail.item } }))}
3372
3580
  />
3373
3581
  </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