@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
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The media library contract.
3
+ *
4
+ * The File Browser can show and fill a library it does not own: a partner's own CMS, an S3 bucket, a DAM.
5
+ * The partner hands the File Browser a {@link MediaLibraryProvider} (plain functions) and the File Browser calls
6
+ * them. Nothing in here talks to Widgetic; the Widgetic library is just one provider (see `widgetic.ts`).
7
+ *
8
+ * Everything a provider returns is untrusted data from another party's code: it is validated before use
9
+ * (see `normalize.ts`), so a bad answer produces a clear error instead of a broken screen.
10
+ */
11
+ /** One file, as a library hands it to the File Browser. */
12
+ export interface MediaLibraryFile {
13
+ /**
14
+ * The file's id in the library. Stable, unique within the library. It is handed back unchanged when the
15
+ * visitor picks the file, and when a rename or delete is requested. Numbers are accepted and become strings.
16
+ */
17
+ id: string;
18
+ /** The name shown to the visitor, with its extension (`logo.png`). */
19
+ name: string;
20
+ /**
21
+ * Where the file can be fetched from by the visitor's browser. Must be an `http:` or `https:` address (or a
22
+ * path on the page's own site). `javascript:` and other schemes are refused.
23
+ */
24
+ url: string;
25
+ /** The file's media type, like `image/png`. Used to tell images from audio, video and documents. */
26
+ mimeType?: string;
27
+ /** Size in bytes. */
28
+ size?: number;
29
+ /** When the file last changed: an ISO 8601 string, a `Date`, or milliseconds since 1970. */
30
+ modified?: string | number | Date;
31
+ /** A small preview picture (an image address), when the file is not itself a small image. */
32
+ thumbnail?: string;
33
+ /** A content hash, handed back to the partner as is. Never interpreted. */
34
+ hash?: string;
35
+ }
36
+ /** What `list` is asked for. */
37
+ export interface MediaLibraryListRequest {
38
+ /** The `nextCursor` of the previous page. Absent for the first page. Opaque to the File Browser. */
39
+ cursor?: string;
40
+ /** The most files the File Browser wants in this page. Returning fewer is fine. */
41
+ limit: number;
42
+ /** Aborted when the File Browser no longer wants the answer (it was closed, or reloaded). */
43
+ signal: AbortSignal;
44
+ }
45
+ /** One page of the library, newest files first. */
46
+ export interface MediaLibraryPage {
47
+ items: MediaLibraryFile[];
48
+ /** Pass this back as `cursor` to get the next page. Absent, `null` or empty when there is no more. */
49
+ nextCursor?: string | null;
50
+ }
51
+ /** What `upload` is asked for. */
52
+ export interface MediaLibraryUploadRequest {
53
+ file: File;
54
+ /** Tell the File Browser how far the upload is, from 0 to 100. Optional to call. */
55
+ onProgress: (percentage: number) => void;
56
+ signal: AbortSignal;
57
+ }
58
+ /** What `rename` is asked for. */
59
+ export interface MediaLibraryRenameRequest {
60
+ id: string;
61
+ /** The new name, with its extension. */
62
+ name: string;
63
+ signal: AbortSignal;
64
+ }
65
+ /** What `delete` is asked for. */
66
+ export interface MediaLibraryDeleteRequest {
67
+ id: string;
68
+ signal: AbortSignal;
69
+ }
70
+ /**
71
+ * Which actions the File Browser offers the visitor. An action the provider cannot do is not shown, rather than
72
+ * shown and failing.
73
+ */
74
+ export interface MediaLibraryCapabilities {
75
+ /** Show the upload area. */
76
+ upload: boolean;
77
+ /** Show Rename. */
78
+ rename: boolean;
79
+ /** Show Delete. */
80
+ delete: boolean;
81
+ /** Show Download. */
82
+ download: boolean;
83
+ /**
84
+ * Show New folder and Move. Only the File Browser's own (Widgetic) storage has folders; a media library is one
85
+ * flat list, so this is always off for a library.
86
+ */
87
+ folders: boolean;
88
+ }
89
+ /** The functions a library has to offer. Only `list` is required. */
90
+ export interface MediaLibraryProvider {
91
+ /** A short stable name for this library, like `acme-assets`. Used in logs. */
92
+ readonly id: string;
93
+ /** What the visitor sees as the folder's name. Default: "My uploads". */
94
+ readonly label?: string;
95
+ /**
96
+ * Switches actions off. A provider can only take actions away: Rename and Delete are only ever shown when the
97
+ * provider also has the matching function, and Upload only when it has `upload`.
98
+ */
99
+ readonly capabilities?: Partial<Omit<MediaLibraryCapabilities, 'folders'>>;
100
+ /** Gives one page of the library. */
101
+ list(request: MediaLibraryListRequest): Promise<MediaLibraryPage>;
102
+ /** Stores a new file and gives back how the library knows it now. */
103
+ upload?(request: MediaLibraryUploadRequest): Promise<MediaLibraryFile>;
104
+ /** Renames a file. Gives back the file as it is now, or nothing. */
105
+ rename?(request: MediaLibraryRenameRequest): Promise<MediaLibraryFile | void>;
106
+ /** Removes a file from the library. */
107
+ delete?(request: MediaLibraryDeleteRequest): Promise<void>;
108
+ }
109
+ /** Why a library call failed, in terms the File Browser can act on. */
110
+ export type MediaLibraryErrorCode =
111
+ /** The library refused the credentials (HTTP 401). The File Browser's host may refresh them and retry. */
112
+ 'UNAUTHORIZED'
113
+ /** The credentials are fine but not allowed to do this (HTTP 403). */
114
+ | 'FORBIDDEN'
115
+ /** There is no such file (HTTP 404). */
116
+ | 'NOT_FOUND'
117
+ /** The library could not be reached. */
118
+ | 'NETWORK'
119
+ /** The library answered with something that is not a valid answer. */
120
+ | 'INVALID_RESPONSE'
121
+ /** The call was cancelled on purpose. Not a failure to show the visitor. */
122
+ | 'ABORTED'
123
+ /** The library does not do this. */
124
+ | 'NOT_SUPPORTED'
125
+ /** Anything else. */
126
+ | 'FAILED';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The media library contract.
3
+ *
4
+ * The File Browser can show and fill a library it does not own: a partner's own CMS, an S3 bucket, a DAM.
5
+ * The partner hands the File Browser a {@link MediaLibraryProvider} (plain functions) and the File Browser calls
6
+ * them. Nothing in here talks to Widgetic; the Widgetic library is just one provider (see `widgetic.ts`).
7
+ *
8
+ * Everything a provider returns is untrusted data from another party's code: it is validated before use
9
+ * (see `normalize.ts`), so a bad answer produces a clear error instead of a broken screen.
10
+ */
11
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Which addresses a media library may hand to the File Browser.
3
+ *
4
+ * The File Browser puts a file's address in `<img src>`, `<audio>`, `<video>`, `<iframe>` (PDF preview), `fetch` and
5
+ * `window.open` (Download). An address like `javascript:...` would run code in the partner's page the moment a
6
+ * visitor clicks Download, so only addresses that fetch something are accepted.
7
+ */
8
+ /** The longest address taken as a file's address or thumbnail address. */
9
+ export declare const MAX_URL_LENGTH = 8192;
10
+ /** The longest `data:` picture taken as a thumbnail (about 220 KB of image). */
11
+ export declare const MAX_DATA_THUMBNAIL_LENGTH = 300000;
12
+ export interface SafeMediaUrlOptions {
13
+ /** The page's address, to turn a path like `/media/1.png` into a full address. Default: the current page. */
14
+ baseHref?: string;
15
+ /**
16
+ * Accept a small `data:` picture. Only for thumbnails: a file's own address is opened in a new tab by Download,
17
+ * and a browser tab must never be pointed at inline data.
18
+ */
19
+ allowDataPicture?: boolean;
20
+ }
21
+ /** The address of the page the File Browser is on, to turn a path like `/media/1.png` into a full address. */
22
+ export declare function currentPageHref(): string | undefined;
23
+ /**
24
+ * The full, safe form of an address a library gave, or `null` when it must not be used.
25
+ *
26
+ * Accepted: `http:` and `https:` addresses, paths relative to the page (made absolute) and `blob:` addresses the
27
+ * partner's own page created; for thumbnails also small `data:` pictures. Everything else (`javascript:`, `file:`,
28
+ * `ftp:`, `vbscript:`, `data:text/html` ...) is refused.
29
+ */
30
+ export declare function toSafeMediaUrl(raw: unknown, options?: SafeMediaUrlOptions): string | null;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Which addresses a media library may hand to the File Browser.
3
+ *
4
+ * The File Browser puts a file's address in `<img src>`, `<audio>`, `<video>`, `<iframe>` (PDF preview), `fetch` and
5
+ * `window.open` (Download). An address like `javascript:...` would run code in the partner's page the moment a
6
+ * visitor clicks Download, so only addresses that fetch something are accepted.
7
+ */
8
+ /** The longest address taken as a file's address or thumbnail address. */
9
+ export const MAX_URL_LENGTH = 8192;
10
+ /** The longest `data:` picture taken as a thumbnail (about 220 KB of image). */
11
+ export const MAX_DATA_THUMBNAIL_LENGTH = 300_000;
12
+ /** `data:` addresses are only accepted for pictures; they can hold a small preview but never a script or a page. */
13
+ const DATA_IMAGE_PATTERN = /^data:image\/(?:png|jpe?g|gif|webp|avif|svg\+xml)[;,]/i;
14
+ /** The address of the page the File Browser is on, to turn a path like `/media/1.png` into a full address. */
15
+ export function currentPageHref() {
16
+ try {
17
+ return typeof location !== 'undefined' ? location.href : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ /**
24
+ * The full, safe form of an address a library gave, or `null` when it must not be used.
25
+ *
26
+ * Accepted: `http:` and `https:` addresses, paths relative to the page (made absolute) and `blob:` addresses the
27
+ * partner's own page created; for thumbnails also small `data:` pictures. Everything else (`javascript:`, `file:`,
28
+ * `ftp:`, `vbscript:`, `data:text/html` ...) is refused.
29
+ */
30
+ export function toSafeMediaUrl(raw, options = {}) {
31
+ if (typeof raw !== 'string')
32
+ return null;
33
+ const trimmed = raw.trim();
34
+ if (trimmed === '')
35
+ return null;
36
+ const isDataPicture = DATA_IMAGE_PATTERN.test(trimmed);
37
+ if (trimmed.length > (isDataPicture ? MAX_DATA_THUMBNAIL_LENGTH : MAX_URL_LENGTH))
38
+ return null;
39
+ const baseHref = options.baseHref ?? currentPageHref();
40
+ let parsed;
41
+ try {
42
+ // A base is only needed for paths; a full address ignores it. The browser's parser also strips the tabs and
43
+ // line breaks that `java\nscript:` tricks rely on, so the protocol checked here is the one the browser sees.
44
+ parsed = baseHref ? new URL(trimmed, baseHref) : new URL(trimmed);
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ switch (parsed.protocol) {
50
+ case 'https:':
51
+ case 'http:':
52
+ case 'blob:':
53
+ return parsed.href;
54
+ case 'data:':
55
+ return options.allowDataPicture === true && isDataPicture ? trimmed : null;
56
+ default:
57
+ return null;
58
+ }
59
+ }
@@ -0,0 +1,39 @@
1
+ import type { FileBrowserUploadConfig } from '../stores/uploadApiStore';
2
+ import type { MediaLibraryCapabilities, MediaLibraryProvider } from './types';
3
+ /** Why the Widgetic API is about to be called with a token. `expired` means the API just refused the previous one. */
4
+ export type TokenReason = 'initial' | 'expired';
5
+ export interface WidgeticMediaLibraryOptions {
6
+ /** The API's address including the version, like `https://api.widgetic.com/v1`. */
7
+ apiBasePath: string;
8
+ /**
9
+ * Gives the token to call the API with. Called before every request, so a host that keeps its token fresh is
10
+ * always used up to date; called again with `'expired'` when the API answers 401, after which the request is
11
+ * tried once more with the token that returns. That second call also gets the token that was refused, so a host
12
+ * can tell the refusal of its current token (get a new one) from the late refusal of one it has already replaced
13
+ * (hand out the new one) when several requests are refused together.
14
+ */
15
+ getAccessToken: (reason: TokenReason, refusedToken?: string) => Promise<string> | string;
16
+ /** What the uploaded files are for, as the API records it. Default: `content-property`. */
17
+ contextType?: FileBrowserUploadConfig['contextType'];
18
+ /** Where in the product the upload came from, as the API records it. Default: `file-browser-upload`. */
19
+ source?: string;
20
+ widgetId?: string;
21
+ conversationId?: string;
22
+ /**
23
+ * Allow files over 10 MB, which use the resumable (TUS) upload. Default: true. An editor session cannot use TUS
24
+ * yet, so the module turns this off and such files are refused with a clear message instead of a 403.
25
+ */
26
+ allowResumableUploads?: boolean;
27
+ /** Actions to switch off. Rename and Delete are off anyway: the API has no such calls yet. */
28
+ capabilities?: Partial<MediaLibraryCapabilities>;
29
+ label?: string;
30
+ }
31
+ /**
32
+ * The Widgetic library (`GET /v1/uploads`, `POST /v1/uploads`) as a media library provider.
33
+ *
34
+ * Behaves as the File Browser always has with a Widgetic token, but the API address and token belong to this
35
+ * provider instead of to one global setting, so two File Browsers on a page can use different accounts. It has no
36
+ * Rename or Delete: the API cannot do them yet, and a button that only hides a file on the visitor's own device
37
+ * would be a lie.
38
+ */
39
+ export declare function createWidgeticMediaLibrary(options: WidgeticMediaLibraryOptions): MediaLibraryProvider;
@@ -0,0 +1,89 @@
1
+ import { fetchUserUploadsFromApi, uploadToWidgeticApi } from '../utils/widgeticUpload';
2
+ import { WIDGETIC_MULTIPART_MAX_BYTES, shouldUseTusUpload } from '../utils/widgeticTusUpload';
3
+ import { MediaLibraryError, codeForHttpStatus, isUnauthorized, toMediaLibraryError } from './errors';
4
+ /**
5
+ * The Widgetic library (`GET /v1/uploads`, `POST /v1/uploads`) as a media library provider.
6
+ *
7
+ * Behaves as the File Browser always has with a Widgetic token, but the API address and token belong to this
8
+ * provider instead of to one global setting, so two File Browsers on a page can use different accounts. It has no
9
+ * Rename or Delete: the API cannot do them yet, and a button that only hides a file on the visitor's own device
10
+ * would be a lie.
11
+ */
12
+ export function createWidgeticMediaLibrary(options) {
13
+ if (typeof options.apiBasePath !== 'string' || options.apiBasePath.trim() === '') {
14
+ throw new TypeError('createWidgeticMediaLibrary needs the API address (apiBasePath)');
15
+ }
16
+ if (typeof options.getAccessToken !== 'function') {
17
+ throw new TypeError('createWidgeticMediaLibrary needs a getAccessToken function');
18
+ }
19
+ const apiBasePath = options.apiBasePath.trim().replace(/\/+$/, '');
20
+ const allowResumableUploads = options.allowResumableUploads !== false;
21
+ /** Builds the settings the existing upload functions take, around one token. */
22
+ const configAround = (accessToken) => ({
23
+ apiBasePath,
24
+ accessToken,
25
+ contextType: options.contextType,
26
+ source: options.source,
27
+ widgetId: options.widgetId,
28
+ conversationId: options.conversationId
29
+ });
30
+ /** Runs a request with the host's token; when the API refuses that token, asks for a fresh one and runs it once more. */
31
+ async function withTokenRetriedOnce(request) {
32
+ let accessToken;
33
+ try {
34
+ accessToken = await options.getAccessToken('initial');
35
+ }
36
+ catch (error) {
37
+ throw toMediaLibraryError(error, 'Could not get an access token from the page', 'libraryError.accessToken');
38
+ }
39
+ try {
40
+ return await request(accessToken);
41
+ }
42
+ catch (error) {
43
+ if (!isUnauthorized(error))
44
+ throw error;
45
+ console.warn('[FileBrowser] The Widgetic API refused the access token; asking the page for a fresh one');
46
+ let renewedToken;
47
+ try {
48
+ renewedToken = await options.getAccessToken('expired', accessToken);
49
+ }
50
+ catch (renewError) {
51
+ throw toMediaLibraryError(renewError, 'Could not get a fresh access token from the page', 'libraryError.accessTokenRenew');
52
+ }
53
+ return await request(renewedToken);
54
+ }
55
+ }
56
+ return {
57
+ id: 'widgetic',
58
+ label: options.label,
59
+ capabilities: options.capabilities,
60
+ async list({ limit, signal }) {
61
+ const items = await withTokenRetriedOnce((accessToken) => fetchUserUploadsFromApi(configAround(accessToken), { limit, signal }));
62
+ // The API lists the newest uploads up to `limit` and has no cursor yet, so there is never a next page.
63
+ // Every row listed has an id and a url (rows without are dropped by the function), which the item type cannot say.
64
+ return { items: items, nextCursor: null };
65
+ },
66
+ async upload({ file, onProgress, signal }) {
67
+ if (!allowResumableUploads && shouldUseTusUpload(file)) {
68
+ const limitInMegabytes = Math.round(WIDGETIC_MULTIPART_MAX_BYTES / (1024 * 1024));
69
+ throw new MediaLibraryError('NOT_SUPPORTED', `Files over ${limitInMegabytes} MB cannot be uploaded here yet`, { messageKey: 'libraryError.fileTooLarge', messageValues: { limit: limitInMegabytes } });
70
+ }
71
+ const uploaded = await withTokenRetriedOnce(async (accessToken) => {
72
+ const result = await uploadToWidgeticApi(file, configAround(accessToken), {
73
+ abortSignal: signal,
74
+ onProgress: ({ percentage }) => onProgress(percentage)
75
+ });
76
+ if (!result.success || !result.file) {
77
+ const message = result.error || 'The upload failed';
78
+ throw new MediaLibraryError(result.status !== undefined ? codeForHttpStatus(result.status) : 'FAILED', message, {
79
+ status: result.status,
80
+ // The API's own reason is shown as it is; without one, the File Browser's sentence is.
81
+ messageKey: result.error ? undefined : 'libraryError.uploadFailed'
82
+ });
83
+ }
84
+ return result.file;
85
+ });
86
+ return uploaded;
87
+ }
88
+ };
89
+ }
@@ -5,7 +5,7 @@ export declare const fileStore: {
5
5
  update: (this: void, updater: import("svelte/store").Updater<FileSystemRoot>) => void;
6
6
  };
7
7
  export declare const currentFolder: import("svelte/store").Writable<string[]>;
8
- export declare const sortCriteria: import("svelte/store").Writable<"size" | "name" | "date">;
8
+ export declare const sortCriteria: import("svelte/store").Writable<"name" | "date" | "size">;
9
9
  export declare const sortDirection: import("svelte/store").Writable<"desc" | "asc">;
10
10
  export declare const selectedFiles: import("svelte/store").Writable<FileSystemItem[]>;
11
11
  export declare const fileFilter: import("svelte/store").Writable<string[]>;
@@ -13,7 +13,7 @@ export declare const fileFilter: import("svelte/store").Writable<string[]>;
13
13
  * Derived store that automatically sorts files based on criteria
14
14
  * Maintains folder priority (folders always appear before files)
15
15
  */
16
- export declare const sortedFiles: import("svelte/store").Readable<FileSystemRoot>;
16
+ export declare const sortedFiles: import("svelte/store").Readable<any>;
17
17
  /**
18
18
  * Initializes or updates the file store with new data
19
19
  * Includes validation and error handling
@@ -1,6 +1,6 @@
1
1
  import { writable, derived } from 'svelte/store';
2
2
  import { fileStore } from './fileStore';
3
- import { getFileType } from '../utils/fileUtils';
3
+ import { getFileTypeOf } from '../utils/fileKinds';
4
4
  // Store to keep track of file counts for each folder
5
5
  export const folderCounts = writable(new Map());
6
6
  // Helper function to count files in a folder
@@ -11,7 +11,7 @@ function countFiles(folder, filter) {
11
11
  if (item.type === 'folder') {
12
12
  count += 1;
13
13
  }
14
- else if (filter === 'all' || getFileType(item.name) === filter) {
14
+ else if (filter === 'all' || getFileTypeOf(item) === filter) {
15
15
  count++;
16
16
  }
17
17
  }
@@ -1,5 +1,5 @@
1
1
  import { currentFolder } from './fileStore';
2
- export declare const currentPathNames: import("svelte/store").Readable<string[]>;
2
+ export declare const currentPathNames: import("svelte/store").Readable<any>;
3
3
  export { currentFolder };
4
4
  export declare const navigationActions: import("svelte/store").Writable<{
5
5
  navigateToPath: (path: string[]) => void;
@@ -4,6 +4,16 @@ interface StoredSelections {
4
4
  [filterType: string]: string[];
5
5
  }
6
6
  export declare const persistentSelectStore: {
7
+ /**
8
+ * Turns the localStorage copy of the selection on or off.
9
+ *
10
+ * Off: nothing is read from or written to localStorage, and what was selected so far is forgotten, so a
11
+ * previous visitor's choices on the same browser can never show up. (The File Browser turns it off when it
12
+ * shows a host's media library.) On again: the stored selection is read back.
13
+ *
14
+ * This is a setting of the page, not of one File Browser: the last one to set it wins.
15
+ */
16
+ configurePersistence: (enabled: boolean) => void;
7
17
  getSelected: (filterType: FileFilterType) => string[];
8
18
  toggleSelection: (file: FileSystemItem, filterType: FileFilterType) => void;
9
19
  setSelections: (filterType: FileFilterType, selectedIds: string[]) => void;
@@ -14,5 +24,5 @@ export declare const persistentSelectStore: {
14
24
  update(this: void, updater: import("svelte/store").Updater<StoredSelections>): void;
15
25
  subscribe(this: void, run: import("svelte/store").Subscriber<StoredSelections>, invalidate?: () => void): import("svelte/store").Unsubscriber;
16
26
  };
17
- export declare const validSelections: import("svelte/store").Readable<(filterType: FileFilterType, files: FileSystemItem[]) => FileSystemItem[]>;
27
+ export declare const validSelections: import("svelte/store").Readable<(filterType: FileFilterType, files: FileSystemItem[]) => any[]>;
18
28
  export {};
@@ -21,12 +21,23 @@ function getStoredSelections() {
21
21
  return {};
22
22
  }
23
23
  }
24
+ // Whether the selection is kept in this browser's localStorage. On by default, as it has always been.
25
+ let persistenceEnabled = true;
24
26
  // Create the base store
25
27
  function createPersistentSelectStore() {
26
28
  const selections = writable(getStoredSelections());
27
29
  // Save to localStorage whenever the store changes
28
30
  if (browser) {
31
+ // A subscriber is called once as soon as it subscribes, with what was just read from localStorage. That is not
32
+ // a change, so it is not written back (it would also write to a page that never stored anything).
33
+ let isFirstValue = true;
29
34
  selections.subscribe(value => {
35
+ if (isFirstValue) {
36
+ isFirstValue = false;
37
+ return;
38
+ }
39
+ if (!persistenceEnabled)
40
+ return;
30
41
  try {
31
42
  localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
32
43
  }
@@ -37,6 +48,21 @@ function createPersistentSelectStore() {
37
48
  }
38
49
  return {
39
50
  ...selections,
51
+ /**
52
+ * Turns the localStorage copy of the selection on or off.
53
+ *
54
+ * Off: nothing is read from or written to localStorage, and what was selected so far is forgotten, so a
55
+ * previous visitor's choices on the same browser can never show up. (The File Browser turns it off when it
56
+ * shows a host's media library.) On again: the stored selection is read back.
57
+ *
58
+ * This is a setting of the page, not of one File Browser: the last one to set it wins.
59
+ */
60
+ configurePersistence: (enabled) => {
61
+ if (enabled === persistenceEnabled)
62
+ return;
63
+ persistenceEnabled = enabled;
64
+ selections.set(enabled ? getStoredSelections() : {});
65
+ },
40
66
  // Get selected files for a specific filter type
41
67
  getSelected: (filterType) => {
42
68
  const stored = get(selections);
@@ -1,2 +1,11 @@
1
- export declare function formatDate(date: string | Date): string;
2
- export declare function formatRelativeDate(date: string | Date): string;
1
+ import { type Translate } from '../i18n/context';
2
+ /**
3
+ * Format a date as month, day and year ("Oct 5, 2026"). The month's name and the order of the three follow `locale`
4
+ * (a BCP 47 tag like "de" or "pt-BR"; the File Browser's own locale when called from a screen).
5
+ */
6
+ export declare function formatDate(date: string | Date, locale?: string): string;
7
+ /**
8
+ * Format a date relative to the current time ("2 days ago"). The words come from the File Browser's messages: pass the
9
+ * `t` of the screen to have them in the page's language (English when left out).
10
+ */
11
+ export declare function formatRelativeDate(date: string | Date, translate?: Translate): string;
@@ -1,13 +1,18 @@
1
- import { format,
2
- // formatDistanceToNow, // not used
3
- differenceInHours, differenceInDays, differenceInWeeks, differenceInMonths } from 'date-fns';
4
- // Format a date to a specific string format
5
- export function formatDate(date) {
1
+ import { differenceInHours, differenceInDays, differenceInWeeks, differenceInMonths } from 'date-fns';
2
+ import { translateEnglish } from '../i18n/context';
3
+ /**
4
+ * Format a date as month, day and year ("Oct 5, 2026"). The month's name and the order of the three follow `locale`
5
+ * (a BCP 47 tag like "de" or "pt-BR"; the File Browser's own locale when called from a screen).
6
+ */
7
+ export function formatDate(date, locale = 'en-US') {
6
8
  const dateObj = typeof date === 'string' ? new Date(date) : date;
7
- return format(dateObj, 'MMM d, yyyy');
9
+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', year: 'numeric' }).format(dateObj);
8
10
  }
9
- // Format a date relative to the current time (e.g., "2 days ago")
10
- export function formatRelativeDate(date) {
11
+ /**
12
+ * Format a date relative to the current time ("2 days ago"). The words come from the File Browser's messages: pass the
13
+ * `t` of the screen to have them in the page's language (English when left out).
14
+ */
15
+ export function formatRelativeDate(date, translate = translateEnglish) {
11
16
  const now = new Date();
12
17
  const inputDate = new Date(date);
13
18
  const hoursAgo = differenceInHours(now, inputDate);
@@ -15,24 +20,24 @@ export function formatRelativeDate(date) {
15
20
  const weeksAgo = differenceInWeeks(now, inputDate);
16
21
  const monthsAgo = differenceInMonths(now, inputDate);
17
22
  if (hoursAgo < 1) {
18
- return 'A few seconds ago';
23
+ return translate('date.fewSecondsAgo');
19
24
  }
20
25
  else if (hoursAgo < 24) {
21
- return hoursAgo === 1 ? '1 hour ago' : `${hoursAgo} hours ago`;
26
+ return translate('date.hoursAgo', { count: hoursAgo });
22
27
  }
23
28
  else if (daysAgo < 7) {
24
- return daysAgo === 1 ? '1 day ago' : `${daysAgo} days ago`;
29
+ return translate('date.daysAgo', { count: daysAgo });
25
30
  }
26
31
  else if (weeksAgo < 4) {
27
- return weeksAgo === 1 ? '1 week ago' : `${weeksAgo} weeks ago`;
32
+ return translate('date.weeksAgo', { count: weeksAgo });
28
33
  }
29
34
  else if (monthsAgo < 2) {
30
- return 'About a month ago';
35
+ return translate('date.aboutAMonthAgo');
31
36
  }
32
37
  else if (monthsAgo < 12) {
33
- return 'Several months ago';
38
+ return translate('date.severalMonthsAgo');
34
39
  }
35
40
  else {
36
- return 'Over a year ago';
41
+ return translate('date.overAYearAgo');
37
42
  }
38
43
  }
@@ -0,0 +1,44 @@
1
+ import { type FileFilterType } from './fileTypes';
2
+ /**
3
+ * True when the mime type or the extension says the file is NOT a picture (a PDF, a text file...).
4
+ *
5
+ * The File Browser draws a remote file as an image thumbnail unless it knows better. A PDF or a text
6
+ * file cannot be drawn that way: the picture fails to load and the file would be shown as "missing"
7
+ * (red, and impossible to select). Those files get the file-type icon instead.
8
+ *
9
+ * A file whose type is not known (no usable mime type and no known document extension) is not
10
+ * reported here, so it keeps being tried as a picture.
11
+ */
12
+ export declare function isKnownNonImageFile(file: {
13
+ name?: string;
14
+ mimeType?: string;
15
+ }): boolean;
16
+ /** A kind of file the tabs know (every tab but "all"). */
17
+ type FileKind = Exclude<FileFilterType, 'all'>;
18
+ /**
19
+ * The kind a file extension belongs to, read from a file name or an address (`photo.png`, `/media/a/photo.png?v=2`),
20
+ * or `null` when there is no extension or the tabs do not know it.
21
+ */
22
+ export declare function fileKindFromExtension(nameOrAddress: string | undefined): FileKind | null;
23
+ /**
24
+ * The kind a media type belongs to, or `null` when the media type says nothing (missing, or a "binary, who knows"
25
+ * type) or is not one of the kinds the tabs have.
26
+ */
27
+ export declare function fileKindFromMimeType(mimeType: string | undefined): FileKind | null;
28
+ /**
29
+ * The tab a file belongs to (image, video, audio, document, font, svg).
30
+ *
31
+ * Looks at everything the file came with, in this order: the extension in its address, the extension in its name,
32
+ * then its media type. The address comes first because it always has (a Widgetic upload has it right), and the
33
+ * rest only matter where it says nothing: a library that serves `/media/8f3a2c` (no extension at all), or a signed
34
+ * address that ends in `download`, still has a name like `logo.png` and a media type like `image/png`. Judging by
35
+ * the address alone would have put every one of those files under "document".
36
+ *
37
+ * A file nothing says anything about is a document.
38
+ */
39
+ export declare function getFileTypeOf(file: {
40
+ name?: string;
41
+ url?: string;
42
+ mimeType?: string;
43
+ }): FileFilterType;
44
+ export {};