@widgetic/file-browser 0.5.48 → 0.5.49

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 (81) hide show
  1. package/dist/actions/dragSelectedToFolder.js +115 -104
  2. package/dist/components/FolderTree.svelte.d.ts +7 -4
  3. package/dist/components/core/FileBrowser.svelte +1 -3
  4. package/dist/components/core/dropzoneClick.js +2 -3
  5. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  6. package/dist/config.js +3 -4
  7. package/dist/i18n/context.js +2 -2
  8. package/dist/i18n/errors.js +1 -2
  9. package/dist/i18n/messages.js +2 -2
  10. package/dist/i18n/text.js +2 -2
  11. package/dist/mediaLibrary/capabilities.js +3 -4
  12. package/dist/mediaLibrary/context.js +3 -4
  13. package/dist/mediaLibrary/errors.js +35 -46
  14. package/dist/mediaLibrary/normalize.js +42 -45
  15. package/dist/mediaLibrary/paging.js +45 -100
  16. package/dist/mediaLibrary/resolve.js +95 -214
  17. package/dist/mediaLibrary/treeOps.js +20 -40
  18. package/dist/mediaLibrary/urls.js +10 -12
  19. package/dist/mediaLibrary/widgetic.js +54 -140
  20. package/dist/stores/dragStore.js +1 -1
  21. package/dist/stores/fileStore.d.ts +3 -3
  22. package/dist/stores/fileStore.js +37 -44
  23. package/dist/stores/folderCountStore.js +11 -12
  24. package/dist/stores/missingFilesStore.js +3 -3
  25. package/dist/stores/navigationStore.d.ts +1 -1
  26. package/dist/stores/navigationStore.js +178 -217
  27. package/dist/stores/persistentSelectStore.d.ts +1 -1
  28. package/dist/stores/persistentSelectStore.js +94 -117
  29. package/dist/stores/searchStore.js +1 -1
  30. package/dist/stores/uploadApiStore.js +7 -7
  31. package/dist/stores/viewportStore.js +4 -4
  32. package/dist/types/index.js +1 -0
  33. package/dist/utils/apiConfig.js +9 -9
  34. package/dist/utils/brandKitLibraryTree.js +42 -57
  35. package/dist/utils/dateUtils.js +9 -11
  36. package/dist/utils/dragToFolder/batchMoveResult.js +54 -114
  37. package/dist/utils/dragToFolder/folderDropTarget.js +17 -23
  38. package/dist/utils/dragToFolder/springStep.js +3 -4
  39. package/dist/utils/fileGoneProbe.js +16 -65
  40. package/dist/utils/fileKinds.js +13 -14
  41. package/dist/utils/fileNames.js +7 -7
  42. package/dist/utils/fileOperations.js +332 -440
  43. package/dist/utils/fileTypes.js +14 -19
  44. package/dist/utils/fileUtils.js +31 -85
  45. package/dist/utils/folderUtils.js +4 -5
  46. package/dist/utils/gridLayout.js +7 -7
  47. package/dist/utils/imagePreviewCache.js +15 -26
  48. package/dist/utils/imagePreviewFrame.js +13 -13
  49. package/dist/utils/imagePreviewVisualState.js +4 -5
  50. package/dist/utils/imageTransform.js +14 -27
  51. package/dist/utils/itemMenuCapabilities.js +7 -7
  52. package/dist/utils/libraryTree.js +39 -55
  53. package/dist/utils/pendingUploadDeletes.js +113 -289
  54. package/dist/utils/previewKeys.js +1 -1
  55. package/dist/utils/previewListNavigation.js +11 -13
  56. package/dist/utils/previewNavigation.js +7 -10
  57. package/dist/utils/recentFiles.js +6 -16
  58. package/dist/utils/recentFilesLimit.js +2 -2
  59. package/dist/utils/removeItems.js +29 -61
  60. package/dist/utils/resolveFileUrl.js +6 -6
  61. package/dist/utils/safeText.js +12 -14
  62. package/dist/utils/searchDropdownPhase.js +2 -2
  63. package/dist/utils/searchItems.js +14 -30
  64. package/dist/utils/searchNavigation.js +5 -5
  65. package/dist/utils/uploadAuth.js +36 -111
  66. package/dist/utils/uploadDisplayProgress.js +1 -1
  67. package/dist/utils/uploadLimits.js +66 -138
  68. package/dist/utils/uploadListReconcile.js +11 -24
  69. package/dist/utils/uploadPanelDismiss.js +1 -1
  70. package/dist/utils/uploadPanelProgress.js +4 -4
  71. package/dist/utils/uploadProgressMath.js +11 -13
  72. package/dist/utils/uploadRefusals.js +24 -40
  73. package/dist/utils/uploadResponseMapping.js +8 -9
  74. package/dist/utils/uploadUiHelpers.js +17 -17
  75. package/dist/utils/userUploadsStorage.js +133 -270
  76. package/dist/utils/videoFrame.js +2 -2
  77. package/dist/utils/widgeticDelete.js +30 -103
  78. package/dist/utils/widgeticTusUpload.js +105 -189
  79. package/dist/utils/widgeticUpload.js +62 -130
  80. package/dist/utils/xhrMultipartUpload.js +116 -164
  81. package/package.json +1 -1
