@widgetic/file-browser 0.5.36 → 0.5.38

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 (41) hide show
  1. package/dist/components/core/FileBrowser.svelte +88 -98
  2. package/dist/components/core/FileUploader.svelte +307 -133
  3. package/dist/components/core/Header.svelte +1 -1
  4. package/dist/components/core/RecentFiles.svelte +21 -8
  5. package/dist/components/core/SearchDropdown.svelte +312 -0
  6. package/dist/components/core/SearchDropdown.svelte.d.ts +30 -0
  7. package/dist/components/core/UploadPanel.svelte +27 -15
  8. package/dist/components/core/UploadPanel.svelte.d.ts +3 -0
  9. package/dist/components/core/UploadRow.svelte +22 -1
  10. package/dist/components/core/UploadRow.svelte.d.ts +3 -0
  11. package/dist/components/core/index.d.ts +1 -0
  12. package/dist/components/core/index.js +1 -0
  13. package/dist/components/items/FileItem.svelte +28 -3
  14. package/dist/components/items/FolderItem.svelte +21 -2
  15. package/dist/components/modals/MoveDialog.svelte +16 -11
  16. package/dist/components/modals/MoveDialog.svelte.d.ts +1 -0
  17. package/dist/components/modals/SearchModal.svelte +4 -44
  18. package/dist/components/ui/DropdownMenu.svelte +7 -3
  19. package/dist/components/ui/DropdownMenu.svelte.d.ts +1 -0
  20. package/dist/i18n/messages.d.ts +7 -1
  21. package/dist/i18n/messages.js +7 -1
  22. package/dist/utils/fileNames.d.ts +9 -0
  23. package/dist/utils/fileNames.js +19 -0
  24. package/dist/utils/libraryTree.d.ts +22 -0
  25. package/dist/utils/libraryTree.js +177 -0
  26. package/dist/utils/searchItems.d.ts +27 -0
  27. package/dist/utils/searchItems.js +77 -0
  28. package/dist/utils/uploadProgressMath.d.ts +29 -0
  29. package/dist/utils/uploadProgressMath.js +66 -0
  30. package/dist/utils/uploadResponseMapping.d.ts +11 -0
  31. package/dist/utils/uploadResponseMapping.js +51 -0
  32. package/dist/utils/uploadUiHelpers.d.ts +28 -0
  33. package/dist/utils/uploadUiHelpers.js +49 -0
  34. package/dist/utils/userUploadsStorage.d.ts +2 -2
  35. package/dist/utils/userUploadsStorage.js +25 -17
  36. package/dist/utils/widgeticTusUpload.d.ts +2 -0
  37. package/dist/utils/widgeticTusUpload.js +4 -20
  38. package/dist/utils/widgeticUpload.js +3 -66
  39. package/dist/utils/xhrMultipartUpload.d.ts +16 -0
  40. package/dist/utils/xhrMultipartUpload.js +125 -0
  41. package/package.json +3 -3
@@ -36,7 +36,10 @@
36
36
  import { UPLOAD_ERROR_KEYS } from '../../i18n/messages';
37
37
  import { kindWord } from '../../i18n/text';
38
38
  import type { Translate } from '../../i18n/context';
39
- import { translateEnglish } from '../../i18n/context';
39
+ import { translateEnglish } from '../../i18n/context';
40
+ import type { ThroughputSample } from '../../utils/uploadProgressMath';
41
+ import { overallBytesProgressRatio, ratioToPercent, UPLOAD_UI_PROGRESS_THROTTLE_MS } from '../../utils/uploadProgressMath';
42
+ import { buildActiveRowStatusText, formatUploadPercent, type UploadPhase, updateThroughputEstimateState } from '../../utils/uploadUiHelpers';
40
43
 
41
44
  // The host's media library, when the File Browser was given one. It then stores the files, instead of the
42
45
  // Widgetic upload settings.
