@widgetic/file-browser 0.5.40 → 0.5.41

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 (51) hide show
  1. package/dist/components/core/FileBrowser.svelte +108 -55
  2. package/dist/components/core/FileBrowser.svelte.d.ts +5 -1
  3. package/dist/components/core/FileUploader.svelte +49 -15
  4. package/dist/components/core/RecentFiles.svelte +23 -11
  5. package/dist/components/core/RecentFiles.svelte.d.ts +1 -0
  6. package/dist/components/core/SearchDropdown.svelte +124 -26
  7. package/dist/components/core/UploadPanel.svelte +1 -1
  8. package/dist/components/items/FileItem.svelte +12 -2
  9. package/dist/components/items/FolderItem.svelte +8 -1
  10. package/dist/components/modals/index.d.ts +0 -1
  11. package/dist/components/modals/index.js +0 -1
  12. package/dist/components/previews/FilePreview.svelte +198 -31
  13. package/dist/components/previews/FilePreview.svelte.d.ts +1 -0
  14. package/dist/components/previews/ImagePreview.svelte +60 -31
  15. package/dist/components/previews/ImagePreview.svelte.d.ts +3 -0
  16. package/dist/components/previews/PreviewHeaderBar.svelte +33 -25
  17. package/dist/components/previews/PreviewHeaderBar.svelte.d.ts +2 -0
  18. package/dist/components/ui/DragSelect.svelte +85 -67
  19. package/dist/components/ui/DragSelect.svelte.d.ts +1 -0
  20. package/dist/data/demoContent.json +13 -11
  21. package/dist/i18n/messages.d.ts +0 -1
  22. package/dist/i18n/messages.js +0 -1
  23. package/dist/stores/navigationStore.d.ts +5 -0
  24. package/dist/stores/navigationStore.js +40 -67
  25. package/dist/utils/escapeSelectionAction.d.ts +18 -0
  26. package/dist/utils/escapeSelectionAction.js +18 -0
  27. package/dist/utils/imagePreviewCache.d.ts +16 -0
  28. package/dist/utils/imagePreviewCache.js +78 -0
  29. package/dist/utils/imagePreviewVisualState.d.ts +19 -0
  30. package/dist/utils/imagePreviewVisualState.js +22 -0
  31. package/dist/utils/menuKeydownBubble.d.ts +9 -0
  32. package/dist/utils/menuKeydownBubble.js +11 -0
  33. package/dist/utils/previewNavigation.d.ts +4 -0
  34. package/dist/utils/previewNavigation.js +17 -0
  35. package/dist/utils/recentFiles.d.ts +6 -0
  36. package/dist/utils/recentFiles.js +21 -0
  37. package/dist/utils/recentFilesLimit.d.ts +8 -0
  38. package/dist/utils/recentFilesLimit.js +17 -0
  39. package/dist/utils/searchEscapeAction.d.ts +10 -0
  40. package/dist/utils/searchEscapeAction.js +12 -0
  41. package/dist/utils/searchItems.d.ts +2 -4
  42. package/dist/utils/searchItems.js +12 -5
  43. package/dist/utils/searchNavigation.d.ts +12 -0
  44. package/dist/utils/searchNavigation.js +42 -0
  45. package/dist/utils/uploadDisplayProgress.d.ts +4 -0
  46. package/dist/utils/uploadDisplayProgress.js +9 -0
  47. package/dist/utils/uploadPanelProgress.d.ts +5 -0
  48. package/dist/utils/uploadPanelProgress.js +17 -0
  49. package/package.json +1 -1
  50. package/dist/components/modals/SearchModal.svelte +0 -296
  51. package/dist/components/modals/SearchModal.svelte.d.ts +0 -27
@@ -30,8 +30,11 @@
30
30
 
31
31
  // Utils
32
32
  import { getFileTypeOf } from '../../utils/fileKinds';
33
+ import { countPreviewNavigationPeers } from '../../utils/previewNavigation';
33
34
  import { toSafeFontFamilyName } from '../../utils/safeText';
34
35
  import { previewKeyAction } from '../../utils/previewKeys';
36
+ import { getCachedImageNaturalSize, preloadImageUrl, probeDecodedImage } from '../../utils/imagePreviewCache';
37
+ import { IMAGE_SLOW_LOADER_DELAY_MS, imageRevealDelayMs } from '../../utils/imagePreviewVisualState';
35
38
 
36
39
  // Stores
37
40
  import { missingFiles } from '../../stores/missingFilesStore';
@@ -48,11 +51,15 @@
48
51
  export let file: FileSystemItem;
