@widgetic/file-browser 0.5.46 → 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 (104) hide show
  1. package/dist/actions/dragSelectedToFolder.js +104 -115
  2. package/dist/components/FolderTree.svelte.d.ts +2 -6
  3. package/dist/components/core/Dropzone.svelte +42 -2
  4. package/dist/components/core/FileBrowser.svelte +249 -32
  5. package/dist/components/core/FileUploader.svelte +134 -54
  6. package/dist/components/core/RecentFiles.svelte +74 -19
  7. package/dist/components/core/RecentFiles.svelte.d.ts +1 -0
  8. package/dist/components/core/SearchDropdown.svelte +6 -8
  9. package/dist/components/core/UploadPanel.svelte +7 -0
  10. package/dist/components/core/UploadPanel.svelte.d.ts +4 -0
  11. package/dist/components/core/UploadRow.svelte +9 -4
  12. package/dist/components/core/UploadRow.svelte.d.ts +2 -0
  13. package/dist/components/core/dropzoneClick.d.ts +28 -0
  14. package/dist/components/core/dropzoneClick.js +32 -0
  15. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  16. package/dist/components/ui/DropdownMenu.svelte +1 -1
  17. package/dist/config.js +4 -3
  18. package/dist/i18n/context.js +2 -2
  19. package/dist/i18n/errors.js +2 -1
  20. package/dist/i18n/messages.d.ts +15 -1
  21. package/dist/i18n/messages.js +17 -3
  22. package/dist/i18n/text.js +2 -2
  23. package/dist/mediaLibrary/capabilities.js +4 -3
  24. package/dist/mediaLibrary/context.js +4 -3
  25. package/dist/mediaLibrary/errors.js +46 -35
  26. package/dist/mediaLibrary/normalize.js +45 -42
  27. package/dist/mediaLibrary/paging.js +100 -45
  28. package/dist/mediaLibrary/resolve.js +214 -95
  29. package/dist/mediaLibrary/treeOps.js +40 -20
  30. package/dist/mediaLibrary/urls.js +12 -10
  31. package/dist/mediaLibrary/widgetic.js +140 -54
  32. package/dist/stores/dragStore.js +1 -1
  33. package/dist/stores/fileStore.d.ts +1 -1
  34. package/dist/stores/fileStore.js +44 -37
  35. package/dist/stores/folderCountStore.js +12 -11
  36. package/dist/stores/missingFilesStore.js +3 -3
  37. package/dist/stores/navigationStore.d.ts +1 -1
  38. package/dist/stores/navigationStore.js +217 -178
  39. package/dist/stores/persistentSelectStore.d.ts +1 -1
  40. package/dist/stores/persistentSelectStore.js +117 -94
  41. package/dist/stores/searchStore.js +1 -1
  42. package/dist/stores/uploadApiStore.d.ts +10 -0
  43. package/dist/stores/uploadApiStore.js +7 -7
  44. package/dist/stores/viewportStore.js +4 -4
  45. package/dist/types/index.js +0 -1
  46. package/dist/utils/apiConfig.js +9 -9
  47. package/dist/utils/brandKitLibraryTree.js +57 -42
  48. package/dist/utils/dateUtils.js +11 -9
  49. package/dist/utils/deleteSelectionAction.d.ts +26 -0
  50. package/dist/utils/deleteSelectionAction.js +23 -0
  51. package/dist/utils/dragToFolder/batchMoveResult.js +114 -54
  52. package/dist/utils/dragToFolder/folderDropTarget.js +23 -17
  53. package/dist/utils/dragToFolder/springStep.js +4 -3
  54. package/dist/utils/fileGoneProbe.js +65 -16
  55. package/dist/utils/fileKinds.js +14 -13
  56. package/dist/utils/fileNames.js +7 -7
  57. package/dist/utils/fileOperations.js +440 -333
  58. package/dist/utils/fileTypes.js +19 -14
  59. package/dist/utils/fileUtils.js +85 -31
  60. package/dist/utils/folderUtils.js +5 -4
  61. package/dist/utils/gridLayout.js +7 -7
  62. package/dist/utils/imagePreviewCache.js +26 -15
  63. package/dist/utils/imagePreviewFrame.js +13 -13
  64. package/dist/utils/imagePreviewVisualState.js +5 -4
  65. package/dist/utils/imageTransform.js +27 -14
  66. package/dist/utils/itemMenuCapabilities.js +7 -7
  67. package/dist/utils/libraryTree.js +55 -39
  68. package/dist/utils/pendingUploadDeletes.d.ts +102 -0
  69. package/dist/utils/pendingUploadDeletes.js +400 -0
  70. package/dist/utils/previewKeys.js +1 -1
  71. package/dist/utils/previewListNavigation.js +13 -11
  72. package/dist/utils/previewNavigation.js +10 -7
  73. package/dist/utils/recentFiles.js +16 -6
  74. package/dist/utils/recentFilesLimit.js +2 -2
  75. package/dist/utils/removeItems.d.ts +30 -0
  76. package/dist/utils/removeItems.js +124 -0
  77. package/dist/utils/resolveFileUrl.js +6 -6
  78. package/dist/utils/safeText.js +14 -12
  79. package/dist/utils/searchDropdownPhase.d.ts +14 -3
  80. package/dist/utils/searchDropdownPhase.js +13 -9
  81. package/dist/utils/searchItems.js +30 -14
  82. package/dist/utils/searchNavigation.js +5 -5
  83. package/dist/utils/uploadAuth.d.ts +24 -0
  84. package/dist/utils/uploadAuth.js +140 -0
  85. package/dist/utils/uploadDisplayProgress.js +1 -1
  86. package/dist/utils/uploadLimits.d.ts +76 -0
  87. package/dist/utils/uploadLimits.js +242 -0
  88. package/dist/utils/uploadListReconcile.js +24 -11
  89. package/dist/utils/uploadPanelDismiss.d.ts +13 -0
  90. package/dist/utils/uploadPanelDismiss.js +11 -0
  91. package/dist/utils/uploadPanelProgress.js +4 -4
  92. package/dist/utils/uploadProgressMath.js +13 -11
  93. package/dist/utils/uploadRefusals.d.ts +42 -0
  94. package/dist/utils/uploadRefusals.js +86 -0
  95. package/dist/utils/uploadResponseMapping.js +9 -8
  96. package/dist/utils/uploadUiHelpers.js +17 -17
  97. package/dist/utils/userUploadsStorage.js +270 -133
  98. package/dist/utils/videoFrame.d.ts +23 -0
  99. package/dist/utils/videoFrame.js +26 -0
  100. package/dist/utils/widgeticDelete.js +103 -28
  101. package/dist/utils/widgeticTusUpload.js +189 -105
  102. package/dist/utils/widgeticUpload.js +133 -59
  103. package/dist/utils/xhrMultipartUpload.js +164 -116
  104. package/package.json +3 -3