@@ -1,57 +1,12 @@
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
1
  import { withTokenRetriedOnce } from './uploadAuth';
47
2
  import { WIDGETIC_MULTIPART_MAX_BYTES } from './widgeticTusUpload';
48
3
  /**
49
4
  * How long the answer of the API is kept before it is asked again. The limits are configuration that rarely changes; the
50
5
  * minute is short so that the request that doubles as the session check still runs before each batch of files.
51
6
  */
52
- var LIMITS_CACHE_MILLISECONDS = 60 * 1000;
7
+ const LIMITS_CACHE_MILLISECONDS = 60 * 1000;
53
8
  /** 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 = {
9
+ const EXTENSIONS_BY_MIME_TYPE = {
55
10
  'image/png': ['.png'],
56
11
  'image/jpeg': ['.jpg', '.jpeg'],
57
12
  'image/webp': ['.webp'],
@@ -70,7 +25,7 @@ var EXTENSIONS_BY_MIME_TYPE = {
70
25
  function stringList(value) {
71
26
  if (!Array.isArray(value))
72
27
  return null;
73
- return value.filter(function (entry) { return typeof entry === 'string'; }).map(function (entry) { return entry.trim().toLowerCase(); });
28
+ return value.filter((entry) => typeof entry === 'string').map((entry) => entry.trim().toLowerCase());
74
29
  }
75
30
  function positiveNumber(value) {
76
31
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
@@ -82,12 +37,12 @@ function positiveNumber(value) {
82
37
  export function parseUploadLimits(json) {
83
38
  if (json === null || typeof json !== 'object')
84
39
  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);
40
+ const body = json;
41
+ const payload = body.data !== null && typeof body.data === 'object' ? body.data : body;
42
+ const multipartMimeTypes = stringList(payload.multipart_mime_types);
88
43
  if (multipartMimeTypes === null || multipartMimeTypes.length === 0)
89
44
  return null;
90
- var tusMimeTypes = stringList(payload.tus_mime_types);
45
+ const tusMimeTypes = stringList(payload.tus_mime_types);
91
46
  return {
92
47
  multipartMaxBytes: positiveNumber(payload.multipart_max_bytes),
93
48
  tusMaxBytes: positiveNumber(payload.tus_max_bytes),
@@ -101,23 +56,21 @@ export function parseUploadLimits(json) {
101
56
  * 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
57
  * of a kind the API never takes is refused for that whatever its size.
103
58
  */