49
52
  export let open = false;
50
53
  export let allowSelecting: boolean = false;
54
+ /** Editor picker mode — shows Select in the preview header and Space-to-select. */
55
+ export let showAddToEditor = false;
51
56
  export let currentFiles: FileSystemItem[] = [];
52
57
  export let currentFilter: FileFilterType = 'all';
53
58
  export let target: string = 'file-preview-modal'; // target for Portal
54
59
  /** Horizontal inset inside the dialog shell (Figma pad 24 each side + the 1px border of the card on each side). */
55
60
  const DIALOG_HORIZONTAL_PAD = 50;
61
+ /** Narrowest card for a picture: the header (name, previous, next, Select, close) needs this much room. */
62
+ const MIN_IMAGE_DIALOG_WIDTH = 320;
56
63
  /** Header (title + meta) + gap to body (Figma 36 + 16). */
57
64
  const HEADER_BLOCK = 52;
58
65
  /** Shell vertical padding (p-6 top + bottom, and the 1px border of the card on each side). */
@@ -194,17 +201,79 @@
194
201
  // A file the library lost, one without an address, or a picture that does not load: the card says so (Figma "Preview Dialog / Error")
195
202
  let imageFailed = false;
196
203
  $: showsErrorState = !hasValidUrl || $missingFiles.has(file.id) || imageFailed;
197
- $: modalDimensions = showsErrorState
198
- ? getModalDimensions('error')
199
- : fileType === 'video' && fittedVideo && fittedVideoForId === file.id
200
- ? fittedVideo
201
- : fileType === 'image' && fittedImage && fittedImageForId === file.id
202
- ? fittedImage
203
- : getModalDimensions(fileType);
204
+ // (`modalDimensions`, the card's size, is declared below the block that sizes the frame of a known picture.)
205
+ // What the person sees when a picture opens (round 26, the timing rules live in `imagePreviewVisualState.ts`):
206
+ // - a picture the browser already holds is shown at once, with no spinner;
207
+ // - any other picture keeps an empty frame while it loads, and only if it is STILL not there after
208
+ // `IMAGE_SLOW_LOADER_DELAY_MS` does the spinner show;
209
+ // - a loaded picture fades in after the card has eased to its size (at once when the card was sized long ago).
210
+ // Every flag below names the FILE it is true for, and every timer checks that name when it fires, so a late timer or a late
211
+ // "load" of the file the person just left can never show an empty frame or a spinner on the file that is open now.
204
212
  let imageRevealForId = '';
213
+ let imageBitmapReadyForId = '';
214
+ let slowLoaderForId = '';
215
+ let frameSizedForId = '';
216
+ let frameSizedAtMs = 0;
205
217
  let imageRevealTimer: ReturnType<typeof setTimeout> | undefined;
218
+ let slowLoaderTimer: ReturnType<typeof setTimeout> | undefined;
219
+
220
+ function clearImageRevealTimers() {
221
+ if (imageRevealTimer) clearTimeout(imageRevealTimer);
222
+ if (slowLoaderTimer) clearTimeout(slowLoaderTimer);
223
+ imageRevealTimer = undefined;
224
+ slowLoaderTimer = undefined;
225
+ }
206
226
 