@@ -78,14 +81,24 @@ import { translateEnglish } from '../../i18n/context';
78
81
  type UploadItem = {
79
82
  id: string;
80
83
  file: File;
81
- progress: number;
84
+ /** Bar + summary (0–100); may sit at 100 while phase is finishing */
85
+ displayProgress: number;
86
+ bytesUploaded: number;
87
+ bytesTotal: number;
88
+ /** Set only while status is uploading */
89
+ uploadPhase?: 'starting' | 'uploading' | 'finishing';
82
90
  status: 'uploading' | 'complete' | 'failed';
83
91
  previewUrl: string;
84
92
  errorMessage?: string;
85
- timeRemaining?: string;
93
+ /** Estimated seconds left; internal (shown via buildActiveRowStatusText) */
94
+ timeRemainingSeconds?: number;
95
+ throughputBps?: number;
96
+ lastThroughputSample?: ThroughputSample;
97
+ firstThroughputSampleAt?: number;
98
+ lastUiTick?: number;
86
99
  controller?: AbortController;
87
100
  };
88
-
101
+
89
102
  let uploadItems: UploadItem[] = [];
90
103
  let uploadInProgress = false;
91
104
 
@@ -99,8 +112,20 @@ import { translateEnglish } from '../../i18n/context';
99
112
  $: allowedTypesDisplayText = kindsText(filter, allowedKinds, $t);
100
113
  // With the "all" filter every kind of file is taken, and the sentences of the dropzone do not name a kind ("Upload files").
101
114
  $: acceptsAnyKind = filter === 'all';
102
- // Calculate overall progress for all uploads
103
- $: overallProgress = calculateOverallProgress(uploadItems);
115
+ /** Byte-weighted overall progress for the panel bar (0–100). */
116
+ $: overallProgress = ratioToPercent(
117
+ overallBytesProgressRatio({
118
+ items: uploadItems.map((it) => ({
119
+ status: it.status,
120
+ bytesTotal: it.bytesTotal > 0 ? it.bytesTotal : it.file.size,
121
+ bytesUploaded:
122
+ it.status === 'complete'
123
+ ? (it.bytesTotal > 0 ? it.bytesTotal : it.file.size)
124
+ : Math.max(0, it.bytesUploaded),
125
+ })),
126
+ includeComplete: true,
127
+ }),
128
+ );
104
129
 
105
130
  $: dropzoneState = (
106
131
  dragActive && dragInvalid
@@ -112,7 +137,7 @@ import { translateEnglish } from '../../i18n/context';
112
137
 
113
138
  $: completedUploadCount = uploadItems.filter((item) => item.status === 'complete').length;
114
139
  $: failedUploadCount = uploadItems.filter((item) => item.status === 'failed').length;
115
- $: activeUploadCount = uploadItems.filter((item) => item.status === 'uploading').length;
140
+ $: uploadingCount = uploadItems.filter((item) => item.status === 'uploading').length;
116
141
  $: totalUploadCount = uploadItems.length;
117
142
  $: isBatchUpload = totalUploadCount > 1;
118
143
 
@@ -124,17 +149,26 @@ import { translateEnglish } from '../../i18n/context';
124
149
  const uploadErrorKeyLiterals = ['libraryError.uploadFailed', 'upload.networkError', 'action.preview'] as const;
125
150
  void uploadErrorKeyLiterals;
126
151
 
152
+ function displayPercent01(item: UploadItem): number {
153
+ const total = item.bytesTotal > 0 ? item.bytesTotal : item.file.size;
154
+ if (total <= 0) return 0;
155
+ return Math.min(1, Math.max(0, item.bytesUploaded / total));
156
+ }
157
+
127
158
  function statusTextForItem(item: UploadItem): string {
128
159
  if (item.status === 'complete') return $t('upload.complete');
129
160
  if (item.status === 'failed') return item.errorMessage || $t('upload.failed');
130
- const size = formatFileSize(item.file.size, $t, $locale);
131
- if (item.timeRemaining) {
132
- return $t('upload.rowMeta', {
133
- size,
134
- detail: $t('upload.timeLeft', { time: item.timeRemaining })
135
- });
136
- }
137
- return size;
161
+ const phase = item.uploadPhase ?? 'uploading';
162
+ if (phase === 'starting') return $t('upload.rowStarting');
163
+ return buildActiveRowStatusText({
164
+ translate: $t,
165
+ locale: $locale,
166
+ phase: phase as UploadPhase,
167
+ displayPercent01: displayPercent01(item),
168
+ bytesUploaded: item.bytesUploaded,
169
+ bytesTotal: item.bytesTotal > 0 ? item.bytesTotal : item.file.size,
170
+ secondsLeft: item.timeRemainingSeconds,
171
+ });
138
172
  }
139
173
 
140
174
  function fileThumbForItem(item: UploadItem) {
@@ -150,16 +184,17 @@ import { translateEnglish } from '../../i18n/context';
150
184
  id: item.id,
151
185
  fileName: item.file.name,
152
186
  file: fileThumbForItem(item),
153
- progress: item.progress,
187
+ progress: item.displayProgress,
188
+ progressIndeterminate: item.uploadPhase === 'finishing',
154
189
  status: item.status,
155
190
  statusText: statusTextForItem(item),
156
- errorMessage: item.errorMessage
191
+ errorMessage: item.errorMessage,
157
192
  })
