@reuse-sh/lightbox 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1051 @@
1
+ import { createCarousel } from "@reuse-sh/carousel";
2
+ import { boundZoom, clamp, contain, cover, identity, zoomAround, } from "./geometry.js";
3
+ const locks = new WeakMap();
4
+ function lockScroll(doc) {
5
+ const win = doc.defaultView;
6
+ if (!win)
7
+ return () => { };
8
+ let lock = locks.get(doc);
9
+ if (!lock) {
10
+ lock = {
11
+ count: 0,
12
+ overflow: doc.body.style.overflow,
13
+ paddingRight: doc.body.style.paddingRight,
14
+ gapProperty: doc.documentElement.style.getPropertyValue("--reuse-scrollbar-gap"),
15
+ x: win.scrollX,
16
+ y: win.scrollY,
17
+ };
18
+ locks.set(doc, lock);
19
+ const gap = Math.max(0, win.innerWidth - doc.documentElement.clientWidth);
20
+ if (gap)
21
+ doc.body.style.paddingRight = `${Number.parseFloat(win.getComputedStyle(doc.body).paddingRight || "0") + gap}px`;
22
+ // Fixed elements ignore body padding; they can add this gap themselves.
23
+ doc.documentElement.style.setProperty("--reuse-scrollbar-gap", `${gap}px`);
24
+ doc.body.style.overflow = "hidden";
25
+ }
26
+ lock.count++;
27
+ let restored = false;
28
+ return () => {
29
+ if (restored || !lock)
30
+ return;
31
+ restored = true;
32
+ lock.count--;
33
+ if (lock.count)
34
+ return;
35
+ doc.body.style.overflow = lock.overflow;
36
+ doc.body.style.paddingRight = lock.paddingRight;
37
+ if (lock.gapProperty)
38
+ doc.documentElement.style.setProperty("--reuse-scrollbar-gap", lock.gapProperty);
39
+ else
40
+ doc.documentElement.style.removeProperty("--reuse-scrollbar-gap");
41
+ if (win.scrollX !== lock.x || win.scrollY !== lock.y)
42
+ win.scrollTo(lock.x, lock.y);
43
+ locks.delete(doc);
44
+ };
45
+ }
46
+ function validateItems(items) {
47
+ if (!items.length)
48
+ throw new TypeError("Lightbox needs at least one image.");
49
+ return items.map((item) => {
50
+ if (!item || typeof item.src !== "string" || !item.src.trim())
51
+ throw new TypeError("Lightbox images need a source.");
52
+ if ((item.width !== undefined &&
53
+ (!Number.isFinite(item.width) || item.width <= 0)) ||
54
+ (item.height !== undefined &&
55
+ (!Number.isFinite(item.height) || item.height <= 0)))
56
+ throw new TypeError("Image dimensions must be positive finite numbers.");
57
+ return { ...item };
58
+ });
59
+ }
60
+ function distance(points) {
61
+ return Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
62
+ }
63
+ function midpoint(points) {
64
+ return {
65
+ x: (points[0].x + points[1].x) / 2,
66
+ y: (points[0].y + points[1].y) / 2,
67
+ };
68
+ }
69
+ 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);
74
+ let items = [];
75
+ let session;
76
+ let destroyed = false;
77
+ let syncingCarousel = false;
78
+ let closePromise;
79
+ let state = {
80
+ isOpen: false,
81
+ isClosing: false,
82
+ index: 0,
83
+ count: 0,
84
+ zoom: { ...identity },
85
+ };
86
+ const listeners = new Set();
87
+ let notifiedState = state;
88
+ function updateState(update) {
89
+ state = { ...state, ...update };
90
+ }
91
+ function publish(update) {
92
+ updateState(update);
93
+ if (state.isOpen === notifiedState.isOpen &&
94
+ state.isClosing === notifiedState.isClosing &&
95
+ state.index === notifiedState.index &&
96
+ state.count === notifiedState.count &&
97
+ state.zoom.scale === notifiedState.zoom.scale &&
98
+ state.zoom.x === notifiedState.zoom.x &&
99
+ state.zoom.y === notifiedState.zoom.y)
100
+ return;
101
+ notifiedState = state;
102
+ options.onChange?.(state);
103
+ for (const listener of listeners)
104
+ listener(state);
105
+ }
106
+ function view(s) {
107
+ const rect = s.viewport.getBoundingClientRect();
108
+ const win = s.dialog.ownerDocument.defaultView;
109
+ return {
110
+ width: rect.width || win?.innerWidth || 1,
111
+ height: rect.height || win?.innerHeight || 1,
112
+ };
113
+ }
114
+ function imageSize(index, s) {
115
+ 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
+ };
121
+ }
122
+ function fit(index, s) {
123
+ return contain(imageSize(index, s), view(s), padding);
124
+ }
125
+ function applyZoom(s) {
126
+ 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;
132
+ 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 ? "−" : "+";
137
+ s.dialog.dataset.zoomed = String(state.zoom.scale > 1);
138
+ }
139
+ function restoreOrigin(s) {
140
+ if (!s.hiddenOrigin)
141
+ return;
142
+ s.hiddenOrigin.element.style.visibility = s.hiddenOrigin.visibility;
143
+ s.hiddenOrigin = undefined;
144
+ }
145
+ function hideOrigin(s) {
146
+ restoreOrigin(s);
147
+ const origin = items[state.index]?.origin;
148
+ if (!origin?.isConnected)
149
+ return;
150
+ s.hiddenOrigin = { element: origin, visibility: origin.style.visibility };
151
+ origin.style.visibility = "hidden";
152
+ }
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")
156
+ return Promise.resolve();
157
+ 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
+ s.animations.add(animation);
164
+ let settled = false;
165
+ const finish = () => {
166
+ if (settled)
167
+ return;
168
+ settled = true;
169
+ clearTimeout(timer);
170
+ s.animations.delete(animation);
171
+ s.finishAnimations.delete(finish);
172
+ // commitStyles throws on an element that is no longer rendered, such
173
+ // as one inside a dialog the browser already closed.
174
+ try {
175
+ if (node.isConnected)
176
+ animation.commitStyles?.();
177
+ }
178
+ catch { }
179
+ animation.cancel();
180
+ resolve();
181
+ };
182
+ const timer = setTimeout(finish, duration + 80);
183
+ s.finishAnimations.add(finish);
184
+ void animation.finished.then(finish, finish);
185
+ });
186
+ }
187
+ function cancelAnimations(s) {
188
+ for (const finish of [...s.finishAnimations])
189
+ finish();
190
+ }
191
+ function morph(s, closing) {
192
+ const entry = s.loaded.get(state.index);
193
+ const item = items[state.index];
194
+ if (!entry || !item)
195
+ return Promise.resolve();
196
+ const win = s.dialog.ownerDocument.defaultView;
197
+ if (!win)
198
+ return Promise.resolve();
199
+ const current = win.getComputedStyle(entry.frame);
200
+ const resting = entry.frame.style.transform || "translate(0px, 0px) scale(1)";
201
+ const live = {
202
+ transform: current.transform === "none" ? resting : current.transform || resting,
203
+ clipPath: current.clipPath || "inset(0px round 0px)",
204
+ opacity: current.opacity || "1",
205
+ };
206
+ const origin = item.origin;
207
+ const rect = origin?.isConnected
208
+ ? origin.getBoundingClientRect()
209
+ : undefined;
210
+ const viewport = view(s);
211
+ 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) {
221
+ return animate(s, entry.frame, closing
222
+ ? [
223
+ live,
224
+ {
225
+ transform: `${live.transform} scale(.96)`,
226
+ opacity: 0,
227
+ },
228
+ ]
229
+ : [
230
+ { transform: "scale(.96)", opacity: 0 },
231
+ { transform: resting, opacity: 1 },
232
+ ], duration);
233
+ }
234
+ const style = win.getComputedStyle(origin);
235
+ const positions = style.objectPosition
236
+ .split(" ")
237
+ .map((value) => Number.parseFloat(value) / 100);
238
+ const crop = style.objectFit === "contain"
239
+ ? contain(imageSize(state.index, s), rect, 0)
240
+ : cover(imageSize(state.index, s), rect, {
241
+ x: Number.isFinite(positions[0]) ? positions[0] : 0.5,
242
+ y: Number.isFinite(positions[1]) ? positions[1] : 0.5,
243
+ });
244
+ const left = "left" in crop && typeof crop.left === "number"
245
+ ? crop.left
246
+ : (rect.width - crop.width) / 2;
247
+ const top = "top" in crop && typeof crop.top === "number"
248
+ ? crop.top
249
+ : (rect.height - crop.height) / 2;
250
+ 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;
254
+ const clipped = {
255
+ 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)`,
257
+ opacity: 1,
258
+ };
259
+ const expanded = {
260
+ transform: resting,
261
+ clipPath: "inset(0px round 0px)",
262
+ opacity: 1,
263
+ };
264
+ return animate(s, entry.frame, closing ? [live, clipped] : [clipped, expanded], duration);
265
+ }
266
+ function layout(s) {
267
+ for (const [index, entry] of s.loaded) {
268
+ const size = fit(index, s);
269
+ entry.frame.style.width = `${size.width}px`;
270
+ entry.frame.style.height = `${size.height}px`;
271
+ }
272
+ if (state.zoom.scale > 1)
273
+ publish({ zoom: boundZoom(state.zoom, fit(state.index, s), view(s)) });
274
+ applyZoom(s);
275
+ }
276
+ function visibleRange(s) {
277
+ const width = s.viewport.clientWidth;
278
+ const rtl = s.dialog.ownerDocument.defaultView?.getComputedStyle(s.viewport)
279
+ .direction === "rtl";
280
+ 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
+ });
289
+ }
290
+ // Unloads images outside the preload window, except those still on screen
291
+ // while the strip travels.
292
+ function trimSlides(s) {
293
+ if (session !== s)
294
+ return;
295
+ const visible = visibleRange(s);
296
+ for (const [index, entry] of s.loaded) {
297
+ if (Math.abs(index - state.index) <= preload || visible.includes(index))
298
+ continue;
299
+ entry.cancel();
300
+ entry.frame.remove();
301
+ s.loaded.delete(index);
302
+ }
303
+ }
304
+ function loadSlides(s) {
305
+ 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))
308
+ continue;
309
+ const item = items[index];
310
+ const doc = s.dialog.ownerDocument;
311
+ const frame = doc.createElement("div");
312
+ frame.className = "reuse-lightbox-frame";
313
+ const image = doc.createElement("img");
314
+ image.className = "reuse-lightbox-image";
315
+ image.alt = item.alt || "";
316
+ image.draggable = false;
317
+ image.decoding = "async";
318
+ const loader = doc.createElement("img");
319
+ loader.decoding = "async";
320
+ let alive = true;
321
+ let cleanup;
322
+ frame.append(image);
323
+ s.slides[index].append(frame);
324
+ const swap = () => {
325
+ if (!alive || session !== s)
326
+ 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;
332
+ frame.removeAttribute("data-loading");
333
+ layout(s);
334
+ };
335
+ const failed = () => {
336
+ if (!alive)
337
+ return;
338
+ frame.removeAttribute("data-loading");
339
+ frame.dataset.error = "true";
340
+ if (!item.previewSrc) {
341
+ const error = doc.createElement("span");
342
+ error.className = "reuse-lightbox-error";
343
+ error.setAttribute("role", "status");
344
+ error.textContent = "Image could not be loaded.";
345
+ frame.append(error);
346
+ }
347
+ };
348
+ loader.onload = () => {
349
+ if (typeof loader.decode === "function")
350
+ void loader.decode().then(swap, failed);
351
+ else
352
+ swap();
353
+ };
354
+ loader.onerror = failed;
355
+ if (item.previewSrc)
356
+ image.src = item.previewSrc;
357
+ frame.dataset.loading = "true";
358
+ s.loaded.set(index, {
359
+ frame,
360
+ image,
361
+ loader,
362
+ cancel: () => {
363
+ alive = false;
364
+ loader.onload = null;
365
+ loader.onerror = null;
366
+ loader.removeAttribute("src");
367
+ image.removeAttribute("src");
368
+ cleanup?.();
369
+ },
370
+ });
371
+ loader.src = item.src;
372
+ if (loader.complete && loader.naturalWidth)
373
+ loader.onload(new Event("load"));
374
+ cleanup = options.renderContent?.({
375
+ item,
376
+ index,
377
+ container: frame,
378
+ image,
379
+ });
380
+ }
381
+ layout(s);
382
+ }
383
+ function activeChanged(s, index) {
384
+ if (session !== s || state.index === index || state.isClosing)
385
+ return;
386
+ cancelAnimations(s);
387
+ const old = s.loaded.get(state.index);
388
+ if (old) {
389
+ old.frame.style.transform = "";
390
+ old.frame.style.clipPath = "";
391
+ old.frame.style.opacity = "";
392
+ }
393
+ publish({ index, zoom: { ...identity } });
394
+ update(s);
395
+ }
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);
410
+ }
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();
419
+ for (const entry of s.loaded.values())
420
+ entry.cancel();
421
+ restoreOrigin(s);
422
+ if (s.dialog.open)
423
+ s.dialog.close();
424
+ s.dialog.remove();
425
+ s.restoreScroll();
426
+ if (s.previousFocus?.isConnected)
427
+ s.previousFocus.focus({ preventScroll: true });
428
+ }
429
+ function setZoom(scale, focus, notify) {
430
+ const s = session;
431
+ if (!s || state.isClosing || !Number.isFinite(scale))
432
+ 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;
440
+ 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) {
455
+ frame.style.clipPath = "";
456
+ frame.style.opacity = "";
457
+ }
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
+ }
462
+ }
463
+ function zoomTo(scale, focus = { x: 0, y: 0 }) {
464
+ setZoom(scale, focus, true);
465
+ }
466
+ function toggleZoom(focus) {
467
+ zoomTo(state.zoom.scale > 1 ? 1 : tapZoom, focus);
468
+ }
469
+ function finishFade(s, jump) {
470
+ const fade = s.fade;
471
+ if (!fade)
472
+ return;
473
+ s.fade = undefined;
474
+ fade.animation?.cancel();
475
+ if (jump && !fade.jumped)
476
+ fade.jump();
477
+ }
478
+ // Distant images fade through the backdrop instead of scrolling past
479
+ // unloaded pages. The jump waits for the fade-out to really finish, because
480
+ // a busy main thread delays when an animation starts.
481
+ function fadeTo(s, target) {
482
+ const fade = {
483
+ jumped: false,
484
+ jump: () => {
485
+ fade.jumped = true;
486
+ if (session !== s)
487
+ return;
488
+ syncingCarousel = true;
489
+ s.carousel.goTo(target, "instant");
490
+ syncingCarousel = false;
491
+ trimSlides(s);
492
+ },
493
+ };
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") {
497
+ fade.jump();
498
+ return;
499
+ }
500
+ s.fade = fade;
501
+ const fadeOut = s.viewport.animate([{ opacity: 1 }, { opacity: 0 }], {
502
+ duration: duration * 0.45,
503
+ easing: "ease-in",
504
+ fill: "forwards",
505
+ });
506
+ fade.animation = fadeOut;
507
+ fadeOut.finished.then(() => {
508
+ if (s.fade !== fade)
509
+ return;
510
+ fade.jump();
511
+ const fadeIn = s.viewport.animate([{ opacity: 0 }, { opacity: 1 }], {
512
+ duration: duration * 0.55,
513
+ easing: "ease-out",
514
+ });
515
+ fade.animation = fadeIn;
516
+ fadeOut.cancel();
517
+ const done = () => {
518
+ if (s.fade === fade)
519
+ s.fade = undefined;
520
+ };
521
+ fadeIn.finished.then(done, done);
522
+ }, () => { });
523
+ }
524
+ function goTo(index) {
525
+ const s = session;
526
+ if (!s || state.isClosing || !Number.isFinite(index))
527
+ return;
528
+ finishFade(s, true);
529
+ 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);
538
+ }
539
+ function isSettled(s) {
540
+ return visibleRange(s).length <= 1;
541
+ }
542
+ function interruptImageMotion(s) {
543
+ const frame = s.loaded.get(state.index)?.frame;
544
+ const win = s.dialog.ownerDocument.defaultView;
545
+ const transform = frame && win?.getComputedStyle(frame).transform;
546
+ cancelAnimations(s);
547
+ if (transform && transform !== "none" && win?.DOMMatrixReadOnly) {
548
+ const matrix = new win.DOMMatrixReadOnly(transform);
549
+ const scale = Math.hypot(matrix.a, matrix.b);
550
+ if (scale > 1 || state.zoom.scale > 1) {
551
+ updateState({
552
+ zoom: boundZoom({ scale: Math.max(1, scale), x: matrix.e, y: matrix.f }, fit(state.index, s), view(s)),
553
+ });
554
+ }
555
+ }
556
+ if (frame) {
557
+ frame.style.clipPath = "";
558
+ frame.style.opacity = "";
559
+ }
560
+ applyZoom(s);
561
+ }
562
+ function installGestures(s) {
563
+ const signal = s.abort.signal;
564
+ const point = (event) => ({
565
+ x: event.clientX,
566
+ y: event.clientY,
567
+ });
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
+ };
576
+ const resetGesture = () => {
577
+ const points = [...s.pointers.values()];
578
+ if (!points.length) {
579
+ s.gesture = undefined;
580
+ return;
581
+ }
582
+ s.gesture = {
583
+ start: points[0],
584
+ zoom: { ...state.zoom },
585
+ distance: points.length > 1 ? distance(points) : 0,
586
+ midpoint: points.length > 1 ? midpoint(points) : points[0],
587
+ moved: false,
588
+ touch: s.gesture?.touch ?? true,
589
+ };
590
+ };
591
+ s.viewport.addEventListener("pointerdown", (event) => {
592
+ if (event.button !== 0 ||
593
+ state.isClosing ||
594
+ (event.target instanceof Element &&
595
+ event.target.closest("button, a, input, textarea, select, [data-lightbox-interactive]")))
596
+ return;
597
+ if (s.wheelTimer !== undefined) {
598
+ clearTimeout(s.wheelTimer);
599
+ s.wheelTimer = undefined;
600
+ publish({});
601
+ }
602
+ interruptImageMotion(s);
603
+ s.pointers.set(event.pointerId, point(event));
604
+ resetGesture();
605
+ if (s.gesture)
606
+ s.gesture.touch = event.pointerType !== "mouse";
607
+ if (state.zoom.scale > 1 || s.pointers.size > 1) {
608
+ s.viewport.setPointerCapture?.(event.pointerId);
609
+ event.preventDefault();
610
+ }
611
+ }, { signal });
612
+ s.viewport.addEventListener("pointermove", (event) => {
613
+ if (!s.pointers.has(event.pointerId) || !s.gesture)
614
+ return;
615
+ s.pointers.set(event.pointerId, point(event));
616
+ const points = [...s.pointers.values()];
617
+ const gesture = s.gesture;
618
+ const dx = event.clientX - gesture.start.x;
619
+ const dy = event.clientY - gesture.start.y;
620
+ if (Math.hypot(dx, dy) > 8 || points.length > 1)
621
+ gesture.moved = true;
622
+ if (points.length > 1 && gesture.distance > 0) {
623
+ event.preventDefault();
624
+ const middle = midpoint(points);
625
+ const scale = clamp((gesture.zoom.scale * distance(points)) / gesture.distance, 0.8, maxZoom * 1.15);
626
+ const zoom = zoomAround(gesture.zoom, scale, focus(gesture.midpoint));
627
+ zoom.x += middle.x - gesture.midpoint.x;
628
+ zoom.y += middle.y - gesture.midpoint.y;
629
+ updateState({ zoom });
630
+ applyZoom(s);
631
+ }
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})`;
659
+ }
660
+ }, { signal, passive: false });
661
+ const release = (event) => {
662
+ if (!s.pointers.has(event.pointerId))
663
+ return;
664
+ const gesture = s.gesture;
665
+ const hadPinch = s.pointers.size > 1;
666
+ s.pointers.delete(event.pointerId);
667
+ if (gesture?.moved)
668
+ 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();
675
+ return;
676
+ }
677
+ if (event.type === "pointerup" &&
678
+ gesture?.touch &&
679
+ !gesture.moved &&
680
+ !hadPinch) {
681
+ const now = Date.now();
682
+ const previous = s.lastTap;
683
+ const current = point(event);
684
+ if (options.doubleTapZoom !== false &&
685
+ previous &&
686
+ now - previous.time < 300 &&
687
+ Math.hypot(current.x - previous.point.x, current.y - previous.point.y) < 30) {
688
+ toggleZoom(focus(current));
689
+ s.lastTap = undefined;
690
+ }
691
+ else {
692
+ s.lastTap = { time: now, point: current };
693
+ if (options.imageClick === "close")
694
+ void close();
695
+ }
696
+ s.suppressClickUntil = now + 400;
697
+ }
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);
703
+ resetGesture();
704
+ if (hadPinch && s.gesture)
705
+ s.gesture.moved = true;
706
+ if (hadPinch)
707
+ s.lastTap = undefined;
708
+ };
709
+ s.dialog.ownerDocument.defaultView?.addEventListener("pointerup", release, {
710
+ signal,
711
+ });
712
+ s.dialog.ownerDocument.defaultView?.addEventListener("pointercancel", release, { signal });
713
+ s.viewport.addEventListener("lostpointercapture", release, { signal });
714
+ s.viewport.addEventListener("click", (event) => {
715
+ if (Date.now() < s.suppressClickUntil || state.isClosing)
716
+ return;
717
+ const target = event.target;
718
+ if (!(target instanceof Element) ||
719
+ target.closest("[data-lightbox-interactive],button,a,input,textarea,select"))
720
+ return;
721
+ if (!target.closest(".reuse-lightbox-frame")) {
722
+ void close();
723
+ return;
724
+ }
725
+ if (options.imageClick === "close")
726
+ void close();
727
+ else if (options.imageClick !== "none" && isSettled(s))
728
+ toggleZoom(focus({ x: event.clientX, y: event.clientY }));
729
+ }, { signal });
730
+ s.viewport.addEventListener("wheel", (event) => {
731
+ if (state.isClosing || (!event.ctrlKey && state.zoom.scale <= 1))
732
+ return;
733
+ 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);
743
+ }
744
+ else {
745
+ const unit = event.deltaMode === 1
746
+ ? 16
747
+ : event.deltaMode === 2
748
+ ? view(s).height
749
+ : 1;
750
+ updateState({
751
+ zoom: boundZoom({
752
+ ...state.zoom,
753
+ x: state.zoom.x - event.deltaX * unit,
754
+ y: state.zoom.y - event.deltaY * unit,
755
+ }, fit(state.index, s), view(s)),
756
+ });
757
+ applyZoom(s);
758
+ }
759
+ clearTimeout(s.wheelTimer);
760
+ s.wheelTimer = setTimeout(() => {
761
+ s.wheelTimer = undefined;
762
+ if (session === s && !state.isClosing)
763
+ publish({});
764
+ }, 150);
765
+ }, { signal, passive: false });
766
+ }
767
+ function open(input, index = 0) {
768
+ if (destroyed)
769
+ throw new Error("This lightbox has been destroyed.");
770
+ const nextItems = validateItems(input);
771
+ if (!Number.isFinite(index))
772
+ throw new TypeError("Image index must be finite.");
773
+ const doc = options.container?.ownerDocument ??
774
+ (typeof document === "undefined" ? undefined : document);
775
+ if (!doc?.body)
776
+ throw new Error("Opening a lightbox needs a browser document.");
777
+ if (session)
778
+ teardown(session);
779
+ items = nextItems;
780
+ closePromise = undefined;
781
+ const dialog = doc.createElement("dialog");
782
+ if (typeof dialog.showModal !== "function")
783
+ throw new Error("Lightbox requires native dialog support.");
784
+ dialog.className = ["reuse-lightbox", options.className]
785
+ .filter(Boolean)
786
+ .join(" ");
787
+ dialog.setAttribute("aria-label", options.label || "Image gallery");
788
+ const viewport = doc.createElement("div");
789
+ viewport.className = "reuse-lightbox-viewport";
790
+ viewport.tabIndex = 0;
791
+ viewport.setAttribute("aria-label", "Images");
792
+ const slides = items.map((_item, imageIndex) => {
793
+ const slide = doc.createElement("div");
794
+ slide.className = "reuse-lightbox-slide";
795
+ slide.dataset.carouselSlide = "";
796
+ slide.setAttribute("role", "group");
797
+ slide.setAttribute("aria-label", `${imageIndex + 1} of ${items.length}`);
798
+ viewport.append(slide);
799
+ return slide;
800
+ });
801
+ const backdrop = doc.createElement("div");
802
+ backdrop.className = "reuse-lightbox-backdrop";
803
+ backdrop.setAttribute("aria-hidden", "true");
804
+ dialog.append(backdrop, viewport);
805
+ const abort = new AbortController();
806
+ const button = (name, label, text, action) => {
807
+ const element = doc.createElement("button");
808
+ element.type = "button";
809
+ element.className = `reuse-lightbox-button reuse-lightbox-${name}`;
810
+ 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);
818
+ return element;
819
+ };
820
+ const closeButton = button("close", "Close gallery", "×", () => {
821
+ void close();
822
+ });
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());
827
+ const footer = doc.createElement("div");
828
+ footer.className = "reuse-lightbox-footer";
829
+ const counter = doc.createElement("output");
830
+ counter.className = "reuse-lightbox-counter";
831
+ counter.setAttribute("aria-live", "polite");
832
+ const caption = doc.createElement("p");
833
+ caption.className = "reuse-lightbox-caption";
834
+ footer.append(caption, counter);
835
+ dialog.append(footer);
836
+ const thumbs = [];
837
+ if (options.thumbnails) {
838
+ const strip = doc.createElement("div");
839
+ strip.className = "reuse-lightbox-thumbnails";
840
+ strip.setAttribute("role", "group");
841
+ strip.setAttribute("aria-label", "Choose image");
842
+ items.forEach((item, i) => {
843
+ const thumb = doc.createElement("button");
844
+ thumb.type = "button";
845
+ thumb.setAttribute("aria-label", `Show image ${i + 1}`);
846
+ const thumbnailSrc = item.thumbnailSrc || item.previewSrc;
847
+ if (thumbnailSrc) {
848
+ const image = doc.createElement("img");
849
+ image.src = thumbnailSrc;
850
+ image.alt = "";
851
+ image.loading = "lazy";
852
+ thumb.append(image);
853
+ }
854
+ else
855
+ thumb.textContent = String(i + 1);
856
+ thumb.addEventListener("click", () => goTo(i), {
857
+ signal: abort.signal,
858
+ });
859
+ strip.append(thumb);
860
+ 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);
866
+ const restoreScroll = lockScroll(doc);
867
+ try {
868
+ dialog.showModal();
869
+ }
870
+ catch (error) {
871
+ restoreScroll();
872
+ dialog.remove();
873
+ throw error;
874
+ }
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
+ const s = {
883
+ dialog,
884
+ viewport,
885
+ backdrop,
886
+ slides,
887
+ loaded: new Map(),
888
+ carousel,
889
+ abort,
890
+ animations: new Set(),
891
+ finishAnimations: new Set(),
892
+ previousFocus,
893
+ restoreScroll,
894
+ counter,
895
+ caption,
896
+ prev,
897
+ next,
898
+ zoomButton,
899
+ thumbs,
900
+ pointers: new Map(),
901
+ suppressClickUntil: 0,
902
+ };
903
+ session = s;
904
+ publish({
905
+ isOpen: true,
906
+ isClosing: false,
907
+ index: clamp(Math.floor(index), 0, items.length - 1),
908
+ count: items.length,
909
+ zoom: { ...identity },
910
+ });
911
+ update(s);
912
+ carousel.goTo(state.index, "instant");
913
+ dialog.addEventListener("cancel", (event) => {
914
+ event.preventDefault();
915
+ void close();
916
+ }, { signal: abort.signal });
917
+ dialog.addEventListener("close", () => {
918
+ if (session === s) {
919
+ teardown(s);
920
+ publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
921
+ }
922
+ }, { signal: abort.signal });
923
+ dialog.addEventListener("keydown", (event) => {
924
+ if (event.defaultPrevented ||
925
+ (event.target instanceof Element &&
926
+ event.target.closest("input,textarea,select,[contenteditable=true],[data-lightbox-interactive]")))
927
+ return;
928
+ if (event.key === "ArrowLeft") {
929
+ event.preventDefault();
930
+ goTo(state.index - 1);
931
+ }
932
+ if (event.key === "ArrowRight") {
933
+ event.preventDefault();
934
+ goTo(state.index + 1);
935
+ }
936
+ if (event.key === "+" || event.key === "=") {
937
+ event.preventDefault();
938
+ zoomTo(state.zoom.scale * 1.5);
939
+ }
940
+ if (event.key === "-") {
941
+ event.preventDefault();
942
+ zoomTo(state.zoom.scale / 1.5);
943
+ }
944
+ if (event.key === "0") {
945
+ event.preventDefault();
946
+ zoomTo(1);
947
+ }
948
+ }, { signal: abort.signal });
949
+ doc.defaultView?.addEventListener("resize", () => {
950
+ cancelAnimations(s);
951
+ layout(s);
952
+ }, { signal: abort.signal });
953
+ viewport.addEventListener("scrollend", () => trimSlides(s), {
954
+ signal: abort.signal,
955
+ });
956
+ 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
+ ]);
962
+ }
963
+ function close() {
964
+ const s = session;
965
+ if (!s)
966
+ return Promise.resolve();
967
+ if (closePromise)
968
+ return closePromise;
969
+ cancelAnimations(s);
970
+ 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
+ ]);
976
+ if (session !== s)
977
+ return;
978
+ teardown(s);
979
+ closePromise = undefined;
980
+ publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
981
+ })();
982
+ return closePromise;
983
+ }
984
+ return {
985
+ open,
986
+ close,
987
+ next: () => goTo(state.index + 1),
988
+ prev: () => goTo(state.index - 1),
989
+ goTo,
990
+ zoomTo,
991
+ toggleZoom,
992
+ getState: () => state,
993
+ subscribe: (listener) => {
994
+ listeners.add(listener);
995
+ return () => {
996
+ listeners.delete(listener);
997
+ };
998
+ },
999
+ destroy: () => {
1000
+ if (destroyed)
1001
+ return;
1002
+ destroyed = true;
1003
+ if (session)
1004
+ teardown(session);
1005
+ closePromise = undefined;
1006
+ publish({ isOpen: false, isClosing: false, zoom: { ...identity } });
1007
+ listeners.clear();
1008
+ },
1009
+ };
1010
+ }
1011
+ export function lightboxItemFromImage(image, source = image.dataset.lightboxSrc || image.currentSrc || image.src) {
1012
+ 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,
1019
+ };
1020
+ }
1021
+ export function bindLightboxGallery(root, options = {}) {
1022
+ const controller = createLightbox(options);
1023
+ const click = (event) => {
1024
+ if (event.defaultPrevented ||
1025
+ event.button !== 0 ||
1026
+ event.metaKey ||
1027
+ event.ctrlKey ||
1028
+ event.shiftKey ||
1029
+ event.altKey)
1030
+ return;
1031
+ const target = event.target;
1032
+ if (!(target instanceof Element))
1033
+ 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)
1039
+ return;
1040
+ event.preventDefault();
1041
+ controller.open(images.map((image) => (options.getItem || lightboxItemFromImage)(image)), index);
1042
+ };
1043
+ root.addEventListener("click", click);
1044
+ return {
1045
+ ...controller,
1046
+ destroy: () => {
1047
+ root.removeEventListener("click", click);
1048
+ controller.destroy();
1049
+ },
1050
+ };
1051
+ }