@widgetic/file-browser 0.5.24 → 0.5.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +225 -0
  2. package/dist/components/FolderTree.svelte +4 -1
  3. package/dist/components/FolderTree.svelte.d.ts +2 -6
  4. package/dist/components/core/FileBrowser.svelte +494 -120
  5. package/dist/components/core/FileBrowser.svelte.d.ts +25 -1
  6. package/dist/components/core/FileUploader.svelte +114 -45
  7. package/dist/components/core/Header.svelte +12 -1
  8. package/dist/components/core/Header.svelte.d.ts +1 -0
  9. package/dist/components/core/RecentFiles.svelte +34 -26
  10. package/dist/components/core/UploadStatus.svelte +8 -5
  11. package/dist/components/core/UploadStatusList.svelte +13 -21
  12. package/dist/components/items/FileItem.svelte +19 -10
  13. package/dist/components/items/FolderItem.svelte +6 -3
  14. package/dist/components/modals/MoveDialog.svelte +43 -32
  15. package/dist/components/modals/NewFolderButton.svelte +5 -2
  16. package/dist/components/modals/SearchModal.svelte +16 -21
  17. package/dist/components/modals/SearchModal.svelte.d.ts +1 -1
  18. package/dist/components/modals/SelectedFilesModal.svelte +14 -9
  19. package/dist/components/modals/SelectedFilesModal.svelte.d.ts +1 -1
  20. package/dist/components/previews/AudioPlayer.svelte +5 -2
  21. package/dist/components/previews/ErrorPreview.svelte +7 -4
  22. package/dist/components/previews/ErrorPreview.svelte.d.ts +1 -1
  23. package/dist/components/previews/FilePreview.svelte +17 -7
  24. package/dist/components/previews/FontPreview.svelte +18 -9
  25. package/dist/components/previews/FontPreview.svelte.d.ts +1 -1
  26. package/dist/components/previews/TextPreview.svelte +12 -5
  27. package/dist/components/previews/VideoPlayer.svelte +8 -5
  28. package/dist/components/ui/ControlToolbar.svelte +45 -23
  29. package/dist/components/ui/ControlToolbar.svelte.d.ts +1 -1
  30. package/dist/components/ui/DragSelect.svelte +2 -2
  31. package/dist/components/ui/DropdownMenu.svelte +35 -14
  32. package/dist/components/ui/FileIcon.svelte +8 -5
  33. package/dist/components/ui/FileIcon.svelte.d.ts +1 -0
  34. package/dist/components/ui/FileMetadata.svelte +12 -15
  35. package/dist/components/ui/SearchResults.svelte +4 -1
  36. package/dist/i18n/context.d.ts +38 -0
  37. package/dist/i18n/context.js +70 -0
  38. package/dist/i18n/errors.d.ts +11 -0
  39. package/dist/i18n/errors.js +19 -0
  40. package/dist/i18n/index.d.ts +11 -0
  41. package/dist/i18n/index.js +18 -0
  42. package/dist/i18n/messages.d.ts +277 -0
  43. package/dist/i18n/messages.js +290 -0
  44. package/dist/i18n/text.d.ts +19 -0
  45. package/dist/i18n/text.js +35 -0
  46. package/dist/i18n/translator.d.ts +75 -0
  47. package/dist/i18n/translator.js +317 -0
  48. package/dist/index.d.ts +3 -0
  49. package/dist/index.js +4 -0
  50. package/dist/mediaLibrary/capabilities.d.ts +22 -0
  51. package/dist/mediaLibrary/capabilities.js +42 -0
  52. package/dist/mediaLibrary/context.d.ts +17 -0
  53. package/dist/mediaLibrary/context.js +16 -0
  54. package/dist/mediaLibrary/errors.d.ts +42 -0
  55. package/dist/mediaLibrary/errors.js +114 -0
  56. package/dist/mediaLibrary/index.d.ts +10 -0
  57. package/dist/mediaLibrary/index.js +9 -0
  58. package/dist/mediaLibrary/normalize.d.ts +39 -0
  59. package/dist/mediaLibrary/normalize.js +139 -0
  60. package/dist/mediaLibrary/paging.d.ts +37 -0
  61. package/dist/mediaLibrary/paging.js +62 -0
  62. package/dist/mediaLibrary/resolve.d.ts +39 -0
  63. package/dist/mediaLibrary/resolve.js +137 -0
  64. package/dist/mediaLibrary/treeOps.d.ts +24 -0
  65. package/dist/mediaLibrary/treeOps.js +67 -0
  66. package/dist/mediaLibrary/types.d.ts +126 -0
  67. package/dist/mediaLibrary/types.js +11 -0
  68. package/dist/mediaLibrary/urls.d.ts +30 -0
  69. package/dist/mediaLibrary/urls.js +59 -0
  70. package/dist/mediaLibrary/widgetic.d.ts +39 -0
  71. package/dist/mediaLibrary/widgetic.js +89 -0
  72. package/dist/stores/fileStore.d.ts +2 -2
  73. package/dist/stores/folderCountStore.js +2 -2
  74. package/dist/stores/navigationStore.d.ts +1 -1
  75. package/dist/stores/persistentSelectStore.d.ts +11 -1
  76. package/dist/stores/persistentSelectStore.js +26 -0
  77. package/dist/utils/dateUtils.d.ts +11 -2
  78. package/dist/utils/dateUtils.js +20 -15
  79. package/dist/utils/fileKinds.d.ts +44 -0
  80. package/dist/utils/fileKinds.js +96 -0
  81. package/dist/utils/fileNames.d.ts +7 -0
  82. package/dist/utils/fileNames.js +19 -0
  83. package/dist/utils/fileOperations.js +2 -11
  84. package/dist/utils/fileTypes.d.ts +11 -2
  85. package/dist/utils/fileTypes.js +26 -14
  86. package/dist/utils/fileUtils.d.ts +8 -1
  87. package/dist/utils/fileUtils.js +22 -7
  88. package/dist/utils/folderUtils.js +3 -2
  89. package/dist/utils/safeText.d.ts +29 -0
  90. package/dist/utils/safeText.js +66 -0
  91. package/dist/utils/userUploadsStorage.d.ts +4 -1
  92. package/dist/utils/userUploadsStorage.js +5 -2
  93. package/dist/utils/widgeticTusUpload.d.ts +10 -0
  94. package/dist/utils/widgeticTusUpload.js +61 -3
  95. package/dist/utils/widgeticUpload.d.ts +3 -0
  96. package/dist/utils/widgeticUpload.js +7 -2
  97. package/package.json +4 -2