158
193
  );
159
194
 
160
195
  $: panelSummaryScope = (isBatchUpload ? 'batch' : 'single') satisfies UploadRowScope;
161
196
  $: panelSummaryState = (
162
- activeUploadCount > 0
197
+ uploadingCount > 0
163
198
  ? 'uploading'
164
199
  : failedUploadCount === totalUploadCount
165
200
  ? 'failed'
@@ -173,48 +208,56 @@ import { translateEnglish } from '../../i18n/context';
173
208
  $: panelSummaryName = isBatchUpload ? '' : uploadItems[0]?.file.name ?? '';
174
209
 
175
210
  $: panelSummaryStatus = isBatchUpload
176
- ? failedUploadCount > 0 && activeUploadCount === 0
211
+ ? failedUploadCount > 0 && uploadingCount === 0
177
212
  ? joinMeta(
178
213
  $t('upload.progress', { done: completedUploadCount, total: totalUploadCount }),
179
214
  $t('upload.failedCount', { count: failedUploadCount })
180
215
  )
181
- : $t('upload.progress', { done: completedUploadCount, total: totalUploadCount })
216
+ : uploadingCount > 0
217
+ ? $t('upload.batchSummaryActive', {
218
+ total: totalUploadCount,
219
+ percent: formatUploadPercent($locale, overallProgress / 100),
220
+ })
221
+ : $t('upload.progress', { done: completedUploadCount, total: totalUploadCount })
182
222
  : uploadItems[0]
183
223
  ? statusTextForItem(uploadItems[0])
184
224
  : '';
185
225
 
186
226
  $: panelProgressTone = (failedUploadCount > 0 ? 'destructive' : 'default') as 'default' | 'destructive';
187
227
  $: panelProgressDone = completedUploadCount === totalUploadCount && failedUploadCount === 0;
228
+ $: panelProgressIndeterminate =
229
+ !panelProgressDone &&
230
+ uploadItems.some((i) => i.status === 'uploading' && i.uploadPhase === 'finishing');
188
231
 
189
232
  $: panelFooterDestructive = failedUploadCount > 0;
190
233
  $: panelFooterAction =
191
- failedUploadCount > 0 && activeUploadCount === 0 && completedUploadCount < totalUploadCount;
234
+ failedUploadCount > 0 && uploadingCount === 0 && completedUploadCount < totalUploadCount;
192
235
 
193
236
  $: panelFooterText = (() => {
194
237
  if (totalUploadCount === 0) return $t('upload.uploading');
195
238
  if (panelFooterAction) return $t('upload.retryFailed');
196
- if (totalUploadCount === 1 && activeUploadCount === 1) return $t('upload.uploading');
239
+ if (totalUploadCount === 1 && uploadingCount === 1) return $t('upload.uploading');
197
240
  if (totalUploadCount === 1 && failedUploadCount === 1) return $t('upload.retry');
198
241
  if (totalUploadCount === 1 && completedUploadCount === 1) return $t('upload.complete');
199
- if (activeUploadCount > 0 && failedUploadCount > 0) {
242
+ if (uploadingCount > 0 && failedUploadCount > 0) {
200
243
  return joinMeta(
201
244
  $t('upload.uploadingProgress', {
202
- done: completedUploadCount + activeUploadCount,
203
- total: totalUploadCount
245
+ done: completedUploadCount + uploadingCount,
246
+ total: totalUploadCount,
204
247
  }),
205
- $t('upload.failedCount', { count: failedUploadCount })
248
+ $t('upload.failedCount', { count: failedUploadCount }),
206
249
  );
207
250
  }
208
- if (activeUploadCount > 0) {
251
+ if (uploadingCount > 0) {
209
252
  return $t('upload.uploadingProgress', {
210
- done: completedUploadCount + activeUploadCount,
211
- total: totalUploadCount
253
+ done: completedUploadCount + uploadingCount,
254
+ total: totalUploadCount,
212
255
  });
213
256
  }
214
257
  if (failedUploadCount > 0 && completedUploadCount > 0) {
215
258
  return joinMeta(
216
259
  $t('upload.completeCount', { done: completedUploadCount, total: totalUploadCount }),
217
- $t('upload.failedCount', { count: failedUploadCount })
260
+ $t('upload.failedCount', { count: failedUploadCount }),
218
261
  );
219
262
  }
220
263
  if (completedUploadCount === totalUploadCount) {
@@ -243,26 +286,6 @@ import { translateEnglish } from '../../i18n/context';
243
286
  }
244
287
  }*/
245
288
 
246
- /**
247
- * Calculates the overall progress of all uploads
248
- * @param items Array of upload items
249
- * @returns Progress percentage (0-100)
250
- */
251
- function calculateOverallProgress(items: UploadItem[]): number {
252
- if (items.length === 0) return 0;
253
-
254
- const totalItems = items.length;
255
- const completedItems = items.filter(item => item.status === 'complete').length;
256
- const failedItems = items.filter(item => item.status === 'failed').length;
257
- const inProgressItems = items.filter(item => item.status === 'uploading');
258
-
259
- // Calculate progress percentage
260
- const completedPercentage = (completedItems / totalItems) * 100;
261
- const inProgressPercentage = inProgressItems.reduce((sum, item) => sum + (item.progress / totalItems), 0);
262
-
263
- return Math.round(completedPercentage + inProgressPercentage);
264
- }
265
-
266
289
  function isFileTypeAllowed(file: File): boolean {
267
290
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
268
291
  return acceptTypes.includes(fileExtension);
@@ -437,22 +460,48 @@ import { translateEnglish } from '../../i18n/context';
437
460
  }
438
461
 
439
462
  /**
440
- * Estimates the time remaining for an upload
441
- * @param file File being uploaded
442
- * @param progress Current progress (0-100)
443
- * @param startTime Time when upload started
444
- * @returns Formatted time remaining string
463
+ * Apply byte-accurate progress and optionally refresh the throttled bar (≤ ~10 Hz).
445
464
  */
446
- function estimateTimeRemaining(file: File, progress: number, startTime: number): string {
447
- if (progress === 0) return '';
448
-
449
- const elapsedMs = Date.now() - startTime;
450
- const totalEstimatedMs = (elapsedMs / progress) * 100;
451
- const remainingMs = totalEstimatedMs - elapsedMs;
452
-
453
- if (remainingMs < 1000) return $t('upload.time.lessThanSecond');
454
- if (remainingMs < 60000) return $t('upload.time.seconds', { count: Math.round(remainingMs / 1000) });
455
- return $t('upload.time.minutes', { count: Math.round(remainingMs / 60000) });
465
+ function applyProgressUpdate(
466
+ uploadId: string,
467
+ args: {
468
+ phase: NonNullable<UploadItem['uploadPhase']>;
469
+ bytesUploaded: number;
470
+ bytesTotal: number;
471
+ /** Rounded 0–100 from the transport layer (or derived from bytes). */
472
+ rawPercent: number;
473
+ secondsLeft?: number;
474
+ now: number;
475
+ forcePaint?: boolean;
476
+ },
477
+ ) {
478
+ const item = uploadItems.find((i) => i.id === uploadId);
479
+ if (!item || item.status !== 'uploading') return;
480
+
481
+ const lastTick = item.lastUiTick ?? 0;
482
+ const shouldPaint =
483
+ args.forcePaint ||
484
+ args.now - lastTick >= UPLOAD_UI_PROGRESS_THROTTLE_MS ||
485
+ args.phase === 'finishing' ||
486
+ args.rawPercent >= 100;
487
+
488
+ const displayProgress =
489
+ args.phase === 'finishing'
490
+ ? 100
491
+ : Math.min(100, Math.max(0, Math.round(args.rawPercent)));
492
+
493
+ uploadItems = uploadItems.map((it) =>
494
+ it.id === uploadId
495
+ ? {
496
+ ...it,
497
+ uploadPhase: args.phase,
498
+ bytesUploaded: args.bytesUploaded,
499
+ bytesTotal: args.bytesTotal,
500
+ timeRemainingSeconds: args.secondsLeft,
501
+ ...(shouldPaint ? { displayProgress, lastUiTick: args.now } : {}),
502
+ }
503
+ : it,
504
+ );
456
505
  }
457
506
 
458
507
  /**
@@ -520,25 +569,32 @@ import { translateEnglish } from '../../i18n/context';
520
569
 
521
570
  // Create a unique ID for this upload
522
571
  const uploadId = `upload_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
523
- const startTime = Date.now();
524
572
  const previewUrl = createPreviewUrl(normalizedFile);
525
573
  const controller = new AbortController();
526
-
574
+ const uploadConfig = get(fileBrowserUploadConfig);
575
+ const bytesTotal = Math.max(1, normalizedFile.size);
576
+
527
577
  // Create an upload item
528
578
  const uploadItem: UploadItem = {
529
579
  id: uploadId,
530
580
  file: normalizedFile,
531
- progress: 0,
581
+ displayProgress: 0,
582
+ bytesUploaded: 0,
583
+ bytesTotal,
584
+ uploadPhase: 'starting',
532
585
  status: 'uploading',
533
586
  previewUrl,
534
587
  controller,
535
- timeRemaining: $t('upload.time.calculating')
536
588
  };
537
-
589
+
538
590
  // Add to the list of uploads
539
591
  uploadItems = [...uploadItems, uploadItem];
540
592
  uploadInProgress = true;
541
-
593
+
594
+ // The folder the visitor is in when the upload starts: the file belongs there even when the visitor opens
595
+ // another folder before the upload is done (a copy, `currentPath` changes with the navigation)
596
+ const folderPathIds = [...currentPath];
597
+
542
598
  try {
543
599
  const path = currentPath.join('/');
544
600
  const formData = new FormData();
@@ -546,30 +602,56 @@ import { translateEnglish } from '../../i18n/context';
546
602
  formData.append('path', path);
547
603
  formData.append('folderId', currentFolderId);
548
604
 
549
- const uploadConfig = get(fileBrowserUploadConfig);
550
605
  let response: { success: boolean; file?: any; error?: string };
551
606
 
552
607
  if (library) {
553
- // The host's media library stores the file. It reports progress as a number from 0 to 100, which is
554
- // clamped here because the number comes from the host's code.
608
+ // The host's media library stores the file. It reports progress as a number from 0 to 100.
555
609
  if (!library.upload) {
556
610
  throw new MediaLibraryError('NOT_SUPPORTED', 'This media library does not accept uploads', { messageKey: 'libraryError.uploadNotAllowed' });
557
611
  }
612
+ applyProgressUpdate(uploadId, {
613
+ phase: 'starting',
614
+ bytesUploaded: 0,
615
+ bytesTotal,
616
+ rawPercent: 0,
617
+ now: Date.now(),
618
+ forcePaint: true,
619
+ });
558
620
  const storedFile = await library.upload({
559
621
  file: normalizedFile,
560
622
  signal: controller.signal,
561
623
  onProgress: (reportedPercentage) => {
562
624
  const percentage = Number.isFinite(reportedPercentage) ? Math.min(100, Math.max(0, reportedPercentage)) : 0;
563
- const timeRemaining = estimateTimeRemaining(normalizedFile, percentage, startTime);
564
- uploadItems = uploadItems.map((item) =>
565
- item.id === uploadId
566
- ? { ...item, progress: percentage, timeRemaining }
567
- : item,
568
- );
625
+ const now = Date.now();
626
+ const bytesUploaded = (percentage / 100) * bytesTotal;
627
+ const cur = uploadItems.find((i) => i.id === uploadId);
628
+ const est = updateThroughputEstimateState({
629
+ bytesUploaded,
630
+ bytesTotal,
631
+ now,
632
+ prevSample: cur?.lastThroughputSample,
633
+ throughputBps: cur?.throughputBps,
634
+ firstSampleAt: cur?.firstThroughputSampleAt,
635
+ });
636
+ uploadItems = uploadItems.map((it) => {
637
+ if (it.id !== uploadId) return it;
638
+ const lastTick = it.lastUiTick ?? 0;
639
+ const shouldPaint = now - lastTick >= UPLOAD_UI_PROGRESS_THROTTLE_MS || percentage >= 100;
640
+ const displayProgress = Math.min(100, Math.max(0, Math.round(percentage)));
641
+ return {
642
+ ...it,
643
+ uploadPhase: percentage >= 100 ? 'finishing' : 'uploading',
644
+ bytesUploaded,
645
+ bytesTotal,
646
+ timeRemainingSeconds: est.secondsLeft,
647
+ lastThroughputSample: est.nextSample,
648
+ throughputBps: est.throughputBps,
649
+ firstThroughputSampleAt: est.firstSampleAt,
650
+ ...(shouldPaint ? { displayProgress, lastUiTick: now } : {}),
651
+ };
652
+ });
569
653
  },
570
654
  });
571
- // A library that finishes after the visitor cancelled (or after the File Browser closed) has stored the
572
- // file, but this screen no longer waits for it: it is not added to the list.
573
655
  if (controller.signal.aborted) {
574
656
  throw new MediaLibraryError('ABORTED', 'The upload was cancelled');
575
657
  }
@@ -578,15 +660,60 @@ import { translateEnglish } from '../../i18n/context';
578
660
  if (showLogs) {
579
661
  // console.log('[FileUploader] Widgetic upload:', file.name, uploadConfig.contextType);
580
662
  }
663
+ applyProgressUpdate(uploadId, {
664
+ phase: 'starting',
665
+ bytesUploaded: 0,
666
+ bytesTotal,
667
+ rawPercent: 0,
668
+ now: Date.now(),
669
+ forcePaint: true,
670
+ });
671
+
581
672
  response = await uploadToWidgeticApi(normalizedFile, uploadConfig, {
582
673
  abortSignal: controller.signal,
583
- onProgress: ({ percentage }) => {
584
- const timeRemaining = estimateTimeRemaining(normalizedFile, percentage, startTime);
585
- uploadItems = uploadItems.map((item) =>
586
- item.id === uploadId
587
- ? { ...item, progress: percentage, timeRemaining }
588
- : item,
589
- );
674
+ onProgress: ({ bytesUploaded, bytesTotal: reportedTotal, percentage }) => {
675
+ const total = reportedTotal > 0 ? reportedTotal : bytesTotal;
676
+ const now = Date.now();
677
+ const loaded = Math.min(total, Math.max(0, bytesUploaded));
678
+ const cur = uploadItems.find((i) => i.id === uploadId);
679
+ const est = updateThroughputEstimateState({
680
+ bytesUploaded: loaded,
681
+ bytesTotal: total,
682
+ now,
683
+ prevSample: cur?.lastThroughputSample,
684
+ throughputBps: cur?.throughputBps,
685
+ firstSampleAt: cur?.firstThroughputSampleAt,
686
+ });
687
+ uploadItems = uploadItems.map((it) => {
688
+ if (it.id !== uploadId) return it;
689
+ const lastTick = it.lastUiTick ?? 0;
690
+ const shouldPaint =
691
+ now - lastTick >= UPLOAD_UI_PROGRESS_THROTTLE_MS || percentage >= 100;
692
+ const displayProgress = Math.min(100, Math.max(0, Math.round(percentage)));
693
+ return {
694
+ ...it,
695
+ uploadPhase: 'uploading',
696
+ bytesUploaded: loaded,
697
+ bytesTotal: total,
698
+ timeRemainingSeconds: est.secondsLeft,
699
+ lastThroughputSample: est.nextSample,
700
+ throughputBps: est.throughputBps,
701
+ firstThroughputSampleAt: est.firstSampleAt,
702
+ ...(shouldPaint ? { displayProgress, lastUiTick: now } : {}),
703
+ };
704
+ });
705
+ },
706
+ onAwaitingResponse: () => {
707
+ const cur = uploadItems.find((i) => i.id === uploadId);
708
+ const total = cur?.bytesTotal && cur.bytesTotal > 0 ? cur.bytesTotal : bytesTotal;
709
+ applyProgressUpdate(uploadId, {
710
+ phase: 'finishing',
711
+ bytesUploaded: total,
712
+ bytesTotal: total,
713
+ rawPercent: 100,
714
+ now: Date.now(),
715
+ forcePaint: true,
716
+ });
590
717
  },
591
718
  });
592
719
  } else {
@@ -594,17 +721,48 @@ import { translateEnglish } from '../../i18n/context';
594
721
  // console.log(`[FileUploader] Mock upload ${file.name} to path: ${path}, folder: ${currentFolderId}`);
595
722
  }
596
723
 
724
+ applyProgressUpdate(uploadId, {
725
+ phase: 'starting',
726
+ bytesUploaded: 0,
727
+ bytesTotal,
728
+ rawPercent: 0,
729
+ now: Date.now(),
730
+ forcePaint: true,
731
+ });
732
+
597
733
  const progressInterval = setInterval(() => {
598
734
  const currentItem = uploadItems.find((item) => item.id === uploadId);
599
735
  if (!currentItem || currentItem.status !== 'uploading') {
600
736
  clearInterval(progressInterval);
601
737
  return;
602
738
  }
603
- const newProgress = Math.min(95, currentItem.progress + Math.random() * 10);
604
- const timeRemaining = estimateTimeRemaining(file, newProgress, startTime);
605
- uploadItems = uploadItems.map((item) =>
606
- item.id === uploadId ? { ...item, progress: newProgress, timeRemaining } : item,
607
- );
739
+ const newPercent = Math.min(95, currentItem.displayProgress + Math.random() * 10);
740
+ const bytesUploaded = (newPercent / 100) * bytesTotal;
741
+ const now = Date.now();
742
+ const est = updateThroughputEstimateState({
743
+ bytesUploaded,
744
+ bytesTotal,
745
+ now,
746
+ prevSample: currentItem.lastThroughputSample,
747
+ throughputBps: currentItem.throughputBps,
748
+ firstSampleAt: currentItem.firstThroughputSampleAt,
749
+ });
750
+ uploadItems = uploadItems.map((it) => {
751
+ if (it.id !== uploadId) return it;
752
+ const lastTick = it.lastUiTick ?? 0;
753
+ const shouldPaint = now - lastTick >= UPLOAD_UI_PROGRESS_THROTTLE_MS || newPercent >= 95;
754
+ return {
755
+ ...it,
756
+ uploadPhase: 'uploading',
757
+ bytesUploaded,
758
+ bytesTotal,
759
+ timeRemainingSeconds: est.secondsLeft,
760
+ lastThroughputSample: est.nextSample,
761
+ throughputBps: est.throughputBps,
762
+ firstThroughputSampleAt: est.firstSampleAt,
763
+ ...(shouldPaint ? { displayProgress: Math.round(newPercent), lastUiTick: now } : {}),
764
+ };
765
+ });
608
766
  }, 500);
609
767
 
610
768
  const uploadTime = Math.random() * 3000 + 2000;
@@ -620,52 +778,66 @@ import { translateEnglish } from '../../i18n/context';
620
778
  }, uploadTime);
621
779
  });
622
780
 
781
+ applyProgressUpdate(uploadId, {
782
+ phase: 'finishing',
783
+ bytesUploaded: bytesTotal,
784
+ bytesTotal,
785
+ rawPercent: 100,
786
+ now: Date.now(),
787
+ forcePaint: true,
788
+ });
789
+
623
790
  response = await mockUploadAPI(formData);
624
791
  }
625
-
792
+
626
793
  if (response.success) {
627
794
  const cdnUrl = response.file?.url;
628
795
  // Swap blob preview for CDN URL after upload so preview pane is not stuck black
629
796
  if (cdnUrl && previewUrl.startsWith('blob:')) {
630
797
  URL.revokeObjectURL(previewUrl);
631
798
  }
632
- uploadItems = uploadItems.map(item =>
633
- item.id === uploadId
634
- ? {
635
- ...item,
636
- progress: 100,
637
- status: 'complete',
638
- timeRemaining: '',
799
+ uploadItems = uploadItems.map((item) =>
800
+ item.id === uploadId
801
+ ? {
802
+ ...item,
803
+ displayProgress: 100,
804
+ bytesUploaded: item.bytesTotal,
805
+ status: 'complete',
806
+ uploadPhase: undefined,
807
+ timeRemainingSeconds: undefined,
639
808
  previewUrl: cdnUrl || item.previewUrl,
640
- }
641
- : item
809
+ }
810
+ : item,
642
811
  );
643
- dispatch('fileUploaded', {
812
+ dispatch('fileUploaded', {
644
813
  file: response.file,
645
814
  path,
815
+ // The ids of the folders that lead to the folder the upload was started in (`path` joins them with "/")
816
+ pathIds: folderPathIds,
646
817
  folderId: currentFolderId,
647
- success: true
818
+ success: true,
648
819
  });
649
820
 
650
821
  // Close progress overlay so the file grid is visible again (black dim was the upload overlay)
651
822
  scheduleUploadDrawerDismiss();
652
823
  } else {
653
824
  // Update the upload item to failed
654
- uploadItems = uploadItems.map(item =>
655
- item.id === uploadId
656
- ? {
657
- ...item,
658
- progress: 0,
659
- status: 'failed',
825
+ uploadItems = uploadItems.map((item) =>
826
+ item.id === uploadId
827
+ ? {
828
+ ...item,
829
+ displayProgress: 0,
830
+ status: 'failed',
831
+ uploadPhase: undefined,
660
832
  errorMessage: response.error || $t('libraryError.uploadFailed'),
661
- timeRemaining: ''
662
- }
663
- : item
833
+ timeRemainingSeconds: undefined,
834
+ }
835
+ : item,
664
836
  );
665
-
666
- dispatch('error', {
837
+
838
+ dispatch('error', {
667
839
  message: response.error || 'Server error',
668
- file: file.name
840
+ file: file.name,
669
841
  });
670
842
  }
671
843
  } catch (error) {
@@ -677,36 +849,37 @@ import { translateEnglish } from '../../i18n/context';
677
849
  }
678
850
 
679
851
  console.error('Upload failed:', error);
680
-
852
+
681
853
  // Update the upload item with error status
682
- uploadItems = uploadItems.map(item =>
683
- item.id === uploadItem.id
684
- ? {
685
- ...item,
686
- status: 'failed',
687
- progress: 0,
854
+ uploadItems = uploadItems.map((item) =>
855
+ item.id === uploadId
856
+ ? {
857
+ ...item,
858
+ status: 'failed',
859
+ displayProgress: 0,
860
+ uploadPhase: undefined,
688
861
  errorMessage: messageForVisitor(
689
862
  toMediaLibraryError(error, $t(UPLOAD_ERROR_KEYS.libraryFailed), UPLOAD_ERROR_KEYS.libraryFailed),
690
863
  $t,
691
- 'upload.unknownError'
864
+ 'upload.unknownError',
692
865
  ),
693
- }
694
- : item
866
+ }
867
+ : item,
695
868
  );
696
-
697
- dispatch('error', {
869
+
870
+ dispatch('error', {
698
871
  message: error instanceof Error ? error.message : 'Unknown error',
699
872
  // Which kind of failure it was, when a media library said (so the host can tell "not allowed" from "offline")
700
873
  code: error instanceof MediaLibraryError ? error.code : undefined,
701
- file: file.name
874
+ file: file.name,
702
875
  });
703
876
  } finally {
704
877
  // Check if all uploads are complete
705
- const hasActiveUploads = uploadItems.some(item => item.status === 'uploading');
878
+ const hasActiveUploads = uploadItems.some((item) => item.status === 'uploading');
706
879
  if (!hasActiveUploads) {
707
880
  uploading = false;
708
881
  }
709
-
882
+
710
883
  if (fileInput) fileInput.value = '';
711
884
  }
712
885
  }
@@ -982,6 +1155,7 @@ import { translateEnglish } from '../../i18n/context';
982
1155
  summaryName={panelSummaryName}
983
1156
  summaryStatus={panelSummaryStatus}
984
1157
  progressValue={overallProgress}
1158
+ progressIndeterminate={panelProgressIndeterminate}
985
1159
  progressTone={panelProgressTone}
986
1160
  progressDone={panelProgressDone}
987
1161
  footerText={panelFooterText}
@@ -133,7 +133,7 @@
133
133
  side="bottom"
134
134
  align="end"
135
135
  sideOffset={6}
136
- class="selected-files-tooltip bg-inverse text-inverse-foreground text-caption z-[200000] rounded-lg px-2 py-1"
136
+ class="selected-files-tooltip bg-foreground text-background text-caption z-[200000] rounded-lg px-2 py-1"
137
137
  >
138
138
  {$t('selectedFiles.title')}
139
139
  </Tooltip.Content>