@@ -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';
@@ -41,6 +43,7 @@
41
43
  import { buildActiveRowStatusText, formatUploadPercent, type UploadPhase, updateThroughputEstimateState } from '../../utils/uploadUiHelpers';
42
44
  import { monotonicDisplayProgress } from '../../utils/uploadDisplayProgress';
43
45
  import { monotonicPanelProgress, nextUploadPanelPeak } from '../../utils/uploadPanelProgress';
46
+ import { shouldDismissUploadPanel } from '../../utils/uploadPanelDismiss';
44
47
 
45
48
  // The host's media library, when the File Browser was given one. It then stores the files, instead of the
46
49
  // Widgetic upload settings.
@@ -64,6 +67,8 @@
64
67
 
65
68
  // Local variables
66
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;
67
72
  let fileInput: HTMLInputElement;
68
73
  let uploaderRootEl: HTMLDivElement;
69
74
  // show logs
@@ -91,6 +96,8 @@
91
96
  status: 'uploading' | 'complete' | 'failed';
92
97
  previewUrl: string;
93
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;
94
101
  /** Estimated seconds left; internal (shown via buildActiveRowStatusText) */
95
102
  timeRemainingSeconds?: number;
96
103
  throughputBps?: number;
@@ -107,10 +114,20 @@
107
114
 
108
115
  // Reactive variables
109
116
  $: allowedKinds = allowedKindsOf(filter === 'all' ? allowedTypes : FILE_TYPES[filter as Exclude<FileFilterType, 'all'>]);
