@widgetic/file-browser 0.5.24 → 0.5.25

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 (97) hide show
  1. package/README.md +225 -0
  2. package/dist/components/FolderTree.svelte +4 -1
  3. package/dist/components/FolderTree.svelte.d.ts +2 -6
  4. package/dist/components/core/FileBrowser.svelte +494 -120
  5. package/dist/components/core/FileBrowser.svelte.d.ts +25 -1
  6. package/dist/components/core/FileUploader.svelte +114 -45
  7. package/dist/components/core/Header.svelte +12 -1
  8. package/dist/components/core/Header.svelte.d.ts +1 -0
  9. package/dist/components/core/RecentFiles.svelte +34 -26
  10. package/dist/components/core/UploadStatus.svelte +8 -5
  11. package/dist/components/core/UploadStatusList.svelte +13 -21
  12. package/dist/components/items/FileItem.svelte +19 -10
  13. package/dist/components/items/FolderItem.svelte +6 -3
  14. package/dist/components/modals/MoveDialog.svelte +43 -32
  15. package/dist/components/modals/NewFolderButton.svelte +5 -2
  16. package/dist/components/modals/SearchModal.svelte +16 -21
  17. package/dist/components/modals/SearchModal.svelte.d.ts +1 -1
  18. package/dist/components/modals/SelectedFilesModal.svelte +14 -9
  19. package/dist/components/modals/SelectedFilesModal.svelte.d.ts +1 -1
  20. package/dist/components/previews/AudioPlayer.svelte +5 -2
  21. package/dist/components/previews/ErrorPreview.svelte +7 -4
  22. package/dist/components/previews/ErrorPreview.svelte.d.ts +1 -1
  23. package/dist/components/previews/FilePreview.svelte +17 -7
  24. package/dist/components/previews/FontPreview.svelte +18 -9
  25. package/dist/components/previews/FontPreview.svelte.d.ts +1 -1
  26. package/dist/components/previews/TextPreview.svelte +12 -5
  27. package/dist/components/previews/VideoPlayer.svelte +8 -5
  28. package/dist/components/ui/ControlToolbar.svelte +45 -23
  29. package/dist/components/ui/ControlToolbar.svelte.d.ts +1 -1
  30. package/dist/components/ui/DragSelect.svelte +2 -2
  31. package/dist/components/ui/DropdownMenu.svelte +35 -14
  32. package/dist/components/ui/FileIcon.svelte +8 -5
  33. package/dist/components/ui/FileIcon.svelte.d.ts +1 -0
  34. package/dist/components/ui/FileMetadata.svelte +12 -15
  35. package/dist/components/ui/SearchResults.svelte +4 -1
  36. package/dist/i18n/context.d.ts +38 -0
  37. package/dist/i18n/context.js +70 -0
  38. package/dist/i18n/errors.d.ts +11 -0
  39. package/dist/i18n/errors.js +19 -0
  40. package/dist/i18n/index.d.ts +11 -0
  41. package/dist/i18n/index.js +18 -0
  42. package/dist/i18n/messages.d.ts +277 -0
  43. package/dist/i18n/messages.js +290 -0
  44. package/dist/i18n/text.d.ts +19 -0
  45. package/dist/i18n/text.js +35 -0
  46. package/dist/i18n/translator.d.ts +75 -0
  47. package/dist/i18n/translator.js +317 -0
  48. package/dist/index.d.ts +3 -0
  49. package/dist/index.js +4 -0
  50. package/dist/mediaLibrary/capabilities.d.ts +22 -0
  51. package/dist/mediaLibrary/capabilities.js +42 -0
  52. package/dist/mediaLibrary/context.d.ts +17 -0
  53. package/dist/mediaLibrary/context.js +16 -0
  54. package/dist/mediaLibrary/errors.d.ts +42 -0
  55. package/dist/mediaLibrary/errors.js +114 -0
  56. package/dist/mediaLibrary/index.d.ts +10 -0
  57. package/dist/mediaLibrary/index.js +9 -0
  58. package/dist/mediaLibrary/normalize.d.ts +39 -0
  59. package/dist/mediaLibrary/normalize.js +139 -0
  60. package/dist/mediaLibrary/paging.d.ts +37 -0
  61. package/dist/mediaLibrary/paging.js +62 -0
  62. package/dist/mediaLibrary/resolve.d.ts +39 -0
  63. package/dist/mediaLibrary/resolve.js +137 -0
  64. package/dist/mediaLibrary/treeOps.d.ts +24 -0
  65. package/dist/mediaLibrary/treeOps.js +67 -0
  66. package/dist/mediaLibrary/types.d.ts +126 -0
  67. package/dist/mediaLibrary/types.js +11 -0
  68. package/dist/mediaLibrary/urls.d.ts +30 -0
  69. package/dist/mediaLibrary/urls.js +59 -0
  70. package/dist/mediaLibrary/widgetic.d.ts +39 -0
  71. package/dist/mediaLibrary/widgetic.js +89 -0
  72. package/dist/stores/fileStore.d.ts +2 -2
  73. package/dist/stores/folderCountStore.js +2 -2
  74. package/dist/stores/navigationStore.d.ts +1 -1
  75. package/dist/stores/persistentSelectStore.d.ts +11 -1
  76. package/dist/stores/persistentSelectStore.js +26 -0
  77. package/dist/utils/dateUtils.d.ts +11 -2
  78. package/dist/utils/dateUtils.js +20 -15
  79. package/dist/utils/fileKinds.d.ts +44 -0
  80. package/dist/utils/fileKinds.js +96 -0
  81. package/dist/utils/fileNames.d.ts +7 -0
  82. package/dist/utils/fileNames.js +19 -0
  83. package/dist/utils/fileOperations.js +2 -11
  84. package/dist/utils/fileTypes.d.ts +11 -2
  85. package/dist/utils/fileTypes.js +26 -14
  86. package/dist/utils/fileUtils.d.ts +8 -1
  87. package/dist/utils/fileUtils.js +22 -7
  88. package/dist/utils/folderUtils.js +3 -2
  89. package/dist/utils/safeText.d.ts +29 -0
  90. package/dist/utils/safeText.js +66 -0
  91. package/dist/utils/userUploadsStorage.d.ts +4 -1
  92. package/dist/utils/userUploadsStorage.js +5 -2
  93. package/dist/utils/widgeticTusUpload.d.ts +10 -0
  94. package/dist/utils/widgeticTusUpload.js +61 -3
  95. package/dist/utils/widgeticUpload.d.ts +3 -0
  96. package/dist/utils/widgeticUpload.js +7 -2
  97. package/package.json +4 -2
@@ -43,10 +43,11 @@
43
43
  }
44
44
 
45
45
  // UTILS IMPORTS
46
- import { getFileType, getFileIcon } from '../../utils/fileUtils';
46
+ import { getFileIcon } from '../../utils/fileUtils';
47
+ import { getFileTypeOf } from '../../utils/fileKinds';
47
48
  import { getFolderIcon } from '../../utils/folderUtils';
48
49
  import { type FileFilterType, FILTER_OPTIONS, getAllowedFileTypes, FILE_TYPES, formatFileTypesForDisplay } from '../../utils/fileTypes';
49
- import { getPathNamesFromIds, deleteItem, renameItem, moveItem } from '../../utils/fileOperations';
50
+ import { getPathNamesFromIds, deleteItem, renameItem, moveItem, findItemById } from '../../utils/fileOperations';
50
51
  import { getFileBrowserUploadConfig, setFileBrowserUploadConfig } from '../../stores/uploadApiStore';