package/README.md CHANGED
@@ -61,6 +61,231 @@ pnpm link --global @widgetic/file-browser
61
61
  <FileBrowser />
62
62
  ```
63
63
 
64
+ ## Using your own media library
65
+
66
+ By default the File Browser shows the Widgetic account's uploads. A platform that already has a media library of its
67
+ own (a CMS, an S3 bucket, a DAM) can hand the File Browser that library instead, as plain functions. The File Browser
68
+ then lists, uploads, renames and deletes through those functions and never talks to Widgetic.
69
+
70
+ ```svelte
71
+ <script lang="ts">
72
+ import { FileBrowser, type MediaLibraryProvider } from '@widgetic/file-browser';
73
+
74
+ const mediaLibrary: MediaLibraryProvider = {
75
+ id: 'acme-assets',
76
+ label: 'Acme assets', // the title above the files. Default: "My uploads"
77
+
78
+ // Required. One page of the library, newest files first.
79
+ async list({ cursor, limit, signal }) {
80
+ const response = await fetch(`/api/assets?cursor=${cursor ?? ''}&limit=${limit}`, { signal });
81
+ if (!response.ok) throw Object.assign(new Error('Could not load your files'), { status: response.status });
82
+ const page = await response.json();
83
+ return {
84
+ items: page.assets.map((asset) => ({
85
+ id: asset.id,
86
+ name: asset.fileName,
87
+ url: asset.publicUrl,
88
+ mimeType: asset.contentType,
89
+ size: asset.bytes,
90
+ })),
91
+ nextCursor: page.next ?? null, // null (or leaving it out) means this was the last page
92
+ };
93
+ },
94
+
95
+ // Optional. Leave a function out and its button is not shown.
96
+ async upload({ file, onProgress, signal }) { /* store the file, call onProgress(0..100), return it as a MediaLibraryFile */ },
97
+ async rename({ id, name, signal }) { /* rename it; return the file as it is now, or nothing */ },
98
+ async delete({ id, signal }) { /* remove it */ },
99
+ };
100
+ </script>
101
+
102
+ <FileBrowser
103
+ {mediaLibrary}
104
+ on:select={(event) => console.log('picked', event.detail.files)}
105
+ on:error={(event) => console.warn('media library problem', event.detail)}
106
+ />
107
+ ```
108
+
109
+ ### What the File Browser does with a library
110
+
111
+ - **One flat list.** A media library has no folders, so there is no New folder, Move, breadcrumb or Recent files.
112
+ - **Pages.** It calls `list` with `limit: 100` and the previous page's `nextCursor` until there is no next page. It
113
+ reads at most **1,000 files** (and at most 50 pages) and then shows "Only the newest files are shown." Search and
114
+ the type filter only look at the files that were loaded.
115
+ - **Only the actions the library can do.** Upload needs `upload`, Rename needs `rename`, Delete needs `delete`.
116
+ Download is always offered. `capabilities` can switch actions off (`capabilities: { delete: false }`), never on.
117
+ - **Nothing is kept on the visitor's device.** No local cache, no saved file tree, and the picked files are not
118
+ remembered between visits (a shared browser must not show the next visitor the previous one's picks). Pass
119
+ `persistSelection` to keep them anyway.
120
+ - **Library mode ignores** `data`, `useDemoContent`, `enableLocalCache` and the Widgetic upload settings.
121
+ - **The library's own failures are shown as they are.** The message of the error you throw reaches the visitor (cut
122
+ at 300 characters): a screen with "Try again" when the first page cannot be read, a notice when a later page fails,
123
+ a message in the upload panel, a toast for rename and delete. Toasts are drawn by the design system's
124
+ `<ToasterModal />`, which **the app around the File Browser has to render** (the Widgetic site's layout does): without
125
+ one, a refused rename or delete shows the visitor nothing and the `error` event is the only sign.
126
+ - **Calls are given 30 seconds** (`list`, `rename`, `delete`). An upload has no time limit, the visitor can cancel it.
127
+ `signal` is aborted when the visitor cancels, or the File Browser is closed: stop your request then.
128
+
129
+ ### A file (`MediaLibraryFile`)
130
+
131
+ | Field | | |
132
+ | --- | --- | --- |
133
+ | `id` | required | Stable and unique in the library. Handed back unchanged on `select`, `rename` and `delete`. |
134
+ | `name` | required | Shown to the visitor, with its extension (`logo.png`). |
135
+ | `url` | required | Where the visitor's browser fetches the file. |
136
+ | `mimeType` | optional | Tells images, audio, video and documents apart when the extension cannot (see below). |
137
+ | `size` | optional | Bytes. |
138
+ | `modified` | optional | ISO 8601 string, `Date`, or milliseconds since 1970. |
139
+ | `thumbnail` | optional | A small preview picture. Without it an image is drawn from `url` and any other file gets its type icon. |
140
+ | `hash` | optional | Handed back as is. Never interpreted. |
141
+
142
+ **Which tab a file lands under** (Images, Video, Audio, Documents, Fonts, SVG) is decided in this order: the
143
+ extension in its `url`, the extension in its `name`, then its `mimeType`. A file nothing says anything about is a
144
+ document. So `/media/8f3a2c` with `name: 'logo.png'`, or a `blob:` address with `mimeType: 'image/png'`, is an image.
145
+ Give a `name` with its extension, or a `mimeType`, whenever your addresses carry no extension: otherwise those files
146
+ only show up under "All" and "Documents".
147
+
148
+ Everything a library returns is treated as untrusted. A file without an `id`, `name` or usable `url`, or with a
149
+ duplicate `id`, is skipped (with a console warning) instead of breaking the list. Ids longer than 512 characters are
150
+ refused, names longer than 255 are cut, and a page uses at most its first 1,000 files. Addresses must be `http:`,
151
+ `https:`, a path on the page's own site, or `blob:`; a thumbnail may also be a small `data:` picture. `javascript:`
152
+ and every other kind of address is refused. Names are always shown as text, never as HTML.
153
+
154
+ A file on another website needs a CORS header (`Access-Control-Allow-Origin`) for the previews that read it with a
155
+ script: text, PDF and font previews. Pictures, audio and video are shown without it.
156
+
157
+ ### Errors
158
+
159
+ Throw anything from a library function: an `Error` (its message is shown), or an object with a `status` (HTTP). The
160
+ File Browser maps it to a code:
161
+
162
+ | Code | When |
163
+ | --- | --- |
164
+ | `UNAUTHORIZED` | `status` 401 |
165
+ | `FORBIDDEN` | `status` 403 |
166
+ | `NOT_FOUND` | `status` 404 |
167
+ | `NETWORK` | `fetch` could not reach the server (a `TypeError`) |
168
+ | `INVALID_RESPONSE` | `list` did not answer with `{ items: [...] }`, or keeps returning the same files |
169
+ | `NOT_SUPPORTED` | the library has no function for this (for example no `upload`) |
170
+ | `FAILED` | anything else |
171
+
172
+ An `AbortError` is a cancellation, not a failure: nothing is shown and no `error` event is sent.
173
+
174
+ ### Events
175
+
176
+ - `select` — `{ files }`: the files the visitor picked, as the File Browser holds them (`id`, `name`, `url`, ...).
177
+ - `error` — `{ message, code, action, file? }` for a problem with the library. `action` is `setup` (the
178
+ `mediaLibrary` option is not a media library), `load`, `upload`, `rename` or `delete`; `file` is the file name for an
179
+ upload. Listen to it to log problems or to refresh your own token (`UNAUTHORIZED`).
180
+
181
+ ### The Widgetic library as a provider
182
+
183
+ `createWidgeticMediaLibrary({ apiBasePath, getAccessToken })` is the Widgetic upload library (`GET /v1/uploads`,
184
+ `POST /v1/uploads`) as a provider. `getAccessToken('initial' | 'expired', refusedToken?)` is called before every
185
+ request, and again with `'expired'` (and the token the API refused) when it answers 401, after which the request is
186
+ tried once more. It has no Rename or Delete: the API cannot do them yet.
187
+
188
+ ## Languages
189
+
190
+ The File Browser shows English until it is told otherwise. Two props change that, and both can change while the File
191
+ Browser is open:
192
+
193
+ ```svelte
194
+ <FileBrowser
195
+ locale="de"
196
+ messages={{
197
+ 'action.cancel': 'Abbrechen',
198
+ 'action.delete': 'Löschen',
199
+ 'toolbar.deleteMany': '{count, plural, one {# Datei löschen} other {# Dateien löschen}}',
200
+ }}
201
+ />
202
+ ```
203
+
204
+ - **`locale`** is a BCP 47 language tag (`de`, `pt-BR`, `ar-EG`). It decides the plural rules and how numbers, dates,
205
+ "2 days ago" and file sizes are written (all through `Intl`). It translates nothing. Blank or left out is English. A
206
+ tag the browser does not know is said once in the console and numbers and dates stay English.
207
+ - **`messages`** replaces words. Every word the File Browser shows is a message with a key; give the keys you want
208
+ to change and every key you leave out stays English, so a language can be added one screen at a time. A key that does
209
+ not exist is ignored and the console says which key you probably meant.
210
+
211
+ `FILE_BROWSER_MESSAGES` is the list: an object of every key and its English text (the keys are grouped by where the words
212
+ appear), and it is the list to hand to a translator:
213
+
214
+ ```ts
215
+ import { FILE_BROWSER_MESSAGES } from '@widgetic/file-browser';
216
+
217
+ console.log(Object.keys(FILE_BROWSER_MESSAGES).length); // every word of the File Browser
218
+ console.log(FILE_BROWSER_MESSAGES['toolbar.deleteMany']); // '{count, plural, one {Delete # file} other {Delete # files}}'
219
+ ```
220
+
221
+ | Keys start with | The words of |
222
+ | --- | --- |
223
+ | `action.`, `list.separator` | buttons that appear in several places (Cancel, Delete, Rename, Select, Add to Editor) |
224
+ | `search.`, `filter.`, `filterName.`, `filterOption.`, `sort.`, `breadcrumbs.` | the bar above the files and the path |
225
+ | `empty.` | what the list says when there is nothing to show |
226
+ | `library.`, `libraryError.` | the page's own media library: its name, and what the File Browser says when it gave no reason |
227
+ | `size.`, `date.` | file sizes ("1.5 MB") and "2 days ago" |
228
+ | `fileKind.`, `fileTypes.` | the kinds of file inside a sentence ("Upload image files") |
229
+ | `upload.` | the upload panel, its progress and its problems |
230
+ | `dialog.` | Rename, New folder and Delete: titles, hints and the sentences about a name that is not allowed |
231
+ | `toast.` | the messages that pop up after an action |
232
+ | `folder.`, `item.`, `recent.`, `menu.`, `newFolder.` | folders and items in the list, and their menus |
233
+ | `selectedFiles.`, `toolbar.` | the bar over a selection and the list of selected files |
234
+ | `searchModal.`, `moveDialog.` | the search window and the Move window |
235
+ | `preview.`, `metadata.`, `fontPreview.` | the previews and the details of a file |
236
+
237
+ ### Writing a message
238
+
239
+ A message is text. Two kinds of `{...}` have a meaning:
240
+
241
+ | Write | It shows |
242
+ | --- | --- |
243
+ | `{name}` | a value the File Browser puts in. A number is written the way the locale writes numbers (`1,234` or `1.234`). |
244
+ | `{count, plural, one {# file} other {# files}}` | the branch that fits the number in the page's language. `other` is required; `=0 {none}` matches exactly 0; `#` is the number. A language with more forms says so: Polish uses `one`, `few`, `many` and `other`. |
245
+
246
+ `\{`, `\}`, `\#` and `\\` write that character itself. An apostrophe is only an apostrophe: `Delete '{name}'?` works.
247
+ Each English message names the values it is given (`'filter.by': 'Filter by {type}'`): a translation may leave one out,
248
+ and it may use a value in any order, but it cannot ask for a value the message is never given (it would show as
249
+ written, `{kind}`).
250
+
251
+ ```ts
252
+ // Polish: "1 plik", "2 pliki", "5 plików", "1,5 pliku"
253
+ 'toolbar.deleteMany': '{count, plural, one {Usuń # plik} few {Usuń # pliki} many {Usuń # plików} other {Usuń # pliku}}'
254
+ ```
255
+
256
+ ### Finding a mistake before a visitor does
257
+
258
+ `checkFileBrowserMessages(messages)` checks a `messages` object without showing anything, and `describeMessageProblem`
259
+ turns each problem into a sentence. It finds a key that does not exist (with the nearest real one), a value that is not
260
+ text, a template that does not parse, and a message that asks for a value it is never given. An empty list means every
261
+ message will be used. Put it in a test of your page:
262
+
263
+ ```ts
264
+ import { checkFileBrowserMessages, describeMessageProblem } from '@widgetic/file-browser';
265
+ import german from './file-browser.de.json';
266
+
267
+ expect(checkFileBrowserMessages(german).map(describeMessageProblem)).toEqual([]);
268
+ ```
269
+
270
+ While the File Browser runs, a message that cannot be used is never thrown: the English text of that key is shown and
271
+ the console says `[FileBrowser] ...` once.
272
+
273
+ ### What stays as it is
274
+
275
+ - **Words that belong to someone else.** The File Browser shows what your media library says as it says it: the message
276
+ of an error you throw from `list`, `upload`, `rename` or `delete` is not translated (the `libraryError.` messages are
277
+ only used when the library gave no reason), and neither are your file names, your library's `label`, or the names
278
+ of folders a visitor made. The same goes for a sentence Widgetic's API sends back.
279
+ - **`error` events.** `event.detail.message` stays English: it is for your logs, not for the visitor.
280
+ - **Right to left.** Arabic and Hebrew words show, and numbers and dates follow the locale, but the layout does not
281
+ flip: this version is made for left to right languages.
282
+ - **The design system.** The words of the Rename and New folder windows, the close button of every window, the path
283
+ bar and the PDF viewer come from `@widgetic/design-system` **0.5.16 or newer**; with an older one those words stay
284
+ English (nothing breaks). The File Browser's own words are not affected.
285
+
286
+ The `@widgetic/ui-sdk` module of the File Browser takes the same `locale` and `messages`, and adds `setLanguage()`; see
287
+ its README, "Speaking your visitors' language".
288
+
64
289
  ## Available Components
65
290
 
66
291
  The package exports all components from:
@@ -1,6 +1,7 @@
1
1
  <script lang="ts">
2
2
  import type { FileSystemItem } from '../types';
3
3
  import { getFolderIcon } from '../utils/folderUtils';
4
+ import { useI18n } from '../i18n';
4
5
  // Import IconArrowBounce
5
6
  import { IconArrowBounce } from '@widgetic/design-system/icons';
6
7
 
@@ -22,6 +23,8 @@
22
23
  export let currentLocationClass = "text-sm text-[hsl(var(--info))] mr-2";
23
24
  export let selectedIcon = IconArrowBounce;
24
25
 
26
+ const { t } = useI18n();
27
+
25
28
  // Filter children to only include folders
26
29
  $: folderChildren = folder.children?.filter(item => item.type === 'folder') || [];
27
30
  $: isSelected = selectedFolder?.id === folder.id;
@@ -66,7 +69,7 @@
66
69
  <span class="flex-grow text-left {isCurrentLocation ? 'text-[hsl(var(--grey3))]' : 'text-[hsl(var(--grey7))]'} {isSelected ? 'font-bold' : 'font-normal'} body-medium truncate">{folder.name}</span>
67
70
  <div class="flex items-center ml-auto">
68
71
  {#if isCurrentLocation}
69
- <span class="h6 text-[hsl(var(--sage-green))] relative z-10">current location</span>
72
+ <span class="h6 text-[hsl(var(--sage-green))] relative z-10">{$t('folder.currentLocation')}</span>
70
73
  {/if}
71
74
  {#if isSelected}
72
75
  <svelte:component this={selectedIcon} class="{selectedIconClass}" />
@@ -13,14 +13,10 @@ interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> =
13
13
  z_$$bindings?: Bindings;
14
14
  }
15
15
  declare const FolderTree: $$__sveltets_2_IsomorphicComponent<{
16
- folder: FileSystemItem & {
17
- displayChildren?: FileSystemItem[];
18
- };
16
+ folder: any;
19
17
  selectedFolder: FileSystemItem | undefined;
20
18
  immediateParentId: string | null;
21
- onSelect: (folder: FileSystemItem & {
22
- displayChildren?: FileSystemItem[];
23
- }) => void;
19
+ onSelect: (folder: any) => void;
24
20
  getFolderIconForItem: (folder: FileSystemItem) => string;
25
21
  customClasses?: string;
26
22
  iconSize?: string;