-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlite-light.js
More file actions
588 lines (501 loc) · 18.8 KB
/
Copy pathlite-light.js
File metadata and controls
588 lines (501 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// LiteLight - A lightweight, elegant lightbox utility
// npm: litelight-js | Demo: https://litelightbox.com
// AI agents: see AGENTS.md and llms-full.txt in this package
// Author: Byron Johnson
// License: MIT
// Initialization guard to prevent duplicate listeners
let initialized = false;
// Preloaded images cache (capped LRU)
const PRELOAD_CACHE_MAX = 20;
const preloadedImages = new Map();
// Touch and zoom state variables
let touchState = {
startX: 0,
startY: 0,
initialDistance: 0,
isZooming: false,
lastCenterX: 0,
lastCenterY: 0
};
let zoomState = {
scale: 1,
x: 0,
y: 0,
initialScale: 1,
initialX: 0,
initialY: 0
};
// Constants for performance
const ZOOM_TOLERANCE = 0.01;
const MIN_ZOOM = 1;
const MAX_ZOOM = 5;
// rAF batching flag for zoom transforms
let rafPending = false;
const mobileMediaQuery = typeof window !== 'undefined'
? window.matchMedia('(max-width: 768px)')
: { matches: false };
// Utility functions
function preloadImage(url) {
if (preloadedImages.has(url)) {
const img = preloadedImages.get(url);
preloadedImages.delete(url);
preloadedImages.set(url, img);
return img;
}
if (preloadedImages.size >= PRELOAD_CACHE_MAX) {
const oldestKey = preloadedImages.keys().next().value;
preloadedImages.delete(oldestKey);
}
const img = new Image();
img.src = url;
preloadedImages.set(url, img);
return img;
}
function scheduleIdlePreload(fn) {
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(fn, { timeout: 2000 });
} else {
setTimeout(fn, 0);
}
}
// Store scroll position globally
let storedScrollPosition = 0;
function disableBodyScroll() {
storedScrollPosition = window.scrollY;
document.body.style.position = 'fixed';
document.body.style.top = `-${storedScrollPosition}px`;
document.body.style.width = '100%';
document.body.style.overflowY = 'scroll';
}
function enableBodyScroll() {
document.body.style.position = '';
document.body.style.top = '';
document.body.style.width = '';
document.body.style.overflowY = '';
window.scrollTo({
top: storedScrollPosition,
left: 0,
behavior: 'instant'
});
}
function getTouchDistance(touches) {
if (touches.length < 2) return 0;
const touch1 = touches[0];
const touch2 = touches[1];
return Math.sqrt(
Math.pow(touch2.screenX - touch1.screenX, 2) +
Math.pow(touch2.screenY - touch1.screenY, 2)
);
}
function getTouchCenter(touches) {
if (touches.length < 2) return { x: touches[0].screenX, y: touches[0].screenY };
const touch1 = touches[0];
const touch2 = touches[1];
return {
x: (touch1.screenX + touch2.screenX) / 2,
y: (touch1.screenY + touch2.screenY) / 2
};
}
function applyZoomTransform(imageElement) {
// translate3d keeps the same scale-then-translate math while promoting a GPU layer (helps iOS)
imageElement.style.transform =
`scale(${zoomState.scale}) translate3d(${zoomState.x}px, ${zoomState.y}px, 0)`;
}
function scheduleZoomUpdate(imageElement) {
if (!rafPending) {
rafPending = true;
requestAnimationFrame(() => {
applyZoomTransform(imageElement);
rafPending = false;
});
}
}
function resetZoom(imageElement, smooth = false) {
const wasZoomed = !isApproximatelyOne(zoomState.scale) || zoomState.x !== 0 || zoomState.y !== 0;
zoomState.scale = 1;
zoomState.x = 0;
zoomState.y = 0;
if (smooth && wasZoomed) {
applyZoomTransform(imageElement);
} else {
imageElement.classList.add('lite-light-no-transform-transition');
applyZoomTransform(imageElement);
requestAnimationFrame(() => {
imageElement.classList.remove('lite-light-no-transform-transition');
});
}
}
function waitTransition(element, propertyName, durationMs, callback) {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
element.removeEventListener('transitionend', onTransitionEnd);
callback();
};
const onTransitionEnd = (e) => {
if (e.target !== element || e.propertyName !== propertyName) return;
finish();
};
element.addEventListener('transitionend', onTransitionEnd);
setTimeout(finish, durationMs + 50);
}
function setImageZoomingActive(imageElement, active) {
imageElement.classList.toggle('lite-light-zooming', active);
const overlay = imageElement.parentElement;
if (overlay) overlay.classList.toggle('lite-light-gesture', active);
}
function whenImageReady(img, callback) {
const done = () => callback();
const fail = () => done();
if (img.complete && img.naturalWidth) {
if (img.decode) img.decode().then(done).catch(fail);
else done();
} else {
img.onload = () => {
if (img.decode) img.decode().then(done).catch(fail);
else done();
};
img.onerror = fail;
}
}
function isApproximatelyOne(value) {
return Math.abs(value - 1) < ZOOM_TOLERANCE;
}
// Initialize lightbox functionality
export function initLiteLight(options = {}) {
if (initialized) return;
initialized = true;
const config = {
imageSelector: options.imageSelector || 'img[data-lightbox]',
imageUrlAttribute: options.imageUrlAttribute || 'data-lightbox',
lightboxClass: options.lightboxClass || 'lite-light',
swipeThreshold: options.swipeThreshold || 50,
fadeAnimationDuration: options.fadeAnimationDuration || 150,
...options
};
if (!document.querySelector(`.${config.lightboxClass}`)) {
createLightboxHTML(config.lightboxClass);
}
const lightbox = document.querySelector(`.${config.lightboxClass}`);
const lightboxImage = lightbox.querySelector('img');
const prevButton = lightbox.querySelector('.lite-light-prev');
const nextButton = lightbox.querySelector('.lite-light-next');
const closeButton = lightbox.querySelector('.lite-light-close');
document.addEventListener('click', (e) => {
// Trigger element may be an <img> (default) or any element matched by a
// custom imageSelector (e.g. 'a[data-lightbox]' for text-link triggers)
// — walk up from the click target instead of hardcoding tagName === IMG.
const trigger = e.target.closest(config.imageSelector);
if (!trigger || !trigger.hasAttribute(config.imageUrlAttribute)) return;
// Allow modified clicks (new tab / new window) to keep native <a> behavior
if (
trigger.tagName === 'A' &&
!e.metaKey &&
!e.ctrlKey &&
!e.shiftKey &&
!e.altKey
) {
e.preventDefault();
}
const images = Array.from(document.querySelectorAll(config.imageSelector));
let currentIndex = images.findIndex(img => img === trigger);
let isNavigating = false;
function preloadAdjacentImages(currentIdx) {
const prevIdx = (currentIdx - 1 + images.length) % images.length;
const nextIdx = (currentIdx + 1) % images.length;
preloadImage(images[prevIdx].getAttribute(config.imageUrlAttribute));
preloadImage(images[nextIdx].getAttribute(config.imageUrlAttribute));
}
function setLoading(active) {
lightbox.classList.toggle('lite-light-loading', active);
}
function clearEntranceClasses() {
lightboxImage.classList.remove('lite-light-entering', 'lite-light-entered');
}
function fadeImage(toOpacity, durationMs, callback) {
lightboxImage.style.opacity = String(toOpacity);
waitTransition(lightboxImage, 'opacity', durationMs, callback);
}
function navigateToImage(index) {
if (isNavigating) return;
isNavigating = true;
currentIndex = (index + images.length) % images.length;
const nextImageUrl = images[currentIndex].getAttribute(config.imageUrlAttribute);
const preloaded = preloadImage(nextImageUrl);
const fadeMs = config.fadeAnimationDuration;
const finishNavigation = () => {
scheduleIdlePreload(() => preloadAdjacentImages(currentIndex));
isNavigating = false;
};
const fadeIn = () => {
lightboxImage.style.opacity = '0';
void lightboxImage.offsetWidth;
fadeImage(1, fadeMs, finishNavigation);
};
const swapImage = () => {
const needsLoad = !(preloaded.complete && preloaded.naturalWidth);
if (needsLoad) setLoading(true);
whenImageReady(preloaded, () => {
lightboxImage.src = nextImageUrl;
lightboxImage.alt = images[currentIndex].alt || '';
resetZoom(lightboxImage);
if (needsLoad) setLoading(false);
fadeIn();
});
};
const fadeOut = () => fadeImage(0, fadeMs, swapImage);
if (!isApproximatelyOne(zoomState.scale)) {
resetZoom(lightboxImage, true);
lightboxImage.addEventListener('transitionend', function onZoomEnd(e) {
if (e.propertyName !== 'transform') return;
lightboxImage.removeEventListener('transitionend', onZoomEnd);
fadeOut();
});
} else {
fadeOut();
}
}
function performAction(action) {
switch (action) {
case 'close':
closeLightbox();
break;
case 'prev':
navigateToImage(currentIndex - 1);
break;
case 'next':
navigateToImage(currentIndex + 1);
break;
}
}
function handleTouchStart(e) {
const touches = e.touches;
if (touches.length === 1) {
const touch = touches[0];
touchState.startX = touch.screenX;
touchState.startY = touch.screenY;
touchState.lastCenterX = touch.screenX;
touchState.lastCenterY = touch.screenY;
touchState.isZooming = false;
zoomState.initialScale = zoomState.scale;
zoomState.initialX = zoomState.x;
zoomState.initialY = zoomState.y;
} else if (touches.length === 2) {
touchState.initialDistance = getTouchDistance(touches);
const center = getTouchCenter(touches);
touchState.lastCenterX = center.x;
touchState.lastCenterY = center.y;
zoomState.initialScale = zoomState.scale;
zoomState.initialX = zoomState.x;
zoomState.initialY = zoomState.y;
touchState.isZooming = true;
setImageZoomingActive(lightboxImage, true);
}
}
function handleTouchMove(e) {
const touches = e.touches;
// Non-passive listener: block browser page zoom/pan while we handle image gestures
if (touches.length >= 2 || zoomState.scale > MIN_ZOOM) {
e.preventDefault();
}
if (touches.length === 2) {
const currentDistance = getTouchDistance(touches);
const center = getTouchCenter(touches);
if (touchState.initialDistance > 0) {
const scaleChange = currentDistance / touchState.initialDistance;
zoomState.scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoomState.initialScale * scaleChange));
if (isApproximatelyOne(zoomState.scale)) {
zoomState.x = 0;
zoomState.y = 0;
} else {
const deltaX = center.x - touchState.lastCenterX;
const deltaY = center.y - touchState.lastCenterY;
if (zoomState.scale > MIN_ZOOM) {
zoomState.x = zoomState.initialX + deltaX / zoomState.scale;
zoomState.y = zoomState.initialY + deltaY / zoomState.scale;
}
}
scheduleZoomUpdate(lightboxImage);
setImageZoomingActive(lightboxImage, true);
}
touchState.lastCenterX = center.x;
touchState.lastCenterY = center.y;
touchState.isZooming = true;
} else if (touches.length === 1 && zoomState.scale > MIN_ZOOM) {
const touch = touches[0];
const deltaX = touch.screenX - touchState.lastCenterX;
const deltaY = touch.screenY - touchState.lastCenterY;
zoomState.x += deltaX / zoomState.scale;
zoomState.y += deltaY / zoomState.scale;
scheduleZoomUpdate(lightboxImage);
setImageZoomingActive(lightboxImage, true);
touchState.lastCenterX = touch.screenX;
touchState.lastCenterY = touch.screenY;
touchState.isZooming = true;
}
}
function handleTouchEnd(e) {
if (e.changedTouches.length === 1 && !touchState.isZooming && e.touches.length === 0 && isApproximatelyOne(zoomState.scale)) {
const touch = e.changedTouches[0];
const swipeDistanceX = touch.screenX - touchState.startX;
const swipeDistanceY = touch.screenY - touchState.startY;
if (Math.abs(swipeDistanceX) > Math.abs(swipeDistanceY) &&
Math.abs(swipeDistanceX) > config.swipeThreshold) {
navigateToImage(swipeDistanceX > 0 ? currentIndex - 1 : currentIndex + 1);
e.stopPropagation();
}
}
if (e.touches.length === 0) {
if (isApproximatelyOne(zoomState.scale) && zoomState.scale !== 1) {
resetZoom(lightboxImage, true);
}
touchState.isZooming = false;
touchState.initialDistance = 0;
setImageZoomingActive(lightboxImage, false);
}
}
function handleKeyboardNav(e) {
switch (e.key) {
case 'ArrowLeft':
performAction('prev');
e.preventDefault();
break;
case 'ArrowRight':
performAction('next');
e.preventDefault();
break;
case 'Escape':
performAction('close');
e.preventDefault();
break;
case 'Enter':
case ' ':
if (document.activeElement === closeButton) {
performAction('close');
e.preventDefault();
} else if (document.activeElement === prevButton && !mobileMediaQuery.matches) {
performAction('prev');
e.preventDefault();
} else if (document.activeElement === nextButton && !mobileMediaQuery.matches) {
performAction('next');
e.preventDefault();
}
break;
}
}
function handleFocusTrap(e) {
if (e.key !== 'Tab') return;
const focusableElements = mobileMediaQuery.matches
? [closeButton]
: [closeButton, prevButton, nextButton];
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
if (e.shiftKey) {
if (document.activeElement === firstElement || !lightbox.contains(document.activeElement)) {
e.preventDefault();
lastElement.focus();
}
} else {
if (document.activeElement === lastElement || !lightbox.contains(document.activeElement)) {
e.preventDefault();
firstElement.focus();
}
}
}
function handleControlClick(e) {
e.stopPropagation();
const target = e.currentTarget;
if (target === closeButton) performAction('close');
else if (target === prevButton) performAction('prev');
else if (target === nextButton) performAction('next');
}
function handleBackgroundClick(e) {
e.stopPropagation();
performAction('close');
}
// Safari legacy gesture events — block page pinch-zoom while the overlay handles it
function preventSafariPageZoom(e) {
e.preventDefault();
}
function closeLightbox() {
lightbox.classList.remove('lite-light-active', 'lite-light-loading');
resetZoom(lightboxImage, true);
setImageZoomingActive(lightboxImage, false);
clearEntranceClasses();
lightboxImage.style.opacity = '';
lightboxImage.style.transform = '';
enableBodyScroll();
document.removeEventListener('keydown', handleKeyboardNav);
document.removeEventListener('keydown', handleFocusTrap);
lightbox.removeEventListener('touchstart', handleTouchStart);
lightbox.removeEventListener('touchmove', handleTouchMove);
lightbox.removeEventListener('touchend', handleTouchEnd);
lightbox.removeEventListener('gesturestart', preventSafariPageZoom);
lightbox.removeEventListener('gesturechange', preventSafariPageZoom);
prevButton.removeEventListener('click', handleControlClick);
nextButton.removeEventListener('click', handleControlClick);
closeButton.removeEventListener('click', handleControlClick);
lightbox.removeEventListener('click', handleBackgroundClick);
}
const currentUrl = images[currentIndex].getAttribute(config.imageUrlAttribute);
const fadeMs = config.fadeAnimationDuration;
const preloadedCurrent = preloadImage(currentUrl);
lightbox.style.setProperty('--ll-duration', `${fadeMs}ms`);
lightbox.classList.add('lite-light-active');
disableBodyScroll();
closeButton.focus();
scheduleIdlePreload(() => preloadAdjacentImages(currentIndex));
const needsLoad = !(preloadedCurrent.complete && preloadedCurrent.naturalWidth);
if (needsLoad) setLoading(true);
whenImageReady(preloadedCurrent, () => {
lightboxImage.src = currentUrl;
lightboxImage.alt = images[currentIndex].alt || '';
lightboxImage.style.transform = '';
clearEntranceClasses();
lightboxImage.classList.add('lite-light-entering');
lightboxImage.style.opacity = '0';
void lightboxImage.offsetWidth;
lightboxImage.style.opacity = '1';
lightboxImage.classList.add('lite-light-entered');
if (needsLoad) setLoading(false);
waitTransition(lightboxImage, 'opacity', fadeMs, () => {
clearEntranceClasses();
resetZoom(lightboxImage);
});
});
lightbox.addEventListener('touchstart', handleTouchStart, { passive: true });
// touchmove must be non-passive so preventDefault can block browser page zoom
lightbox.addEventListener('touchmove', handleTouchMove, { passive: false });
lightbox.addEventListener('touchend', handleTouchEnd, { passive: true });
lightbox.addEventListener('gesturestart', preventSafariPageZoom, { passive: false });
lightbox.addEventListener('gesturechange', preventSafariPageZoom, { passive: false });
document.addEventListener('keydown', handleKeyboardNav);
document.addEventListener('keydown', handleFocusTrap);
prevButton.addEventListener('click', handleControlClick);
nextButton.addEventListener('click', handleControlClick);
closeButton.addEventListener('click', handleControlClick);
lightbox.addEventListener('click', handleBackgroundClick);
});
}
function createLightboxHTML(lightboxClass) {
const lightboxHTML = `
<div class="${lightboxClass}" role="dialog" aria-modal="true" aria-label="Image lightbox">
<div class="lite-light-prev lite-light-button" role="button" aria-label="Previous image" tabindex="0">
<span class="lite-light-arrow lite-light-left"></span>
</div>
<img alt="" />
<div class="lite-light-next lite-light-button" role="button" aria-label="Next image" tabindex="0">
<span class="lite-light-arrow lite-light-right"></span>
</div>
<div class="lite-light-close lite-light-button" role="button" aria-label="Close lightbox" tabindex="0">
<span class="lite-light-bar"></span>
<span class="lite-light-bar"></span>
</div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', lightboxHTML);
}
export function init(options) {
initLiteLight(options);
}