51
52
  import {
52
53
  loadUserUploads,
@@ -90,6 +91,21 @@
90
91
  import { persistentSelectStore, validSelections } from '../../stores/persistentSelectStore';
91
92
  import { isModalOpen, modalState } from '@widgetic/design-system/components/modals/modalStore';
92
93
 
94
+ // MEDIA LIBRARY IMPORTS (the host's own storage; see the `mediaLibrary` prop)
95
+ import { provideMediaLibraryContext, type MediaLibraryContext } from '../../mediaLibrary/context';
96
+ import { LEGACY_CAPABILITIES, NO_CAPABILITIES } from '../../mediaLibrary/capabilities';
97
+ import { MediaLibraryError, isCancellation, toMediaLibraryError } from '../../mediaLibrary/errors';
98
+ import { loadLibraryPages } from '../../mediaLibrary/paging';
99
+ import { resolveMediaLibrary, type ResolvedMediaLibrary } from '../../mediaLibrary/resolve';
100
+ import { appendNewFiles, createLibraryRoot, removeFiles, replaceFile, upsertFile } from '../../mediaLibrary/treeOps';
101
+ import type { MediaLibraryErrorCode, MediaLibraryProvider } from '../../mediaLibrary/types';
102
+ import { getRenamedFileName } from '../../utils/fileNames';
103
+
104
+ // I18N IMPORTS (the words of the File Browser, in the page's language)
105
+ import { provideI18n } from '../../i18n/context';
106
+ import { messageForVisitor } from '../../i18n/errors';
107
+ import type { MessageOverrides } from '../../i18n/translator';
108
+
93
109
  // logs flags
94
110
  let showLogs = false;
95
111
  let showRecentFilesLogs = false;
@@ -100,6 +116,21 @@
100
116
  */
101
117
  // data props
102
118
  export let data: any = null;
119
+ /**
120
+ * The host's own media library (a `MediaLibraryProvider`): plain functions the File Browser calls to list, upload,
121
+ * rename and delete the host's files. When given, the File Browser shows that one flat library instead of the
122
+ * Widgetic uploads or the demo content, and stores nothing about it on this device (no local cache, no saved
123
+ * tree, no saved selection unless `persistSelection` says so).
124
+ *
125
+ * Read once, when the File Browser is created: to show another library, create a new File Browser.
126
+ */
127
+ export let mediaLibrary: MediaLibraryProvider | null = null;
128
+ /**
129
+ * Whether the picked files are remembered in this browser's localStorage between visits. Default: yes, as always,
130
+ * except with a `mediaLibrary` (a shared browser must not show the next visitor the previous one's picks).
131
+ * This is a setting of the page: when two File Browsers disagree, the last one created wins.
132
+ */
133
+ export let persistSelection: boolean | undefined = undefined;
103
134
  // reactive statement to initialize the component if data is passed
104
135
  $: if(data) {
105
136
  // if(showLogs) console.log('FileBrowser: data reactive statement:', data);
@@ -131,7 +162,18 @@
131
162
  /** When set (single-file picker), disables confirm until user picks a different file. */
132
163
  export let activeFileId: string | null = null;
133
164
  export let showAddToEditor = false; // Toggle visibility of "Add to Editor" functionality
134
- export let addToEditorLabel = 'Add to Editor';
165
+ /** The text of the button that hands the picked files to the page. Default: the message "action.addToEditor". */
166
+ export let addToEditorLabel: string | undefined = undefined;
167
+ /**
168
+ * The language of the File Browser: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers, dates and
169
+ * file sizes are written. Default "en". The words themselves come from `messages`.
170
+ */
171
+ export let locale: string | undefined = undefined;
172
+ /**
173
+ * The page's own words: any of the keys of FILE_BROWSER_MESSAGES (see the README, "Languages"). A key left out keeps
174
+ * its English text. Can change while the File Browser is open.
175
+ */
176
+ export let messages: MessageOverrides | null = null;
135
177
  /** When false, skips bundled demo tree (use with Widgetic upload config). */
136
178
  export let useDemoContent = true;
137
179
  /**
@@ -345,6 +387,223 @@
345
387
  // $: controlsVisible = showFilters || showSorting;
346
388
  // console.log("File Browser component: controlsVisible", showFilters, showSorting, controlsVisible);
347
389
 
390
+ /**
391
+ * MEDIA LIBRARY (the host's own storage)
392
+ *
393
+ * With a `mediaLibrary` the File Browser shows one flat list of the host's files and calls the host's functions to
394
+ * list, upload, rename and delete them. Everything stays in memory: the local cache (IndexedDB) and the saved
395
+ * "My uploads" tree are never read or written, and the picked-file selection is only kept in localStorage when
396
+ * `persistSelection` asks for it.
397
+ */
398
+ // Decided when the File Browser is created (see the `mediaLibrary` prop).
399
+ const libraryMode = mediaLibrary !== null && mediaLibrary !== undefined;
400
+ // A library supplies every file, so `data` handed in by the host is not used next to it.
401
+ if (libraryMode) data = null;
402
+
403
+ // The library as the File Browser uses it: every answer checked, every failure a MediaLibraryError.
404
+ let resolvedMediaLibrary: ResolvedMediaLibrary | null = null;
405
+ // Set when `mediaLibrary` is not a usable library: the screen says so instead of showing files.
406
+ let libraryConfigError: MediaLibraryError | null = null;
407
+ if (libraryMode) {
408
+ try {
409
+ resolvedMediaLibrary = resolveMediaLibrary(mediaLibrary);
410
+ } catch (error) {
411
+ libraryConfigError = new MediaLibraryError('FAILED', error instanceof Error ? error.message : 'mediaLibrary is not a media library', { cause: error });
412
+ console.error('[FileBrowser] The mediaLibrary option cannot be used:', error);
413
+ }
414
+ }
415
+
416
+ // What the parts of this File Browser may offer (Rename, Delete, Upload...), shared through Svelte's context.
417
+ const libraryContext: MediaLibraryContext = {
418
+ library: resolvedMediaLibrary,
419
+ capabilities: !libraryMode ? LEGACY_CAPABILITIES : (resolvedMediaLibrary?.capabilities ?? NO_CAPABILITIES),
420
+ };
421
+ provideMediaLibraryContext(libraryContext);
422
+ const libraryCapabilities = libraryContext.capabilities;
423
+
424
+ // The language: the parts below read it from Svelte's context, and follow when the page changes `locale` or `messages`.
425
+ const i18n = provideI18n({ locale, messages });
426
+ const { t } = i18n;
427
+ $: i18n.update({ locale, messages });
428
+ // The text of the confirm button: the page's label, or the message of the language in use.
429
+ $: addToEditorText = addToEditorLabel ?? $t('action.addToEditor');
430
+
431
+ // A shared browser must not show the next visitor the previous one's picks, so a library turns this off unless the
432
+ // host asks for it. Selecting still works; the picks just live in memory.
433
+ const selectionIsKept = persistSelection ?? !libraryMode;
434
+ if (isBrowser) {
435
+ persistentSelectStore.configurePersistence(selectionIsKept);
436
+ if (!selectionIsKept) persistentSelectStore.clearSelections('all');
437
+ }
438
+
439
+ // Loading the library: what stopped it, whether a list was already shown when it did, and whether the library
440
+ // has more files than were loaded.
441
+ let libraryLoadError: MediaLibraryError | null = null;
442
+ let libraryShowsPartialList = false;
443
+ let libraryListIsTruncated = false;
444
+ let libraryLoadController: AbortController | null = null;
445
+ // Aborted when the File Browser is closed: ends every call to the library that is still waiting, so a closed
446
+ // File Browser does not touch the (page-wide) file list of the next one.
447
+ const libraryActionsController = new AbortController();
448
+
449
+ /** Tells the host about a problem with its library, in the form `{ message, code, action }`. */
450
+ function reportLibraryError(error: MediaLibraryError, action: 'setup' | 'load' | 'upload' | 'rename' | 'delete') {
451
+ dispatch('error', { message: error.message, code: error.code, action });
452
+ }
453
+
454
+ /**
455
+ * Reads the library into the grid, page by page. The first page ends the loading screen and the rest is added as
456
+ * it arrives. If the first page fails the screen shows the error with "Try again"; if a later page fails what was
457
+ * loaded stays and a notice says the list is incomplete.
458
+ */
459
+ async function loadFromLibrary(): Promise<void> {
460
+ const library = resolvedMediaLibrary;
461
+ if (!library) return;
462
+
463
+ // A new load replaces one that is still running (the visitor pressed "Try again").
464
+ libraryLoadController?.abort();
465
+ const controller = new AbortController();
466
+ libraryLoadController = controller;
467
+ libraryLoadError = null;
468
+ libraryShowsPartialList = false;
469
+ libraryListIsTruncated = false;
470
+ isLoading = true;
471
+
472
+ let viewStarted = false;
473
+ const showLibraryFiles = (files: FileSystemItem[]) => {
474
+ if (controller.signal.aborted) return;
475
+ if (!viewStarted) {
476
+ viewStarted = true;
477
+ // `data` is what init() builds the view from; that also ends the loading screen.
478
+ data = { basePath: '', root: createLibraryRoot(files) };
479
+ } else {
480
+ fileStore.update((store) => ({ ...store, root: appendNewFiles(store.root, files) }));
481
+ }
482
+ };
483
+
484
+ try {
485
+ const loaded = await loadLibraryPages(library, { signal: controller.signal, onPage: (files) => showLibraryFiles(files) });
486
+ if (controller.signal.aborted) return;
487
+ // An empty library never delivered a page of files.
488
+ if (!viewStarted) showLibraryFiles([]);
489
+ libraryListIsTruncated = loaded.truncated;
490
+ if (loaded.failure) {
491
+ libraryLoadError = loaded.failure;
492
+ libraryShowsPartialList = loaded.items.length > 0;
493
+ reportLibraryError(loaded.failure, 'load');
494
+ }
495
+ } catch (error) {
496
+ // Only a load this File Browser cancelled itself (closed, or replaced by "Try again") is silent.
497
+ if (controller.signal.aborted) return;
498
+ const failure = toMediaLibraryError(error, 'Could not load the files', 'libraryError.loadFailed');
499
+ console.error('[FileBrowser] Could not load the media library:', failure);
500
+ libraryLoadError = failure;
501
+ // Ends the loading screen; the error is shown instead of the grid.
502
+ if (!viewStarted) showLibraryFiles([]);
503
+ reportLibraryError(failure, 'load');
504
+ } finally {
505
+ if (libraryLoadController === controller) libraryLoadController = null;
506
+ }
507
+ }
508
+
509
+ /** The "Try again" button: reads the whole library again. */
510
+ function reloadLibrary() {
511
+ void loadFromLibrary();
512
+ }
513
+
514
+ /**
515
+ * Renames a file in the host's library and then in the list: the list changes only after the library said yes.
516
+ * Resolves `false` when there was nothing to change; throws a MediaLibraryError when the library refuses.
517
+ */
518
+ async function renameInLibrary(itemId: string, newName: string): Promise<boolean> {
519
+ const library = resolvedMediaLibrary;
520
+ if (!library?.rename) throw new MediaLibraryError('NOT_SUPPORTED', 'This media library does not allow renaming files', { messageKey: 'libraryError.renameNotAllowed' });
521
+ const item = findItemById(itemId);
522
+ if (!item) throw new MediaLibraryError('NOT_FOUND', 'The file is no longer in the list', { messageKey: 'libraryError.fileGone' });
523
+
524
+ const typedName = newName.trim();
525
+ if (typedName === '') return false;
526
+ // A file keeps its extension, as everywhere else in the File Browser.
527
+ const finalName = item.type === 'file' ? getRenamedFileName(item.name, typedName) : typedName;
528
+ if (finalName === item.name) return false;
529
+
530
+ const renamedFile = await library.rename({ id: itemId, name: finalName, signal: libraryActionsController.signal });
531
+ // The File Browser was closed while the library was working: its list is no longer ours to change.
532
+ if (libraryActionsController.signal.aborted) return false;
533
+
534
+ // The library may answer with the file as it is now (it can change the address or the id). When it only says
535
+ // "done", the file stays as it was and takes the new name.
536
+ const updatedFile: FileSystemItem = renamedFile ?? { ...item, name: finalName, modified: new Date().toISOString() };
537
+ fileStore.update((store) => ({ ...store, root: replaceFile(store.root, itemId, updatedFile) }));
538
+ selectedFiles.update((files) => files.map((file) => (file.id === itemId ? updatedFile : file)));
539
+ return true;
540
+ }
541
+
542
+ /**
543
+ * Deletes a file in the host's library and then from the list. Resolves `true` when it is gone; throws a
544
+ * MediaLibraryError when the library refuses.
545
+ */
546
+ async function deleteFromLibrary(item: FileSystemItem): Promise<boolean> {
547
+ const library = resolvedMediaLibrary;
548
+ if (!library?.remove) throw new MediaLibraryError('NOT_SUPPORTED', 'This media library does not allow deleting files', { messageKey: 'libraryError.deleteNotAllowed' });
549
+
550
+ await library.remove({ id: item.id, signal: libraryActionsController.signal });
551
+ // The File Browser was closed while the library was working: its list is no longer ours to change.
552
+ if (libraryActionsController.signal.aborted) throw new MediaLibraryError('ABORTED', 'The File Browser was closed');
553
+
554
+ fileStore.update((store) => ({ ...store, root: removeFiles(store.root, new Set([item.id])) }));
555
+ selectedFiles.update((files) => files.filter((file) => file.id !== item.id));
556
+ return true;
557
+ }
558
+
559
+ /** Shows a file the library just stored, and brings it into view. */
560
+ function addUploadedFileToLibraryList(file: FileSystemItem) {
561
+ fileStore.update((store) => ({ ...store, root: upsertFile(store.root, file) }));
562
+ // Wait for the grid to draw the new file, then scroll to it and flash it, as for any upload.
563
+ setTimeout(() => {
564
+ scrollItemIntoView(file.id);
565
+ const itemElement = findItemElement(file.id);
566
+ if (itemElement) {
567
+ itemElement.classList.add('wave-goodbye');
568
+ setTimeout(() => itemElement.classList.remove('wave-goodbye'), 600);
569
+ }
570
+ }, 100);
571
+ }
572
+
573
+ /** An upload failed (the uploader already shows the failed row). Logged as always; a media library's host is told too. */
574
+ function handleUploadError(event: CustomEvent<{ message: string; file?: string; code?: MediaLibraryErrorCode }>) {
575
+ console.error('Upload error:', event.detail);
576
+ if (libraryMode) {
577
+ dispatch('error', { message: event.detail.message, code: event.detail.code ?? 'FAILED', action: 'upload', file: event.detail.file });
578
+ }
579
+ }
580
+
581
+ /** Finds the element of an item inside this File Browser (also when it sits inside a shadow root). */
582
+ function findItemElement(itemId: string): HTMLElement | null {
583
+ // An id comes from the host's library and may hold any character, so it is escaped before it joins a selector.
584
+ const selector = `[data-item-id="${typeof CSS !== 'undefined' ? CSS.escape(itemId) : itemId.replace(/["\\]/g, '\\$&')}"]`;
585
+ return (mainContainer?.querySelector(selector) ?? document.querySelector(selector)) as HTMLElement | null;
586
+ }
587
+
588
+ // A notice above the grid when the list on screen is not the whole library: a later page failed, or the library
589
+ // has more files than the File Browser loads.
590
+ let libraryNotice: { text: string; canRetry: boolean } | null = null;
591
+ $: libraryNotice = libraryMode && !isLoading
592
+ ? libraryLoadError && libraryShowsPartialList
593
+ ? { text: $t('library.partialNotice'), canRetry: true }
594
+ : libraryListIsTruncated
595
+ ? { text: $t('library.truncatedNotice'), canRetry: false }
596
+ : null
597
+ : null;
598
+
599
+ // Shown instead of the grid: the library cannot be used, or its first page could not be read.
600
+ let libraryErrorMessage = '';
601
+ $: libraryErrorMessage = libraryConfigError
602
+ ? $t('library.notSetUp')
603
+ : libraryLoadError && !libraryShowsPartialList
604
+ ? messageForVisitor(libraryLoadError, $t, 'libraryError.loadFailed')
605
+ : '';
606
+
348
607
  /**
349
608
  * LIFE CYCLE HOOKS
350
609
  */
@@ -352,7 +611,8 @@
352
611
  if(showLogs) console.log('FileBrowser onMount instanceId: ', instanceId);
353
612
  // if(showLogs) console.log('FileBrowser onMount start:', performance.now() - startTime, 'ms');
354
613
 
355
- if (enableLocalCache) {
614
+ // A media library keeps its files to itself: the local cache (IndexedDB) is never scoped, read or written for it.
615
+ if (enableLocalCache && !libraryMode) {
356
616
  const existing = getFileBrowserUploadConfig();
357
617
  if (existing?.accessToken) {
358
618
  setFileBrowserUploadConfig({ ...existing, enableLocalCache: true });
@@ -380,9 +640,20 @@
380
640
  }
381
641
  }
382
642
 
643
+ // The host's media library supplies the files; nothing else is loaded.
644
+ if (libraryMode) {
645
+ basePath = '';
646
+ if (libraryConfigError) {
647
+ isLoading = false;
648
+ reportLibraryError(libraryConfigError, 'setup');
649
+ } else {
650
+ // Not awaited: the rest of the setup (breakpoints, listeners) does not wait for the library.
651
+ void loadFromLibrary();
652
+ }
653
+ }
383
654
  // load demo content from localStorage if no data is passed
384
655
  // if(showLogs) console.log('FileBrowser onMount data & useDemoContent: ', data, useDemoContent);
385
- if (!data) {
656
+ else if (!data) {
386
657
  const uploadConfig = getFileBrowserUploadConfig();
387
658
  const widgeticLibraryMode = Boolean(
388
659
  uploadConfig?.accessToken && uploadConfig?.apiBasePath,
@@ -406,7 +677,7 @@
406
677
  console.warn('[FileBrowser] Upload hydration failed, using local cache:', hydrateError);
407
678
  }
408
679
  }
409
- data = await createUserUploadsFileSystemRoot(files);
680
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
410
681
  basePath = '';
411
682
  if (showLogs) {
412
683
  // console.log('[FileBrowser] Widgetic library mode — user uploads only');
@@ -443,8 +714,9 @@
443
714
  // Add event listener for window resize
444
715
  window.addEventListener('resize', handleResize);
445
716
 
446
- // Set up window key handler
447
- window.addEventListener('keydown', handleKeyDown);
717
+ // Set up window key handler. With a media library the File Browser sits inside the host's page, where Ctrl+A and
718
+ // Backspace belong to the host: it then listens only to keys pressed inside its own container.
719
+ if (!libraryMode) window.addEventListener('keydown', handleKeyDown);
448
720
  window.addEventListener('widgetic:file-browser-command', handleFileBrowserCommand);
449
721
  publishFileBrowserNav();
450
722
 
@@ -478,8 +750,9 @@
478
750
  // set base path
479
751
  data.basePath = basePath;
480
752
 
481
- // save as demo content if not already saved
482
- if(!getFromStorage(demoContentKey, null)) {
753
+ // save as demo content if not already saved (never for a media library: its files are not demo content, and
754
+ // the visitor's file list must not be copied into localStorage)
755
+ if(!libraryMode && !getFromStorage(demoContentKey, null)) {
483
756
  // console.log('FileBrowser: saving demo content to localStorage:', data);
484
757
  saveToStorage(demoContentKey, data);
485
758
  }
@@ -502,8 +775,8 @@
502
775
  // Store the path we want to navigate to after loading
503
776
  let pathToNavigate: string[] = [];
504
777
 
505
- // Check if we have a stored path to restore
506
- if (persistHistory) {
778
+ // Check if we have a stored path to restore (a media library has no folders to go back to)
779
+ if (persistHistory && !libraryMode) {
507
780
  const storedState = getStoredState(instanceId);
508
781
  if (storedState) {
509
782
  pathToNavigate = storedState.pathsArray[storedState.currentIndex] || [];
@@ -550,6 +823,11 @@
550
823
  // onDestroy: cleanup event listener on component destroy
551
824
  onDestroy(() => {
552
825
 
826
+ // Stop waiting for the media library. The file list is shared by the whole page, so an answer that arrives after
827
+ // this File Browser is gone must not be written into the list of the next one.
828
+ libraryLoadController?.abort();
829
+ libraryActionsController.abort();
830
+
553
831
  // check if browser environment is available
554
832
  if (!isBrowser) return;
555
833
 
@@ -731,7 +1009,7 @@
731
1009
  */
732
1010
  function fileMatchesFilter(file: FileSystemItem): boolean {
733
1011
  if (filter === 'all') return true;
734
- return getFileType(file.url || file.name) === filter;
1012
+ return getFileTypeOf(file) === filter;
735
1013
  }
736
1014
 
737
1015
  /**
@@ -941,7 +1219,7 @@
941
1219
  // Filter by type
942
1220
  const typeFilteredFiles = allFiles.filter(file => {
943
1221
  if (filter === 'all') return true;
944
- const fileType = getFileType(file.url || file.name);
1222
+ const fileType = getFileTypeOf(file);
945
1223
  return fileType === filter;
946
1224
  });
947
1225
  if(showLogs && showRecentFilesLogs) console.log('Files after type filtering:', typeFilteredFiles.length);
@@ -975,6 +1253,25 @@
975
1253
  return resolveFileItemUrl(item, storeBasePath);
976
1254
  }
977
1255
 
1256
+ /**
1257
+ * The file as the grid draws it: its address and thumbnail address resolved against the base path.
1258
+ * A Widgetic upload always has a picture to show, so its thumbnail defaults to the file itself.
1259
+ * A media library file only has a thumbnail when the library sent one. Without it the grid draws the
1260
+ * file-type icon (or the file itself when it is a picture) instead of loading a PDF as a picture,
1261
+ * which would fail and show the file as "missing".
1262
+ */
1263
+ function toGridFileItem(item: FileSystemItem): FileSystemItem {
1264
+ const storeBasePath = $fileStore?.basePath ?? basePath;
1265
+ return {
1266
+ ...item,
1267
+ url: getCorrectFileUrl(item),
1268
+ thumbnail:
1269
+ libraryMode && !item.thumbnail
1270
+ ? undefined
1271
+ : resolveFileItemUrl({ ...item, url: item.thumbnail || item.url }, storeBasePath),
1272
+ };
1273
+ }
1274
+
978
1275
  /**
979
1276
  * Type guard for FileSystemItem
980
1277
  * Ensures safe type checking for file operations
@@ -1105,34 +1402,38 @@
1105
1402
  // console.log('call showToast method:', showToast);
1106
1403
 
1107
1404
  // Show initial toast notification
1108
- showToast('success', `Renaming "${oldName}"...`, {
1109
- description: 'This will happen in the background',
1405
+ showToast('success', $t('toast.rename.started', { name: oldName }), {
1406
+ description: $t('toast.inBackground'),
1110
1407
  // duration: 1500
1111
1408
  });
1112
1409
 
1113
- // Perform the rename operation
1114
- renameItem(itemId, newName)
1410
+ // Perform the rename operation (through the host's media library when there is one)
1411
+ (libraryMode ? renameInLibrary(itemId, newName) : renameItem(itemId, newName))
1115
1412
  .then(success => {
1413
+ // The File Browser was closed while the library was working: there is no one to tell.
1414
+ if (libraryMode && libraryActionsController.signal.aborted) return;
1116
1415
  if (success) {
1117
- showToast('success', 'Item renamed', {
1118
- description: `Successfully renamed "${oldName}" to "${newName}"`,
1416
+ showToast('success', $t('toast.rename.done'), {
1417
+ description: $t('toast.rename.doneDetail', { oldName, newName }),
1119
1418
  });
1120
1419
  } else {
1121
- showToast('error', 'Rename failed', {
1122
- description: 'No changes were made',
1420
+ showToast('error', $t('toast.rename.failed'), {
1421
+ description: $t('toast.rename.noChange'),
1123
1422
  });
1124
1423
  }
1125
1424
  })
1126
1425
  .catch(error => {
1426
+ if (libraryMode && (libraryActionsController.signal.aborted || isCancellation(error))) return;
1127
1427
  console.error('Error during rename operation:', error);
1128
- showToast('error', 'Rename failed', {
1129
- description: error instanceof Error ? error.message : 'An unknown error occurred',
1428
+ showToast('error', $t('toast.rename.failed'), {
1429
+ description: messageForVisitor(error, $t, 'toast.rename.unknownError'),
1130
1430
  });
1431
+ if (libraryMode) reportLibraryError(toMediaLibraryError(error, 'Could not rename the file', 'libraryError.renameFailed'), 'rename');
1131
1432
  });
1132
1433
  } else {
1133
1434
  console.error('No valid item selected for rename operation');
1134
- showToast('error', 'Rename failed', {
1135
- description: 'No valid item selected',
1435
+ showToast('error', $t('toast.rename.failed'), {
1436
+ description: $t('toast.rename.noItem'),
1136
1437
  });
1137
1438
  }
1138
1439
  }
@@ -1159,12 +1460,13 @@
1159
1460
  showDeleteConfirmation = false;
1160
1461
 
1161
1462
  // Show initial toast notification
1162
- const initialToastMessage = itemsToDelete.length === 1
1163
- ? `Deleting "${itemsToDelete[0].name}"...`
1164
- : `Deleting ${itemsToDelete.length} items...`;
1463
+ const initialToastMessage = $t('toast.delete.started', {
1464
+ count: itemsToDelete.length,
1465
+ name: itemsToDelete[0]?.name ?? ''
1466
+ });
1165
1467
 
1166
1468
  showToast('success', initialToastMessage, {
1167
- description: 'This will happen in the background',
1469
+ description: $t('toast.inBackground'),
1168
1470
  });
1169
1471
 
1170
1472
  // Process deletions in the background
@@ -1173,11 +1475,13 @@
1173
1475
  let successCount = 0;
1174
1476
  const deletedItems: string[] = [];
1175
1477
  const failedItems: string[] = [];
1478
+ // Why the media library refused, to tell the visitor (only a media library gives reasons)
1479
+ let libraryFailure: MediaLibraryError | null = null;
1176
1480
 
1177
1481
  // Process each item for deletion
1178
1482
  for (const item of itemsToDelete) {
1179
1483
  try {
1180
- const success = await deleteItem(item.id);
1484
+ const success = libraryMode ? await deleteFromLibrary(item) : await deleteItem(item.id);
1181
1485
  if (success) {
1182
1486
  successCount++;
1183
1487
  deletedItems.push(item.name);
@@ -1195,8 +1499,11 @@
1195
1499
  failedItems.push(item.name);
1196
1500
  }
1197
1501
  } catch (itemError) {
1502
+ // The File Browser was closed while the library was working: stop, and tell no one.
1503
+ if (libraryMode && (libraryActionsController.signal.aborted || isCancellation(itemError))) return;
1198
1504
  console.error(`Error deleting ${item.name}:`, itemError);
1199
1505
  failedItems.push(item.name);
1506
+ if (libraryMode) libraryFailure = toMediaLibraryError(itemError, 'Could not delete the file', 'libraryError.deleteFailed');
1200
1507
  }
1201
1508
  }
1202
1509
 
@@ -1209,19 +1516,19 @@
1209
1516
  // Single item deletion
1210
1517
  const isFolder = itemsToDelete.find(item => item.name === deletedItems[0])?.type === 'folder';
1211
1518
  toastMessage = isFolder
1212
- ? `Deleted folder "${deletedItems[0]}"`
1213
- : `Deleted "${deletedItems[0]}"`;
1519
+ ? $t('toast.delete.doneFolder', { name: deletedItems[0] })
1520
+ : $t('toast.delete.doneFile', { name: deletedItems[0] });
1214
1521
  toastDescription = isFolder
1215
- ? 'Folder and its contents were deleted successfully'
1216
- : 'Item was deleted successfully';
1522
+ ? $t('toast.delete.doneFolderDetail')
1523
+ : $t('toast.delete.doneFileDetail');
1217
1524
  } else {
1218
1525
  // Multiple item deletion
1219
- toastMessage = `Deleted ${successCount} items`;
1220
- toastDescription = `${successCount} items were deleted successfully`;
1526
+ toastMessage = $t('toast.delete.doneMany', { count: successCount });
1527
+ toastDescription = $t('toast.delete.doneManyDetail', { count: successCount });
1221
1528
 
1222
1529
  // Add details if small number of items deleted (up to 3)
1223
1530
  if (successCount <= 3) {
1224
- toastDescription = `Deleted: ${deletedItems.join(', ')}`;
1531
+ toastDescription = $t('toast.delete.doneNames', { names: deletedItems.join($t('list.separator')) });
1225
1532
  }
1226
1533
  }
1227
1534
 
@@ -1233,21 +1540,23 @@
1233
1540
  // Show error toast if any deletions failed
1234
1541
  if (failedItems.length > 0) {
1235
1542
  const errorMessage = failedItems.length === 1
1236
- ? `Failed to delete "${failedItems[0]}"`
1237
- : `Failed to delete ${failedItems.length} items`;
1543
+ ? $t('toast.delete.failedOne', { name: failedItems[0] })
1544
+ : $t('toast.delete.failedMany', { count: failedItems.length });
1238
1545
 
1239
1546
  const errorDescription = failedItems.length <= 3
1240
- ? `Failed to delete: ${failedItems.join(', ')}`
1241
- : 'Some items could not be deleted';
1547
+ ? $t('toast.delete.failedNames', { names: failedItems.join($t('list.separator')) })
1548
+ : $t('toast.delete.failedSome');
1242
1549
 
1243
1550
  showToast('error', errorMessage, {
1244
- description: errorDescription,
1551
+ // A media library says why (for example "not allowed"); that is more useful than the names again.
1552
+ description: libraryFailure ? messageForVisitor(libraryFailure, $t) : errorDescription,
1245
1553
  });
1554
+ if (libraryFailure) reportLibraryError(libraryFailure, 'delete');
1246
1555
  }
1247
1556
  } catch (error) {
1248
1557
  console.error('Error deleting items:', error);
1249
- showToast('error', 'Failed to delete items', {
1250
- description: error instanceof Error ? error.message : 'Unknown error occurred',
1558
+ showToast('error', $t('toast.delete.failedAll'), {
1559
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1251
1560
  });
1252
1561
  }
1253
1562
  }, 100); // Small delay to ensure UI updates first
@@ -1258,6 +1567,22 @@
1258
1567
  return Boolean(uploadConfig?.accessToken && uploadConfig?.apiBasePath) || !useDemoContent;
1259
1568
  }
1260
1569
 
1570
+ // The built-in "My uploads" folder is named in the visitor's language, and follows a change of language.
1571
+ function nameBuiltInFolder(folderName: string) {
1572
+ fileStore.update((store) => {
1573
+ const builtInFolder = store.root?.children?.find((child) => child.type === 'folder' && child.id === 'folder_my_uploads');
1574
+ if (!store.root || !builtInFolder || builtInFolder.name === folderName) return store;
1575
+ return {
1576
+ ...store,
1577
+ root: {
1578
+ ...store.root,
1579
+ children: (store.root.children ?? []).map((child) => (child === builtInFolder ? { ...child, name: folderName } : child)),
1580
+ },
1581
+ };
1582
+ });
1583
+ }
1584
+ $: if (!libraryMode) nameBuiltInFolder($t('library.defaultLabel'));
1585
+
1261
1586
  function persistMyUploadsTree() {
1262
1587
  const store = get(fileStore);
1263
1588
  const myUploads = store.root?.children?.find((c) => c.id === 'folder_my_uploads');
@@ -1291,8 +1616,8 @@
1291
1616
 
1292
1617
  persistMyUploadsTree();
1293
1618
  showNewFolderDialog = false;
1294
- showToast('success', 'Folder created', {
1295
- description: `Created folder "${folderName}"`,
1619
+ showToast('success', $t('toast.folder.created'), {
1620
+ description: $t('toast.folder.createdDetail', { name: folderName }),
1296
1621
  });
1297
1622
  }
1298
1623
 
@@ -1318,7 +1643,8 @@
1318
1643
 
1319
1644
  if (!response.ok) {
1320
1645
  const error = await response.json();
1321
- throw new Error(error.message || 'Failed to create folder');
1646
+ // The server's own words are shown as they are; without any, the visitor reads the File Browser's sentence in the page's language
1647
+ throw new MediaLibraryError('FAILED', error.message || 'Failed to create folder', error.message ? {} : { messageKey: 'toast.folder.failed' });
1322
1648
  }
1323
1649
 
1324
1650
  const { folder } = await response.json();
@@ -1343,13 +1669,13 @@
1343
1669
  });
1344
1670
 
1345
1671
  showNewFolderDialog = false;
1346
- showToast('success', 'Folder created', {
1347
- description: `Created folder "${folderName}"`,
1672
+ showToast('success', $t('toast.folder.created'), {
1673
+ description: $t('toast.folder.createdDetail', { name: folderName }),
1348
1674
  });
1349
1675
  } catch (error) {
1350
1676
  if(showLogs) console.error('Error creating folder:', error);
1351
- showToast('error', 'Failed to create folder', {
1352
- description: error instanceof Error ? error.message : 'Unknown error occurred',
1677
+ showToast('error', $t('toast.folder.failed'), {
1678
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1353
1679
  });
1354
1680
  }
1355
1681
  }
@@ -1383,7 +1709,7 @@
1383
1709
  // });
1384
1710
 
1385
1711
  // Backspace key handler
1386
- if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused() && !$isModalOpen) {
1712
+ if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused(event) && !$isModalOpen) {
1387
1713
  event.preventDefault();
1388
1714
  event.stopPropagation();
1389
1715
 
@@ -1398,10 +1724,12 @@
1398
1724
  /**
1399
1725
  * Checks if an input element is currently focused
1400
1726
  * Prevents unintended backspace navigation when typing
1727
+ * @param event The key event being handled. Inside a shadow root `document.activeElement` is the shadow host, not
1728
+ * the field being typed in, so the field is taken from the event when there is one.
1401
1729
  * @returns boolean indicating if an input element has focus
1402
1730
  */
1403
- function isInputFocused() {
1404
- const activeElement = document.activeElement;
1731
+ function isInputFocused(event?: Event) {
1732
+ const activeElement = (event?.composedPath?.()[0] as Element | undefined) ?? document.activeElement;
1405
1733
  return (
1406
1734
  activeElement instanceof HTMLInputElement ||
1407
1735
  activeElement instanceof HTMLTextAreaElement ||
@@ -1440,7 +1768,7 @@
1440
1768
  if (item.type === 'folder') {
1441
1769
  return getFolderIcon(item, filter);
1442
1770
  }
1443
- const fileType = getFileType(item.url || item.name);
1771
+ const fileType = getFileTypeOf(item);
1444
1772
 
1445
1773
  if (fileType === 'video' && item.url) {
1446
1774
  // For video files, construct the thumbnail path by replacing the video extension with .png
@@ -1456,7 +1784,7 @@
1456
1784
  return getFileIcon(item.name);
1457
1785
  }
1458
1786
 
1459
- $: fileTypesText = formatFileTypesForDisplay();
1787
+ $: fileTypesText = formatFileTypesForDisplay($t);
1460
1788
 
1461
1789
  function handleModalClose() {
1462
1790
  showModal = false;
@@ -1472,6 +1800,12 @@
1472
1800
  */
1473
1801
  function handleFileUploaded(event: CustomEvent) {
1474
1802
  const { file, success } = event.detail;
1803
+
1804
+ // A media library keeps the file itself: the list only shows what it stored. Nothing is saved on this device.
1805
+ if (libraryMode) {
1806
+ if (success && file && !libraryActionsController.signal.aborted) addUploadedFileToLibraryList(file);
1807
+ return;
1808
+ }
1475
1809
 
1476
1810
  if (success && file) {
1477
1811
  const uploadedFile = {
@@ -1567,7 +1901,7 @@
1567
1901
  // Scroll to and highlight the new file after a short delay to ensure rendering
1568
1902
  setTimeout(() => {
1569
1903
  scrollItemIntoView(file.id);
1570
- const itemElement = document.querySelector(`[data-item-id="${file.id}"]`);
1904
+ const itemElement = findItemElement(file.id);
1571
1905
  if (itemElement) {
1572
1906
  itemElement.classList.add('wave-goodbye');
1573
1907
  setTimeout(() => {
@@ -1671,8 +2005,8 @@
1671
2005
  // if(showLogs) console.log('Attempting to scroll item into view:', itemId);
1672
2006
 
1673
2007
  requestAnimationFrame(() => {
1674
- const itemElement = document.querySelector(`[data-item-id="${itemId}"]`) as HTMLElement;
1675
- const scrollableArea = scrollContainer || (document.querySelector('.scroll-area-container') as HTMLElement);
2008
+ const itemElement = findItemElement(itemId);
2009
+ const scrollableArea = scrollContainer || (mainContainer?.querySelector('.scroll-area-container') as HTMLElement | null) || (document.querySelector('.scroll-area-container') as HTMLElement);
1676
2010
 
1677
2011
  if (itemElement && scrollableArea) {
1678
2012
  // Handle animation first if it's a goodbye animation
@@ -1902,8 +2236,10 @@
1902
2236
  return;
1903
2237
  }
1904
2238
 
1905
- // Focus the container when clicking anywhere inside it
1906
- mainContainer?.focus();
2239
+ // Focus the container when clicking anywhere inside it. Without preventScroll the browser scrolls the whole page
2240
+ // to bring the container into view when it is only partly visible, which moves the control under the pointer
2241
+ // between mousedown and mouseup (the click is lost) and scrolls a host page that embeds the File Browser.
2242
+ mainContainer?.focus({ preventScroll: true });
1907
2243
  }
1908
2244
 
1909
2245
  // Update the keyboard shortcuts handler to batch updates
@@ -1922,10 +2258,12 @@
1922
2258
  if ((event.metaKey || event.ctrlKey) && event.key === 'a') {
1923
2259
  // console.log('FileBrowser Handle CMD/CTRL + A:', event, $isModalOpen);
1924
2260
 
2261
+ // Typing in a field: Ctrl+A selects the field's text, as it does everywhere else.
2262
+ if (isInputFocused(event)) return;
2263
+
1925
2264
  event.preventDefault();
1926
2265
  event.stopPropagation();
1927
2266
 
1928
- if (isInputFocused()) return;
1929
2267
  if (maxSelections === 1) return;
1930
2268
 
1931
2269
  // Clear any text selection
@@ -2030,14 +2368,14 @@
2030
2368
  currentPath = newPath;
2031
2369
  } else {
2032
2370
  if(showLogs) console.error('Could not find path for folder:', targetFolderId);
2033
- showToast('error', 'Navigation failed', {
2034
- description: 'Could not find the target folder location',
2371
+ showToast('error', $t('toast.navigation.failed'), {
2372
+ description: $t('toast.navigation.noFolder'),
2035
2373
  });
2036
2374
  }
2037
2375
  } catch (error) {
2038
2376
  if(showLogs) console.error('Error during move navigation:', error);
2039
- showToast('error', 'Navigation failed', {
2040
- description: 'An error occurred while navigating to the target folder',
2377
+ showToast('error', $t('toast.navigation.failed'), {
2378
+ description: $t('toast.navigation.error'),
2041
2379
  });
2042
2380
  }
2043
2381
  }
@@ -2061,22 +2399,16 @@
2061
2399
  }
2062
2400
 
2063
2401
  // Add in script section after other filter-related code
2064
- // Format filter type for display
2065
- function formatFilterType(filterType: FileFilterType): string {
2066
- if (filterType === 'all') return 'All';
2067
- // Capitalize first letter
2068
- return filterType.charAt(0).toUpperCase() + filterType.slice(1);
2069
- }
2070
-
2071
2402
  // Filter options for the dropdown
2072
- const filterOptions = [
2073
- { value: 'all', label: 'All' },
2074
- { value: 'image', label: 'Images' },
2075
- { value: 'video', label: 'Videos' },
2076
- { value: 'document', label: 'Documents' },
2077
- { value: 'audio', label: 'Audio' },
2078
- { value: 'font', label: 'Fonts' },
2079
- { value: 'svg', label: 'SVG' }
2403
+ let filterOptions: Array<{ value: FileFilterType; label: string }> = [];
2404
+ $: filterOptions = [
2405
+ { value: 'all', label: $t('filterOption.all') },
2406
+ { value: 'image', label: $t('filterOption.image') },
2407
+ { value: 'video', label: $t('filterOption.video') },
2408
+ { value: 'document', label: $t('filterOption.document') },
2409
+ { value: 'audio', label: $t('filterOption.audio') },
2410
+ { value: 'font', label: $t('filterOption.font') },
2411
+ { value: 'svg', label: $t('filterOption.svg') }
2080
2412
  ];
2081
2413
 
2082
2414
  // Add these state variables
@@ -2122,7 +2454,7 @@
2122
2454
 
2123
2455
  // Find the files that match the new filter type
2124
2456
  const matchingFiles = allFiles.filter(file =>
2125
- getFileType(file.url || file.name) === newFilter
2457
+ getFileTypeOf(file) === newFilter
2126
2458
  );
2127
2459
 
2128
2460
  // Get IDs of matching files that were previously selected
@@ -2150,7 +2482,7 @@
2150
2482
 
2151
2483
  // Find the files that match the new filter type
2152
2484
  const matchingFiles = allFiles.filter(file =>
2153
- getFileType(file.url || file.name) === newFilter
2485
+ getFileTypeOf(file) === newFilter
2154
2486
  );
2155
2487
 
2156
2488
  // Get selected files from the "all" filter (which should be the master list)
@@ -2316,7 +2648,8 @@ mainGridClass="app-main-grid"
2316
2648
  canGoBack={$canGoBackStore}
2317
2649
  canGoForward={$canGoForwardStore}
2318
2650
  on:toggleSelectedFiles={(e : CustomEvent) => allowSelecting && toggleModal()}
2319
- showBreadcrumbs={showBreadcrumbs}
2651
+ showBreadcrumbs={showBreadcrumbs && !libraryMode}
2652
+ title={libraryMode ? (resolvedMediaLibrary?.hasOwnLabel ? resolvedMediaLibrary.label : $t('library.defaultLabel')) : ''}
2320
2653
  />
2321
2654
 
2322
2655
  <!-- FILE BROWSER CONTROLS -->
@@ -2326,7 +2659,7 @@ mainGridClass="app-main-grid"
2326
2659
  <!-- svelte-ignore a11y_click_events_have_key_events -->
2327
2660
  <div onclick={handleSearch} class="w-full cursor-pointer">
2328
2661
  <SearchInput
2329
- placeholder="Search..."
2662
+ placeholder={$t('search.placeholder')}
2330
2663
  value=""
2331
2664
  containerClass="w-full"
2332
2665
  onInput={() => {}}
@@ -2352,7 +2685,7 @@ mainGridClass="app-main-grid"
2352
2685
  filterDropdownOpen = !filterDropdownOpen;
2353
2686
  }}
2354
2687
  >
2355
- <span>Filter by {formatFilterType(filter)}</span>
2688
+ <span>{$t('filter.by', { type: $t(`filterName.${filter}`) })}</span>
2356
2689
  <IconAdjustmentsHorizontal class="h-5 w-5 text-[hsl(var(--grey5))] ml-1 transition-colors duration-200 group-hover:text-[hsl(var(--grey7))]" />
2357
2690
  </button>
2358
2691
 
@@ -2392,9 +2725,9 @@ mainGridClass="app-main-grid"
2392
2725
  class="bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm"
2393
2726
  bind:value={$sortCriteria}
2394
2727
  >
2395
- <option value="name">Name</option>
2396
- <option value="date">Date</option>
2397
- <option value="size">Size</option>
2728
+ <option value="name">{$t('sort.name')}</option>
2729
+ <option value="date">{$t('sort.date')}</option>
2730
+ <option value="size">{$t('sort.size')}</option>
2398
2731
  </select>
2399
2732
 
2400
2733
  <!-- Sort Direction Button -->
@@ -2413,6 +2746,16 @@ mainGridClass="app-main-grid"
2413
2746
 
2414
2747
  <!-- FILE BROWSER CONTENT -->
2415
2748
  <div class="file-browser-content flex min-h-0 flex-col grow mr-[4px] overflow-hidden relative widgetic-colors">
2749
+ <!-- Media library notice: the list on screen is not the whole library -->
2750
+ {#if libraryNotice}
2751
+ <div class="library-notice mx-6 mt-3 flex shrink-0 items-center justify-between gap-3 rounded-md bg-[hsl(var(--grey1))] px-3 py-2 subtext text-[hsl(var(--grey7))]" role="status">
2752
+ <span>{libraryNotice.text}</span>
2753
+ {#if libraryNotice.canRetry}
2754
+ <button type="button" class="library-notice-retry shrink-0 underline" onclick={reloadLibrary}>{$t('action.tryAgain')}</button>
2755
+ {/if}
2756
+ </div>
2757
+ {/if}
2758
+
2416
2759
  <!-- Loader Container -->
2417
2760
  {#if isLoading}
2418
2761
  <div class="loader-container p-6">
@@ -2429,6 +2772,20 @@ mainGridClass="app-main-grid"
2429
2772
  </div>
2430
2773
  </div>
2431
2774
 
2775
+ <!-- Media library error: it cannot be used, or its first page could not be read -->
2776
+ {:else if libraryErrorMessage}
2777
+ <div class="library-error-container relative min-h-0 flex-1" role="alert">
2778
+ <div class="empty-state-wrapper w-full flex justify-center items-center">
2779
+ <EmptyState message={libraryErrorMessage} height="auto">
2780
+ <svelte:fragment slot="action">
2781
+ {#if !libraryConfigError}
2782
+ <Button variant="outline" size="sm" onclick={reloadLibrary}>{$t('action.tryAgain')}</Button>
2783
+ {/if}
2784
+ </svelte:fragment>
2785
+ </EmptyState>
2786
+ </div>
2787
+ </div>
2788
+
2432
2789
  <!-- Files container -->
2433
2790
  {:else}
2434
2791
  <!-- Main content container with Files Inside --> <!-- {!showAddToEditor ? 'overflow-y-auto px-6' : ''} -->
@@ -2471,7 +2828,7 @@ mainGridClass="app-main-grid"
2471
2828
  <!-- Files GRID List(VirtualList) -->
2472
2829
  <VirtualList class="content-container grow"
2473
2830
  {scrollContainer}
2474
- items={[{ type: 'new-folder' }, ...sortedFilteredFiles]}
2831
+ items={libraryCapabilities.folders ? [{ type: 'new-folder' }, ...sortedFilteredFiles] : sortedFilteredFiles}
2475
2832
  itemHeight={GRID_ITEM_HEIGHT}
2476
2833
  columns={mainContainerWidth <= mobileBreakpoint ? 2 :
2477
2834
  mainContainerWidth <= tabletBreakpoint ? 3 : 4}
@@ -2500,14 +2857,7 @@ mainGridClass="app-main-grid"
2500
2857
  />
2501
2858
  {:else}
2502
2859
  <FileItem
2503
- item={{
2504
- ...item,
2505
- url: getCorrectFileUrl(item),
2506
- thumbnail: resolveFileItemUrl(
2507
- { ...item, url: item.thumbnail || item.url },
2508
- $fileStore?.basePath ?? basePath
2509
- ),
2510
- }}
2860
+ item={toGridFileItem(item)}
2511
2861
  selected={allowSelecting && currentSelections.some(f => f.id === item.id)}
2512
2862
  {allowSelecting}
2513
2863
  gridLayout={true}
@@ -2520,8 +2870,8 @@ mainGridClass="app-main-grid"
2520
2870
  </div>
2521
2871
  </VirtualList>
2522
2872
 
2523
- <!-- Recent Files -->
2524
- {#if currentPath.length === 0 && recentFiles.length > 0 && mainContainerWidth > tabletBreakpoint}
2873
+ <!-- Recent Files (a media library is one flat list, so they would only repeat the grid) -->
2874
+ {#if !libraryMode && currentPath.length === 0 && recentFiles.length > 0 && mainContainerWidth > tabletBreakpoint}
2525
2875
  <RecentFiles class="recent-files-container"
2526
2876
  {recentFiles}
2527
2877
  selectedFiles={allSelectedFiles}
@@ -2539,14 +2889,16 @@ mainGridClass="app-main-grid"
2539
2889
  <div class="empty-content-container">
2540
2890
 
2541
2891
  <!-- New Folder Button -->
2542
- <div class="grid grid-cols-3 gap-8 relative z-20 pointer-events-auto">
2543
- <NewFolderButton on:click={handleNewFolderClick} />
2544
- </div>
2892
+ {#if libraryCapabilities.folders}
2893
+ <div class="grid grid-cols-3 gap-8 relative z-20 pointer-events-auto">
2894
+ <NewFolderButton on:click={handleNewFolderClick} />
2895
+ </div>
2896
+ {/if}
2545
2897
 
2546
2898
  <!-- Empty State Container -->
2547
2899
  <div class="empty-state-wrapper w-full flex justify-center items-center">
2548
2900
  <EmptyState
2549
- message="No files in this folder!"
2901
+ message={libraryMode ? (filter === 'all' ? $t('empty.library') : $t('empty.libraryFiltered')) : $t('empty.folder')}
2550
2902
  height="auto"
2551
2903
  >
2552
2904
  </EmptyState>
@@ -2570,7 +2922,7 @@ mainGridClass="app-main-grid"
2570
2922
  filter={filter}
2571
2923
  allowSelecting={allowSelecting}
2572
2924
  {showAddToEditor}
2573
- {addToEditorLabel}
2925
+ addToEditorLabel={addToEditorText}
2574
2926
  {activeFileId}
2575
2927
  {maxSelections}
2576
2928
  compact={mainContainerWidth > 0 && mainContainerWidth < 700}
@@ -2587,8 +2939,8 @@ mainGridClass="app-main-grid"
2587
2939
  </div>
2588
2940
  {/if}
2589
2941
 
2590
- <!-- FILE UPLOADER -->
2591
- {#if !isLoading}
2942
+ <!-- FILE UPLOADER (a media library without upload has nothing to upload to) -->
2943
+ {#if !isLoading && libraryCapabilities.upload}
2592
2944
  <div class="file-uploader-container shrink-0 bg-white border-t border-[hsl(var(--grey1))] {isTablet ? 'px-2' : 'px-6'} {isTablet ? 'py-2' : 'py-6'} error widgetic-colors">
2593
2945
  <FileUploader
2594
2946
  bind:this={fileUploaderComponent}
@@ -2597,7 +2949,7 @@ mainGridClass="app-main-grid"
2597
2949
  {filter}
2598
2950
  portalTarget={mainContainer}
2599
2951
  on:fileUploaded={handleFileUploaded}
2600
- on:error={(event: CustomEvent<{message: string}>) => console.error('Upload error:', event.detail)}
2952
+ on:error={handleUploadError}
2601
2953
  bind:dragActive
2602
2954
  bind:dragInvalid
2603
2955
  bind:hasValidFiles
@@ -2617,7 +2969,7 @@ mainGridClass="app-main-grid"
2617
2969
  target={rootContainerClass}
2618
2970
  allFiles={getAllFiles($fileStore.root)}
2619
2971
  {showAddToEditor}
2620
- {addToEditorLabel}
2972
+ addToEditorLabel={addToEditorText}
2621
2973
  on:close={handleModalClose}
2622
2974
  on:fileUploaded={handleFileUploaded}
2623
2975
  on:navigate={handleSearchNavigate}
@@ -2654,8 +3006,19 @@ mainGridClass="app-main-grid"
2654
3006
  itemName={selectedItem?.name ?? ''}
2655
3007
  itemType={selectedItem?.type === 'folder' ? 'folder' : 'file'}
2656
3008
  itemId={selectedItem?.id ?? ''}
2657
- confirmLabel="Rename"
2658
- cancelLabel="Cancel"
3009
+ placeholder={selectedItem?.type === 'folder' ? $t('dialog.rename.folderPlaceholder') : $t('dialog.rename.filePlaceholder')}
3010
+ confirmLabel={$t('action.rename')}
3011
+ cancelLabel={$t('action.cancel')}
3012
+ closeLabel={$t('dialog.close')}
3013
+ messages={{
3014
+ invalidTitle: $t('dialog.rename.invalidTitle'),
3015
+ enterName: $t('dialog.rename.enterName'),
3016
+ enterDifferentName: $t('dialog.rename.enterDifferentName'),
3017
+ enterValidName: $t('dialog.rename.enterValidName'),
3018
+ tooShort: $t('dialog.rename.tooShort'),
3019
+ // The dialog knows its own limit: it puts the number in where {max} stands
3020
+ tooLong: $t('dialog.rename.tooLong', { max: '{max}' })
3021
+ }}
2659
3022
  target={rootContainerClass}
2660
3023
  shouldUseCustomRenameFunction={true}
2661
3024
  on:rename={handleRename}
@@ -2703,7 +3066,7 @@ mainGridClass="app-main-grid"
2703
3066
 
2704
3067
  // Add wave animation to all moved items
2705
3068
  detail.movedItems.forEach((item: { id: string }) => {
2706
- const itemElement = document.querySelector(`[data-item-id="${item.id}"]`);
3069
+ const itemElement = findItemElement(item.id);
2707
3070
  if (itemElement) {
2708
3071
  itemElement.classList.add('wave-goodbye');
2709
3072
  setTimeout(() => {
@@ -2721,18 +3084,21 @@ mainGridClass="app-main-grid"
2721
3084
  {#if showDeleteConfirmation}
2722
3085
  <ActionModal
2723
3086
  bind:isOpen={showDeleteConfirmation}
2724
- title={selectedItem?.type === 'folder' ? 'Delete folder' : (allSelectedFiles.length > 1 ? 'Delete items' : 'Delete file')}
3087
+ title={selectedItem?.type === 'folder' ? $t('dialog.delete.folderTitle') : (allSelectedFiles.length > 1 ? $t('dialog.delete.itemsTitle') : $t('dialog.delete.fileTitle'))}
2725
3088
  message={selectedItem?.type === 'folder'
2726
- ? `Delete '${selectedItem?.name}' and all content inside?`
3089
+ ? $t('dialog.delete.folderMessage', { name: selectedItem?.name ?? '' })
2727
3090
  : (allSelectedFiles.length > 1
2728
- ? `Are you sure you want to delete ${allSelectedFiles.length} items?`
2729
- : `Delete '${allSelectedFiles[0]?.name}'?`)}
3091
+ ? $t('dialog.delete.itemsMessage', { count: allSelectedFiles.length })
3092
+ : $t('dialog.delete.fileMessage', { name: allSelectedFiles[0]?.name ?? '' }))}
2730
3093
  items={selectedItem?.type === 'folder' ? [selectedItem] : allSelectedFiles}
2731
3094
  target={rootContainerClass}
2732
3095
  on:confirm={handleDelete}
2733
3096
  on:cancel={() => {
2734
3097
  showDeleteConfirmation = false;
2735
3098
  }}
3099
+ confirmLabel={$t('action.confirm')}
3100
+ cancelLabel={$t('action.cancel')}
3101
+ closeLabel={$t('dialog.close')}
2736
3102
  actionType="delete"
2737
3103
  confirmVariant="attention"
2738
3104
  modalType="delete"
@@ -2744,13 +3110,21 @@ mainGridClass="app-main-grid"
2744
3110
  bind:isOpen={showNewFolderDialog}
2745
3111
  itemType="folder"
2746
3112
  modalType="newFolder"
2747
- placeholder="folder name..."
3113
+ placeholder={$t('dialog.newFolder.placeholder')}
2748
3114
  target={rootContainerClass}
2749
3115
  {currentPath}
2750
3116
  {currentPathNames}
2751
3117
  showTitle={false}
2752
- confirmLabel="Create"
2753
- cancelLabel="Cancel"
3118
+ confirmLabel={$t('action.create')}
3119
+ cancelLabel={$t('action.cancel')}
3120
+ closeLabel={$t('dialog.close')}
3121
+ messages={{
3122
+ invalidTitle: $t('dialog.newFolder.invalidTitle'),
3123
+ required: $t('dialog.newFolder.required'),
3124
+ invalidCharacters: $t('dialog.newFolder.invalidCharacters'),
3125
+ // The dialog knows its own limit: it puts the number in where {max} stands
3126
+ tooLong: $t('dialog.newFolder.tooLong', { max: '{max}' })
3127
+ }}
2754
3128
  on:create={handleNewFolder}
2755
3129
  on:cancel={() => { showNewFolderDialog = false; }}
2756
3130
  />