@widgetic/file-browser 0.5.46 → 0.5.48

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 (104) hide show
  1. package/dist/actions/dragSelectedToFolder.js +104 -115
  2. package/dist/components/FolderTree.svelte.d.ts +2 -6
  3. package/dist/components/core/Dropzone.svelte +42 -2
  4. package/dist/components/core/FileBrowser.svelte +249 -32
  5. package/dist/components/core/FileUploader.svelte +134 -54
  6. package/dist/components/core/RecentFiles.svelte +74 -19
  7. package/dist/components/core/RecentFiles.svelte.d.ts +1 -0
  8. package/dist/components/core/SearchDropdown.svelte +6 -8
  9. package/dist/components/core/UploadPanel.svelte +7 -0
  10. package/dist/components/core/UploadPanel.svelte.d.ts +4 -0
  11. package/dist/components/core/UploadRow.svelte +9 -4
  12. package/dist/components/core/UploadRow.svelte.d.ts +2 -0
  13. package/dist/components/core/dropzoneClick.d.ts +28 -0
  14. package/dist/components/core/dropzoneClick.js +32 -0
  15. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  16. package/dist/components/ui/DropdownMenu.svelte +1 -1
  17. package/dist/config.js +4 -3
  18. package/dist/i18n/context.js +2 -2
  19. package/dist/i18n/errors.js +2 -1
  20. package/dist/i18n/messages.d.ts +15 -1
  21. package/dist/i18n/messages.js +17 -3
  22. package/dist/i18n/text.js +2 -2
  23. package/dist/mediaLibrary/capabilities.js +4 -3
  24. package/dist/mediaLibrary/context.js +4 -3
  25. package/dist/mediaLibrary/errors.js +46 -35
  26. package/dist/mediaLibrary/normalize.js +45 -42
  27. package/dist/mediaLibrary/paging.js +100 -45
  28. package/dist/mediaLibrary/resolve.js +214 -95
  29. package/dist/mediaLibrary/treeOps.js +40 -20
  30. package/dist/mediaLibrary/urls.js +12 -10
  31. package/dist/mediaLibrary/widgetic.js +140 -54
  32. package/dist/stores/dragStore.js +1 -1
  33. package/dist/stores/fileStore.d.ts +1 -1
  34. package/dist/stores/fileStore.js +44 -37
  35. package/dist/stores/folderCountStore.js +12 -11
  36. package/dist/stores/missingFilesStore.js +3 -3
  37. package/dist/stores/navigationStore.d.ts +1 -1
  38. package/dist/stores/navigationStore.js +217 -178
  39. package/dist/stores/persistentSelectStore.d.ts +1 -1
  40. package/dist/stores/persistentSelectStore.js +117 -94
  41. package/dist/stores/searchStore.js +1 -1
  42. package/dist/stores/uploadApiStore.d.ts +10 -0
  43. package/dist/stores/uploadApiStore.js +7 -7
  44. package/dist/stores/viewportStore.js +4 -4
  45. package/dist/types/index.js +0 -1
  46. package/dist/utils/apiConfig.js +9 -9
  47. package/dist/utils/brandKitLibraryTree.js +57 -42
  48. package/dist/utils/dateUtils.js +11 -9
  49. package/dist/utils/deleteSelectionAction.d.ts +26 -0
  50. package/dist/utils/deleteSelectionAction.js +23 -0
  51. package/dist/utils/dragToFolder/batchMoveResult.js +114 -54
  52. package/dist/utils/dragToFolder/folderDropTarget.js +23 -17
  53. package/dist/utils/dragToFolder/springStep.js +4 -3
  54. package/dist/utils/fileGoneProbe.js +65 -16
  55. package/dist/utils/fileKinds.js +14 -13
  56. package/dist/utils/fileNames.js +7 -7
  57. package/dist/utils/fileOperations.js +440 -333
  58. package/dist/utils/fileTypes.js +19 -14
  59. package/dist/utils/fileUtils.js +85 -31
  60. package/dist/utils/folderUtils.js +5 -4
  61. package/dist/utils/gridLayout.js +7 -7
  62. package/dist/utils/imagePreviewCache.js +26 -15
  63. package/dist/utils/imagePreviewFrame.js +13 -13
  64. package/dist/utils/imagePreviewVisualState.js +5 -4
  65. package/dist/utils/imageTransform.js +27 -14
  66. package/dist/utils/itemMenuCapabilities.js +7 -7
  67. package/dist/utils/libraryTree.js +55 -39
  68. package/dist/utils/pendingUploadDeletes.d.ts +102 -0
  69. package/dist/utils/pendingUploadDeletes.js +400 -0
  70. package/dist/utils/previewKeys.js +1 -1
  71. package/dist/utils/previewListNavigation.js +13 -11
  72. package/dist/utils/previewNavigation.js +10 -7
  73. package/dist/utils/recentFiles.js +16 -6
  74. package/dist/utils/recentFilesLimit.js +2 -2
  75. package/dist/utils/removeItems.d.ts +30 -0
  76. package/dist/utils/removeItems.js +124 -0
  77. package/dist/utils/resolveFileUrl.js +6 -6
  78. package/dist/utils/safeText.js +14 -12
  79. package/dist/utils/searchDropdownPhase.d.ts +14 -3
  80. package/dist/utils/searchDropdownPhase.js +13 -9
  81. package/dist/utils/searchItems.js +30 -14
  82. package/dist/utils/searchNavigation.js +5 -5
  83. package/dist/utils/uploadAuth.d.ts +24 -0
  84. package/dist/utils/uploadAuth.js +140 -0
  85. package/dist/utils/uploadDisplayProgress.js +1 -1
  86. package/dist/utils/uploadLimits.d.ts +76 -0
  87. package/dist/utils/uploadLimits.js +242 -0
  88. package/dist/utils/uploadListReconcile.js +24 -11
  89. package/dist/utils/uploadPanelDismiss.d.ts +13 -0
  90. package/dist/utils/uploadPanelDismiss.js +11 -0
  91. package/dist/utils/uploadPanelProgress.js +4 -4
  92. package/dist/utils/uploadProgressMath.js +13 -11
  93. package/dist/utils/uploadRefusals.d.ts +42 -0
  94. package/dist/utils/uploadRefusals.js +86 -0
  95. package/dist/utils/uploadResponseMapping.js +9 -8
  96. package/dist/utils/uploadUiHelpers.js +17 -17
  97. package/dist/utils/userUploadsStorage.js +270 -133
  98. package/dist/utils/videoFrame.d.ts +23 -0
  99. package/dist/utils/videoFrame.js +26 -0
  100. package/dist/utils/widgeticDelete.js +103 -28
  101. package/dist/utils/widgeticTusUpload.js +189 -105
  102. package/dist/utils/widgeticUpload.js +133 -59
  103. package/dist/utils/xhrMultipartUpload.js +164 -116
  104. package/package.json +3 -3