207
- function fitImageFrame(width: number, height: number) {
227
+ /** A new file starts with nothing shown, nothing loaded and a fresh slow-loader clock. */
228
+ function resetImageRevealState(fileId: string) {
229
+ clearImageRevealTimers();
230
+ imageRevealForId = '';
231
+ imageBitmapReadyForId = '';
232
+ slowLoaderForId = '';
233
+ frameSizedForId = '';
234
+ slowLoaderTimer = setTimeout(() => {
235
+ slowLoaderTimer = undefined;
236
+ // Still on this file and its picture is still not there: now (and only now) the spinner shows
237
+ if (file.id === fileId && imageRevealForId !== fileId) slowLoaderForId = fileId;
238
+ }, IMAGE_SLOW_LOADER_DELAY_MS);
239
+ }
240
+
241
+ /** Shows the picture of this file, if it has loaded, once its card has had the time to ease to the picture's size. */
242
+ function revealImageWhenReady(fileId: string) {
243
+ if (file.id !== fileId || imageRevealForId === fileId || imageBitmapReadyForId !== fileId) return;
244
+ if (imageRevealTimer) clearTimeout(imageRevealTimer);
245
+ // A card that never got a size (the picture reported none) has no move to wait for
246
+ const waitMs = frameSizedForId === fileId ? imageRevealDelayMs(frameSizedAtMs, performance.now()) : 0;
247
+ imageRevealTimer = setTimeout(() => {
248
+ imageRevealTimer = undefined;
249
+ if (file.id !== fileId || imageBitmapReadyForId !== fileId) return;
250
+ imageRevealForId = fileId;
251
+ slowLoaderForId = '';
252
+ if (slowLoaderTimer) clearTimeout(slowLoaderTimer);
253
+ slowLoaderTimer = undefined;
254
+ }, waitMs);
255
+ }
256
+
257
+ /** The picture of the file that is open has arrived (the "load" event of `ImagePreview`). */
258
+ function handleImageBitmapLoaded(event: CustomEvent<{ src: string }>) {
259
+ // The picture of a file the person has already left says nothing about the one that is open
260
+ if (!fileUrl || event.detail?.src !== fileUrl) return;
261
+ const id = file.id;
262
+ imageLoaded = true;
263
+ imageBitmapReadyForId = id;
264
+ if (frameSizedForId !== id) {
265
+ // No size was known before the picture came (not in the library's data, no "dimensions" event): the picture's own size is
266
+ const natural = getCachedImageNaturalSize(fileUrl);
267
+ if (natural) fitImageFrame(natural.width, natural.height);
268
+ }
269
+ revealImageWhenReady(id);
270
+ }
271
+
272
+ function fitImageFrame(
273
+ width: number,
274
+ height: number,
275
+ options?: { revealImmediately?: boolean }
276
+ ) {
208
277
  const frame = hostFrame();
209
278
  const element = document.querySelector('.widgetic-breakpoints');
210
279
  let margin = 24;
@@ -216,19 +285,60 @@
216
285
  const maxHeight = Math.max(120, frame.height - TOTAL_VERTICAL_SPACE - 48);
217
286
  const scale = Math.min(1, maxWidth / width, maxHeight / height);
218
287
  const pictureWidth = Math.max(100, Math.round(width * scale));
288
+ // A tall, thin picture gets a card as wide as the header needs (the picture stays centred in it), never wider than the box.
289
+ const cardWidth = Math.min(
290
+ Math.max(MIN_IMAGE_DIALOG_WIDTH, pictureWidth + DIALOG_HORIZONTAL_PAD),
291
+ Math.max(pictureWidth + DIALOG_HORIZONTAL_PAD, frame.width - 2 * margin)
292
+ );
219
293
  const next = {
220
- width: `${pictureWidth + DIALOG_HORIZONTAL_PAD}px`,
294
+ width: `${cardWidth}px`,
221
295
  height: `${Math.max(100, Math.round(height * scale) + TOTAL_VERTICAL_SPACE)}px`
222
296
  };
223
297
  const id = file.id;
224
298
  fittedImageForId = id;
225
299
  fittedImage = next;
226
- imageRevealForId = '';
300
+ frameSizedForId = id;
301
+ frameSizedAtMs = performance.now();
227
302
  if (imageRevealTimer) clearTimeout(imageRevealTimer);
228
- // The card eases to this size first. The picture appears after that move.
229
- imageRevealTimer = setTimeout(() => {
230
- if (fittedImageForId === id) imageRevealForId = id;
231
- }, 220);
303
+ imageRevealTimer = undefined;
304
+ if (options?.revealImmediately) {
305
+ // The picture was decoded before: the card takes its size and the picture is there at once, with no spinner
306
+ imageBitmapReadyForId = id;
307
+ imageRevealForId = id;
308
+ slowLoaderForId = '';
309
+ return;
310
+ }
311
+ // The card eases to this size first. The picture stays hidden until it has loaded AND the card has made that move
312
+ // (if it loaded already, it appears when the move is over; if not, `handleImageBitmapLoaded` shows it when it arrives).
313
+ imageRevealForId = '';
314
+ revealImageWhenReady(id);
315
+ }
316
+
317
+ function revealCachedImageIfReady() {
318
+ if (!open || fileType !== 'image' || !hasValidUrl || !fileUrl) return;
319
+ const id = file.id;
320
+ // This file's card has its size already: the "load" of the picture, or the end of the card's move, finishes the job
321
+ if (fittedImageForId === id) return;
322
+
323
+ // The browser may still hold the picture decoded (opened before, or loaded as a neighbour): then it is shown at once
324
+ const cached = probeDecodedImage(fileUrl);
325
+ if (file.width && file.height) {
326
+ fitImageFrame(file.width, file.height, { revealImmediately: !!cached });
327
+ return;
328
+ }
329
+ if (cached) {
330
+ fitImageFrame(cached.width, cached.height, { revealImmediately: true });
331
+ }
332
+ }
333
+
334
+ function preloadNeighborPreviewImages() {
335
+ if (!open || fileType !== 'image') return;
336
+ for (const direction of ['prev', 'next'] as const) {
337
+ const neighbor = findNextAvailableFile(currentIndex, direction);
338
+ if (!neighbor?.url) continue;
339
+ if (getFileTypeOf(neighbor) !== 'image') continue;
340
+ void preloadImageUrl(neighbor.url);
341
+ }
232
342
  }
233
343
 
234
344
  $: currentIndex = currentFiles.findIndex((f: FileSystemItem) => f.id === file.id);
@@ -253,7 +363,7 @@
253
363
  isMissing: $missingFiles.has(candidateFile.id)
254
364
  });
