@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.
- package/README.md +279 -0
- package/dist/components/FolderTree.svelte +16 -9
- package/dist/components/FolderTree.svelte.d.ts +2 -6
- package/dist/components/core/FileBrowser.svelte +529 -127
- package/dist/components/core/FileBrowser.svelte.d.ts +40 -1
- package/dist/components/core/FileUploader.svelte +130 -57
- package/dist/components/core/Header.svelte +13 -2
- package/dist/components/core/Header.svelte.d.ts +1 -0
- package/dist/components/core/RecentFiles.svelte +41 -29
- package/dist/components/core/UploadStatus.svelte +14 -7
- package/dist/components/core/UploadStatusList.svelte +13 -21
- package/dist/components/items/FileItem.svelte +28 -15
- package/dist/components/items/FolderItem.svelte +13 -6
- package/dist/components/modals/MoveDialog.svelte +49 -38
- package/dist/components/modals/NewFolderButton.svelte +5 -2
- package/dist/components/modals/SearchModal.svelte +25 -26
- package/dist/components/modals/SearchModal.svelte.d.ts +1 -1
- package/dist/components/modals/SelectedFilesModal.svelte +23 -14
- package/dist/components/modals/SelectedFilesModal.svelte.d.ts +1 -1
- package/dist/components/previews/AudioPlayer.svelte +5 -2
- package/dist/components/previews/ErrorPreview.svelte +7 -4
- package/dist/components/previews/ErrorPreview.svelte.d.ts +1 -1
- package/dist/components/previews/FilePreview.svelte +25 -9
- package/dist/components/previews/FontPreview.svelte +18 -9
- package/dist/components/previews/FontPreview.svelte.d.ts +1 -1
- package/dist/components/previews/TextPreview.svelte +12 -5
- package/dist/components/previews/VideoPlayer.svelte +11 -7
- package/dist/components/ui/ControlToolbar.svelte +50 -28
- package/dist/components/ui/ControlToolbar.svelte.d.ts +1 -1
- package/dist/components/ui/DragSelect.svelte +3 -2
- package/dist/components/ui/DropdownMenu.svelte +35 -14
- package/dist/components/ui/FileIcon.svelte +8 -5
- package/dist/components/ui/FileIcon.svelte.d.ts +1 -0
- package/dist/components/ui/FileMetadata.svelte +16 -15
- package/dist/components/ui/SearchResults.svelte +9 -2
- package/dist/i18n/context.d.ts +28 -0
- package/dist/i18n/context.js +17 -0
- package/dist/i18n/errors.d.ts +11 -0
- package/dist/i18n/errors.js +19 -0
- package/dist/i18n/index.d.ts +15 -0
- package/dist/i18n/index.js +18 -0
- package/dist/i18n/messages.d.ts +281 -0
- package/dist/i18n/messages.js +294 -0
- package/dist/i18n/text.d.ts +19 -0
- package/dist/i18n/text.js +35 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -0
- package/dist/mediaLibrary/capabilities.d.ts +22 -0
- package/dist/mediaLibrary/capabilities.js +42 -0
- package/dist/mediaLibrary/context.d.ts +17 -0
- package/dist/mediaLibrary/context.js +16 -0
- package/dist/mediaLibrary/errors.d.ts +42 -0
- package/dist/mediaLibrary/errors.js +114 -0
- package/dist/mediaLibrary/index.d.ts +10 -0
- package/dist/mediaLibrary/index.js +9 -0
- package/dist/mediaLibrary/normalize.d.ts +39 -0
- package/dist/mediaLibrary/normalize.js +139 -0
- package/dist/mediaLibrary/paging.d.ts +37 -0
- package/dist/mediaLibrary/paging.js +62 -0
- package/dist/mediaLibrary/resolve.d.ts +39 -0
- package/dist/mediaLibrary/resolve.js +137 -0
- package/dist/mediaLibrary/treeOps.d.ts +24 -0
- package/dist/mediaLibrary/treeOps.js +67 -0
- package/dist/mediaLibrary/types.d.ts +126 -0
- package/dist/mediaLibrary/types.js +11 -0
- package/dist/mediaLibrary/urls.d.ts +30 -0
- package/dist/mediaLibrary/urls.js +59 -0
- package/dist/mediaLibrary/widgetic.d.ts +39 -0
- package/dist/mediaLibrary/widgetic.js +89 -0
- package/dist/stores/fileStore.d.ts +2 -2
- package/dist/stores/folderCountStore.js +2 -2
- package/dist/stores/navigationStore.d.ts +1 -1
- package/dist/stores/persistentSelectStore.d.ts +11 -1
- package/dist/stores/persistentSelectStore.js +26 -0
- package/dist/utils/dateUtils.d.ts +11 -2
- package/dist/utils/dateUtils.js +20 -15
- package/dist/utils/fileKinds.d.ts +44 -0
- package/dist/utils/fileKinds.js +96 -0
- package/dist/utils/fileNames.d.ts +7 -0
- package/dist/utils/fileNames.js +19 -0
- package/dist/utils/fileOperations.js +2 -11
- package/dist/utils/fileTypes.d.ts +11 -2
- package/dist/utils/fileTypes.js +26 -14
- package/dist/utils/fileUtils.d.ts +8 -1
- package/dist/utils/fileUtils.js +22 -7
- package/dist/utils/folderUtils.js +3 -2
- package/dist/utils/previewKeys.d.ts +12 -0
- package/dist/utils/previewKeys.js +14 -0
- package/dist/utils/safeText.d.ts +29 -0
- package/dist/utils/safeText.js +66 -0
- package/dist/utils/userUploadsStorage.d.ts +4 -1
- package/dist/utils/userUploadsStorage.js +5 -2
- package/dist/utils/widgeticTusUpload.d.ts +10 -0
- package/dist/utils/widgeticTusUpload.js +61 -3
- package/dist/utils/widgeticUpload.d.ts +3 -0
- package/dist/utils/widgeticUpload.js +7 -2
- package/package.json +5 -2
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { MediaLibraryError, isAbortError, isCancellation, isUnauthorized, toMediaLibraryError } from './errors';
|
|
2
|
+
export { LEGACY_CAPABILITIES, NO_CAPABILITIES, capabilitiesOf } from './capabilities';
|
|
3
|
+
export { appendNewFiles, createLibraryRoot, removeFiles, replaceFile, upsertFile } from './treeOps';
|
|
4
|
+
export { toSafeMediaUrl } from './urls';
|
|
5
|
+
export { normalizeMediaLibraryFile, normalizeMediaLibraryPage } from './normalize';
|
|
6
|
+
export { DEFAULT_LIBRARY_LABEL, resolveMediaLibrary } from './resolve';
|
|
7
|
+
export { loadLibraryPages } from './paging';
|
|
8
|
+
export { createWidgeticMediaLibrary } from './widgetic';
|
|
9
|
+
export { provideMediaLibraryContext, useMediaLibraryContext } from './context';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { FileSystemItem } from '../types';
|
|
2
|
+
/** Limits that keep a library's data from breaking the screen. A value over its limit is cut or refused. */
|
|
3
|
+
export declare const LIMITS: {
|
|
4
|
+
readonly idLength: 512;
|
|
5
|
+
readonly nameLength: 255;
|
|
6
|
+
readonly hashLength: 256;
|
|
7
|
+
readonly cursorLength: 2048;
|
|
8
|
+
/** More files than this in one page are ignored. */
|
|
9
|
+
readonly itemsPerPage: 1000;
|
|
10
|
+
};
|
|
11
|
+
export interface NormalizeOptions {
|
|
12
|
+
/** The page's address, to make relative file addresses absolute. Default: the current page. */
|
|
13
|
+
baseHref?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Checks one file a library gave and turns it into the File Browser's own item.
|
|
17
|
+
*
|
|
18
|
+
* Throws a {@link MediaLibraryError} (`INVALID_RESPONSE`) saying what is wrong when the file cannot be shown:
|
|
19
|
+
* no id, no name, or no address the browser may fetch. Optional fields that are wrong (a size of -1, a media type
|
|
20
|
+
* of `banana`) are dropped instead: the file is still usable without them.
|
|
21
|
+
*/
|
|
22
|
+
export declare function normalizeMediaLibraryFile(raw: unknown, options?: NormalizeOptions): FileSystemItem;
|
|
23
|
+
/** One page of a library after checking. */
|
|
24
|
+
export interface NormalizedPage {
|
|
25
|
+
items: FileSystemItem[];
|
|
26
|
+
/** What to pass back for the next page, or `null` when this was the last. */
|
|
27
|
+
nextCursor: string | null;
|
|
28
|
+
/** How many files were left out because they were not valid, or repeated an earlier id. */
|
|
29
|
+
skipped: number;
|
|
30
|
+
/** Why the first few were left out, for the log. */
|
|
31
|
+
skippedReasons: string[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Checks a page a library gave. A file that is not valid is left out (and counted); the rest is shown, because
|
|
35
|
+
* one bad record in a library of thousands must not leave the visitor with an empty screen.
|
|
36
|
+
*
|
|
37
|
+
* Throws only when the page itself is not a page: it is not `{ items: [...] }` (a bare array is accepted too).
|
|
38
|
+
*/
|
|
39
|
+
export declare function normalizeMediaLibraryPage(raw: unknown, options?: NormalizeOptions): NormalizedPage;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { MediaLibraryError } from './errors';
|
|
2
|
+
import { toSafeMediaUrl } from './urls';
|
|
3
|
+
/** Limits that keep a library's data from breaking the screen. A value over its limit is cut or refused. */
|
|
4
|
+
export const LIMITS = {
|
|
5
|
+
idLength: 512,
|
|
6
|
+
nameLength: 255,
|
|
7
|
+
hashLength: 256,
|
|
8
|
+
cursorLength: 2048,
|
|
9
|
+
/** More files than this in one page are ignored. */
|
|
10
|
+
itemsPerPage: 1000
|
|
11
|
+
};
|
|
12
|
+
const MEDIA_TYPE_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
|
|
13
|
+
/** Control characters (line breaks, tabs, NUL ...) have no place in a name shown on one line. */
|
|
14
|
+
// eslint-disable-next-line no-control-regex
|
|
15
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]+/g;
|
|
16
|
+
function isPlainObject(value) {
|
|
17
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function toIdOrNull(value) {
|
|
20
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
21
|
+
return String(value);
|
|
22
|
+
if (typeof value !== 'string')
|
|
23
|
+
return null;
|
|
24
|
+
const trimmed = value.trim();
|
|
25
|
+
return trimmed !== '' && trimmed.length <= LIMITS.idLength ? trimmed : null;
|
|
26
|
+
}
|
|
27
|
+
function toNameOrNull(value) {
|
|
28
|
+
if (typeof value !== 'string')
|
|
29
|
+
return null;
|
|
30
|
+
const cleaned = value.replace(CONTROL_CHARACTERS, ' ').trim();
|
|
31
|
+
if (cleaned === '')
|
|
32
|
+
return null;
|
|
33
|
+
return cleaned.length > LIMITS.nameLength ? cleaned.slice(0, LIMITS.nameLength) : cleaned;
|
|
34
|
+
}
|
|
35
|
+
function toIsoDateOrUndefined(value) {
|
|
36
|
+
let date = null;
|
|
37
|
+
if (value instanceof Date)
|
|
38
|
+
date = value;
|
|
39
|
+
else if (typeof value === 'number' && Number.isFinite(value))
|
|
40
|
+
date = new Date(value);
|
|
41
|
+
else if (typeof value === 'string' && value.trim() !== '')
|
|
42
|
+
date = new Date(value);
|
|
43
|
+
return date !== null && !Number.isNaN(date.getTime()) ? date.toISOString() : undefined;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Checks one file a library gave and turns it into the File Browser's own item.
|
|
47
|
+
*
|
|
48
|
+
* Throws a {@link MediaLibraryError} (`INVALID_RESPONSE`) saying what is wrong when the file cannot be shown:
|
|
49
|
+
* no id, no name, or no address the browser may fetch. Optional fields that are wrong (a size of -1, a media type
|
|
50
|
+
* of `banana`) are dropped instead: the file is still usable without them.
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeMediaLibraryFile(raw, options = {}) {
|
|
53
|
+
if (!isPlainObject(raw)) {
|
|
54
|
+
throw new MediaLibraryError('INVALID_RESPONSE', 'A file in the media library is not an object');
|
|
55
|
+
}
|
|
56
|
+
const id = toIdOrNull(raw.id);
|
|
57
|
+
if (id === null) {
|
|
58
|
+
throw new MediaLibraryError('INVALID_RESPONSE', 'A file in the media library has no id (a non-empty string)');
|
|
59
|
+
}
|
|
60
|
+
const name = toNameOrNull(raw.name);
|
|
61
|
+
if (name === null) {
|
|
62
|
+
throw new MediaLibraryError('INVALID_RESPONSE', `The file "${id}" in the media library has no name`);
|
|
63
|
+
}
|
|
64
|
+
const url = toSafeMediaUrl(raw.url, { baseHref: options.baseHref });
|
|
65
|
+
if (url === null) {
|
|
66
|
+
throw new MediaLibraryError('INVALID_RESPONSE', `The file "${id}" in the media library has no usable url (it must be an http or https address, or a path on this site)`);
|
|
67
|
+
}
|
|
68
|
+
const mimeType = typeof raw.mimeType === 'string' && MEDIA_TYPE_PATTERN.test(raw.mimeType.trim())
|
|
69
|
+
? raw.mimeType.trim().toLowerCase()
|
|
70
|
+
: undefined;
|
|
71
|
+
const size = typeof raw.size === 'number' && Number.isFinite(raw.size) && raw.size >= 0
|
|
72
|
+
? raw.size
|
|
73
|
+
: undefined;
|
|
74
|
+
const thumbnail = toSafeMediaUrl(raw.thumbnail, { baseHref: options.baseHref, allowDataPicture: true }) ??
|
|
75
|
+
undefined;
|
|
76
|
+
const hash = typeof raw.hash === 'string' && raw.hash !== '' && raw.hash.length <= LIMITS.hashLength
|
|
77
|
+
? raw.hash
|
|
78
|
+
: undefined;
|
|
79
|
+
const modified = toIsoDateOrUndefined(raw.modified);
|
|
80
|
+
return {
|
|
81
|
+
id,
|
|
82
|
+
name,
|
|
83
|
+
type: 'file',
|
|
84
|
+
url,
|
|
85
|
+
...(mimeType !== undefined && { mimeType }),
|
|
86
|
+
...(size !== undefined && { size }),
|
|
87
|
+
...(modified !== undefined && { modified }),
|
|
88
|
+
...(thumbnail !== undefined && { thumbnail }),
|
|
89
|
+
...(hash !== undefined && { hash })
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function toCursorOrNull(value) {
|
|
93
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
94
|
+
return String(value);
|
|
95
|
+
if (typeof value !== 'string')
|
|
96
|
+
return null;
|
|
97
|
+
return value !== '' && value.length <= LIMITS.cursorLength ? value : null;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Checks a page a library gave. A file that is not valid is left out (and counted); the rest is shown, because
|
|
101
|
+
* one bad record in a library of thousands must not leave the visitor with an empty screen.
|
|
102
|
+
*
|
|
103
|
+
* Throws only when the page itself is not a page: it is not `{ items: [...] }` (a bare array is accepted too).
|
|
104
|
+
*/
|
|
105
|
+
export function normalizeMediaLibraryPage(raw, options = {}) {
|
|
106
|
+
const rawItems = Array.isArray(raw) ? raw : isPlainObject(raw) ? raw.items : undefined;
|
|
107
|
+
if (!Array.isArray(rawItems)) {
|
|
108
|
+
throw new MediaLibraryError('INVALID_RESPONSE', "The media library's list must resolve to { items: [...], nextCursor? }");
|
|
109
|
+
}
|
|
110
|
+
const nextCursor = isPlainObject(raw) ? toCursorOrNull(raw.nextCursor) : null;
|
|
111
|
+
const items = [];
|
|
112
|
+
const seenIds = new Set();
|
|
113
|
+
const skippedReasons = [];
|
|
114
|
+
let skipped = 0;
|
|
115
|
+
const note = (reason) => {
|
|
116
|
+
skipped += 1;
|
|
117
|
+
if (skippedReasons.length < 3)
|
|
118
|
+
skippedReasons.push(reason);
|
|
119
|
+
};
|
|
120
|
+
rawItems.slice(0, LIMITS.itemsPerPage).forEach((rawItem) => {
|
|
121
|
+
try {
|
|
122
|
+
const item = normalizeMediaLibraryFile(rawItem, options);
|
|
123
|
+
if (seenIds.has(item.id)) {
|
|
124
|
+
note(`The file id "${item.id}" appears twice`);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
seenIds.add(item.id);
|
|
128
|
+
items.push(item);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
note(error instanceof Error ? error.message : String(error));
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
if (rawItems.length > LIMITS.itemsPerPage) {
|
|
135
|
+
skipped += rawItems.length - LIMITS.itemsPerPage;
|
|
136
|
+
skippedReasons.push(`Only the first ${LIMITS.itemsPerPage} files of a page are used`);
|
|
137
|
+
}
|
|
138
|
+
return { items, nextCursor, skipped, skippedReasons };
|
|
139
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { FileSystemItem } from '../types';
|
|
2
|
+
import { MediaLibraryError } from './errors';
|
|
3
|
+
import type { ResolvedMediaLibrary } from './resolve';
|
|
4
|
+
/** How many files the File Browser asks for per page. */
|
|
5
|
+
export declare const DEFAULT_PAGE_SIZE = 100;
|
|
6
|
+
/**
|
|
7
|
+
* The most files the File Browser loads. Files beyond it are not shown (search and filters only look at the files
|
|
8
|
+
* that were loaded), so a library with more files should list the ones a visitor is most likely to want first.
|
|
9
|
+
*/
|
|
10
|
+
export declare const DEFAULT_MAX_ITEMS = 1000;
|
|
11
|
+
/** A safety stop: no library is read for more pages than this, whatever it says about having more. */
|
|
12
|
+
export declare const DEFAULT_MAX_PAGES = 50;
|
|
13
|
+
export interface LoadLibraryOptions {
|
|
14
|
+
pageSize?: number;
|
|
15
|
+
maxItems?: number;
|
|
16
|
+
maxPages?: number;
|
|
17
|
+
signal: AbortSignal;
|
|
18
|
+
/** Called with the new files of each page as soon as it arrives, so the grid fills in while the rest loads. */
|
|
19
|
+
onPage?: (newItems: FileSystemItem[], pageNumber: number) => void;
|
|
20
|
+
}
|
|
21
|
+
export interface LoadedLibrary {
|
|
22
|
+
items: FileSystemItem[];
|
|
23
|
+
/** True when the library has more files than were loaded: a limit was reached, or a later page failed. */
|
|
24
|
+
truncated: boolean;
|
|
25
|
+
/** Set when a page after the first failed. The files loaded before it are still in `items`. */
|
|
26
|
+
failure?: MediaLibraryError;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Reads a library page by page, newest first, until it runs out or a limit is reached.
|
|
30
|
+
*
|
|
31
|
+
* A library is another party's code, so the loop cannot trust it to end: it stops when a cursor comes back that was
|
|
32
|
+
* already used, when a page adds nothing new, and after a fixed number of files and pages.
|
|
33
|
+
*
|
|
34
|
+
* The first page failing throws (there is nothing to show). A later page failing returns what was loaded with the
|
|
35
|
+
* failure attached, because most of the library is better than none of it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function loadLibraryPages(library: ResolvedMediaLibrary, options: LoadLibraryOptions): Promise<LoadedLibrary>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { MediaLibraryError, toMediaLibraryError } from './errors';
|
|
2
|
+
/** How many files the File Browser asks for per page. */
|
|
3
|
+
export const DEFAULT_PAGE_SIZE = 100;
|
|
4
|
+
/**
|
|
5
|
+
* The most files the File Browser loads. Files beyond it are not shown (search and filters only look at the files
|
|
6
|
+
* that were loaded), so a library with more files should list the ones a visitor is most likely to want first.
|
|
7
|
+
*/
|
|
8
|
+
export const DEFAULT_MAX_ITEMS = 1000;
|
|
9
|
+
/** A safety stop: no library is read for more pages than this, whatever it says about having more. */
|
|
10
|
+
export const DEFAULT_MAX_PAGES = 50;
|
|
11
|
+
/**
|
|
12
|
+
* Reads a library page by page, newest first, until it runs out or a limit is reached.
|
|
13
|
+
*
|
|
14
|
+
* A library is another party's code, so the loop cannot trust it to end: it stops when a cursor comes back that was
|
|
15
|
+
* already used, when a page adds nothing new, and after a fixed number of files and pages.
|
|
16
|
+
*
|
|
17
|
+
* The first page failing throws (there is nothing to show). A later page failing returns what was loaded with the
|
|
18
|
+
* failure attached, because most of the library is better than none of it.
|
|
19
|
+
*/
|
|
20
|
+
export async function loadLibraryPages(library, options) {
|
|
21
|
+
const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
22
|
+
const maxItems = options.maxItems ?? DEFAULT_MAX_ITEMS;
|
|
23
|
+
const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
|
|
24
|
+
const items = [];
|
|
25
|
+
const seenIds = new Set();
|
|
26
|
+
const usedCursors = new Set();
|
|
27
|
+
let cursor;
|
|
28
|
+
for (let pageNumber = 1; pageNumber <= maxPages; pageNumber += 1) {
|
|
29
|
+
let page;
|
|
30
|
+
try {
|
|
31
|
+
page = await library.listPage({ cursor, limit: pageSize, signal: options.signal });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
const failure = toMediaLibraryError(error, 'Could not load the files', 'libraryError.loadFailed');
|
|
35
|
+
if (pageNumber === 1 || failure.code === 'ABORTED')
|
|
36
|
+
throw failure;
|
|
37
|
+
console.warn(`[FileBrowser] Page ${pageNumber} of the media library "${library.id}" failed; showing the ${items.length} files already loaded:`, failure.message);
|
|
38
|
+
return { items, truncated: true, failure };
|
|
39
|
+
}
|
|
40
|
+
if (page.skipped > 0) {
|
|
41
|
+
console.warn(`[FileBrowser] The media library "${library.id}" gave ${page.skipped} file(s) on page ${pageNumber} that cannot be shown:`, page.skippedReasons);
|
|
42
|
+
}
|
|
43
|
+
const newItems = page.items.filter((item) => !seenIds.has(item.id));
|
|
44
|
+
newItems.forEach((item) => seenIds.add(item.id));
|
|
45
|
+
items.push(...newItems);
|
|
46
|
+
if (newItems.length > 0)
|
|
47
|
+
options.onPage?.(newItems, pageNumber);
|
|
48
|
+
if (page.nextCursor === null)
|
|
49
|
+
return { items, truncated: false };
|
|
50
|
+
// The library says there is more. Make sure it is not going in circles before asking again.
|
|
51
|
+
if (newItems.length === 0 || usedCursors.has(page.nextCursor) || page.nextCursor === cursor) {
|
|
52
|
+
const failure = new MediaLibraryError('INVALID_RESPONSE', 'The media library keeps returning the same files, so the rest was not loaded', { messageKey: 'libraryError.repeatedPage' });
|
|
53
|
+
console.warn(`[FileBrowser] The media library "${library.id}" returned a page with nothing new or a repeated cursor; stopping at ${items.length} files`);
|
|
54
|
+
return { items, truncated: true, failure };
|
|
55
|
+
}
|
|
56
|
+
if (items.length >= maxItems)
|
|
57
|
+
return { items, truncated: true };
|
|
58
|
+
usedCursors.add(page.nextCursor);
|
|
59
|
+
cursor = page.nextCursor;
|
|
60
|
+
}
|
|
61
|
+
return { items, truncated: true };
|
|
62
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { FileSystemItem } from '../types';
|
|
2
|
+
import { type NormalizedPage } from './normalize';
|
|
3
|
+
import type { MediaLibraryCapabilities, MediaLibraryDeleteRequest, MediaLibraryListRequest, MediaLibraryRenameRequest, MediaLibraryUploadRequest } from './types';
|
|
4
|
+
/** How long a library gets to answer `list`, `rename` and `delete` before the File Browser gives up on it. */
|
|
5
|
+
export declare const DEFAULT_CALL_TIMEOUT_MS = 30000;
|
|
6
|
+
/** The name of the folder the library's files are shown in, unless the library names it. */
|
|
7
|
+
export declare const DEFAULT_LIBRARY_LABEL = "My uploads";
|
|
8
|
+
/**
|
|
9
|
+
* A library as the File Browser uses it: every answer already checked, every failure already a
|
|
10
|
+
* {@link MediaLibraryError}, and the actions the visitor may use already decided.
|
|
11
|
+
*/
|
|
12
|
+
export interface ResolvedMediaLibrary {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly label: string;
|
|
15
|
+
/** True when the library named itself; false when `label` is the default, which the File Browser words in the visitor's language. */
|
|
16
|
+
readonly hasOwnLabel: boolean;
|
|
17
|
+
readonly capabilities: MediaLibraryCapabilities;
|
|
18
|
+
/** One checked page of the library. */
|
|
19
|
+
listPage(request: MediaLibraryListRequest): Promise<NormalizedPage>;
|
|
20
|
+
/** Stores a file; resolves to the file as the library knows it. Absent when the library cannot store files. */
|
|
21
|
+
upload?: (request: MediaLibraryUploadRequest) => Promise<FileSystemItem>;
|
|
22
|
+
/** Renames a file; resolves to the renamed file, or `null` when the library did not say. Absent when it cannot. */
|
|
23
|
+
rename?: (request: MediaLibraryRenameRequest) => Promise<FileSystemItem | null>;
|
|
24
|
+
/** Removes a file. Absent when the library cannot. */
|
|
25
|
+
remove?: (request: MediaLibraryDeleteRequest) => Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
export interface ResolveOptions {
|
|
28
|
+
/** The page's address, to make relative file addresses absolute. Default: the current page. */
|
|
29
|
+
baseHref?: string;
|
|
30
|
+
/** See {@link DEFAULT_CALL_TIMEOUT_MS}. */
|
|
31
|
+
callTimeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Checks a provider a host passed in and wraps it for the File Browser.
|
|
35
|
+
*
|
|
36
|
+
* Throws a `TypeError` naming the problem when it is not a provider (no `list` function), so a partner's mistake
|
|
37
|
+
* shows up at mount time with a clear message instead of as an empty screen.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveMediaLibrary(provider: unknown, options?: ResolveOptions): ResolvedMediaLibrary;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { capabilitiesOf } from './capabilities';
|
|
2
|
+
import { MediaLibraryError, toMediaLibraryError } from './errors';
|
|
3
|
+
import { normalizeMediaLibraryFile, normalizeMediaLibraryPage } from './normalize';
|
|
4
|
+
/** How long a library gets to answer `list`, `rename` and `delete` before the File Browser gives up on it. */
|
|
5
|
+
export const DEFAULT_CALL_TIMEOUT_MS = 30_000;
|
|
6
|
+
/** The name of the folder the library's files are shown in, unless the library names it. */
|
|
7
|
+
export const DEFAULT_LIBRARY_LABEL = 'My uploads';
|
|
8
|
+
/** What the visitor is told when a library does not answer in time. */
|
|
9
|
+
const TIMEOUT_MESSAGE = 'The media library did not answer in time';
|
|
10
|
+
/**
|
|
11
|
+
* Runs one call of a library with a time limit. The library gets an `AbortSignal` that fires on timeout or when the
|
|
12
|
+
* caller gives up; a library that ignores it is still let go of, so the screen never waits forever.
|
|
13
|
+
*/
|
|
14
|
+
async function callWithTimeout(run, callerSignal, timeoutMs) {
|
|
15
|
+
if (callerSignal.aborted)
|
|
16
|
+
throw new MediaLibraryError('ABORTED', 'The request was cancelled');
|
|
17
|
+
const callController = new AbortController();
|
|
18
|
+
const forwardAbort = () => callController.abort();
|
|
19
|
+
callerSignal.addEventListener('abort', forwardAbort, { once: true });
|
|
20
|
+
let timer;
|
|
21
|
+
const timedOut = new Promise((_, reject) => {
|
|
22
|
+
timer = setTimeout(() => {
|
|
23
|
+
callController.abort();
|
|
24
|
+
reject(new MediaLibraryError('NETWORK', TIMEOUT_MESSAGE, { messageKey: 'libraryError.timeout' }));
|
|
25
|
+
}, timeoutMs);
|
|
26
|
+
});
|
|
27
|
+
const cancelled = new Promise((_, reject) => {
|
|
28
|
+
callController.signal.addEventListener('abort', () => {
|
|
29
|
+
if (callerSignal.aborted)
|
|
30
|
+
reject(new MediaLibraryError('ABORTED', 'The request was cancelled'));
|
|
31
|
+
}, { once: true });
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
return await Promise.race([run(callController.signal), timedOut, cancelled]);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
if (timer !== undefined)
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
callerSignal.removeEventListener('abort', forwardAbort);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function isObject(value) {
|
|
43
|
+
return value !== null && typeof value === 'object';
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Checks a provider a host passed in and wraps it for the File Browser.
|
|
47
|
+
*
|
|
48
|
+
* Throws a `TypeError` naming the problem when it is not a provider (no `list` function), so a partner's mistake
|
|
49
|
+
* shows up at mount time with a clear message instead of as an empty screen.
|
|
50
|
+
*/
|
|
51
|
+
export function resolveMediaLibrary(provider, options = {}) {
|
|
52
|
+
if (!isObject(provider) || typeof provider.list !== 'function') {
|
|
53
|
+
throw new TypeError('mediaLibrary must be an object with a list({ cursor, limit, signal }) function');
|
|
54
|
+
}
|
|
55
|
+
for (const optionalFunction of ['upload', 'rename', 'delete']) {
|
|
56
|
+
if (provider[optionalFunction] !== undefined &&
|
|
57
|
+
typeof provider[optionalFunction] !== 'function') {
|
|
58
|
+
throw new TypeError(`mediaLibrary.${optionalFunction} must be a function when it is given`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const library = provider;
|
|
62
|
+
const callTimeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
|
|
63
|
+
const normalizeOptions = { baseHref: options.baseHref };
|
|
64
|
+
const id = typeof library.id === 'string' && library.id.trim() !== ''
|
|
65
|
+
? library.id.trim().slice(0, 64)
|
|
66
|
+
: 'host';
|
|
67
|
+
const hasOwnLabel = typeof library.label === 'string' && library.label.trim() !== '';
|
|
68
|
+
const label = hasOwnLabel ? library.label.trim().slice(0, 64) : DEFAULT_LIBRARY_LABEL;
|
|
69
|
+
const capabilities = capabilitiesOf(library);
|
|
70
|
+
const resolved = {
|
|
71
|
+
id,
|
|
72
|
+
label,
|
|
73
|
+
hasOwnLabel,
|
|
74
|
+
capabilities,
|
|
75
|
+
async listPage(request) {
|
|
76
|
+
const raw = await callWithTimeout(async (signal) => {
|
|
77
|
+
try {
|
|
78
|
+
return await library.list({ ...request, signal });
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
throw toMediaLibraryError(error, 'Could not load the files', 'libraryError.loadFailed');
|
|
82
|
+
}
|
|
83
|
+
}, request.signal, callTimeoutMs);
|
|
84
|
+
return normalizeMediaLibraryPage(raw, normalizeOptions);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
if (capabilities.upload && typeof library.upload === 'function') {
|
|
88
|
+
resolved.upload = async (request) => {
|
|
89
|
+
let raw;
|
|
90
|
+
try {
|
|
91
|
+
raw = await library.upload(request);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw toMediaLibraryError(error, 'The upload failed', 'libraryError.uploadFailed');
|
|
95
|
+
}
|
|
96
|
+
// An upload the library accepted but described badly is reported, not shown: the visitor must not believe a
|
|
97
|
+
// file is there when the grid cannot show it.
|
|
98
|
+
return normalizeMediaLibraryFile(raw, normalizeOptions);
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (capabilities.rename && typeof library.rename === 'function') {
|
|
102
|
+
resolved.rename = async (request) => {
|
|
103
|
+
const raw = await callWithTimeout(async (signal) => {
|
|
104
|
+
try {
|
|
105
|
+
return await library.rename({ ...request, signal });
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
throw toMediaLibraryError(error, 'Could not rename the file', 'libraryError.renameFailed');
|
|
109
|
+
}
|
|
110
|
+
}, request.signal, callTimeoutMs);
|
|
111
|
+
if (raw === undefined || raw === null)
|
|
112
|
+
return null;
|
|
113
|
+
try {
|
|
114
|
+
return normalizeMediaLibraryFile(raw, normalizeOptions);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// The rename itself worked; only the description of the result is wrong, so the File Browser keeps the name
|
|
118
|
+
// the visitor typed.
|
|
119
|
+
console.warn(`[FileBrowser] The media library "${id}" renamed the file but described the result badly:`, error);
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
if (capabilities.delete && typeof library.delete === 'function') {
|
|
125
|
+
resolved.remove = async (request) => {
|
|
126
|
+
await callWithTimeout(async (signal) => {
|
|
127
|
+
try {
|
|
128
|
+
await library.delete({ ...request, signal });
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
throw toMediaLibraryError(error, 'Could not delete the file', 'libraryError.deleteFailed');
|
|
132
|
+
}
|
|
133
|
+
}, request.signal, callTimeoutMs);
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return resolved;
|
|
137
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { FileSystemItem } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* A media library is one flat list of files, so the File Browser's tree for it is a root folder whose children are
|
|
4
|
+
* the files. These helpers change that list the way the library's own answers do (a file arrives, is renamed, is
|
|
5
|
+
* removed). Each returns a new root and never changes what it was given, so a screen that still holds the old root
|
|
6
|
+
* is not surprised.
|
|
7
|
+
*/
|
|
8
|
+
/** The root folder of a library's tree. */
|
|
9
|
+
export declare function createLibraryRoot(files: FileSystemItem[]): FileSystemItem;
|
|
10
|
+
/** Adds the files whose id is not in the list yet. A file already in the list is left exactly as it is. */
|
|
11
|
+
export declare function appendNewFiles(root: FileSystemItem, files: FileSystemItem[]): FileSystemItem;
|
|
12
|
+
/**
|
|
13
|
+
* Puts a file in the list: replaces the file with the same id (a library may answer an upload with a file it
|
|
14
|
+
* already had), or adds it when it is new.
|
|
15
|
+
*/
|
|
16
|
+
export declare function upsertFile(root: FileSystemItem, file: FileSystemItem): FileSystemItem;
|
|
17
|
+
/**
|
|
18
|
+
* Replaces the file `id` with `file`. The new file may have another id (a library can name files by their path, and
|
|
19
|
+
* a rename then changes it). When another file in the list already has the new id, that one is dropped: the library
|
|
20
|
+
* says the id is now this file, and the list never holds two files with one id. An unknown `id` changes nothing.
|
|
21
|
+
*/
|
|
22
|
+
export declare function replaceFile(root: FileSystemItem, id: string, file: FileSystemItem): FileSystemItem;
|
|
23
|
+
/** Takes the files with these ids out of the list. */
|
|
24
|
+
export declare function removeFiles(root: FileSystemItem, ids: ReadonlySet<string>): FileSystemItem;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A media library is one flat list of files, so the File Browser's tree for it is a root folder whose children are
|
|
3
|
+
* the files. These helpers change that list the way the library's own answers do (a file arrives, is renamed, is
|
|
4
|
+
* removed). Each returns a new root and never changes what it was given, so a screen that still holds the old root
|
|
5
|
+
* is not surprised.
|
|
6
|
+
*/
|
|
7
|
+
/** The root folder of a library's tree. */
|
|
8
|
+
export function createLibraryRoot(files) {
|
|
9
|
+
return { id: 'root', name: 'Root', type: 'folder', children: files };
|
|
10
|
+
}
|
|
11
|
+
function childrenOf(root) {
|
|
12
|
+
return root.children ?? [];
|
|
13
|
+
}
|
|
14
|
+
/** Adds the files whose id is not in the list yet. A file already in the list is left exactly as it is. */
|
|
15
|
+
export function appendNewFiles(root, files) {
|
|
16
|
+
const knownIds = new Set(childrenOf(root).map((item) => item.id));
|
|
17
|
+
const newFiles = [];
|
|
18
|
+
for (const file of files) {
|
|
19
|
+
if (knownIds.has(file.id))
|
|
20
|
+
continue;
|
|
21
|
+
knownIds.add(file.id);
|
|
22
|
+
newFiles.push(file);
|
|
23
|
+
}
|
|
24
|
+
if (newFiles.length === 0)
|
|
25
|
+
return root;
|
|
26
|
+
return { ...root, children: [...childrenOf(root), ...newFiles] };
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Puts a file in the list: replaces the file with the same id (a library may answer an upload with a file it
|
|
30
|
+
* already had), or adds it when it is new.
|
|
31
|
+
*/
|
|
32
|
+
export function upsertFile(root, file) {
|
|
33
|
+
const children = childrenOf(root);
|
|
34
|
+
const index = children.findIndex((item) => item.id === file.id);
|
|
35
|
+
if (index === -1)
|
|
36
|
+
return { ...root, children: [...children, file] };
|
|
37
|
+
return {
|
|
38
|
+
...root,
|
|
39
|
+
children: children.map((item, position) => (position === index ? file : item))
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Replaces the file `id` with `file`. The new file may have another id (a library can name files by their path, and
|
|
44
|
+
* a rename then changes it). When another file in the list already has the new id, that one is dropped: the library
|
|
45
|
+
* says the id is now this file, and the list never holds two files with one id. An unknown `id` changes nothing.
|
|
46
|
+
*/
|
|
47
|
+
export function replaceFile(root, id, file) {
|
|
48
|
+
const children = childrenOf(root);
|
|
49
|
+
if (!children.some((item) => item.id === id))
|
|
50
|
+
return root;
|
|
51
|
+
const replaced = [];
|
|
52
|
+
for (const item of children) {
|
|
53
|
+
if (item.id === id)
|
|
54
|
+
replaced.push(file);
|
|
55
|
+
else if (item.id !== file.id)
|
|
56
|
+
replaced.push(item);
|
|
57
|
+
}
|
|
58
|
+
return { ...root, children: replaced };
|
|
59
|
+
}
|
|
60
|
+
/** Takes the files with these ids out of the list. */
|
|
61
|
+
export function removeFiles(root, ids) {
|
|
62
|
+
const children = childrenOf(root);
|
|
63
|
+
const kept = children.filter((item) => !ids.has(item.id));
|
|
64
|
+
if (kept.length === children.length)
|
|
65
|
+
return root;
|
|
66
|
+
return { ...root, children: kept };
|
|
67
|
+
}
|