@reuse-sh/lightbox 0.0.6 → 0.2.0

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 (53) hide show
  1. package/README.md +65 -16
  2. package/dist/audio.d.ts +2 -0
  3. package/dist/audio.js +17 -0
  4. package/dist/base.css +602 -0
  5. package/dist/browser/audio.js +3 -0
  6. package/dist/browser/audio.js.map +1 -0
  7. package/dist/browser/carousel-link.js +3 -0
  8. package/dist/browser/carousel-link.js.map +1 -0
  9. package/dist/browser/embed.js +3 -0
  10. package/dist/browser/embed.js.map +1 -0
  11. package/dist/browser/html.js +3 -0
  12. package/dist/browser/html.js.map +1 -0
  13. package/dist/browser/iframe.js +3 -0
  14. package/dist/browser/iframe.js.map +1 -0
  15. package/dist/browser/lightbox.js +3 -0
  16. package/dist/browser/lightbox.js.map +1 -0
  17. package/dist/browser/video.js +3 -0
  18. package/dist/browser/video.js.map +1 -0
  19. package/dist/carousel.d.ts +6 -0
  20. package/dist/carousel.js +17 -0
  21. package/dist/chrome.d.ts +35 -0
  22. package/dist/chrome.js +53 -0
  23. package/dist/embed.d.ts +14 -0
  24. package/dist/embed.js +173 -0
  25. package/dist/geometry.d.ts +37 -1
  26. package/dist/geometry.js +75 -5
  27. package/dist/html.d.ts +2 -0
  28. package/dist/html.js +15 -0
  29. package/dist/icons.d.ts +15 -0
  30. package/dist/icons.js +40 -0
  31. package/dist/iframe.d.ts +8 -0
  32. package/dist/iframe.js +43 -0
  33. package/dist/index.d.ts +180 -47
  34. package/dist/index.js +3817 -398
  35. package/dist/react.d.ts +18 -9
  36. package/dist/react.js +71 -46
  37. package/dist/sources.d.ts +28 -0
  38. package/dist/sources.js +179 -0
  39. package/dist/theme.css +236 -0
  40. package/dist/themes/dark.css +12 -0
  41. package/dist/themes/light.css +12 -0
  42. package/dist/themes/page.css +28 -0
  43. package/dist/themes/photos.css +17 -0
  44. package/dist/unlayered/base.css +599 -0
  45. package/dist/unlayered/theme.css +233 -0
  46. package/dist/unlayered/themes/dark.css +9 -0
  47. package/dist/unlayered/themes/light.css +9 -0
  48. package/dist/unlayered/themes/page.css +25 -0
  49. package/dist/unlayered/themes/photos.css +14 -0
  50. package/dist/video.d.ts +3 -0
  51. package/dist/video.js +55 -0
  52. package/package.json +33 -4
  53. package/dist/styles.css +0 -218
package/dist/index.js CHANGED
@@ -1,6 +1,130 @@
1
1
  import { createCarousel } from "@reuse-sh/carousel";
2
- import { boundZoom, clamp, contain, cover, identity, zoomAround, } from "./geometry.js";
2
+ import { createThinkingDots } from "@reuse-sh/loaders";
3
+ import { initialChrome, stepChrome, } from "./chrome.js";
4
+ import { boundZoom, clamp, contain, cover, elasticZoom, identity, panRange, shapeOf, unrubber, widthFit, zoomAround, zoomLimits, } from "./geometry.js";
5
+ import { showIcon } from "./icons.js";
6
+ import { fileWidth, formatOf, isImageFile, largestSource, largestWidth, lookupFormat, svgSize, } from "./sources.js";
7
+ const carouselInternals = Symbol.for("@reuse-sh/carousel internals");
8
+ function carouselInternalsOf(carousel) {
9
+ return carousel[carouselInternals];
10
+ }
11
+ // What bindLightboxGallery reads from a controller it did not create, under a key that another
12
+ // copy of this package finds too: whether a module plays a type, and the options set so far,
13
+ // which markup options must not override.
14
+ const lightboxInternals = Symbol.for("@reuse-sh/lightbox internals");
15
+ function internalsOf(lightbox) {
16
+ return lightbox?.[lightboxInternals];
17
+ }
18
+ const defaultStrings = {
19
+ dialog: "Image gallery",
20
+ slide: (index, count, caption) => `Image ${index + 1} of ${count}${caption ? `, ${caption}` : ""}`,
21
+ counter: (index, count) => `${index + 1} / ${count}`,
22
+ close: "Close gallery",
23
+ previous: "Previous image",
24
+ next: "Next image",
25
+ zoomIn: "Zoom in",
26
+ zoomOut: "Zoom out",
27
+ fullscreenEnter: "Enter full screen",
28
+ fullscreenExit: "Exit full screen",
29
+ download: "Download",
30
+ thumbnails: "Choose image",
31
+ thumbnail: (index) => `Show image ${index + 1}`,
32
+ slideshowStart: "Start slideshow",
33
+ slideshowStop: "Stop slideshow",
34
+ loading: "Loading",
35
+ error: "Image could not be loaded.",
36
+ retry: "Try again",
37
+ carouselRole: "carousel",
38
+ };
39
+ const defaultControls = {
40
+ close: true,
41
+ arrows: true,
42
+ counter: true,
43
+ zoom: true,
44
+ fullscreen: false,
45
+ download: false,
46
+ slideshow: false,
47
+ };
48
+ const builtInIcons = {
49
+ close: "close",
50
+ previous: "previous",
51
+ next: "next",
52
+ zoom: "zoomIn",
53
+ zoomOut: "zoomOut",
54
+ fullscreen: "fullscreenEnter",
55
+ fullscreenExit: "fullscreenExit",
56
+ download: "download",
57
+ slideshow: "play",
58
+ slideshowPause: "pause",
59
+ };
60
+ const firstStateIcon = {
61
+ zoomOut: "zoom",
62
+ fullscreenExit: "fullscreen",
63
+ slideshowPause: "slideshow",
64
+ };
3
65
  const locks = new WeakMap();
66
+ // A tile often rounds a wrapper that clips the image to its own box rather than the image itself.
67
+ function corners(origin, rect, win) {
68
+ const sides = [
69
+ "borderTopLeftRadius",
70
+ "borderTopRightRadius",
71
+ "borderBottomRightRadius",
72
+ "borderBottomLeftRadius",
73
+ ];
74
+ for (let element = origin; element; element = element.parentElement) {
75
+ const box = element.getBoundingClientRect();
76
+ if (Math.abs(box.left - rect.left) > 1 ||
77
+ Math.abs(box.top - rect.top) > 1 ||
78
+ Math.abs(box.right - rect.right) > 1 ||
79
+ Math.abs(box.bottom - rect.bottom) > 1)
80
+ break;
81
+ const style = win.getComputedStyle(element);
82
+ if (element !== origin && style.overflow === "visible")
83
+ continue;
84
+ const radii = sides.map((side) => {
85
+ const value = style[side].split(" ")[0] ?? "";
86
+ const size = Number.parseFloat(value) || 0;
87
+ return value.endsWith("%") ? (size * rect.width) / 100 : size;
88
+ });
89
+ if (radii.some(Boolean))
90
+ return radii;
91
+ }
92
+ return [0, 0, 0, 0];
93
+ }
94
+ // A tile shows when part of it lies inside the window and inside every ancestor that clips it.
95
+ function onScreen(origin, rect, win) {
96
+ let left = Math.max(rect.left, 0);
97
+ let top = Math.max(rect.top, 0);
98
+ let right = Math.min(rect.right, win.innerWidth);
99
+ let bottom = Math.min(rect.bottom, win.innerHeight);
100
+ for (let element = origin.parentElement;
101
+ // The body's overflow belongs to the window, which the start already clips to.
102
+ element &&
103
+ element !== origin.ownerDocument.body &&
104
+ right > left &&
105
+ bottom > top; element = element.parentElement) {
106
+ const style = win.getComputedStyle(element);
107
+ if (style.overflowX === "visible" && style.overflowY === "visible")
108
+ continue;
109
+ const clip = element.getBoundingClientRect();
110
+ if (style.overflowX !== "visible") {
111
+ left = Math.max(left, clip.left);
112
+ right = Math.min(right, clip.right);
113
+ }
114
+ if (style.overflowY !== "visible") {
115
+ top = Math.max(top, clip.top);
116
+ bottom = Math.min(bottom, clip.bottom);
117
+ }
118
+ }
119
+ return right > left && bottom > top;
120
+ }
121
+ function counterNode(doc) {
122
+ const counter = doc.createElement("span");
123
+ counter.className = "re-lightbox-counter";
124
+ counter.dir = "auto";
125
+ counter.setAttribute("aria-hidden", "true");
126
+ return counter;
127
+ }
4
128
  function lockScroll(doc) {
5
129
  const win = doc.defaultView;
6
130
  if (!win)
@@ -43,11 +167,116 @@ function lockScroll(doc) {
43
167
  locks.delete(doc);
44
168
  };
45
169
  }
