@widgetic/file-browser 0.5.31 → 0.5.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,9 +65,14 @@ pnpm link --global @widgetic/file-browser
65
65
 
66
66
  ## Using your own media library
67
67
 
68
- By default the File Browser shows the Widgetic account's uploads. A platform that already has a media library of its
69
- own (a CMS, an S3 bucket, a DAM) can hand the File Browser that library instead, as plain functions. The File Browser
70
- then lists, uploads, renames and deletes through those functions and never talks to Widgetic.
68
+ By default the File Browser shows the Widgetic account's uploads. The path above them reads `Files / Uploads`.
69
+ An image or video preview opens as a 100px card and eases to the picture. The video controls are the width of that
70
+ picture, with space on either side of it. Filter and sort stay on one line; the search field gives up width when the
71
+ container is narrow. A file over 10 MB goes up in pieces unless `allowResumableUploads` is false.
72
+
73
+ A platform that already has a media library of its own (a CMS, an S3 bucket, a DAM) can hand the File Browser that
74
+ library instead, as plain functions. The File Browser then lists, uploads, renames and deletes through those functions
75
+ and never talks to Widgetic.
71
76
 
72
77
  ```svelte
73
78
  <script lang="ts">
@@ -75,7 +80,7 @@ then lists, uploads, renames and deletes through those functions and never talks
75
80
 
76
81
  const mediaLibrary: MediaLibraryProvider = {
77
82
  id: 'acme-assets',
78
- label: 'Acme assets', // the title above the files. Default: "My uploads"
83
+ label: 'Acme assets', // the title above the files. Default: "Uploads"
79
84
 
80
85
  // Required. One page of the library, newest files first.
81
86
  async list({ cursor, limit, signal }) {
@@ -21,8 +21,8 @@
21
21
  import '@widgetic/design-system/styles';
22
22
 
23
23
  // Design system components
24
- import { Button, DebugGrid, WScrollArea, EmptyState, ActionModal, SearchInput } from '@widgetic/design-system/components';
25
- import {IconSearch, IconAdjustmentsHorizontal, IconCheck } from '@widgetic/design-system/icons';
24
+ import { Button, DebugGrid, WScrollArea, EmptyState, ActionModal, SearchInput, DropdownMenu, Tooltip } from '@widgetic/design-system/components';
25
+ import {IconSearch, IconCheck } from '@widgetic/design-system/icons';
26
26
 
27
27
  // LOCAL COMPONENT IMPORTS
28
28
  import { NewFolderButton } from '../modals';
@@ -2436,6 +2436,32 @@
2436
2436
 
2437
2437
  // Add these state variables
2438
2438
  let filterDropdownOpen = false;
2439
+ let sortDropdownOpen = false;
2440
+ // Remounting the other menu closes it. Binding `open` kept both shut.
2441
+ let filterMenuKey = 0;
2442
+ let sortMenuKey = 0;
2443
+
2444
+ function setFilterMenuOpen(next: boolean) {
2445
+ filterDropdownOpen = next;
2446
+ if (next) sortMenuKey += 1;
2447
+ }
2448
+
2449
+ function setSortMenuOpen(next: boolean) {
2450
+ sortDropdownOpen = next;
2451
+ if (next) filterMenuKey += 1;
2452
+ }
2453
+
2454
+ const sortOptions = [
2455
+ { value: 'name', labelKey: 'sort.name' },
2456
+ { value: 'date', labelKey: 'sort.date' },
2457
+ { value: 'size', labelKey: 'sort.size' }
2458
+ ] as const;
2459
+
2460
+ $: widestFilterLabel = filterOptions.reduce((widest, option) => option.label.length > widest.length ? option.label : widest, '');
2461
+ $: widestSortLabel = sortOptions.reduce((widest, option) => {
2462
+ const label = $t(option.labelKey);
2463
+ return label.length > widest.length ? label : widest;
2464
+ }, '');
2439
2465
 
2440
2466
  // Replace the existing reactive statement for filter
2441
2467
  $: {
@@ -2676,9 +2702,9 @@ mainGridClass="app-main-grid"
2676
2702
  />
2677
2703
 
2678
2704
  <!-- FILE BROWSER CONTROLS -->
2679
- <div class="file-browser-controls flex justify-between items-center p-6 pb-0 h-[64px] widgetic-colors widgetic-radius widgetic-colors">
2680
- <!-- Search Bar - Always visible -->
2681
- <div class={`search-bar-container flex items-center ${(showFilters || showSorting) && mainContainerWidth > tabletBreakpoint ? 'w-2/3' : 'w-full'}`}>
2705
+ <div class="file-browser-controls flex flex-nowrap items-center gap-3 p-6 pb-0 h-[64px] widgetic-colors widgetic-radius widgetic-colors">
2706
+ <!-- Search Bar - Always visible. It gives up width so filter and sort stay on one line. -->
2707
+ <div class="search-bar-container flex min-w-0 flex-1 items-center">
2682
2708
  <!-- svelte-ignore a11y_click_events_have_key_events -->
2683
2709
  <div onclick={handleSearch} class="w-full cursor-pointer">
2684
2710
  <SearchInput
@@ -2693,74 +2719,98 @@ mainGridClass="app-main-grid"
2693
2719
  </div>
2694
2720
  </div>
2695
2721
 
2696
- <!-- Controls - Only show if enabled and above tablet breakpoint -->
2697
- {#if (showFilters || showSorting) && mainContainerWidth > tabletBreakpoint}
2698
- <div class="controls-container flex items-center gap-4">
2722
+ <!-- Controls stay on narrow widths. The search field shrinks instead. -->
2723
+ {#if showFilters || showSorting}
2724
+ <div class="controls-container flex shrink-0 items-center gap-3 whitespace-nowrap">
2699
2725
 
2700
2726
  <!-- Filter Controls Container -->
2701
2727
  {#if showFilters}
2702
2728
  <div class="filter-controls-container flex items-center pointer-events-auto relative z-10 widgetic-colors widgetic-radius">
2703
- <!-- Filter Button -->
2704
- <button
2705
- class="filter-button group flex items-center gap-2 border-none bg-transparent py-2.5 rounded-small subtext text-[hsl(var(--grey5))] hover:text-[hsl(var(--grey7))] transition-colors duration-200"
2706
- onclick={(e) => {
2707
- e.stopPropagation();
2708
- filterDropdownOpen = !filterDropdownOpen;
2709
- }}
2710
- >
2711
- <span>{$t('filter.by', { type: $t(`filterName.${filter}`) })}</span>
2712
- <IconAdjustmentsHorizontal class="h-5 w-5 text-[hsl(var(--grey5))] ms-1 transition-colors duration-200 group-hover:text-[hsl(var(--grey7))]" />
2713
- </button>
2714
-
2715
- <!-- Filter Dropdown -->
2716
- {#if filterDropdownOpen}
2717
- <div
2718
- class="filter-dropdown absolute end-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none z-50"
2719
- role="menu"
2720
- aria-orientation="vertical"
2721
- aria-labelledby="filter-menu"
2729
+ {#key filterMenuKey}
2730
+ <DropdownMenu.Root onOpenChange={setFilterMenuOpen}>
2731
+ <DropdownMenu.Trigger
2732
+ class="filter-button group flex items-center gap-2 whitespace-nowrap border-none bg-transparent py-1 rounded-small subtext text-[hsl(var(--grey5))] hover:text-[hsl(var(--grey7))] transition-colors duration-200 focus:outline-none focus-visible:outline-none"
2722
2733
  >
2723
- <div class="filter-dropdown-list py-1" role="none">
2724
- {#each filterOptions as option}
2725
- <button
2726
- class="filter-dropdown-item flex items-center justify-between w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900"
2727
- role="menuitem"
2728
- onclick={() => {
2729
- handleFilterChange(option.value as FileFilterType);
2730
- }}
2731
- >
2732
- <span>{option.label}</span>
2733
- {#if filter === option.value}
2734
- <IconCheck class="h-4 w-4" />
2735
- {/if}
2736
- </button>
2737
- {/each}
2738
- </div>
2739
- </div>
2740
- {/if}
2734
+ <span class="whitespace-nowrap">{$t('filter.by', { type: '\u0001' }).split('\u0001')[0].trim()}</span>
2735
+ <span class="filter-value-chip inline-flex items-center gap-1 whitespace-nowrap rounded-small border border-[hsl(var(--grey3))] bg-white px-2 py-1 text-[hsl(var(--grey7))]">
2736
+ <span class="relative inline-grid">
2737
+ <span class="invisible col-start-1 row-start-1 whitespace-nowrap">{widestFilterLabel}</span>
2738
+ <span class="col-start-1 row-start-1 whitespace-nowrap">{$t(`filterOption.${filter}`)}</span>
2739
+ </span>
2740
+ <svg class="h-3 w-3 shrink-0" viewBox="0 0 12 12" aria-hidden="true"><path d="M2 4.5 L6 8.5 L10 4.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
2741
+ </span>
2742
+ </DropdownMenu.Trigger>
2743
+ <DropdownMenu.Content side="bottom" align="end" class="filter-dropdown !w-max !min-w-0 bg-white">
2744
+ {#each filterOptions as option}
2745
+ <DropdownMenu.Item
2746
+ class="filter-dropdown-item flex w-full items-center justify-between gap-3 bg-transparent data-highlighted:!bg-[hsl(var(--light-green))] data-highlighted:!text-[hsl(var(--grey7))] data-[highlighted]:!bg-[hsl(var(--light-green))] data-[highlighted]:!text-[hsl(var(--grey7))]"
2747
+ onclick={() => handleFilterChange(option.value as FileFilterType)}
2748
+ >
2749
+ <span>{option.label}</span>
2750
+ {#if filter === option.value}
2751
+ <IconCheck class="h-4 w-4 text-[hsl(var(--deep-forest-green))]" />
2752
+ {/if}
2753
+ </DropdownMenu.Item>
2754
+ {/each}
2755
+ </DropdownMenu.Content>
2756
+ </DropdownMenu.Root>
2757
+ {/key}
2741
2758
  </div>
2742
2759
  {/if}
2743
2760
 
2744
2761
  <!-- Sort Controls Container -->
2745
2762
  {#if showSorting}
2746
2763
  <div class="sort-controls-container flex items-center gap-2">
2747
- <select
2748
- class="bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm"
2749
- bind:value={$sortCriteria}
2750
- >
2751
- <option value="name">{$t('sort.name')}</option>
2752
- <option value="date">{$t('sort.date')}</option>
2753
- <option value="size">{$t('sort.size')}</option>
2754
- </select>
2764
+ {#key sortMenuKey}
2765
+ <DropdownMenu.Root onOpenChange={setSortMenuOpen}>
2766
+ <DropdownMenu.Trigger
2767
+ class="sort-button flex items-center gap-2 whitespace-nowrap border-none bg-transparent py-1 subtext text-[hsl(var(--grey5))] hover:text-[hsl(var(--grey7))] focus:outline-none focus-visible:outline-none"
2768
+ >
2769
+ <span class="whitespace-nowrap">{$t('sort.by')}</span>
2770
+ <span class="sort-value-chip inline-flex items-center gap-1 whitespace-nowrap rounded-small border border-[hsl(var(--grey3))] bg-white px-2 py-1 text-[hsl(var(--grey7))]">
2771
+ <span class="relative inline-grid">
2772
+ <span class="invisible col-start-1 row-start-1 whitespace-nowrap">{widestSortLabel}</span>
2773
+ <span class="col-start-1 row-start-1 whitespace-nowrap">{$t(`sort.${$sortCriteria}`)}</span>
2774
+ </span>
2775
+ <svg class="h-3 w-3 shrink-0" viewBox="0 0 12 12" aria-hidden="true"><path d="M2 4.5 L6 8.5 L10 4.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" /></svg>
2776
+ </span>
2777
+ </DropdownMenu.Trigger>
2778
+ <DropdownMenu.Content side="bottom" align="end" class="sort-dropdown !w-max !min-w-0 bg-white">
2779
+ {#each sortOptions as option}
2780
+ <DropdownMenu.Item
2781
+ class="sort-dropdown-item flex w-full items-center justify-between gap-3 bg-transparent data-highlighted:!bg-[hsl(var(--light-green))] data-highlighted:!text-[hsl(var(--grey7))] data-[highlighted]:!bg-[hsl(var(--light-green))] data-[highlighted]:!text-[hsl(var(--grey7))]"
2782
+ onclick={() => sortCriteria.set(option.value)}
2783
+ >
2784
+ <span>{$t(option.labelKey)}</span>
2785
+ {#if $sortCriteria === option.value}
2786
+ <IconCheck class="h-4 w-4 text-[hsl(var(--deep-forest-green))]" />
2787
+ {/if}
2788
+ </DropdownMenu.Item>
2789
+ {/each}
2790
+ </DropdownMenu.Content>
2791
+ </DropdownMenu.Root>
2792
+ {/key}
2755
2793
 
2756
2794
  <!-- Sort Direction Button -->
2757
- <Button
2758
- variant="ghost"
2759
- size="sm"
2760
- onclick={toggleSortDirection}
2761
- >
2762
- {$sortDirection === 'asc' ? '↑' : '↓'}
2763
- </Button>
2795
+ <Tooltip.Provider delayDuration={200}>
2796
+ <Tooltip.Root>
2797
+ <Tooltip.Trigger
2798
+ class="sort-order-button inline-flex h-9 items-center px-2 text-[hsl(var(--grey7))] focus:outline-none focus-visible:outline-none"
2799
+ onclick={toggleSortDirection}
2800
+ >
2801
+ {$sortDirection === 'asc' ? '↑' : '↓'}
2802
+ </Tooltip.Trigger>
2803
+ <Tooltip.Portal>
2804
+ <Tooltip.Content
2805
+ side="top"
2806
+ sideOffset={8}
2807
+ class="sort-order-tooltip !bg-[hsl(var(--deep-forest-green))] !text-white z-[99999] border-0"
2808
+ >
2809
+ {$sortDirection === 'asc' ? $t('sort.orderDescending') : $t('sort.orderAscending')}
2810
+ </Tooltip.Content>
2811
+ </Tooltip.Portal>
2812
+ </Tooltip.Root>
2813
+ </Tooltip.Provider>
2764
2814
  </div>
2765
2815
  {/if}
2766
2816
  </div>
@@ -27,7 +27,7 @@
27
27
  import { uploadToWidgeticApi } from '../../utils/widgeticUpload';
28
28
  import { getAssetUrl } from '../../utils/fileUtils';
29
29
  import { useMediaLibraryContext } from '../../mediaLibrary/context';
30
- import { MediaLibraryError, isCancellation } from '../../mediaLibrary/errors';
30
+ import { MediaLibraryError, isCancellation, toMediaLibraryError } from '../../mediaLibrary/errors';
31
31
  import { useI18n } from '../../i18n/context';
32
32
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
33
33
  import { messageForVisitor } from '../../i18n/errors';
@@ -539,7 +539,7 @@ import { translateEnglish } from '../../i18n/context';
539
539
  ...item,
540
540
  progress: 0,
541
541
  status: 'failed',
542
- errorMessage: response.error || 'Server error',
542
+ errorMessage: response.error || $t('libraryError.uploadFailed'),
543
543
  timeRemaining: ''
544
544
  }
545
545
  : item
@@ -567,7 +567,7 @@ import { translateEnglish } from '../../i18n/context';
567
567
  ...item,
568
568
  status: 'failed',
569
569
  progress: 0,
570
- errorMessage: messageForVisitor(error, $t, 'upload.unknownError'),
570
+ errorMessage: messageForVisitor(toMediaLibraryError(error, $t('libraryError.uploadFailed'), 'libraryError.uploadFailed'), $t, 'upload.unknownError'),
571
571
  }
572
572
  : item
573
573
  );
@@ -862,26 +862,22 @@ import { translateEnglish } from '../../i18n/context';
862
862
  >
863
863
  <!-- Add help icon with tooltip -->
864
864
  <div class="help-icon-container absolute {isSmallScreen ? 'top-2 end-2' : 'top-4 end-4'} z-10">
865
- <Tooltip.Provider>
866
- <Tooltip.Root open={showHelp}>
867
- <Tooltip.Trigger class="focus:outline-none focus-visible:outline-none inline-block">
868
- <div
869
- class="flex items-center justify-center w-5 h-5 cursor-pointer transition-colors focus:outline-none focus-visible:outline-none"
870
- onmouseenter={handleMouseEnter}
871
- onmousemove={handleMouseMove}
872
- onmouseleave={handleMouseLeave}
873
- >
865
+ <Tooltip.Provider delayDuration={200}>
866
+ <Tooltip.Root>
867
+ <Tooltip.Trigger class="help-tooltip-trigger focus:outline-none focus-visible:outline-none inline-block">
868
+ <div class="flex items-center justify-center w-5 h-5 cursor-pointer transition-colors focus:outline-none focus-visible:outline-none">
874
869
  <IconHelp class="w-5 h-5 text-[hsl(var(--grey3))] hover:text-[hsl(var(--deep-forest-green))] transition-colors" />
875
870
  </div>
876
871
  </Tooltip.Trigger>
877
- <Tooltip.Content
878
- side={/* rtl-ok: the tooltip is put where the pointer is, by the style below */ 'left'}
879
- sideOffset={5}
880
- class="bg-[hsl(var(--dark))] text-white z-[99999] overflow-hidden rounded-md px-3 py-1.5 shadow-md max-w-[250px] whitespace-normal break-words"
881
- style="position: fixed; left: {mouseX - 20}px; top: {mouseY}px; /* rtl-ok: put where the pointer is, measured from the left edge of the page */"
882
- >
883
- <p class="caption text-white whitespace-pre-line">{tooltipTypesText}</p>
884
- </Tooltip.Content>
872
+ <Tooltip.Portal>
873
+ <Tooltip.Content
874
+ side="top"
875
+ sideOffset={8}
876
+ class="help-tooltip !bg-[hsl(var(--deep-forest-green))] !text-white z-[99999] overflow-hidden rounded-md px-3 py-1.5 shadow-md max-w-[250px] whitespace-normal break-words border-0"
877
+ >
878
+ <p class="caption text-white whitespace-pre-line">{tooltipTypesText}</p>
879
+ </Tooltip.Content>
880
+ </Tooltip.Portal>
885
881
  </Tooltip.Root>
886
882
  </Tooltip.Provider>
887
883
  </div>
@@ -938,7 +934,7 @@ import { translateEnglish } from '../../i18n/context';
938
934
  {:else}
939
935
  <Button
940
936
  variant="secondary"
941
- class="btn-secondary rounded-small widgetic-radius focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 hover:border-[hsl(var(--light-green))] transition-colors file-uploader-button"
937
+ class="file-uploader-button rounded-small widgetic-radius focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 !border-[hsl(var(--deep-forest-green))] !bg-[hsl(var(--deep-forest-green))] !text-white hover:!border-[hsl(var(--deep-forest-green))] hover:!bg-[hsl(var(--sage-green))] hover:!text-white transition-colors"
942
938
  onclick={() => fileInput.click()}
943
939
  >
944
940
  {$t('upload.button', { types: allowedTypesDisplayText })}
@@ -1113,9 +1109,9 @@ import { translateEnglish } from '../../i18n/context';
1113
1109
  </div>
1114
1110
  {:else if item.status === 'failed'}
1115
1111
  <div class="flex items-center justify-between">
1116
- <!-- A media library says why its upload failed ("File too large", "Not allowed"...); Widgetic uploads keep the generic text -->
1112
+ <!-- The row says why this file failed: the API's own sentence, or the File Browser's when the request never got an answer -->
1117
1113
  <p class="caption min-w-0 break-words text-[hsl(var(--error))]">
1118
- {library ? (item.errorMessage || $t('libraryError.uploadFailed')) : $t('upload.networkError')}
1114
+ {item.errorMessage || $t(library ? 'libraryError.uploadFailed' : 'upload.networkError')}
1119
1115
  </p>
1120
1116
  <button
1121
1117
  class="text-[hsl(var(--grey5))] hover:text-[hsl(var(--grey7))] transition-colors flex items-center justify-center w-5 h-5"
@@ -72,7 +72,10 @@
72
72
  // A PDF or a text file without a thumbnail gets the file-type icon: drawing the file itself as a picture
73
73
  // fails and would show it as "missing", which also makes it impossible to select (see fileKinds.ts).
74
74
  $: isKnownNonPicture = !item.thumbnail && isKnownNonImageFile(item);
75
- $: showImageThumb = isImage || isSvg || (isLikelyRemoteImage && !isAudio && !isVideo && !isFont && !isKnownNonPicture);
75
+ // A video's own address is not a picture. Only a separate thumbnail that is an image may be drawn as one.
76
+ $: hasPicturePoster = !!(item.thumbnail && looksLikePicture(item.thumbnail));
77
+ let posterFailed = false;
78
+ $: showImageThumb = !posterFailed && (isImage || isSvg || hasPicturePoster || (isLikelyRemoteImage && !isAudio && !isVideo && !isFont && !isKnownNonPicture));
76
79
 
77
80
  // State for file availability and loading
78
81
  let isLoading = true;
@@ -292,6 +295,13 @@
292
295
  * @param file File to get background for
293
296
  * @returns CSS color value
294
297
  */
298
+ /** True when an address is a picture the browser can draw in an img, not the file itself (an mp4, a pdf). */
299
+ function looksLikePicture(address: string): boolean {
300
+ if (/^data:image\//i.test(address)) return true;
301
+ const path = address.split(/[?#]/)[0];
302
+ return /\.(png|jpe?g|gif|webp|avif|heic|heif)$/i.test(path);
303
+ }
304
+
295
305
  function getBackgroundColor(file: FileSystemItem): string {
296
306
  if (file.isMissing) return 'hsl(var(--grey1))';
297
307
 
@@ -519,12 +529,12 @@
519
529
  alt=""
520
530
  class="svg-icon-image w-full h-full rounded-[var(--radius-large)] object-contain {isImageCached ? 'no-fade' : 'fade-in'}"
521
531
  />
522
- <!-- Audio or Document Icon -->
532
+ <!-- A file that is not a picture: the type icon. Drawing the file itself as an img marks it missing. -->
523
533
  {:else if !imageMissing}
524
- {#if isAudio || (fileType === 'document' && !showImageThumb)}
534
+ {#if !showImageThumb}
525
535
  <img
526
536
  src={getAssetUrl(getFileIcon(item.name))}
527
- alt={isAudio ? $t('item.audioFile') : $t('item.documentFile')}
537
+ alt={isAudio ? $t('item.audioFile') : isVideo ? $t('filterName.video') : $t('item.documentFile')}
528
538
  class="audio-doc-icon-image w-full h-full rounded-[var(--radius-large)] object-contain {isImageCached ? 'no-fade' : 'fade-in'}"
529
539
  />
530
540
  <!-- Image -->
@@ -559,10 +569,19 @@
559
569
  imgEl.src = item.url || previewSrc;
560
570
  return;
561
571
  }
562
- if (item.thumbnail && item.url && previewSrc === item.thumbnail && imgEl.src !== item.url) {
572
+ if (item.thumbnail && item.url && previewSrc === item.thumbnail && imgEl.src !== item.url && (isImage || isSvg)) {
563
573
  imgEl.src = item.url;
564
574
  return;
565
575
  }
576
+ // A video, a PDF or any other non-picture keeps its type icon and stays selectable.
577
+ if (!isImage && !isSvg) {
578
+ posterFailed = true;
579
+ imageMissing = false;
580
+ thumbnailMissing = true;
581
+ opacity.set(1);
582
+ isLoading = false;
583
+ return;
584
+ }
566
585
  thumbnailMissing = true;
567
586
  imageMissing = true;
568
587
  opacity.set(1);
@@ -52,6 +52,15 @@
52
52
  // STATE VARS
53
53
  let showLogs = false;
54
54
 
55
+ // The preview sits in the file browser, not in the whole window. Measuring the window first
56
+ // paints the card at the site's width, then the portal shrinks it to this box.
57
+ function hostFrame() {
58
+ const host = document.querySelector(`.${target}`) || document.querySelector('.file-browser-module');
59
+ const width = host instanceof HTMLElement && host.clientWidth > 0 ? host.clientWidth : window.innerWidth;
60
+ const height = host instanceof HTMLElement && host.clientHeight > 0 ? host.clientHeight : window.innerHeight;
61
+ return { width, height };
62
+ }
63
+
55
64
  // Function to determine modal dimensions based on file type
56
65
  function getModalDimensions(fileType: string) {
57
66
 
@@ -63,30 +72,12 @@
63
72
  margin = parseInt(styles.getPropertyValue('--app-margin').trim()) || margin;
64
73
  }
65
74
 
66
- // Calculate maximum available width based on window size and margins
67
- let maxWidth = window.innerWidth - (2 * margin); // Default max width (margin on each side)
75
+ const frame = hostFrame();
76
+ // Calculate maximum available width based on the file browser, and margins
77
+ let maxWidth = frame.width - (2 * margin); // Default max width (margin on each side)
68
78
 
69
79
  // Calculate maximum available height for content
70
- const maxAvailableHeight = window.innerHeight - TOTAL_VERTICAL_SPACE - 100; // 100px for top/bottom margins
71
-
72
- // Calculate aspect ratio based dimensions for video
73
- const calculateVideoDimensions = () => {
74
- const aspectRatio = 16/9; // Standard video aspect ratio
75
- let width = Math.min(800, maxWidth);
76
- let height = width / aspectRatio;
77
-
78
- // If height is too large, scale down maintaining aspect ratio
79
- if (height > maxAvailableHeight) {
80
- height = maxAvailableHeight;
81
- width = height * aspectRatio;
82
- }
83
-
84
- // Add the UI space to the final height
85
- return {
86
- width: Math.floor(width),
87
- height: Math.floor(height + TOTAL_VERTICAL_SPACE)
88
- };
89
- };
80
+ const maxAvailableHeight = frame.height - TOTAL_VERTICAL_SPACE - 48;
90
81
 
91
82
  // Determine modal dimensions based on file type
92
83
  switch (fileType) {
@@ -95,22 +86,14 @@
95
86
  width: '410px',
96
87
  height: '234px'
97
88
  };
98
- case 'image': {
99
- const maxDim = maxWidth;
100
- const contentHeight = Math.min(maxAvailableHeight, maxDim * 0.75);
89
+ case 'image':
90
+ case 'video':
91
+ // A 100px box, then it grows to the picture. Shrinking from a large card reads as a jump.
101
92
  return {
102
- width: `${maxDim}px`,
103
- height: `${contentHeight + TOTAL_VERTICAL_SPACE}px`,
104
- dynamicHeight: true // Flag to indicate this can be resized
93
+ width: '100px',
94
+ height: '100px',
95
+ dynamicHeight: true
105
96
  };
106
- }
107
- case 'video': {
108
- const { width, height } = calculateVideoDimensions();
109
- return {
110
- width: `${width}px`,
111
- height: `${height}px`
112
- };
113
- }
114
97
  case 'font':
115
98
  return {
116
99
  width: '600px',
@@ -146,8 +129,79 @@
146
129
  }
147
130
  }
148
131
 
132
+ // A video's own picture, once the file says how wide and tall it is. Until then the card uses the
133
+ // file-browser box, never the browser window.
134
+ let fittedVideo: { width: string; height: string; pictureWidth: number; pictureHeight: number } | null = null;
135
+ let fittedVideoForId = '';
136
+
137
+ function fitVideoFrame(videoWidth: number, videoHeight: number) {
138
+ if (!videoWidth || !videoHeight) return;
139
+ const frame = hostFrame();
140
+ const element = document.querySelector('.widgetic-breakpoints');
141
+ let margin = 24;
142
+ if (element) {
143
+ const styles = getComputedStyle(element);
144
+ margin = parseInt(styles.getPropertyValue('--app-margin').trim()) || margin;
145
+ }
146
+ // 16px each side, the same inset the player keeps around the picture.
147
+ const sideInset = 32;
148
+ const maxWidth = Math.max(100, frame.width - 2 * margin - sideInset);
149
+ const maxHeight = Math.max(100, frame.height - TOTAL_VERTICAL_SPACE - 48);
150
+ const aspect = videoWidth / videoHeight;
151
+ let width = maxWidth;
152
+ let height = width / aspect;
153
+ if (height > maxHeight) {
154
+ height = maxHeight;
155
+ width = height * aspect;
156
+ }
157
+ const pictureWidth = Math.max(68, Math.floor(width));
158
+ const pictureHeight = Math.max(68, Math.floor(height));
159
+ fittedVideoForId = file.id;
160
+ fittedVideo = {
161
+ width: `${pictureWidth + sideInset}px`,
162
+ height: `${pictureHeight + TOTAL_VERTICAL_SPACE}px`,
163
+ pictureWidth,
164
+ pictureHeight
165
+ };
166
+ }
167
+
149
168
  $: isSelected = allowSelecting && $validSelections(currentFilter, [file]).length > 0;
150
- $: modalDimensions = getModalDimensions(fileType);
169
+ let fittedImage: { width: string; height: string } | null = null;
170
+ let fittedImageForId = '';
171
+
172
+ $: modalDimensions = fileType === 'video' && fittedVideo && fittedVideoForId === file.id
173
+ ? fittedVideo
174
+ : fileType === 'image' && fittedImage && fittedImageForId === file.id
175
+ ? fittedImage
176
+ : getModalDimensions(fileType);
177
+ let imageRevealForId = '';
178
+ let imageRevealTimer: ReturnType<typeof setTimeout> | undefined;
179
+
180
+ function fitImageFrame(width: number, height: number) {
181
+ const frame = hostFrame();
182
+ const element = document.querySelector('.widgetic-breakpoints');
183
+ let margin = 24;
184
+ if (element) {
185
+ const styles = getComputedStyle(element);
186
+ margin = parseInt(styles.getPropertyValue('--app-margin').trim()) || margin;
187
+ }
188
+ const maxWidth = Math.max(160, frame.width - 2 * margin);
189
+ const maxHeight = Math.max(120, frame.height - TOTAL_VERTICAL_SPACE - 48);
190
+ const scale = Math.min(1, maxWidth / width, maxHeight / height);
191
+ const next = {
192
+ width: `${Math.max(100, Math.round(width * scale))}px`,
193
+ height: `${Math.max(100, Math.round(height * scale) + TOTAL_VERTICAL_SPACE)}px`
194
+ };
195
+ const id = file.id;
196
+ fittedImageForId = id;
197
+ fittedImage = next;
198
+ imageRevealForId = '';
199
+ if (imageRevealTimer) clearTimeout(imageRevealTimer);
200
+ // The card eases to this size first. The picture appears after that move.
201
+ imageRevealTimer = setTimeout(() => {
202
+ if (fittedImageForId === id) imageRevealForId = id;
203
+ }, 220);
204
+ }
151
205
 
152
206
  $: currentIndex = currentFiles.findIndex((f: FileSystemItem) => f.id === file.id);
153
207
 
@@ -327,6 +381,7 @@
327
381
  closeLabel={$t('dialog.close')}
328
382
  width={modalDimensions.width}
329
383
  height={modalDimensions.height}
384
+ animateSize={fileType === 'image' || fileType === 'video'}
330
385
  {target}
331
386
  showScroll={false}
332
387
  on:close={handleClose}
@@ -383,54 +438,38 @@
383
438
  </div>
384
439
  </div>
385
440
  {:else}
386
- <ImagePreview
387
- hash={file.hash}
388
- src={fileUrl}
389
- alt={file.name}
390
- width={file.width}
391
- height={file.height}
392
- initiallyLoaded={imageLoaded}
393
- on:load={() => imageLoaded = true}
394
- on:dimensions={(event) => {
395
- // Only update dimensions if they're smaller than our max
396
- const { width, height } = event.detail;
397
-
398
- // Get grid system margins from CSS variables
399
- const element = document.querySelector('.widgetic-breakpoints');
400
- let maxWidth = window.innerWidth - 48; // 24px padding on each side
401
-
402
- if (element) {
403
- const styles = getComputedStyle(element);
404
- const margin = parseInt(styles.getPropertyValue('--app-margin').trim()) || 24;
405
- // Calculate maximum available width based on window size and margins
406
- maxWidth = window.innerWidth - (2 * margin);
407
- }
408
-
409
- const maxHeight = window.innerHeight - TOTAL_VERTICAL_SPACE - 100;
410
-
411
- // Calculate scale to fit within bounds
412
- const scaleWidth = maxWidth / width;
413
- const scaleHeight = maxHeight / height;
414
- const scale = Math.min(1, scaleWidth, scaleHeight);
415
-
416
- // Apply scale to dimensions
417
- const finalWidth = Math.round(width * scale);
418
- const finalHeight = Math.round(height * scale);
419
-
420
- // Always update dimensions to fit content exactly
421
- modalDimensions = {
422
- width: `${finalWidth}px`,
423
- height: `${finalHeight + TOTAL_VERTICAL_SPACE}px`,
424
- dynamicHeight: true
425
- };
426
- }}
427
- />
441
+ <div class="image-preview-slot relative h-full">
442
+ <div class="image-preview-frame h-full {imageRevealForId === file.id ? 'opacity-100' : 'opacity-0'}">
443
+ <ImagePreview
444
+ hash={file.hash}
445
+ src={fileUrl}
446
+ alt={file.name}
447
+ width={file.width}
448
+ height={file.height}
449
+ initiallyLoaded={imageLoaded}
450
+ on:load={() => imageLoaded = true}
451
+ on:dimensions={(event) => {
452
+ const { width, height } = event.detail;
453
+ if (!width || !height) return;
454
+ fitImageFrame(width, height);
455
+ }}
456
+ />
457
+ </div>
458
+ {#if imageRevealForId !== file.id}
459
+ <div class="image-preview-loader absolute inset-0 flex items-center justify-center">
460
+ <div class="h-8 w-8 animate-spin rounded-full border-2 border-[hsl(var(--forest-green))] border-t-transparent"></div>
461
+ </div>
462
+ {/if}
463
+ </div>
428
464
  {/if}
429
465
  {:else if isVideo}
430
466
  <VideoPlayer
431
467
  src={fileUrl}
432
468
  bind:mediaElement={videoElement}
433
469
  {autoplay}
470
+ frameWidth={fittedVideo && fittedVideoForId === file.id ? fittedVideo.pictureWidth : 0}
471
+ frameHeight={fittedVideo && fittedVideoForId === file.id ? fittedVideo.pictureHeight : 0}
472
+ on:metadata={(event) => fitVideoFrame(event.detail.width, event.detail.height)}
434
473
  />
435
474
  {:else if isAudio}
436
475
  <AudioPlayer
@@ -2,12 +2,9 @@
2
2
  import { onMount, onDestroy, afterUpdate, tick } from 'svelte';
3
3
  import { browser } from '$app/environment';
4
4
  // import ThumbHashImage from './ThumbHashImage.svelte';
5
- import { ThumbHashImage } from "@widgetic/design-system/components";
6
5
  import { createEventDispatcher } from 'svelte';
7
6
  import { tweened } from 'svelte/motion';
8
7
  import { cubicOut } from 'svelte/easing';
9
- import { buildTransformedUrl } from '../../utils/imageTransform';
10
-
11
8
  export let hash: string | undefined = undefined;
12
9
  export let src: string | undefined = undefined;
13
10
  export let alt: string = '';
@@ -26,6 +23,12 @@
26
23
  let containerWidth: string;
27
24
  let containerHeight: string;
28
25
  let imgElement: HTMLImageElement | null = null;
26
+ // The popup lives in a shadow root in the Shopify app. document.querySelector cannot see inside it.
27
+ let previewRoot: HTMLElement | null = null;
28
+
29
+ function previewContainer(): HTMLElement | null {
30
+ return previewRoot;
31
+ }
29
32
 
30
33
  // Debug variables
31
34
  let lastOpacityValue = 0;
@@ -171,7 +174,7 @@
171
174
  if (!debugMode) return;
172
175
 
173
176
  setTimeout(() => {
174
- const container = document.querySelector('.image-preview-container');
177
+ const container = previewContainer();
175
178
  if (container) {
176
179
  // Log all image containers
177
180
  const imageContainers = container.querySelectorAll('.image-container');
@@ -219,7 +222,7 @@
219
222
  // Find the actual image element inside the ThumbHashImage component
220
223
  if (!width || !height) {
221
224
  setTimeout(() => {
222
- const container = document.querySelector('.image-preview-container');
225
+ const container = previewContainer();
223
226
  if (container) {
224
227
  // Find the current image container
225
228
  const currentContainer = container.querySelector(`div[data-image-key="${imageKey}"]`);
@@ -241,7 +244,7 @@
241
244
  function setupDOMObserver() {
242
245
  if (!debugMode || domObserver) return;
243
246
 
244
- const container = document.querySelector('.image-preview-container');
247
+ const container = previewContainer();
245
248
  if (container) {
246
249
  domObserver = new MutationObserver((mutations) => {
247
250
  for (const mutation of mutations) {
@@ -275,7 +278,7 @@
275
278
  function updateImageContainersVisibility() {
276
279
  if (!browser) return;
277
280
 
278
- const container = document.querySelector('.image-preview-container');
281
+ const container = previewContainer();
279
282
  if (container) {
280
283
  // Find all image containers
281
284
  const imageContainers = container.querySelectorAll('div[data-image-key]');
@@ -325,7 +328,7 @@
325
328
  // Wait for the DOM to update
326
329
  await tick();
327
330
 
328
- const container = document.querySelector('.image-preview-container');
331
+ const container = previewContainer();
329
332
  if (container) {
330
333
  // Find all image containers
331
334
  const allContainers = container.querySelectorAll('.image-container');
@@ -379,7 +382,7 @@
379
382
  }
380
383
  });
381
384
 
382
- const container = document.querySelector('.image-preview-container');
385
+ const container = previewContainer();
383
386
  if (container) {
384
387
  observer.observe(container, { childList: true, subtree: true });
385
388
 
@@ -490,28 +493,27 @@
490
493
  });
491
494
  </script>
492
495
 
493
- <div class="image-preview-container w-full flex items-center justify-center px-4 rounded-large overflow-hidden">
496
+ <div bind:this={previewRoot} class="image-preview-container w-full flex items-center justify-center px-4 rounded-large overflow-hidden">
494
497
  <div
495
498
  class="image-parent-container relative flex items-center justify-center"
496
499
  style="width: {containerWidth}; height: {containerHeight};"
497
500
  >
498
501
  {#if browser && src}
499
- {#each [{ src: buildTransformedUrl(src, { width: 1920, fit: 'scale-down', quality: 85 }), key: imageKey }] as item (item.key)}
502
+ {#each [{ src, key: imageKey }] as item (item.key)}
500
503
  <div
501
504
  class="image-container absolute inset-0 flex items-center justify-center"
502
505
  style="opacity: {$containerOpacity};"
503
506
  data-image-key={imageKey}
504
507
  data-src={src}
505
508
  >
506
- <!-- Use ThumbHashImage with a wrapper div that has the data attribute -->
507
- <ThumbHashImage
509
+ <!-- The stored file, not the 1920px transform. That transform stays invisible until it loads, and in the Shopify shadow root it never does. -->
510
+ <img
508
511
  src={item.src}
509
512
  {alt}
510
- thumbhash={hash || ''}
511
- class_="w-full h-full object-cover thumbhash-image"
512
- roundedCorners="rounded-large"
513
- style="--thumb-fade: 600ms; --hide-main-image: 0;"
514
- onLoad={handleImageLoad}
513
+ loading="eager"
514
+ decoding="async"
515
+ class="preview-image h-full w-full object-contain"
516
+ onload={handleImageLoad}
515
517
  />
516
518
  </div>
517
519
  {/each}
@@ -1,5 +1,6 @@
1
1
  <script lang="ts">
2
- import { onMount, onDestroy } from 'svelte';
2
+ import { onMount, onDestroy, createEventDispatcher } from 'svelte';
3
+ const dispatch = createEventDispatcher();
3
4
  import ErrorPreview from './ErrorPreview.svelte';
4
5
  import { useI18n } from '../../i18n';
5
6
 
@@ -8,6 +9,9 @@
8
9
  export let src: string;
9
10
  export let autoplay = false;
10
11
  export let mediaElement: HTMLVideoElement | undefined = undefined;
12
+ // The picture box, in pixels. The modal sizes itself from this content, so a percentage height collapses to nothing.
13
+ export let frameWidth = 0;
14
+ export let frameHeight = 0;
11
15
 
12
16
  let hasError = false;
13
17
  let isLoading = true;
@@ -20,7 +24,6 @@
20
24
  let controlsTimeout: ReturnType<typeof setTimeout>;
21
25
  let progressBarContainer: HTMLDivElement;
22
26
  let isDragging = false;
23
-
24
27
  function togglePlay() {
25
28
  if (!mediaElement) return;
26
29
 
@@ -61,6 +64,7 @@
61
64
  if (!mediaElement) return;
62
65
  duration = mediaElement.duration;
63
66
  isLoading = false;
67
+ dispatch('metadata', { width: mediaElement.videoWidth, height: mediaElement.videoHeight });
64
68
 
65
69
  if (autoplay) {
66
70
  isPlaying = !mediaElement.paused;
@@ -160,15 +164,21 @@
160
164
  <!-- svelte-ignore a11y-media-has-caption -->
161
165
  <!-- svelte-ignore a11y_no_static_element_interactions -->
162
166
  <div
163
- class="video-preview-container relative flex justify-center mx-4 overflow-hidden rounded-large widgetic-radius widgetic-colors"
167
+ class="video-preview-container relative flex w-full items-center justify-center overflow-hidden rounded-large px-4 widgetic-radius widgetic-colors"
164
168
  onmousemove={handleMouseMove}
165
169
  onmouseenter={() => showControls = true}
166
170
  >
171
+ <div
172
+ class="video-preview-frame relative max-w-full overflow-hidden rounded-large widgetic-radius"
173
+ style={frameWidth > 0 && frameHeight > 0
174
+ ? `width: ${frameWidth}px; height: ${frameHeight}px;`
175
+ : 'width: 68px; height: 68px;'}
176
+ >
167
177
  <video
168
178
  {src}
169
179
  bind:this={mediaElement}
170
180
  {autoplay}
171
- class="w-full h-full rounded-large widgetic-radius widgetic-colors"
181
+ class="video-preview-media h-full w-full object-contain rounded-large widgetic-radius widgetic-colors"
172
182
  onerror={handleError}
173
183
  onended={handleVideoEnded}
174
184
  ontimeupdate={handleTimeUpdate}
@@ -260,7 +270,8 @@
260
270
  {#if !isPlaying && showControls}
261
271
  <button
262
272
  onclick={togglePlay}
263
- class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 flex items-center justify-center w-16 h-16 bg-black/40 rounded-full text-white focus:outline-none"
273
+ class="play-button absolute flex items-center justify-center w-16 h-16 bg-black/40 rounded-full text-white focus:outline-none focus-visible:outline-none"
274
+ style="top: 50%; left: 50%; transform: translate(-50%, -50%);"
264
275
  aria-label={$t('action.play')}
265
276
  >
266
277
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-10 h-10">
@@ -268,5 +279,6 @@
268
279
  </svg>
269
280
  </button>
270
281
  {/if}
282
+ </div>
271
283
  </div>
272
284
  {/if}
@@ -15,7 +15,11 @@ declare const VideoPlayer: $$__sveltets_2_IsomorphicComponent<{
15
15
  src: string;
16
16
  autoplay?: boolean;
17
17
  mediaElement?: HTMLVideoElement | undefined;
18
+ frameWidth?: number;
19
+ frameHeight?: number;
18
20
  }, {
21
+ metadata: CustomEvent<any>;
22
+ } & {
19
23
  [evt: string]: CustomEvent<any>;
20
24
  }, {}, {}, string>;
21
25
  type VideoPlayer = InstanceType<typeof VideoPlayer>;
@@ -49,17 +49,20 @@ export declare const FILE_BROWSER_MESSAGES: {
49
49
  readonly 'filterOption.all': "All";
50
50
  readonly 'filterOption.image': "Images";
51
51
  readonly 'filterOption.video': "Videos";
52
- readonly 'filterOption.document': "Documents";
52
+ readonly 'filterOption.document': "Docs";
53
53
  readonly 'filterOption.audio': "Audio";
54
54
  readonly 'filterOption.font': "Fonts";
55
55
  readonly 'filterOption.svg': "SVG";
56
+ readonly 'sort.by': "Sort by";
57
+ readonly 'sort.orderAscending': "Click to order Ascending";
58
+ readonly 'sort.orderDescending': "Click to order Descending";
56
59
  readonly 'sort.name': "Name";
57
60
  readonly 'sort.date': "Date";
58
61
  readonly 'sort.size': "Size";
59
62
  readonly 'breadcrumbs.back': "Back";
60
63
  readonly 'breadcrumbs.forward': "Forward";
61
64
  /** The first step of the path above the files. */
62
- readonly 'breadcrumbs.root': "File browser";
65
+ readonly 'breadcrumbs.root': "Files";
63
66
  /** What a screen reader says for the path above the files. */
64
67
  readonly 'breadcrumbs.label': "breadcrumb";
65
68
  readonly 'empty.library': "No files yet!";
@@ -69,7 +72,7 @@ export declare const FILE_BROWSER_MESSAGES: {
69
72
  readonly 'library.truncatedNotice': "Only the newest files are shown.";
70
73
  readonly 'library.notSetUp': "The media library is not set up correctly.";
71
74
  /** The name of the folder that holds the files, when the page's library does not name itself. */
72
- readonly 'library.defaultLabel': "My uploads";
75
+ readonly 'library.defaultLabel': "Uploads";
73
76
  /** Why a call to the library failed, when the library gave no reason of its own. */
74
77
  readonly 'libraryError.loadFailed': "Could not load the files";
75
78
  readonly 'libraryError.uploadFailed': "The upload failed";
@@ -224,7 +227,7 @@ export declare const FILE_BROWSER_MESSAGES: {
224
227
  readonly 'moveDialog.titleOne': "Move \"{name}\"";
225
228
  readonly 'moveDialog.titleMany': "{count, plural, one {Move # item} other {Move # items}}";
226
229
  /** The name of the top of the library in the folder list of the move window. */
227
- readonly 'moveDialog.rootName': "File browser";
230
+ readonly 'moveDialog.rootName': "Files";
228
231
  readonly 'moveDialog.movingTo': "Moving to {name}";
229
232
  readonly 'moveDialog.confirmFolder': "Move folder";
230
233
  readonly 'moveDialog.confirmItem': "Move to folder";
@@ -51,17 +51,20 @@ export const FILE_BROWSER_MESSAGES = {
51
51
  'filterOption.all': 'All',
52
52
  'filterOption.image': 'Images',
53
53
  'filterOption.video': 'Videos',
54
- 'filterOption.document': 'Documents',
54
+ 'filterOption.document': 'Docs',
55
55
  'filterOption.audio': 'Audio',
56
56
  'filterOption.font': 'Fonts',
57
57
  'filterOption.svg': 'SVG',
58
+ 'sort.by': 'Sort by',
59
+ 'sort.orderAscending': 'Click to order Ascending',
60
+ 'sort.orderDescending': 'Click to order Descending',
58
61
  'sort.name': 'Name',
59
62
  'sort.date': 'Date',
60
63
  'sort.size': 'Size',
61
64
  'breadcrumbs.back': 'Back',
62
65
  'breadcrumbs.forward': 'Forward',
63
66
  /** The first step of the path above the files. */
64
- 'breadcrumbs.root': 'File browser',
67
+ 'breadcrumbs.root': 'Files',
65
68
  /** What a screen reader says for the path above the files. */
66
69
  'breadcrumbs.label': 'breadcrumb',
67
70
  // ===== What the list says when there is nothing to show =====
@@ -73,7 +76,7 @@ export const FILE_BROWSER_MESSAGES = {
73
76
  'library.truncatedNotice': 'Only the newest files are shown.',
74
77
  'library.notSetUp': 'The media library is not set up correctly.',
75
78
  /** The name of the folder that holds the files, when the page's library does not name itself. */
76
- 'library.defaultLabel': 'My uploads',
79
+ 'library.defaultLabel': 'Uploads',
77
80
  /** Why a call to the library failed, when the library gave no reason of its own. */
78
81
  'libraryError.loadFailed': 'Could not load the files',
79
82
  'libraryError.uploadFailed': 'The upload failed',
@@ -237,7 +240,7 @@ export const FILE_BROWSER_MESSAGES = {
237
240
  'moveDialog.titleOne': 'Move "{name}"',
238
241
  'moveDialog.titleMany': '{count, plural, one {Move # item} other {Move # items}}',
239
242
  /** The name of the top of the library in the folder list of the move window. */
240
- 'moveDialog.rootName': 'File browser',
243
+ 'moveDialog.rootName': 'Files',
241
244
  'moveDialog.movingTo': 'Moving to {name}',
242
245
  'moveDialog.confirmFolder': 'Move folder',
243
246
  'moveDialog.confirmItem': 'Move to folder',
@@ -4,7 +4,7 @@ import type { MediaLibraryCapabilities, MediaLibraryDeleteRequest, MediaLibraryL
4
4
  /** How long a library gets to answer `list`, `rename` and `delete` before the File Browser gives up on it. */
5
5
  export declare const DEFAULT_CALL_TIMEOUT_MS = 30000;
6
6
  /** The name of the folder the library's files are shown in, unless the library names it. */
7
- export declare const DEFAULT_LIBRARY_LABEL = "My uploads";
7
+ export declare const DEFAULT_LIBRARY_LABEL = "Uploads";
8
8
  /**
9
9
  * A library as the File Browser uses it: every answer already checked, every failure already a
10
10
  * {@link MediaLibraryError}, and the actions the visitor may use already decided.
@@ -4,7 +4,7 @@ import { normalizeMediaLibraryFile, normalizeMediaLibraryPage } from './normaliz
4
4
  /** How long a library gets to answer `list`, `rename` and `delete` before the File Browser gives up on it. */
5
5
  export const DEFAULT_CALL_TIMEOUT_MS = 30_000;
6
6
  /** The name of the folder the library's files are shown in, unless the library names it. */
7
- export const DEFAULT_LIBRARY_LABEL = 'My uploads';
7
+ export const DEFAULT_LIBRARY_LABEL = 'Uploads';
8
8
  /** What the visitor is told when a library does not answer in time. */
9
9
  const TIMEOUT_MESSAGE = 'The media library did not answer in time';
10
10
  /**
@@ -90,7 +90,7 @@ export interface MediaLibraryCapabilities {
90
90
  export interface MediaLibraryProvider {
91
91
  /** A short stable name for this library, like `acme-assets`. Used in logs. */
92
92
  readonly id: string;
93
- /** What the visitor sees as the folder's name. Default: "My uploads". */
93
+ /** What the visitor sees as the folder's name. Default: "Uploads". */
94
94
  readonly label?: string;
95
95
  /**
96
96
  * Switches actions off. A provider can only take actions away: Rename and Delete are only ever shown when the
@@ -1,4 +1,5 @@
1
1
  import { FILE_TYPES } from './fileTypes';
2
+ import { isKnownNonImageFile } from './fileKinds';
2
3
  import { translateEnglish } from '../i18n/context';
3
4
  import icAudio from '../static/icons/audio.svg?url';
4
5
  import icChecked from '../static/icons/checked.svg?url';
@@ -100,15 +101,19 @@ export function getItemFileType(item) {
100
101
  const fromName = getFileType(item.name || '');
101
102
  if (fromName !== 'document')
102
103
  return fromName;
104
+ // A PDF, a text file or any other named non-picture stays that kind. A thumbnail
105
+ // does not turn it into an image: the picture fails to load and the file is
106
+ // then shown as missing.
107
+ if (isKnownNonImageFile({ name: item.name, mimeType: item.mimeType })) {
108
+ return fromName;
109
+ }
103
110
  if (/IMG_\d+/i.test(item.name || ''))
104
111
  return 'image';
105
112
  const urlHint = item.thumbnail || item.url || '';
106
113
  if (urlHint && (/^data:image\//i.test(urlHint) || /\.(jpe?g|png|gif|webp|avif|svg)(\?|$)/i.test(urlHint.split(/[?#]/)[0]))) {
107
114
  return 'image';
108
115
  }
109
- if (item.thumbnail)
110
- return 'image';
111
- return getFileType(urlHint || item.name || '');
116
+ return getFileType(item.url || item.name || '');
112
117
  }
113
118
  export async function checkFileExists(url) {
114
119
  if (!url)
@@ -30,6 +30,6 @@ export declare function mergeMyUploadsChildren(savedChildren: FileSystemItem[] |
30
30
  * Empty library root — only user uploads (CDN URLs), no broken demo assets.
31
31
  *
32
32
  * `myUploadsName` is what the visitor reads as the name of the one folder in it: the File Browser passes the word in
33
- * the visitor's language ("My uploads" in English).
33
+ * the visitor's language ("Uploads" in English).
34
34
  */
35
35
  export declare function createUserUploadsFileSystemRoot(files: FileSystemItem[], myUploadsName?: string): Promise<FileSystemRoot>;
@@ -157,9 +157,9 @@ export function mergeMyUploadsChildren(savedChildren, uploadFiles) {
157
157
  * Empty library root — only user uploads (CDN URLs), no broken demo assets.
158
158
  *
159
159
  * `myUploadsName` is what the visitor reads as the name of the one folder in it: the File Browser passes the word in
160
- * the visitor's language ("My uploads" in English).
160
+ * the visitor's language ("Uploads" in English).
161
161
  */
162
- export async function createUserUploadsFileSystemRoot(files, myUploadsName = 'My uploads') {
162
+ export async function createUserUploadsFileSystemRoot(files, myUploadsName = 'Uploads') {
163
163
  const savedChildren = await loadLibraryTreeChildren();
164
164
  const children = mergeMyUploadsChildren(savedChildren, files);
165
165
  return {
@@ -96,9 +96,25 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
96
96
  const endpoint = `${basePath}/uploads/tus`;
97
97
  return new Promise((resolve) => {
98
98
  let tusUpload = null;
99
+ let settled = false;
100
+ const finish = (result) => {
101
+ if (settled)
102
+ return;
103
+ settled = true;
104
+ options.abortSignal?.removeEventListener('abort', abortHandler);
105
+ if (typeof window !== 'undefined')
106
+ window.removeEventListener('offline', offlineHandler);
107
+ resolve(result);
108
+ };
99
109
  const abortHandler = () => {
100
110
  tusUpload?.abort(true);
101
- resolve({ success: false, error: 'Upload cancelled.' });
111
+ finish({ success: false, error: 'Upload cancelled.' });
112
+ };
113
+ // Going offline leaves the current piece hanging until the browser gives up (often ~15s),
114
+ // and then the retries wait again. Stop that piece as soon as the browser says the connection is gone.
115
+ const offlineHandler = () => {
116
+ tusUpload?.abort(true);
117
+ finish({ success: false, error: 'Could not reach the media library.' });
102
118
  };
103
119
  if (options.abortSignal?.aborted) {
104
120
  resolve({ success: false, error: 'Upload cancelled.' });
@@ -118,17 +134,22 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
118
134
  tusUpload = new tus.Upload(file, {
119
135
  endpoint,
120
136
  chunkSize: DEFAULT_TUS_CHUNK_SIZE,
121
- retryDelays: [0, 1000, 3000, 5000],
137
+ retryDelays: [0, 400, 800],
138
+ onShouldRetry: (error) => {
139
+ if (typeof navigator !== 'undefined' && navigator.onLine === false)
140
+ return false;
141
+ const status = error.originalResponse?.getStatus?.();
142
+ return status !== 0;
143
+ },
122
144
  metadata,
123
145
  headers: {
124
146
  Authorization: `Bearer ${token}`,
125
147
  },
126
148
  onError: (error) => {
127
- options.abortSignal?.removeEventListener('abort', abortHandler);
128
149
  console.error('[widgeticTusUpload] TUS error:', error);
129
150
  // A refusal from the server (for example 401 for an expired token) carries its status; a lost connection does not.
130
151
  const refusedWithStatus = error.originalResponse?.getStatus?.();
131
- resolve({
152
+ finish({
132
153
  success: false,
133
154
  error: error.message || 'TUS upload failed.',
134
155
  ...(typeof refusedWithStatus === 'number' && { status: refusedWithStatus }),
@@ -139,10 +160,11 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
139
160
  options.onProgress?.({ bytesUploaded, bytesTotal, percentage });
140
161
  },
141
162
  onSuccess: async () => {
142
- options.abortSignal?.removeEventListener('abort', abortHandler);
163
+ if (settled)
164
+ return;
143
165
  const tusId = extractTusId(tusUpload?.url);
144
166
  if (!tusId) {
145
- resolve({ success: false, error: 'TUS upload finished without upload id.' });
167
+ finish({ success: false, error: 'TUS upload finished without upload id.' });
146
168
  return;
147
169
  }
148
170
  try {
@@ -156,26 +178,28 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
156
178
  if (!completeResponse.ok) {
157
179
  // Cancelled while waiting to ask again: say so, instead of repeating the server's "busy" answer.
158
180
  if (options.abortSignal?.aborted) {
159
- resolve({ success: false, error: 'Upload cancelled.' });
181
+ finish({ success: false, error: 'Upload cancelled.' });
160
182
  return;
161
183
  }
162
184
  const detail = await parseErrorMessage(completeResponse, `Complete failed (${completeResponse.status})`);
163
- resolve({ success: false, error: detail, status: completeResponse.status });
185
+ finish({ success: false, error: detail, status: completeResponse.status });
164
186
  return;
165
187
  }
166
188
  const json = await completeResponse.json();
167
189
  const data = (json?.data ?? json);
168
- resolve(mapCompleteResponse(data, file));
190
+ finish(mapCompleteResponse(data, file));
169
191
  }
170
192
  catch (error) {
171
193
  console.error('[widgeticTusUpload] Complete request failed:', error);
172
- resolve({
194
+ finish({
173
195
  success: false,
174
196
  error: error instanceof Error ? error.message : 'Failed to finalize upload.',
175
197
  });
176
198
  }
177
199
  },
178
200
  });
201
+ if (typeof window !== 'undefined')
202
+ window.addEventListener('offline', offlineHandler);
179
203
  tusUpload.findPreviousUploads().then((previousUploads) => {
180
204
  if (previousUploads.length > 0) {
181
205
  tusUpload?.resumeFromPreviousUpload(previousUploads[0]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/file-browser",
3
- "version": "0.5.31",
3
+ "version": "0.5.33",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "repository": {