110
- $: tooltipTypesText = formatAllowedTypesForDisplay(filter, $t);
111
- $: acceptTypes = filter === 'all'
112
- ? Object.values(FILE_TYPES).flat().join(',')
113
- : 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);
114
131
  // The kinds of file the uploader takes, as words in the visitor's language: "image, video", "any", "document".
115
132
  $: allowedTypesDisplayText = kindsText(filter, allowedKinds, $t);
116
133
  // With the "all" filter every kind of file is taken, and the sentences of the dropzone do not name a kind ("Upload files").
@@ -191,6 +208,7 @@
191
208
  status: item.status,
192
209
  statusText: statusTextForItem(item),
193
210
  errorMessage: item.errorMessage,
211
+ canRetry: item.canRetry !== false,
194
212
  })
195
213
  );
196
214
 
@@ -241,14 +259,17 @@
241
259
  );
242
260
 
243
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;
244
265
  $: panelFooterAction =
245
- failedUploadCount > 0 && uploadingCount === 0 && completedUploadCount < totalUploadCount;
266
+ retryableFailedCount > 0 && uploadingCount === 0 && completedUploadCount < totalUploadCount;
246
267
 
247
268
  $: panelFooterText = (() => {
248
269
  if (totalUploadCount === 0) return $t('upload.uploading');
249
270
  if (panelFooterAction) return $t('upload.retryFailed');
250
271
  if (totalUploadCount === 1 && uploadingCount === 1) return $t('upload.uploading');
251
- if (totalUploadCount === 1 && failedUploadCount === 1) return $t('upload.retry');
272
+ if (totalUploadCount === 1 && failedUploadCount === 1) return retryableFailedCount === 1 ? $t('upload.retry') : $t('upload.failed');
252
273
  if (totalUploadCount === 1 && completedUploadCount === 1) return $t('upload.complete');
253
274
  if (uploadingCount > 0 && failedUploadCount > 0) {
254
275
  return joinMeta(
@@ -324,7 +345,9 @@
324
345
 
325
346
  isDraggingFolder = false;
326
347
  const extension = getMimeTypeExtension(item.type);
327
- 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);
328
351
  return isInvalid;
329
352
  }
330
353
  return false;
@@ -364,24 +387,9 @@
364
387
  }
365
388
 
366
389
  isDraggingFolder = false;
367
- const hasInvalidFiles = Array.from(files).some(file => {
368
- const extension = file.name.split('.').pop()?.toLowerCase();
369
- const fileExtension = extension ? '.' + extension : '';
370
- return !acceptTypes.includes(fileExtension);
371
- });
372
-
373
- if (hasInvalidFiles) {
374
- isDraggingFolder = false;
375
- dragInvalid = true;
376
- setTimeout(() => {
377
- showToast('error', $t('upload.invalidType', { types: allowedTypesDisplayText }));
378
- return;
379
- }, 0);
380
- return;
381
- }
382
-
383
390
  dragInvalid = false;
384
- 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.
385
393
  handleFiles(files);
386
394
  }
387
395
  }
@@ -614,7 +622,7 @@
614
622
  formData.append('path', path);
615
623
  formData.append('folderId', currentFolderId);
616
624
 
617
- let response: { success: boolean; file?: any; error?: string };
625
+ let response: { success: boolean; file?: any; error?: string; status?: number };
618
626
 
