@widgetic/file-browser 0.5.24 → 0.5.26

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 +279 -0
  2. package/dist/components/FolderTree.svelte +16 -9
  3. package/dist/components/FolderTree.svelte.d.ts +2 -6
  4. package/dist/components/core/FileBrowser.svelte +529 -127
  5. package/dist/components/core/FileBrowser.svelte.d.ts +40 -1
  6. package/dist/components/core/FileUploader.svelte +130 -57
  7. package/dist/components/core/Header.svelte +13 -2
  8. package/dist/components/core/Header.svelte.d.ts +1 -0
  9. package/dist/components/core/RecentFiles.svelte +41 -29
  10. package/dist/components/core/UploadStatus.svelte +14 -7
  11. package/dist/components/core/UploadStatusList.svelte +13 -21
  12. package/dist/components/items/FileItem.svelte +28 -15
  13. package/dist/components/items/FolderItem.svelte +13 -6
  14. package/dist/components/modals/MoveDialog.svelte +49 -38
  15. package/dist/components/modals/NewFolderButton.svelte +5 -2
  16. package/dist/components/modals/SearchModal.svelte +25 -26
  17. package/dist/components/modals/SearchModal.svelte.d.ts +1 -1
  18. package/dist/components/modals/SelectedFilesModal.svelte +23 -14
  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 +25 -9
  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 +11 -7
  28. package/dist/components/ui/ControlToolbar.svelte +50 -28
  29. package/dist/components/ui/ControlToolbar.svelte.d.ts +1 -1
  30. package/dist/components/ui/DragSelect.svelte +3 -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 +16 -15
  35. package/dist/components/ui/SearchResults.svelte +9 -2
  36. package/dist/i18n/context.d.ts +28 -0
  37. package/dist/i18n/context.js +17 -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 +15 -0
  41. package/dist/i18n/index.js +18 -0
  42. package/dist/i18n/messages.d.ts +281 -0
  43. package/dist/i18n/messages.js +294 -0
  44. package/dist/i18n/text.d.ts +19 -0
  45. package/dist/i18n/text.js +35 -0
  46. package/dist/index.d.ts +3 -0
  47. package/dist/index.js +4 -0
  48. package/dist/mediaLibrary/capabilities.d.ts +22 -0
  49. package/dist/mediaLibrary/capabilities.js +42 -0
  50. package/dist/mediaLibrary/context.d.ts +17 -0
  51. package/dist/mediaLibrary/context.js +16 -0
  52. package/dist/mediaLibrary/errors.d.ts +42 -0
  53. package/dist/mediaLibrary/errors.js +114 -0
  54. package/dist/mediaLibrary/index.d.ts +10 -0
  55. package/dist/mediaLibrary/index.js +9 -0
  56. package/dist/mediaLibrary/normalize.d.ts +39 -0
  57. package/dist/mediaLibrary/normalize.js +139 -0
  58. package/dist/mediaLibrary/paging.d.ts +37 -0
  59. package/dist/mediaLibrary/paging.js +62 -0
  60. package/dist/mediaLibrary/resolve.d.ts +39 -0
  61. package/dist/mediaLibrary/resolve.js +137 -0
  62. package/dist/mediaLibrary/treeOps.d.ts +24 -0
  63. package/dist/mediaLibrary/treeOps.js +67 -0
  64. package/dist/mediaLibrary/types.d.ts +126 -0
  65. package/dist/mediaLibrary/types.js +11 -0
  66. package/dist/mediaLibrary/urls.d.ts +30 -0
  67. package/dist/mediaLibrary/urls.js +59 -0
  68. package/dist/mediaLibrary/widgetic.d.ts +39 -0
  69. package/dist/mediaLibrary/widgetic.js +89 -0
  70. package/dist/stores/fileStore.d.ts +2 -2
  71. package/dist/stores/folderCountStore.js +2 -2
  72. package/dist/stores/navigationStore.d.ts +1 -1
  73. package/dist/stores/persistentSelectStore.d.ts +11 -1
  74. package/dist/stores/persistentSelectStore.js +26 -0
  75. package/dist/utils/dateUtils.d.ts +11 -2
  76. package/dist/utils/dateUtils.js +20 -15
  77. package/dist/utils/fileKinds.d.ts +44 -0
  78. package/dist/utils/fileKinds.js +96 -0
  79. package/dist/utils/fileNames.d.ts +7 -0
  80. package/dist/utils/fileNames.js +19 -0
  81. package/dist/utils/fileOperations.js +2 -11
  82. package/dist/utils/fileTypes.d.ts +11 -2
  83. package/dist/utils/fileTypes.js +26 -14
  84. package/dist/utils/fileUtils.d.ts +8 -1
  85. package/dist/utils/fileUtils.js +22 -7
  86. package/dist/utils/folderUtils.js +3 -2
  87. package/dist/utils/previewKeys.d.ts +12 -0
  88. package/dist/utils/previewKeys.js +14 -0
  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 +5 -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,
@@ -56,12 +57,12 @@
56
57
  createUserUploadsFileSystemRoot,
57
58
  } from '../../utils/userUploadsStorage';
58
59
  import { fetchUserUploadsFromApi } from '../../utils/widgeticUpload';
59
- import { get } from 'svelte/store';
60
+ import { get, writable } from 'svelte/store';
60
61
  import { resolveFileItemUrl } from '../../utils/resolveFileUrl';
61
62
  import { dev } from '$app/environment';
62
63
  import demoContentData from '../../data/demoContent.json';
63
64
  // import { showToast } from '../../utils/toastUtils';
64
- import { showToast } from '@widgetic/design-system/components';
65
+ import { showToast, ToasterModal } from '@widgetic/design-system/components';
65
66
 
66
67
  // Constants for localStorage keys
67
68
  const FILTER_STORAGE_KEY = (id: string) => `file-browser-filter-${id}`;
@@ -90,6 +91,23 @@
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 '@widgetic/design-system/i18n';
108
+ // The reading direction the screen is laid out in, shared with the parts below (see the `dir` prop)
109
+ import { shareTextDirection, type TextDirection } from '@widgetic/design-system/components/textDirection';
110
+
93
111
  // logs flags
94
112
  let showLogs = false;
95
113
  let showRecentFilesLogs = false;
@@ -100,6 +118,21 @@
100
118
  */
101
119
  // data props
102
120
  export let data: any = null;
121
+ /**
122
+ * The host's own media library (a `MediaLibraryProvider`): plain functions the File Browser calls to list, upload,
123
+ * rename and delete the host's files. When given, the File Browser shows that one flat library instead of the
124
+ * Widgetic uploads or the demo content, and stores nothing about it on this device (no local cache, no saved
125
+ * tree, no saved selection unless `persistSelection` says so).
126
+ *
127
+ * Read once, when the File Browser is created: to show another library, create a new File Browser.
128
+ */
129
+ export let mediaLibrary: MediaLibraryProvider | null = null;
130
+ /**
131
+ * Whether the picked files are remembered in this browser's localStorage between visits. Default: yes, as always,
132
+ * except with a `mediaLibrary` (a shared browser must not show the next visitor the previous one's picks).
133
+ * This is a setting of the page: when two File Browsers disagree, the last one created wins.
134
+ */
135
+ export let persistSelection: boolean | undefined = undefined;
103
136
  // reactive statement to initialize the component if data is passed