255
365
 
256
- if (!$missingFiles.has(candidateFile.id)) {
366
+ if (candidateFile.id !== file.id && !$missingFiles.has(candidateFile.id)) {
257
367
  if(showLogs) console.log('Found available file:', candidateFile.name);
258
368
  return candidateFile;
259
369
  }
@@ -262,8 +372,39 @@
262
372
  return null;
263
373
  }
264
374
 
375
+ $: showNavigation =
376
+ allowSelecting &&
377
+ countPreviewNavigationPeers(currentFiles, file, $missingFiles) > 0;
378
+
379
+ // A new file starts with its own reveal state: nothing shown, nothing loaded, a fresh slow-loader clock. This block sits
380
+ // ABOVE the one that sizes the card on purpose, and that one reads `imageStateForFileId`, so when the file changes the reset
381
+ // always runs first (a picture that is warm is then shown by the sizing block, and is not wiped by the reset).
382
+ let imageStateForFileId = '';
383
+ $: if (file.id !== imageStateForFileId) {
384
+ imageStateForFileId = file.id;
385
+ resetImageRevealState(file.id);
386
+ }
387
+
388
+ /** Size the shell from catalogued dimensions or a warm decoder cache before the bitmap loads. */
389
+ $: if (open && file?.id && fileUrl && fileType === 'image' && imageStateForFileId === file.id) {
390
+ revealCachedImageIfReady();
391
+ preloadNeighborPreviewImages();
392
+ }
393
+
394
+ // The card's size. It stays BELOW the block above on purpose: that block sets `fittedImage` and `fittedImageForId`
395
+ // inside a function, so Svelte cannot order the two statements by their assignments. A statement placed above it reads
396
+ // the frame of the previous file in the same update (the small loading card) and does not run again, so a file that
397
+ // shares its picture with the one before (no new load event, no later "dimensions" event) kept the small card.
398
+ $: modalDimensions = showsErrorState
399
+ ? getModalDimensions('error')
400
+ : fileType === 'video' && fittedVideo && fittedVideoForId === file.id
401
+ ? fittedVideo
402
+ : fileType === 'image' && fittedImage && fittedImageForId === file.id
403
+ ? fittedImage
404
+ : getModalDimensions(fileType);
405
+
265
406
  function handleKeydown(event: KeyboardEvent) {
266
- if (!open || !allowSelecting) return;
407
+ if (!open || !allowSelecting || !showNavigation) return;
267
408
 
268
409
  // The arrow keys follow the reading direction: the left arrow is "previous" in English and "next" in Arabic.
269
410
  const keyAction = previewKeyAction(event.key, $textDirection);
@@ -295,6 +436,7 @@
295
436
  window.addEventListener('keydown', handleKeydown);
296
437
  return () => {
297
438
  window.removeEventListener('keydown', handleKeydown);
439
+ clearImageRevealTimers();
298
440
  };
299
441
  });
300
442
 
@@ -400,8 +542,10 @@
400
542
 
401
543
  // Update imageLoaded state when file changes