104
- export function refusalForFile(file, limits, isResumable) {
105
- var _a;
106
- if (isResumable === void 0) { isResumable = file.size > WIDGETIC_MULTIPART_MAX_BYTES; }
59
+ export function refusalForFile(file, limits, isResumable = file.size > WIDGETIC_MULTIPART_MAX_BYTES) {
107
60
  if (limits === null)
108
61
  return null;
109
- var mimeType = file.type.trim().toLowerCase();
110
- var takenTypes = isResumable && limits.tusEnabled ? limits.tusMimeTypes : limits.multipartMimeTypes;
62
+ const mimeType = file.type.trim().toLowerCase();
63
+ const takenTypes = isResumable && limits.tusEnabled ? limits.tusMimeTypes : limits.multipartMimeTypes;
111
64
  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;
65
+ return { reason: 'unsupportedType', mimeType };
66
+ const largestSize = limits.tusEnabled ? (limits.tusMaxBytes ?? limits.multipartMaxBytes) : limits.multipartMaxBytes;
114
67
  if (largestSize !== null && file.size > largestSize)
115
68
  return { reason: 'tooLarge', maxBytes: largestSize };
116
69
  return null;
117
70
  }
118
71
  /** The extension of a file name with its dot and in lower case (".otf"); an empty string when the name has none. */
119
72
  export function extensionOfFileName(fileName) {
120
- var dotIndex = fileName.lastIndexOf('.');
73
+ const dotIndex = fileName.lastIndexOf('.');
121
74
  if (dotIndex <= 0 || dotIndex === fileName.length - 1)
122
75
  return '';
123
76
  return fileName.slice(dotIndex).toLowerCase();
@@ -127,25 +80,21 @@ export function extensionOfFileName(fileName) {
127
80
  * own kinds. `null` when the limits are not known.
128
81
  */
129
82
  export function extensionsTakenBy(limits) {
130
- var _a;
131
83
  if (limits === null)
132
84
  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];
85
+ const extensions = new Set();
86
+ for (const mimeType of [...limits.multipartMimeTypes, ...limits.tusMimeTypes]) {
87
+ for (const extension of EXTENSIONS_BY_MIME_TYPE[mimeType] ?? [])
138
88
  extensions.add(extension);
139
- }
140
89
  }
141
90
  return extensions;
142
91
  }
143
92
  /** The extensions of a list that the API takes. The whole list when the limits are not known. */
144
93
  export function extensionsTakenFrom(extensions, limits) {
145
- var taken = extensionsTakenBy(limits);
94
+ const taken = extensionsTakenBy(limits);
146
95
  if (taken === null)
147
- return __spreadArray([], extensions, true);
148
- return extensions.filter(function (extension) { return taken.has(extension.toLowerCase()); });
96
+ return [...extensions];
97
+ return extensions.filter((extension) => taken.has(extension.toLowerCase()));
149
98
  }
150
99
  /**
151
100
  * 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
@@ -154,13 +103,13 @@ export function extensionsTakenFrom(extensions, limits) {
154
103
  export function limitsTakeMimeType(mimeType, limits) {
155
104
  if (limits === null)
156
105
  return true;
157
- var normalized = mimeType.trim().toLowerCase();
106
+ const normalized = mimeType.trim().toLowerCase();
158
107
  if (normalized === '')
159
108
  return true;
160
109
  return limits.multipartMimeTypes.has(normalized) || limits.tusMimeTypes.has(normalized);
161
110
  }
162
- var limitsCacheByApiBase = new Map();
163
- var limitsRequestByApiBase = new Map();
111
+ const limitsCacheByApiBase = new Map();
112
+ const limitsRequestByApiBase = new Map();
164
113
  /** Forgets what was read (a test, or a page that changed its API address). */
165
114
  export function resetUploadLimitsCache() {
166
115
  limitsCacheByApiBase.clear();
@@ -172,71 +121,50 @@ export function resetUploadLimitsCache() {
172
121
  * request is the check of the session that comes before the first file of a batch. One request is shared by every caller
173
122
  * that asks while it is under way.
174
123
  */
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 }];
124
+ export async function loadUploadLimits(config, options = {}) {
125
+ const apiBasePath = config.apiBasePath.replace(/\/+$/, '');
126
+ const now = options.now ?? Date.now;
127
+ const cached = limitsCacheByApiBase.get(apiBasePath);
128
+ if (!options.forceReload && cached && now() - cached.fetchedAt < LIMITS_CACHE_MILLISECONDS) {
129
+ return { limits: cached.limits, sessionRefused: false };
130
+ }
131
+ const requestInFlight = limitsRequestByApiBase.get(apiBasePath);
132
+ if (requestInFlight && !options.forceReload)
133
+ return requestInFlight;
134
+ const request = (async () => {
135
+ try {
136
+ const response = await withTokenRetriedOnce(config, (accessToken) => fetch(`${apiBasePath}/uploads/limits`, {
137
+ headers: { Authorization: `Bearer ${accessToken}` },
138
+ signal: options.signal,
139
+ }), { signal: options.signal });
140
+ if (response.status === 401) {
141
+ console.warn('[FileBrowser] The API refused the session when asking for the upload limits');
142
+ return { limits: null, sessionRefused: true };
143
+ }
144
+ if (!response.ok) {
145
+ console.warn(`[FileBrowser] Could not read the upload limits (${response.status}); the API will judge each file`);
146
+ return { limits: null, sessionRefused: false };
147
+ }
148
+ const limits = parseUploadLimits(await response.json());
149
+ if (limits === null) {
150
+ console.warn('[FileBrowser] The upload limits had no list of accepted types; the API will judge each file');
151
+ return { limits: null, sessionRefused: false };
187
152
  }
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
- });
153
+ limitsCacheByApiBase.set(apiBasePath, { limits, fetchedAt: now() });
154
+ return { limits, sessionRefused: false };
155
+ }
156
+ catch (error) {
157
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
158
+ console.warn('[FileBrowser] Could not read the upload limits; the API will judge each file', error);
159
+ }
160
+ return { limits: null, sessionRefused: false };
161
+ }
162
+ })();
163
+ limitsRequestByApiBase.set(apiBasePath, request);
164
+ // The request is shared only while it is under way. (A newer one, started with `forceReload`, is not forgotten.)
165
+ void request.finally(() => {
166
+ if (limitsRequestByApiBase.get(apiBasePath) === request)
167
+ limitsRequestByApiBase.delete(apiBasePath);
241
168
  });