619
627
  if (library) {
620
628
  // The host's media library stores the file. It reports progress as a number from 0 to 100.
@@ -838,6 +846,9 @@
838
846
  // Close progress overlay so the file grid is visible again (black dim was the upload overlay)
839
847
  scheduleUploadDrawerDismiss();
840
848
  } else {
849
+ // What the row says, and whether trying again can change anything
850
+ const failure = describeFailedUpload(response, normalizedFile);
851
+
841
852
  // Update the upload item to failed
842
853
  uploadItems = uploadItems.map((item) =>
843
854
  item.id === uploadId
@@ -846,7 +857,8 @@
846
857
  displayProgress: 0,
847
858
  status: 'failed',
848
859
  uploadPhase: undefined,
849
- errorMessage: response.error || $t('libraryError.uploadFailed'),
860
+ errorMessage: failure.errorMessage,
861
+ canRetry: failure.canRetry,
850
862
  timeRemainingSeconds: undefined,
851
863
  }
852
864
  : item,
@@ -905,26 +917,45 @@
905
917
  * Handles the upload of multiple files
906
918
  * @param files The files to upload
907
919
  */
908
- async function handleFiles(files: FileList) {
909
- // open the uploads overlay with the drawer open
910
- isUploadsModalOpen = true;
911
-
912
- // 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)
913
922
  uploading = true;
914
-
923
+
915
924
  // prepare an array to store the files that were skipped
916
925
  let skippedFiles: string[] = [];
917
926
 
918
927
  // try to upload the files
919
928
  try {
920
- // Process each file
921
- for (const file of files) {
922
- const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
923
- if (!acceptTypes.includes(fileExtension)) {
924
- console.error(`File type not allowed: ${file.name}`);
925
- dispatch('error', { message: `File type not allowed: ${file.name}. Please use ${kindsText(filter, allowedKinds, translateEnglish)} files only.` });
926
- 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;
927
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);
928
959
 
929
960
  if (restrictDuplicateNames && isDuplicate(file.name, fileExtension)) {
930
961
  if(showLogs) console.log(`Skipping duplicate file: ${file.name}`);
@@ -947,6 +978,55 @@
947
978
  } catch (error) {
948
979
  console.error('Upload failed:', error);
949
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);
950
1030
  }
951
1031
  }
952
1032
 
@@ -1072,7 +1152,7 @@
1072
1152
 
1073
1153
  // Function to retry all failed uploads
1074
1154
  function retryAllFailedUploads() {
1075
- const failedUploads = uploadItems.filter(item => item.status === 'failed');
1155
+ const failedUploads = uploadItems.filter(item => item.status === 'failed' && item.canRetry !== false);
1076
1156
  failedUploads.forEach(item => handleRetryUpload(item.id));
1077
1157
  }
1078
1158
 
@@ -1102,29 +1182,28 @@
1102
1182
  }
1103
1183
  }
1104
1184
 
1105
- /** After uploads finish, close the dim overlay so the file grid is usable again. */
1185
+ /**
1186
+ * After uploads finish, close the dim overlay so the file grid is usable again.
1187
+ * Only when every file went through: a batch with a failed file keeps the panel open, so the person sees which ones failed
1188
+ * and can ask for another try (the summary and footer retry buttons, or the retry of a single file).
1189
+ */
1106
1190
  function scheduleUploadDrawerDismiss() {
1107
- const allDone = uploadItems.every(
1108
- (item) => item.status === 'complete' || item.status === 'failed',
1109
- );
1110
- if (!allDone) return;
1191
+ if (!shouldDismissUploadPanel(uploadItems)) return;
1111
1192
  setTimeout(() => {
1112
- const stillDone = uploadItems.every(
1113
- (item) => item.status === 'complete' || item.status === 'failed',
1114
- );
1115
- if (!stillDone) return;
1193
+ if (!shouldDismissUploadPanel(uploadItems)) return;
1116
1194
  isUploadsModalOpen = false;
1117
1195
  isUploadsDrawerCollapsed = true;
1118
- uploadItems = uploadItems.filter((item) => item.status === 'failed');
1119
- if (uploadItems.length === 0) {
1120
- dispatch('uploadsCleared');
1121
- }
1196
+ uploadItems = [];
1197
+ dispatch('uploadsCleared');
1122
1198
  }, 600);
1123
1199
  }
1124
1200
 