402
544
  $: if (fileUrl && fileType === 'image') {
403
- checkImageLoaded(fileUrl).then(loaded => {
404
- imageLoaded = loaded;
545
+ const urlBeingChecked = fileUrl;
546
+ checkImageLoaded(urlBeingChecked).then(loaded => {
547
+ // The answer for a file the person has already left must not be taken for the one that is open
548
+ if (urlBeingChecked === fileUrl) imageLoaded = loaded;
405
549
  });
406
550
  }
407
551
 
@@ -450,9 +594,16 @@
450
594
  !pdfLoadError &&
451
595
  !(fileType === 'image' && imageRevealForId !== file.id);
452
596
 
453
- $: canGoPrevious =
454
- allowSelecting && findNextAvailableFile(currentIndex, 'prev') !== null;
455
- $: canGoNext = allowSelecting && findNextAvailableFile(currentIndex, 'next') !== null;
597
+ $: canGoPrevious = showNavigation && findNextAvailableFile(currentIndex, 'prev') !== null;
598
+ $: canGoNext = showNavigation && findNextAvailableFile(currentIndex, 'next') !== null;
599
+
600
+ // The spinner: only for a picture that is STILL loading after `IMAGE_SLOW_LOADER_DELAY_MS` (the timer of the file that is
601
+ // open sets `slowLoaderForId`), never for one that was cached or arrived sooner, and never over an error card.
602
+ $: showSlowImageLoader =
603
+ fileType === 'image' &&
604
+ slowLoaderForId === file.id &&
605
+ imageRevealForId !== file.id &&
606
+ !showsErrorState;
456
607
 
457
608
  function goPreviousFile() {
458
609
  const prevFile = findNextAvailableFile(currentIndex, 'prev');
@@ -477,20 +628,22 @@
477
628
  class="file-preview-modal"
478
629
  bind:open
479
630
  bare
631
+ ariaLabel={file.name}
480
632
  width={modalDimensions.width}
481
633
  height={modalDimensions.height}
482
634
  animateSize={fileType === 'image' || fileType === 'video'}
483
635
  {target}
484
636
  showScroll={false}
485
637
  on:close={handleClose}
486
- enableSpaceKey={allowSelecting && !isMissing}
638
+ enableSpaceKey={allowSelecting && showAddToEditor && !isMissing}
487
639
  isSelected={isSelected}
488
640
  modalType="filePreview"
489
641
  modalData={{
490
642
  file,
491
643
  currentFiles,
492
644
  currentFilter,
493
- allowSelecting
645
+ allowSelecting,
646
+ showAddToEditor
494
647
  }}
495
648
  on:restore={(event) => {
496
649
  if (event.detail) {
@@ -498,6 +651,7 @@
498
651
  currentFiles = event.detail.currentFiles;
499
652
  currentFilter = event.detail.currentFilter;
500
653
  allowSelecting = event.detail.allowSelecting;
654
+ showAddToEditor = event.detail.showAddToEditor ?? showAddToEditor;
501
655
 
502
656
  // Re-trigger file type checks and URL validation
503
657
  fileType = getFileTypeOf(file);
@@ -523,7 +677,9 @@
523
677
  meta={previewMetaLine}
524
678
  showMeta={showPreviewMeta}
525
679
  {allowSelecting}
680
+ showSelectInPreview={allowSelecting && showAddToEditor}
526
681
  {isSelected}
682
+ {showNavigation}
527
683
  {canGoPrevious}
528
684
  {canGoNext}
529
685
  on:previous={goPreviousFile}
@@ -552,30 +708,41 @@
552
708
  {:else}
553
709
  <!-- Until the picture's size is known the slot is the loading card's body (156px); then it is as tall as the picture -->
554
710
  <div
555
- class="image-preview-slot relative h-full"
556
- style={fittedImageForId === file.id ? '' : 'height: 9.75rem; overflow: hidden;'}
711
+ class="image-preview-slot relative flex w-full shrink-0 justify-center"
712
+ style={fittedImageForId === file.id ? 'min-height: 0' : 'min-height: 9.75rem; overflow: hidden;'}
557
713
  >
558
- <div class="image-preview-frame h-full {imageRevealForId === file.id ? 'opacity-100' : 'opacity-0'}">
714
+ <div
715
+ class="image-preview-frame inline-flex max-w-full justify-center {imageRevealForId === file.id ? 'opacity-100' : 'opacity-0'}"
716
+ >
559
717
  <ImagePreview
560
718
  hash={file.hash}
561
719
  src={fileUrl}
562
720
  alt={file.name}
563
721
  width={file.width}
564
722
  height={file.height}
723
+ maxContentWidth={hostFrame().width - 100}
724
+ maxContentHeight={hostFrame().height - TOTAL_VERTICAL_SPACE - 48}
565
725
  initiallyLoaded={imageLoaded}
566
- on:load={() => imageLoaded = true}
726
+ on:load={handleImageBitmapLoaded}
567
727
  on:error={() => (imageFailed = true)}
568
728
  on:dimensions={(event) => {
569
729
  const { width, height } = event.detail;
570
730
  if (!width || !height) return;
571
- fitImageFrame(width, height);
731
+ // The picture was decoded before this view started: show it at once (the cache is filled by the bitmap load
732
+ // in ImagePreview, with the natural size; the size of this event is the fitted one and is not stored).
733
+ const wasWarm = !!getCachedImageNaturalSize(fileUrl);
734
+ fitImageFrame(width, height, { revealImmediately: wasWarm });
572
735
  }}
573
736
  />
574
737
  </div>
575
- {#if imageRevealForId !== file.id}
576
- <div class="image-preview-loader absolute inset-0 flex flex-col items-center justify-center gap-3">
738
+ {#if showSlowImageLoader}
739
+ <div
740
+ class="image-preview-loader absolute inset-0 flex flex-col items-center justify-center"
741
+ role="status"
742
+ aria-label={$t('preview.loading')}
743
+ >
577
744
  <IconLoader2 class="size-8 animate-spin stroke-[1.333] text-primary motion-reduce:animate-none" />
578
- <p class="text-caption text-muted-foreground">{$t('preview.loading')}</p>
745
+ <span class="sr-only">{$t('preview.loading')}</span>
579
746
  </div>
580
747
  {/if}
581
748
  </div>
@@ -17,6 +17,7 @@ declare const FilePreview: $$__sveltets_2_IsomorphicComponent<{
17
17
  file: FileSystemItem;
18
18
  open?: boolean;
19
19
  allowSelecting?: boolean;
20
+ /** Editor picker mode — shows Select in the preview header and Space-to-select. */ showAddToEditor?: boolean;
20
21
  currentFiles?: FileSystemItem[];
21
22
  currentFilter?: FileFilterType;
22
23
  target?: string;
@@ -5,12 +5,17 @@
5
5
  import { createEventDispatcher } from 'svelte';
6
6
  import { tweened } from 'svelte/motion';
7
7
  import { cubicOut } from 'svelte/easing';
8
+ import { rememberImageNaturalSize } from '../../utils/imagePreviewCache';
8
9
  export let hash: string | undefined = undefined;
9
10
  export let src: string | undefined = undefined;
10
11
  export let alt: string = '';
11
12
  export let initiallyLoaded: boolean = false;
12
13
  export let width: number | undefined = undefined;
13
14
  export let height: number | undefined = undefined;
15
+ /** Max picture width inside the preview host (falls back to window when omitted). */
16
+ export let maxContentWidth: number | undefined = undefined;
17
+ /** Max picture height inside the preview host (falls back to window when omitted). */
18
+ export let maxContentHeight: number | undefined = undefined;
14
19
 
15
20
  let imageLoaded = initiallyLoaded;
16
21
  let isImageCached = false;
@@ -38,21 +43,34 @@
38
43
  let domObserver: MutationObserver | null = null;
39
44
  let elementStates: {timestamp: number, mainImage: string, thumbhash: string}[] = [];
40
45
 
46
+ function pictureMaxBounds() {
47
+ const maxWidth =
48
+ maxContentWidth ??
49
+ (typeof window !== 'undefined' ? Math.max(160, window.innerWidth - 100) : 1024);
50
+ const maxHeight =
51
+ maxContentHeight ??
52
+ (typeof window !== 'undefined' ? Math.max(120, window.innerHeight - 200) : 768);
53
+ return { maxWidth, maxHeight };
54
+ }
55
+
56
+ function scaleToFitBounds(pictureWidth: number, pictureHeight: number) {
57
+ const { maxWidth, maxHeight } = pictureMaxBounds();
58
+ const scale = Math.min(1, maxWidth / pictureWidth, maxHeight / pictureHeight);
59
+ return {
60
+ width: Math.max(1, Math.round(pictureWidth * scale)),
61
+ height: Math.max(1, Math.round(pictureHeight * scale)),
62
+ };
63
+ }
64
+
41
65
  // Calculate initial dimensions with proper scaling
42
66
  $: {
43
67
  if (width && height) {
44
- const maxWidth = typeof window !== 'undefined' ? window.innerWidth - 100 : 1024; // 50px padding each side
45
- const maxHeight = typeof window !== 'undefined' ? window.innerHeight - 200 : 768; // 100px padding top/bottom
46
-
47
- const scaleWidth = maxWidth / width;
48
- const scaleHeight = maxHeight / height;
49
- const scale = Math.min(1, scaleWidth, scaleHeight);
50
-
51
- containerWidth = `${Math.round(width * scale)}px`;
52
- containerHeight = `${Math.round(height * scale)}px`;
68
+ const fitted = scaleToFitBounds(width, height);
69
+ containerWidth = `${fitted.width}px`;
70
+ containerHeight = `${fitted.height}px`;
53
71
  } else {
54
- containerWidth = "500px";
55
- containerHeight = "400px";
72
+ containerWidth = '10rem';
73
+ containerHeight = '10rem';
56
74
  }
57
75
  }
58
76
 
@@ -104,22 +122,13 @@
104
122
  }
105
123
 
106
124
  function updateDimensions(imgWidth: number, imgHeight: number) {
107
- // Use provided dimensions if available, otherwise use image dimensions
108
- const actualWidth = width || imgWidth;
109
- const actualHeight = height || imgHeight;
110
-
111
- // Get viewport dimensions with some padding
112
- const maxWidth = window.innerWidth - 100; // 50px padding each side
113
- const maxHeight = window.innerHeight - 200; // 100px padding top/bottom
114
-
115
- // Calculate scale to fit within bounds while maintaining aspect ratio
116
- const scaleWidth = maxWidth / actualWidth;
117
- const scaleHeight = maxHeight / actualHeight;
118
- const scale = Math.min(1, scaleWidth, scaleHeight);
125
+ // Loaded bitmap dimensions beat stale catalog metadata (wrong aspect → grey bands in the preview).
126
+ const actualWidth = imgWidth > 0 ? imgWidth : (width ?? imgWidth);
127
+ const actualHeight = imgHeight > 0 ? imgHeight : (height ?? imgHeight);
119
128
 
120
- // Apply scale to dimensions
121
- const finalWidth = Math.round(actualWidth * scale);
122
- const finalHeight = Math.round(actualHeight * scale);
129
+ const fitted = scaleToFitBounds(actualWidth, actualHeight);
130
+ const finalWidth = fitted.width;
131
+ const finalHeight = fitted.height;
123
132
 
124
133
  containerWidth = `${finalWidth}px`;
125
134
  containerHeight = `${finalHeight}px`;
@@ -135,7 +144,22 @@
135
144
  }
136
145
  }
137
146
 
138
- function handleImageLoad() {
147
+ function handleImageLoad(event: Event, loadedSrc: string) {
148
+ // A picture that is no longer the one shown (the person moved on before it arrived) must neither size the card nor
149
+ // fill the cache under the address of the picture that is shown now.
150
+ if (loadedSrc !== src) return;
151
+ const loadedImage = event.currentTarget as HTMLImageElement | null;
152
+ if (loadedImage?.naturalWidth && loadedImage?.naturalHeight) {
153
+ updateDimensions(loadedImage.naturalWidth, loadedImage.naturalHeight);
154
+ // Remembered after the "dimensions" event, so the preview can tell a picture it had not seen before from one it had
155
+ // (the first view eases the card before it shows the picture; a view of a known picture shows it at once).
156
+ if (src) {
157
+ rememberImageNaturalSize(src, loadedImage.naturalWidth, loadedImage.naturalHeight);
158
+ }
159
+ }
160
+ // The picture itself has arrived: the preview shows it (and takes its spinner away) when its card has the right size.
161
+ dispatch('load', { src: loadedSrc });
162
+
139
163
  if (imageLoaded || isTransitioning) {
140
164
  if (debugMode) console.log(`[DEBUG] Image load handler skipped - already loaded: ${imageLoaded}, transitioning: ${isTransitioning}`);
141
165
  return;
@@ -170,7 +194,9 @@
170
194
  }
171
195
 
172
196
  // The file cannot be fetched or is not a picture: tell the preview, so it can say so instead of loading for ever.
173
- function handleImageError() {
197
+ function handleImageError(failedSrc: string) {
198
+ // The failure of a picture that is no longer shown says nothing about the one that is
199
+ if (failedSrc !== src) return;
174
200
  console.warn('ImagePreview: the image could not be loaded:', src);
175
201
  dispatch('error');
176
202
  }
@@ -499,7 +525,10 @@
499
525
  });
500
526
  </script>
501
527
 
502
- <div bind:this={previewRoot} class="image-preview-container flex w-full items-center justify-center overflow-hidden rounded-xl bg-muted">
528
+ <div
529
+ bind:this={previewRoot}
530
+ class="image-preview-container inline-flex max-w-full items-center justify-center overflow-hidden rounded-xl bg-muted"
531
+ >
503
532
  <div
504
533
  class="image-parent-container relative flex items-center justify-center"
505
534
  style="width: {containerWidth}; height: {containerHeight};"
@@ -519,8 +548,8 @@
519
548
  loading="eager"
520
549
  decoding="async"
521
550
  class="preview-image h-full w-full object-contain"
522
- onload={handleImageLoad}
523
- onerror={handleImageError}
551
+ onload={(event) => handleImageLoad(event, item.src)}
552
+ onerror={() => handleImageError(item.src)}
524
553
  />
525
554
  </div>
526
555
  {/each}
@@ -18,8 +18,11 @@ declare const ImagePreview: $$__sveltets_2_IsomorphicComponent<{
18
18
  initiallyLoaded?: boolean;
19
19
  width?: number | undefined;
20
20
  height?: number | undefined;
21
+ /** Max picture width inside the preview host (falls back to window when omitted). */ maxContentWidth?: number | undefined;
22
+ /** Max picture height inside the preview host (falls back to window when omitted). */ maxContentHeight?: number | undefined;
21
23
  }, {
22
24
  dimensions: CustomEvent<any>;
25
+ load: CustomEvent<any>;
23
26
  error: CustomEvent<any>;
24
27
  } & {
25
28
  [evt: string]: CustomEvent<any>;
@@ -16,9 +16,13 @@
16
16
  export let meta = '';
17
17
  export let showMeta = true;
18
18
  export let allowSelecting = false;
19
+ /** When true, the preview shows the picker Select control (editor embed mode). */
20
+ export let showSelectInPreview = false;
19
21
  export let isSelected = false;
20
22
  export let canGoPrevious = false;
21
23
  export let canGoNext = false;
24
+ /** When false, previous/next controls are not shown (single item in folder). */
25
+ export let showNavigation = true;
22
26
  // What a screen reader says for the close button
23
27
  export let closeLabel = '';
24
28
  </script>
@@ -35,32 +39,36 @@
35
39
  {/if}
36
40
  </div>
37
41
 
38
- {#if allowSelecting}
42
+ {#if allowSelecting && (showNavigation || showSelectInPreview)}
39
43
  <div class="flex shrink-0 items-center gap-1">
40
- <IconButton
41
- variant="ghost"
42
- label={$t('preview.previousFile')}
43
- disabled={!canGoPrevious}
44
- onclick={() => dispatch('previous')}
45
- >
46
- <IconChevronLeft class="size-4 stroke-2 rtl:rotate-180" />
47
- </IconButton>
48
- <IconButton
49
- variant="ghost"
50
- label={$t('preview.nextFile')}
51
- disabled={!canGoNext}
52
- onclick={() => dispatch('next')}
53
- >
54
- <IconChevronRight class="size-4 stroke-2 rtl:rotate-180" />
55
- </IconButton>
56
- <Button
57
- variant="outline"
58
- size="sm"
59
- class="press-feedback"
60
- onclick={() => dispatch('select')}
61
- >
62
- {isSelected ? $t('action.selected') : $t('action.select')}
63
- </Button>
44
+ {#if showNavigation}
45
+ <IconButton
46
+ variant="ghost"
47
+ label={$t('preview.previousFile')}
48
+ disabled={!canGoPrevious}
49
+ onclick={() => dispatch('previous')}
50
+ >
51
+ <IconChevronLeft class="size-4 stroke-2 rtl:rotate-180" />
52
+ </IconButton>
53
+ <IconButton
54
+ variant="ghost"
55
+ label={$t('preview.nextFile')}
56
+ disabled={!canGoNext}
57
+ onclick={() => dispatch('next')}
58
+ >
59
+ <IconChevronRight class="size-4 stroke-2 rtl:rotate-180" />
60
+ </IconButton>
61
+ {/if}
62
+ {#if showSelectInPreview}
63
+ <Button
64
+ variant="outline"
65
+ size="sm"
66
+ class="press-feedback"
67
+ onclick={() => dispatch('select')}
68
+ >
69
+ {isSelected ? $t('action.selected') : $t('action.select')}
70
+ </Button>
71
+ {/if}
64
72
  </div>
65
73
  {/if}
66
74
 
@@ -16,9 +16,11 @@ declare const PreviewHeaderBar: $$__sveltets_2_IsomorphicComponent<{
16
16
  meta?: string;
17
17
  showMeta?: boolean;
18
18
  allowSelecting?: boolean;
19
+ /** When true, the preview shows the picker Select control (editor embed mode). */ showSelectInPreview?: boolean;
19
20
  isSelected?: boolean;
20
21
  canGoPrevious?: boolean;
21
22
  canGoNext?: boolean;
23
+ /** When false, previous/next controls are not shown (single item in folder). */ showNavigation?: boolean;
22
24
  closeLabel?: string;
23
25
  }, {
24
26
  previous: CustomEvent<void>;