46
- function validateItems(items) {
170
+ // history.back() lands asynchronously, so a lightbox that opens or closes before it lands must
171
+ // not push or go back again; the pending back is shared by every lightbox of the window.
172
+ const historyBacks = new WeakMap();
173
+ const landings = new WeakSet();
174
+ // A viewer that leaves while another viewer's entry sits above its own cannot go back to it, so
175
+ // its entry is drained once it becomes the current one.
176
+ const HISTORY_KEY = "reuseLightbox";
177
+ const orphans = new WeakMap();
178
+ function entryOf(win) {
179
+ const current = win.history.state;
180
+ const id = typeof current === "object" && current !== null
181
+ ? current[HISTORY_KEY]
182
+ : undefined;
183
+ return typeof id === "string" ? id : undefined;
184
+ }
185
+ function orphan(win, id) {
186
+ const current = entryOf(win);
187
+ if (current === undefined || current === id)
188
+ return;
189
+ const set = orphans.get(win) ?? new Set();
190
+ orphans.set(win, set);
191
+ set.add(id);
192
+ }
193
+ function takeOrphan(win) {
194
+ const id = entryOf(win);
195
+ return id !== undefined && Boolean(orphans.get(win)?.delete(id));
196
+ }
197
+ function landed(win, event) {
198
+ if (landings.has(event))
199
+ return true;
200
+ const back = historyBacks.get(win);
201
+ if (!back)
202
+ return false;
203
+ landings.add(event);
204
+ if (takeOrphan(win)) {
205
+ win.history.back();
206
+ return true;
207
+ }
208
+ win.removeEventListener("popstate", back.drain);
209
+ historyBacks.delete(win);
210
+ releaseScroll(win);
211
+ back.land();
212
+ return true;
213
+ }
214
+ // Going back would restore the scroll the page had when the viewer opened and undo a scroll made
215
+ // during the close flight. Chrome and Firefox read the mode of the entry they return to, Safari
216
+ // reads the current mode in a task after popstate, so the page's entry is manual while the viewer
217
+ // has its own entry, the viewer's entry keeps the page's mode for a reload, and the back sets
218
+ // manual again until one task after it lands.
219
+ const heldScrolls = new WeakMap();
220
+ function holdScroll(win) {
221
+ const held = heldScrolls.get(win);
222
+ if (held) {
223
+ held.release = undefined;
224
+ return held.mode;
225
+ }
226
+ const mode = win.history.scrollRestoration;
227
+ heldScrolls.set(win, { mode });
228
+ win.history.scrollRestoration = "manual";
229
+ return mode;
230
+ }
231
+ function releaseScroll(win) {
232
+ const held = heldScrolls.get(win);
233
+ if (!held || held.release)
234
+ return;
235
+ const release = {};
236
+ held.release = release;
237
+ const restore = () => {
238
+ if (held.release !== release)
239
+ return;
240
+ heldScrolls.delete(win);
241
+ win.history.scrollRestoration = held.mode;
242
+ };
243
+ const Channel = win.MessageChannel;
244
+ if (!Channel)
245
+ return restore();
246
+ const channel = new Channel();
247
+ channel.port1.onmessage = () => {
248
+ channel.port1.close();
249
+ restore();
250
+ };
251
+ channel.port2.postMessage(null);
252
+ }
253
+ function goBack(win) {
254
+ const pending = historyBacks.get(win);
255
+ if (pending)
256
+ return pending.landing;
257
+ let land = () => { };
258
+ const landing = new Promise((resolve) => {
259
+ land = resolve;
260
+ });
261
+ const drain = (event) => {
262
+ landed(win, event);
263
+ };
264
+ historyBacks.set(win, { drain, land, landing });
265
+ win.addEventListener("popstate", drain);
266
+ if (heldScrolls.has(win))
267
+ win.history.scrollRestoration = "manual";
268
+ win.history.back();
269
+ return landing;
270
+ }
271
+ function validateItems(items, content = []) {
47
272
  if (!items.length)
48
273
  throw new TypeError("Lightbox needs at least one image.");
49
274
  return items.map((item) => {
50
- if (!item || typeof item.src !== "string" || !item.src.trim())
275
+ if (item?.type !== undefined) {
276
+ if (!content.some((module) => module.type === item.type))
277
+ throw new TypeError(`Lightbox items of type ${item.type} need their module in the content option.`);
278
+ }
279
+ else if (!item || typeof item.src !== "string" || !item.src.trim())
51
280
  throw new TypeError("Lightbox images need a source.");
52
281
  if ((item.width !== undefined &&
53
282
  (!Number.isFinite(item.width) || item.width <= 0)) ||
@@ -57,6 +286,76 @@ function validateItems(items) {
57
286
  return { ...item };
58
287
  });
59
288
  }
289
+ const OPEN_DURATION = 400;
290
+ const CLOSE_DURATION = 300;
291
+ const REDUCED_DURATION = 150;
292
+ const ZOOM_DURATION = 350;
293
+ const FADE_DURATION = 240;
294
+ const PADDING = 32;
295
+ const FLIGHT_EASE = "cubic-bezier(0.32, 0.72, 0, 1)";
296
+ const ZOOM_EASE = "cubic-bezier(.16,1,.3,1)";
297
+ const NUDGE_DURATION = 220;
298
+ const DOUBLE_TAP_TIME = 300;
299
+ const DOUBLE_TAP_DISTANCE = 30;
300
+ const DISMISS_DISTANCE = 120;
301
+ const DISMISS_SPEED = 0.5;
302
+ const SPEED_WINDOW = 80;
303
+ const GLIDE_TIME = 180;
304
+ const GLIDE_DURATION = 400;
305
+ const PINCH_MIN = 0.6;
306
+ const PINCH_OVER = 1.25;
307
+ const PINCH_CLOSE = 0.75;
308
+ const EDGE_PAGE = 0.3;
309
+ const KEY_PAN = 0.1;
310
+ const LOADING_DELAY = 300;
311
+ const ZOOM_IDLE = 150;
312
+ const SPINNER_SIZE = 32;
313
+ const LANDING_HANDOFF = 0.7;
314
+ const MAX_THUMB_RATIO = 3;
315
+ // A node from another document's window fails instanceof against this window's classes.
316
+ function isNode(value) {
317
+ return typeof value?.nodeType === "number";
318
+ }
319
+ function isElement(value) {
320
+ return isNode(value) && value.nodeType === 1;
321
+ }
322
+ function isHTMLElement(value) {
323
+ return (isElement(value) && value.namespaceURI === "http://www.w3.org/1999/xhtml");
324
+ }
325
+ function resolveOrigin(origin) {
326
+ return (typeof origin === "function" ? origin() : origin) ?? null;
327
+ }
328
+ function sameZoom(a, b) {
329
+ return a.scale === b.scale && a.x === b.x && a.y === b.y;
330
+ }
331
+ function zoomTransform(zoom) {
332
+ return `translate(${zoom.x}px, ${zoom.y}px) scale(${zoom.scale})`;
333
+ }
334
+ function milliseconds(value, fallback) {
335
+ const number = Number.parseFloat(value);
336
+ if (!Number.isFinite(number))
337
+ return fallback;
338
+ return value.trim().endsWith("ms") || !value.trim().endsWith("s")
339
+ ? number
340
+ : number * 1000;
341
+ }
342
+ function releaseVelocity(samples, time, at) {
343
+ const first = samples.find((sample) => sample.time >= time - SPEED_WINDOW);
344
+ if (!first || time - first.time <= 0)
345
+ return { x: 0, y: 0 };
346
+ return {
347
+ x: (at.x - first.x) / (time - first.time),
348
+ y: (at.y - first.y) / (time - first.time),
349
+ };
350
+ }
351
+ function matches(element, selector) {
352
+ try {
353
+ return element.matches(selector);
354
+ }
355
+ catch {
356
+ return false;
357
+ }
358
+ }
60
359
  function distance(points) {
61
360
  return Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
62
361
  }
@@ -67,74 +366,526 @@ function midpoint(points) {
67
366
  };
68
367
  }
69
368
  export function createLightbox(options = {}) {
70
- const maxZoom = Math.max(1, options.maxZoom ?? 4);
71
- const tapZoom = clamp(options.tapZoom ?? 2.5, 1, maxZoom);
72
- const preload = clamp(Math.floor(options.preload ?? 1), 0, 2);
73
- const padding = Math.max(0, options.padding ?? 32);
369
+ // The caller's object is copied once, so changing it later changes nothing; setOptions does.
370
+ const current = { ...options };
371
+ let settings = { ...current };
372
+ let preload = 1;
373
+ let padding = PADDING;
374
+ let autoHide = 2500;
375
+ let loop = Boolean(options.loop);
74
376
  let items = [];
377
+ let sources = [];
75
378
  let session;
76
379
  let destroyed = false;
77
380
  let syncingCarousel = false;
78
381
  let closePromise;
382
+ let pendingClosed;
383
+ let listAfterClose;
79
384
  let state = {
80
385
  isOpen: false,
81
386
  isClosing: false,
387
+ isAnimating: false,
82
388
  index: 0,
83
389
  count: 0,
390
+ item: undefined,
391
+ canPrev: false,
392
+ canNext: false,
393
+ isPlaying: false,
84
394
  zoom: { ...identity },
395
+ chrome: "shown",
85
396
  };
86
397
  const listeners = new Set();
398
+ const stops = new Set();
399
+ const handlers = new Map();
400
+ const historyId = Math.random().toString(36).slice(2);
401
+ let historyWindow;
402
+ let vetting = false;
403
+ let forcing = false;
87
404
  let notifiedState = state;
405
+ const initial = state;
406
+ // A gallery's markup options for the next open, set only while bindLightboxGallery opens.
407
+ let galleryOptions;
408
+ function configure(layer) {
409
+ settings = { ...current };
410
+ for (const [key, value] of Object.entries(layer ?? {}))
411
+ if (settings[key] === undefined)
412
+ Object.assign(settings, { [key]: value });
413
+ if (layer?.strings && current.strings)
414
+ settings.strings = { ...layer.strings, ...current.strings };
415
+ loop = Boolean(settings.loop);
416
+ preload = clamp(Math.floor(settings.preload ?? 1), 0, 2);
417
+ autoHide =
418
+ settings.autoHide === false
419
+ ? false
420
+ : Number.isFinite(settings.autoHide)
421
+ ? Math.max(0, settings.autoHide)
422
+ : 2500;
423
+ }
424
+ configure();
425
+ // item, canPrev and canNext follow index, count, the list and loop.
88
426
  function updateState(update) {
89
- state = { ...state, ...update };
427
+ const next = { ...state, ...update };
428
+ const many = next.count > 1;
429
+ state = {
430
+ ...next,
431
+ item: sources[next.index],
432
+ canPrev: many && (loop || next.index > 0),
433
+ canNext: many && (loop || next.index < next.count - 1),
434
+ };
90
435
  }
91
436
  function publish(update) {
92
437
  updateState(update);
93
438
  if (state.isOpen === notifiedState.isOpen &&
94
439
  state.isClosing === notifiedState.isClosing &&
440
+ state.isAnimating === notifiedState.isAnimating &&
95
441
  state.index === notifiedState.index &&
96
442
  state.count === notifiedState.count &&
443
+ state.item === notifiedState.item &&
444
+ state.canPrev === notifiedState.canPrev &&
445
+ state.canNext === notifiedState.canNext &&
446
+ state.isPlaying === notifiedState.isPlaying &&
447
+ state.chrome === notifiedState.chrome &&
97
448
  state.zoom.scale === notifiedState.zoom.scale &&
98
449
  state.zoom.x === notifiedState.zoom.x &&
99
450
  state.zoom.y === notifiedState.zoom.y)
100
451
  return;
101
452
  notifiedState = state;
102
- options.onChange?.(state);
103
453
  for (const listener of listeners)
104
454
  listener(state);
455
+ for (const slot of session?.slots ?? [])
456
+ slot.update?.(state);
105
457
  }
106
- function view(s) {
107
- const rect = s.viewport.getBoundingClientRect();
458
+ function emit(type, s, { cancelable = true, nextIndex, } = {}) {
459
+ let prevented = false;
460
+ const event = {
461
+ type,
462
+ index: state.index,
463
+ slide: s?.slides[state.index] ?? null,
464
+ };
465
+ if (type === "beforechange")
466
+ Object.defineProperty(event, "nextIndex", {
467
+ value: nextIndex,
468
+ enumerable: true,
469
+ });
470
+ if (type === "beforeclose")
471
+ Object.defineProperties(event, {
472
+ cancelable: { value: cancelable, enumerable: true },
473
+ defaultPrevented: { get: () => prevented, enumerable: true },
474
+ preventDefault: {
475
+ value: () => {
476
+ prevented = cancelable;
477
+ },
478
+ },
479
+ });
480
+ for (const listener of [...(handlers.get(type) ?? [])])
481
+ listener(event);
482
+ return prevented;
483
+ }
484
+ function syncAnimating(s) {
485
+ if (session !== s)
486
+ return;
487
+ const busy = s.animations.size > 0 || Boolean(s.fade) || Boolean(s.motion);
488
+ if (busy !== state.isAnimating)
489
+ publish({ isAnimating: busy });
490
+ }
491
+ function prefersReducedMotion(s) {
492
+ return Boolean(s.dialog.ownerDocument.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
493
+ }
494
+ function setPhase(s, phase) {
495
+ s.phase = phase;
496
+ s.dialog.dataset.phase = phase;
497
+ holdSlideshow(s, "phase", phase !== "open");
498
+ }
499
+ function slideshowRuns(s) {
500
+ return (session === s &&
501
+ !state.isClosing &&
502
+ !s.pauses.size &&
503
+ items.length > 1 &&
504
+ !s.dialog.ownerDocument.hidden);
505
+ }
506
+ // The wait keeps what it ran before a pause, so a pause only delays the next photo.
507
+ function scheduleSlideshow(s) {
508
+ const show = s.slideshow;
509
+ if (!show)
510
+ return;
108
511
  const win = s.dialog.ownerDocument.defaultView;
512
+ const now = win?.performance.now() ?? 0;
513
+ if (show.since !== undefined)
514
+ show.waited += now - show.since;
515
+ clearTimeout(show.timer);
516
+ if (show.frame !== undefined)
517
+ win?.cancelAnimationFrame(show.frame);
518
+ show.timer = show.frame = undefined;
519
+ const runs = slideshowRuns(s);
520
+ show.since = runs ? now : undefined;
521
+ if (!runs || !win)
522
+ return;
523
+ show.timer = setTimeout(() => advanceSlideshow(s), Math.max(0, show.interval - show.waited));
524
+ if (prefersReducedMotion(s))
525
+ return;
526
+ const tick = () => {
527
+ const since = show.since;
528
+ if (since === undefined)
529
+ return;
530
+ s.slideshowButton?.style.setProperty("--re-lightbox-slideshow-progress", String(Math.min(1, (show.waited + win.performance.now() - since) / show.interval)));
531
+ show.frame = win.requestAnimationFrame(tick);
532
+ };
533
+ tick();
534
+ }
535
+ function holdSlideshow(s, reason, isHeld) {
536
+ if (s.pauses.has(reason) === isHeld)
537
+ return;
538
+ if (isHeld)
539
+ s.pauses.add(reason);
540
+ else
541
+ s.pauses.delete(reason);
542
+ scheduleSlideshow(s);
543
+ }
544
+ function restartSlideshow(s) {
545
+ const show = s.slideshow;
546
+ if (!show)
547
+ return;
548
+ show.waited = 0;
549
+ show.since = undefined;
550
+ s.slideshowButton?.style.setProperty("--re-lightbox-slideshow-progress", "0");
551
+ scheduleSlideshow(s);
552
+ }
553
+ function advanceSlideshow(s) {
554
+ if (session !== s || !s.slideshow)
555
+ return;
556
+ if (s.pointers.size) {
557
+ restartSlideshow(s);
558
+ return;
559
+ }
560
+ if (looping() || state.index < items.length - 1)
561
+ step(1);
562
+ else
563
+ goTo(0);
564
+ restartSlideshow(s);
565
+ }
566
+ function toggleSlideshow(s, on = !s.slideshow) {
567
+ const button = s.slideshowButton;
568
+ if (on === Boolean(s.slideshow))
569
+ return;
570
+ const show = s.slideshow;
571
+ if (show) {
572
+ clearTimeout(show.timer);
573
+ if (show.frame !== undefined)
574
+ s.dialog.ownerDocument.defaultView?.cancelAnimationFrame(show.frame);
575
+ s.slideshow = undefined;
576
+ s.slideshowButton?.style.removeProperty("--re-lightbox-slideshow-progress");
577
+ }
578
+ else {
579
+ const interval = settings.slideshow?.interval;
580
+ s.slideshow = {
581
+ interval: interval !== undefined && Number.isFinite(interval) && interval > 0
582
+ ? interval
583
+ : 4000,
584
+ waited: 0,
585
+ };
586
+ restartSlideshow(s);
587
+ }
588
+ if (on)
589
+ s.dialog.dataset.slideshow = "playing";
590
+ else
591
+ delete s.dialog.dataset.slideshow;
592
+ if (session === s)
593
+ publish({ isPlaying: on });
594
+ else
595
+ updateState({ isPlaying: on });
596
+ if (!button)
597
+ return;
598
+ button.setAttribute("aria-label", on ? s.strings.slideshowStop : s.strings.slideshowStart);
599
+ showStateIcon(button, "slideshow", "slideshowPause", on);
600
+ }
601
+ // A CSS easing list passes CSS.supports but makes animate() throw, so the check asks the same parser animate() uses.
602
+ function easing(value, win) {
603
+ const Effect = win?.KeyframeEffect;
604
+ if (!value || !Effect)
605
+ return FLIGHT_EASE;
606
+ try {
607
+ new Effect(null, null, { easing: value });
608
+ return value;
609
+ }
610
+ catch {
611
+ return FLIGHT_EASE;
612
+ }
613
+ }
614
+ function readTiming(s) {
615
+ const style = s.dialog.ownerDocument.defaultView?.getComputedStyle(s.dialog);
616
+ const read = (name) => style?.getPropertyValue(name) ?? "";
617
+ s.timing = {
618
+ open: milliseconds(read("--re-lightbox-open-duration"), OPEN_DURATION),
619
+ close: milliseconds(read("--re-lightbox-close-duration"), CLOSE_DURATION),
620
+ zoom: milliseconds(read("--re-lightbox-zoom-duration"), ZOOM_DURATION),
621
+ fade: milliseconds(read("--re-lightbox-fade-duration"), FADE_DURATION),
622
+ ease: easing(read("--re-lightbox-ease").trim(), s.dialog.ownerDocument.defaultView),
623
+ };
624
+ }
625
+ function controlInUse(s) {
626
+ const active = s.dialog.ownerDocument.activeElement;
627
+ return s.chromeRoots.some((root) => {
628
+ if (s.chrome.lastPointerIsMouse && root.matches(":hover"))
629
+ return true;
630
+ if (!isElement(active) || active === s.openingFocus)
631
+ return false;
632
+ if (!root.contains(active))
633
+ return false;
634
+ try {
635
+ return active.matches(":focus-visible");
636
+ }
637
+ catch {
638
+ return true;
639
+ }
640
+ });
641
+ }
642
+ function applyChrome(s, model, notify = true) {
643
+ s.chrome = model;
644
+ clearTimeout(s.chromeTimer);
645
+ s.chromeTimer =
646
+ model.timer && autoHide !== false
647
+ ? setTimeout(() => chromeInput(s, { type: "idle" }), autoHide)
648
+ : undefined;
649
+ if (s.dialog.dataset.chrome !== model.chrome)
650
+ s.dialog.dataset.chrome = model.chrome;
651
+ if (state.chrome === model.chrome)
652
+ return;
653
+ if (notify)
654
+ publish({ chrome: model.chrome });
655
+ else
656
+ updateState({ chrome: model.chrome });
657
+ }
658
+ function chromeInput(s, input, notify = true) {
659
+ if (session !== s)
660
+ return;
661
+ const hides = input.type === "idle" ||
662
+ input.type === "tap" ||
663
+ input.type === "zoom" ||
664
+ input.type === "pinch";
665
+ applyChrome(s, stepChrome(s.chrome, input, hides && controlInUse(s)), notify);
666
+ }
667
+ function looping() {
668
+ return loop && items.length > 1;
669
+ }
670
+ // The carousel's change events come from the viewer's own moves here, so they are ignored.
671
+ function quietly(move) {
672
+ const syncing = syncingCarousel;
673
+ syncingCarousel = true;
674
+ try {
675
+ move();
676
+ }
677
+ finally {
678
+ syncingCarousel = syncing;
679
+ }
680
+ }
681
+ const shownIcons = new WeakMap();
682
+ function showControlIcon(button, name) {
683
+ if (shownIcons.get(button) === name)
684
+ return;
685
+ shownIcons.set(button, name);
686
+ const own = settings.icons?.[name]?.();
687
+ if (own)
688
+ button.replaceChildren(own);
689
+ else
690
+ showIcon(button, builtInIcons[name]);
691
+ }
692
+ // A given first icon stays in the second state unless the second one is given too.
693
+ function showStateIcon(button, first, second, on) {
694
+ const icons = settings.icons;
695
+ showControlIcon(button, on && (icons?.[second] || !icons?.[first]) ? second : first);
696
+ }
697
+ function lastIndex() {
698
+ return clamp(state.index, 0, Math.max(0, items.length - 1));
699
+ }
700
+ function wrap(index) {
701
+ return ((index % items.length) + items.length) % items.length;
702
+ }
703
+ function originOf(index) {
704
+ return resolveOrigin(items[index]?.origin);
705
+ }
706
+ function rendered(element) {
707
+ if (!element.isConnected || element.checkVisibility?.() === false)
708
+ return undefined;
709
+ const rect = element.getBoundingClientRect();
710
+ return rect.width > 0 && rect.height > 0 ? rect : undefined;
711
+ }
712
+ function measure(s) {
713
+ const rect = s.viewport.getBoundingClientRect();
714
+ const win = s.viewport.ownerDocument.defaultView;
715
+ const space = Number.parseFloat(win?.getComputedStyle(s.paddingProbe).paddingLeft ?? "");
716
+ padding = Number.isFinite(space) ? Math.max(0, space) : PADDING;
717
+ const room = Number.parseFloat(win?.getComputedStyle(s.paddingProbe).height ?? "");
718
+ const width = rect.width || win?.innerWidth || 1;
719
+ const height = rect.height || win?.innerHeight || 1;
720
+ const strip = s.thumbStrip?.getBoundingClientRect();
721
+ const layout = strip?.width && strip.height ? s.dialog.dataset.thumbnails : undefined;
722
+ const rtl = s.viewport.matches(":dir(rtl)");
723
+ const inset = { left: 0, right: 0, bottom: 0 };
724
+ if (strip && layout === "bottom")
725
+ inset.bottom = Math.max(0, rect.bottom - strip.top);
726
+ else if (strip && layout === "side" && rtl)
727
+ inset.left = Math.max(0, strip.right - rect.left);
728
+ else if (strip && layout === "side")
729
+ inset.right = Math.max(0, rect.right - strip.left);
730
+ const kept = {
731
+ left: 0,
732
+ right: 0,
733
+ bottom: Number.isFinite(room) ? room : 0,
734
+ };
735
+ const aside = s.aside && rendered(s.aside);
736
+ if (aside) {
737
+ const above = width * Math.max(0, aside.top - rect.top);
738
+ const before = height * Math.max(0, aside.left - rect.left);
739
+ const after = height * Math.max(0, rect.right - aside.right);
740
+ if (above >= before && above >= after)
741
+ kept.bottom = Math.max(kept.bottom, rect.bottom - aside.top);
742
+ else if (after > before)
743
+ kept.left = Math.max(0, aside.right - rect.left);
744
+ else
745
+ kept.right = Math.max(0, rect.right - aside.left);
746
+ }
747
+ s.room = kept;
748
+ inset.left = Math.max(inset.left, kept.left);
749
+ inset.right = Math.max(inset.right, kept.right);
750
+ inset.bottom = Math.max(inset.bottom, kept.bottom);
751
+ s.inset = inset;
752
+ s.viewport.style.setProperty("--re-lightbox-thumbnails-room", `0px ${inset.right}px ${inset.bottom}px ${inset.left}px`);
753
+ s.box = {
754
+ left: rect.left + inset.left,
755
+ top: rect.top,
756
+ width: width - inset.left - inset.right,
757
+ height: height - inset.bottom,
758
+ };
759
+ s.area = {
760
+ width,
761
+ height,
762
+ x: (inset.right - inset.left) / 2,
763
+ y: inset.bottom / 2,
764
+ };
765
+ }
766
+ function view(s) {
767
+ return s.box;
768
+ }
769
+ function area(s, scale) {
770
+ return scale > 1 ? s.area : s.box;
771
+ }
772
+ function bound(s, zoom) {
773
+ return boundZoom(zoom, fit(state.index, s), area(s, zoom.scale));
774
+ }
775
+ function tileImage(index) {
776
+ const origin = originOf(index);
777
+ return origin?.localName === "img"
778
+ ? origin
779
+ : origin?.querySelector("img");
780
+ }
781
+ function previewOf(index) {
782
+ const tile = tileImage(index);
783
+ return tile?.complete && tile.naturalWidth
784
+ ? tile.currentSrc || tile.src
785
+ : items[index].previewSrc;
786
+ }
787
+ function filling(aspect, s) {
788
+ const { width, height } = view(s);
109
789
  return {
110
- width: rect.width || win?.innerWidth || 1,
111
- height: rect.height || win?.innerHeight || 1,
790
+ width: Math.max(width, height * aspect),
791
+ height: Math.max(height, width / aspect),
112
792
  };
113
793
  }
794
+ // Before the file arrives, the shown preview or the tile gives only the proportions, since its
795
+ // pixels are the tile's and not the file's; a player has no pixels to stop at. Both fill the screen.
114
796
  function imageSize(index, s) {
115
797
  const item = items[index];
116
- const image = s.loaded.get(index)?.image;
117
- return {
118
- width: item.width || image?.naturalWidth || view(s).width,
119
- height: item.height || image?.naturalHeight || view(s).height,
120
- };
798
+ if (item.width && item.height)
799
+ return { width: item.width, height: item.height };
800
+ if (item.type)
801
+ return filling(s.loaded.get(index)?.media?.mounted?.aspect || 16 / 9, s);
802
+ for (const image of [s.loaded.get(index)?.image, tileImage(index)])
803
+ if (image?.naturalWidth && image.naturalHeight)
804
+ return filling(image.naturalWidth / image.naturalHeight, s);
805
+ return view(s);
806
+ }
807
+ function tall(index, s) {
808
+ if (items[index].type)
809
+ return false;
810
+ return shapeOf(imageSize(index, s), view(s), padding) === "tall";
121
811
  }
122
812
  function fit(index, s) {
123
- return contain(imageSize(index, s), view(s), padding);
813
+ // A player leaves 24px at each side for a swipe that pages past it.
814
+ return (tall(index, s) ? widthFit : contain)(imageSize(index, s), view(s), items[index].type ? Math.max(padding, 24) : padding);
815
+ }
816
+ function restZoom(s, index) {
817
+ const zoom = tall(index, s)
818
+ ? { scale: 1, x: 0, y: panRange(1, fit(index, s), view(s)).y.max }
819
+ : { ...identity };
820
+ s.rest = zoom;
821
+ return zoom;
822
+ }
823
+ function limits(s, index = state.index) {
824
+ const item = items[index];
825
+ const entry = s.loaded.get(index);
826
+ if (entry?.status === "failed" || item?.type !== undefined)
827
+ return { min: 1, max: 1, tap: 1 };
828
+ return zoomLimits({
829
+ fileWidth: largestWidth(item?.srcset) ?? entry?.natural ?? item?.width,
830
+ image: imageSize(index, s),
831
+ viewport: view(s),
832
+ zoomed: s.area,
833
+ padding,
834
+ svg: Boolean(item?.src &&
835
+ formatOf(item.src, s.dialog.ownerDocument.baseURI) === "svg"),
836
+ maxZoom: settings.maxZoom,
837
+ tapZoom: settings.tapZoom ?? 2.5,
838
+ });
124
839
  }
125
- function applyZoom(s) {
840
+ function applyZoom(s, notify = true) {
126
841
  const frame = s.loaded.get(state.index)?.frame;
127
- if (frame)
128
- frame.style.transform = `translate(${state.zoom.x}px, ${state.zoom.y}px) scale(${state.zoom.scale})`;
129
- syncingCarousel = true;
130
- s.carousel.setEnabled(state.zoom.scale <= 1);
131
- syncingCarousel = false;
842
+ const range = limits(s);
843
+ if (s.phase !== "dragging") {
844
+ if (frame)
845
+ frame.style.transform = zoomTransform(state.zoom);
846
+ quietly(() => s.carousel.setEnabled(state.zoom.scale <= 1 &&
847
+ state.zoom.scale >= range.min - 1e-3 &&
848
+ s.gesture?.axis !== "pan" &&
849
+ s.pointers.size < 2 &&
850
+ items.length > 1));
851
+ }
852
+ const zoomable = range.max > 1 || range.min < 1;
853
+ const clickable = String(zoomable && (settings.imageClick ?? "zoom") === "zoom");
854
+ if (s.dialog.dataset.zoomable !== clickable)
855
+ s.dialog.dataset.zoomable = clickable;
856
+ const hidden = !zoomable && state.zoom.scale <= 1;
857
+ const zoomButton = s.zoomButton;
858
+ if (zoomButton && zoomButton.hidden !== hidden) {
859
+ if (hidden && s.dialog.ownerDocument.activeElement === zoomButton)
860
+ s.viewport.focus({ preventScroll: true });
861
+ zoomButton.hidden = hidden;
862
+ }
132
863
  s.viewport.style.touchAction = state.zoom.scale > 1 ? "none" : "pan-x";
133
- s.zoomButton.setAttribute("aria-label", state.zoom.scale > 1 ? "Zoom out" : "Zoom in");
134
- s.zoomButton.setAttribute("aria-pressed", String(state.zoom.scale > 1));
135
- if (!options.icons?.zoom)
136
- s.zoomButton.textContent = state.zoom.scale > 1 ? "−" : "+";
864
+ const out = range.tap < 1 ? state.zoom.scale >= 1 : state.zoom.scale > 1;
865
+ zoomButton?.setAttribute("aria-label", out ? s.strings.zoomOut : s.strings.zoomIn);
866
+ zoomButton?.setAttribute("aria-pressed", String(state.zoom.scale > 1));
867
+ if (zoomButton)
868
+ showStateIcon(zoomButton, "zoom", "zoomOut", out);
137
869
  s.dialog.dataset.zoomed = String(state.zoom.scale > 1);
870
+ s.dialog.dataset.zoom = out ? "out" : "in";
871
+ if (s.watchedScale !== state.zoom.scale) {
872
+ s.watchedScale = state.zoom.scale;
873
+ clearTimeout(s.sharpTimer);
874
+ s.sharpTimer = setTimeout(() => sharpen(s), ZOOM_IDLE);
875
+ }
876
+ if (s.zoomed !== state.zoom.scale > 1) {
877
+ s.zoomed = state.zoom.scale > 1;
878
+ const active = s.dialog.ownerDocument.activeElement;
879
+ if (active &&
880
+ active !== s.viewport &&
881
+ s.dialog.contains(active) &&
882
+ ((s.zoomed &&
883
+ !active.closest(".re-lightbox-zoom, .re-lightbox-close")) ||
884
+ active.checkVisibility?.() === false))
885
+ s.viewport.focus({ preventScroll: true });
886
+ chromeInput(s, { type: s.zoomed ? "zoom" : "unzoom" }, notify);
887
+ holdSlideshow(s, "zoom", s.zoomed);
888
+ }
138
889
  }
139
890
  function restoreOrigin(s) {
140
891
  if (!s.hiddenOrigin)
@@ -144,51 +895,189 @@ export function createLightbox(options = {}) {
144
895
  }
145
896
  function hideOrigin(s) {
146
897
  restoreOrigin(s);
147
- const origin = items[state.index]?.origin;
898
+ const origin = originOf(state.index);
148
899
  if (!origin?.isConnected)
149
900
  return;
150
901
  s.hiddenOrigin = { element: origin, visibility: origin.style.visibility };
151
902
  origin.style.visibility = "hidden";
152
903
  }
153
- function animate(s, node, frames, duration) {
154
- const reduced = s.dialog.ownerDocument.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
155
- if (reduced || duration <= 0 || typeof node.animate !== "function")
904
+ function animate(s, node, frames, duration, easing = ZOOM_EASE) {
905
+ if (duration <= 0 || typeof node.animate !== "function")
156
906
  return Promise.resolve();
907
+ const animation = node.animate(frames, {
908
+ duration,
909
+ easing,
910
+ fill: "both",
911
+ });
157
912
  return new Promise((resolve) => {
158
- const animation = node.animate(frames, {
159
- duration,
160
- easing: "cubic-bezier(.16,1,.3,1)",
161
- fill: "both",
162
- });
163
913
  s.animations.add(animation);
914
+ syncAnimating(s);
164
915
  let settled = false;
165
- const finish = () => {
916
+ const finish = (landed = false) => {
166
917
  if (settled)
167
918
  return;
168
919
  settled = true;
169
920
  clearTimeout(timer);
170
921
  s.animations.delete(animation);
171
922
  s.finishAnimations.delete(finish);
923
+ syncAnimating(s);
172
924
  // commitStyles throws on an element that is no longer rendered, such
173
925
  // as one inside a dialog the browser already closed.
174
926
  try {
175
- if (node.isConnected)
927
+ if (landed)
928
+ Object.assign(node.style, frames.at(-1));
929
+ else if (node.isConnected)
176
930
  animation.commitStyles?.();
177
931
  }
178
932
  catch { }
179
933
  animation.cancel();
180
934
  resolve();
181
935
  };
182
- const timer = setTimeout(finish, duration + 80);
936
+ // A timeline that has not advanced by the deadline still lands the last keyframe. It is
937
+ // written directly, since WebKit commits the first keyframe of an animation that never got a frame.
938
+ // The deadline counts from the animation's start, so a busy main thread does not cut it short,
939
+ // and waits while a visible document has yet to start it.
940
+ let elapsed = -1;
941
+ const deadline = () => {
942
+ const time = Number(animation.currentTime);
943
+ if (animation.pending &&
944
+ node.ownerDocument.visibilityState === "visible")
945
+ timer = setTimeout(deadline, duration + 80);
946
+ else if (animation.startTime === null ||
947
+ !(time > elapsed) ||
948
+ time >= duration)
949
+ finish(true);
950
+ else {
951
+ elapsed = time;
952
+ timer = setTimeout(deadline, duration - time + 80);
953
+ }
954
+ };
955
+ let timer = setTimeout(deadline, duration + 80);
183
956
  s.finishAnimations.add(finish);
184
- void animation.finished.then(finish, finish);
957
+ void animation.finished.then(() => finish(), () => finish());
185
958
  });
186
959
  }
187
- function cancelAnimations(s) {
960
+ function cancelAnimations(s, landed = false) {
961
+ freezeZoom(s);
188
962
  for (const finish of [...s.finishAnimations])
189
- finish();
963
+ finish(landed);
964
+ }
965
+ function liveZoom(s) {
966
+ const motion = s.zoomMotion;
967
+ if (!motion)
968
+ return state.zoom;
969
+ const progress = motion.animation.effect?.getComputedTiming().progress;
970
+ const t = typeof progress === "number" ? progress : 1;
971
+ const { from, to } = motion;
972
+ return {
973
+ scale: from.scale + (to.scale - from.scale) * t,
974
+ x: from.x + (to.x - from.x) * t,
975
+ y: from.y + (to.y - from.y) * t,
976
+ };
190
977
  }
191
- function morph(s, closing) {
978
+ function freezeZoom(s) {
979
+ const motion = s.zoomMotion;
980
+ if (!motion)
981
+ return;
982
+ const zoom = liveZoom(s);
983
+ s.zoomMotion = undefined;
984
+ s.animations.delete(motion.animation);
985
+ motion.animation.cancel();
986
+ updateState({ zoom });
987
+ applyZoom(s, false);
988
+ }
989
+ function moveZoom(s, to, duration, ease) {
990
+ const from = liveZoom(s);
991
+ const previous = s.zoomMotion;
992
+ s.zoomMotion = undefined;
993
+ if (previous) {
994
+ s.animations.delete(previous.animation);
995
+ previous.animation.cancel();
996
+ }
997
+ updateState({ zoom: to });
998
+ applyZoom(s, false);
999
+ const frame = s.loaded.get(state.index)?.frame;
1000
+ if (!frame ||
1001
+ duration <= 0 ||
1002
+ sameZoom(from, to) ||
1003
+ typeof frame.animate !== "function")
1004
+ return;
1005
+ const animation = frame.animate([{ transform: zoomTransform(from) }, { transform: zoomTransform(to) }], { duration, easing: ease });
1006
+ const motion = { from, to, animation };
1007
+ s.zoomMotion = motion;
1008
+ s.animations.add(animation);
1009
+ syncAnimating(s);
1010
+ const done = () => {
1011
+ if (s.zoomMotion === motion)
1012
+ s.zoomMotion = undefined;
1013
+ s.animations.delete(animation);
1014
+ syncAnimating(s);
1015
+ };
1016
+ void animation.finished.then(done, done);
1017
+ }
1018
+ function zoomDuration(s) {
1019
+ return prefersReducedMotion(s) ? 0 : s.timing.zoom;
1020
+ }
1021
+ function nudgeDuration(s) {
1022
+ return Math.min(zoomDuration(s), NUDGE_DURATION);
1023
+ }
1024
+ function flightDuration(s, closing) {
1025
+ const duration = closing ? s.timing.close : s.timing.open;
1026
+ return prefersReducedMotion(s)
1027
+ ? Math.min(duration, REDUCED_DURATION)
1028
+ : duration;
1029
+ }
1030
+ function flight(s, closing, landing = false) {
1031
+ const from = closing
1032
+ ? s.dialog.ownerDocument.defaultView?.getComputedStyle(s.backdrop)
1033
+ .opacity || "1"
1034
+ : "0";
1035
+ const flying = Promise.all([
1036
+ morph(s, closing, landing),
1037
+ animate(s, s.backdrop, [{ opacity: from }, { opacity: closing ? 0 : 1 }], flightDuration(s, closing), s.timing.ease),
1038
+ ]);
1039
+ // The timeline's time stands still within a task, so a start taken from it would skip the
1040
+ // work this close already did; the time origin is the document timeline's zero.
1041
+ const now = s.dialog.ownerDocument.defaultView?.performance.now();
1042
+ if (closing && now !== undefined)
1043
+ for (const animation of s.animations)
1044
+ animation.startTime = now;
1045
+ return flying;
1046
+ }
1047
+ function landingCopy(s, image, origin, rect, size, box) {
1048
+ const doc = s.dialog.ownerDocument;
1049
+ const src = image.currentSrc || image.src;
1050
+ if (origin.ownerDocument !== doc ||
1051
+ !origin.parentNode ||
1052
+ !src ||
1053
+ !image.complete ||
1054
+ !image.naturalWidth)
1055
+ return undefined;
1056
+ const copy = doc.createElement("img");
1057
+ copy.className = "re-lightbox-landing";
1058
+ copy.alt = "";
1059
+ copy.setAttribute("aria-hidden", "true");
1060
+ copy.draggable = false;
1061
+ copy.src = src;
1062
+ const reset = "position:absolute;left:0;top:0;right:auto;bottom:auto;display:block;box-sizing:content-box;min-width:0;min-height:0;max-width:none;max-height:none;margin:0;padding:0;border:0;border-radius:0;box-shadow:none;outline:0;opacity:1;visibility:visible;filter:none;transition:none;animation:none;transform:none;translate:none;rotate:none;scale:none;pointer-events:none";
1063
+ copy.style.cssText = `${reset};width:${size.width}px;height:${size.height}px;object-fit:fill;transform-origin:center`;
1064
+ // The box covers the tile and clips the copy, so the full-size copy adds no scrollable
1065
+ // overflow to a strip whose tiles have no position of their own.
1066
+ const holder = doc.createElement("span");
1067
+ holder.setAttribute("aria-hidden", "true");
1068
+ holder.style.cssText = `${reset};width:${rect.width}px;height:${rect.height}px;overflow:hidden;overflow:clip`;
1069
+ holder.append(copy);
1070
+ // A carousel of bare children would count a copy beside its slide as one more slide.
1071
+ const parent = origin.parentElement;
1072
+ (parent?.classList.contains("re-carousel") ? parent : origin).after(holder);
1073
+ const at = holder.getBoundingClientRect();
1074
+ holder.style.left = `${rect.left - at.left}px`;
1075
+ holder.style.top = `${rect.top - at.top}px`;
1076
+ copy.style.left = `${box.left + (box.width - size.width) / 2 - rect.left}px`;
1077
+ copy.style.top = `${box.top + (box.height - size.height) / 2 - rect.top}px`;
1078
+ return { holder, copy };
1079
+ }
1080
+ function morph(s, closing, landing) {
192
1081
  const entry = s.loaded.get(state.index);
193
1082
  const item = items[state.index];
194
1083
  if (!entry || !item)
@@ -200,36 +1089,57 @@ export function createLightbox(options = {}) {
200
1089
  const resting = entry.frame.style.transform || "translate(0px, 0px) scale(1)";
201
1090
  const live = {
202
1091
  transform: current.transform === "none" ? resting : current.transform || resting,
203
- clipPath: current.clipPath || "inset(0px round 0px)",
1092
+ clipPath: current.clipPath && current.clipPath !== "none"
1093
+ ? current.clipPath
1094
+ : "inset(0px round 0px)",
204
1095
  opacity: current.opacity || "1",
205
1096
  };
206
- const origin = item.origin;
207
- const rect = origin?.isConnected
208
- ? origin.getBoundingClientRect()
209
- : undefined;
210
- const viewport = view(s);
1097
+ const origin = originOf(state.index);
1098
+ const rect = origin ? rendered(origin) : undefined;
1099
+ const box = s.viewport.getBoundingClientRect();
1100
+ let slide = s.slides[state.index]?.getBoundingClientRect();
1101
+ const shift = slide ? slide.left - box.left : 0;
1102
+ // Disabling ends a held mouse drag and a touch fling, and keeps the strip still while it flies.
1103
+ if (closing)
1104
+ quietly(() => s.carousel.setEnabled(false));
1105
+ if (closing && Math.abs(shift) > 1) {
1106
+ quietly(() => {
1107
+ s.carousel.setEnabled(true);
1108
+ s.carousel.goTo(state.index, "instant");
1109
+ s.carousel.setEnabled(false);
1110
+ });
1111
+ slide = s.slides[state.index]?.getBoundingClientRect();
1112
+ if (slide && Math.abs(slide.left - box.left) <= 1)
1113
+ live.transform = `translate(${shift}px, 0px) ${live.transform}`;
1114
+ }
211
1115
  const size = fit(state.index, s);
212
- const duration = Math.max(0, options.duration ?? 280);
213
- const visible = rect &&
214
- rect.width > 0 &&
215
- rect.height > 0 &&
216
- rect.bottom > 0 &&
217
- rect.right > 0 &&
218
- rect.top < viewport.height &&
219
- rect.left < viewport.width;
220
- if (!visible || !origin) {
1116
+ const duration = flightDuration(s, closing);
1117
+ const ease = s.timing.ease;
1118
+ if (prefersReducedMotion(s))
1119
+ return animate(s, entry.frame, closing
1120
+ ? [{ opacity: live.opacity }, { opacity: 0 }]
1121
+ : [{ opacity: 0 }, { opacity: 1 }], duration, "ease");
1122
+ const visible = origin &&
1123
+ rect &&
1124
+ slide &&
1125
+ Math.abs(slide.left - box.left) <= 1 &&
1126
+ Math.abs(slide.right - box.right) <= 1 &&
1127
+ onScreen(origin, rect, win);
1128
+ if (!visible ||
1129
+ !origin ||
1130
+ (item.type && !entry.image.getAttribute("src"))) {
221
1131
  return animate(s, entry.frame, closing
222
1132
  ? [
223
1133
  live,
224
1134
  {
225
- transform: `${live.transform} scale(.96)`,
1135
+ transform: `${live.transform} scale(.94)`,
226
1136
  opacity: 0,
227
1137
  },
228
1138
  ]
229
1139
  : [
230
- { transform: "scale(.96)", opacity: 0 },
1140
+ { transform: `${resting} scale(.94)`, opacity: 0 },
231
1141
  { transform: resting, opacity: 1 },
232
- ], duration);
1142
+ ], duration, ease);
233
1143
  }
234
1144
  const style = win.getComputedStyle(origin);
235
1145
  const positions = style.objectPosition
@@ -248,12 +1158,20 @@ export function createLightbox(options = {}) {
248
1158
  ? crop.top
249
1159
  : (rect.height - crop.height) / 2;
250
1160
  const scale = crop.width / size.width;
251
- const x = rect.left + left + crop.width / 2 - viewport.width / 2;
252
- const y = rect.top + top + crop.height / 2 - viewport.height / 2;
253
- const radius = (Number.parseFloat(style.borderRadius) || 0) / scale;
1161
+ const room = {
1162
+ left: box.left + s.inset.left,
1163
+ top: box.top,
1164
+ width: box.width - s.inset.left - s.inset.right,
1165
+ height: box.height - s.inset.bottom,
1166
+ };
1167
+ const x = rect.left + left + crop.width / 2 - room.left - room.width / 2;
1168
+ const y = rect.top + top + crop.height / 2 - room.top - room.height / 2;
1169
+ const radius = corners(origin, rect, win)
1170
+ .map((corner) => `${corner / scale}px`)
1171
+ .join(" ");
254
1172
  const clipped = {
255
1173
  transform: `translate(${x}px, ${y}px) scale(${scale})`,
256
- clipPath: `inset(${Math.max(0, -top / scale)}px ${Math.max(0, (crop.width + left - rect.width) / scale)}px ${Math.max(0, (crop.height + top - rect.height) / scale)}px ${Math.max(0, -left / scale)}px round ${radius}px)`,
1174
+ clipPath: `inset(${Math.max(0, -top / scale)}px ${Math.max(0, (crop.width + left - rect.width) / scale)}px ${Math.max(0, (crop.height + top - rect.height) / scale)}px ${Math.max(0, -left / scale)}px round ${radius})`,
257
1175
  opacity: 1,
258
1176
  };
259
1177
  const expanded = {
@@ -261,31 +1179,140 @@ export function createLightbox(options = {}) {
261
1179
  clipPath: "inset(0px round 0px)",
262
1180
  opacity: 1,
263
1181
  };
264
- return animate(s, entry.frame, closing ? [live, clipped] : [clipped, expanded], duration);
1182
+ if (!closing)
1183
+ return animate(s, entry.frame, [clipped, expanded], duration, ease);
1184
+ const made = landing && duration > 0
1185
+ ? landingCopy(s, entry.image, origin, rect, size, room)
1186
+ : undefined;
1187
+ if (!made)
1188
+ return animate(s, entry.frame, [live, clipped], duration, ease);
1189
+ const { holder, copy } = made;
1190
+ s.landing = holder;
1191
+ return Promise.all([
1192
+ animate(s, entry.frame, [
1193
+ { transform: live.transform, clipPath: live.clipPath },
1194
+ { transform: clipped.transform, clipPath: clipped.clipPath },
1195
+ ], duration, ease),
1196
+ animate(s, entry.frame, [
1197
+ { opacity: live.opacity },
1198
+ { opacity: live.opacity, offset: LANDING_HANDOFF },
1199
+ { opacity: 0 },
1200
+ ], duration, "linear"),
1201
+ animate(s, copy, [{ ...live, opacity: 1 }, clipped], duration, ease),
1202
+ ]);
1203
+ }
1204
+ // A zoom asks for a larger file only once its scale has rested, through sizes.
1205
+ function requestSizes(s) {
1206
+ for (const [index, entry] of s.loaded) {
1207
+ const item = items[index];
1208
+ if (item.type !== undefined ||
1209
+ !item.srcset ||
1210
+ !entry.loader ||
1211
+ entry.status === "failed")
1212
+ continue;
1213
+ const width = fit(index, s).width;
1214
+ const scale = index === state.index ? Math.min(s.sharpScale, state.zoom.scale) : 1;
1215
+ const sizes = scale > 1
1216
+ ? `${Math.ceil(width * scale)}px`
1217
+ : item.sizes || `${Math.ceil(width)}px`;
1218
+ if (entry.loader.getAttribute("sizes") !== sizes)
1219
+ entry.loader.setAttribute("sizes", sizes);
1220
+ }
1221
+ }
1222
+ function sharpen(s) {
1223
+ s.sharpTimer = undefined;
1224
+ if (session !== s)
1225
+ return;
1226
+ const apply = () => {
1227
+ if (session !== s)
1228
+ return;
1229
+ s.sharpScale = state.zoom.scale;
1230
+ requestSizes(s);
1231
+ };
1232
+ const win = s.dialog.ownerDocument.defaultView;
1233
+ if (state.zoom.scale > 1 || !win?.requestIdleCallback)
1234
+ apply();
1235
+ else
1236
+ win.requestIdleCallback(apply);
265
1237
  }
266
1238
  function layout(s) {
1239
+ const resting = s.rest !== undefined && sameZoom(state.zoom, s.rest);
267
1240
  for (const [index, entry] of s.loaded) {
268
1241
  const size = fit(index, s);
269
1242
  entry.frame.style.width = `${size.width}px`;
270
1243
  entry.frame.style.height = `${size.height}px`;
271
1244
  }
272
- if (state.zoom.scale > 1)
273
- publish({ zoom: boundZoom(state.zoom, fit(state.index, s), view(s)) });
1245
+ requestSizes(s);
1246
+ if (resting)
1247
+ publish({ zoom: restZoom(s, state.index) });
1248
+ else if (state.zoom.scale > 1) {
1249
+ const scale = Math.min(state.zoom.scale, limits(s).max);
1250
+ publish({
1251
+ zoom: scale > 1 ? bound(s, { ...state.zoom, scale }) : { ...identity },
1252
+ });
1253
+ }
274
1254
  applyZoom(s);
275
1255
  }
1256
+ function resized(s) {
1257
+ s.resizeFrame = undefined;
1258
+ if (session !== s)
1259
+ return;
1260
+ cancelAnimations(s, true);
1261
+ clearStands(s);
1262
+ const before = state.zoom;
1263
+ const from = fit(state.index, s);
1264
+ const resting = s.rest !== undefined && sameZoom(before, s.rest);
1265
+ measure(s);
1266
+ s.pinned = undefined;
1267
+ s.thumbCenters = undefined;
1268
+ if (resting)
1269
+ updateState({ zoom: restZoom(s, state.index) });
1270
+ else {
1271
+ const to = fit(state.index, s);
1272
+ const range = limits(s);
1273
+ const scale = clamp(before.scale, range.min, range.max);
1274
+ const ratio = scale / before.scale;
1275
+ updateState({
1276
+ zoom: bound(s, {
1277
+ scale,
1278
+ x: ((before.x * to.width) / from.width) * ratio,
1279
+ y: ((before.y * to.height) / from.height) * ratio,
1280
+ }),
1281
+ });
1282
+ }
1283
+ layout(s);
1284
+ quietly(() => {
1285
+ s.carousel.setEnabled(true);
1286
+ s.carousel.refresh();
1287
+ s.carousel.goTo(state.index, "instant");
1288
+ });
1289
+ applyZoom(s, false);
1290
+ ringThumb(s, false);
1291
+ if (!sameZoom(before, state.zoom))
1292
+ publish({});
1293
+ }
276
1294
  function visibleRange(s) {
1295
+ const count = s.slides.length;
1296
+ const size = count ? s.slides[0].getBoundingClientRect().width : 0;
1297
+ if (!size)
1298
+ return [];
277
1299
  const width = s.viewport.clientWidth;
278
- const rtl = s.dialog.ownerDocument.defaultView?.getComputedStyle(s.viewport)
279
- .direction === "rtl";
280
1300
  const start = Math.abs(s.viewport.scrollLeft);
281
- return s.slides.flatMap((slide, index) => {
282
- const left = rtl
283
- ? s.viewport.scrollWidth - slide.offsetLeft - slide.offsetWidth
284
- : slide.offsetLeft;
285
- return left < start + width - 1 && left + slide.offsetWidth > start + 1
286
- ? [index]
287
- : [];
288
- });
1301
+ const looped = s.carousel.getState().isLooping;
1302
+ const visible = new Set();
1303
+ for (let k = Math.floor((start + 1) / size) - 1; k * size < start + width - 1; k++) {
1304
+ if (k * size + size <= start + 1)
1305
+ continue;
1306
+ if (looped && k >= 0 && k < 3 * count)
1307
+ visible.add(wrap(k));
1308
+ else if (k >= 0 && k < count)
1309
+ visible.add(k);
1310
+ }
1311
+ return [...visible].sort((a, b) => a - b);
1312
+ }
1313
+ function distanceTo(index) {
1314
+ const gap = Math.abs(index - state.index);
1315
+ return looping() ? Math.min(gap, items.length - gap) : gap;
289
1316
  }
290
1317
  // Unloads images outside the preload window, except those still on screen
291
1318
  // while the strip travels.
@@ -294,17 +1321,146 @@ export function createLightbox(options = {}) {
294
1321
  return;
295
1322
  const visible = visibleRange(s);
296
1323
  for (const [index, entry] of s.loaded) {
297
- if (Math.abs(index - state.index) <= preload || visible.includes(index))
1324
+ if (distanceTo(index) <= preload ||
1325
+ visible.includes(index) ||
1326
+ index === s.leaving ||
1327
+ s.stands?.moved.has(s.slides[index]))
298
1328
  continue;
299
1329
  entry.cancel();
300
1330
  entry.frame.remove();
301
1331
  s.loaded.delete(index);
302
1332
  }
303
1333
  }
1334
+ // The current image loads first; the neighbors wait until it has decoded or failed, and
1335
+ // Save-Data keeps them at their previews.
1336
+ function startLoads(s) {
1337
+ if (s.scrubbing)
1338
+ return;
1339
+ const current = s.loaded.get(state.index);
1340
+ if (current?.status === "idle")
1341
+ current.load("high");
1342
+ if (current?.status === "loading")
1343
+ return;
1344
+ const connection = s.dialog.ownerDocument.defaultView?.navigator?.connection;
1345
+ if (connection?.saveData)
1346
+ return;
1347
+ const order = [];
1348
+ for (let step = 1; step <= preload; step++)
1349
+ for (const side of [s.heading, -s.heading]) {
1350
+ const index = state.index + side * step;
1351
+ order.push(looping() ? wrap(index) : index);
1352
+ }
1353
+ for (const index of [...order, ...s.loaded.keys()]) {
1354
+ const entry = s.loaded.get(index);
1355
+ if (entry?.status === "idle")
1356
+ entry.load("low");
1357
+ }
1358
+ }
1359
+ function spin(s, frame) {
1360
+ const doc = s.dialog.ownerDocument;
1361
+ const status = doc.createElement("span");
1362
+ status.className = "re-lightbox-loading";
1363
+ status.setAttribute("role", "status");
1364
+ status.setAttribute("aria-label", s.strings.loading);
1365
+ const canvas = doc.createElement("canvas");
1366
+ canvas.setAttribute("aria-hidden", "true");
1367
+ status.append(canvas);
1368
+ frame.append(status);
1369
+ let dots;
1370
+ try {
1371
+ dots = createThinkingDots(canvas, { size: SPINNER_SIZE });
1372
+ }
1373
+ catch { }
1374
+ return () => {
1375
+ dots?.destroy();
1376
+ status.remove();
1377
+ };
1378
+ }
1379
+ // A player mounts in its own layer above the poster, which stays under it.
1380
+ function mountMedia(s, index, entry) {
1381
+ const media = entry.media;
1382
+ const item = items[index];
1383
+ if (!media || media.mounted || session !== s || item.type === undefined)
1384
+ return;
1385
+ const doc = s.dialog.ownerDocument;
1386
+ const holder = doc.createElement("div");
1387
+ holder.className = "re-lightbox-media";
1388
+ entry.frame.append(holder);
1389
+ const abort = new AbortController();
1390
+ const mounted = media.content.mount(holder, {
1391
+ item,
1392
+ index,
1393
+ signal: abort.signal,
1394
+ autoplay: s.autoplay,
1395
+ });
1396
+ media.abort = abort;
1397
+ media.mounted = mounted;
1398
+ media.holder = holder;
1399
+ if (mounted.interactive) {
1400
+ holder.dataset.lightboxInteractive = "";
1401
+ holder.dataset.carouselNoDrag = "";
1402
+ }
1403
+ if (mounted.ready) {
1404
+ entry.frame.dataset.loading = "true";
1405
+ const wait = setTimeout(() => {
1406
+ stop = spin(s, entry.frame);
1407
+ }, LOADING_DELAY);
1408
+ let stop = () => clearTimeout(wait);
1409
+ const settle = () => {
1410
+ if (media.abort !== abort)
1411
+ return;
1412
+ stop();
1413
+ entry.frame.removeAttribute("data-loading");
1414
+ };
1415
+ abort.signal.addEventListener("abort", () => stop());
1416
+ void mounted.ready.then(settle, settle);
1417
+ }
1418
+ layout(s);
1419
+ if (index === state.index && !s.flying && !state.isClosing)
1420
+ mounted.resume?.();
1421
+ if (index === state.index)
1422
+ holdForMedia(s);
1423
+ }
1424
+ function holdForMedia(s) {
1425
+ const media = s.loaded.get(state.index)?.media;
1426
+ const player = media?.holder?.querySelector("video, audio");
1427
+ holdSlideshow(s, "media", Boolean(media?.mounted) &&
1428
+ (player
1429
+ ? !player.paused && !player.ended
1430
+ : media?.content.type === "embed"));
1431
+ }
1432
+ function swapHeld(s) {
1433
+ for (const entry of s.loaded.values()) {
1434
+ const commit = entry.commit;
1435
+ entry.commit = undefined;
1436
+ commit?.();
1437
+ }
1438
+ }
1439
+ function unmountMedia(entry) {
1440
+ const media = entry.media;
1441
+ if (!media?.mounted)
1442
+ return;
1443
+ const { mounted, abort } = media;
1444
+ media.mounted = media.abort = media.holder = undefined;
1445
+ abort?.abort();
1446
+ mounted.unmount();
1447
+ entry.frame.querySelector(":scope > .re-lightbox-media")?.remove();
1448
+ entry.frame.removeAttribute("data-loading");
1449
+ }
1450
+ function pauseMedia(entry) {
1451
+ const mounted = entry?.media?.mounted;
1452
+ if (!entry || !mounted)
1453
+ return;
1454
+ if (mounted.pause)
1455
+ mounted.pause();
1456
+ else
1457
+ unmountMedia(entry);
1458
+ }
304
1459
  function loadSlides(s) {
305
1460
  trimSlides(s);
306
- for (let index = Math.max(0, state.index - preload); index <= Math.min(items.length - 1, state.index + preload); index++) {
307
- if (s.loaded.has(index))
1461
+ for (let step = -preload; step <= preload; step++) {
1462
+ const index = looping() ? wrap(state.index + step) : state.index + step;
1463
+ if (index < 0 || index >= items.length || s.loaded.has(index))
308
1464
  continue;
309
1465
  const item = items[index];
310
1466
  const doc = s.dialog.ownerDocument;
@@ -315,156 +1471,861 @@ export function createLightbox(options = {}) {
315
1471
  image.alt = item.alt || "";
316
1472
  image.draggable = false;
317
1473
  image.decoding = "async";
318
- const loader = doc.createElement("img");
319
- loader.decoding = "async";
1474
+ if (item.type !== undefined) {
1475
+ const content = settings.content?.find((module) => module.type === item.type);
1476
+ if (!content)
1477
+ continue;
1478
+ frame.dataset.media = content.type;
1479
+ const poster = previewOf(index);
1480
+ if (poster)
1481
+ image.src = poster;
1482
+ frame.append(image);
1483
+ s.slides[index].append(frame);
1484
+ const entry = {
1485
+ frame,
1486
+ image,
1487
+ media: { content },
1488
+ status: "settled",
1489
+ load: () => { },
1490
+ cancel: () => {
1491
+ unmountMedia(entry);
1492
+ image.removeAttribute("src");
1493
+ },
1494
+ };
1495
+ s.loaded.set(index, entry);
1496
+ // A poster flies open like a photo, and its player mounts once the flight lands.
1497
+ if (!(s.flying && index === state.index && poster))
1498
+ mountMedia(s, index, entry);
1499
+ continue;
1500
+ }
320
1501
  let alive = true;
321
1502
  let cleanup;
1503
+ let wait;
1504
+ let spinner;
322
1505
  frame.append(image);
323
1506
  s.slides[index].append(frame);
324
- const swap = () => {
1507
+ const stopWaiting = () => {
1508
+ clearTimeout(wait);
1509
+ wait = undefined;
1510
+ spinner?.();
1511
+ spinner = undefined;
1512
+ };
1513
+ const showSpinner = () => {
1514
+ if (alive && session === s)
1515
+ spinner = spin(s, frame);
1516
+ };
1517
+ const fetcher = (url, init) => (doc.defaultView ?? globalThis).fetch(url, init);
1518
+ let shown = "";
1519
+ const display = (url) => {
1520
+ shown = url;
1521
+ image.src = url;
1522
+ const mark = (format) => {
1523
+ if (format && format !== "opaque")
1524
+ frame.dataset.transparent = "true";
1525
+ else
1526
+ delete frame.dataset.transparent;
1527
+ };
1528
+ const format = formatOf(url, doc.baseURI);
1529
+ mark(format);
1530
+ if (!format && /^blob:/i.test(url))
1531
+ void lookupFormat(url, doc.baseURI, fetcher).then((found) => {
1532
+ if (alive && shown === url)
1533
+ mark(found);
1534
+ });
1535
+ };
1536
+ const show = (source, width, size) => {
325
1537
  if (!alive || session !== s)
326
1538
  return;
327
- if (!item.width && loader.naturalWidth)
328
- item.width = loader.naturalWidth;
329
- if (!item.height && loader.naturalHeight)
330
- item.height = loader.naturalHeight;
331
- image.src = item.src;
1539
+ if (entry.natural !== undefined && width <= entry.natural)
1540
+ return;
1541
+ entry.natural = width;
1542
+ const before = index === state.index && !s.flying ? fit(index, s) : undefined;
1543
+ const shape = size ??
1544
+ (source.naturalWidth && source.naturalHeight
1545
+ ? { width: source.naturalWidth, height: source.naturalHeight }
1546
+ : undefined);
1547
+ if (shape) {
1548
+ const ratio = shape.height / shape.width;
1549
+ if (!item.width)
1550
+ item.width = item.height
1551
+ ? Math.round(item.height / ratio)
1552
+ : size
1553
+ ? Math.round(size.width)
1554
+ : (largestWidth(item.srcset) ?? width);
1555
+ if (!item.height)
1556
+ item.height = Math.round(item.width * ratio);
1557
+ }
1558
+ display(source.currentSrc || source.src);
332
1559
  frame.removeAttribute("data-loading");
333
1560
  layout(s);
1561
+ const after = before && fit(index, s);
1562
+ if (before &&
1563
+ after &&
1564
+ (Math.abs(after.width - before.width) > 0.5 ||
1565
+ Math.abs(after.height - before.height) > 0.5))
1566
+ void animate(s, frame, [
1567
+ { width: `${before.width}px`, height: `${before.height}px` },
1568
+ { width: `${after.width}px`, height: `${after.height}px` },
1569
+ ], nudgeDuration(s));
334
1570
  };
335
1571
  const failed = () => {
336
- if (!alive)
337
- return;
338
1572
  frame.removeAttribute("data-loading");
339
1573
  frame.dataset.error = "true";
340
- if (!item.previewSrc) {
341
- const error = doc.createElement("span");
342
- error.className = "re-lightbox-error";
343
- error.setAttribute("role", "status");
344
- error.textContent = "Image could not be loaded.";
345
- frame.append(error);
346
- }
1574
+ const error = doc.createElement("div");
1575
+ error.className = "re-lightbox-error";
1576
+ error.setAttribute("role", "status");
1577
+ const message = doc.createElement("p");
1578
+ message.textContent = s.strings.error;
1579
+ const retry = doc.createElement("button");
1580
+ retry.type = "button";
1581
+ retry.className = "re-lightbox-retry";
1582
+ retry.textContent = s.strings.retry;
1583
+ retry.addEventListener("click", () => {
1584
+ if (doc.activeElement === retry)
1585
+ s.viewport.focus({ preventScroll: true });
1586
+ error.remove();
1587
+ delete frame.dataset.error;
1588
+ frame.dataset.loading = "true";
1589
+ entry.load(index === state.index ? "high" : "low");
1590
+ }, { signal: s.abort.signal });
1591
+ error.append(message, retry);
1592
+ frame.append(error);
347
1593
  };
348
- loader.onload = () => {
349
- if (typeof loader.decode === "function")
350
- void loader.decode().then(swap, failed);
351
- else
352
- swap();
1594
+ const load = (priority) => {
1595
+ const loader = doc.createElement("img");
1596
+ loader.decoding = "async";
1597
+ loader.setAttribute("fetchpriority", priority);
1598
+ entry.loader = loader;
1599
+ entry.status = "loading";
1600
+ wait = setTimeout(showSpinner, LOADING_DELAY);
1601
+ const settle = (status) => {
1602
+ if (entry.status !== "loading")
1603
+ return;
1604
+ entry.status = status;
1605
+ stopWaiting();
1606
+ startLoads(s);
1607
+ };
1608
+ loader.onload = () => {
1609
+ const source = loader.currentSrc || loader.src;
1610
+ const width = fileWidth(loader, item.srcset, doc.baseURI);
1611
+ const current = () => alive &&
1612
+ session === s &&
1613
+ entry.loader === loader &&
1614
+ entry.status !== "failed" &&
1615
+ (loader.currentSrc || loader.src) === source;
1616
+ const ready = (size) => {
1617
+ if (!current())
1618
+ return;
1619
+ const held = s.flying ||
1620
+ (s.pointers.size > 0 && s.loaded.get(state.index) === entry);
1621
+ if (held && image.hasAttribute("src"))
1622
+ entry.commit = () => show(loader, width, size);
1623
+ else
1624
+ show(loader, width, size);
1625
+ settle("settled");
1626
+ };
1627
+ // An SVG shows once its own size is read, since browsers decode a viewBox-only file at most 300px wide.
1628
+ const decoded = () => {
1629
+ if (!current())
1630
+ return;
1631
+ const sized = Boolean(item.width && item.height);
1632
+ const format = formatOf(source, doc.baseURI);
1633
+ if (format && (format !== "svg" || sized))
1634
+ return ready();
1635
+ // Only an SVG without its own size decodes at 300x150, so a CDN URL without an
1636
+ // extension asks for no type.
1637
+ if (!format &&
1638
+ !/^blob:/i.test(source) &&
1639
+ (loader.naturalWidth !== 300 || loader.naturalHeight !== 150))
1640
+ return ready();
1641
+ void lookupFormat(source, doc.baseURI, fetcher)
1642
+ .then((found) => found === "svg" && !sized
1643
+ ? svgSize(source, fetcher, new (doc.defaultView ?? globalThis).DOMParser())
1644
+ : undefined)
1645
+ .then(ready, () => ready());
1646
+ };
1647
+ if (typeof loader.decode !== "function")
1648
+ decoded();
1649
+ else
1650
+ void loader.decode().then(decoded, () => {
1651
+ if (loader.complete && loader.naturalWidth)
1652
+ decoded();
1653
+ });
1654
+ };
1655
+ loader.onerror = () => {
1656
+ if (!alive || session !== s || entry.loader !== loader)
1657
+ return;
1658
+ if (entry.status !== "loading")
1659
+ return;
1660
+ failed();
1661
+ settle("failed");
1662
+ if (!state.isClosing)
1663
+ layout(s);
1664
+ };
1665
+ if (item.srcset) {
1666
+ loader.srcset = item.srcset;
1667
+ requestSizes(s);
1668
+ }
1669
+ loader.src = item.src;
353
1670
  };
354
- loader.onerror = failed;
355
- if (item.previewSrc)
356
- image.src = item.previewSrc;
1671
+ const preview = previewOf(index);
1672
+ if (preview)
1673
+ display(preview);
357
1674
  frame.dataset.loading = "true";
358
- s.loaded.set(index, {
1675
+ const entry = {
359
1676
  frame,
360
1677
  image,
361
- loader,
1678
+ status: "idle",
1679
+ load,
362
1680
  cancel: () => {
363
1681
  alive = false;
364
- loader.onload = null;
365
- loader.onerror = null;
366
- loader.removeAttribute("src");
1682
+ stopWaiting();
1683
+ entry.commit = undefined;
1684
+ if (entry.loader) {
1685
+ entry.loader.onload = null;
1686
+ entry.loader.onerror = null;
1687
+ entry.loader.removeAttribute("srcset");
1688
+ entry.loader.removeAttribute("src");
1689
+ }
367
1690
  image.removeAttribute("src");
368
1691
  cleanup?.();
369
1692
  },
370
- });
371
- loader.src = item.src;
372
- if (loader.complete && loader.naturalWidth)
373
- loader.onload(new Event("load"));
374
- cleanup = options.renderContent?.({
375
- item,
1693
+ };
1694
+ s.loaded.set(index, entry);
1695
+ cleanup = settings.renderContent?.({
1696
+ item: item,
376
1697
  index,
377
1698
  container: frame,
378
1699
  image,
379
1700
  });
380
1701
  }
381
1702
  layout(s);
1703
+ startLoads(s);
1704
+ }
1705
+ let notifyingBeforeChange = false;
1706
+ function notifyBeforeChange(s, nextIndex) {
1707
+ if (notifyingBeforeChange)
1708
+ return true;
1709
+ const previousIndex = state.index;
1710
+ const previousItems = items;
1711
+ notifyingBeforeChange = true;
1712
+ try {
1713
+ emit("beforechange", s, { nextIndex });
1714
+ }
1715
+ finally {
1716
+ notifyingBeforeChange = false;
1717
+ }
1718
+ return (session === s &&
1719
+ !state.isClosing &&
1720
+ state.index === previousIndex &&
1721
+ items === previousItems);
382
1722
  }
383
- function activeChanged(s, index) {
1723
+ function activeChanged(s, index, report = true) {
384
1724
  if (session !== s || state.index === index || state.isClosing)
385
1725
  return;
1726
+ if (!notifyBeforeChange(s, index))
1727
+ return;
386
1728
  cancelAnimations(s);
1729
+ s.backdrop.style.opacity = "";
387
1730
  const old = s.loaded.get(state.index);
388
1731
  if (old) {
389
1732
  old.frame.style.transform = "";
390
1733
  old.frame.style.clipPath = "";
391
1734
  old.frame.style.opacity = "";
392
1735
  }
393
- publish({ index, zoom: { ...identity } });
394
- update(s);
1736
+ pauseMedia(old);
1737
+ const gap = index - state.index;
1738
+ const forward = looping() && Math.abs(gap) > items.length / 2 ? gap < 0 : gap > 0;
1739
+ s.pinned = undefined;
1740
+ s.heading = forward ? 1 : -1;
1741
+ s.paged = true;
1742
+ publish({ index, zoom: restZoom(s, index) });
1743
+ update(s, forward ? 1 : -1);
1744
+ arrived(s, index, report);
395
1745
  }
396
- function update(s) {
397
- loadSlides(s);
398
- hideOrigin(s);
399
- s.counter.value = `${state.index + 1} / ${items.length}`;
400
- s.caption.textContent = items[state.index].caption || "";
401
- s.prev.disabled = state.index === 0;
402
- s.next.disabled = state.index === items.length - 1;
403
- for (const [index, slide] of s.slides.entries()) {
404
- slide.inert = index !== state.index;
405
- slide.setAttribute("aria-hidden", String(index !== state.index));
406
- }
407
- for (const [index, thumb] of s.thumbs.entries())
408
- thumb.setAttribute("aria-current", String(index === state.index));
409
- applyZoom(s);
1746
+ function arrived(s, index, report = true) {
1747
+ const entry = s.loaded.get(index);
1748
+ if (entry?.media?.mounted)
1749
+ entry.media.mounted.resume?.();
1750
+ else if (entry)
1751
+ mountMedia(s, index, entry);
1752
+ holdForMedia(s);
1753
+ restartSlideshow(s);
1754
+ if (report)
1755
+ announce(s, index);
410
1756
  }
411
- function teardown(s) {
412
- if (session === s)
413
- session = undefined;
414
- s.abort.abort();
415
- clearTimeout(s.wheelTimer);
416
- finishFade(s, false);
417
- cancelAnimations(s);
418
- s.carousel.destroy();
1757
+ function announce(s, index) {
1758
+ s.reported = index;
1759
+ s.status.textContent = s.strings.slide(index, items.length, items[index]?.caption || undefined);
1760
+ emit("change", s);
1761
+ }
1762
+ function showCaption(s, text, direction) {
1763
+ const caption = s.caption;
1764
+ if (text === s.captionText)
1765
+ return;
1766
+ s.captionText = text;
1767
+ const shown = caption.textContent ?? "";
1768
+ const win = caption.ownerDocument.defaultView;
1769
+ const opacity = () => Number(win?.getComputedStyle(caption).opacity ?? 1);
1770
+ const running = s.captionFade;
1771
+ const at = running ? opacity() : 1;
1772
+ const drift = running?.drift.effect?.getComputedTiming().progress;
1773
+ const side = running
1774
+ ? running.from + (running.to - running.from) * (drift ?? 1)
1775
+ : 0;
1776
+ running?.fade.cancel();
1777
+ running?.drift.cancel();
1778
+ s.captionFade = undefined;
1779
+ const duration = s.timing.fade;
1780
+ if (direction === 0 ||
1781
+ duration <= 0 ||
1782
+ prefersReducedMotion(s) ||
1783
+ typeof caption.animate !== "function") {
1784
+ caption.textContent = text;
1785
+ return;
1786
+ }
1787
+ const rest = opacity();
1788
+ const share = running && rest > 0 ? Math.min(at / rest, 1) : 1;
1789
+ const run = (frames, from, to, timing) => {
1790
+ const fade = caption.animate(frames, timing);
1791
+ const drift = caption.animate([from, to].map((shift) => ({ translate: `0 ${shift * 0.4}em` })), { ...timing, composite: "add" });
1792
+ s.captionFade = { fade, drift, from, to };
1793
+ return fade;
1794
+ };
1795
+ const fadeIn = (start, from, share = 0) => {
1796
+ const fade = run([{ opacity: start, offset: 0 }], from, 0, {
1797
+ duration: duration * 0.55 * (1 - share),
1798
+ easing: "ease-out",
1799
+ });
1800
+ fade.onfinish = () => {
1801
+ if (s.captionFade?.fade === fade)
1802
+ s.captionFade = undefined;
1803
+ };
1804
+ };
1805
+ if (text === shown)
1806
+ return fadeIn(running ? at : rest, side, share);
1807
+ if (!shown) {
1808
+ caption.textContent = text;
1809
+ return fadeIn(0, direction);
1810
+ }
1811
+ const fadeOut = run([{ opacity: running ? at : rest }, { opacity: 0 }], side, -direction, {
1812
+ duration: duration * 0.45 * share,
1813
+ easing: "ease-in",
1814
+ fill: "forwards",
1815
+ });
1816
+ fadeOut.onfinish = () => {
1817
+ const current = s.captionFade;
1818
+ if (current?.fade !== fadeOut)
1819
+ return;
1820
+ s.captionFade = undefined;
1821
+ caption.textContent = text;
1822
+ if (text)
1823
+ fadeIn(0, direction);
1824
+ current.fade.cancel();
1825
+ current.drift.cancel();
1826
+ };
1827
+ }
1828
+ function renderCounter(s, direction) {
1829
+ const text = s.strings.counter(state.index, items.length);
1830
+ if (text === s.counterText)
1831
+ return;
1832
+ s.counterText = text;
1833
+ for (const counter of s.counters)
1834
+ drawCounter(s, counter, text, direction);
1835
+ }
1836
+ function drawCounter(s, counter, text, direction) {
1837
+ const doc = s.dialog.ownerDocument;
1838
+ const parts = text.match(/\p{Nd}+(?:[^\p{Nd}\s]\p{Nd}+)*|\P{Nd}+/gu) ?? [];
1839
+ const kind = (part) => /\p{Nd}/u.test(part)
1840
+ ? "re-lightbox-counter-number"
1841
+ : "re-lightbox-counter-text";
1842
+ let nodes = [...counter.children];
1843
+ if (nodes.length !== parts.length ||
1844
+ nodes.some((node, index) => node.className !== kind(parts[index]))) {
1845
+ nodes = parts.map((part) => {
1846
+ const node = doc.createElement("span");
1847
+ node.className = kind(part);
1848
+ return node;
1849
+ });
1850
+ counter.replaceChildren(...nodes);
1851
+ }
1852
+ const roll = direction !== 0 &&
1853
+ !prefersReducedMotion(s) &&
1854
+ typeof counter.animate === "function";
1855
+ for (const [index, node] of nodes.entries()) {
1856
+ const part = parts[index];
1857
+ if (node.className === "re-lightbox-counter-text") {
1858
+ if (node.textContent !== part)
1859
+ node.textContent = part;
1860
+ continue;
1861
+ }
1862
+ const digits = [...part];
1863
+ const cells = [...node.children];
1864
+ while (cells.length > digits.length)
1865
+ cells.shift()?.remove();
1866
+ while (cells.length < digits.length) {
1867
+ const cell = doc.createElement("span");
1868
+ cell.className = "re-lightbox-counter-cell";
1869
+ cell.append(doc.createElement("span"));
1870
+ node.prepend(cell);
1871
+ cells.unshift(cell);
1872
+ }
1873
+ for (const [at, cell] of cells.entries()) {
1874
+ const digit = digits[at];
1875
+ const current = cell.lastElementChild;
1876
+ if (current.textContent === digit)
1877
+ continue;
1878
+ while (cell.firstElementChild !== current)
1879
+ cell.firstElementChild?.remove();
1880
+ const previous = current.textContent;
1881
+ if (!roll || !previous) {
1882
+ current.textContent = digit;
1883
+ continue;
1884
+ }
1885
+ const incoming = doc.createElement("span");
1886
+ incoming.textContent = digit;
1887
+ cell.append(incoming);
1888
+ current.dataset.char = previous;
1889
+ current.textContent = "";
1890
+ const timing = { duration: 200, easing: "ease" };
1891
+ incoming.animate([{ translate: `0 ${direction * 100}%` }, { translate: "0 0" }], timing);
1892
+ const leaving = current.animate([{ translate: "0 0" }, { translate: `0 ${direction * -100}%` }], { ...timing, fill: "forwards" });
1893
+ leaving.onfinish = () => current.remove();
1894
+ }
1895
+ }
1896
+ }
1897
+ function update(s, direction = 0) {
1898
+ loadSlides(s);
1899
+ hideOrigin(s);
1900
+ renderCounter(s, direction);
1901
+ const item = items[state.index];
1902
+ showCaption(s, item.caption || "", direction);
1903
+ const single = items.length < 2;
1904
+ for (const control of [s.prev, s.next, ...s.counters, s.slideshowButton])
1905
+ if (control)
1906
+ control.hidden = single;
1907
+ if (s.prev)
1908
+ s.prev.disabled = !looping() && state.index === 0;
1909
+ if (s.next)
1910
+ s.next.disabled = !looping() && state.index === items.length - 1;
1911
+ if (single)
1912
+ toggleSlideshow(s, false);
1913
+ if (s.download) {
1914
+ const href = item.type === undefined ? largestSource(item.srcset, item.src) : "";
1915
+ let file = false;
1916
+ if (href)
1917
+ try {
1918
+ const url = new URL(href, s.dialog.ownerDocument.baseURI);
1919
+ file =
1920
+ /^(https?|blob):$/.test(url.protocol) ||
1921
+ /^data:image\/(png|jpeg|gif|webp|avif)[;,]/i.test(url.href);
1922
+ }
1923
+ catch { }
1924
+ s.download.hidden = !file;
1925
+ if (file)
1926
+ s.download.setAttribute("href", href);
1927
+ else
1928
+ s.download.removeAttribute("href");
1929
+ }
1930
+ const mark = (index, current) => {
1931
+ const slide = s.slides[index];
1932
+ if (slide) {
1933
+ slide.inert = !current;
1934
+ slide.setAttribute("aria-hidden", String(!current));
1935
+ }
1936
+ s.thumbs[index]?.setAttribute("aria-current", String(current));
1937
+ };
1938
+ if (s.marked === undefined) {
1939
+ for (const [index, slide] of s.slides.entries()) {
1940
+ mark(index, index === state.index);
1941
+ slide.setAttribute("aria-label", s.strings.slide(index, items.length));
1942
+ }
1943
+ }
1944
+ else if (s.marked !== state.index) {
1945
+ mark(s.marked, false);
1946
+ mark(state.index, true);
1947
+ }
1948
+ s.marked = state.index;
1949
+ if (!s.thumbStrip?.contains(s.dialog.ownerDocument.activeElement))
1950
+ rove(s, state.index);
1951
+ centerThumb(s);
1952
+ ringThumb(s, true);
1953
+ applyZoom(s);
1954
+ }
1955
+ function rove(s, index) {
1956
+ if (s.roving === index)
1957
+ return;
1958
+ if (s.thumbs[s.roving])
1959
+ s.thumbs[s.roving].tabIndex = -1;
1960
+ if (s.thumbs[index])
1961
+ s.thumbs[index].tabIndex = 0;
1962
+ s.roving = index;
1963
+ }
1964
+ function inRoom(s, x, y) {
1965
+ const rect = s.viewport.getBoundingClientRect();
1966
+ return (x < rect.left + s.room.left ||
1967
+ x > rect.right - s.room.right ||
1968
+ y > rect.bottom - s.room.bottom);
1969
+ }
1970
+ function overThumbnails(s, x, y) {
1971
+ const first = s.thumbs[0]?.getBoundingClientRect();
1972
+ const last = s.thumbs.at(-1)?.getBoundingClientRect();
1973
+ const strip = s.thumbStrip?.getBoundingClientRect();
1974
+ if (!first || !last || !strip?.width)
1975
+ return false;
1976
+ return (x >= Math.max(strip.left, Math.min(first.left, last.left)) &&
1977
+ x <= Math.min(strip.right, Math.max(first.right, last.right)) &&
1978
+ y >= Math.max(strip.top, Math.min(first.top, last.top)) &&
1979
+ y <= Math.min(strip.bottom, Math.max(first.bottom, last.bottom)));
1980
+ }
1981
+ // The bottom strip is a carousel that centers the thumbnail; the side column has no carousel
1982
+ // axis, so it scrolls the same way natively.
1983
+ function centerThumb(s) {
1984
+ const strip = s.thumbStrip;
1985
+ const thumb = s.thumbs[state.index];
1986
+ if (!strip || !thumb || s.centeredThumb === state.index)
1987
+ return;
1988
+ const behavior = s.centeredThumb < 0 || prefersReducedMotion(s) ? "instant" : "smooth";
1989
+ s.centeredThumb = state.index;
1990
+ s.stripInput = false;
1991
+ if (s.thumbCarousel) {
1992
+ s.thumbCarousel.goTo(state.index, behavior);
1993
+ return;
1994
+ }
1995
+ strip.scrollTo({
1996
+ top: thumb.offsetTop - (strip.clientHeight - thumb.offsetHeight) / 2,
1997
+ behavior,
1998
+ });
1999
+ }
2000
+ // The ring stands over the strip's center and takes the current thumbnail's size; the
2001
+ // thumbnails scroll under it.
2002
+ function ringThumb(s, glide) {
2003
+ const ring = s.thumbRing;
2004
+ const strip = s.thumbStrip;
2005
+ const thumb = s.thumbs[state.index];
2006
+ if (!ring || !strip)
2007
+ return;
2008
+ ring.hidden = !thumb;
2009
+ if (!thumb)
2010
+ return;
2011
+ const instant = !glide || !ring.style.width;
2012
+ if (instant)
2013
+ ring.style.transition = "none";
2014
+ const left = strip.offsetLeft + strip.clientLeft;
2015
+ const top = strip.offsetTop + strip.clientTop;
2016
+ if (s.dialog.dataset.thumbnails === "side") {
2017
+ ring.style.left = `${left + thumb.offsetLeft}px`;
2018
+ ring.style.top = `${top + strip.clientHeight / 2}px`;
2019
+ ring.style.bottom = "";
2020
+ }
2021
+ else {
2022
+ const parent = ring.parentElement?.clientHeight ?? 0;
2023
+ ring.style.left = `${left + strip.clientWidth / 2}px`;
2024
+ ring.style.top = "";
2025
+ ring.style.bottom = `${parent - top - thumb.offsetTop - thumb.offsetHeight}px`;
2026
+ }
2027
+ ring.style.width = `${thumb.offsetWidth}px`;
2028
+ ring.style.height = `${thumb.offsetHeight}px`;
2029
+ if (!instant)
2030
+ return;
2031
+ void ring.offsetWidth;
2032
+ ring.style.removeProperty("transition");
2033
+ }
2034
+ // A drag on the strip swaps the photo in place as each thumbnail reaches the ring, without
2035
+ // paging, and the full files wait until the strip settles.
2036
+ function scrubTo(s, index) {
2037
+ if (session !== s || state.isClosing || index === state.index)
2038
+ return;
2039
+ s.scrubbing = true;
2040
+ finishFade(s, true);
2041
+ clearStands(s);
2042
+ s.centeredThumb = index;
2043
+ quietly(() => {
2044
+ activeChanged(s, index, false);
2045
+ s.carousel.goTo(index, "instant");
2046
+ });
2047
+ trimSlides(s);
2048
+ }
2049
+ function scrubNow(s, ended = false) {
2050
+ const strip = s.thumbStrip;
2051
+ if (s.scrubFrame !== undefined)
2052
+ s.dialog.ownerDocument.defaultView?.cancelAnimationFrame(s.scrubFrame);
2053
+ s.scrubFrame = undefined;
2054
+ if (strip && (ended || s.stripInput))
2055
+ scrubTo(s, thumbUnderRing(s, strip));
2056
+ }
2057
+ // The photo the strip landed on is reported once, and focus and the tab stop follow it.
2058
+ function endScrub(s) {
2059
+ clearTimeout(s.scrubTimer);
2060
+ if (s.scrubFrame !== undefined)
2061
+ scrubNow(s, true);
2062
+ if (!s.scrubbing)
2063
+ return;
2064
+ s.scrubbing = false;
2065
+ if (session !== s)
2066
+ return;
2067
+ if (!state.isClosing && s.reported !== state.index)
2068
+ announce(s, state.index);
2069
+ rove(s, state.index);
2070
+ const thumb = s.thumbs[state.index];
2071
+ const active = s.dialog.ownerDocument.activeElement;
2072
+ if (thumb && active !== thumb && s.thumbStrip?.contains(active))
2073
+ thumb.focus({ preventScroll: true, focusVisible: false });
2074
+ startLoads(s);
2075
+ }
2076
+ function thumbCenters(s, strip, side) {
2077
+ if (s.thumbCenters)
2078
+ return s.thumbCenters;
2079
+ const box = strip.getBoundingClientRect();
2080
+ const scrolled = side ? strip.scrollTop : strip.scrollLeft;
2081
+ s.thumbCenters = s.thumbs.map((thumb) => {
2082
+ const rect = thumb.getBoundingClientRect();
2083
+ return (scrolled +
2084
+ (side
2085
+ ? rect.top + rect.height / 2 - box.top
2086
+ : rect.left + rect.width / 2 - box.left));
2087
+ });
2088
+ return s.thumbCenters;
2089
+ }
2090
+ // Walks from the current thumbnail toward the ring over positions read once per layout, so a
2091
+ // frame of scrolling reads only the strip's scroll offset.
2092
+ function thumbUnderRing(s, strip) {
2093
+ const side = s.dialog.dataset.thumbnails === "side";
2094
+ const centers = thumbCenters(s, strip, side);
2095
+ const middle = side
2096
+ ? strip.scrollTop + strip.clientHeight / 2
2097
+ : strip.scrollLeft + strip.clientWidth / 2;
2098
+ const away = (index) => index in centers
2099
+ ? Math.abs(centers[index] - middle)
2100
+ : Number.POSITIVE_INFINITY;
2101
+ let index = state.index;
2102
+ let distance = away(index);
2103
+ for (const step of [1, -1]) {
2104
+ while (away(index + step) < distance) {
2105
+ index += step;
2106
+ distance = away(index);
2107
+ }
2108
+ }
2109
+ return index;
2110
+ }
2111
+ function teardown(s) {
2112
+ if (session === s) {
2113
+ session = undefined;
2114
+ configure();
2115
+ }
2116
+ s.abort.abort();
2117
+ clearTimeout(s.wheelTimer);
2118
+ clearTimeout(s.sharpTimer);
2119
+ clearTimeout(s.chromeTimer);
2120
+ clearTimeout(s.tapTimer);
2121
+ clearTimeout(s.scrubTimer);
2122
+ const win = s.dialog.ownerDocument.defaultView;
2123
+ if (s.scrubFrame !== undefined)
2124
+ win?.cancelAnimationFrame(s.scrubFrame);
2125
+ if (s.motion)
2126
+ win?.cancelAnimationFrame(s.motion.frame);
2127
+ s.motion = undefined;
2128
+ if (s.resizeFrame !== undefined)
2129
+ win?.cancelAnimationFrame(s.resizeFrame);
2130
+ s.resizeFrame = undefined;
2131
+ finishFade(s, false);
2132
+ clearStands(s);
2133
+ cancelAnimations(s);
2134
+ toggleSlideshow(s, false);
2135
+ leaveFullscreen(s);
2136
+ s.carousel.destroy();
2137
+ s.thumbCarousel?.destroy();
419
2138
  for (const entry of s.loaded.values())
420
2139
  entry.cancel();
2140
+ for (const slot of s.slots.splice(0))
2141
+ slot.destroy?.();
421
2142
  restoreOrigin(s);
2143
+ s.landing?.remove();
2144
+ s.landing = undefined;
422
2145
  if (s.dialog.open)
423
2146
  s.dialog.close();
424
2147
  s.dialog.remove();
425
2148
  s.restoreScroll();
426
- if (s.previousFocus?.isConnected)
427
- s.previousFocus.focus({ preventScroll: true });
2149
+ const active = s.dialog.ownerDocument.activeElement;
2150
+ if (s.releasedFocus === undefined ||
2151
+ active === s.releasedFocus ||
2152
+ active === s.dialog.ownerDocument.body)
2153
+ returnFocus(s);
2154
+ if (listAfterClose) {
2155
+ ({ items, sources } = listAfterClose);
2156
+ listAfterClose = undefined;
2157
+ updateState({ count: items.length, index: lastIndex() });
2158
+ }
2159
+ }
2160
+ function leaveFullscreen(s) {
2161
+ const doc = s.dialog.ownerDocument;
2162
+ if (doc.fullscreenElement === s.stage)
2163
+ void doc.exitFullscreen().catch(() => { });
2164
+ }
2165
+ function returnFocus(s) {
2166
+ const origin = originOf(state.index);
2167
+ const tile = origin && rendered(origin) ? origin : null;
2168
+ const quiet = s.input === "pointer";
2169
+ const options = { preventScroll: true };
2170
+ if (s.input)
2171
+ options.focusVisible = !quiet;
2172
+ for (const target of [
2173
+ tile,
2174
+ tile?.closest("a[href], button"),
2175
+ s.previousFocus,
2176
+ ]) {
2177
+ if (!target?.isConnected)
2178
+ continue;
2179
+ // Firefox's dialog close already restored focus here without a ring, and focus() on the
2180
+ // focused element changes nothing.
2181
+ if (s.input === "keyboard" &&
2182
+ target.ownerDocument.activeElement === target &&
2183
+ !matches(target, ":focus-visible"))
2184
+ target.blur();
2185
+ target.focus(options);
2186
+ if (target.ownerDocument.activeElement !== target)
2187
+ continue;
2188
+ if (quiet && matches(target, ":focus-visible"))
2189
+ quietFocus(target);
2190
+ return;
2191
+ }
2192
+ }
2193
+ // Focus that still shows a ring after a pointer close, from an engine without focusVisible or
2194
+ // the dialog's own focus restore, gets an attribute the theme hides the ring by.
2195
+ function quietFocus(target) {
2196
+ const stop = new AbortController();
2197
+ const clear = () => {
2198
+ target.removeAttribute("data-re-focus-quiet");
2199
+ stop.abort();
2200
+ };
2201
+ target.setAttribute("data-re-focus-quiet", "");
2202
+ target.ownerDocument.defaultView?.addEventListener("keydown", clear, {
2203
+ capture: true,
2204
+ signal: stop.signal,
2205
+ });
2206
+ target.addEventListener("blur", clear, { signal: stop.signal });
428
2207
  }
429
2208
  function setZoom(scale, focus, notify) {
430
2209
  const s = session;
431
2210
  if (!s || state.isClosing || !Number.isFinite(scale))
432
2211
  return;
433
- const nextScale = clamp(scale, 1, maxZoom);
434
- if (nextScale > 1 && state.zoom.scale <= 1) {
435
- syncingCarousel = true;
436
- s.carousel.goTo(state.index, "instant");
437
- syncingCarousel = false;
438
- }
439
- const shouldAnimate = notify && Math.abs(nextScale - state.zoom.scale) > 0.001;
2212
+ const range = limits(s);
2213
+ const nextScale = clamp(scale, range.min, range.max);
2214
+ if (nextScale > 1 && state.zoom.scale <= 1)
2215
+ quietly(() => s.carousel.goTo(state.index, "instant"));
2216
+ const animated = notify && Math.abs(nextScale - state.zoom.scale) > 0.001;
2217
+ if (animated && s.animations.size > 0 && !s.zoomMotion)
2218
+ interruptImageMotion(s);
2219
+ if (!animated)
2220
+ freezeZoom(s);
2221
+ const zoom = bound(s, zoomAround(state.zoom, nextScale, focus));
440
2222
  const frame = s.loaded.get(state.index)?.frame;
441
- const live = frame && shouldAnimate
442
- ? s.dialog.ownerDocument.defaultView?.getComputedStyle(frame)
443
- .transform || frame.style.transform
444
- : undefined;
445
- if (shouldAnimate)
446
- cancelAnimations(s);
447
- const zoom = nextScale === 1
448
- ? { ...identity }
449
- : boundZoom(zoomAround(state.zoom, nextScale, focus), fit(state.index, s), view(s));
450
- if (notify)
451
- publish({ zoom });
452
- else
453
- updateState({ zoom });
454
- if (frame && shouldAnimate) {
2223
+ if (frame && animated) {
455
2224
  frame.style.clipPath = "";
456
2225
  frame.style.opacity = "";
457
2226
  }
458
- applyZoom(s);
459
- if (frame && live && shouldAnimate) {
460
- void animate(s, frame, [{ transform: live }, { transform: frame.style.transform }], Math.min(220, Math.max(0, options.duration ?? 280)));
461
- }
2227
+ moveZoom(s, zoom, animated ? zoomDuration(s) : 0, s.timing.ease);
2228
+ if (notify)
2229
+ publish({});
462
2230
  }
463
2231
  function zoomTo(scale, focus = { x: 0, y: 0 }) {
464
2232
  setZoom(scale, focus, true);
465
2233
  }
466
2234
  function toggleZoom(focus) {
467
- zoomTo(state.zoom.scale > 1 ? 1 : tapZoom, focus);
2235
+ const s = session;
2236
+ if (!s)
2237
+ return;
2238
+ zoomTo(Math.abs(state.zoom.scale - 1) > 1e-3 ? 1 : limits(s).tap, focus);
2239
+ }
2240
+ function panBy(s, dx, dy) {
2241
+ moveZoom(s, bound(s, { ...state.zoom, x: state.zoom.x + dx, y: state.zoom.y + dy }), nudgeDuration(s), ZOOM_EASE);
2242
+ publish({});
2243
+ }
2244
+ function keepLaps(s, slides) {
2245
+ carouselInternalsOf(s.carousel)?.keepLaps(slides);
2246
+ }
2247
+ function clearStands(s) {
2248
+ const stands = s.stands;
2249
+ if (!stands)
2250
+ return;
2251
+ s.stands = undefined;
2252
+ keepLaps(s, []);
2253
+ for (const [slide, transform] of stands.moved)
2254
+ slide.style.transform = transform;
2255
+ for (const [slide, visibility] of stands.hidden)
2256
+ slide.style.visibility = visibility;
2257
+ }
2258
+ // A distant photo pages in like the next one: the slides on screen keep their place while the
2259
+ // strip jumps to the slot beside the photo, then the strip moves one slide with the usual
2260
+ // spring. Without that slot it fades.
2261
+ function slideTo(s, from, target, forward) {
2262
+ const side = forward ? -1 : 1;
2263
+ const beside = looping() && s.carousel.getState().isLooping
2264
+ ? wrap(target + side)
2265
+ : target + side;
2266
+ if (prefersReducedMotion(s) ||
2267
+ beside < 0 ||
2268
+ beside >= items.length ||
2269
+ !s.box.width) {
2270
+ fadeTo(s, target);
2271
+ return;
2272
+ }
2273
+ const port = s.viewport.getBoundingClientRect();
2274
+ const shown = new Map();
2275
+ const candidates = new Set([
2276
+ ...(s.stands?.moved.keys() ?? []),
2277
+ ...visibleRange(s).map((index) => s.slides[index]),
2278
+ ]);
2279
+ for (const slide of candidates) {
2280
+ if (s.stands?.hidden.has(slide))
2281
+ continue;
2282
+ const rect = slide.getBoundingClientRect();
2283
+ if (rect.right > port.left + 1 && rect.left < port.right - 1)
2284
+ shown.set(slide, rect.left);
2285
+ }
2286
+ const anchor = s.slides[from];
2287
+ const anchorLeft = shown.get(anchor) ?? port.left;
2288
+ const moved = new Map(s.stands?.moved);
2289
+ const hidden = new Map(s.stands?.hidden);
2290
+ clearStands(s);
2291
+ s.carousel.goTo(beside, "instant");
2292
+ if (Math.abs(anchorLeft - port.left) > 0.5)
2293
+ s.viewport.scrollLeft -= anchorLeft - port.left;
2294
+ const arriving = s.slides[target].getBoundingClientRect();
2295
+ const stands = {
2296
+ moved: new Map(),
2297
+ hidden: new Map(),
2298
+ };
2299
+ const covered = [];
2300
+ for (const [slide, left] of shown) {
2301
+ if (slide === s.slides[target])
2302
+ continue;
2303
+ if (Math.abs(left - arriving.left) < arriving.width - 1 &&
2304
+ slide !== anchor)
2305
+ continue;
2306
+ const transform = moved.get(slide) ?? slide.style.transform;
2307
+ const natural = slide.getBoundingClientRect().left;
2308
+ if (Math.abs(left - natural) > 0.5) {
2309
+ stands.moved.set(slide, transform);
2310
+ slide.style.transform = `translateX(${left - natural}px) ${transform}`;
2311
+ }
2312
+ covered.push(slide.getBoundingClientRect());
2313
+ }
2314
+ for (const index of visibleRange(s)) {
2315
+ const slide = s.slides[index];
2316
+ if (index === target || shown.has(slide))
2317
+ continue;
2318
+ const rect = slide.getBoundingClientRect();
2319
+ if (!covered.some((cover) => rect.right > cover.left + 1 && rect.left < cover.right - 1))
2320
+ continue;
2321
+ stands.hidden.set(slide, hidden.get(slide) ?? slide.style.visibility);
2322
+ slide.style.visibility = "hidden";
2323
+ }
2324
+ if (stands.moved.size || stands.hidden.size) {
2325
+ s.stands = stands;
2326
+ keepLaps(s, [...stands.moved.keys()]);
2327
+ }
2328
+ s.carousel[forward ? "next" : "prev"]();
468
2329
  }
469
2330
  function finishFade(s, jump) {
470
2331
  const fade = s.fade;
@@ -474,6 +2335,7 @@ export function createLightbox(options = {}) {
474
2335
  fade.animation?.cancel();
475
2336
  if (jump && !fade.jumped)
476
2337
  fade.jump();
2338
+ syncAnimating(s);
477
2339
  }
478
2340
  // Distant images fade through the backdrop instead of scrolling past
479
2341
  // unloaded pages. The jump waits for the fade-out to really finish, because
@@ -485,19 +2347,19 @@ export function createLightbox(options = {}) {
485
2347
  fade.jumped = true;
486
2348
  if (session !== s)
487
2349
  return;
488
- syncingCarousel = true;
489
- s.carousel.goTo(target, "instant");
490
- syncingCarousel = false;
2350
+ quietly(() => s.carousel.goTo(target, "instant"));
491
2351
  trimSlides(s);
492
2352
  },
493
2353
  };
494
- const reduced = s.dialog.ownerDocument.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
495
- const duration = Math.min(240, Math.max(0, options.duration ?? 280));
496
- if (reduced || duration <= 0 || typeof s.viewport.animate !== "function") {
2354
+ const duration = s.timing.fade;
2355
+ if (prefersReducedMotion(s) ||
2356
+ duration <= 0 ||
2357
+ typeof s.viewport.animate !== "function") {
497
2358
  fade.jump();
498
2359
  return;
499
2360
  }
500
2361
  s.fade = fade;
2362
+ syncAnimating(s);
501
2363
  const fadeOut = s.viewport.animate([{ opacity: 1 }, { opacity: 0 }], {
502
2364
  duration: duration * 0.45,
503
2365
  easing: "ease-in",
@@ -515,26 +2377,49 @@ export function createLightbox(options = {}) {
515
2377
  fade.animation = fadeIn;
516
2378
  fadeOut.cancel();
517
2379
  const done = () => {
518
- if (s.fade === fade)
519
- s.fade = undefined;
2380
+ if (s.fade !== fade)
2381
+ return;
2382
+ s.fade = undefined;
2383
+ syncAnimating(s);
520
2384
  };
521
2385
  fadeIn.finished.then(done, done);
522
2386
  }, () => { });
523
2387
  }
524
- function goTo(index) {
2388
+ function goTo(index, direction) {
525
2389
  const s = session;
526
2390
  if (!s || state.isClosing || !Number.isFinite(index))
527
2391
  return;
528
2392
  finishFade(s, true);
529
2393
  const target = clamp(Math.floor(index), 0, items.length - 1);
530
- const far = Math.abs(target - state.index) > 1;
531
- syncingCarousel = true;
532
- activeChanged(s, target);
533
- if (!far)
534
- s.carousel.goTo(target, "smooth");
535
- syncingCarousel = false;
536
- if (far)
537
- fadeTo(s, target);
2394
+ const gap = Math.abs(target - state.index);
2395
+ const far = (looping() && s.carousel.getState().isLooping
2396
+ ? Math.min(gap, items.length - gap)
2397
+ : gap) > 1;
2398
+ const from = state.index;
2399
+ const paged = far || (s.stands !== undefined && target !== from);
2400
+ quietly(() => {
2401
+ if (paged)
2402
+ s.leaving = from;
2403
+ activeChanged(s, target);
2404
+ // A change listener that paged on owns the strip now.
2405
+ if (session !== s || state.index !== target) {
2406
+ s.leaving = undefined;
2407
+ return;
2408
+ }
2409
+ if (paged) {
2410
+ slideTo(s, from, target, direction ? direction > 0 : target > from);
2411
+ s.leaving = undefined;
2412
+ trimSlides(s);
2413
+ }
2414
+ else if (direction && looping() && s.carousel.getState().isLooping)
2415
+ s.carousel[direction > 0 ? "next" : "prev"]();
2416
+ else
2417
+ s.carousel.goTo(target, "smooth");
2418
+ });
2419
+ }
2420
+ function step(direction) {
2421
+ const index = state.index + direction;
2422
+ goTo(looping() ? wrap(index) : index, direction);
538
2423
  }
539
2424
  function isSettled(s) {
540
2425
  return visibleRange(s).length <= 1;
@@ -542,14 +2427,20 @@ export function createLightbox(options = {}) {
542
2427
  function interruptImageMotion(s) {
543
2428
  const frame = s.loaded.get(state.index)?.frame;
544
2429
  const win = s.dialog.ownerDocument.defaultView;
545
- const transform = frame && win?.getComputedStyle(frame).transform;
2430
+ const transform = frame && !s.zoomMotion && s.animations.size > 0
2431
+ ? win?.getComputedStyle(frame).transform
2432
+ : undefined;
546
2433
  cancelAnimations(s);
547
2434
  if (transform && transform !== "none" && win?.DOMMatrixReadOnly) {
548
2435
  const matrix = new win.DOMMatrixReadOnly(transform);
549
2436
  const scale = Math.hypot(matrix.a, matrix.b);
550
2437
  if (scale > 1 || state.zoom.scale > 1) {
551
2438
  updateState({
552
- zoom: boundZoom({ scale: Math.max(1, scale), x: matrix.e, y: matrix.f }, fit(state.index, s), view(s)),
2439
+ zoom: bound(s, {
2440
+ scale: Math.max(1, scale),
2441
+ x: matrix.e,
2442
+ y: matrix.f,
2443
+ }),
553
2444
  });
554
2445
  }
555
2446
  }
@@ -557,7 +2448,189 @@ export function createLightbox(options = {}) {
557
2448
  frame.style.clipPath = "";
558
2449
  frame.style.opacity = "";
559
2450
  }
2451
+ s.backdrop.style.opacity = "";
2452
+ s.dialog.style.removeProperty("--re-lightbox-chrome-opacity");
2453
+ if (s.phase !== "entering" && s.phase !== "closing")
2454
+ setPhase(s, "open");
2455
+ applyZoom(s);
2456
+ }
2457
+ function dismissDrag(s, dx, dy, half) {
2458
+ const progress = clamp(Math.abs(dy) / half, 0, 1);
2459
+ const frame = s.loaded.get(state.index)?.frame;
2460
+ const { scale, x, y } = state.zoom;
2461
+ const shrink = 1 - progress * 0.25;
2462
+ if (frame)
2463
+ frame.style.transform = `translate(${x * shrink + dx}px, ${y * shrink + dy}px) scale(${scale * shrink})`;
2464
+ s.backdrop.style.opacity = String(1 - progress);
2465
+ s.dialog.style.setProperty("--re-lightbox-chrome-opacity", String(Math.max(0, 1 - 2 * progress)));
2466
+ }
2467
+ function returnFromDismiss(s) {
2468
+ const frame = s.loaded.get(state.index)?.frame;
2469
+ const win = s.dialog.ownerDocument.defaultView;
2470
+ const transform = frame && win?.getComputedStyle(frame).transform;
2471
+ const opacity = win?.getComputedStyle(s.backdrop).opacity || "1";
2472
+ setPhase(s, "returning");
2473
+ s.backdrop.style.opacity = "";
560
2474
  applyZoom(s);
2475
+ const duration = prefersReducedMotion(s) ? 0 : s.timing.open;
2476
+ void Promise.all([
2477
+ frame && transform && transform !== "none"
2478
+ ? animate(s, frame, [{ transform }, { transform: frame.style.transform }], duration, s.timing.ease)
2479
+ : undefined,
2480
+ animate(s, s.backdrop, [{ opacity }, { opacity: 1 }], duration, s.timing.ease),
2481
+ ]).then(() => {
2482
+ if (session === s && s.phase === "returning")
2483
+ setPhase(s, "open");
2484
+ });
2485
+ }
2486
+ function settle(s, gesture, event, pinch, pinched) {
2487
+ const scale = state.zoom.scale;
2488
+ const { min, max } = limits(s);
2489
+ if (pinched && scale < PINCH_CLOSE * min && event.type === "pointerup") {
2490
+ void close();
2491
+ if (state.isClosing || session !== s)
2492
+ return;
2493
+ }
2494
+ const viewport = view(s);
2495
+ const reduced = prefersReducedMotion(s);
2496
+ let target;
2497
+ if (scale < min)
2498
+ target = bound(s, zoomAround(state.zoom, min, gesture.focus));
2499
+ else if (scale > max)
2500
+ target = bound(s, zoomAround(state.zoom, max, gesture.focus));
2501
+ else {
2502
+ const speed = pinch || reduced || event.type !== "pointerup" || gesture.axis === "x"
2503
+ ? { x: 0, y: 0 }
2504
+ : releaseVelocity(gesture.samples, event.timeStamp, {
2505
+ x: event.clientX,
2506
+ y: event.clientY,
2507
+ });
2508
+ target = bound(s, {
2509
+ scale,
2510
+ x: state.zoom.x + speed.x * GLIDE_TIME,
2511
+ y: state.zoom.y + speed.y * GLIDE_TIME,
2512
+ });
2513
+ const dx = event.clientX - gesture.start.x;
2514
+ const dy = event.clientY - gesture.start.y;
2515
+ const pinned = gesture.pinned;
2516
+ if (pinned &&
2517
+ gesture.touch &&
2518
+ !pinched &&
2519
+ event.type === "pointerup" &&
2520
+ Math.abs(dx) > Math.abs(dy) &&
2521
+ Math.abs(dx) > viewport.width * EDGE_PAGE &&
2522
+ (dx < 0 ? pinned.right : pinned.left)) {
2523
+ const rtl = s.dialog.ownerDocument.defaultView?.getComputedStyle(s.dialog)
2524
+ .direction === "rtl";
2525
+ const direction = dx < 0 !== rtl ? 1 : -1;
2526
+ const index = state.index + direction;
2527
+ if (looping() || (index >= 0 && index < items.length)) {
2528
+ freezeZoom(s);
2529
+ updateState({ zoom: { ...identity } });
2530
+ applyZoom(s);
2531
+ step(direction);
2532
+ return;
2533
+ }
2534
+ }
2535
+ const range = panRange(scale, fit(state.index, s), area(s, scale)).x;
2536
+ if (pinched)
2537
+ s.pinned = undefined;
2538
+ else if (gesture.moved)
2539
+ s.pinned = {
2540
+ index: state.index,
2541
+ zoom: target,
2542
+ left: target.x >= range.max - 0.5,
2543
+ right: target.x <= range.min + 0.5,
2544
+ };
2545
+ }
2546
+ if (target.scale <= 1)
2547
+ s.pinned = undefined;
2548
+ moveZoom(s, target, reduced ? 0 : GLIDE_DURATION, s.timing.ease);
2549
+ publish({});
2550
+ }
2551
+ function copyImage(s, event) {
2552
+ const win = s.dialog.ownerDocument.defaultView;
2553
+ const Item = win?.ClipboardItem;
2554
+ if (settings.protect ||
2555
+ items[state.index]?.type ||
2556
+ !win ||
2557
+ !Item ||
2558
+ typeof win.navigator.clipboard?.write !== "function" ||
2559
+ Item.supports?.("image/png") === false ||
2560
+ win.getSelection()?.toString())
2561
+ return;
2562
+ event.preventDefault();
2563
+ const doc = s.dialog.ownerDocument;
2564
+ const image = s.loaded.get(state.index)?.image;
2565
+ const source = image?.currentSrc || image?.src;
2566
+ const size = imageSize(state.index, s);
2567
+ const draw = async (file) => {
2568
+ const canvas = doc.createElement("canvas");
2569
+ const context = canvas.getContext("2d");
2570
+ if (!context)
2571
+ throw new Error("No canvas");
2572
+ if (file.type.split(";")[0].trim() === "image/svg+xml") {
2573
+ const url = win.URL.createObjectURL(file);
2574
+ try {
2575
+ const svg = new win.Image();
2576
+ await new Promise((resolve, reject) => {
2577
+ svg.onload = resolve;
2578
+ svg.onerror = reject;
2579
+ svg.src = url;
2580
+ });
2581
+ canvas.width = Math.round(size.width);
2582
+ canvas.height = Math.round(size.height);
2583
+ context.drawImage(svg, 0, 0, canvas.width, canvas.height);
2584
+ }
2585
+ finally {
2586
+ win.URL.revokeObjectURL(url);
2587
+ }
2588
+ }
2589
+ else {
2590
+ const bitmap = await win.createImageBitmap(file);
2591
+ canvas.width = bitmap.width;
2592
+ canvas.height = bitmap.height;
2593
+ context.drawImage(bitmap, 0, 0);
2594
+ bitmap.close();
2595
+ }
2596
+ return new Promise((resolve, reject) => canvas.toBlob((result) => (result ? resolve(result) : reject(new Error("No blob"))), "image/png"));
2597
+ };
2598
+ const shown = () => {
2599
+ if (!image?.complete || !image.naturalWidth)
2600
+ throw new Error("No image");
2601
+ const canvas = doc.createElement("canvas");
2602
+ const svg = formatOf(source ?? "", doc.baseURI) === "svg";
2603
+ canvas.width = Math.round(svg ? size.width : image.naturalWidth);
2604
+ canvas.height = Math.round(svg ? size.height : image.naturalHeight);
2605
+ canvas
2606
+ .getContext("2d")
2607
+ ?.drawImage(image, 0, 0, canvas.width, canvas.height);
2608
+ return new Promise((resolve, reject) => canvas.toBlob((result) => (result ? resolve(result) : reject(new Error("No blob"))), "image/png"));
2609
+ };
2610
+ // Only a tainted canvas fetches the file, since a page's connect-src may refuse data: and blob:.
2611
+ const blob = (async () => {
2612
+ try {
2613
+ return await shown();
2614
+ }
2615
+ catch (error) {
2616
+ if (error.name !== "SecurityError")
2617
+ throw error;
2618
+ }
2619
+ if (!source)
2620
+ throw new Error("No image");
2621
+ const response = await win.fetch(source, {
2622
+ mode: "cors",
2623
+ credentials: "same-origin",
2624
+ });
2625
+ if (!response.ok)
2626
+ throw new Error("No file");
2627
+ const file = await response.blob();
2628
+ return file.type === "image/png" ? file : draw(file);
2629
+ })();
2630
+ blob.catch(() => { });
2631
+ win.navigator.clipboard
2632
+ .write([new Item({ "image/png": blob })])
2633
+ .catch(() => { });
561
2634
  }
562
2635
  function installGestures(s) {
563
2636
  const signal = s.abort.signal;
@@ -565,33 +2638,41 @@ export function createLightbox(options = {}) {
565
2638
  x: event.clientX,
566
2639
  y: event.clientY,
567
2640
  });
568
- const focus = (p) => {
569
- const rect = s.viewport.getBoundingClientRect();
570
- const size = view(s);
571
- return {
572
- x: p.x - rect.left - size.width / 2,
573
- y: p.y - rect.top - size.height / 2,
574
- };
575
- };
2641
+ const focus = (p) => ({
2642
+ x: p.x - s.box.left - s.box.width / 2,
2643
+ y: p.y - s.box.top - s.box.height / 2,
2644
+ });
576
2645
  const resetGesture = () => {
577
2646
  const points = [...s.pointers.values()];
578
2647
  if (!points.length) {
579
2648
  s.gesture = undefined;
580
2649
  return;
581
2650
  }
2651
+ const range = panRange(state.zoom.scale, fit(state.index, s), area(s, state.zoom.scale));
2652
+ const middle = points.length > 1 ? midpoint(points) : points[0];
582
2653
  s.gesture = {
583
2654
  start: points[0],
584
2655
  zoom: { ...state.zoom },
2656
+ raw: {
2657
+ x: unrubber(state.zoom.x, range.x),
2658
+ y: unrubber(state.zoom.y, range.y),
2659
+ },
585
2660
  distance: points.length > 1 ? distance(points) : 0,
586
- midpoint: points.length > 1 ? midpoint(points) : points[0],
2661
+ midpoint: middle,
2662
+ focus: focus(middle),
587
2663
  moved: false,
588
2664
  touch: s.gesture?.touch ?? true,
2665
+ pinched: false,
2666
+ half: 1,
2667
+ samples: [],
589
2668
  };
590
2669
  };
591
2670
  s.viewport.addEventListener("pointerdown", (event) => {
592
2671
  if (event.button !== 0 ||
593
2672
  state.isClosing ||
594
- (event.target instanceof Element &&
2673
+ // A dismiss swipe stays with its finger.
2674
+ s.gesture?.axis === "y" ||
2675
+ (isElement(event.target) &&
595
2676
  event.target.closest("button, a, input, textarea, select, [data-lightbox-interactive]")))
596
2677
  return;
597
2678
  if (s.wheelTimer !== undefined) {
@@ -600,10 +2681,29 @@ export function createLightbox(options = {}) {
600
2681
  publish({});
601
2682
  }
602
2683
  interruptImageMotion(s);
2684
+ if (!s.pointers.size)
2685
+ measure(s);
603
2686
  s.pointers.set(event.pointerId, point(event));
604
2687
  resetGesture();
605
- if (s.gesture)
2688
+ if (s.gesture) {
606
2689
  s.gesture.touch = event.pointerType !== "mouse";
2690
+ s.gesture.samples.push({
2691
+ time: event.timeStamp,
2692
+ x: event.clientX,
2693
+ y: event.clientY,
2694
+ });
2695
+ const pinned = s.pinned;
2696
+ if (s.pointers.size === 1 &&
2697
+ pinned?.index === state.index &&
2698
+ sameZoom(pinned.zoom, state.zoom))
2699
+ s.gesture.pinned = pinned;
2700
+ }
2701
+ if (s.pointers.size === 2) {
2702
+ clearTimeout(s.tapTimer);
2703
+ s.tapTimer = undefined;
2704
+ s.lastTap = undefined;
2705
+ chromeInput(s, { type: "pinch" });
2706
+ }
607
2707
  if (state.zoom.scale > 1 || s.pointers.size > 1) {
608
2708
  s.viewport.setPointerCapture?.(event.pointerId);
609
2709
  event.preventDefault();
@@ -619,46 +2719,80 @@ export function createLightbox(options = {}) {
619
2719
  const dy = event.clientY - gesture.start.y;
620
2720
  if (Math.hypot(dx, dy) > 8 || points.length > 1)
621
2721
  gesture.moved = true;
2722
+ gesture.samples.push({
2723
+ time: event.timeStamp,
2724
+ x: event.clientX,
2725
+ y: event.clientY,
2726
+ });
2727
+ while (gesture.samples[0].time < event.timeStamp - SPEED_WINDOW * 2)
2728
+ gesture.samples.shift();
622
2729
  if (points.length > 1 && gesture.distance > 0) {
623
2730
  event.preventDefault();
624
2731
  const middle = midpoint(points);
625
- const scale = clamp((gesture.zoom.scale * distance(points)) / gesture.distance, 0.8, maxZoom * 1.15);
2732
+ const range = limits(s);
2733
+ const scale = clamp((gesture.zoom.scale * distance(points)) / gesture.distance, PINCH_MIN * range.min, PINCH_OVER * range.max);
626
2734
  const zoom = zoomAround(gesture.zoom, scale, focus(gesture.midpoint));
627
2735
  zoom.x += middle.x - gesture.midpoint.x;
628
2736
  zoom.y += middle.y - gesture.midpoint.y;
2737
+ gesture.focus = focus(middle);
629
2738
  updateState({ zoom });
630
- applyZoom(s);
2739
+ applyZoom(s, false);
631
2740
  }
632
- else if (gesture.zoom.scale > 1) {
633
- event.preventDefault();
634
- updateState({
635
- zoom: boundZoom({
636
- scale: gesture.zoom.scale,
637
- x: gesture.zoom.x + dx,
638
- y: gesture.zoom.y + dy,
639
- }, fit(state.index, s), view(s)),
640
- });
641
- applyZoom(s);
642
- }
643
- else if (gesture.touch &&
644
- Math.abs(dy) > Math.abs(dx) * 1.3 &&
645
- Math.abs(dy) > 8) {
646
- event.preventDefault();
647
- s.carousel.setEnabled(false);
648
- s.viewport.setPointerCapture?.(event.pointerId);
649
- updateState({
650
- zoom: {
651
- scale: Math.max(0.8, 1 - Math.abs(dy) / view(s).height / 2),
652
- x: 0,
653
- y: dy,
654
- },
655
- });
656
- const frame = s.loaded.get(state.index)?.frame;
657
- if (frame)
658
- frame.style.transform = `translateY(${dy}px) scale(${state.zoom.scale})`;
2741
+ else {
2742
+ if (gesture.touch &&
2743
+ points.length === 1 &&
2744
+ gesture.zoom.scale <= 1 &&
2745
+ !gesture.pinched &&
2746
+ !gesture.axis &&
2747
+ Math.hypot(dx, dy) >= 10) {
2748
+ const range = panRange(gesture.zoom.scale, fit(state.index, s), view(s)).y;
2749
+ gesture.axis =
2750
+ Math.abs(dy) <= Math.abs(dx)
2751
+ ? "x"
2752
+ : range.max - range.min > 1 &&
2753
+ !(dy > 0 && gesture.zoom.y >= range.max - 0.5)
2754
+ ? "pan"
2755
+ : "y";
2756
+ if (gesture.axis !== "x") {
2757
+ s.carousel.setEnabled(false);
2758
+ s.viewport.setPointerCapture?.(event.pointerId);
2759
+ }
2760
+ if (gesture.axis === "y") {
2761
+ gesture.half = view(s).height / 2;
2762
+ setPhase(s, "dragging");
2763
+ }
2764
+ }
2765
+ if (gesture.zoom.scale > 1 ||
2766
+ gesture.pinched ||
2767
+ gesture.axis === "pan") {
2768
+ event.preventDefault();
2769
+ if (gesture.moved && !s.dialog.dataset.panning)
2770
+ s.dialog.dataset.panning = "true";
2771
+ updateState({
2772
+ zoom: elasticZoom({
2773
+ scale: gesture.zoom.scale,
2774
+ x: gesture.raw.x + (gesture.axis === "pan" ? 0 : dx),
2775
+ y: gesture.raw.y + dy,
2776
+ }, fit(state.index, s), area(s, gesture.zoom.scale)),
2777
+ });
2778
+ applyZoom(s, false);
2779
+ }
2780
+ else if (gesture.axis === "y") {
2781
+ event.preventDefault();
2782
+ dismissDrag(s, dx, dy, gesture.half);
2783
+ if (!gesture.buzzed && Math.abs(dy) > DISMISS_DISTANCE) {
2784
+ gesture.buzzed = true;
2785
+ s.dialog.ownerDocument.defaultView?.navigator.vibrate?.(10);
2786
+ }
2787
+ }
659
2788
  }
660
2789
  }, { signal, passive: false });
661
2790
  const release = (event) => {
2791
+ lift(event);
2792
+ if (session === s && !s.flying && !state.isClosing && !s.pointers.size)
2793
+ swapHeld(s);
2794
+ };
2795
+ const lift = (event) => {
662
2796
  if (!s.pointers.has(event.pointerId))
663
2797
  return;
664
2798
  const gesture = s.gesture;
@@ -666,43 +2800,95 @@ export function createLightbox(options = {}) {
666
2800
  s.pointers.delete(event.pointerId);
667
2801
  if (gesture?.moved)
668
2802
  s.suppressClickUntil = Date.now() + 400;
669
- if (event.type === "pointerup" &&
670
- !hadPinch &&
671
- gesture?.touch &&
672
- gesture.zoom.scale <= 1 &&
673
- Math.abs(state.zoom.y) > 120) {
674
- void close();
2803
+ delete s.dialog.dataset.panning;
2804
+ if (gesture?.axis === "y" && !hadPinch) {
2805
+ s.dialog.style.removeProperty("--re-lightbox-chrome-opacity");
2806
+ const dy = event.clientY - gesture.start.y;
2807
+ const speed = releaseVelocity(gesture.samples, event.timeStamp, {
2808
+ x: event.clientX,
2809
+ y: event.clientY,
2810
+ }).y;
2811
+ resetGesture();
2812
+ if (event.type === "pointerup" &&
2813
+ (Math.abs(dy) > DISMISS_DISTANCE || Math.abs(speed) > DISMISS_SPEED)) {
2814
+ void close();
2815
+ if (state.isClosing || session !== s)
2816
+ return;
2817
+ }
2818
+ returnFromDismiss(s);
675
2819
  return;
676
2820
  }
677
2821
  if (event.type === "pointerup" &&
678
2822
  gesture?.touch &&
679
2823
  !gesture.moved &&
680
- !hadPinch) {
2824
+ !hadPinch &&
2825
+ !gesture.pinched) {
681
2826
  const now = Date.now();
682
- const previous = s.lastTap;
2827
+ s.suppressClickUntil = now + 400;
683
2828
  const current = point(event);
684
- if (options.doubleTapZoom !== false &&
2829
+ const box = s.loaded.get(state.index)?.frame.getBoundingClientRect();
2830
+ const onPhoto = box !== undefined &&
2831
+ current.x >= box.left &&
2832
+ current.x <= box.right &&
2833
+ current.y >= box.top &&
2834
+ current.y <= box.bottom;
2835
+ const previous = s.lastTap;
2836
+ const pending = s.tapTimer !== undefined;
2837
+ clearTimeout(s.tapTimer);
2838
+ s.tapTimer = undefined;
2839
+ s.lastTap = undefined;
2840
+ if (!onPhoto &&
2841
+ (overThumbnails(s, current.x, current.y) ||
2842
+ inRoom(s, current.x, current.y)))
2843
+ return;
2844
+ const doubleTap = settings.imageClick !== "close" &&
2845
+ settings.doubleTapZoom !== false &&
2846
+ (state.zoom.scale !== 1 || limits(s).max > 1 || limits(s).min < 1);
2847
+ if (!onPhoto || settings.imageClick === "close") {
2848
+ void close();
2849
+ if (state.isClosing || session !== s)
2850
+ return;
2851
+ }
2852
+ else if (doubleTap &&
685
2853
  previous &&
686
- now - previous.time < 300 &&
687
- Math.hypot(current.x - previous.point.x, current.y - previous.point.y) < 30) {
2854
+ now - previous.time < DOUBLE_TAP_TIME &&
2855
+ Math.hypot(current.x - previous.point.x, current.y - previous.point.y) < DOUBLE_TAP_DISTANCE) {
688
2856
  toggleZoom(focus(current));
689
- s.lastTap = undefined;
2857
+ resetGesture();
2858
+ return;
690
2859
  }
691
2860
  else {
692
- s.lastTap = { time: now, point: current };
693
- if (options.imageClick === "close")
694
- void close();
2861
+ if (pending)
2862
+ chromeInput(s, { type: "tap" });
2863
+ if (doubleTap) {
2864
+ s.lastTap = { time: now, point: current };
2865
+ s.tapTimer = setTimeout(() => {
2866
+ s.tapTimer = undefined;
2867
+ s.lastTap = undefined;
2868
+ chromeInput(s, { type: "tap" });
2869
+ }, DOUBLE_TAP_TIME);
2870
+ }
2871
+ else
2872
+ chromeInput(s, { type: "tap" });
695
2873
  }
696
- s.suppressClickUntil = now + 400;
697
2874
  }
698
- if (state.zoom.scale < 1 ||
699
- (gesture?.zoom.scale === 1 && !hadPinch && state.zoom.scale <= 1))
700
- setZoom(1, { x: 0, y: 0 }, s.pointers.size === 0);
701
- else
702
- setZoom(state.zoom.scale, { x: 0, y: 0 }, s.pointers.size === 0);
2875
+ if (s.pointers.size > 0) {
2876
+ const focusPoint = gesture?.focus;
2877
+ resetGesture();
2878
+ if (s.gesture) {
2879
+ s.gesture.moved = true;
2880
+ s.gesture.pinched = true;
2881
+ if (focusPoint)
2882
+ s.gesture.focus = focusPoint;
2883
+ }
2884
+ s.lastTap = undefined;
2885
+ return;
2886
+ }
2887
+ if (gesture)
2888
+ settle(s, gesture, event, hadPinch, hadPinch || gesture.pinched);
703
2889
  resetGesture();
704
- if (hadPinch && s.gesture)
705
- s.gesture.moved = true;
2890
+ if (gesture?.axis === "pan" && session === s)
2891
+ applyZoom(s, false);
706
2892
  if (hadPinch)
707
2893
  s.lastTap = undefined;
708
2894
  };
@@ -710,36 +2896,71 @@ export function createLightbox(options = {}) {
710
2896
  signal,
711
2897
  });
712
2898
  s.dialog.ownerDocument.defaultView?.addEventListener("pointercancel", release, { signal });
713
- s.viewport.addEventListener("lostpointercapture", release, { signal });
2899
+ s.viewport.addEventListener("lostpointercapture", (event) => {
2900
+ if (event.target === s.viewport)
2901
+ release(event);
2902
+ }, { signal });
2903
+ s.viewport.addEventListener("dragstart", (event) => {
2904
+ if (isElement(event.target) &&
2905
+ event.target.matches(".re-lightbox-image"))
2906
+ event.preventDefault();
2907
+ }, { signal });
2908
+ s.viewport.addEventListener("contextmenu", (event) => {
2909
+ if (settings.protect &&
2910
+ isElement(event.target) &&
2911
+ event.target.matches(".re-lightbox-image"))
2912
+ event.preventDefault();
2913
+ }, { signal });
714
2914
  s.viewport.addEventListener("click", (event) => {
715
2915
  if (Date.now() < s.suppressClickUntil || state.isClosing)
716
2916
  return;
717
2917
  const target = event.target;
718
- if (!(target instanceof Element) ||
2918
+ if (!isElement(target) ||
719
2919
  target.closest("[data-lightbox-interactive],button,a,input,textarea,select"))
720
2920
  return;
721
- if (!target.closest(".re-lightbox-frame")) {
722
- void close();
2921
+ // A pan captures the pointer, which retargets its click to the viewport.
2922
+ const box = s.loaded.get(state.index)?.frame.getBoundingClientRect();
2923
+ const onPhoto = target.closest(".re-lightbox-frame") !== null ||
2924
+ (box !== undefined &&
2925
+ event.clientX >= box.left &&
2926
+ event.clientX <= box.right &&
2927
+ event.clientY >= box.top &&
2928
+ event.clientY <= box.bottom);
2929
+ if (!onPhoto) {
2930
+ if (!overThumbnails(s, event.clientX, event.clientY) &&
2931
+ !inRoom(s, event.clientX, event.clientY))
2932
+ void close();
723
2933
  return;
724
2934
  }
725
- if (options.imageClick === "close")
2935
+ if (settings.imageClick === "close")
726
2936
  void close();
727
- else if (options.imageClick !== "none" && isSettled(s))
2937
+ else if (settings.imageClick !== "none" && isSettled(s))
728
2938
  toggleZoom(focus({ x: event.clientX, y: event.clientY }));
729
2939
  }, { signal });
2940
+ const settleLater = () => {
2941
+ clearTimeout(s.wheelTimer);
2942
+ s.wheelTimer = setTimeout(() => {
2943
+ s.wheelTimer = undefined;
2944
+ if (session === s && !state.isClosing)
2945
+ publish({});
2946
+ }, 150);
2947
+ };
730
2948
  s.viewport.addEventListener("wheel", (event) => {
731
- if (state.isClosing || (!event.ctrlKey && state.zoom.scale <= 1))
2949
+ const zooming = event.ctrlKey || event.metaKey;
2950
+ if (!zooming &&
2951
+ (state.isClosing ||
2952
+ (state.zoom.scale <= 1 &&
2953
+ (!tall(state.index, s) ||
2954
+ Math.abs(event.deltaX) > Math.abs(event.deltaY)))))
732
2955
  return;
733
2956
  event.preventDefault();
734
- if (s.animations.size)
735
- interruptImageMotion(s);
736
- if (event.ctrlKey) {
737
- const rect = s.viewport.getBoundingClientRect();
738
- const size = view(s);
739
- setZoom(state.zoom.scale * Math.exp(-event.deltaY * 0.01), {
740
- x: event.clientX - rect.left - size.width / 2,
741
- y: event.clientY - rect.top - size.height / 2,
742
- }, false);
2957
+ if (state.isClosing ||
2958
+ s.pointers.size > 0 ||
2959
+ (s.animations.size > 0 && !s.zoomMotion))
2960
+ return;
2961
+ freezeZoom(s);
2962
+ if (zooming) {
2963
+ setZoom(state.zoom.scale * Math.exp(-event.deltaY * 0.01), focus({ x: event.clientX, y: event.clientY }), false);
743
2964
  }
744
2965
  else {
745
2966
  const unit = event.deltaMode === 1
@@ -748,101 +2969,637 @@ export function createLightbox(options = {}) {
748
2969
  ? view(s).height
749
2970
  : 1;
750
2971
  updateState({
751
- zoom: boundZoom({
2972
+ zoom: bound(s, {
752
2973
  ...state.zoom,
753
2974
  x: state.zoom.x - event.deltaX * unit,
754
2975
  y: state.zoom.y - event.deltaY * unit,
755
- }, fit(state.index, s), view(s)),
2976
+ }),
756
2977
  });
757
- applyZoom(s);
2978
+ applyZoom(s, false);
758
2979
  }
759
- clearTimeout(s.wheelTimer);
760
- s.wheelTimer = setTimeout(() => {
761
- s.wheelTimer = undefined;
762
- if (session === s && !state.isClosing)
763
- publish({});
764
- }, 150);
2980
+ settleLater();
765
2981
  }, { signal, passive: false });
2982
+ s.viewport.addEventListener("gesturestart", (event) => {
2983
+ event.preventDefault();
2984
+ s.safariScale = undefined;
2985
+ if (state.isClosing ||
2986
+ s.pointers.size > 0 ||
2987
+ (s.animations.size > 0 && !s.zoomMotion))
2988
+ return;
2989
+ freezeZoom(s);
2990
+ measure(s);
2991
+ s.safariScale = state.zoom.scale;
2992
+ }, { signal });
2993
+ s.viewport.addEventListener("gesturechange", (input) => {
2994
+ const event = input;
2995
+ event.preventDefault();
2996
+ const base = s.safariScale;
2997
+ if (base === undefined || state.isClosing || s.pointers.size > 0)
2998
+ return;
2999
+ if (!Number.isFinite(event.scale))
3000
+ return;
3001
+ setZoom(base * event.scale, focus({
3002
+ x: event.clientX ?? s.box.left + s.box.width / 2,
3003
+ y: event.clientY ?? s.box.top + s.box.height / 2,
3004
+ }), false);
3005
+ }, { signal });
3006
+ s.viewport.addEventListener("gestureend", (event) => {
3007
+ event.preventDefault();
3008
+ if (s.safariScale === undefined)
3009
+ return;
3010
+ s.safariScale = undefined;
3011
+ if (session === s && !state.isClosing)
3012
+ publish({});
3013
+ }, { signal });
3014
+ }
3015
+ function connect(viewport, strings) {
3016
+ const carousel = createCarousel(viewport, {
3017
+ drag: true,
3018
+ loop: looping(),
3019
+ strings: { carouselRole: strings.carouselRole },
3020
+ });
3021
+ carousel.subscribe((value) => {
3022
+ if (!syncingCarousel &&
3023
+ session?.viewport === viewport &&
3024
+ session.resizeFrame === undefined)
3025
+ activeChanged(session, value.index);
3026
+ });
3027
+ carouselInternalsOf(carousel)?.silence();
3028
+ return carousel;
3029
+ }
3030
+ function ownsHistory(win) {
3031
+ return entryOf(win) === historyId;
3032
+ }
3033
+ function pushHistory(win) {
3034
+ const current = win.history.state;
3035
+ const mode = holdScroll(win);
3036
+ win.history.pushState({
3037
+ ...(typeof current === "object" && current !== null ? current : {}),
3038
+ [HISTORY_KEY]: historyId,
3039
+ }, "", win.location.href);
3040
+ win.history.scrollRestoration = mode;
3041
+ }
3042
+ // A frame shares the page's session history but sees none of the page's entries, so it opts in.
3043
+ function enterHistory(win) {
3044
+ if (settings.history === false || (!settings.history && win.top !== win))
3045
+ return;
3046
+ if (historyWindow !== win) {
3047
+ historyWindow?.removeEventListener("popstate", onPopState);
3048
+ historyWindow = win;
3049
+ win.addEventListener("popstate", onPopState);
3050
+ }
3051
+ // While a back is still on its way, its popstate restores the entry.
3052
+ if (!historyBacks.has(win) && !ownsHistory(win))
3053
+ pushHistory(win);
3054
+ }
3055
+ // Resolves once the back has landed, so a navigation after close() is not undone by it.
3056
+ function leaveHistory() {
3057
+ const win = historyWindow;
3058
+ if (!win)
3059
+ return Promise.resolve();
3060
+ if (!ownsHistory(win))
3061
+ orphan(win, historyId);
3062
+ if (!ownsHistory(win) && !historyBacks.has(win))
3063
+ releaseScroll(win);
3064
+ const landing = ownsHistory(win)
3065
+ ? goBack(win)
3066
+ : (historyBacks.get(win)?.landing ?? Promise.resolve());
3067
+ releaseHistory();
3068
+ return landing;
3069
+ }
3070
+ function releaseHistory() {
3071
+ if (session)
3072
+ return;
3073
+ historyWindow?.removeEventListener("popstate", onPopState);
3074
+ historyWindow = undefined;
3075
+ }
3076
+ function onPopState(event) {
3077
+ const win = historyWindow;
3078
+ if (!win)
3079
+ return;
3080
+ if (landed(win, event)) {
3081
+ if (session &&
3082
+ !state.isClosing &&
3083
+ !ownsHistory(win) &&
3084
+ !historyBacks.has(win))
3085
+ pushHistory(win);
3086
+ return;
3087
+ }
3088
+ if (ownsHistory(win))
3089
+ return;
3090
+ if (takeOrphan(win))
3091
+ void goBack(win);
3092
+ else
3093
+ releaseScroll(win);
3094
+ if (session && !state.isClosing)
3095
+ void closeSession(true);
3096
+ }
3097
+ // The caption panel shows when some photo has a caption, so the photo keeps one width while paging.
3098
+ function placeAside(s, relayout = false) {
3099
+ const needed = Boolean(settings.slots?.aside) ||
3100
+ (settings.caption === "side" && items.some((item) => item.caption));
3101
+ if (needed === Boolean(s.aside))
3102
+ return;
3103
+ if (s.aside) {
3104
+ s.aside.remove();
3105
+ s.chromeRoots = s.chromeRoots.filter((root) => root !== s.aside);
3106
+ s.aside = undefined;
3107
+ delete s.dialog.dataset.aside;
3108
+ }
3109
+ else {
3110
+ const aside = s.dialog.ownerDocument.createElement("div");
3111
+ aside.className = "re-lightbox-aside";
3112
+ if (settings.caption === "side")
3113
+ aside.append(s.caption);
3114
+ s.stage.append(aside);
3115
+ s.chromeRoots.push(aside);
3116
+ s.aside = aside;
3117
+ s.dialog.dataset.aside = "";
3118
+ }
3119
+ if (relayout) {
3120
+ const win = s.dialog.ownerDocument.defaultView;
3121
+ s.resizeFrame ??= win?.requestAnimationFrame(() => resized(s));
3122
+ }
3123
+ }
3124
+ // A side column turns into the bottom strip below 720px, where the strip pages as a carousel.
3125
+ function placeThumbs(s) {
3126
+ const strip = s.thumbStrip;
3127
+ if (!strip)
3128
+ return;
3129
+ const win = s.dialog.ownerDocument.defaultView;
3130
+ const side = settings.thumbnails === "side" &&
3131
+ !win?.matchMedia?.("(max-width: 719.98px)").matches;
3132
+ const layout = settings.thumbnailsVisible === false
3133
+ ? undefined
3134
+ : side
3135
+ ? "side"
3136
+ : "bottom";
3137
+ if (s.dialog.dataset.thumbnails === layout)
3138
+ return;
3139
+ endScrub(s);
3140
+ s.thumbCarousel?.destroy();
3141
+ s.thumbCarousel = undefined;
3142
+ s.chromeRoots = s.chromeRoots.filter((root) => root !== strip);
3143
+ if (!layout) {
3144
+ if (strip.contains(strip.ownerDocument.activeElement)) {
3145
+ s.viewport.focus({ preventScroll: true });
3146
+ }
3147
+ strip.remove();
3148
+ s.thumbRing?.remove();
3149
+ delete s.dialog.dataset.thumbnails;
3150
+ return;
3151
+ }
3152
+ s.dialog.dataset.thumbnails = layout;
3153
+ if (side) {
3154
+ s.stage.append(strip);
3155
+ s.chromeRoots.push(strip);
3156
+ }
3157
+ else {
3158
+ s.footer.append(strip);
3159
+ strip.tabIndex = -1;
3160
+ s.thumbCarousel = createCarousel(strip, { drag: true, align: "center" });
3161
+ const internals = carouselInternalsOf(s.thumbCarousel);
3162
+ internals?.silence();
3163
+ internals?.passClicks();
3164
+ }
3165
+ if (s.thumbRing)
3166
+ strip.after(s.thumbRing);
3167
+ s.thumbCenters = undefined;
3168
+ s.centeredThumb = -1;
3169
+ centerThumb(s);
3170
+ ringThumb(s, false);
3171
+ }
3172
+ function watchControls(s) {
3173
+ const doc = s.dialog.ownerDocument;
3174
+ const win = doc.defaultView;
3175
+ const signal = s.abort.signal;
3176
+ doc.addEventListener("fullscreenchange", () => {
3177
+ const full = doc.fullscreenElement === s.stage;
3178
+ s.fullscreenButton?.setAttribute("aria-label", full ? s.strings.fullscreenExit : s.strings.fullscreenEnter);
3179
+ if (s.fullscreenButton)
3180
+ showStateIcon(s.fullscreenButton, "fullscreen", "fullscreenExit", full);
3181
+ if (full)
3182
+ s.dialog.dataset.fullscreen = "";
3183
+ else
3184
+ delete s.dialog.dataset.fullscreen;
3185
+ }, { signal });
3186
+ doc.addEventListener("visibilitychange", () => scheduleSlideshow(s), {
3187
+ signal,
3188
+ });
3189
+ for (const type of ["play", "pause", "ended"])
3190
+ s.viewport.addEventListener(type, (event) => {
3191
+ holdForMedia(s);
3192
+ const player = s.loaded
3193
+ .get(state.index)
3194
+ ?.media?.holder?.querySelector("video, audio");
3195
+ if (type === "ended" &&
3196
+ event.target === player &&
3197
+ s.slideshow &&
3198
+ slideshowRuns(s))
3199
+ advanceSlideshow(s);
3200
+ }, { signal, capture: true });
3201
+ const hover = (event, target) => {
3202
+ if (event.pointerType !== "mouse")
3203
+ return;
3204
+ holdSlideshow(s, "hover", isNode(target) && s.chromeRoots.some((root) => root.contains(target)));
3205
+ };
3206
+ s.dialog.addEventListener("pointerover", (event) => hover(event, event.target), {
3207
+ signal,
3208
+ });
3209
+ s.dialog.addEventListener("pointerout", (event) => hover(event, event.relatedTarget), { signal });
3210
+ if (s.slots.length && win?.MutationObserver) {
3211
+ // :popover-open throws where popovers are missing, so each selector is tried alone.
3212
+ const opened = () => holdSlideshow(s, "menu", ['[aria-expanded="true"]', "details[open]", ":popover-open"].some((selector) => {
3213
+ try {
3214
+ return Boolean(s.stage.querySelector(selector));
3215
+ }
3216
+ catch {
3217
+ return false;
3218
+ }
3219
+ }));
3220
+ const observer = new win.MutationObserver(opened);
3221
+ observer.observe(s.stage, {
3222
+ subtree: true,
3223
+ attributes: true,
3224
+ attributeFilter: ["aria-expanded", "open"],
3225
+ });
3226
+ s.stage.addEventListener("toggle", opened, { signal, capture: true });
3227
+ signal.addEventListener("abort", () => observer.disconnect());
3228
+ }
3229
+ const strip = s.thumbStrip;
3230
+ if (!strip)
3231
+ return;
3232
+ strip.addEventListener("keydown", (event) => {
3233
+ const at = s.thumbs.indexOf(event.target);
3234
+ if (at < 0 || event.altKey || event.ctrlKey || event.metaKey)
3235
+ return;
3236
+ const side = s.dialog.dataset.thumbnails === "side";
3237
+ const rtl = win?.getComputedStyle(strip).direction === "rtl";
3238
+ const forward = side ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight";
3239
+ const back = side ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft";
3240
+ const to = {
3241
+ [forward]: at + 1,
3242
+ [back]: at - 1,
3243
+ Home: 0,
3244
+ End: s.thumbs.length - 1,
3245
+ }[event.key];
3246
+ if (to === undefined)
3247
+ return;
3248
+ event.preventDefault();
3249
+ s.stripInput = false;
3250
+ const count = s.thumbs.length;
3251
+ const index = looping()
3252
+ ? (to + count) % count
3253
+ : clamp(to, 0, count - 1);
3254
+ rove(s, index);
3255
+ goTo(index);
3256
+ s.thumbs[index].focus({ preventScroll: true });
3257
+ },
3258
+ // Ahead of the strip carousel's own keys, which would scroll it instead.
3259
+ { signal, capture: true });
3260
+ strip.addEventListener("focusout", (event) => {
3261
+ if (!isNode(event.relatedTarget) ||
3262
+ !strip.contains(event.relatedTarget))
3263
+ rove(s, state.index);
3264
+ }, { signal });
3265
+ const pressed = () => {
3266
+ s.stripInput = true;
3267
+ };
3268
+ strip.addEventListener("pointerdown", pressed, { signal });
3269
+ strip.addEventListener("wheel", pressed, { signal, passive: true });
3270
+ strip.addEventListener("re-carousel:settle", () => endScrub(s), { signal });
3271
+ strip.addEventListener("scroll", () => {
3272
+ if (!s.stripInput)
3273
+ return;
3274
+ s.scrubFrame ??= win?.requestAnimationFrame(() => {
3275
+ s.scrubFrame = undefined;
3276
+ scrubNow(s);
3277
+ });
3278
+ clearTimeout(s.scrubTimer);
3279
+ s.scrubTimer = setTimeout(() => endScrub(s), 180);
3280
+ }, { signal, passive: true });
3281
+ if (settings.thumbnails === "side")
3282
+ win
3283
+ ?.matchMedia?.("(max-width: 719.98px)")
3284
+ .addEventListener("change", () => placeThumbs(s), { signal });
3285
+ }
3286
+ // New strings reach every label at once; the live region keeps its last announcement.
3287
+ function relabel(s) {
3288
+ const strings = { ...defaultStrings, ...settings.strings };
3289
+ s.strings = strings;
3290
+ const doc = s.dialog.ownerDocument;
3291
+ const name = (selector, label) => s.stage.querySelector(selector)?.setAttribute("aria-label", label);
3292
+ s.dialog.setAttribute("aria-label", strings.dialog);
3293
+ s.viewport.setAttribute("aria-label", strings.dialog);
3294
+ s.carousel.setOptions({ strings: { carouselRole: strings.carouselRole } });
3295
+ name(".re-lightbox-close", strings.close);
3296
+ name(".re-lightbox-prev", strings.previous);
3297
+ name(".re-lightbox-next", strings.next);
3298
+ name(".re-lightbox-download", strings.download);
3299
+ name(".re-lightbox-fullscreen", doc.fullscreenElement === s.stage
3300
+ ? strings.fullscreenExit
3301
+ : strings.fullscreenEnter);
3302
+ name(".re-lightbox-slideshow", s.slideshow ? strings.slideshowStop : strings.slideshowStart);
3303
+ s.thumbStrip?.setAttribute("aria-label", strings.thumbnails);
3304
+ for (const [index, thumb] of s.thumbs.entries())
3305
+ thumb.setAttribute("aria-label", strings.thumbnail(index, items.length));
3306
+ for (const node of s.stage.querySelectorAll(".re-lightbox-loading"))
3307
+ node.setAttribute("aria-label", strings.loading);
3308
+ for (const node of s.stage.querySelectorAll(".re-lightbox-error p"))
3309
+ node.textContent = strings.error;
3310
+ for (const node of s.stage.querySelectorAll(".re-lightbox-retry"))
3311
+ node.textContent = strings.retry;
3312
+ s.marked = undefined;
3313
+ update(s);
3314
+ }
3315
+ function mountSlots(s, places) {
3316
+ const doc = s.dialog.ownerDocument;
3317
+ for (const name of Object.keys(places)) {
3318
+ const slot = settings.slots?.[name];
3319
+ if (!slot)
3320
+ continue;
3321
+ const instance = slot({
3322
+ lightbox: controller,
3323
+ document: doc,
3324
+ icon: (name) => {
3325
+ const own = settings.icons?.[name]?.() ??
3326
+ (firstStateIcon[name]
3327
+ ? settings.icons?.[firstStateIcon[name]]?.()
3328
+ : undefined);
3329
+ if (own) {
3330
+ if ((name === "previous" || name === "next") &&
3331
+ own instanceof Element)
3332
+ own.classList.add("re-lightbox-arrow-icon");
3333
+ return own;
3334
+ }
3335
+ const holder = doc.createElement("span");
3336
+ showIcon(holder, builtInIcons[name]);
3337
+ return holder.firstElementChild;
3338
+ },
3339
+ counter: () => {
3340
+ const counter = counterNode(doc);
3341
+ counter.hidden = items.length < 2;
3342
+ s.counters.push(counter);
3343
+ drawCounter(s, counter, s.strings.counter(state.index, items.length), 0);
3344
+ return counter;
3345
+ },
3346
+ });
3347
+ places[name](instance.node);
3348
+ s.slots.push(instance);
3349
+ instance.update?.(state);
3350
+ }
766
3351
  }
767
3352
  function open(input, index = 0) {
3353
+ const before = session;
3354
+ try {
3355
+ openSession(input, index);
3356
+ }
3357
+ catch (error) {
3358
+ const s = session;
3359
+ if (s && s !== before) {
3360
+ // The same callback may throw again while focus returns; the first error is the one to report.
3361
+ try {
3362
+ teardown(s);
3363
+ }
3364
+ catch { }
3365
+ publish({
3366
+ isOpen: false,
3367
+ isClosing: false,
3368
+ isAnimating: false,
3369
+ zoom: { ...identity },
3370
+ });
3371
+ void leaveHistory();
3372
+ }
3373
+ throw error;
3374
+ }
3375
+ }
3376
+ function openSession(input, index) {
768
3377
  if (destroyed)
769
3378
  throw new Error("This lightbox has been destroyed.");
770
- const nextItems = validateItems(input);
3379
+ const nextItems = validateItems(input, current.content);
771
3380
  if (!Number.isFinite(index))
772
3381
  throw new TypeError("Image index must be finite.");
773
- const doc = options.container?.ownerDocument ??
3382
+ const layer = galleryOptions;
3383
+ const doc = current.container?.ownerDocument ??
3384
+ resolveOrigin(nextItems[clamp(Math.floor(index), 0, nextItems.length - 1)].origin)?.ownerDocument ??
774
3385
  (typeof document === "undefined" ? undefined : document);
775
3386
  if (!doc?.body)
776
3387
  throw new Error("Opening a lightbox needs a browser document.");
777
- if (session)
3388
+ pendingClosed?.();
3389
+ if (session) {
778
3390
  teardown(session);
3391
+ emit("closed", null);
3392
+ }
3393
+ if (destroyed)
3394
+ return;
3395
+ configure(layer);
779
3396
  items = nextItems;
3397
+ sources = [...input];
780
3398
  closePromise = undefined;
3399
+ const strings = { ...defaultStrings, ...settings.strings };
781
3400
  const dialog = doc.createElement("dialog");
782
3401
  if (typeof dialog.showModal !== "function")
783
3402
  throw new Error("Lightbox requires native dialog support.");
784
- dialog.className = ["re-lightbox", options.className]
3403
+ dialog.className = ["re-lightbox", settings.className]
785
3404
  .filter(Boolean)
786
3405
  .join(" ");
787
- dialog.setAttribute("aria-label", options.label || "Image gallery");
3406
+ dialog.setAttribute("aria-label", strings.dialog);
3407
+ dialog.dataset.chrome = "shown";
3408
+ dialog.dataset.phase = "entering";
3409
+ if (settings.protect)
3410
+ dialog.dataset.protect = "";
3411
+ const control = (name) => settings.controls?.[name] ?? defaultControls[name];
3412
+ const stage = doc.createElement("div");
3413
+ stage.className = "re-lightbox-stage";
3414
+ dialog.append(stage);
788
3415
  const viewport = doc.createElement("div");
789
3416
  viewport.className = "re-lightbox-viewport";
790
3417
  viewport.tabIndex = 0;
791
- viewport.setAttribute("aria-label", "Images");
792
- const slides = items.map((_item, imageIndex) => {
3418
+ viewport.setAttribute("aria-label", strings.dialog);
3419
+ const makeSlide = () => {
793
3420
  const slide = doc.createElement("div");
794
3421
  slide.className = "re-lightbox-slide";
795
3422
  slide.dataset.carouselSlide = "";
796
3423
  slide.setAttribute("role", "group");
797
- slide.setAttribute("aria-label", `${imageIndex + 1} of ${items.length}`);
798
- viewport.append(slide);
799
3424
  return slide;
800
- });
3425
+ };
3426
+ const slides = items.map(() => makeSlide());
3427
+ viewport.append(...slides);
801
3428
  const backdrop = doc.createElement("div");
802
3429
  backdrop.className = "re-lightbox-backdrop";
803
3430
  backdrop.setAttribute("aria-hidden", "true");
804
- dialog.append(backdrop, viewport);
3431
+ const toolbar = doc.createElement("div");
3432
+ toolbar.className = "re-lightbox-toolbar";
3433
+ const toolbarStart = doc.createElement("div");
3434
+ toolbarStart.className = "re-lightbox-toolbar-start";
3435
+ const toolbarEnd = doc.createElement("div");
3436
+ toolbarEnd.className = "re-lightbox-toolbar-end";
3437
+ toolbar.append(toolbarStart, toolbarEnd);
3438
+ const paddingProbe = doc.createElement("div");
3439
+ paddingProbe.setAttribute("aria-hidden", "true");
3440
+ paddingProbe.style.cssText =
3441
+ "position:absolute;left:0;top:0;width:0;height:var(--re-lightbox-bottom-room, 0px);visibility:hidden;pointer-events:none;padding-left:var(--re-lightbox-padding, 32px)";
3442
+ stage.append(backdrop, viewport, toolbar, paddingProbe);
805
3443
  const abort = new AbortController();
806
- const button = (name, label, text, action) => {
807
- const element = doc.createElement("button");
808
- element.type = "button";
809
- element.className = `re-lightbox-button re-lightbox-${name}`;
3444
+ const button = (tag, name, label, action, parent) => {
3445
+ const element = doc.createElement(tag);
3446
+ if (tag === "button")
3447
+ element.setAttribute("type", "button");
3448
+ element.className = `re-lightbox-button re-lightbox-${name === "previous" ? "prev" : name}`;
810
3449
  element.setAttribute("aria-label", label);
811
- const icon = options.icons?.[name]?.();
812
- if (icon)
813
- element.append(icon);
814
- else
815
- element.textContent = text;
816
- element.addEventListener("click", action, { signal: abort.signal });
817
- dialog.append(element);
3450
+ showControlIcon(element, name);
3451
+ if (action)
3452
+ element.addEventListener("click", action, { signal: abort.signal });
3453
+ parent.append(element);
818
3454
  return element;
819
3455
  };
820
- const closeButton = button("close", "Close gallery", "×", () => {
821
- void close();
3456
+ let counter;
3457
+ if (control("counter")) {
3458
+ counter = counterNode(doc);
3459
+ toolbarStart.append(counter);
3460
+ }
3461
+ const zoomButton = control("zoom")
3462
+ ? button("button", "zoom", strings.zoomIn, () => toggleZoom(), toolbarEnd)
3463
+ : undefined;
3464
+ const slideshowButton = control("slideshow")
3465
+ ? button("button", "slideshow", strings.slideshowStart, () => toggleSlideshow(s), toolbarEnd)
3466
+ : undefined;
3467
+ const fullscreenButton = control("fullscreen") && doc.fullscreenEnabled
3468
+ ? button("button", "fullscreen", strings.fullscreenEnter, () => {
3469
+ if (doc.fullscreenElement === stage)
3470
+ void doc.exitFullscreen().catch(() => { });
3471
+ else
3472
+ void stage.requestFullscreen().catch(() => { });
3473
+ }, toolbarEnd)
3474
+ : undefined;
3475
+ const download = control("download")
3476
+ ? button("a", "download", strings.download, undefined, toolbarEnd)
3477
+ : undefined;
3478
+ download?.setAttribute("download", "");
3479
+ download?.setAttribute("rel", "noopener");
3480
+ // Browsers ignore the download attribute across origins, also after a same-origin URL
3481
+ // redirects to another one, and navigate the tab instead, and block a popup opened after
3482
+ // an await, so every web file is fetched before the click.
3483
+ let fetched;
3484
+ const native = () => !download ||
3485
+ download.protocol === "data:" ||
3486
+ download.protocol === "blob:";
3487
+ const save = (blob, pathname, named) => {
3488
+ const link = doc.createElement("a");
3489
+ link.href = URL.createObjectURL(blob);
3490
+ const name = pathname.split("/").pop() ?? "";
3491
+ try {
3492
+ link.download = named ?? decodeURIComponent(name);
3493
+ }
3494
+ catch {
3495
+ link.download = name;
3496
+ }
3497
+ link.click();
3498
+ setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
3499
+ };
3500
+ const prefetch = () => {
3501
+ if (!download || native() || fetched?.href === download.href)
3502
+ return;
3503
+ const { href, pathname } = download;
3504
+ const entry = { href };
3505
+ fetched = entry;
3506
+ fetch(href)
3507
+ .then((response) => {
3508
+ if (!response.ok)
3509
+ return Promise.reject();
3510
+ entry.name = dispositionName(response.headers.get("content-disposition"));
3511
+ return response.blob();
3512
+ })
3513
+ .then((blob) => {
3514
+ entry.blob = blob;
3515
+ if (entry.wanted)
3516
+ save(blob, pathname, entry.name);
3517
+ entry.wanted = false;
3518
+ }, () => {
3519
+ entry.failed = true;
3520
+ if (entry.wanted)
3521
+ doc.defaultView?.open(href, "_blank", "noopener");
3522
+ entry.wanted = false;
3523
+ });
3524
+ };
3525
+ download?.addEventListener("pointerdown", prefetch, {
3526
+ signal: abort.signal,
822
3527
  });
823
- closeButton.autofocus = true;
824
- const prev = button("prev", "Previous image", "‹", () => goTo(state.index - 1));
825
- const next = button("next", "Next image", "›", () => goTo(state.index + 1));
826
- const zoomButton = button("zoom", "Zoom in", "+", () => toggleZoom());
3528
+ download?.addEventListener("keydown", (event) => {
3529
+ if (event.key === "Enter" || event.key === " ")
3530
+ prefetch();
3531
+ }, { signal: abort.signal });
3532
+ download?.addEventListener("click", (event) => {
3533
+ download.removeAttribute("target");
3534
+ if (native() ||
3535
+ event.button ||
3536
+ event.metaKey ||
3537
+ event.ctrlKey ||
3538
+ event.shiftKey ||
3539
+ event.altKey)
3540
+ return;
3541
+ prefetch();
3542
+ const entry = fetched;
3543
+ if (!entry)
3544
+ return;
3545
+ if (entry.failed) {
3546
+ download.target = "_blank";
3547
+ return;
3548
+ }
3549
+ event.preventDefault();
3550
+ if (entry.blob)
3551
+ save(entry.blob, download.pathname, entry.name);
3552
+ else
3553
+ entry.wanted = true;
3554
+ }, { signal: abort.signal });
3555
+ const closeButton = control("close")
3556
+ ? button("button", "close", strings.close, () => void close(), toolbarEnd)
3557
+ : undefined;
3558
+ if (closeButton)
3559
+ closeButton.autofocus = true;
3560
+ const prev = control("arrows")
3561
+ ? button("button", "previous", strings.previous, () => step(-1), stage)
3562
+ : undefined;
3563
+ const next = control("arrows")
3564
+ ? button("button", "next", strings.next, () => step(1), stage)
3565
+ : undefined;
827
3566
  const footer = doc.createElement("div");
828
3567
  footer.className = "re-lightbox-footer";
829
- const counter = doc.createElement("output");
830
- counter.className = "re-lightbox-counter";
831
- counter.setAttribute("aria-live", "polite");
832
3568
  const caption = doc.createElement("p");
833
3569
  caption.className = "re-lightbox-caption";
834
- footer.append(caption, counter);
835
- dialog.append(footer);
3570
+ if (settings.caption !== "side")
3571
+ footer.append(caption);
3572
+ const status = doc.createElement("div");
3573
+ status.className = "re-lightbox-status";
3574
+ status.setAttribute("role", "status");
3575
+ stage.append(footer, status);
836
3576
  const thumbs = [];
837
- if (options.thumbnails) {
838
- const strip = doc.createElement("div");
839
- strip.className = "re-lightbox-thumbnails";
840
- strip.setAttribute("role", "group");
841
- strip.setAttribute("aria-label", "Choose image");
842
- items.forEach((item, i) => {
3577
+ let thumbStrip;
3578
+ let thumbRing;
3579
+ if (settings.thumbnails) {
3580
+ thumbStrip = doc.createElement("div");
3581
+ thumbStrip.className = "re-lightbox-thumbnails";
3582
+ thumbStrip.setAttribute("role", "group");
3583
+ thumbStrip.setAttribute("aria-label", strings.thumbnails);
3584
+ thumbRing = doc.createElement("span");
3585
+ thumbRing.className = "re-lightbox-thumbnail-ring";
3586
+ thumbRing.setAttribute("aria-hidden", "true");
3587
+ thumbRing.hidden = true;
3588
+ }
3589
+ const makeThumbs = (labels) => {
3590
+ if (!thumbStrip)
3591
+ return;
3592
+ thumbs.length = 0;
3593
+ thumbStrip.replaceChildren(...items.map((item, i) => {
843
3594
  const thumb = doc.createElement("button");
844
3595
  thumb.type = "button";
845
- thumb.setAttribute("aria-label", `Show image ${i + 1}`);
3596
+ thumb.tabIndex = -1;
3597
+ if (item.width && item.height)
3598
+ thumb.style.aspectRatio =
3599
+ item.width > MAX_THUMB_RATIO * item.height
3600
+ ? String(MAX_THUMB_RATIO)
3601
+ : `${item.width} / ${item.height}`;
3602
+ thumb.setAttribute("aria-label", labels.thumbnail(i, items.length));
846
3603
  const thumbnailSrc = item.thumbnailSrc || item.previewSrc;
847
3604
  if (thumbnailSrc) {
848
3605
  const image = doc.createElement("img");
@@ -853,16 +3610,24 @@ export function createLightbox(options = {}) {
853
3610
  }
854
3611
  else
855
3612
  thumb.textContent = String(i + 1);
856
- thumb.addEventListener("click", () => goTo(i), {
3613
+ thumb.addEventListener("click", () => {
3614
+ if (session)
3615
+ session.stripInput = false;
3616
+ if (i === state.index)
3617
+ session?.thumbCarousel?.goTo(i, "smooth");
3618
+ goTo(i);
3619
+ }, {
857
3620
  signal: abort.signal,
858
3621
  });
859
- strip.append(thumb);
860
3622
  thumbs.push(thumb);
861
- });
862
- footer.append(strip);
863
- }
864
- const previousFocus = doc.activeElement instanceof HTMLElement ? doc.activeElement : null;
865
- (options.container ?? doc.body).append(dialog);
3623
+ return thumb;
3624
+ }));
3625
+ };
3626
+ makeThumbs(strings);
3627
+ const previousFocus = isHTMLElement(doc.activeElement)
3628
+ ? doc.activeElement
3629
+ : null;
3630
+ (settings.container ?? doc.body).append(dialog);
866
3631
  const restoreScroll = lockScroll(doc);
867
3632
  try {
868
3633
  dialog.showModal();
@@ -872,66 +3637,146 @@ export function createLightbox(options = {}) {
872
3637
  dialog.remove();
873
3638
  throw error;
874
3639
  }
875
- const carousel = createCarousel(viewport, {
876
- drag: true,
877
- onChange: (value) => {
878
- if (!syncingCarousel && session?.dialog === dialog)
879
- activeChanged(session, value.index);
880
- },
881
- });
882
3640
  const s = {
883
3641
  dialog,
3642
+ stage,
884
3643
  viewport,
885
3644
  backdrop,
886
3645
  slides,
887
3646
  loaded: new Map(),
888
- carousel,
3647
+ carousel: connect(viewport, strings),
3648
+ heading: 1,
3649
+ strings,
3650
+ slots: [],
3651
+ footer,
3652
+ thumbStrip,
3653
+ thumbRing,
3654
+ roving: -1,
3655
+ centeredThumb: -1,
3656
+ stripInput: false,
3657
+ scrubbing: false,
3658
+ reported: -1,
3659
+ pauses: new Set(["phase"]),
889
3660
  abort,
890
3661
  animations: new Set(),
891
3662
  finishAnimations: new Set(),
892
3663
  previousFocus,
893
3664
  restoreScroll,
894
- counter,
3665
+ phase: "entering",
3666
+ timing: {
3667
+ open: OPEN_DURATION,
3668
+ close: CLOSE_DURATION,
3669
+ zoom: ZOOM_DURATION,
3670
+ fade: FADE_DURATION,
3671
+ ease: FLIGHT_EASE,
3672
+ },
3673
+ chrome: initialChrome(false),
3674
+ chromeRoots: [toolbar, footer, ...(prev && next ? [prev, next] : [])],
3675
+ openingFocus: closeButton ?? viewport,
3676
+ zoomed: false,
3677
+ counters: counter ? [counter] : [],
3678
+ counterText: "",
3679
+ status,
895
3680
  caption,
3681
+ captionText: "",
896
3682
  prev,
897
3683
  next,
898
3684
  zoomButton,
3685
+ fullscreenButton,
3686
+ download,
3687
+ slideshowButton,
899
3688
  thumbs,
3689
+ makeSlide,
3690
+ makeThumbs,
900
3691
  pointers: new Map(),
3692
+ paddingProbe,
3693
+ box: { left: 0, top: 0, width: 1, height: 1 },
3694
+ area: { width: 1, height: 1 },
3695
+ inset: { left: 0, right: 0, bottom: 0 },
3696
+ room: { left: 0, right: 0, bottom: 0 },
901
3697
  suppressClickUntil: 0,
3698
+ paged: false,
3699
+ flying: true,
3700
+ watchedScale: 1,
3701
+ sharpScale: 1,
3702
+ autoplay: settings.autoplayMedia !== false &&
3703
+ (doc.defaultView?.navigator.userActivation?.isActive ?? true),
902
3704
  };
3705
+ measure(s);
903
3706
  session = s;
3707
+ if (doc.defaultView)
3708
+ enterHistory(doc.defaultView);
904
3709
  publish({
905
3710
  isOpen: true,
906
3711
  isClosing: false,
3712
+ isAnimating: false,
907
3713
  index: clamp(Math.floor(index), 0, items.length - 1),
908
3714
  count: items.length,
909
- zoom: { ...identity },
3715
+ zoom: restZoom(s, clamp(Math.floor(index), 0, items.length - 1)),
3716
+ chrome: "shown",
3717
+ });
3718
+ placeAside(s);
3719
+ mountSlots(s, {
3720
+ toolbarStart: (node) => toolbarStart.append(node),
3721
+ toolbarEnd: (node) => closeButton ? closeButton.before(node) : toolbarEnd.append(node),
3722
+ footer: (node) => footer.append(node),
3723
+ aside: (node) => s.aside?.append(node),
910
3724
  });
3725
+ placeThumbs(s);
3726
+ measure(s);
911
3727
  update(s);
912
- carousel.goTo(state.index, "instant");
3728
+ s.carousel.goTo(state.index, "instant");
913
3729
  dialog.addEventListener("cancel", (event) => {
914
3730
  event.preventDefault();
915
3731
  void close();
916
3732
  }, { signal: abort.signal });
917
3733
  dialog.addEventListener("close", () => {
918
- if (session === s) {
919
- teardown(s);
920
- publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
921
- }
3734
+ if (session !== s || s.phase === "closing")
3735
+ return;
3736
+ teardown(s);
3737
+ publish({
3738
+ isOpen: false,
3739
+ isClosing: false,
3740
+ isAnimating: false,
3741
+ zoom: { ...identity },
3742
+ });
3743
+ void reportClosed(leaveHistory());
922
3744
  }, { signal: abort.signal });
923
3745
  dialog.addEventListener("keydown", (event) => {
3746
+ s.openingFocus = null;
3747
+ chromeInput(s, { type: "key" });
924
3748
  if (event.defaultPrevented ||
925
- (event.target instanceof Element &&
3749
+ (isElement(event.target) &&
926
3750
  event.target.closest("input,textarea,select,[contenteditable=true],[data-lightbox-interactive]")))
927
3751
  return;
928
- if (event.key === "ArrowLeft") {
3752
+ if ((event.ctrlKey || event.metaKey) &&
3753
+ !event.altKey &&
3754
+ (event.key.toLowerCase() === "c" ||
3755
+ (!/^[a-z]$/i.test(event.key) && event.code === "KeyC"))) {
3756
+ copyImage(s, event);
3757
+ return;
3758
+ }
3759
+ if (event.altKey || event.ctrlKey || event.metaKey)
3760
+ return;
3761
+ const pan = {
3762
+ ArrowLeft: [KEY_PAN, 0],
3763
+ ArrowRight: [-KEY_PAN, 0],
3764
+ ArrowUp: [0, KEY_PAN],
3765
+ ArrowDown: [0, -KEY_PAN],
3766
+ }[event.key];
3767
+ if (pan &&
3768
+ (state.zoom.scale > 1 || (pan[0] === 0 && tall(state.index, s)))) {
929
3769
  event.preventDefault();
930
- goTo(state.index - 1);
3770
+ panBy(s, pan[0] * view(s).width, pan[1] * view(s).height);
931
3771
  }
932
- if (event.key === "ArrowRight") {
3772
+ else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
933
3773
  event.preventDefault();
934
- goTo(state.index + 1);
3774
+ const rtl = doc.defaultView?.getComputedStyle(dialog).direction === "rtl";
3775
+ step((event.key === "ArrowRight") !== rtl ? 1 : -1);
3776
+ }
3777
+ if (event.key === "Home" || event.key === "End") {
3778
+ event.preventDefault();
3779
+ goTo(event.key === "Home" ? 0 : items.length - 1);
935
3780
  }
936
3781
  if (event.key === "+" || event.key === "=") {
937
3782
  event.preventDefault();
@@ -947,81 +3792,647 @@ export function createLightbox(options = {}) {
947
3792
  }
948
3793
  }, { signal: abort.signal });
949
3794
  doc.defaultView?.addEventListener("resize", () => {
950
- cancelAnimations(s);
951
- layout(s);
3795
+ s.resizeFrame ??= doc.defaultView?.requestAnimationFrame(() => resized(s));
952
3796
  }, { signal: abort.signal });
3797
+ viewport.addEventListener("pointerdown", () => {
3798
+ if (!s.stands)
3799
+ return;
3800
+ clearStands(s);
3801
+ quietly(() => s.carousel.goTo(state.index, "instant"));
3802
+ }, { signal: abort.signal, capture: true });
953
3803
  viewport.addEventListener("scrollend", () => trimSlides(s), {
954
3804
  signal: abort.signal,
955
3805
  });
3806
+ const win = doc.defaultView;
3807
+ const watch = () => {
3808
+ const motion = s.motion;
3809
+ if (!motion || session !== s || !win)
3810
+ return;
3811
+ const left = viewport.scrollLeft;
3812
+ motion.still = left === motion.left ? motion.still + 1 : 0;
3813
+ if (!Number.isNaN(motion.left) && left !== motion.left)
3814
+ motion.moved = true;
3815
+ motion.left = left;
3816
+ if ((motion.still >= 3 && isSettled(s)) || motion.still >= 30) {
3817
+ s.motion = undefined;
3818
+ clearStands(s);
3819
+ trimSlides(s);
3820
+ syncAnimating(s);
3821
+ const moved = motion.moved || s.paged;
3822
+ s.paged = false;
3823
+ if (moved)
3824
+ emit("settle", s);
3825
+ return;
3826
+ }
3827
+ motion.frame = win.requestAnimationFrame(watch);
3828
+ };
3829
+ viewport.addEventListener("scroll", () => {
3830
+ if (s.motion || session !== s || !win)
3831
+ return;
3832
+ s.motion = {
3833
+ frame: win.requestAnimationFrame(watch),
3834
+ left: Number.NaN,
3835
+ still: 0,
3836
+ moved: false,
3837
+ };
3838
+ syncAnimating(s);
3839
+ }, { signal: abort.signal, passive: true });
956
3840
  installGestures(s);
957
- closeButton.focus({ preventScroll: true });
958
- void Promise.all([
959
- morph(s, false),
960
- animate(s, s.backdrop, [{ opacity: 0 }, { opacity: 1 }], Math.max(0, options.duration ?? 280)),
961
- ]);
3841
+ for (const [type, input] of [
3842
+ ["keydown", "keyboard"],
3843
+ ["pointerdown", "pointer"],
3844
+ ])
3845
+ win?.addEventListener(type, () => {
3846
+ s.input = input;
3847
+ }, { signal: abort.signal, capture: true, passive: true });
3848
+ dialog.addEventListener("pointermove", (event) => {
3849
+ if (event.pointerType === "mouse" && event.buttons === 0)
3850
+ chromeInput(s, {
3851
+ type: "move",
3852
+ point: { x: event.clientX, y: event.clientY },
3853
+ movement: { x: event.movementX, y: event.movementY },
3854
+ });
3855
+ }, { signal: abort.signal, passive: true });
3856
+ dialog.addEventListener("pointerdown", (event) => {
3857
+ if (event.pointerType === "touch" || event.pointerType === "pen")
3858
+ chromeInput(s, { type: "touch" });
3859
+ }, { signal: abort.signal, passive: true, capture: true });
3860
+ dialog.addEventListener("focusin", (event) => {
3861
+ const target = event.target;
3862
+ if (target !== s.openingFocus &&
3863
+ isNode(target) &&
3864
+ s.chromeRoots.some((root) => root.contains(target)))
3865
+ chromeInput(s, { type: "focus" });
3866
+ }, { signal: abort.signal });
3867
+ const opening = closeButton ?? viewport;
3868
+ // window.event is the click or tap that called open(); a key's click has detail 0.
3869
+ const opener = win?.event;
3870
+ const pointerOpen = opener !== undefined &&
3871
+ (/^(pointer|touch|mouse)/.test(opener.type) ||
3872
+ (opener.type === "click" && opener.detail > 0));
3873
+ opening.focus(pointerOpen
3874
+ ? { preventScroll: true, focusVisible: false }
3875
+ : { preventScroll: true });
3876
+ if (pointerOpen && matches(opening, ":focus-visible"))
3877
+ quietFocus(opening);
3878
+ watchControls(s);
3879
+ readTiming(s);
3880
+ void win?.getComputedStyle(toolbar).opacity;
3881
+ setPhase(s, "opening");
3882
+ applyChrome(s, initialChrome(Boolean(win?.matchMedia?.("(hover: hover)").matches)));
3883
+ s.reported = state.index;
3884
+ emit("open", s);
3885
+ void flight(s, false).then(() => {
3886
+ if (session !== s || state.isClosing)
3887
+ return;
3888
+ s.flying = false;
3889
+ swapHeld(s);
3890
+ const current = s.loaded.get(state.index);
3891
+ if (current?.media?.mounted)
3892
+ current.media.mounted.resume?.();
3893
+ else if (current)
3894
+ mountMedia(s, state.index, current);
3895
+ if (s.phase === "opening")
3896
+ setPhase(s, "open");
3897
+ emit("opened", s);
3898
+ });
962
3899
  }
963
3900
  function close() {
3901
+ return closeSession(false);
3902
+ }
3903
+ // The stage keeps its open size, so a page scrollbar that returns does not reflow the viewer,
3904
+ // and the dialog clips it to the page's new client size, which WebKit's dialog box lags behind.
3905
+ function pinToPage(s, open) {
3906
+ const win = s.dialog.ownerDocument.defaultView;
3907
+ if (!win)
3908
+ return;
3909
+ const root = s.dialog.ownerDocument.documentElement;
3910
+ Object.assign(s.stage.style, {
3911
+ right: "auto",
3912
+ bottom: "auto",
3913
+ width: `${open.width}px`,
3914
+ height: `${open.height}px`,
3915
+ });
3916
+ Object.assign(s.dialog.style, {
3917
+ position: "absolute",
3918
+ inset: "auto",
3919
+ top: `${open.top + win.scrollY}px`,
3920
+ left: `${open.left + win.scrollX}px`,
3921
+ width: `${Math.min(open.width, root.clientWidth)}px`,
3922
+ height: `${Math.min(open.height, root.clientHeight)}px`,
3923
+ });
3924
+ }
3925
+ // A modal dialog keeps the page inert, so the close flight moves to a manual popover: still
3926
+ // above the page, but wheel, touch and clicks pass through to it.
3927
+ function releasePage(s) {
3928
+ const dialog = s.dialog;
3929
+ if (typeof dialog.showPopover !== "function")
3930
+ return;
3931
+ dialog.inert = true;
3932
+ dialog.close();
3933
+ dialog.style.display = "block";
3934
+ dialog.popover = "manual";
3935
+ dialog.showPopover();
3936
+ s.releasedFocus = dialog.ownerDocument.activeElement;
3937
+ }
3938
+ // closed waits for the history back, unless open() or destroy() comes first.
3939
+ function reportClosed(landing) {
3940
+ let reported = false;
3941
+ const report = () => {
3942
+ if (reported)
3943
+ return;
3944
+ reported = true;
3945
+ if (pendingClosed === report)
3946
+ pendingClosed = undefined;
3947
+ emit("closed", null);
3948
+ };
3949
+ pendingClosed = report;
3950
+ return landing.then(report);
3951
+ }
3952
+ function closeSession(fromHistory, force = false) {
964
3953
  const s = session;
965
3954
  if (!s)
966
- return Promise.resolve();
3955
+ return closePromise ?? Promise.resolve();
967
3956
  if (closePromise)
968
3957
  return closePromise;
3958
+ if (vetting) {
3959
+ forcing ||= force;
3960
+ return Promise.resolve();
3961
+ }
3962
+ vetting = true;
3963
+ forcing = force;
3964
+ let prevented;
3965
+ try {
3966
+ prevented = emit("beforeclose", s, { cancelable: !force }) && !forcing;
3967
+ }
3968
+ finally {
3969
+ vetting = false;
3970
+ forcing = false;
3971
+ }
3972
+ if (prevented) {
3973
+ if (fromHistory && historyWindow)
3974
+ pushHistory(historyWindow);
3975
+ return Promise.resolve();
3976
+ }
3977
+ if (session !== s || closePromise)
3978
+ return closePromise ?? Promise.resolve();
3979
+ const landing = s.phase !== "entering" && s.phase !== "opening";
3980
+ if (fromHistory)
3981
+ s.input = "pointer";
969
3982
  cancelAnimations(s);
3983
+ clearStands(s);
3984
+ clearTimeout(s.tapTimer);
3985
+ s.tapTimer = undefined;
3986
+ s.pointers.clear();
3987
+ s.gesture = undefined;
3988
+ delete s.dialog.dataset.panning;
3989
+ // beforeclose may have rendered the tile again.
3990
+ hideOrigin(s);
3991
+ chromeInput(s, { type: "close" });
970
3992
  publish({ isClosing: true });
971
- closePromise = (async () => {
972
- await Promise.all([
973
- morph(s, true),
974
- animate(s, s.backdrop, [{ opacity: 1 }, { opacity: 0 }], Math.max(0, options.duration ?? 280)),
975
- ]);
3993
+ leaveFullscreen(s);
3994
+ for (const entry of s.loaded.values())
3995
+ entry.media?.mounted?.pause?.();
3996
+ s.dialog.style.removeProperty("--re-lightbox-chrome-opacity");
3997
+ setPhase(s, "closing");
3998
+ const open = s.dialog.getBoundingClientRect();
3999
+ s.restoreScroll();
4000
+ pinToPage(s, open);
4001
+ releasePage(s);
4002
+ let closing;
4003
+ closing = (async () => {
4004
+ await flight(s, true, landing);
976
4005
  if (session !== s)
977
4006
  return;
978
4007
  teardown(s);
979
- closePromise = undefined;
980
- publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
4008
+ publish({
4009
+ isOpen: false,
4010
+ isClosing: false,
4011
+ isAnimating: false,
4012
+ zoom: { ...identity },
4013
+ });
4014
+ if (fromHistory)
4015
+ releaseHistory();
4016
+ await reportClosed(fromHistory ? Promise.resolve() : leaveHistory());
4017
+ if (closePromise === closing)
4018
+ closePromise = undefined;
981
4019
  })();
982
- return closePromise;
4020
+ closePromise = closing;
4021
+ return closing;
983
4022
  }
984
- return {
4023
+ function setItems(input, index) {
4024
+ if (destroyed)
4025
+ throw new Error("This lightbox has been destroyed.");
4026
+ const nextItems = input.length
4027
+ ? validateItems(input, (session ? settings : current).content)
4028
+ : [];
4029
+ if (index !== undefined && !Number.isFinite(index))
4030
+ throw new TypeError("Image index must be finite.");
4031
+ const s = session;
4032
+ if (!s) {
4033
+ items = nextItems;
4034
+ sources = [...input];
4035
+ publish({ count: items.length, index: lastIndex() });
4036
+ return;
4037
+ }
4038
+ if (state.isClosing || !nextItems.length) {
4039
+ listAfterClose = { items: nextItems, sources: [...input] };
4040
+ if (!state.isClosing)
4041
+ void closeSession(false, true);
4042
+ if (!state.isClosing && !forcing && session === s)
4043
+ listAfterClose = undefined;
4044
+ return;
4045
+ }
4046
+ finishFade(s, true);
4047
+ clearStands(s);
4048
+ const taken = new Set();
4049
+ const from = input.map((item) => {
4050
+ const old = sources.indexOf(item);
4051
+ if (old < 0 || taken.has(old))
4052
+ return -1;
4053
+ taken.add(old);
4054
+ return old;
4055
+ });
4056
+ for (const [j, item] of nextItems.entries()) {
4057
+ if (from[j] >= 0)
4058
+ continue;
4059
+ const old = items.findIndex((candidate, i) => !taken.has(i) && item.src !== undefined && candidate.src === item.src);
4060
+ if (old < 0)
4061
+ continue;
4062
+ taken.add(old);
4063
+ from[j] = old;
4064
+ }
4065
+ let target = from.indexOf(state.index);
4066
+ const kept = target >= 0;
4067
+ if (!kept && index !== undefined)
4068
+ target = clamp(Math.floor(index), 0, nextItems.length - 1);
4069
+ for (let gap = 1; target < 0 && gap < items.length; gap++) {
4070
+ target = from.indexOf(state.index + gap);
4071
+ if (target < 0)
4072
+ target = from.indexOf(state.index - gap);
4073
+ }
4074
+ if (target < 0)
4075
+ target = clamp(state.index, 0, nextItems.length - 1);
4076
+ if ((!kept || target !== state.index) && !notifyBeforeChange(s, target))
4077
+ return;
4078
+ const slides = nextItems.map((item, j) => {
4079
+ const old = from[j];
4080
+ if (old < 0)
4081
+ return s.makeSlide();
4082
+ item.width ??= items[old].width;
4083
+ item.height ??= items[old].height;
4084
+ return s.slides[old];
4085
+ });
4086
+ const loaded = new Map();
4087
+ for (const [old, entry] of s.loaded) {
4088
+ const j = from.indexOf(old);
4089
+ if (j >= 0)
4090
+ loaded.set(j, entry);
4091
+ else
4092
+ entry.cancel();
4093
+ }
4094
+ for (const [old, slide] of s.slides.entries())
4095
+ if (!taken.has(old))
4096
+ slide.remove();
4097
+ if (kept) {
4098
+ let anchor = slides[target];
4099
+ for (let j = target - 1; j >= 0; j--) {
4100
+ if (anchor.previousElementSibling !== slides[j])
4101
+ anchor.before(slides[j]);
4102
+ anchor = slides[j];
4103
+ }
4104
+ anchor = slides[target];
4105
+ for (let j = target + 1; j < slides.length; j++) {
4106
+ if (anchor.nextElementSibling !== slides[j])
4107
+ anchor.after(slides[j]);
4108
+ anchor = slides[j];
4109
+ }
4110
+ }
4111
+ else {
4112
+ cancelAnimations(s);
4113
+ s.viewport.append(...slides);
4114
+ }
4115
+ items = nextItems;
4116
+ sources = [...input];
4117
+ s.slides = slides;
4118
+ s.loaded = loaded;
4119
+ s.marked = undefined;
4120
+ s.makeThumbs(s.strings);
4121
+ s.thumbCenters = undefined;
4122
+ s.roving = -1;
4123
+ s.thumbCarousel?.refresh();
4124
+ s.centeredThumb = Number.NaN;
4125
+ placeAside(s, true);
4126
+ const changed = target !== state.index;
4127
+ const looped = s.carousel.getState().isLooping;
4128
+ if ((changed || !kept || looped) && state.zoom.scale > 1) {
4129
+ updateState({ zoom: restZoom(s, target) });
4130
+ applyZoom(s);
4131
+ }
4132
+ else if (changed || !kept)
4133
+ updateState({ zoom: restZoom(s, target) });
4134
+ quietly(() => {
4135
+ s.carousel.refresh();
4136
+ s.carousel.setOptions({ loop: looping() });
4137
+ if (!kept || looped !== s.carousel.getState().isLooping)
4138
+ s.carousel.goTo(target, "instant");
4139
+ });
4140
+ publish({ index: target, count: items.length });
4141
+ update(s);
4142
+ s.reported = target;
4143
+ if (!kept)
4144
+ arrived(s, target);
4145
+ else if (changed)
4146
+ emit("change", s);
4147
+ }
4148
+ const controller = {
985
4149
  open,
986
4150
  close,
987
- next: () => goTo(state.index + 1),
988
- prev: () => goTo(state.index - 1),
4151
+ next: () => step(1),
4152
+ prev: () => step(-1),
989
4153
  goTo,
990
4154
  zoomTo,
991
4155
  toggleZoom,
992
- getState: () => state,
993
- subscribe: (listener) => {
994
- listeners.add(listener);
995
- return () => {
996
- listeners.delete(listener);
997
- };
4156
+ play: () => {
4157
+ if (session && !state.isClosing && items.length > 1)
4158
+ toggleSlideshow(session, true);
4159
+ },
4160
+ pause: () => {
4161
+ if (session)
4162
+ toggleSlideshow(session, false);
4163
+ },
4164
+ getState: () => notifiedState,
4165
+ subscribe: (listener, { signal } = {}) => listen(listeners, listener, stops, signal),
4166
+ on: (type, listener, { signal } = {}) => {
4167
+ const set = handlers.get(type) ?? new Set();
4168
+ handlers.set(type, set);
4169
+ return listen(set, listener, stops, signal);
4170
+ },
4171
+ append: (input) => setItems([...(listAfterClose?.sources ?? sources), ...input]),
4172
+ setItems,
4173
+ setOptions: (next) => {
4174
+ for (const key of Object.keys(next))
4175
+ if (key !== "container")
4176
+ Object.assign(current, { [key]: next[key] });
4177
+ const s = session;
4178
+ if ("strings" in next) {
4179
+ settings.strings = next.strings;
4180
+ if (s)
4181
+ relabel(s);
4182
+ }
4183
+ if ("thumbnailsVisible" in next &&
4184
+ settings.thumbnailsVisible !== next.thumbnailsVisible) {
4185
+ settings.thumbnailsVisible = next.thumbnailsVisible;
4186
+ if (s?.thumbStrip && !state.isClosing) {
4187
+ placeThumbs(s);
4188
+ resized(s);
4189
+ }
4190
+ }
4191
+ if (!("loop" in next) || Boolean(next.loop) === loop)
4192
+ return;
4193
+ loop = Boolean(next.loop);
4194
+ publish({});
4195
+ if (!s || state.isClosing)
4196
+ return;
4197
+ const looped = s.carousel.getState().isLooping;
4198
+ quietly(() => {
4199
+ s.carousel.setOptions({ loop: looping() });
4200
+ s.carousel.goTo(state.index, "instant");
4201
+ });
4202
+ if (looped !== s.carousel.getState().isLooping)
4203
+ applyZoom(s);
4204
+ update(s);
998
4205
  },
4206
+ getSlide: (index) => session?.slides[index] ?? null,
999
4207
  destroy: () => {
1000
4208
  if (destroyed)
1001
4209
  return;
1002
4210
  destroyed = true;
1003
- if (session)
1004
- teardown(session);
1005
- closePromise = undefined;
1006
- publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
4211
+ release();
4212
+ for (const stop of [...stops])
4213
+ stop();
1007
4214
  listeners.clear();
4215
+ handlers.clear();
1008
4216
  },
1009
4217
  };
4218
+ function release() {
4219
+ pendingClosed?.();
4220
+ const s = session;
4221
+ if (s)
4222
+ teardown(s);
4223
+ closePromise = undefined;
4224
+ publish({
4225
+ isOpen: false,
4226
+ isClosing: false,
4227
+ isAnimating: false,
4228
+ zoom: { ...identity },
4229
+ });
4230
+ if (s)
4231
+ emit("closed", null);
4232
+ const win = historyWindow;
4233
+ if (win && ownsHistory(win))
4234
+ goBack(win);
4235
+ else if (win) {
4236
+ orphan(win, historyId);
4237
+ if (!historyBacks.has(win))
4238
+ releaseScroll(win);
4239
+ }
4240
+ win?.removeEventListener("popstate", onPopState);
4241
+ historyWindow = undefined;
4242
+ }
4243
+ const reach = {
4244
+ initial: initial,
4245
+ release: () => {
4246
+ if (!destroyed)
4247
+ release();
4248
+ },
4249
+ shows: (type) => Boolean(current.content?.some((module) => module.type === type)),
4250
+ destroyed: () => destroyed,
4251
+ openWith: (layer, open) => {
4252
+ galleryOptions = layer;
4253
+ try {
4254
+ open();
4255
+ }
4256
+ finally {
4257
+ galleryOptions = undefined;
4258
+ }
4259
+ },
4260
+ };
4261
+ Object.defineProperty(controller, lightboxInternals, { value: reach });
4262
+ return controller;
4263
+ }
4264
+ function listen(set, listener, stops, signal) {
4265
+ const stop = () => {
4266
+ set.delete(listener);
4267
+ stops.delete(stop);
4268
+ signal?.removeEventListener("abort", stop);
4269
+ };
4270
+ if (signal?.aborted)
4271
+ return stop;
4272
+ set.add(listener);
4273
+ stops.add(stop);
4274
+ signal?.addEventListener("abort", stop, { once: true });
4275
+ return stop;
4276
+ }
4277
+ function dispositionName(header) {
4278
+ if (!header)
4279
+ return undefined;
4280
+ const extended = /filename\*\s*=\s*utf-8'[^']*'([^;\s]+)/i.exec(header);
4281
+ if (extended)
4282
+ try {
4283
+ return decodeURIComponent(extended[1]);
4284
+ }
4285
+ catch { }
4286
+ const plain = /filename\s*=\s*(?:"((?:\\.|[^"\\])*)"|([^;\s]+))/i.exec(header);
4287
+ return plain?.[1]?.replace(/\\(.)/g, "$1") || plain?.[2] || undefined;
1010
4288
  }
1011
- export function lightboxItemFromImage(image, source = image.dataset.lightboxSrc || image.currentSrc || image.src) {
4289
+ function dimension(value) {
4290
+ const number = Number(value);
4291
+ return value && Number.isFinite(number) && number > 0 ? number : undefined;
4292
+ }
4293
+ /**
4294
+ * The item a gallery trigger opens: a link, a button or an img, and the img inside it. Returns
4295
+ * null when the trigger names no image file and no media type, so the page keeps its click.
4296
+ */
4297
+ export function lightboxItemFromElement(trigger) {
4298
+ const image = trigger.localName === "img"
4299
+ ? trigger
4300
+ : trigger.querySelector("img");
4301
+ const base = trigger.baseURI;
4302
+ const link = trigger.closest("a[href]");
4303
+ const href = link?.getAttribute("href") || undefined;
4304
+ const data = (name) => trigger.dataset[name] || image?.dataset[name] || undefined;
4305
+ const tile = (image && (image.currentSrc || image.src)) || undefined;
4306
+ const width = dimension(data("lightboxWidth"));
4307
+ const height = dimension(data("lightboxHeight"));
4308
+ const caption = trigger
4309
+ .closest("figure")
4310
+ ?.querySelector(":scope > figcaption")
4311
+ ?.textContent?.trim() ||
4312
+ data("lightboxCaption") ||
4313
+ link?.dataset.lightboxCaption;
4314
+ const alt = image
4315
+ ? image.alt
4316
+ : trigger.getAttribute("aria-label") || trigger.textContent?.trim();
4317
+ const origin = image ?? trigger;
4318
+ // Without JavaScript the link still leads to the video or the page it plays.
4319
+ const type = data("lightboxType") || link?.dataset.lightboxType;
4320
+ if (type)
4321
+ return {
4322
+ type,
4323
+ src: href || data("lightboxSrc") || tile,
4324
+ previewSrc: tile,
4325
+ width,
4326
+ height,
4327
+ alt,
4328
+ caption: caption || undefined,
4329
+ origin,
4330
+ };
4331
+ const src = (href && isImageFile(href, base) ? href : undefined) ||
4332
+ data("lightboxSrc") ||
4333
+ tile;
4334
+ if (!src)
4335
+ return null;
4336
+ const resolve = (url) => {
4337
+ try {
4338
+ return new URL(url, base).href;
4339
+ }
4340
+ catch {
4341
+ return url;
4342
+ }
4343
+ };
4344
+ const file = image?.naturalWidth &&
4345
+ image.naturalHeight &&
4346
+ resolve(src) === resolve(tile ?? "")
4347
+ ? fileWidth(image, image.srcset || undefined, base)
4348
+ : undefined;
1012
4349
  return {
1013
- src: source,
1014
- previewSrc: image.currentSrc || image.src,
1015
- width: image.naturalWidth || undefined,
1016
- height: image.naturalHeight || undefined,
1017
- alt: image.alt,
1018
- origin: image,
4350
+ src,
4351
+ srcset: data("lightboxSrcset"),
4352
+ sizes: data("lightboxSizes"),
4353
+ previewSrc: tile,
4354
+ width: width ?? file,
4355
+ height: height ??
4356
+ (file && image
4357
+ ? Math.round((file * image.naturalHeight) / image.naturalWidth)
4358
+ : undefined),
4359
+ alt,
4360
+ caption: caption || undefined,
4361
+ origin,
1019
4362
  };
1020
4363
  }
1021
- export function bindLightboxGallery(root, options = {}) {
1022
- const controller = createLightbox(options);
4364
+ // Options that JSON can carry; strings only the ones that are text, not functions.
4365
+ const MARKUP_OPTIONS = new Set([
4366
+ "imageClick",
4367
+ "doubleTapZoom",
4368
+ "maxZoom",
4369
+ "tapZoom",
4370
+ "preload",
4371
+ "controls",
4372
+ "thumbnails",
4373
+ "thumbnailsVisible",
4374
+ "caption",
4375
+ "slideshow",
4376
+ "autoHide",
4377
+ "className",
4378
+ "autoplayMedia",
4379
+ "loop",
4380
+ "history",
4381
+ "strings",
4382
+ "protect",
4383
+ ]);
4384
+ function markupOptions(root) {
4385
+ const text = root.dataset.lightboxOptions;
4386
+ if (text === undefined)
4387
+ return undefined;
4388
+ const name = [
4389
+ root.localName,
4390
+ root.id && `#${root.id}`,
4391
+ ...[...root.classList].map((name) => `.${name}`),
4392
+ ].join("");
4393
+ const fail = (reason) => {
4394
+ throw new TypeError(`Invalid data-lightbox-options on ${name}: ${reason}`);
4395
+ };
4396
+ let value;
4397
+ try {
4398
+ value = JSON.parse(text);
4399
+ }
4400
+ catch (error) {
4401
+ fail(error.message);
4402
+ }
4403
+ if (typeof value !== "object" || value === null || Array.isArray(value))
4404
+ fail("expected a JSON object");
4405
+ const options = value;
4406
+ for (const key of Object.keys(options))
4407
+ if (!MARKUP_OPTIONS.has(key))
4408
+ fail(`${key} cannot be set in markup`);
4409
+ const strings = options.strings;
4410
+ if (strings !== undefined &&
4411
+ (typeof strings !== "object" || strings === null || Array.isArray(strings)))
4412
+ fail("strings must be an object");
4413
+ if (strings)
4414
+ for (const [key, text] of Object.entries(strings))
4415
+ if (typeof text !== "string" ||
4416
+ typeof defaultStrings[key] !== "string")
4417
+ fail(`strings.${key} must be one of the text strings`);
4418
+ return options;
4419
+ }
4420
+ const DEFAULT_TRIGGERS = "a[href]:not([download]):is(:has(img), [data-lightbox-type], [data-lightbox-src]), button, img:not(a[download] img)";
4421
+ /** Opens the triggers inside root in the lightbox on a plain click, and returns the function that unbinds. */
4422
+ export function bindLightboxGallery(root, lightbox, options = {}) {
4423
+ const reach = internalsOf(lightbox);
4424
+ if (!reach)
4425
+ throw new TypeError("bindLightboxGallery needs a lightbox from createLightbox() as its second argument.");
4426
+ const markup = markupOptions(root);
4427
+ const selector = options.selector ?? DEFAULT_TRIGGERS;
4428
+ const read = options.item ??
4429
+ lightboxItemFromElement;
4430
+ const group = options.group ??
4431
+ ((trigger) => trigger.closest("[data-lightbox-group]")?.dataset
4432
+ .lightboxGroup ?? "");
1023
4433
  const click = (event) => {
1024
4434
  if (event.defaultPrevented ||
4435
+ reach.destroyed() ||
1025
4436
  event.button !== 0 ||
1026
4437
  event.metaKey ||
1027
4438
  event.ctrlKey ||
@@ -1029,23 +4440,31 @@ export function bindLightboxGallery(root, options = {}) {
1029
4440
  event.altKey)
1030
4441
  return;
1031
4442
  const target = event.target;
1032
- if (!(target instanceof Element))
4443
+ if (!isElement(target) || target.closest(".re-lightbox"))
4444
+ return;
4445
+ const triggers = [...root.querySelectorAll(selector)].filter((element) => {
4446
+ if (element.classList.contains("re-lightbox-landing") ||
4447
+ element.closest(".re-lightbox"))
4448
+ return false;
4449
+ const outer = element.parentElement?.closest(selector);
4450
+ return !outer || outer === root || !root.contains(outer);
4451
+ });
4452
+ const trigger = triggers.find((candidate) => candidate.contains(target));
4453
+ if (!trigger)
1033
4454
  return;
1034
- const images = [
1035
- ...root.querySelectorAll(options.selector || "img"),
1036
- ];
1037
- const index = images.findIndex((image) => image === target || image.closest("a, button")?.contains(target));
1038
- if (index < 0)
4455
+ const name = group(trigger);
4456
+ // A clicked trigger whose media type has no module is followed; others leave such items out.
4457
+ const opened = triggers
4458
+ .filter((candidate) => group(candidate) === name)
4459
+ .map((candidate) => [candidate, read(candidate)])
4460
+ .filter((entry) => entry[1] !== null &&
4461
+ (entry[1].type === undefined || reach.shows(entry[1].type)));
4462
+ const at = opened.findIndex(([candidate]) => candidate === trigger);
4463
+ if (at < 0)
1039
4464
  return;
4465
+ reach.openWith(markup, () => lightbox.open(opened.map(([, item]) => item), at));
1040
4466
  event.preventDefault();
1041
- controller.open(images.map((image) => (options.getItem || lightboxItemFromImage)(image)), index);
1042
4467
  };
1043
4468
  root.addEventListener("click", click);
1044
- return {
1045
- ...controller,
1046
- destroy: () => {
1047
- root.removeEventListener("click", click);
1048
- controller.destroy();
1049
- },
1050
- };
4469
+ return () => root.removeEventListener("click", click);
1051
4470
  }