@@ -0,0 +1,76 @@
1
+ import type { FileBrowserUploadConfig } from '../stores/uploadApiStore';
2
+ /**
3
+ * What the Widgetic API takes as an upload, read from `GET /v1/uploads/limits`, and the check of a file against it.
4
+ *
5
+ * The File Browser lists more kinds of file than the API takes (fonts, audio, Word documents ...), so a file could be
6
+ * dropped, queued, sent, and only then be refused with "415 Unsupported file type: font/otf". Knowing the API's list
7
+ * before the first file is sent lets the File Browser say so up front, name the reason, and leave the file out of the
8
+ * list of uploads instead of showing it as a failure that "Retry" can never fix.
9
+ */
10
+ export type UploadLimits = {
11
+ /** The most bytes of a file sent in one request; `null` when the API did not say. */
12
+ multipartMaxBytes: number | null;
13
+ /** The most bytes of a resumable (TUS) upload; `null` when the API did not say. */
14
+ tusMaxBytes: number | null;
15
+ tusEnabled: boolean;
16
+ /** The MIME types a file sent in one request may have. */
17
+ multipartMimeTypes: ReadonlySet<string>;
18
+ /** The MIME types a resumable upload (a file over `WIDGETIC_MULTIPART_MAX_BYTES`) may have. */
19
+ tusMimeTypes: ReadonlySet<string>;
20
+ };
21
+ /** Why a file is not taken: its type is not one the API accepts, or it is over the biggest size the API takes. */
22
+ export type UploadRefusal = {
23
+ reason: 'unsupportedType';
24
+ mimeType: string;
25
+ } | {
26
+ reason: 'tooLarge';
27
+ maxBytes: number;
28
+ };
29
+ /**
30
+ * Reads the answer of `GET /v1/uploads/limits` (the payload is the `data` of the API's envelope; a bare payload is read
31
+ * too). `null` when it does not list the accepted types, so a changed answer never blocks an upload on a guess.
32
+ */
33
+ export declare function parseUploadLimits(json: unknown): UploadLimits | null;
34
+ /**
35
+ * The reason the API would refuse a file, or `null` when it takes it (or when the limits are not known: the API then
36
+ * decides, as it always has). The type is judged first with the list that fits the way the file is sent, because a file
37
+ * of a kind the API never takes is refused for that whatever its size.
38
+ */
39
+ export declare function refusalForFile(file: Pick<File, 'type' | 'size'>, limits: UploadLimits | null, isResumable?: boolean): UploadRefusal | null;
40
+ /** The extension of a file name with its dot and in lower case (".otf"); an empty string when the name has none. */
41
+ export declare function extensionOfFileName(fileName: string): string;
42
+ /**
43
+ * The extensions the API takes: the ones that go with every MIME type it lists, in the order the File Browser lists its
44
+ * own kinds. `null` when the limits are not known.
45
+ */
46
+ export declare function extensionsTakenBy(limits: UploadLimits | null): ReadonlySet<string> | null;
47
+ /** The extensions of a list that the API takes. The whole list when the limits are not known. */
48
+ export declare function extensionsTakenFrom(extensions: readonly string[], limits: UploadLimits | null): string[];
49
+ /**
50
+ * True when the API takes a file of this MIME type, as far as the limits say. An empty type is "not known" (a browser
51
+ * reports none for some files while they are only dragged), so it is not refused here.
52
+ */
53
+ export declare function limitsTakeMimeType(mimeType: string, limits: UploadLimits | null): boolean;
54
+ /**
55
+ * What asking the API for its limits came to: the limits (`null` when the API could not be asked or did not list its
56
+ * accepted types, so whoever asks goes on without them and the API judges each file), and whether the API refused the
57
+ * session itself (a 401 that a fresh token did not fix), so the uploader can tell the visitor to sign in again instead of
58
+ * queueing files that cannot be sent.
59
+ */
60
+ export type UploadLimitsAnswer = {
61
+ limits: UploadLimits | null;
62
+ sessionRefused: boolean;
63
+ };
64
+ /** Forgets what was read (a test, or a page that changed its API address). */
65
+ export declare function resetUploadLimitsCache(): void;
66
+ /**
67
+ * The limits of the API behind `config`: from memory when they were read in the last minute, else asked for
68
+ * (`GET {apiBasePath}/uploads/limits`, with the token the page gives and a fresh one when the API refuses it). The same
69
+ * request is the check of the session that comes before the first file of a batch. One request is shared by every caller
70
+ * that asks while it is under way.
71
+ */
72
+ export declare function loadUploadLimits(config: FileBrowserUploadConfig, options?: {
73
+ signal?: AbortSignal;
74
+ forceReload?: boolean;
75
+ now?: () => number;
76
+ }): Promise<UploadLimitsAnswer>;
@@ -0,0 +1,242 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __generator = (this && this.__generator) || function (thisArg, body) {
11
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
12
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
+ function verb(n) { return function (v) { return step([n, v]); }; }
14
+ function step(op) {
15
+ if (f) throw new TypeError("Generator is already executing.");
16
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
+ if (y = 0, t) op = [op[0] & 2, t.value];
19
+ switch (op[0]) {
20
+ case 0: case 1: t = op; break;
21
+ case 4: _.label++; return { value: op[1], done: false };
22
+ case 5: _.label++; y = op[1]; op = [0]; continue;
23
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
+ default:
25
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
+ if (t[2]) _.ops.pop();
30
+ _.trys.pop(); continue;
31
+ }
32
+ op = body.call(thisArg, _);
33
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
+ }
36
+ };
37
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
38
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
39
+ if (ar || !(i in from)) {
40
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
41
+ ar[i] = from[i];
42
+ }
43
+ }
44
+ return to.concat(ar || Array.prototype.slice.call(from));
45
+ };
46
+ import { withTokenRetriedOnce } from './uploadAuth';
47
+ import { WIDGETIC_MULTIPART_MAX_BYTES } from './widgeticTusUpload';
48
+ /**
49
+ * How long the answer of the API is kept before it is asked again. The limits are configuration that rarely changes; the
50
+ * minute is short so that the request that doubles as the session check still runs before each batch of files.
51
+ */
52
+ var LIMITS_CACHE_MILLISECONDS = 60 * 1000;
53
+ /** The extensions that go with each MIME type the API can list (what the file chooser and the allowed types name). */
54
+ var EXTENSIONS_BY_MIME_TYPE = {
55
+ 'image/png': ['.png'],
56
+ 'image/jpeg': ['.jpg', '.jpeg'],
57
+ 'image/webp': ['.webp'],
58
+ 'image/gif': ['.gif'],
59
+ 'image/svg+xml': ['.svg'],
60
+ 'image/heic': ['.heic'],
61
+ 'image/heif': ['.heif'],
62
+ 'video/mp4': ['.mp4'],
63
+ 'video/webm': ['.webm'],
64
+ 'video/quicktime': ['.mov'],
65
+ 'application/pdf': ['.pdf'],
66
+ 'text/csv': ['.csv'],
67
+ 'application/json': ['.json'],
68
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
69
+ };
70
+ function stringList(value) {
71
+ if (!Array.isArray(value))
72
+ return null;
73
+ return value.filter(function (entry) { return typeof entry === 'string'; }).map(function (entry) { return entry.trim().toLowerCase(); });
74
+ }
75
+ function positiveNumber(value) {
76
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
77
+ }
78
+ /**
79
+ * Reads the answer of `GET /v1/uploads/limits` (the payload is the `data` of the API's envelope; a bare payload is read
80
+ * too). `null` when it does not list the accepted types, so a changed answer never blocks an upload on a guess.
81
+ */
82
+ export function parseUploadLimits(json) {
83
+ if (json === null || typeof json !== 'object')
84
+ return null;
85
+ var body = json;
86
+ var payload = body.data !== null && typeof body.data === 'object' ? body.data : body;
87
+ var multipartMimeTypes = stringList(payload.multipart_mime_types);
88
+ if (multipartMimeTypes === null || multipartMimeTypes.length === 0)
89
+ return null;
90
+ var tusMimeTypes = stringList(payload.tus_mime_types);
91
+ return {
92
+ multipartMaxBytes: positiveNumber(payload.multipart_max_bytes),
93
+ tusMaxBytes: positiveNumber(payload.tus_max_bytes),
94
+ tusEnabled: payload.tus_enabled !== false,
95
+ multipartMimeTypes: new Set(multipartMimeTypes),
96
+ tusMimeTypes: new Set(tusMimeTypes !== null && tusMimeTypes.length > 0 ? tusMimeTypes : multipartMimeTypes),
97
+ };
98
+ }
99
+ /**
100
+ * The reason the API would refuse a file, or `null` when it takes it (or when the limits are not known: the API then
101
+ * decides, as it always has). The type is judged first with the list that fits the way the file is sent, because a file
102
+ * of a kind the API never takes is refused for that whatever its size.
103
+ */
104
+ export function refusalForFile(file, limits, isResumable) {
105
+ var _a;
106
+ if (isResumable === void 0) { isResumable = file.size > WIDGETIC_MULTIPART_MAX_BYTES; }
107
+ if (limits === null)
108
+ return null;
109
+ var mimeType = file.type.trim().toLowerCase();
110
+ var takenTypes = isResumable && limits.tusEnabled ? limits.tusMimeTypes : limits.multipartMimeTypes;
111
+ if (mimeType === '' || !takenTypes.has(mimeType))
112
+ return { reason: 'unsupportedType', mimeType: mimeType };
113
+ var largestSize = limits.tusEnabled ? ((_a = limits.tusMaxBytes) !== null && _a !== void 0 ? _a : limits.multipartMaxBytes) : limits.multipartMaxBytes;
114
+ if (largestSize !== null && file.size > largestSize)
115
+ return { reason: 'tooLarge', maxBytes: largestSize };
116
+ return null;
117
+ }
118
+ /** The extension of a file name with its dot and in lower case (".otf"); an empty string when the name has none. */
119
+ export function extensionOfFileName(fileName) {
120
+ var dotIndex = fileName.lastIndexOf('.');
121
+ if (dotIndex <= 0 || dotIndex === fileName.length - 1)
122
+ return '';
123
+ return fileName.slice(dotIndex).toLowerCase();
124
+ }
125
+ /**
126
+ * The extensions the API takes: the ones that go with every MIME type it lists, in the order the File Browser lists its
127
+ * own kinds. `null` when the limits are not known.
128
+ */
129
+ export function extensionsTakenBy(limits) {
130
+ var _a;
131
+ if (limits === null)
132
+ return null;
133
+ var extensions = new Set();
134
+ for (var _i = 0, _b = __spreadArray(__spreadArray([], limits.multipartMimeTypes, true), limits.tusMimeTypes, true); _i < _b.length; _i++) {
135
+ var mimeType = _b[_i];
136
+ for (var _c = 0, _d = (_a = EXTENSIONS_BY_MIME_TYPE[mimeType]) !== null && _a !== void 0 ? _a : []; _c < _d.length; _c++) {
137
+ var extension = _d[_c];
138
+ extensions.add(extension);
139
+ }
140
+ }
141
+ return extensions;
142
+ }
143
+ /** The extensions of a list that the API takes. The whole list when the limits are not known. */
144
+ export function extensionsTakenFrom(extensions, limits) {
145
+ var taken = extensionsTakenBy(limits);
146
+ if (taken === null)
147
+ return __spreadArray([], extensions, true);
148
+ return extensions.filter(function (extension) { return taken.has(extension.toLowerCase()); });
149
+ }
150
+ /**
151
+ * True when the API takes a file of this MIME type, as far as the limits say. An empty type is "not known" (a browser
152
+ * reports none for some files while they are only dragged), so it is not refused here.
153
+ */
154
+ export function limitsTakeMimeType(mimeType, limits) {
155
+ if (limits === null)
156
+ return true;
157
+ var normalized = mimeType.trim().toLowerCase();
158
+ if (normalized === '')
159
+ return true;
160
+ return limits.multipartMimeTypes.has(normalized) || limits.tusMimeTypes.has(normalized);
161
+ }
162
+ var limitsCacheByApiBase = new Map();
163
+ var limitsRequestByApiBase = new Map();
164
+ /** Forgets what was read (a test, or a page that changed its API address). */
165
+ export function resetUploadLimitsCache() {
166
+ limitsCacheByApiBase.clear();
167
+ limitsRequestByApiBase.clear();
168
+ }
169
+ /**
170
+ * The limits of the API behind `config`: from memory when they were read in the last minute, else asked for
171
+ * (`GET {apiBasePath}/uploads/limits`, with the token the page gives and a fresh one when the API refuses it). The same
172
+ * request is the check of the session that comes before the first file of a batch. One request is shared by every caller
173
+ * that asks while it is under way.
174
+ */
175
+ export function loadUploadLimits(config_1) {
176
+ return __awaiter(this, arguments, Promise, function (config, options) {
177
+ var apiBasePath, now, cached, requestInFlight, request;
178
+ var _this = this;
179
+ var _a;
180
+ if (options === void 0) { options = {}; }
181
+ return __generator(this, function (_b) {
182
+ apiBasePath = config.apiBasePath.replace(/\/+$/, '');
183
+ now = (_a = options.now) !== null && _a !== void 0 ? _a : Date.now;
184
+ cached = limitsCacheByApiBase.get(apiBasePath);
185
+ if (!options.forceReload && cached && now() - cached.fetchedAt < LIMITS_CACHE_MILLISECONDS) {
186
+ return [2 /*return*/, { limits: cached.limits, sessionRefused: false }];
187
+ }
188
+ requestInFlight = limitsRequestByApiBase.get(apiBasePath);
189
+ if (requestInFlight && !options.forceReload)
190
+ return [2 /*return*/, requestInFlight];
191
+ request = (function () { return __awaiter(_this, void 0, Promise, function () {
192
+ var response, limits, _a, error_1;
193
+ return __generator(this, function (_b) {
194
+ switch (_b.label) {
195
+ case 0:
196
+ _b.trys.push([0, 3, , 4]);
197
+ return [4 /*yield*/, withTokenRetriedOnce(config, function (accessToken) {
198
+ return fetch("".concat(apiBasePath, "/uploads/limits"), {
199
+ headers: { Authorization: "Bearer ".concat(accessToken) },
200
+ signal: options.signal,
201
+ });
202
+ }, { signal: options.signal })];
203
+ case 1:
204
+ response = _b.sent();
205
+ if (response.status === 401) {
206
+ console.warn('[FileBrowser] The API refused the session when asking for the upload limits');
207
+ return [2 /*return*/, { limits: null, sessionRefused: true }];
208
+ }
209
+ if (!response.ok) {
210
+ console.warn("[FileBrowser] Could not read the upload limits (".concat(response.status, "); the API will judge each file"));
211
+ return [2 /*return*/, { limits: null, sessionRefused: false }];
212
+ }
213
+ _a = parseUploadLimits;
214
+ return [4 /*yield*/, response.json()];
215
+ case 2:
216
+ limits = _a.apply(void 0, [_b.sent()]);
217
+ if (limits === null) {
218
+ console.warn('[FileBrowser] The upload limits had no list of accepted types; the API will judge each file');
219
+ return [2 /*return*/, { limits: null, sessionRefused: false }];
220
+ }
221
+ limitsCacheByApiBase.set(apiBasePath, { limits: limits, fetchedAt: now() });
222
+ return [2 /*return*/, { limits: limits, sessionRefused: false }];
223
+ case 3:
224
+ error_1 = _b.sent();
225
+ if (!(error_1 instanceof DOMException && error_1.name === 'AbortError')) {
226
+ console.warn('[FileBrowser] Could not read the upload limits; the API will judge each file', error_1);
227
+ }
228
+ return [2 /*return*/, { limits: null, sessionRefused: false }];
229
+ case 4: return [2 /*return*/];
230
+ }
231
+ });
232
+ }); })();
233
+ limitsRequestByApiBase.set(apiBasePath, request);
234
+ // The request is shared only while it is under way. (A newer one, started with `forceReload`, is not forgotten.)
235
+ void request.finally(function () {
236
+ if (limitsRequestByApiBase.get(apiBasePath) === request)
237
+ limitsRequestByApiBase.delete(apiBasePath);
238
+ });
239
+ return [2 /*return*/, request];
240
+ });
241
+ });
242
+ }
@@ -1,26 +1,39 @@
1
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
2
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
3
+ if (ar || !(i in from)) {
4
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
5
+ ar[i] = from[i];
6
+ }
7
+ }
8
+ return to.concat(ar || Array.prototype.slice.call(from));
9
+ };
1
10
  /** Default page size for GET /v1/uploads (no cursor yet). */