104
137
  $: if(data) {
105
138
  // if(showLogs) console.log('FileBrowser: data reactive statement:', data);
@@ -131,7 +164,34 @@
131
164
  /** When set (single-file picker), disables confirm until user picks a different file. */
132
165
  export let activeFileId: string | null = null;
133
166
  export let showAddToEditor = false; // Toggle visibility of "Add to Editor" functionality
134
- export let addToEditorLabel = 'Add to Editor';
167
+ /** The text of the button that hands the picked files to the page. Default: the message "action.addToEditor". */
168
+ export let addToEditorLabel: string | undefined = undefined;
169
+ /**
170
+ * The language of the File Browser: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers, dates and
171
+ * file sizes are written. Default "en". The words themselves come from `messages`.
172
+ */
173
+ export let locale: string | undefined = undefined;
174
+ /**
175
+ * The page's own words: any of the keys of FILE_BROWSER_MESSAGES (see the README, "Languages"). A key left out keeps
176
+ * its English text. Can change while the File Browser is open.
177
+ */
178
+ export let messages: MessageOverrides | null = null;
179
+ /**
180
+ * Which way the File Browser is read: "ltr" or "rtl". The page that puts it on screen sets `dir` on an element
181
+ * around it, and the browser turns the layout around. This prop says the same to the parts that wrap a library that
182
+ * writes a `dir` of its own (the scroll areas, the menus, the toaster) and to the code that follows the reading
183
+ * direction (the arrow keys of the file preview). It is NOT worked out from `locale`: a File Browser inside an editor
184
+ * that is laid out left to right can speak Arabic and still be left to right. Left out, the File Browser is read the way
185
+ * the screen around it is (a File Browser inside the composition editor turns around with it, whatever the page's
186
+ * `locale`), and left to right when nothing around it says. Can change while the File Browser is open.
187
+ */
188
+ export let dir: TextDirection | undefined = undefined;
189
+ /**
190
+ * Draws the pop-ups ("Folder created", "Rename failed" ...) itself, in the language of `locale` and `messages`. They are
191
+ * shown with the design system's `showToast`, which draws into a `<ToasterModal>`: leave this false when the app around
192
+ * the File Browser already renders one (the Widgetic site does, in its layout), true when nothing does.
193
+ */
194
+ export let renderToaster = false;
135
195
  /** When false, skips bundled demo tree (use with Widgetic upload config). */
136
196
  export let useDemoContent = true;
137
197
  /**
@@ -345,6 +405,228 @@
345
405
  // $: controlsVisible = showFilters || showSorting;
346
406
  // console.log("File Browser component: controlsVisible", showFilters, showSorting, controlsVisible);
347
407
 
408
+ /**
409
+ * MEDIA LIBRARY (the host's own storage)
410
+ *
411
+ * With a `mediaLibrary` the File Browser shows one flat list of the host's files and calls the host's functions to
412
+ * list, upload, rename and delete them. Everything stays in memory: the local cache (IndexedDB) and the saved
413
+ * "My uploads" tree are never read or written, and the picked-file selection is only kept in localStorage when
414
+ * `persistSelection` asks for it.
415
+ */
416
+ // Decided when the File Browser is created (see the `mediaLibrary` prop).
417
+ const libraryMode = mediaLibrary !== null && mediaLibrary !== undefined;
418
+ // A library supplies every file, so `data` handed in by the host is not used next to it.
419
+ if (libraryMode) data = null;
420
+
421
+ // The library as the File Browser uses it: every answer checked, every failure a MediaLibraryError.
422
+ let resolvedMediaLibrary: ResolvedMediaLibrary | null = null;
423
+ // Set when `mediaLibrary` is not a usable library: the screen says so instead of showing files.
424
+ let libraryConfigError: MediaLibraryError | null = null;
425
+ if (libraryMode) {
426
+ try {
427
+ resolvedMediaLibrary = resolveMediaLibrary(mediaLibrary);
428
+ } catch (error) {
429
+ libraryConfigError = new MediaLibraryError('FAILED', error instanceof Error ? error.message : 'mediaLibrary is not a media library', { cause: error });
430
+ console.error('[FileBrowser] The mediaLibrary option cannot be used:', error);
431
+ }
432
+ }
433
+
434
+ // What the parts of this File Browser may offer (Rename, Delete, Upload...), shared through Svelte's context.
435
+ const libraryContext: MediaLibraryContext = {
436
+ library: resolvedMediaLibrary,
437
+ capabilities: !libraryMode ? LEGACY_CAPABILITIES : (resolvedMediaLibrary?.capabilities ?? NO_CAPABILITIES),
438
+ };
439
+ provideMediaLibraryContext(libraryContext);
440
+ const libraryCapabilities = libraryContext.capabilities;
441
+
442
+ // The language: the parts below read it from Svelte's context, and follow when the page changes `locale` or `messages`.
443
+ const i18n = provideI18n({ locale, messages });
444
+ const { t } = i18n;
445
+ $: i18n.update({ locale, messages });
446
+ // The reading direction: the parts below read it from Svelte's context, and follow when the page changes `dir`, or, with
447
+ // no `dir`, when the screen around the File Browser turns around.
448
+ const givenDirection = writable<TextDirection | undefined>(dir);
449
+ shareTextDirection(givenDirection);
450
+ $: givenDirection.set(dir);
451
+ // The text of the confirm button: the page's label, or the message of the language in use.
452
+ $: addToEditorText = addToEditorLabel ?? $t('action.addToEditor');
453
+
454
+ // A shared browser must not show the next visitor the previous one's picks, so a library turns this off unless the
455
+ // host asks for it. Selecting still works; the picks just live in memory.
456
+ const selectionIsKept = persistSelection ?? !libraryMode;
457
+ if (isBrowser) {
458
+ persistentSelectStore.configurePersistence(selectionIsKept);
459
+ if (!selectionIsKept) persistentSelectStore.clearSelections('all');
460
+ }
461
+
462
+ // Loading the library: what stopped it, whether a list was already shown when it did, and whether the library
463
+ // has more files than were loaded.
464
+ let libraryLoadError: MediaLibraryError | null = null;
465
+ let libraryShowsPartialList = false;
466
+ let libraryListIsTruncated = false;
467
+ let libraryLoadController: AbortController | null = null;
468
+ // Aborted when the File Browser is closed: ends every call to the library that is still waiting, so a closed
469
+ // File Browser does not touch the (page-wide) file list of the next one.
470
+ const libraryActionsController = new AbortController();
471
+
472
+ /** Tells the host about a problem with its library, in the form `{ message, code, action }`. */
473
+ function reportLibraryError(error: MediaLibraryError, action: 'setup' | 'load' | 'upload' | 'rename' | 'delete') {
474
+ dispatch('error', { message: error.message, code: error.code, action });
475
+ }
476
+
477
+ /**
478
+ * Reads the library into the grid, page by page. The first page ends the loading screen and the rest is added as
479
+ * it arrives. If the first page fails the screen shows the error with "Try again"; if a later page fails what was
480
+ * loaded stays and a notice says the list is incomplete.
481
+ */
482
+ async function loadFromLibrary(): Promise<void> {
483
+ const library = resolvedMediaLibrary;
484
+ if (!library) return;
485
+
486
+ // A new load replaces one that is still running (the visitor pressed "Try again").
487
+ libraryLoadController?.abort();
488
+ const controller = new AbortController();
489
+ libraryLoadController = controller;
490
+ libraryLoadError = null;
491
+ libraryShowsPartialList = false;
492
+ libraryListIsTruncated = false;
493
+ isLoading = true;
494
+
495
+ let viewStarted = false;
496
+ const showLibraryFiles = (files: FileSystemItem[]) => {
497
+ if (controller.signal.aborted) return;
498
+ if (!viewStarted) {
499
+ viewStarted = true;
500
+ // `data` is what init() builds the view from; that also ends the loading screen.
501
+ data = { basePath: '', root: createLibraryRoot(files) };
502
+ } else {
503
+ fileStore.update((store) => ({ ...store, root: appendNewFiles(store.root, files) }));
504
+ }
505
+ };
506
+
507
+ try {
508
+ const loaded = await loadLibraryPages(library, { signal: controller.signal, onPage: (files) => showLibraryFiles(files) });
509
+ if (controller.signal.aborted) return;
510
+ // An empty library never delivered a page of files.
511
+ if (!viewStarted) showLibraryFiles([]);
512
+ libraryListIsTruncated = loaded.truncated;
513
+ if (loaded.failure) {
514
+ libraryLoadError = loaded.failure;
515
+ libraryShowsPartialList = loaded.items.length > 0;
516
+ reportLibraryError(loaded.failure, 'load');
517
+ }
518
+ } catch (error) {
519
+ // Only a load this File Browser cancelled itself (closed, or replaced by "Try again") is silent.
520
+ if (controller.signal.aborted) return;
521
+ const failure = toMediaLibraryError(error, 'Could not load the files', 'libraryError.loadFailed');
522
+ console.error('[FileBrowser] Could not load the media library:', failure);
523
+ libraryLoadError = failure;
524
+ // Ends the loading screen; the error is shown instead of the grid.
525
+ if (!viewStarted) showLibraryFiles([]);
526
+ reportLibraryError(failure, 'load');
527
+ } finally {
528
+ if (libraryLoadController === controller) libraryLoadController = null;
529
+ }
530
+ }
531
+
532
+ /** The "Try again" button: reads the whole library again. */
533
+ function reloadLibrary() {
534
+ void loadFromLibrary();
535
+ }
536
+
537
+ /**
538
+ * Renames a file in the host's library and then in the list: the list changes only after the library said yes.
539
+ * Resolves `false` when there was nothing to change; throws a MediaLibraryError when the library refuses.
540
+ */
541
+ async function renameInLibrary(itemId: string, newName: string): Promise<boolean> {
542
+ const library = resolvedMediaLibrary;
543
+ if (!library?.rename) throw new MediaLibraryError('NOT_SUPPORTED', 'This media library does not allow renaming files', { messageKey: 'libraryError.renameNotAllowed' });
544
+ const item = findItemById(itemId);
545
+ if (!item) throw new MediaLibraryError('NOT_FOUND', 'The file is no longer in the list', { messageKey: 'libraryError.fileGone' });
546
+
547
+ const typedName = newName.trim();
548
+ if (typedName === '') return false;
549
+ // A file keeps its extension, as everywhere else in the File Browser.
550
+ const finalName = item.type === 'file' ? getRenamedFileName(item.name, typedName) : typedName;
551
+ if (finalName === item.name) return false;
552
+
553
+ const renamedFile = await library.rename({ id: itemId, name: finalName, signal: libraryActionsController.signal });
554
+ // The File Browser was closed while the library was working: its list is no longer ours to change.
555
+ if (libraryActionsController.signal.aborted) return false;
556
+
557
+ // The library may answer with the file as it is now (it can change the address or the id). When it only says
558
+ // "done", the file stays as it was and takes the new name.
559
+ const updatedFile: FileSystemItem = renamedFile ?? { ...item, name: finalName, modified: new Date().toISOString() };
560
+ fileStore.update((store) => ({ ...store, root: replaceFile(store.root, itemId, updatedFile) }));
561
+ selectedFiles.update((files) => files.map((file) => (file.id === itemId ? updatedFile : file)));
562
+ return true;
563
+ }
564
+
565
+ /**
566
+ * Deletes a file in the host's library and then from the list. Resolves `true` when it is gone; throws a
567
+ * MediaLibraryError when the library refuses.
568
+ */
569
+ async function deleteFromLibrary(item: FileSystemItem): Promise<boolean> {
570
+ const library = resolvedMediaLibrary;
571
+ if (!library?.remove) throw new MediaLibraryError('NOT_SUPPORTED', 'This media library does not allow deleting files', { messageKey: 'libraryError.deleteNotAllowed' });
572
+
573
+ await library.remove({ id: item.id, signal: libraryActionsController.signal });
574
+ // The File Browser was closed while the library was working: its list is no longer ours to change.
575
+ if (libraryActionsController.signal.aborted) throw new MediaLibraryError('ABORTED', 'The File Browser was closed');
576
+
577
+ fileStore.update((store) => ({ ...store, root: removeFiles(store.root, new Set([item.id])) }));
578
+ selectedFiles.update((files) => files.filter((file) => file.id !== item.id));
579
+ return true;
580
+ }
581
+
582
+ /** Shows a file the library just stored, and brings it into view. */
583
+ function addUploadedFileToLibraryList(file: FileSystemItem) {
584
+ fileStore.update((store) => ({ ...store, root: upsertFile(store.root, file) }));
585
+ // Wait for the grid to draw the new file, then scroll to it and flash it, as for any upload.
586
+ setTimeout(() => {
587
+ scrollItemIntoView(file.id);
588
+ const itemElement = findItemElement(file.id);
589
+ if (itemElement) {
590
+ itemElement.classList.add('wave-goodbye');
591
+ setTimeout(() => itemElement.classList.remove('wave-goodbye'), 600);
592
+ }
593
+ }, 100);
594
+ }
595
+
596
+ /** An upload failed (the uploader already shows the failed row). Logged as always; a media library's host is told too. */
597
+ function handleUploadError(event: CustomEvent<{ message: string; file?: string; code?: MediaLibraryErrorCode }>) {
598
+ console.error('Upload error:', event.detail);
599
+ if (libraryMode) {
600
+ dispatch('error', { message: event.detail.message, code: event.detail.code ?? 'FAILED', action: 'upload', file: event.detail.file });
601
+ }
602
+ }
603
+
604
+ /** Finds the element of an item inside this File Browser (also when it sits inside a shadow root). */
605
+ function findItemElement(itemId: string): HTMLElement | null {
606
+ // An id comes from the host's library and may hold any character, so it is escaped before it joins a selector.
607
+ const selector = `[data-item-id="${typeof CSS !== 'undefined' ? CSS.escape(itemId) : itemId.replace(/["\\]/g, '\\$&')}"]`;
608
+ return (mainContainer?.querySelector(selector) ?? document.querySelector(selector)) as HTMLElement | null;
609
+ }
610
+
611
+ // A notice above the grid when the list on screen is not the whole library: a later page failed, or the library
612
+ // has more files than the File Browser loads.
613
+ let libraryNotice: { text: string; canRetry: boolean } | null = null;
614
+ $: libraryNotice = libraryMode && !isLoading
615
+ ? libraryLoadError && libraryShowsPartialList
616
+ ? { text: $t('library.partialNotice'), canRetry: true }
617
+ : libraryListIsTruncated
618
+ ? { text: $t('library.truncatedNotice'), canRetry: false }
619
+ : null
620
+ : null;
621
+
622
+ // Shown instead of the grid: the library cannot be used, or its first page could not be read.
623
+ let libraryErrorMessage = '';
624
+ $: libraryErrorMessage = libraryConfigError
625
+ ? $t('library.notSetUp')
626
+ : libraryLoadError && !libraryShowsPartialList
627
+ ? messageForVisitor(libraryLoadError, $t, 'libraryError.loadFailed')
628
+ : '';
629
+
348
630
  /**
349
631
  * LIFE CYCLE HOOKS
350
632
  */
@@ -352,7 +634,8 @@
352
634
  if(showLogs) console.log('FileBrowser onMount instanceId: ', instanceId);
353
635
  // if(showLogs) console.log('FileBrowser onMount start:', performance.now() - startTime, 'ms');
354
636
 
355
- if (enableLocalCache) {
637
+ // A media library keeps its files to itself: the local cache (IndexedDB) is never scoped, read or written for it.
638
+ if (enableLocalCache && !libraryMode) {
356
639
  const existing = getFileBrowserUploadConfig();
357
640
  if (existing?.accessToken) {
358
641
  setFileBrowserUploadConfig({ ...existing, enableLocalCache: true });
@@ -380,9 +663,20 @@
380
663
  }
381
664
  }
382
665
 
666
+ // The host's media library supplies the files; nothing else is loaded.
667
+ if (libraryMode) {
668
+ basePath = '';
669
+ if (libraryConfigError) {
670
+ isLoading = false;
671
+ reportLibraryError(libraryConfigError, 'setup');
672
+ } else {
673
+ // Not awaited: the rest of the setup (breakpoints, listeners) does not wait for the library.
674
+ void loadFromLibrary();
675
+ }
676
+ }
383
677
  // load demo content from localStorage if no data is passed
384
678
  // if(showLogs) console.log('FileBrowser onMount data & useDemoContent: ', data, useDemoContent);
385
- if (!data) {
679
+ else if (!data) {
386
680
  const uploadConfig = getFileBrowserUploadConfig();
387
681
  const widgeticLibraryMode = Boolean(
388
682
  uploadConfig?.accessToken && uploadConfig?.apiBasePath,
@@ -406,7 +700,7 @@
406
700
  console.warn('[FileBrowser] Upload hydration failed, using local cache:', hydrateError);
407
701
  }
408
702
  }
409
- data = await createUserUploadsFileSystemRoot(files);
703
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
410
704
  basePath = '';
411
705
  if (showLogs) {
412
706
  // console.log('[FileBrowser] Widgetic library mode — user uploads only');
@@ -443,8 +737,9 @@
443
737
  // Add event listener for window resize
444
738
  window.addEventListener('resize', handleResize);
445
739
 
446
- // Set up window key handler
447
- window.addEventListener('keydown', handleKeyDown);
740
+ // Set up window key handler. With a media library the File Browser sits inside the host's page, where Ctrl+A and
741
+ // Backspace belong to the host: it then listens only to keys pressed inside its own container.
742
+ if (!libraryMode) window.addEventListener('keydown', handleKeyDown);
448
743
  window.addEventListener('widgetic:file-browser-command', handleFileBrowserCommand);
449
744
  publishFileBrowserNav();
450
745
 
@@ -478,8 +773,9 @@
478
773
  // set base path
479
774
  data.basePath = basePath;
480
775
 
481
- // save as demo content if not already saved
482
- if(!getFromStorage(demoContentKey, null)) {
776
+ // save as demo content if not already saved (never for a media library: its files are not demo content, and
777
+ // the visitor's file list must not be copied into localStorage)
778
+ if(!libraryMode && !getFromStorage(demoContentKey, null)) {
483
779
  // console.log('FileBrowser: saving demo content to localStorage:', data);
484
780
  saveToStorage(demoContentKey, data);
485
781
  }
@@ -502,8 +798,8 @@
502
798
  // Store the path we want to navigate to after loading
503
799
  let pathToNavigate: string[] = [];
504
800
 
505
- // Check if we have a stored path to restore
506
- if (persistHistory) {
801
+ // Check if we have a stored path to restore (a media library has no folders to go back to)
802
+ if (persistHistory && !libraryMode) {
507
803
  const storedState = getStoredState(instanceId);
508
804
  if (storedState) {
509
805
  pathToNavigate = storedState.pathsArray[storedState.currentIndex] || [];
@@ -550,6 +846,11 @@
550
846
  // onDestroy: cleanup event listener on component destroy
551
847
  onDestroy(() => {
552
848
 
849
+ // Stop waiting for the media library. The file list is shared by the whole page, so an answer that arrives after
850
+ // this File Browser is gone must not be written into the list of the next one.
851
+ libraryLoadController?.abort();
852
+ libraryActionsController.abort();
853
+
553
854
  // check if browser environment is available
554
855
  if (!isBrowser) return;
555
856
 
@@ -731,7 +1032,7 @@
731
1032
  */
732
1033
  function fileMatchesFilter(file: FileSystemItem): boolean {
733
1034
  if (filter === 'all') return true;
734
- return getFileType(file.url || file.name) === filter;
1035
+ return getFileTypeOf(file) === filter;
735
1036
  }
736
1037
 
737
1038
  /**
@@ -941,7 +1242,7 @@
941
1242
  // Filter by type
942
1243
  const typeFilteredFiles = allFiles.filter(file => {
943
1244
  if (filter === 'all') return true;
944
- const fileType = getFileType(file.url || file.name);
1245
+ const fileType = getFileTypeOf(file);
945
1246
  return fileType === filter;
946
1247
  });
947
1248
  if(showLogs && showRecentFilesLogs) console.log('Files after type filtering:', typeFilteredFiles.length);
@@ -975,6 +1276,25 @@
975
1276
  return resolveFileItemUrl(item, storeBasePath);
976
1277
  }
977
1278
 
1279
+ /**
1280
+ * The file as the grid draws it: its address and thumbnail address resolved against the base path.
1281
+ * A Widgetic upload always has a picture to show, so its thumbnail defaults to the file itself.
1282
+ * A media library file only has a thumbnail when the library sent one. Without it the grid draws the
1283
+ * file-type icon (or the file itself when it is a picture) instead of loading a PDF as a picture,
1284
+ * which would fail and show the file as "missing".
1285
+ */
1286
+ function toGridFileItem(item: FileSystemItem): FileSystemItem {
1287
+ const storeBasePath = $fileStore?.basePath ?? basePath;
1288
+ return {
1289
+ ...item,
1290
+ url: getCorrectFileUrl(item),
1291
+ thumbnail:
1292
+ libraryMode && !item.thumbnail
1293
+ ? undefined
1294
+ : resolveFileItemUrl({ ...item, url: item.thumbnail || item.url }, storeBasePath),
1295
+ };
1296
+ }
1297
+
978
1298
  /**
979
1299
  * Type guard for FileSystemItem
980
1300
  * Ensures safe type checking for file operations
@@ -1105,34 +1425,38 @@
1105
1425
  // console.log('call showToast method:', showToast);
1106
1426
 
1107
1427
  // Show initial toast notification
1108
- showToast('success', `Renaming "${oldName}"...`, {
1109
- description: 'This will happen in the background',
1428
+ showToast('success', $t('toast.rename.started', { name: oldName }), {
1429
+ description: $t('toast.inBackground'),
1110
1430
  // duration: 1500
1111
1431
  });
1112
1432
 
1113
- // Perform the rename operation
1114
- renameItem(itemId, newName)
1433
+ // Perform the rename operation (through the host's media library when there is one)
1434
+ (libraryMode ? renameInLibrary(itemId, newName) : renameItem(itemId, newName))
1115
1435
  .then(success => {
1436
+ // The File Browser was closed while the library was working: there is no one to tell.
1437
+ if (libraryMode && libraryActionsController.signal.aborted) return;
1116
1438
  if (success) {
1117
- showToast('success', 'Item renamed', {
1118
- description: `Successfully renamed "${oldName}" to "${newName}"`,
1439
+ showToast('success', $t('toast.rename.done'), {
1440
+ description: $t('toast.rename.doneDetail', { oldName, newName }),
1119
1441
  });
1120
1442
  } else {
1121
- showToast('error', 'Rename failed', {
1122
- description: 'No changes were made',
1443
+ showToast('error', $t('toast.rename.failed'), {
1444
+ description: $t('toast.rename.noChange'),
1123
1445
  });
1124
1446
  }
1125
1447
  })
1126
1448
  .catch(error => {
1449
+ if (libraryMode && (libraryActionsController.signal.aborted || isCancellation(error))) return;
1127
1450
  console.error('Error during rename operation:', error);
1128
- showToast('error', 'Rename failed', {
1129
- description: error instanceof Error ? error.message : 'An unknown error occurred',
1451
+ showToast('error', $t('toast.rename.failed'), {
1452
+ description: messageForVisitor(error, $t, 'toast.rename.unknownError'),
1130
1453
  });
1454
+ if (libraryMode) reportLibraryError(toMediaLibraryError(error, 'Could not rename the file', 'libraryError.renameFailed'), 'rename');
1131
1455
  });
1132
1456
  } else {
1133
1457
  console.error('No valid item selected for rename operation');
1134
- showToast('error', 'Rename failed', {
1135
- description: 'No valid item selected',
1458
+ showToast('error', $t('toast.rename.failed'), {
1459
+ description: $t('toast.rename.noItem'),
1136
1460
  });
1137
1461
  }
1138
1462
  }
@@ -1159,12 +1483,13 @@
1159
1483
  showDeleteConfirmation = false;
1160
1484
 
1161
1485
  // Show initial toast notification
1162
- const initialToastMessage = itemsToDelete.length === 1
1163
- ? `Deleting "${itemsToDelete[0].name}"...`
1164
- : `Deleting ${itemsToDelete.length} items...`;
1486
+ const initialToastMessage = $t('toast.delete.started', {
1487
+ count: itemsToDelete.length,
1488
+ name: itemsToDelete[0]?.name ?? ''
1489
+ });
1165
1490
 
1166
1491
  showToast('success', initialToastMessage, {
1167
- description: 'This will happen in the background',
1492
+ description: $t('toast.inBackground'),
1168
1493
  });
1169
1494
 
1170
1495
  // Process deletions in the background
@@ -1173,11 +1498,13 @@
1173
1498
  let successCount = 0;
1174
1499
  const deletedItems: string[] = [];
1175
1500
  const failedItems: string[] = [];
1501
+ // Why the media library refused, to tell the visitor (only a media library gives reasons)
1502
+ let libraryFailure: MediaLibraryError | null = null;
1176
1503
 
1177
1504
  // Process each item for deletion
1178
1505
  for (const item of itemsToDelete) {
1179
1506
  try {
1180
- const success = await deleteItem(item.id);
1507
+ const success = libraryMode ? await deleteFromLibrary(item) : await deleteItem(item.id);
1181
1508
  if (success) {
1182
1509
  successCount++;
1183
1510
  deletedItems.push(item.name);
@@ -1195,8 +1522,11 @@
1195
1522
  failedItems.push(item.name);
1196
1523
  }
1197
1524
  } catch (itemError) {
1525
+ // The File Browser was closed while the library was working: stop, and tell no one.
1526
+ if (libraryMode && (libraryActionsController.signal.aborted || isCancellation(itemError))) return;
1198
1527
  console.error(`Error deleting ${item.name}:`, itemError);
1199
1528
  failedItems.push(item.name);
1529
+ if (libraryMode) libraryFailure = toMediaLibraryError(itemError, 'Could not delete the file', 'libraryError.deleteFailed');
1200
1530
  }
1201
1531
  }
1202
1532
 
@@ -1209,19 +1539,19 @@
1209
1539
  // Single item deletion
1210
1540
  const isFolder = itemsToDelete.find(item => item.name === deletedItems[0])?.type === 'folder';
1211
1541
  toastMessage = isFolder
1212
- ? `Deleted folder "${deletedItems[0]}"`
1213
- : `Deleted "${deletedItems[0]}"`;
1542
+ ? $t('toast.delete.doneFolder', { name: deletedItems[0] })
1543
+ : $t('toast.delete.doneFile', { name: deletedItems[0] });
1214
1544
  toastDescription = isFolder
1215
- ? 'Folder and its contents were deleted successfully'
1216
- : 'Item was deleted successfully';
1545
+ ? $t('toast.delete.doneFolderDetail')
1546
+ : $t('toast.delete.doneFileDetail');
1217
1547
  } else {
1218
1548
  // Multiple item deletion
1219
- toastMessage = `Deleted ${successCount} items`;
1220
- toastDescription = `${successCount} items were deleted successfully`;
1549
+ toastMessage = $t('toast.delete.doneMany', { count: successCount });
1550
+ toastDescription = $t('toast.delete.doneManyDetail', { count: successCount });
1221
1551
 
1222
1552
  // Add details if small number of items deleted (up to 3)
1223
1553
  if (successCount <= 3) {
1224
- toastDescription = `Deleted: ${deletedItems.join(', ')}`;
1554
+ toastDescription = $t('toast.delete.doneNames', { names: deletedItems.join($t('list.separator')) });
1225
1555
  }
1226
1556
  }
1227
1557
 
@@ -1233,21 +1563,23 @@
1233
1563
  // Show error toast if any deletions failed
1234
1564
  if (failedItems.length > 0) {
1235
1565
  const errorMessage = failedItems.length === 1
1236
- ? `Failed to delete "${failedItems[0]}"`
1237
- : `Failed to delete ${failedItems.length} items`;
1566
+ ? $t('toast.delete.failedOne', { name: failedItems[0] })
1567
+ : $t('toast.delete.failedMany', { count: failedItems.length });
1238
1568
 
1239
1569
  const errorDescription = failedItems.length <= 3
1240
- ? `Failed to delete: ${failedItems.join(', ')}`
1241
- : 'Some items could not be deleted';
1570
+ ? $t('toast.delete.failedNames', { names: failedItems.join($t('list.separator')) })
1571
+ : $t('toast.delete.failedSome');
1242
1572
 
1243
1573
  showToast('error', errorMessage, {
1244
- description: errorDescription,
1574
+ // A media library says why (for example "not allowed"); that is more useful than the names again.
1575
+ description: libraryFailure ? messageForVisitor(libraryFailure, $t) : errorDescription,
1245
1576
  });
1577
+ if (libraryFailure) reportLibraryError(libraryFailure, 'delete');
1246
1578
  }
1247
1579
  } catch (error) {
1248
1580
  console.error('Error deleting items:', error);
1249
- showToast('error', 'Failed to delete items', {
1250
- description: error instanceof Error ? error.message : 'Unknown error occurred',
1581
+ showToast('error', $t('toast.delete.failedAll'), {
1582
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1251
1583
  });
1252
1584
  }
1253
1585
  }, 100); // Small delay to ensure UI updates first
@@ -1258,6 +1590,22 @@
1258
1590
  return Boolean(uploadConfig?.accessToken && uploadConfig?.apiBasePath) || !useDemoContent;
1259
1591
  }
1260
1592
 
1593
+ // The built-in "My uploads" folder is named in the visitor's language, and follows a change of language.
1594
+ function nameBuiltInFolder(folderName: string) {
1595
+ fileStore.update((store) => {
1596
+ const builtInFolder = store.root?.children?.find((child) => child.type === 'folder' && child.id === 'folder_my_uploads');
1597
+ if (!store.root || !builtInFolder || builtInFolder.name === folderName) return store;
1598
+ return {
1599
+ ...store,
1600
+ root: {
1601
+ ...store.root,
1602
+ children: (store.root.children ?? []).map((child) => (child === builtInFolder ? { ...child, name: folderName } : child)),
1603
+ },
1604
+ };
1605
+ });
1606
+ }
1607
+ $: if (!libraryMode) nameBuiltInFolder($t('library.defaultLabel'));
1608
+
1261
1609
  function persistMyUploadsTree() {
1262
1610
  const store = get(fileStore);
1263
1611
  const myUploads = store.root?.children?.find((c) => c.id === 'folder_my_uploads');
@@ -1291,8 +1639,8 @@
1291
1639
 
1292
1640
  persistMyUploadsTree();
1293
1641
  showNewFolderDialog = false;
1294
- showToast('success', 'Folder created', {
1295
- description: `Created folder "${folderName}"`,
1642
+ showToast('success', $t('toast.folder.created'), {
1643
+ description: $t('toast.folder.createdDetail', { name: folderName }),
1296
1644
  });
1297
1645
  }
1298
1646
 
@@ -1318,7 +1666,8 @@
1318
1666
 
1319
1667
  if (!response.ok) {
1320
1668
  const error = await response.json();
1321
- throw new Error(error.message || 'Failed to create folder');
1669
+ // 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
1670
+ throw new MediaLibraryError('FAILED', error.message || 'Failed to create folder', error.message ? {} : { messageKey: 'toast.folder.failed' });
1322
1671
  }
1323
1672
 
1324
1673
  const { folder } = await response.json();
@@ -1343,13 +1692,13 @@
1343
1692
  });
1344
1693
 
1345
1694
  showNewFolderDialog = false;
1346
- showToast('success', 'Folder created', {
1347
- description: `Created folder "${folderName}"`,
1695
+ showToast('success', $t('toast.folder.created'), {
1696
+ description: $t('toast.folder.createdDetail', { name: folderName }),
1348
1697
  });
1349
1698
  } catch (error) {
1350
1699
  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',
1700
+ showToast('error', $t('toast.folder.failed'), {
1701
+ description: messageForVisitor(error, $t, 'toast.unknownError'),
1353
1702
  });
1354
1703
  }
1355
1704
  }
@@ -1383,7 +1732,7 @@
1383
1732
  // });
1384
1733
 
1385
1734
  // Backspace key handler
1386
- if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused() && !$isModalOpen) {
1735
+ if (event.key === 'Backspace' && currentPath.length > 0 && !isInputFocused(event) && !$isModalOpen) {
1387
1736
  event.preventDefault();
1388
1737
  event.stopPropagation();
1389
1738
 
@@ -1398,10 +1747,12 @@
1398
1747
  /**
1399
1748
  * Checks if an input element is currently focused
1400
1749
  * Prevents unintended backspace navigation when typing
1750
+ * @param event The key event being handled. Inside a shadow root `document.activeElement` is the shadow host, not
1751
+ * the field being typed in, so the field is taken from the event when there is one.
1401
1752
  * @returns boolean indicating if an input element has focus
1402
1753
  */
1403
- function isInputFocused() {
1404
- const activeElement = document.activeElement;
1754
+ function isInputFocused(event?: Event) {
1755
+ const activeElement = (event?.composedPath?.()[0] as Element | undefined) ?? document.activeElement;
1405
1756
  return (
1406
1757
  activeElement instanceof HTMLInputElement ||
1407
1758
  activeElement instanceof HTMLTextAreaElement ||
@@ -1440,7 +1791,7 @@
1440
1791
  if (item.type === 'folder') {
1441
1792
  return getFolderIcon(item, filter);
1442
1793
  }
1443
- const fileType = getFileType(item.url || item.name);
1794
+ const fileType = getFileTypeOf(item);
1444
1795
 
1445
1796
  if (fileType === 'video' && item.url) {
1446
1797
  // For video files, construct the thumbnail path by replacing the video extension with .png
@@ -1456,7 +1807,7 @@
1456
1807
  return getFileIcon(item.name);
1457
1808
  }
1458
1809
 
1459
- $: fileTypesText = formatFileTypesForDisplay();
1810
+ $: fileTypesText = formatFileTypesForDisplay($t);
1460
1811
 
1461
1812
  function handleModalClose() {
1462
1813
  showModal = false;
@@ -1472,6 +1823,12 @@
1472
1823
  */
1473
1824
  function handleFileUploaded(event: CustomEvent) {
1474
1825
  const { file, success } = event.detail;
1826
+
1827
+ // A media library keeps the file itself: the list only shows what it stored. Nothing is saved on this device.
1828
+ if (libraryMode) {
1829
+ if (success && file && !libraryActionsController.signal.aborted) addUploadedFileToLibraryList(file);
1830
+ return;
1831
+ }
1475
1832
 
1476
1833
  if (success && file) {
1477
1834
  const uploadedFile = {
@@ -1567,7 +1924,7 @@
1567
1924
  // Scroll to and highlight the new file after a short delay to ensure rendering
1568
1925
  setTimeout(() => {
1569
1926
  scrollItemIntoView(file.id);
1570
- const itemElement = document.querySelector(`[data-item-id="${file.id}"]`);
1927
+ const itemElement = findItemElement(file.id);
1571
1928
  if (itemElement) {
1572
1929
  itemElement.classList.add('wave-goodbye');
1573
1930
  setTimeout(() => {
@@ -1671,8 +2028,8 @@
1671
2028
  // if(showLogs) console.log('Attempting to scroll item into view:', itemId);
1672
2029
 
1673
2030
  requestAnimationFrame(() => {
1674
- const itemElement = document.querySelector(`[data-item-id="${itemId}"]`) as HTMLElement;
1675
- const scrollableArea = scrollContainer || (document.querySelector('.scroll-area-container') as HTMLElement);
2031
+ const itemElement = findItemElement(itemId);
2032
+ const scrollableArea = scrollContainer || (mainContainer?.querySelector('.scroll-area-container') as HTMLElement | null) || (document.querySelector('.scroll-area-container') as HTMLElement);
1676
2033
 
1677
2034
  if (itemElement && scrollableArea) {
1678
2035
  // Handle animation first if it's a goodbye animation
@@ -1902,8 +2259,10 @@
1902
2259
  return;
1903
2260
  }
1904
2261
 
1905
- // Focus the container when clicking anywhere inside it
1906
- mainContainer?.focus();
2262
+ // Focus the container when clicking anywhere inside it. Without preventScroll the browser scrolls the whole page
2263
+ // to bring the container into view when it is only partly visible, which moves the control under the pointer
2264
+ // between mousedown and mouseup (the click is lost) and scrolls a host page that embeds the File Browser.
2265
+ mainContainer?.focus({ preventScroll: true });
1907
2266
  }
1908
2267
 
1909
2268
  // Update the keyboard shortcuts handler to batch updates
@@ -1922,10 +2281,12 @@
1922
2281
  if ((event.metaKey || event.ctrlKey) && event.key === 'a') {
1923
2282
  // console.log('FileBrowser Handle CMD/CTRL + A:', event, $isModalOpen);
1924
2283
 
2284
+ // Typing in a field: Ctrl+A selects the field's text, as it does everywhere else.
2285
+ if (isInputFocused(event)) return;
2286
+
1925
2287
  event.preventDefault();
1926
2288
  event.stopPropagation();
1927
2289
 
1928
- if (isInputFocused()) return;
1929
2290
  if (maxSelections === 1) return;
1930
2291
 
1931
2292
  // Clear any text selection
@@ -2030,14 +2391,14 @@
2030
2391
  currentPath = newPath;
2031
2392
  } else {
2032
2393
  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',
2394
+ showToast('error', $t('toast.navigation.failed'), {
2395
+ description: $t('toast.navigation.noFolder'),
2035
2396
  });
2036
2397
  }
2037
2398
  } catch (error) {
2038
2399
  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',
2400
+ showToast('error', $t('toast.navigation.failed'), {
2401
+ description: $t('toast.navigation.error'),
2041
2402
  });
2042
2403
  }
2043
2404
  }
@@ -2061,22 +2422,16 @@
2061
2422
  }
2062
2423
 
2063
2424
  // 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
2425
  // 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' }
2426
+ let filterOptions: Array<{ value: FileFilterType; label: string }> = [];
2427
+ $: filterOptions = [
2428
+ { value: 'all', label: $t('filterOption.all') },
2429
+ { value: 'image', label: $t('filterOption.image') },
2430
+ { value: 'video', label: $t('filterOption.video') },
2431
+ { value: 'document', label: $t('filterOption.document') },
2432
+ { value: 'audio', label: $t('filterOption.audio') },
2433
+ { value: 'font', label: $t('filterOption.font') },
2434
+ { value: 'svg', label: $t('filterOption.svg') }
2080
2435
  ];
2081
2436
 
2082
2437
  // Add these state variables
@@ -2122,7 +2477,7 @@
2122
2477
 
2123
2478
  // Find the files that match the new filter type
2124
2479
  const matchingFiles = allFiles.filter(file =>
2125
- getFileType(file.url || file.name) === newFilter
2480
+ getFileTypeOf(file) === newFilter
2126
2481
  );
2127
2482
 
2128
2483
  // Get IDs of matching files that were previously selected
@@ -2150,7 +2505,7 @@
2150
2505
 
2151
2506
  // Find the files that match the new filter type
2152
2507
  const matchingFiles = allFiles.filter(file =>
2153
- getFileType(file.url || file.name) === newFilter
2508
+ getFileTypeOf(file) === newFilter
2154
2509
  );
2155
2510
 
2156
2511
  // Get selected files from the "all" filter (which should be the master list)
@@ -2316,7 +2671,8 @@ mainGridClass="app-main-grid"
2316
2671
  canGoBack={$canGoBackStore}
2317
2672
  canGoForward={$canGoForwardStore}
2318
2673
  on:toggleSelectedFiles={(e : CustomEvent) => allowSelecting && toggleModal()}
2319
- showBreadcrumbs={showBreadcrumbs}
2674
+ showBreadcrumbs={showBreadcrumbs && !libraryMode}
2675
+ title={libraryMode ? (resolvedMediaLibrary?.hasOwnLabel ? resolvedMediaLibrary.label : $t('library.defaultLabel')) : ''}
2320
2676
  />
2321
2677
 
2322
2678
  <!-- FILE BROWSER CONTROLS -->
@@ -2326,7 +2682,7 @@ mainGridClass="app-main-grid"
2326
2682
  <!-- svelte-ignore a11y_click_events_have_key_events -->
2327
2683
  <div onclick={handleSearch} class="w-full cursor-pointer">
2328
2684
  <SearchInput
2329
- placeholder="Search..."
2685
+ placeholder={$t('search.placeholder')}
2330
2686
  value=""
2331
2687
  containerClass="w-full"
2332
2688
  onInput={() => {}}
@@ -2352,14 +2708,14 @@ mainGridClass="app-main-grid"
2352
2708
  filterDropdownOpen = !filterDropdownOpen;
2353
2709
  }}
2354
2710
  >
2355
- <span>Filter by {formatFilterType(filter)}</span>
2356
- <IconAdjustmentsHorizontal class="h-5 w-5 text-[hsl(var(--grey5))] ml-1 transition-colors duration-200 group-hover:text-[hsl(var(--grey7))]" />
2711
+ <span>{$t('filter.by', { type: $t(`filterName.${filter}`) })}</span>
2712
+ <IconAdjustmentsHorizontal class="h-5 w-5 text-[hsl(var(--grey5))] ms-1 transition-colors duration-200 group-hover:text-[hsl(var(--grey7))]" />
2357
2713
  </button>
2358
2714
 
2359
2715
  <!-- Filter Dropdown -->
2360
2716
  {#if filterDropdownOpen}
2361
2717
  <div
2362
- class="filter-dropdown absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none z-50"
2718
+ class="filter-dropdown absolute end-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none z-50"
2363
2719
  role="menu"
2364
2720
  aria-orientation="vertical"
2365
2721
  aria-labelledby="filter-menu"
@@ -2392,9 +2748,9 @@ mainGridClass="app-main-grid"
2392
2748
  class="bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm"
2393
2749
  bind:value={$sortCriteria}
2394
2750
  >
2395
- <option value="name">Name</option>
2396
- <option value="date">Date</option>
2397
- <option value="size">Size</option>
2751
+ <option value="name">{$t('sort.name')}</option>
2752
+ <option value="date">{$t('sort.date')}</option>
2753
+ <option value="size">{$t('sort.size')}</option>
2398
2754
  </select>
2399
2755
 
2400
2756
  <!-- Sort Direction Button -->
@@ -2412,14 +2768,24 @@ mainGridClass="app-main-grid"
2412
2768
  </div>
2413
2769
 
2414
2770
  <!-- FILE BROWSER CONTENT -->
2415
- <div class="file-browser-content flex min-h-0 flex-col grow mr-[4px] overflow-hidden relative widgetic-colors">
2771
+ <div class="file-browser-content flex min-h-0 flex-col grow me-[4px] overflow-hidden relative widgetic-colors">
2772
+ <!-- Media library notice: the list on screen is not the whole library -->
2773
+ {#if libraryNotice}
2774
+ <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">
2775
+ <span>{libraryNotice.text}</span>
2776
+ {#if libraryNotice.canRetry}
2777
+ <button type="button" class="library-notice-retry shrink-0 underline" onclick={reloadLibrary}>{$t('action.tryAgain')}</button>
2778
+ {/if}
2779
+ </div>
2780
+ {/if}
2781
+
2416
2782
  <!-- Loader Container -->
2417
2783
  {#if isLoading}
2418
2784
  <div class="loader-container p-6">
2419
2785
  <div class="grid grid-cols-3 gap-8">
2420
2786
  {#each Array(skeletonCount) as _}
2421
2787
  <div class="flex items-start">
2422
- <LoadingSkeleton width="62px" height="54px" className="mr-4" />
2788
+ <LoadingSkeleton width="62px" height="54px" className="me-4" />
2423
2789
  <div class="grow">
2424
2790
  <LoadingSkeleton width="100%" height="20px" className="mb-2" />
2425
2791
  <LoadingSkeleton width="60%" height="16px" />
@@ -2429,11 +2795,25 @@ mainGridClass="app-main-grid"
2429
2795
  </div>
2430
2796
  </div>
2431
2797
 
2798
+ <!-- Media library error: it cannot be used, or its first page could not be read -->
2799
+ {:else if libraryErrorMessage}
2800
+ <div class="library-error-container relative min-h-0 flex-1" role="alert">
2801
+ <div class="empty-state-wrapper w-full flex justify-center items-center">
2802
+ <EmptyState message={libraryErrorMessage} height="auto">
2803
+ <svelte:fragment slot="action">
2804
+ {#if !libraryConfigError}
2805
+ <Button variant="outline" size="sm" onclick={reloadLibrary}>{$t('action.tryAgain')}</Button>
2806
+ {/if}
2807
+ </svelte:fragment>
2808
+ </EmptyState>
2809
+ </div>
2810
+ </div>
2811
+
2432
2812
  <!-- Files container -->
2433
2813
  {:else}
2434
2814
  <!-- Main content container with Files Inside --> <!-- {!showAddToEditor ? 'overflow-y-auto px-6' : ''} -->
2435
2815
  <WScrollArea class="scroll-area-container min-h-0 flex-1" bind:element={scrollContainer} type="always">
2436
- <div class="main-content-container flex flex-col p-6 pr-1" bind:this={contentContainer}>
2816
+ <div class="main-content-container flex flex-col p-6 pe-1" bind:this={contentContainer}>
2437
2817
 
2438
2818
  <!-- Drag Select for selecting files -->
2439
2819
  {#if allowSelecting}
@@ -2471,7 +2851,7 @@ mainGridClass="app-main-grid"
2471
2851
  <!-- Files GRID List(VirtualList) -->
2472
2852
  <VirtualList class="content-container grow"
2473
2853
  {scrollContainer}
2474
- items={[{ type: 'new-folder' }, ...sortedFilteredFiles]}
2854
+ items={libraryCapabilities.folders ? [{ type: 'new-folder' }, ...sortedFilteredFiles] : sortedFilteredFiles}
2475
2855
  itemHeight={GRID_ITEM_HEIGHT}
2476
2856
  columns={mainContainerWidth <= mobileBreakpoint ? 2 :
2477
2857
  mainContainerWidth <= tabletBreakpoint ? 3 : 4}
@@ -2500,14 +2880,7 @@ mainGridClass="app-main-grid"
2500
2880
  />
2501
2881
  {:else}
2502
2882
  <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
- }}
2883
+ item={toGridFileItem(item)}
2511
2884
  selected={allowSelecting && currentSelections.some(f => f.id === item.id)}
2512
2885
  {allowSelecting}
2513
2886
  gridLayout={true}
@@ -2520,8 +2893,8 @@ mainGridClass="app-main-grid"
2520
2893
  </div>
2521
2894
  </VirtualList>
2522
2895
 
2523
- <!-- Recent Files -->
2524
- {#if currentPath.length === 0 && recentFiles.length > 0 && mainContainerWidth > tabletBreakpoint}
2896
+ <!-- Recent Files (a media library is one flat list, so they would only repeat the grid) -->
2897
+ {#if !libraryMode && currentPath.length === 0 && recentFiles.length > 0 && mainContainerWidth > tabletBreakpoint}
2525
2898
  <RecentFiles class="recent-files-container"
2526
2899
  {recentFiles}
2527
2900
  selectedFiles={allSelectedFiles}
@@ -2539,14 +2912,16 @@ mainGridClass="app-main-grid"
2539
2912
  <div class="empty-content-container">
2540
2913
 
2541
2914
  <!-- 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>
2915
+ {#if libraryCapabilities.folders}
2916
+ <div class="grid grid-cols-3 gap-8 relative z-20 pointer-events-auto">
2917
+ <NewFolderButton on:click={handleNewFolderClick} />
2918
+ </div>
2919
+ {/if}
2545
2920
 
2546
2921
  <!-- Empty State Container -->
2547
2922
  <div class="empty-state-wrapper w-full flex justify-center items-center">
2548
2923
  <EmptyState
2549
- message="No files in this folder!"
2924
+ message={libraryMode ? (filter === 'all' ? $t('empty.library') : $t('empty.libraryFiltered')) : $t('empty.folder')}
2550
2925
  height="auto"
2551
2926
  >
2552
2927
  </EmptyState>
@@ -2570,7 +2945,7 @@ mainGridClass="app-main-grid"
2570
2945
  filter={filter}
2571
2946
  allowSelecting={allowSelecting}
2572
2947
  {showAddToEditor}
2573
- {addToEditorLabel}
2948
+ addToEditorLabel={addToEditorText}
2574
2949
  {activeFileId}
2575
2950
  {maxSelections}
2576
2951
  compact={mainContainerWidth > 0 && mainContainerWidth < 700}
@@ -2587,8 +2962,8 @@ mainGridClass="app-main-grid"
2587
2962
  </div>
2588
2963
  {/if}
2589
2964
 
2590
- <!-- FILE UPLOADER -->
2591
- {#if !isLoading}
2965
+ <!-- FILE UPLOADER (a media library without upload has nothing to upload to) -->
2966
+ {#if !isLoading && libraryCapabilities.upload}
2592
2967
  <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
2968
  <FileUploader
2594
2969
  bind:this={fileUploaderComponent}
@@ -2597,7 +2972,7 @@ mainGridClass="app-main-grid"
2597
2972
  {filter}
2598
2973
  portalTarget={mainContainer}
2599
2974
  on:fileUploaded={handleFileUploaded}
2600
- on:error={(event: CustomEvent<{message: string}>) => console.error('Upload error:', event.detail)}
2975
+ on:error={handleUploadError}
2601
2976
  bind:dragActive
2602
2977
  bind:dragInvalid
2603
2978
  bind:hasValidFiles
@@ -2617,7 +2992,7 @@ mainGridClass="app-main-grid"
2617
2992
  target={rootContainerClass}
2618
2993
  allFiles={getAllFiles($fileStore.root)}
2619
2994
  {showAddToEditor}
2620
- {addToEditorLabel}
2995
+ addToEditorLabel={addToEditorText}
2621
2996
  on:close={handleModalClose}
2622
2997
  on:fileUploaded={handleFileUploaded}
2623
2998
  on:navigate={handleSearchNavigate}
@@ -2654,8 +3029,19 @@ mainGridClass="app-main-grid"
2654
3029
  itemName={selectedItem?.name ?? ''}
2655
3030
  itemType={selectedItem?.type === 'folder' ? 'folder' : 'file'}
2656
3031
  itemId={selectedItem?.id ?? ''}
2657
- confirmLabel="Rename"
2658
- cancelLabel="Cancel"
3032
+ placeholder={selectedItem?.type === 'folder' ? $t('dialog.rename.folderPlaceholder') : $t('dialog.rename.filePlaceholder')}
3033
+ confirmLabel={$t('action.rename')}
3034
+ cancelLabel={$t('action.cancel')}
3035
+ closeLabel={$t('dialog.close')}
3036
+ messages={{
3037
+ invalidTitle: $t('dialog.rename.invalidTitle'),
3038
+ enterName: $t('dialog.rename.enterName'),
3039
+ enterDifferentName: $t('dialog.rename.enterDifferentName'),
3040
+ enterValidName: $t('dialog.rename.enterValidName'),
3041
+ tooShort: $t('dialog.rename.tooShort'),
3042
+ // The dialog knows its own limit: it puts the number in where {max} stands
3043
+ tooLong: $t('dialog.rename.tooLong', { max: '{max}' })
3044
+ }}
2659
3045
  target={rootContainerClass}
2660
3046
  shouldUseCustomRenameFunction={true}
2661
3047
  on:rename={handleRename}
@@ -2703,7 +3089,7 @@ mainGridClass="app-main-grid"
2703
3089
 
2704
3090
  // Add wave animation to all moved items
2705
3091
  detail.movedItems.forEach((item: { id: string }) => {
2706
- const itemElement = document.querySelector(`[data-item-id="${item.id}"]`);
3092
+ const itemElement = findItemElement(item.id);
2707
3093
  if (itemElement) {
2708
3094
  itemElement.classList.add('wave-goodbye');
2709
3095
  setTimeout(() => {
@@ -2721,18 +3107,21 @@ mainGridClass="app-main-grid"
2721
3107
  {#if showDeleteConfirmation}
2722
3108
  <ActionModal
2723
3109
  bind:isOpen={showDeleteConfirmation}
2724
- title={selectedItem?.type === 'folder' ? 'Delete folder' : (allSelectedFiles.length > 1 ? 'Delete items' : 'Delete file')}
3110
+ title={selectedItem?.type === 'folder' ? $t('dialog.delete.folderTitle') : (allSelectedFiles.length > 1 ? $t('dialog.delete.itemsTitle') : $t('dialog.delete.fileTitle'))}
2725
3111
  message={selectedItem?.type === 'folder'
2726
- ? `Delete '${selectedItem?.name}' and all content inside?`
3112
+ ? $t('dialog.delete.folderMessage', { name: selectedItem?.name ?? '' })
2727
3113
  : (allSelectedFiles.length > 1
2728
- ? `Are you sure you want to delete ${allSelectedFiles.length} items?`
2729
- : `Delete '${allSelectedFiles[0]?.name}'?`)}
3114
+ ? $t('dialog.delete.itemsMessage', { count: allSelectedFiles.length })
3115
+ : $t('dialog.delete.fileMessage', { name: allSelectedFiles[0]?.name ?? '' }))}
2730
3116
  items={selectedItem?.type === 'folder' ? [selectedItem] : allSelectedFiles}
2731
3117
  target={rootContainerClass}
2732
3118
  on:confirm={handleDelete}
2733
3119
  on:cancel={() => {
2734
3120
  showDeleteConfirmation = false;
2735
3121
  }}
3122
+ confirmLabel={$t('action.confirm')}
3123
+ cancelLabel={$t('action.cancel')}
3124
+ closeLabel={$t('dialog.close')}
2736
3125
  actionType="delete"
2737
3126
  confirmVariant="attention"
2738
3127
  modalType="delete"
@@ -2744,18 +3133,31 @@ mainGridClass="app-main-grid"
2744
3133
  bind:isOpen={showNewFolderDialog}
2745
3134
  itemType="folder"
2746
3135
  modalType="newFolder"
2747
- placeholder="folder name..."
3136
+ placeholder={$t('dialog.newFolder.placeholder')}
2748
3137
  target={rootContainerClass}
2749
3138
  {currentPath}
2750
3139
  {currentPathNames}
2751
3140
  showTitle={false}
2752
- confirmLabel="Create"
2753
- cancelLabel="Cancel"
3141
+ confirmLabel={$t('action.create')}
3142
+ cancelLabel={$t('action.cancel')}
3143
+ closeLabel={$t('dialog.close')}
3144
+ messages={{
3145
+ invalidTitle: $t('dialog.newFolder.invalidTitle'),
3146
+ required: $t('dialog.newFolder.required'),
3147
+ invalidCharacters: $t('dialog.newFolder.invalidCharacters'),
3148
+ // The dialog knows its own limit: it puts the number in where {max} stands
3149
+ tooLong: $t('dialog.newFolder.tooLong', { max: '{max}' })
3150
+ }}
2754
3151
  on:create={handleNewFolder}
2755
3152
  on:cancel={() => { showNewFolderDialog = false; }}
2756
3153
  />
2757
3154
  {/if}
2758
3155
 
3156
+ <!-- POP-UPS (only for an app that has no toaster of its own) -->
3157
+ {#if renderToaster}
3158
+ <ToasterModal containerAriaLabel={$t('toast.regionLabel')} closeButtonAriaLabel={$t('toast.closeLabel')} />
3159
+ {/if}
3160
+
2759
3161
  <!-- STYLES -->
2760
3162
  <style>
2761
3163