169
+ return request;
242
170
  }
@@ -1,39 +1,26 @@
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
1
  /** Default page size for GET /v1/uploads (no cursor yet). */
11
- export var WIDGETIC_UPLOADS_LIST_LIMIT = 100;
2
+ export const WIDGETIC_UPLOADS_LIST_LIMIT = 100;
12
3
  /**
13
4
  * Merges a Dexie-cached upload list with a fresh API page.
14
5
  * When the API returns fewer than `listLimit` rows, the list is treated as complete and cached-only ids are dropped.
15
6
  */
16
7
  export function mergeRemoteUploadList(cachedFiles, remoteFiles, options) {
17
- var _a;
18
8
  if (!options.apiHydrationSucceeded) {
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);
9
+ const byId = new Map(cachedFiles.map((file) => [file.id, file]));
10
+ for (const remoteFile of remoteFiles) {
11
+ byId.set(remoteFile.id, remoteFile);
23
12
  }
24
- return Array.from(byId_1.values());
13
+ return Array.from(byId.values());
25
14
  }
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];
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) {
32
20
  byId.set(remoteFile.id, remoteFile);
33
21
  }
34
22
  if (completeList) {
35
- for (var _c = 0, _d = __spreadArray([], byId.keys(), true); _c < _d.length; _c++) {
36
- var cachedId = _d[_c];
23
+ for (const cachedId of [...byId.keys()]) {
37
24
  if (!remoteIds.has(cachedId)) {
38
25
  byId.delete(cachedId);
39
26
  }
@@ -7,5 +7,5 @@
7
7
  */
8
8
  /** Whether every file of the batch went through, which is the only case in which the panel closes on its own. */
9
9
  export function shouldDismissUploadPanel(items) {
10
- return items.length > 0 && items.every(function (item) { return item.status === 'complete'; });
10
+ return items.length > 0 && items.every((item) => item.status === 'complete');
11
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
- 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;
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;
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
- var safeDisplay = Number.isFinite(displayProgress)
12
+ const safeDisplay = Number.isFinite(displayProgress)
13
13
  ? Math.min(100, Math.max(0, displayProgress))
14
14
  : 0;
15
- var safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
15
+ const safePeak = Number.isFinite(previousPeak) ? Math.min(100, Math.max(0, previousPeak)) : 0;
16
16
  return Math.max(safePeak, safeDisplay);
17
17
  }
@@ -1,19 +1,18 @@
1
1
  /** Minimum sampling window before we show a time-left estimate (ms). */
2
- export var UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS = 1000;
2
+ export const UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS = 1000;
3
3
  /** Visual throttle for progress UI (ms). */
4
- export var UPLOAD_UI_PROGRESS_THROTTLE_MS = 100;
4
+ export const 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) {
10
- if (smoothing === void 0) { smoothing = 0.35; }
9
+ export function movingAverageThroughputBps(previousBps, prevSample, next, smoothing = 0.35) {
11
10
  if (!prevSample || next.uploadedBytes <= prevSample.uploadedBytes)
12
11
  return previousBps;
13
- var dt = next.t - prevSample.t;
12
+ const dt = next.t - prevSample.t;
14
13
  if (dt <= 0)
15
14
  return previousBps;
16
- var inst = ((next.uploadedBytes - prevSample.uploadedBytes) / dt) * 1000;
15
+ const inst = ((next.uploadedBytes - prevSample.uploadedBytes) / dt) * 1000;
17
16
  if (!Number.isFinite(inst) || inst < 0)
18
17
  return previousBps;
19
18
  if (previousBps === undefined || !Number.isFinite(previousBps))
@@ -28,7 +27,7 @@ export function secondsRemainingFromThroughput(remainingBytes, throughputBps) {
28
27
  return undefined;
29
28
  if (remainingBytes <= 0)
30
29
  return 0;
31
- var secs = remainingBytes / throughputBps;
30
+ const secs = remainingBytes / throughputBps;
32
31
  if (!Number.isFinite(secs))
33
32
  return undefined;
34
33
  return Math.max(0, secs);
@@ -37,11 +36,10 @@ export function secondsRemainingFromThroughput(remainingBytes, throughputBps) {
37
36
  * Overall fractional progress from per-file byte counts (0–1). Completed/failed items contribute full size when `includeComplete` is true.
38
37
  */
39
38
  export function overallBytesProgressRatio(params) {
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);
39
+ let sumUploaded = 0;
40
+ let sumTotal = 0;
41
+ for (const it of params.items) {
42
+ const total = Math.max(0, it.bytesTotal || 0);
45
43
  if (total === 0)
46
44
  continue;
47
45
  sumTotal += total;
@@ -53,7 +51,7 @@ export function overallBytesProgressRatio(params) {
53
51
  }
54
52
  else {
55
53
  // uploading (or cancelled mid-flight — row removed before this runs)
56
- var uploaded = Math.min(total, Math.max(0, it.bytesUploaded));
54
+ const uploaded = Math.min(total, Math.max(0, it.bytesUploaded));
57
55
  sumUploaded += uploaded;
58
56
  }
59
57
  }
@@ -1,16 +1,7 @@
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
1
  import { extensionOfFileName, refusalForFile } from './uploadLimits';
11
2
  /** 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;
3
+ const MOST_TYPES_NAMED = 4;
4
+ const BYTES_PER_MEGABYTE = 1024 * 1024;
14
5
  /** How a file's type is named to the visitor: its extension (".otf"), else its MIME type, else nothing. */
15
6
  export function typeLabelOfFile(file) {
16
7
  return extensionOfFileName(file.name) || file.type.trim().toLowerCase();
@@ -21,31 +12,30 @@ export function typeLabelOfFile(file) {
21
12
  * would not take it (`limits`; without them the API judges each file, as it always has).
22
13
  */
23
14
  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];
15
+ const accepted = [];
16
+ const refused = [];
17
+ for (const file of files) {
28
18
  if (!rules.takesExtension(extensionOfFileName(file.name))) {
29
- refused.push({ file: file, refusal: { reason: 'filter' } });
19
+ refused.push({ file, refusal: { reason: 'filter' } });
30
20
  continue;
31
21
  }
32
- var refusal = refusalForFile(file, rules.limits);
22
+ const refusal = refusalForFile(file, rules.limits);
33
23
  if (refusal) {
34
- refused.push({ file: file, refusal: refusal });
24
+ refused.push({ file, refusal });
35
25
  continue;
36
26
  }
37
27
  accepted.push(file);
38
28
  }
39
- return { accepted: accepted, refused: refused };
29
+ return { accepted, refused };
40
30
  }
41
31
  /** The sentence that says a kind of file is not supported: ".otf, .woff files are not supported". */
42
32
  export function unsupportedTypeReason(labels, translate) {
43
- var named = __spreadArray([], new Set(labels.filter(function (label) { return label !== ''; })), true);
33
+ const named = [...new Set(labels.filter((label) => label !== ''))];
44
34
  if (named.length === 0)
45
35
  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 });
36
+ const separator = translate('list.separator');
37
+ const shown = named.slice(0, MOST_TYPES_NAMED).join(separator);
38
+ return translate('upload.refusedType', { type: named.length > MOST_TYPES_NAMED ? `${shown}${separator}…` : shown });
49
39
  }
50
40
  /**
51
41
  * The sentences that tell the visitor which files were left out and why: one per reason (a pick of fonts and a huge
@@ -57,30 +47,24 @@ export function unsupportedTypeReason(labels, translate) {
57
47
  * is then worded like any other unsupported type.
58
48
  */
59
49
  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)
50
+ const groups = new Map();
51
+ for (const entry of refused) {
52
+ const groupKey = entry.refusal.reason === 'tooLarge'
53
+ ? `tooLarge:${entry.refusal.maxBytes}`
66
54
  : entry.refusal.reason === 'filter' && filterReason !== null
67
55
  ? 'filter'
68
56
  : 'unsupportedType';
69
- groups.set(groupKey, __spreadArray(__spreadArray([], ((_a = groups.get(groupKey)) !== null && _a !== void 0 ? _a : []), true), [entry], false));
57
+ groups.set(groupKey, [...(groups.get(groupKey) ?? []), entry]);
70
58
  }
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'
59
+ return [...groups.entries()].map(([groupKey, group]) => {
60
+ const firstRefusal = group[0].refusal;
61
+ const reason = groupKey === 'filter'
75
62
  ? filterReason
76
63
  : firstRefusal.reason === 'tooLarge'
77
64
  ? 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);
65
+ : unsupportedTypeReason(group.map(({ file }) => typeLabelOfFile(file)), translate);
82
66
  return group.length === 1
83
- ? translate('upload.refusedOne', { name: group[0].file.name, reason: reason })
84
- : translate('upload.refusedMany', { count: group.length, reason: reason });
67
+ ? translate('upload.refusedOne', { name: group[0].file.name, reason })
68
+ : translate('upload.refusedMany', { count: group.length, reason });
85
69
  });
86
70
  }
@@ -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
- var stored = (mime || '').toLowerCase();
5
+ const stored = (mime || '').toLowerCase();
6
6
  if (stored.startsWith('image/'))
7
7
  return stored;
8
- var hint = "".concat(fileName, " ").concat(url).split(/[?#]/)[0];
8
+ const hint = `${fileName} ${url}`.split(/[?#]/)[0];
9
9
  if (/\.(png)(\?|$)/i.test(hint))
10
10
  return 'image/png';
11
11
  if (/\.(gif)(\?|$)/i.test(hint))
@@ -28,23 +28,22 @@ 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
- var _a, _b;
32
- var url = data.url || '';
31
+ const url = data.url || '';
33
32
  if (!url) {
34
33
  return { success: false, error: 'Upload response missing url' };
35
34
  }
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);
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);
39
38
  return {
40
39
  success: true,
41
40
  file: {
42
41
  id: fileId,
43
42
  name: fileName,
44
43
  type: 'file',
45
- size: ((_b = (_a = data.file_size) !== null && _a !== void 0 ? _a : data.fileSize) !== null && _b !== void 0 ? _b : file.size),
44
+ size: (data.file_size ?? data.fileSize ?? file.size),
46
45
  modified: new Date().toISOString(),
47
- url: url,
46
+ url,
48
47
  thumbnail: storedMimeType.startsWith('image/') ? url : undefined,
49
48
  mimeType: storedMimeType || undefined,
50
49
  },
@@ -1,21 +1,21 @@
1
1
  import { formatFileSize } from './fileUtils';
2
2
  import { movingAverageThroughputBps, secondsRemainingFromThroughput, UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS, } from './uploadProgressMath';
3
3
  export function formatUploadPercent(locale, ratio01) {
4
- var safe = Number.isFinite(ratio01) ? Math.min(1, Math.max(0, ratio01)) : 0;
4
+ const safe = Number.isFinite(ratio01) ? Math.min(1, Math.max(0, ratio01)) : 0;
5
5
  return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(safe);
6
6
  }
7
7
  /** Throughput estimate from cumulative bytes and wall clock; returns optional seconds left string via catalog. */
8
8
  export function updateThroughputEstimateState(params) {
9
- var bytesUploaded = params.bytesUploaded, bytesTotal = params.bytesTotal, now = params.now, prevSample = params.prevSample, throughputBps = params.throughputBps, firstSampleAt = params.firstSampleAt;
10
- var nextSample = { t: now, uploadedBytes: bytesUploaded };
11
- var nextThroughput = movingAverageThroughputBps(throughputBps, prevSample, nextSample);
12
- var startedAt = firstSampleAt !== null && firstSampleAt !== void 0 ? firstSampleAt : now;
13
- var remainingBytes = Math.max(0, bytesTotal - bytesUploaded);
14
- var secs = now - startedAt >= UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS
9
+ const { bytesUploaded, bytesTotal, now, prevSample, throughputBps, firstSampleAt } = params;
10
+ const nextSample = { t: now, uploadedBytes: bytesUploaded };
11
+ const nextThroughput = movingAverageThroughputBps(throughputBps, prevSample, nextSample);
12
+ const startedAt = firstSampleAt ?? now;
13
+ const remainingBytes = Math.max(0, bytesTotal - bytesUploaded);
14
+ const secs = now - startedAt >= UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS
15
15
  ? secondsRemainingFromThroughput(remainingBytes, nextThroughput)
16
16
  : undefined;
17
17
  return {
18
- nextSample: nextSample,
18
+ nextSample,
19
19
  throughputBps: nextThroughput,
20
20
  firstSampleAt: startedAt,
21
21
  secondsLeft: secs,
@@ -33,17 +33,17 @@ export function formatTimeLeftPhrase(translate, secondsLeft) {
33
33
  return translate('upload.time.minutes', { count: Math.max(1, Math.round(secondsLeft / 60)) });
34
34
  }
35
35
  export function buildActiveRowStatusText(params) {
36
- var translate = params.translate, locale = params.locale, phase = params.phase, displayPercent01 = params.displayPercent01, bytesUploaded = params.bytesUploaded, bytesTotal = params.bytesTotal, secondsLeft = params.secondsLeft;
37
- var pct = formatUploadPercent(locale, displayPercent01);
38
- var sent = formatFileSize(bytesUploaded, translate, locale);
39
- var total = formatFileSize(bytesTotal, translate, locale);
36
+ const { translate, locale, phase, displayPercent01, bytesUploaded, bytesTotal, secondsLeft } = params;
37
+ const pct = formatUploadPercent(locale, displayPercent01);
38
+ const sent = formatFileSize(bytesUploaded, translate, locale);
39
+ const total = formatFileSize(bytesTotal, translate, locale);
40
40
  if (phase === 'finishing') {
41
- return translate('upload.rowFinishingSized', { total: total });
41
+ return translate('upload.rowFinishingSized', { total });
42
42
  }
43
- var timePhrase = formatTimeLeftPhrase(translate, secondsLeft);
44
- var timeLeft = timePhrase ? translate('upload.timeLeft', { time: timePhrase }) : undefined;
43
+ const timePhrase = formatTimeLeftPhrase(translate, secondsLeft);
44
+ const timeLeft = timePhrase ? translate('upload.timeLeft', { time: timePhrase }) : undefined;
45
45
  if (timeLeft) {
46
- return translate('upload.rowActiveWithTime', { percent: pct, sent: sent, total: total, time: timeLeft });
46
+ return translate('upload.rowActiveWithTime', { percent: pct, sent, total, time: timeLeft });
47
47
  }
48
- return translate('upload.rowActive', { percent: pct, sent: sent, total: total });
48
+ return translate('upload.rowActive', { percent: pct, sent, total });
49
49
  }