2
- export const WIDGETIC_UPLOADS_LIST_LIMIT = 100;
11
+ export var WIDGETIC_UPLOADS_LIST_LIMIT = 100;
3
12
  /**
4
13
  * Merges a Dexie-cached upload list with a fresh API page.
5
14
  * When the API returns fewer than `listLimit` rows, the list is treated as complete and cached-only ids are dropped.
6
15
  */
7
16
  export function mergeRemoteUploadList(cachedFiles, remoteFiles, options) {
17
+ var _a;
8
18
  if (!options.apiHydrationSucceeded) {
9
- const byId = new Map(cachedFiles.map((file) => [file.id, file]));
10
- for (const remoteFile of remoteFiles) {
11
- byId.set(remoteFile.id, remoteFile);
19
+ var byId_1 = new Map(cachedFiles.map(function (file) { return [file.id, file]; }));
20
+ for (var _i = 0, remoteFiles_1 = remoteFiles; _i < remoteFiles_1.length; _i++) {
21
+ var remoteFile = remoteFiles_1[_i];
22
+ byId_1.set(remoteFile.id, remoteFile);
12
23
  }
13
- return Array.from(byId.values());
24
+ return Array.from(byId_1.values());
14
25
  }
15
- const listLimit = options.listLimit ?? WIDGETIC_UPLOADS_LIST_LIMIT;
16
- const remoteIds = new Set(remoteFiles.map((file) => file.id));
17
- const completeList = remoteFiles.length < listLimit;
18
- const byId = new Map(cachedFiles.map((file) => [file.id, file]));
19
- for (const remoteFile of remoteFiles) {
26
+ var listLimit = (_a = options.listLimit) !== null && _a !== void 0 ? _a : WIDGETIC_UPLOADS_LIST_LIMIT;
27
+ var remoteIds = new Set(remoteFiles.map(function (file) { return file.id; }));
28
+ var completeList = remoteFiles.length < listLimit;
29
+ var byId = new Map(cachedFiles.map(function (file) { return [file.id, file]; }));
30
+ for (var _b = 0, remoteFiles_2 = remoteFiles; _b < remoteFiles_2.length; _b++) {
31
+ var remoteFile = remoteFiles_2[_b];
20
32
  byId.set(remoteFile.id, remoteFile);
21
33
  }
22
34
  if (completeList) {
23
- for (const cachedId of [...byId.keys()]) {
35
+ for (var _c = 0, _d = __spreadArray([], byId.keys(), true); _c < _d.length; _c++) {
36
+ var cachedId = _d[_c];
24
37
  if (!remoteIds.has(cachedId)) {
25
38
  byId.delete(cachedId);
26
39
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * When the upload panel may close by itself.
3
+ *
4
+ * The panel (the dim overlay with the list of the batch) closes shortly after the last file went through, so the file grid is usable
5
+ * again. A batch in which a file failed does not close: the person has to see which files failed and be able to ask for another try
6
+ * (the retry of the summary and of the footer, or of a single row). A file still waiting or sending keeps it open as well.
7
+ */
8
+ /** The part of an upload row that decides this. */
9
+ export interface UploadPanelItemLike {
10
+ status: string;
11
+ }
12
+ /** Whether every file of the batch went through, which is the only case in which the panel closes on its own. */
13
+ export declare function shouldDismissUploadPanel(items: readonly UploadPanelItemLike[]): boolean;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * When the upload panel may close by itself.
3
+ *
4
+ * The panel (the dim overlay with the list of the batch) closes shortly after the last file went through, so the file grid is usable
5
+ * again. A batch in which a file failed does not close: the person has to see which files failed and be able to ask for another try
6
+ * (the retry of the summary and of the footer, or of a single row). A file still waiting or sending keeps it open as well.
7
+ */
8
+ /** Whether every file of the batch went through, which is the only case in which the panel closes on its own. */
9
+ export function shouldDismissUploadPanel(items) {
10
+ return items.length > 0 && items.every(function (item) { return item.status === 'complete'; });
11
+ }
@@ -2,16 +2,16 @@
2
2
  * Panel-level upload bar must never visually regress (CSS width transitions amplify brief dips).
3
3
  */
4
4
  export function monotonicPanelProgress(previousPeak, nextOverall, allSuccess) {
5
- const safeNext = Number.isFinite(nextOverall) ? Math.min(100, Math.max(0, nextOverall)) : 0;
6
- const safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
5
+ var safeNext = Number.isFinite(nextOverall) ? Math.min(100, Math.max(0, nextOverall)) : 0;
6
+ var safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
7
7
  if (allSuccess)
8
8
  return 100;
9
9
  return Math.max(safePeak, safeNext);
10
10
  }
11
11
  export function nextUploadPanelPeak(previousPeak, displayProgress) {
12
- const safeDisplay = Number.isFinite(displayProgress)
12
+ var safeDisplay = Number.isFinite(displayProgress)
13
13
  ? Math.min(100, Math.max(0, displayProgress))
14
14
  : 0;
15
- const safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
15
+ var safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
16
16
  return Math.max(safePeak, safeDisplay);
17
17
  }
@@ -1,18 +1,19 @@
1
1
  /** Minimum sampling window before we show a time-left estimate (ms). */
2
- export const UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS = 1000;
2
+ export var UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS = 1000;
3
3
  /** Visual throttle for progress UI (ms). */
4
- export const UPLOAD_UI_PROGRESS_THROTTLE_MS = 100;
4
+ export var UPLOAD_UI_PROGRESS_THROTTLE_MS = 100;
5
5
  /**
6
6
  * Exponential moving average of throughput (bytes per second) from (time, cumulative uploaded) samples.
7
7
  * Returns a non-negative finite rate or undefined when there is not enough data.
8
8
  */
9
- export function movingAverageThroughputBps(previousBps, prevSample, next, smoothing = 0.35) {
9
+ export function movingAverageThroughputBps(previousBps, prevSample, next, smoothing) {
10
+ if (smoothing === void 0) { smoothing = 0.35; }
10
11
  if (!prevSample || next.uploadedBytes <= prevSample.uploadedBytes)
11
12
  return previousBps;
12
- const dt = next.t - prevSample.t;
13
+ var dt = next.t - prevSample.t;
13
14
  if (dt <= 0)
14
15
  return previousBps;
15
- const inst = ((next.uploadedBytes - prevSample.uploadedBytes) / dt) * 1000;
16
+ var inst = ((next.uploadedBytes - prevSample.uploadedBytes) / dt) * 1000;
16
17
  if (!Number.isFinite(inst) || inst < 0)
17
18
  return previousBps;
18
19
  if (previousBps === undefined || !Number.isFinite(previousBps))
@@ -27,7 +28,7 @@ export function secondsRemainingFromThroughput(remainingBytes, throughputBps) {
27
28
  return undefined;
28
29
  if (remainingBytes <= 0)
29
30
  return 0;
30
- const secs = remainingBytes / throughputBps;
31
+ var secs = remainingBytes / throughputBps;
31
32
  if (!Number.isFinite(secs))
32
33
  return undefined;
33
34
  return Math.max(0, secs);
@@ -36,10 +37,11 @@ export function secondsRemainingFromThroughput(remainingBytes, throughputBps) {
36
37
  * Overall fractional progress from per-file byte counts (0–1). Completed/failed items contribute full size when `includeComplete` is true.
37
38
  */
38
39
  export function overallBytesProgressRatio(params) {
39
- let sumUploaded = 0;
40
- let sumTotal = 0;
41
- for (const it of params.items) {
42
- const total = Math.max(0, it.bytesTotal || 0);
40
+ var sumUploaded = 0;
41
+ var sumTotal = 0;
42
+ for (var _i = 0, _a = params.items; _i < _a.length; _i++) {
43
+ var it = _a[_i];
44
+ var total = Math.max(0, it.bytesTotal || 0);
43
45
  if (total === 0)
44
46
  continue;
45
47
  sumTotal += total;
@@ -51,7 +53,7 @@ export function overallBytesProgressRatio(params) {
51
53
  }
52
54
  else {
53
55
  // uploading (or cancelled mid-flight — row removed before this runs)
54
- const uploaded = Math.min(total, Math.max(0, it.bytesUploaded));
56
+ var uploaded = Math.min(total, Math.max(0, it.bytesUploaded));
55
57
  sumUploaded += uploaded;
56
58
  }
57
59
  }
@@ -0,0 +1,42 @@
1
+ import type { Translate } from '../i18n/context';
2
+ import { type UploadLimits, type UploadRefusal } from './uploadLimits';
3
+ /**
4
+ * Which of the files a visitor picked or dropped are sent, and which are left out with a reason, before anything is
5
+ * queued: a file the API would refuse (415 "Unsupported file type", 413 "too large") never becomes a row of the upload
6
+ * panel that fails after the wait and offers "Retry failed uploads?" for a file that can never go through.
7
+ */
8
+ /** What is wrong with a file: the API's refusal, or the filter of this File Browser (it was set to take only some kinds). */
9
+ export type FileRefusal = UploadRefusal | {
10
+ reason: 'filter';
11
+ };
12
+ export type RefusedFile = {
13
+ file: File;
14
+ refusal: FileRefusal;
15
+ };
16
+ export type UploadPlan = {
17
+ accepted: File[];
18
+ refused: RefusedFile[];
19
+ };
20
+ /** How a file's type is named to the visitor: its extension (".otf"), else its MIME type, else nothing. */
21
+ export declare function typeLabelOfFile(file: Pick<File, 'name' | 'type'>): string;
22
+ /**
23
+ * Splits the files into those that go on to be uploaded and those that are refused. A file is refused when its
24
+ * extension is not one this File Browser takes (`takesExtension`, the visitor's filter), and then when the API says it
25
+ * would not take it (`limits`; without them the API judges each file, as it always has).
26
+ */
27
+ export declare function planUploads(files: readonly File[], rules: {
28
+ takesExtension: (extension: string) => boolean;
29
+ limits: UploadLimits | null;
30
+ }): UploadPlan;
31
+ /** The sentence that says a kind of file is not supported: ".otf, .woff files are not supported". */
32
+ export declare function unsupportedTypeReason(labels: readonly string[], translate: Translate): string;
33
+ /**
34
+ * The sentences that tell the visitor which files were left out and why: one per reason (a pick of fonts and a huge
35
+ * video is two sentences), each naming the file when it is one file ("a.otf" was not uploaded: .otf files are not
36
+ * supported) or counting them when there are several (3 files were not uploaded: .otf, .woff files are not supported).
37
+ *
38
+ * `filterReason` is the sentence for the files the filter does not take, which the File Browser words from the kinds it
39
+ * was set to ("Invalid file type. Please use image files only."). `null` when it takes every kind: a file it does not list
40
+ * is then worded like any other unsupported type.
41
+ */
42
+ export declare function refusalMessages(refused: readonly RefusedFile[], translate: Translate, filterReason: string | null): string[];
@@ -0,0 +1,86 @@
1
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
2
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
3
+ if (ar || !(i in from)) {
4
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
5
+ ar[i] = from[i];
6
+ }
7
+ }
8
+ return to.concat(ar || Array.prototype.slice.call(from));
9
+ };
10
+ import { extensionOfFileName, refusalForFile } from './uploadLimits';
11
+ /** The most kinds of file named in one message (".a, .b, .c, .d, …"): more would only make the toast too long to read. */
12
+ var MOST_TYPES_NAMED = 4;
13
+ var BYTES_PER_MEGABYTE = 1024 * 1024;
14
+ /** How a file's type is named to the visitor: its extension (".otf"), else its MIME type, else nothing. */
15
+ export function typeLabelOfFile(file) {
16
+ return extensionOfFileName(file.name) || file.type.trim().toLowerCase();
17
+ }
18
+ /**
19
+ * Splits the files into those that go on to be uploaded and those that are refused. A file is refused when its
20
+ * extension is not one this File Browser takes (`takesExtension`, the visitor's filter), and then when the API says it
21
+ * would not take it (`limits`; without them the API judges each file, as it always has).
22
+ */
23
+ export function planUploads(files, rules) {
24
+ var accepted = [];
25
+ var refused = [];
26
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
27
+ var file = files_1[_i];
28
+ if (!rules.takesExtension(extensionOfFileName(file.name))) {
29
+ refused.push({ file: file, refusal: { reason: 'filter' } });
30
+ continue;
31
+ }
32
+ var refusal = refusalForFile(file, rules.limits);
33
+ if (refusal) {
34
+ refused.push({ file: file, refusal: refusal });
35
+ continue;
36
+ }
37
+ accepted.push(file);
38
+ }
39
+ return { accepted: accepted, refused: refused };
40
+ }
41
+ /** The sentence that says a kind of file is not supported: ".otf, .woff files are not supported". */
42
+ export function unsupportedTypeReason(labels, translate) {
43
+ var named = __spreadArray([], new Set(labels.filter(function (label) { return label !== ''; })), true);
44
+ if (named.length === 0)
45
+ return translate('upload.refusedTypeUnknown');
46
+ var separator = translate('list.separator');
47
+ var shown = named.slice(0, MOST_TYPES_NAMED).join(separator);
48
+ return translate('upload.refusedType', { type: named.length > MOST_TYPES_NAMED ? "".concat(shown).concat(separator, "\u2026") : shown });
49
+ }
50
+ /**
51
+ * The sentences that tell the visitor which files were left out and why: one per reason (a pick of fonts and a huge
52
+ * video is two sentences), each naming the file when it is one file ("a.otf" was not uploaded: .otf files are not
53
+ * supported) or counting them when there are several (3 files were not uploaded: .otf, .woff files are not supported).
54
+ *
55
+ * `filterReason` is the sentence for the files the filter does not take, which the File Browser words from the kinds it
56
+ * was set to ("Invalid file type. Please use image files only."). `null` when it takes every kind: a file it does not list
57
+ * is then worded like any other unsupported type.
58
+ */
59
+ export function refusalMessages(refused, translate, filterReason) {
60
+ var _a;
61
+ var groups = new Map();
62
+ for (var _i = 0, refused_1 = refused; _i < refused_1.length; _i++) {
63
+ var entry = refused_1[_i];
64
+ var groupKey = entry.refusal.reason === 'tooLarge'
65
+ ? "tooLarge:".concat(entry.refusal.maxBytes)
66
+ : entry.refusal.reason === 'filter' && filterReason !== null
67
+ ? 'filter'
68
+ : 'unsupportedType';
69
+ groups.set(groupKey, __spreadArray(__spreadArray([], ((_a = groups.get(groupKey)) !== null && _a !== void 0 ? _a : []), true), [entry], false));
70
+ }
71
+ return __spreadArray([], groups.entries(), true).map(function (_a) {
72
+ var groupKey = _a[0], group = _a[1];
73
+ var firstRefusal = group[0].refusal;
74
+ var reason = groupKey === 'filter'
75
+ ? filterReason
76
+ : firstRefusal.reason === 'tooLarge'
77
+ ? translate('upload.refusedTooLarge', { limit: Math.round(firstRefusal.maxBytes / BYTES_PER_MEGABYTE) })
78
+ : unsupportedTypeReason(group.map(function (_a) {
79
+ var file = _a.file;
80
+ return typeLabelOfFile(file);
81
+ }), translate);
82
+ return group.length === 1
83
+ ? translate('upload.refusedOne', { name: group[0].file.name, reason: reason })
84
+ : translate('upload.refusedMany', { count: group.length, reason: reason });
85
+ });
86
+ }
@@ -2,10 +2,10 @@
2
2
  * Infer a MIME type for stored files (matches previous widgeticUpload behavior).
3
3
  */
4
4
  export function inferImageMime(mime, fileName, url) {
5
- const stored = (mime || '').toLowerCase();
5
+ var stored = (mime || '').toLowerCase();
6
6
  if (stored.startsWith('image/'))
7
7
  return stored;
8
- const hint = `${fileName} ${url}`.split(/[?#]/)[0];
8
+ var hint = "".concat(fileName, " ").concat(url).split(/[?#]/)[0];
9
9
  if (/\.(png)(\?|$)/i.test(hint))
10
10
  return 'image/png';
11
11
  if (/\.(gif)(\?|$)/i.test(hint))
@@ -28,22 +28,23 @@ export function inferImageMime(mime, fileName, url) {
28
28
  * Map a successful POST /uploads JSON body to {@link WidgeticUploadResult}, or an error when `url` is missing.
29
29
  */
30
30
  export function mapWidgeticUploadSuccessJson(data, file) {
31
- const url = data.url || '';
31
+ var _a, _b;
32
+ var url = data.url || '';
32
33
  if (!url) {
33
34
  return { success: false, error: 'Upload response missing url' };
34
35
  }
35
- const fileName = (data.file_name || data.fileName || file.name);
36
- const fileId = (data.id || `upload_${Date.now()}`);
37
- const storedMimeType = inferImageMime((data.mime_type || data.mimeType || file.type) || '', fileName, url);
36
+ var fileName = (data.file_name || data.fileName || file.name);
37
+ var fileId = (data.id || "upload_".concat(Date.now()));
38
+ var storedMimeType = inferImageMime((data.mime_type || data.mimeType || file.type) || '', fileName, url);
38
39
  return {
39
40
  success: true,
40
41
  file: {
41
42
  id: fileId,
42
43
  name: fileName,
43
44
  type: 'file',
44
- size: (data.file_size ?? data.fileSize ?? file.size),
45
+ size: ((_b = (_a = data.file_size) !== null && _a !== void 0 ? _a : data.fileSize) !== null && _b !== void 0 ? _b : file.size),
45
46
  modified: new Date().toISOString(),
46
- url,
47
+ url: url,
47
48
  thumbnail: storedMimeType.startsWith('image/') ? url : undefined,
48
49
  mimeType: storedMimeType || undefined,
49
50
  },