1125
1201
  onMount(() => {
1126
1202
  // if(showLogs) console.log('FileUploader mounted');
1127
1203
 
1204
+ // Learn what the Widgetic API takes (in the background: the uploader works while it is read).
1205
+ void refreshUploadLimits();
1206
+
1128
1207
  // Get parent element for portal
1129
1208
  if (!portalTarget && uploaderRootEl && uploaderRootEl.parentElement) {
1130
1209
  portalTarget = uploaderRootEl.parentElement;
@@ -1170,6 +1249,7 @@
1170
1249
  footerText={panelFooterText}
1171
1250
  footerDestructive={panelFooterDestructive}
1172
1251
  footerAction={panelFooterAction}
1252
+ summaryCanRetry={retryableFailedCount > 0}
1173
1253
  expanded={!isUploadsDrawerCollapsed}
1174
1254
  onToggleExpand={toggleDrawerCollapse}
1175
1255
  onSummaryCancel={() => {
@@ -1193,7 +1273,7 @@
1193
1273
  onchange={handleFileSelect}
1194
1274
  multiple
1195
1275
  class="upload-input hidden"
1196
- accept={acceptTypes}
1276
+ accept={inputAcceptTypes}
1197
1277
  />
1198
1278
 
1199
1279
  <Dropzone
@@ -11,11 +11,13 @@
11
11
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
12
12
  import { FileIcon, SelectedBadge } from '../ui';
13
13
  import { persistentSelectStore } from '../../stores/persistentSelectStore';
14
+ import { isMobileStore } from '../../stores/viewportStore';
14
15
  import { type FileFilterType } from '../../utils/fileTypes';
15
16
  import { ThumbHashImage } from '@widgetic/design-system/components';
16
- import { IconExclamationCircle, IconPlayerPlayFilled } from '@widgetic/design-system/icons';
17
+ import { IconExclamationCircle, IconPlayerPlayFilled, IconTrash } from '@widgetic/design-system/icons';
17
18
  import { recentFilesLimitForWidth } from '../../utils/recentFilesLimit';
18
19
  import { recentGridColumnsForWidth } from '../../utils/gridLayout';
20
+ import { drawsVideoFrame, videoFrameSrc } from '../../utils/videoFrame';
19
21
 
20
22
  let className = '';
21
23
  export { className as class };
@@ -72,8 +74,8 @@
72
74
  recentFiles.forEach((file) => {
73
75
  try {
74
76
  loadingStates.set(file.id, false);
75
- errorStates.set(file.id, false);
76
- file.isMissing = false;
77
+ // A file the list already knows to be gone stays gone: the card must not forget it and draw a picture that cannot load.
78
+ errorStates.set(file.id, Boolean(file.isMissing));
77
79
  } catch (error) {
78
80
  console.error('Error checking file:', file.name, error);
79
81
  file.isMissing = true;
@@ -95,6 +97,18 @@
95
97
  file.isMissing = true;
96
98
  }
97
99
 
100
+ /**
101
+ * Videos whose first frame could not be read. This is not "the file is missing": the same file may be a codec this
102
+ * browser does not play, and the preview or the download still work. The card shows the icon of the file instead.
103
+ */
104
+ let videoFrameFailedIds = new Set<string>();
105
+
106
+ function handleVideoFrameError(file: FileSystemItem) {
107
+ if (videoFrameFailedIds.has(file.id)) return;
108
+ console.warn(`[RecentFiles] No first frame for the video ${file.name}; showing its icon instead`);
109
+ videoFrameFailedIds = new Set(videoFrameFailedIds).add(file.id);
110
+ }
111
+
98
112
  function shouldShowCoverImage(file: FileSystemItem): boolean {
99
113
  if (isLoading(file) || file.isMissing || errorStates.get(file.id)) return false;
100
114
  const fileType = getFileTypeOf(file);
@@ -224,23 +238,48 @@
224
238
  {#if isLoading(file)}
225
239
  <div class="size-full bg-muted" aria-hidden="true"></div>
226
240
  {:else if shouldShowCoverImage(file)}
227
- {#if file.hash && file.url}
228
- <div class="absolute inset-0">
229
- <ThumbHashImage
230
- src={getCoverSrc(file)}
231
- alt={file.name}
232
- thumbhash={file.hash}
233
- class_="size-full object-cover"
234
- />
235
- </div>
241
+ {#if isVideoFile(file) && drawsVideoFrame(file)}
242
+ {#if videoFrameFailedIds.has(file.id)}
243
+ <!-- The browser could not read a frame (a codec it does not play): the icon of the file, not a broken picture. -->
244
+ <FileIcon {file} size="lg" />
245
+ {:else}
246
+ <!-- No thumbnail came with the video: its first frame is the cover (only the metadata of the file is loaded). -->
247
+ <!-- svelte-ignore a11y_media_has_caption -->
248
+ <video
249
+ src={videoFrameSrc(file.url ?? '')}
250
+ class="pointer-events-none size-full object-cover opacity-0 transition-opacity duration-fast data-[ready=true]:opacity-100"
251
+ muted
252
+ playsinline
253
+ preload="metadata"
254
+ disablepictureinpicture
255
+ disableremoteplayback
256
+ tabindex="-1"
257
+ aria-hidden="true"
258
+ onloadeddata={(event) => {
259
+ event.currentTarget.dataset.ready = 'true';
260
+ }}
261
+ onerror={() => handleVideoFrameError(file)}
262
+ ></video>
263
+ {/if}
264
+ {:else}
265
+ {#if file.hash && file.url}
266
+ <div class="absolute inset-0">
267
+ <ThumbHashImage
268
+ src={getCoverSrc(file)}
269
+ alt={file.name}
270
+ thumbhash={file.hash}
271
+ class_="size-full object-cover"
272
+ />
273
+ </div>
274
+ {/if}
275
+ <img
276
+ src={getCoverSrc(file)}
277
+ alt=""
278
+ class="size-full object-cover"
279
+ onerror={() => handleImageError(file)}
280
+ />
236
281
  {/if}
237
- <img
238
- src={getCoverSrc(file)}
239
- alt=""
240
- class="size-full object-cover"
241
- onerror={() => handleImageError(file)}
242
- />
243
- {#if isVideoFile(file) && !file.isMissing && !errorStates.get(file.id)}
282
+ {#if isVideoFile(file) && !file.isMissing && !errorStates.get(file.id) && !videoFrameFailedIds.has(file.id)}
244
283
  <span class="pointer-events-none absolute inset-0 flex items-center justify-center">
245
284
  <span
246
285
  class="flex size-12 items-center justify-center rounded-full bg-foreground/60 text-background"
@@ -274,6 +313,22 @@
274
313
  {getFormattedDate(file.modified || new Date(), $t)}
275
314
  </p>
276
315
  </div>
316
+ {#if file.isMissing || errorStates.get(file.id)}
317
+ <!-- The error tile of the Files list: a missing file can be deleted from here, as it can there (FileItem). -->
318
+ <button
319
+ type="button"
320
+ class="shrink-0 text-destructive opacity-0 transition-opacity duration-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background group-hover:opacity-100 group-focus-within:opacity-100 {$isMobileStore
321
+ ? 'opacity-100!'
322
+ : ''}"
323
+ onclick={(e) => {
324
+ e.stopPropagation();
325
+ dispatch('delete', { item: file });
326
+ }}
327
+ aria-label={$t('item.deleteMissing')}
328
+ >
329
+ <IconTrash class="size-5 stroke-[1.6]" />
330
+ </button>
331
+ {/if}
277
332
  {#if allowSelecting && fileSelected}
278
333
  <!-- svelte-ignore a11y-click-events-have-key-events -->
279
334
  <!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -28,6 +28,7 @@ declare const RecentFiles: $$__sveltets_2_IsomorphicComponent<{
28
28
  /** Cap from FileBrowser so the strip matches `getRecentFiles()`. */ visibleLimit?: number | undefined;
29
29
  /** Measured width of the file browser panel (not the viewport). */ containerWidth?: number;
30
30
  }, {
31
+ delete: CustomEvent<any>;
31
32
  fileClick: CustomEvent<any>;
32
33
  select: CustomEvent<any>;
33
34
  } & {
@@ -31,6 +31,7 @@
31
31
  import {
32
32
  resolveSearchDropdownPhase,
33
33
  shouldShowSearchEmptyState,
34
+ shouldShowSearchPanel,
34
35
  shouldShowSearchResultsList
35
36
  } from '../../utils/searchDropdownPhase';
36
37
  import { useI18n } from '../../i18n';
@@ -95,7 +96,8 @@
95
96
  });
96
97
  $: showSearchEmpty = shouldShowSearchEmptyState(searchDropdownPhase);
97
98
  $: showResultsList = shouldShowSearchResultsList(searchDropdownPhase, debouncedResults.length);
98
- $: showSearchLoadingRow = searchDropdownPhase === 'loading' && debouncedResults.length === 0;
99
+ /** The card under the field: drawn for a list or for "nothing found", never as a loading state (see searchDropdownPhase.ts). */
100
+ $: showSearchPanel = shouldShowSearchPanel(searchDropdownPhase);
99
101
 
100
102
  function searchTiming() {
101
103
  if (typeof window === 'undefined') return { debounceMs: searchDebounceMs ?? 150, slowMs: 0 };
@@ -364,7 +366,7 @@
364
366
  });
365
367
 
366
368
  $: ariaActivedescendant =
367
- showPanel && activeIndex >= 0 ? `file-browser-search-opt-${uid}-${activeIndex}` : undefined;
369
+ showSearchPanel && activeIndex >= 0 ? `file-browser-search-opt-${uid}-${activeIndex}` : undefined;
368
370
 
369
371
  /** The field is the textbox of a combobox whose listbox is the panel under it (the Search Field takes these as they are). */
370
372
  $: comboboxAttributes = {
@@ -372,7 +374,7 @@
372
374
  role: 'combobox',
373
375
  'aria-haspopup': 'listbox',
374
376
  'aria-autocomplete': 'list',
375
- 'aria-expanded': showPanel,
377
+ 'aria-expanded': showSearchPanel,
376
378
  'aria-controls': listboxId,
377
379
  'aria-activedescendant': ariaActivedescendant,
378
380
  autocomplete: 'off',
@@ -396,7 +398,7 @@
396
398
  onClear={handleClear}
397
399
  />
398
400
 
399
- {#if showPanel}
401
+ {#if showSearchPanel}
400
402
  <div
401
403
  id={listboxId}
402
404
  role="listbox"
@@ -458,10 +460,6 @@
458
460
  {/each}
459
461
  </div>
460
462
  </WScrollArea>
461
- {:else if showSearchLoadingRow}
462
- <div class="search-dropdown-loading flex min-h-[200px] flex-col items-center justify-center px-6 py-8">
463
- <p class="text-caption text-muted-foreground">{$t('preview.loading')}</p>
464
- </div>
465
463
  {:else if showSearchEmpty}
466
464
  <div class="search-dropdown-empty flex min-h-[200px] flex-col items-center justify-center px-6 py-8">
467
465
  <EmptyState message={$t('searchModal.empty')} />
@@ -17,6 +17,8 @@
17
17
  status: UploadRowState;
18
18
  statusText: string;
19
19
  errorMessage?: string;
20
+ /** False when trying again cannot help (the API refuses the file's type or size): its row has no retry button. Default: true. */
21
+ canRetry?: boolean;
20
22
  };
21
23
 
22
24
  interface Props {
@@ -39,6 +41,8 @@
39
41
  onItemRetry?: (id: string) => void;
40
42
  onFooterAction?: () => void;
41
43
  footerAction?: boolean;
44
+ /** False when no failed file can be retried: the summary row has no retry button. Default: true. */
45
+ summaryCanRetry?: boolean;
42
46
  showClearCompleted?: boolean;
43
47
  onClearCompleted?: () => void;
44
48
  }
@@ -63,6 +67,7 @@
63
67
  onItemRetry,
64
68
  onFooterAction,
65
69
  footerAction = false,
70
+ summaryCanRetry = true,
66
71
  showClearCompleted = false,
67
72
  onClearCompleted
68
73
  }: Props = $props();
@@ -89,6 +94,7 @@
89
94
  batchCount={items.length}
90
95
  onCancel={onSummaryCancel}
91
96
  onRetry={onSummaryRetry}
97
+ canRetry={summaryCanRetry}
92
98
  />
93
99
  </div>
94
100
  {#if items.length > 1}
@@ -165,6 +171,7 @@
165
171
  progressIndeterminate={item.status === 'uploading' ? item.progressIndeterminate : false}
166
172
  onCancel={() => onItemCancel?.(item.id)}
167
173
  onRetry={() => onItemRetry?.(item.id)}
174
+ canRetry={item.canRetry !== false}
168
175
  />
169
176
  </div>
170
177
  {/each}
@@ -14,6 +14,8 @@ export type UploadPanelItem = {
14
14
  status: UploadRowState;
15
15
  statusText: string;
16
16
  errorMessage?: string;
17
+ /** False when trying again cannot help (the API refuses the file's type or size): its row has no retry button. Default: true. */
18
+ canRetry?: boolean;
17
19
  };
18
20
  interface Props {
19
21
  items: UploadPanelItem[];
@@ -35,6 +37,8 @@ interface Props {
35
37
  onItemRetry?: (id: string) => void;
36
38
  onFooterAction?: () => void;
37
39
  footerAction?: boolean;
40
+ /** False when no failed file can be retried: the summary row has no retry button. Default: true. */
41
+ summaryCanRetry?: boolean;
38
42
  showClearCompleted?: boolean;
39
43
  onClearCompleted?: () => void;
40
44
  }
@@ -24,6 +24,8 @@
24
24
  progressIndeterminate?: boolean;
25
25
  onCancel?: () => void;
26
26
  onRetry?: () => void;
27
+ /** False when a failed upload cannot be fixed by trying again (the file's type or size is refused): no retry button. */
28
+ canRetry?: boolean;
27
29
  }
28
30
 
29
31
  let {
@@ -36,7 +38,8 @@
36
38
  progressValue,
37
39
  progressIndeterminate = false,
38
40
  onCancel,
39
- onRetry
41
+ onRetry,
42
+ canRetry = true
40
43
  }: Props = $props();
41
44
 
42
45
  const { t } = useI18n();
@@ -78,9 +81,11 @@
78
81
  <IconX class="size-4 stroke-2" aria-hidden="true" />
79
82
  </IconButton>
80
83
  {:else if state === 'failed'}
81
- <IconButton variant="ghost" size="default" label={$t('upload.retry')} onclick={() => onRetry?.()}>
82
- <IconRefresh class="size-4 stroke-2" aria-hidden="true" />
83
- </IconButton>
84
+ {#if canRetry}
85
+ <IconButton variant="ghost" size="default" label={$t('upload.retry')} onclick={() => onRetry?.()}>
86
+ <IconRefresh class="size-4 stroke-2" aria-hidden="true" />
87
+ </IconButton>
88
+ {/if}
84
89
  <IconButton variant="ghost" size="default" label={$t('upload.removeFile')} onclick={() => onCancel?.()}>
85
90
  <IconX class="size-4 stroke-2" aria-hidden="true" />
86
91
  </IconButton>
@@ -18,6 +18,8 @@ interface Props {
18
18
  progressIndeterminate?: boolean;
19
19
  onCancel?: () => void;
20
20
  onRetry?: () => void;
21
+ /** False when a failed upload cannot be fixed by trying again (the file's type or size is refused): no retry button. */
22
+ canRetry?: boolean;
21
23
  }
22
24
  declare const UploadRow: import("svelte").Component<Props, {}, "">;
23
25
  type UploadRow = ReturnType<typeof UploadRow>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Which clicks inside the drop zone open the file chooser.
3
+ *
4
+ * The whole zone is a target, not only the "Upload files" button: a click on the empty part, the dashed outline or the
5
+ * hint text opens the chooser as well. A click that lands on a control inside the zone (the button itself, the "?" help
6
+ * button) belongs to that control and is left alone, otherwise the chooser would open twice, or open from the help icon.
7
+ */
8
+ type ClickTarget = {
9
+ closest?: (selector: string) => unknown;
10
+ } | null | undefined;
11
+ type ClickZone = {
12
+ contains: (node: never) => boolean;
13
+ };
14
+ /** Whether the click landed on a control that sits inside the zone (not on the zone itself). */
15
+ export declare function isClickOnControlInsideZone(target: ClickTarget, zone: ClickZone): boolean;
16
+ /**
17
+ * The zone is only a click target while it is waiting for files: not while a file is dragged over it (the zone shows
18
+ * whether the drop is allowed) and not while the first upload is being set up.
19
+ */
20
+ export declare function canBrowseFromZone(state: string, showInitialUploading: boolean): boolean;
21
+ /** Whether this click opens the file chooser. */
22
+ export declare function shouldBrowseFromZoneClick(input: {
23
+ target: ClickTarget;
24
+ zone: ClickZone;
25
+ state: string;
26
+ showInitialUploading: boolean;
27
+ }): boolean;
28
+ export {};