@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,96 @@
|
|
|
1
|
+
import { FILE_TYPES } from './fileTypes';
|
|
2
|
+
/**
|
|
3
|
+
* Types a host sends when it does not really know what a file is.
|
|
4
|
+
* They say nothing about the file, so the file name decides instead.
|
|
5
|
+
*/
|
|
6
|
+
const UNINFORMATIVE_MIME_TYPES = new Set([
|
|
7
|
+
'application/octet-stream',
|
|
8
|
+
'binary/octet-stream',
|
|
9
|
+
'application/unknown',
|
|
10
|
+
'application/x-unknown'
|
|
11
|
+
]);
|
|
12
|
+
/** The extension of a file name or URL path, with its dot and in lower case ("" when there is none). */
|
|
13
|
+
function extensionOf(fileName) {
|
|
14
|
+
const lastSegment = fileName.split(/[?#]/)[0].split('/').pop() ?? '';
|
|
15
|
+
const dotIndex = lastSegment.lastIndexOf('.');
|
|
16
|
+
// A leading dot (".env") is part of the name, not an extension.
|
|
17
|
+
return dotIndex > 0 ? lastSegment.slice(dotIndex).toLowerCase() : '';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* True when the mime type or the extension says the file is NOT a picture (a PDF, a text file...).
|
|
21
|
+
*
|
|
22
|
+
* The File Browser draws a remote file as an image thumbnail unless it knows better. A PDF or a text
|
|
23
|
+
* file cannot be drawn that way: the picture fails to load and the file would be shown as "missing"
|
|
24
|
+
* (red, and impossible to select). Those files get the file-type icon instead.
|
|
25
|
+
*
|
|
26
|
+
* A file whose type is not known (no usable mime type and no known document extension) is not
|
|
27
|
+
* reported here, so it keeps being tried as a picture.
|
|
28
|
+
*/
|
|
29
|
+
export function isKnownNonImageFile(file) {
|
|
30
|
+
const mimeType = (file.mimeType ?? '').trim().toLowerCase();
|
|
31
|
+
if (mimeType !== '' && !UNINFORMATIVE_MIME_TYPES.has(mimeType)) {
|
|
32
|
+
return !mimeType.startsWith('image/');
|
|
33
|
+
}
|
|
34
|
+
return FILE_TYPES.document.includes(extensionOf(file.name ?? ''));
|
|
35
|
+
}
|
|
36
|
+
/** Mime types of font files that do not start with `font/` (older servers still send these). */
|
|
37
|
+
const LEGACY_FONT_MIME_TYPES = new Set([
|
|
38
|
+
'application/font-woff',
|
|
39
|
+
'application/font-woff2',
|
|
40
|
+
'application/font-sfnt',
|
|
41
|
+
'application/x-font-ttf',
|
|
42
|
+
'application/x-font-otf',
|
|
43
|
+
'application/x-font-woff',
|
|
44
|
+
'application/vnd.ms-fontobject'
|
|
45
|
+
]);
|
|
46
|
+
/**
|
|
47
|
+
* The kind a file extension belongs to, read from a file name or an address (`photo.png`, `/media/a/photo.png?v=2`),
|
|
48
|
+
* or `null` when there is no extension or the tabs do not know it.
|
|
49
|
+
*/
|
|
50
|
+
export function fileKindFromExtension(nameOrAddress) {
|
|
51
|
+
const extension = extensionOf(nameOrAddress ?? '');
|
|
52
|
+
for (const [kind, extensions] of Object.entries(FILE_TYPES)) {
|
|
53
|
+
if (extensions.includes(extension))
|
|
54
|
+
return kind;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The kind a media type belongs to, or `null` when the media type says nothing (missing, or a "binary, who knows"
|
|
60
|
+
* type) or is not one of the kinds the tabs have.
|
|
61
|
+
*/
|
|
62
|
+
export function fileKindFromMimeType(mimeType) {
|
|
63
|
+
// "image/png; charset=binary" is still image/png. A missing or "binary, who knows" type matches none of the
|
|
64
|
+
// kinds below, so it ends up as null like any other type the tabs have no kind for.
|
|
65
|
+
const mime = (mimeType ?? '').split(';')[0].trim().toLowerCase();
|
|
66
|
+
if (mime === 'image/svg+xml')
|
|
67
|
+
return 'svg';
|
|
68
|
+
if (mime.startsWith('image/'))
|
|
69
|
+
return 'image';
|
|
70
|
+
if (mime.startsWith('video/'))
|
|
71
|
+
return 'video';
|
|
72
|
+
if (mime.startsWith('audio/'))
|
|
73
|
+
return 'audio';
|
|
74
|
+
if (mime.startsWith('font/') || LEGACY_FONT_MIME_TYPES.has(mime))
|
|
75
|
+
return 'font';
|
|
76
|
+
if (mime.startsWith('text/') || mime === 'application/pdf')
|
|
77
|
+
return 'document';
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The tab a file belongs to (image, video, audio, document, font, svg).
|
|
82
|
+
*
|
|
83
|
+
* Looks at everything the file came with, in this order: the extension in its address, the extension in its name,
|
|
84
|
+
* then its media type. The address comes first because it always has (a Widgetic upload has it right), and the
|
|
85
|
+
* rest only matter where it says nothing: a library that serves `/media/8f3a2c` (no extension at all), or a signed
|
|
86
|
+
* address that ends in `download`, still has a name like `logo.png` and a media type like `image/png`. Judging by
|
|
87
|
+
* the address alone would have put every one of those files under "document".
|
|
88
|
+
*
|
|
89
|
+
* A file nothing says anything about is a document.
|
|
90
|
+
*/
|
|
91
|
+
export function getFileTypeOf(file) {
|
|
92
|
+
return (fileKindFromExtension(file.url) ??
|
|
93
|
+
fileKindFromExtension(file.name) ??
|
|
94
|
+
fileKindFromMimeType(file.mimeType) ??
|
|
95
|
+
'document');
|
|
96
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The name a file gets when the visitor types `typedName` for it. A file keeps its extension so it stays the same
|
|
3
|
+
* kind of file: typing "holiday" for "beach.jpg" gives "holiday.jpg", while typing "holiday.jpg" stays as typed.
|
|
4
|
+
* A typed name with another extension ("holiday.png") also keeps the original one ("holiday.png.jpg"): a rename
|
|
5
|
+
* never changes what kind of file it is.
|
|
6
|
+
*/
|
|
7
|
+
export declare function getRenamedFileName(currentName: string, typedName: string): string;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The name a file gets when the visitor types `typedName` for it. A file keeps its extension so it stays the same
|
|
3
|
+
* kind of file: typing "holiday" for "beach.jpg" gives "holiday.jpg", while typing "holiday.jpg" stays as typed.
|
|
4
|
+
* A typed name with another extension ("holiday.png") also keeps the original one ("holiday.png.jpg"): a rename
|
|
5
|
+
* never changes what kind of file it is.
|
|
6
|
+
*/
|
|
7
|
+
export function getRenamedFileName(currentName, typedName) {
|
|
8
|
+
const currentNameParts = currentName.split('.');
|
|
9
|
+
const newNameParts = typedName.split('.');
|
|
10
|
+
// If current file has an extension but new name doesn't (or has a different one)
|
|
11
|
+
if (currentNameParts.length > 1 &&
|
|
12
|
+
(newNameParts.length === 1 ||
|
|
13
|
+
newNameParts[newNameParts.length - 1] !== currentNameParts[currentNameParts.length - 1])) {
|
|
14
|
+
// Preserve the original extension
|
|
15
|
+
const originalExtension = currentNameParts[currentNameParts.length - 1];
|
|
16
|
+
return `${typedName}.${originalExtension}`;
|
|
17
|
+
}
|
|
18
|
+
return typedName;
|
|
19
|
+
}
|
|
@@ -3,6 +3,7 @@ import { persistHistory } from '../stores/navigationStore';
|
|
|
3
3
|
import { get } from 'svelte/store';
|
|
4
4
|
import { updateFolderCounts } from '../stores/folderCountStore';
|
|
5
5
|
import { getFileType } from './fileUtils';
|
|
6
|
+
import { getRenamedFileName } from './fileNames';
|
|
6
7
|
import { ENDPOINTS } from './apiConfig';
|
|
7
8
|
// Add helper function for sorting folder contents
|
|
8
9
|
function sortFolderContents(items) {
|
|
@@ -94,17 +95,7 @@ export async function renameItem(itemId, newName) {
|
|
|
94
95
|
// For files, preserve the extension to maintain correct file type
|
|
95
96
|
let finalName = newName;
|
|
96
97
|
if (item.type === 'file') {
|
|
97
|
-
|
|
98
|
-
const newNameParts = newName.split('.');
|
|
99
|
-
// If current file has an extension but new name doesn't (or has a different one)
|
|
100
|
-
if (currentNameParts.length > 1 &&
|
|
101
|
-
(newNameParts.length === 1 ||
|
|
102
|
-
newNameParts[newNameParts.length - 1] !== currentNameParts[currentNameParts.length - 1])) {
|
|
103
|
-
// Preserve the original extension
|
|
104
|
-
const originalExtension = currentNameParts[currentNameParts.length - 1];
|
|
105
|
-
finalName = `${newName}.${originalExtension}`;
|
|
106
|
-
// console.log(`Preserving file extension for type consistency: ${newName} → ${finalName}`);
|
|
107
|
-
}
|
|
98
|
+
finalName = getRenamedFileName(item.name, newName);
|
|
108
99
|
}
|
|
109
100
|
// Get current sort settings
|
|
110
101
|
let currentSortCriteria = 'name';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Translate } from '../i18n/context';
|
|
1
2
|
export type FileFilterType = 'all' | 'image' | 'audio' | 'video' | 'document' | 'font' | 'svg';
|
|
2
3
|
export declare const PREVIEWABLE_TEXT_EXTENSIONS: readonly [".txt", ".md", ".csv", ".json", ".xml", ".log"];
|
|
3
4
|
export declare const FILE_TYPES: Record<Exclude<FileFilterType, 'all'>, string[]>;
|
|
@@ -5,8 +6,16 @@ export declare const FILTER_OPTIONS: FileFilterType[];
|
|
|
5
6
|
export declare function getAllowedFileTypes(filter: FileFilterType): string[];
|
|
6
7
|
export declare function getFileTypeFromExtension(extension: string): FileFilterType;
|
|
7
8
|
export declare function isPreviewableTextFile(filename: string): boolean;
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* One sentence that lists every kind of file with its extensions ("Add images (.jpg, .png), audio (.mp3) ..."). Pass the
|
|
11
|
+
* `t` of the File Browser to have it in the page's language (English when left out).
|
|
12
|
+
*/
|
|
13
|
+
export declare function formatFileTypesForDisplay(translate?: Translate): string;
|
|
14
|
+
/**
|
|
15
|
+
* The help text about what can be uploaded under a filter: "Allowed types: .jpg, .png ...", and for fonts how a font
|
|
16
|
+
* file must be named. Pass the `t` of the File Browser to have it in the page's language (English when left out).
|
|
17
|
+
*/
|
|
18
|
+
export declare function formatAllowedTypesForDisplay(filter: FileFilterType, translate?: Translate): string;
|
|
10
19
|
export declare const MIME_TYPES: Record<string, string>;
|
|
11
20
|
export declare function getMimeTypeExtension(mimeType: string): string;
|
|
12
21
|
/**
|
package/dist/utils/fileTypes.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { translateEnglish } from '../i18n/context';
|
|
1
2
|
// Define which document types can be displayed as text
|
|
2
3
|
export const PREVIEWABLE_TEXT_EXTENSIONS = ['.txt', '.md', '.csv', '.json', '.xml', '.log'];
|
|
3
4
|
export const FILE_TYPES = {
|
|
@@ -29,31 +30,42 @@ export function isPreviewableTextFile(filename) {
|
|
|
29
30
|
const extension = '.' + filename.split('.').pop()?.toLowerCase();
|
|
30
31
|
return PREVIEWABLE_TEXT_EXTENSIONS.includes(extension);
|
|
31
32
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
33
|
+
/**
|
|
34
|
+
* One sentence that lists every kind of file with its extensions ("Add images (.jpg, .png), audio (.mp3) ..."). Pass the
|
|
35
|
+
* `t` of the File Browser to have it in the page's language (English when left out).
|
|
36
|
+
*/
|
|
37
|
+
export function formatFileTypesForDisplay(translate = translateEnglish) {
|
|
38
|
+
const separator = translate('list.separator');
|
|
39
|
+
return translate('fileTypes.addAll', {
|
|
40
|
+
images: FILE_TYPES.image.join(separator),
|
|
41
|
+
audio: FILE_TYPES.audio.join(separator),
|
|
42
|
+
video: FILE_TYPES.video.join(separator),
|
|
43
|
+
documents: FILE_TYPES.document.join(separator),
|
|
44
|
+
fonts: FILE_TYPES.font.join(separator),
|
|
45
|
+
svg: FILE_TYPES.svg.join(separator)
|
|
46
|
+
});
|
|
40
47
|
}
|
|
41
|
-
|
|
48
|
+
/**
|
|
49
|
+
* The help text about what can be uploaded under a filter: "Allowed types: .jpg, .png ...", and for fonts how a font
|
|
50
|
+
* file must be named. Pass the `t` of the File Browser to have it in the page's language (English when left out).
|
|
51
|
+
*/
|
|
52
|
+
export function formatAllowedTypesForDisplay(filter, translate = translateEnglish) {
|
|
53
|
+
const separator = translate('list.separator');
|
|
42
54
|
if (filter === 'all') {
|
|
43
|
-
return
|
|
55
|
+
return translate('fileTypes.allowed', { types: Object.values(FILE_TYPES).flat().join(separator) });
|
|
44
56
|
}
|
|
45
57
|
let allowedTypes = '';
|
|
46
58
|
if (filter === 'svg') {
|
|
47
|
-
allowedTypes = '
|
|
59
|
+
allowedTypes = translate('fileTypes.allowedSvg');
|
|
48
60
|
}
|
|
49
61
|
else if (filter === 'document') {
|
|
50
|
-
allowedTypes =
|
|
62
|
+
allowedTypes = translate('fileTypes.allowedDocument', { types: FILE_TYPES[filter].join(separator) });
|
|
51
63
|
}
|
|
52
64
|
else {
|
|
53
|
-
allowedTypes =
|
|
65
|
+
allowedTypes = translate('fileTypes.allowed', { types: FILE_TYPES[filter].join(separator) });
|
|
54
66
|
}
|
|
55
67
|
if (filter === 'font') {
|
|
56
|
-
allowedTypes +=
|
|
68
|
+
allowedTypes += `\n\n${translate('fileTypes.fontNaming')}`;
|
|
57
69
|
}
|
|
58
70
|
return allowedTypes;
|
|
59
71
|
}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { type FileFilterType } from './fileTypes';
|
|
2
|
-
|
|
2
|
+
import { type Translate } from '../i18n/context';
|
|
3
|
+
/**
|
|
4
|
+
* A size in bytes as the biggest unit that keeps it above 1: "0 Bytes", "1.5 MB". The units and the number format
|
|
5
|
+
* follow the language: pass the `t` and the `locale` of the File Browser (English when left out).
|
|
6
|
+
*/
|
|
7
|
+
export declare function formatFileSize(bytes: number, translate?: Translate, locale?: string): string;
|
|
8
|
+
/** A size in bytes as kilobytes with one decimal ("12.3 KB"), the way the upload list shows it. */
|
|
9
|
+
export declare function formatKilobytes(bytes: number, translate?: Translate, locale?: string): string;
|
|
3
10
|
export declare function getFileIcon(fileName: string): string;
|
|
4
11
|
export declare function getFileExtension(fileNameOrUrl: string): string;
|
|
5
12
|
export declare function getFileType(fileNameOrUrl: string): FileFilterType;
|
package/dist/utils/fileUtils.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { FILE_TYPES } from './fileTypes';
|
|
2
|
+
import { translateEnglish } from '../i18n/context';
|
|
2
3
|
import icAudio from '../static/icons/audio.svg?url';
|
|
3
4
|
import icChecked from '../static/icons/checked.svg?url';
|
|
4
5
|
import icDocument from '../static/icons/document.svg?url';
|
|
@@ -30,13 +31,26 @@ const bundledIconUrls = {
|
|
|
30
31
|
'/icons/player-play.svg': icPlayerPlay,
|
|
31
32
|
'/icons/unorganized-folder.svg': icUnorganizedFolder,
|
|
32
33
|
};
|
|
33
|
-
|
|
34
|
+
/** The message for each unit of size, from bytes to terabytes. */
|
|
35
|
+
const SIZE_MESSAGES = ['size.bytes', 'size.kb', 'size.mb', 'size.gb', 'size.tb'];
|
|
36
|
+
/** A number of a size, written the way `locale` writes numbers, with up to `fractionDigits` decimals and no thousands separator ("1.5", "1,5"). */
|
|
37
|
+
function formatSizeNumber(value, locale, minimumFractionDigits, maximumFractionDigits) {
|
|
38
|
+
return new Intl.NumberFormat(locale, { minimumFractionDigits, maximumFractionDigits, useGrouping: false }).format(value);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A size in bytes as the biggest unit that keeps it above 1: "0 Bytes", "1.5 MB". The units and the number format
|
|
42
|
+
* follow the language: pass the `t` and the `locale` of the File Browser (English when left out).
|
|
43
|
+
*/
|
|
44
|
+
export function formatFileSize(bytes, translate = translateEnglish, locale = 'en') {
|
|
34
45
|
if (bytes === 0)
|
|
35
|
-
return '0
|
|
46
|
+
return translate('size.bytes', { size: formatSizeNumber(0, locale, 0, 2) });
|
|
36
47
|
const k = 1024;
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
48
|
+
const unitIndex = Math.min(SIZE_MESSAGES.length - 1, Math.max(0, Math.floor(Math.log(bytes) / Math.log(k))));
|
|
49
|
+
return translate(SIZE_MESSAGES[unitIndex], { size: formatSizeNumber(bytes / Math.pow(k, unitIndex), locale, 0, 2) });
|
|
50
|
+
}
|
|
51
|
+
/** A size in bytes as kilobytes with one decimal ("12.3 KB"), the way the upload list shows it. */
|
|
52
|
+
export function formatKilobytes(bytes, translate = translateEnglish, locale = 'en') {
|
|
53
|
+
return translate('size.kb', { size: formatSizeNumber(bytes / 1024, locale, 1, 1) });
|
|
40
54
|
}
|
|
41
55
|
export function getFileIcon(fileName) {
|
|
42
56
|
const fileType = getFileType(fileName);
|
|
@@ -117,8 +131,9 @@ export async function checkFileExists(url) {
|
|
|
117
131
|
*/
|
|
118
132
|
export function getAssetUrl(path) {
|
|
119
133
|
// if(showLogs) console.log('getAssetUrl: path:', path);
|
|
120
|
-
// If the URL is already absolute, return it as is
|
|
121
|
-
|
|
134
|
+
// If the URL is already absolute, return it as is. A bundled icon can already be an inlined `data:` URL
|
|
135
|
+
// (the bundler inlines small files), and `getAssetUrl(getFileIcon(name))` passes it in a second time.
|
|
136
|
+
if (absoluteUrlPattern.test(path) || /^(?:data|blob):/i.test(path))
|
|
122
137
|
return path;
|
|
123
138
|
// Ensure path starts with a slash
|
|
124
139
|
let normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getAssetUrl } from './fileUtils';
|
|
2
|
+
import { getFileTypeOf } from './fileKinds';
|
|
2
3
|
const UNORGANIZED_THRESHOLD = 50;
|
|
3
4
|
export function countFilteredItems(folder, filter) {
|
|
4
5
|
let count = 0;
|
|
@@ -7,7 +8,7 @@ export function countFilteredItems(folder, filter) {
|
|
|
7
8
|
if (item.type === 'folder') {
|
|
8
9
|
count += countFilteredItems(item, filter);
|
|
9
10
|
}
|
|
10
|
-
else if (filter === 'all' ||
|
|
11
|
+
else if (filter === 'all' || getFileTypeOf(item) === filter) {
|
|
11
12
|
count++;
|
|
12
13
|
}
|
|
13
14
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { TextDirection } from '@widgetic/design-system/components/textDirection';
|
|
2
|
+
/** What a key press does in the file preview: go to the file before this one, or to the file after it. */
|
|
3
|
+
export type PreviewKeyAction = 'previous' | 'next';
|
|
4
|
+
/**
|
|
5
|
+
* What an arrow key does in the file preview, or `null` for any other key.
|
|
6
|
+
*
|
|
7
|
+
* The arrow keys follow the reading direction: the key that points toward the start of the line goes to the previous
|
|
8
|
+
* file and the key that points toward the end of the line goes to the next one. In a left to right screen that is the
|
|
9
|
+
* left arrow and the right arrow; in a right to left screen the two swap, so the arrow points the way the files are
|
|
10
|
+
* laid out on the screen.
|
|
11
|
+
*/
|
|
12
|
+
export declare function previewKeyAction(key: string, direction: TextDirection): PreviewKeyAction | null;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an arrow key does in the file preview, or `null` for any other key.
|
|
3
|
+
*
|
|
4
|
+
* The arrow keys follow the reading direction: the key that points toward the start of the line goes to the previous
|
|
5
|
+
* file and the key that points toward the end of the line goes to the next one. In a left to right screen that is the
|
|
6
|
+
* left arrow and the right arrow; in a right to left screen the two swap, so the arrow points the way the files are
|
|
7
|
+
* laid out on the screen.
|
|
8
|
+
*/
|
|
9
|
+
export function previewKeyAction(key, direction) {
|
|
10
|
+
if (key !== 'ArrowLeft' && key !== 'ArrowRight')
|
|
11
|
+
return null;
|
|
12
|
+
const keyPointsToStart = (key === 'ArrowLeft') === (direction !== 'rtl');
|
|
13
|
+
return keyPointsToStart ? 'previous' : 'next';
|
|
14
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the places where a file's name or address, which someone else wrote, ends up inside HTML or CSS.
|
|
3
|
+
*
|
|
4
|
+
* A name like `x"; } body { display: none }` is a fine file name for a library to hold. These helpers make sure it
|
|
5
|
+
* can only ever be shown, never run as markup or style.
|
|
6
|
+
*/
|
|
7
|
+
/** Makes text safe to put inside HTML: `& < > " '` become entities. */
|
|
8
|
+
export declare function escapeHtml(text: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Gives `name` as HTML with every (case-insensitive) occurrence of `term` wrapped in `<span class="highlightClass">`.
|
|
11
|
+
*
|
|
12
|
+
* The name is cut into plain and matching parts first and each part is escaped on its own, so a match can never cut
|
|
13
|
+
* an entity such as `&` in two, and nothing in the name or the term can become markup.
|
|
14
|
+
*/
|
|
15
|
+
export declare function highlightMatchesAsHtml(name: string, term: string, highlightClass: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* The name a font file is registered and styled under: its file name without the extension, reduced to letters,
|
|
18
|
+
* digits, spaces, underscores and hyphens.
|
|
19
|
+
*
|
|
20
|
+
* It goes inside CSS (`font-family: '...'`, `@font-face { font-family: "..." }`). A quote or a brace in the name would
|
|
21
|
+
* end the string and let whoever named the file write their own CSS. Use this one function both where the font is
|
|
22
|
+
* registered and where it is used, so the two always agree.
|
|
23
|
+
*/
|
|
24
|
+
export declare function toSafeFontFamilyName(fileName: unknown): string;
|
|
25
|
+
/**
|
|
26
|
+
* An address as a quoted CSS `url("...")`, with the characters that could end the string or the line written as
|
|
27
|
+
* `%XX` so the address stays inside it.
|
|
28
|
+
*/
|
|
29
|
+
export declare function toCssUrlLiteral(address: string): string;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the places where a file's name or address, which someone else wrote, ends up inside HTML or CSS.
|
|
3
|
+
*
|
|
4
|
+
* A name like `x"; } body { display: none }` is a fine file name for a library to hold. These helpers make sure it
|
|
5
|
+
* can only ever be shown, never run as markup or style.
|
|
6
|
+
*/
|
|
7
|
+
const HTML_ENTITIES = {
|
|
8
|
+
'&': '&',
|
|
9
|
+
'<': '<',
|
|
10
|
+
'>': '>',
|
|
11
|
+
'"': '"',
|
|
12
|
+
"'": '''
|
|
13
|
+
};
|
|
14
|
+
/** Makes text safe to put inside HTML: `& < > " '` become entities. */
|
|
15
|
+
export function escapeHtml(text) {
|
|
16
|
+
return text.replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
|
|
17
|
+
}
|
|
18
|
+
function escapeRegExp(text) {
|
|
19
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Gives `name` as HTML with every (case-insensitive) occurrence of `term` wrapped in `<span class="highlightClass">`.
|
|
23
|
+
*
|
|
24
|
+
* The name is cut into plain and matching parts first and each part is escaped on its own, so a match can never cut
|
|
25
|
+
* an entity such as `&` in two, and nothing in the name or the term can become markup.
|
|
26
|
+
*/
|
|
27
|
+
export function highlightMatchesAsHtml(name, term, highlightClass) {
|
|
28
|
+
if (!name)
|
|
29
|
+
return '';
|
|
30
|
+
if (!term)
|
|
31
|
+
return escapeHtml(name);
|
|
32
|
+
// One capturing group, so `split` keeps the matches at the odd positions.
|
|
33
|
+
const parts = name.split(new RegExp(`(${escapeRegExp(term)})`, 'gi'));
|
|
34
|
+
return parts
|
|
35
|
+
.map((part, index) => index % 2 === 1
|
|
36
|
+
? `<span class="${escapeHtml(highlightClass)}">${escapeHtml(part)}</span>`
|
|
37
|
+
: escapeHtml(part))
|
|
38
|
+
.join('');
|
|
39
|
+
}
|
|
40
|
+
const MAX_FONT_FAMILY_LENGTH = 64;
|
|
41
|
+
const FALLBACK_FONT_FAMILY = 'Uploaded font';
|
|
42
|
+
/**
|
|
43
|
+
* The name a font file is registered and styled under: its file name without the extension, reduced to letters,
|
|
44
|
+
* digits, spaces, underscores and hyphens.
|
|
45
|
+
*
|
|
46
|
+
* It goes inside CSS (`font-family: '...'`, `@font-face { font-family: "..." }`). A quote or a brace in the name would
|
|
47
|
+
* end the string and let whoever named the file write their own CSS. Use this one function both where the font is
|
|
48
|
+
* registered and where it is used, so the two always agree.
|
|
49
|
+
*/
|
|
50
|
+
export function toSafeFontFamilyName(fileName) {
|
|
51
|
+
const withoutExtension = typeof fileName === 'string' ? fileName.replace(/\.[^/.]+$/, '') : '';
|
|
52
|
+
const safeName = withoutExtension
|
|
53
|
+
.replace(/[^\p{L}\p{N} _-]/gu, '')
|
|
54
|
+
.trim()
|
|
55
|
+
.slice(0, MAX_FONT_FAMILY_LENGTH)
|
|
56
|
+
.trim();
|
|
57
|
+
return safeName === '' ? FALLBACK_FONT_FAMILY : safeName;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* An address as a quoted CSS `url("...")`, with the characters that could end the string or the line written as
|
|
61
|
+
* `%XX` so the address stays inside it.
|
|
62
|
+
*/
|
|
63
|
+
export function toCssUrlLiteral(address) {
|
|
64
|
+
const escaped = address.replace(/["\\\n\r\f]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
|
|
65
|
+
return `url("${escaped}")`;
|
|
66
|
+
}
|
|
@@ -28,5 +28,8 @@ export declare function saveLibraryTreeChildren(children: FileSystemItem[]): voi
|
|
|
28
28
|
export declare function mergeMyUploadsChildren(savedChildren: FileSystemItem[] | null, uploadFiles: FileSystemItem[]): FileSystemItem[];
|
|
29
29
|
/**
|
|
30
30
|
* Empty library root — only user uploads (CDN URLs), no broken demo assets.
|
|
31
|
+
*
|
|
32
|
+
* `myUploadsName` is what the visitor reads as the name of the one folder in it: the File Browser passes the word in
|
|
33
|
+
* the visitor's language ("My uploads" in English).
|
|
31
34
|
*/
|
|
32
|
-
export declare function createUserUploadsFileSystemRoot(files: FileSystemItem[]): Promise<FileSystemRoot>;
|
|
35
|
+
export declare function createUserUploadsFileSystemRoot(files: FileSystemItem[], myUploadsName?: string): Promise<FileSystemRoot>;
|
|
@@ -155,8 +155,11 @@ export function mergeMyUploadsChildren(savedChildren, uploadFiles) {
|
|
|
155
155
|
}
|
|
156
156
|
/**
|
|
157
157
|
* Empty library root — only user uploads (CDN URLs), no broken demo assets.
|
|
158
|
+
*
|
|
159
|
+
* `myUploadsName` is what the visitor reads as the name of the one folder in it: the File Browser passes the word in
|
|
160
|
+
* the visitor's language ("My uploads" in English).
|
|
158
161
|
*/
|
|
159
|
-
export async function createUserUploadsFileSystemRoot(files) {
|
|
162
|
+
export async function createUserUploadsFileSystemRoot(files, myUploadsName = 'My uploads') {
|
|
160
163
|
const savedChildren = await loadLibraryTreeChildren();
|
|
161
164
|
const children = mergeMyUploadsChildren(savedChildren, files);
|
|
162
165
|
return {
|
|
@@ -168,7 +171,7 @@ export async function createUserUploadsFileSystemRoot(files) {
|
|
|
168
171
|
children: [
|
|
169
172
|
{
|
|
170
173
|
id: 'folder_my_uploads',
|
|
171
|
-
name:
|
|
174
|
+
name: myUploadsName,
|
|
172
175
|
type: 'folder',
|
|
173
176
|
children,
|
|
174
177
|
},
|
|
@@ -11,6 +11,16 @@ export type TusUploadOptions = {
|
|
|
11
11
|
onProgress?: (progress: TusUploadProgress) => void;
|
|
12
12
|
abortSignal?: AbortSignal;
|
|
13
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* POST …/complete. A 409 `TUS_UPLOAD_BUSY` means another request still has the upload (the chunk that
|
|
16
|
+
* just finished, or a retried one), so ask again after a short pause. Every other answer is final: a
|
|
17
|
+
* 409 `TUS_UPLOAD_INCOMPLETE` means chunks are missing, and asking again cannot bring them.
|
|
18
|
+
* Returns the last answer; the caller tells success from failure.
|
|
19
|
+
*/
|
|
20
|
+
export declare function requestTusComplete(url: string, init: RequestInit, options?: {
|
|
21
|
+
retryDelaysMs?: readonly number[];
|
|
22
|
+
abortSignal?: AbortSignal;
|
|
23
|
+
}): Promise<Response>;
|
|
14
24
|
/**
|
|
15
25
|
* Resumable upload via TUS (POST/PATCH /v1/uploads/tus + POST .../complete).
|
|
16
26
|
*/
|
|
@@ -2,12 +2,62 @@ import * as tus from 'tus-js-client';
|
|
|
2
2
|
/** Matches api-gateway MULTIPART_MAX_UPLOAD_BYTES — use TUS above this. */
|
|
3
3
|
export const WIDGETIC_MULTIPART_MAX_BYTES = 10 * 1024 * 1024;
|
|
4
4
|
const DEFAULT_TUS_CHUNK_SIZE = 5 * 1024 * 1024;
|
|
5
|
+
/** The `error.code` api-gateway answers `POST …/complete` with (HTTP 409) while another request still has the upload. */
|
|
6
|
+
const TUS_UPLOAD_BUSY_CODE = 'TUS_UPLOAD_BUSY';
|
|
7
|
+
/** Pauses before asking again after a "busy" answer: 0.5, 1, 2, 4 and 8 seconds, about 15 seconds in all. */
|
|
8
|
+
const COMPLETE_BUSY_RETRY_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
|
|
5
9
|
function parseErrorMessage(response, fallback) {
|
|
6
10
|
return response
|
|
7
11
|
.json()
|
|
8
12
|
.then((json) => json?.message || json?.error?.message || fallback)
|
|
9
13
|
.catch(() => fallback);
|
|
10
14
|
}
|
|
15
|
+
/** The `error.code` of a failed answer, or undefined when the body is not the API's error envelope. */
|
|
16
|
+
function readErrorCode(response) {
|
|
17
|
+
return response
|
|
18
|
+
.json()
|
|
19
|
+
.then((json) => (typeof json?.error?.code === 'string' ? json.error.code : undefined))
|
|
20
|
+
.catch(() => undefined);
|
|
21
|
+
}
|
|
22
|
+
/** Resolves after `delayMs`, or at once when the upload is cancelled meanwhile. */
|
|
23
|
+
function waitBeforeRetry(delayMs, abortSignal) {
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
if (abortSignal?.aborted) {
|
|
26
|
+
resolve();
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const finish = () => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
abortSignal?.removeEventListener('abort', finish);
|
|
32
|
+
resolve();
|
|
33
|
+
};
|
|
34
|
+
const timer = setTimeout(finish, delayMs);
|
|
35
|
+
abortSignal?.addEventListener('abort', finish, { once: true });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* POST …/complete. A 409 `TUS_UPLOAD_BUSY` means another request still has the upload (the chunk that
|
|
40
|
+
* just finished, or a retried one), so ask again after a short pause. Every other answer is final: a
|
|
41
|
+
* 409 `TUS_UPLOAD_INCOMPLETE` means chunks are missing, and asking again cannot bring them.
|
|
42
|
+
* Returns the last answer; the caller tells success from failure.
|
|
43
|
+
*/
|
|
44
|
+
export async function requestTusComplete(url, init, options = {}) {
|
|
45
|
+
const retryDelaysMs = options.retryDelaysMs ?? COMPLETE_BUSY_RETRY_DELAYS_MS;
|
|
46
|
+
let retriesDone = 0;
|
|
47
|
+
for (;;) {
|
|
48
|
+
const response = await fetch(url, init);
|
|
49
|
+
if (response.status !== 409 || retriesDone >= retryDelaysMs.length)
|
|
50
|
+
return response;
|
|
51
|
+
// Read a copy, so the caller can still read the message of an answer that turns out to be final.
|
|
52
|
+
if ((await readErrorCode(response.clone())) !== TUS_UPLOAD_BUSY_CODE)
|
|
53
|
+
return response;
|
|
54
|
+
console.warn(`[widgeticTusUpload] Upload is busy; asking again in ${retryDelaysMs[retriesDone]} ms (retry ${retriesDone + 1} of ${retryDelaysMs.length})`);
|
|
55
|
+
await waitBeforeRetry(retryDelaysMs[retriesDone], options.abortSignal);
|
|
56
|
+
if (options.abortSignal?.aborted)
|
|
57
|
+
return response;
|
|
58
|
+
retriesDone += 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
11
61
|
function extractTusId(uploadUrl) {
|
|
12
62
|
if (!uploadUrl)
|
|
13
63
|
return null;
|
|
@@ -76,9 +126,12 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
|
|
|
76
126
|
onError: (error) => {
|
|
77
127
|
options.abortSignal?.removeEventListener('abort', abortHandler);
|
|
78
128
|
console.error('[widgeticTusUpload] TUS error:', error);
|
|
129
|
+
// A refusal from the server (for example 401 for an expired token) carries its status; a lost connection does not.
|
|
130
|
+
const refusedWithStatus = error.originalResponse?.getStatus?.();
|
|
79
131
|
resolve({
|
|
80
132
|
success: false,
|
|
81
133
|
error: error.message || 'TUS upload failed.',
|
|
134
|
+
...(typeof refusedWithStatus === 'number' && { status: refusedWithStatus }),
|
|
82
135
|
});
|
|
83
136
|
},
|
|
84
137
|
onProgress: (bytesUploaded, bytesTotal) => {
|
|
@@ -93,16 +146,21 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
|
|
|
93
146
|
return;
|
|
94
147
|
}
|
|
95
148
|
try {
|
|
96
|
-
const completeResponse = await
|
|
149
|
+
const completeResponse = await requestTusComplete(`${endpoint}/${tusId}/complete`, {
|
|
97
150
|
method: 'POST',
|
|
98
151
|
headers: {
|
|
99
152
|
Authorization: `Bearer ${token}`,
|
|
100
153
|
'Content-Type': 'application/json',
|
|
101
154
|
},
|
|
102
|
-
});
|
|
155
|
+
}, { abortSignal: options.abortSignal });
|
|
103
156
|
if (!completeResponse.ok) {
|
|
157
|
+
// Cancelled while waiting to ask again: say so, instead of repeating the server's "busy" answer.
|
|
158
|
+
if (options.abortSignal?.aborted) {
|
|
159
|
+
resolve({ success: false, error: 'Upload cancelled.' });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
104
162
|
const detail = await parseErrorMessage(completeResponse, `Complete failed (${completeResponse.status})`);
|
|
105
|
-
resolve({ success: false, error: detail });
|
|
163
|
+
resolve({ success: false, error: detail, status: completeResponse.status });
|
|
106
164
|
return;
|
|
107
165
|
}
|
|
108
166
|
const json = await completeResponse.json();
|
|
@@ -3,6 +3,8 @@ import type { FileSystemItem } from '../types';
|
|
|
3
3
|
import { type TusUploadOptions } from './widgeticTusUpload';
|
|
4
4
|
export type WidgeticUploadResult = {
|
|
5
5
|
success: boolean;
|
|
6
|
+
/** The HTTP status of the answer that made the upload fail, when the failure was an answer from the server. */
|
|
7
|
+
status?: number;
|
|
6
8
|
file?: {
|
|
7
9
|
id: string;
|
|
8
10
|
name: string;
|
|
@@ -27,4 +29,5 @@ export declare function uploadToWidgeticApi(file: File, config: FileBrowserUploa
|
|
|
27
29
|
*/
|
|
28
30
|
export declare function fetchUserUploadsFromApi(config: FileBrowserUploadConfig, options?: {
|
|
29
31
|
limit?: number;
|
|
32
|
+
signal?: AbortSignal;
|
|
30
33
|
}): Promise<FileSystemItem[]>;
|