Files
NODEDC_SITE/assets/custom/js/carousel.js
T

197 lines
11 KiB
JavaScript

/* Shared finite carousel: fitting groups and every overflow item center exactly. */
(() => {
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
const finePointer = matchMedia('(hover: hover) and (pointer: fine)');
// WheelEvent has no device type. Keep macOS pixel gestures entirely native.
const applePointer = /Mac|iPhone|iPad|iPod/i.test(navigator.userAgentData?.platform || navigator.platform || '');
function bind(root) {
if (root.dataset.carouselReady) return;
root.dataset.carouselReady = 'true';
const track = root.querySelector('[data-carousel-track]');
const items = [...track.children];
const prev = root.querySelector('[data-carousel-prev]');
const next = root.querySelector('[data-carousel-next]');
const count = root.querySelector('[data-carousel-count]');
let active = 0, fits = false, settle, dragging = null, layoutWidth = 0;
let wheelFrame = 0, wheelSnap = '';
let pageFrame = 0, alignmentQuietUntil = 0, alignmentDirection = 0;
const center = item => item.offsetLeft + item.offsetWidth / 2 - track.clientWidth / 2;
function cancelPageInput(event) {
if (event.type !== 'wheel' || !track.contains(event.target)) stopPageMotion();
}
function stopPageMotion() {
if (pageFrame) cancelAnimationFrame(pageFrame);
pageFrame = 0;
window.removeEventListener('wheel', cancelPageInput, true);
window.removeEventListener('pointerdown', cancelPageInput, true);
window.removeEventListener('keydown', cancelPageInput, true);
}
function alignPage(offset, direction) {
const from = window.scrollY, start = performance.now();
const max = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);
const destination = Math.max(0, Math.min(max, from + offset));
if (Math.abs(destination - from) < 1) return false;
stopWheelMotion();
alignmentDirection = direction;
window.addEventListener('wheel', cancelPageInput, {capture:true, passive:true});
window.addEventListener('pointerdown', cancelPageInput, {capture:true, passive:true});
window.addEventListener('keydown', cancelPageInput, {capture:true, passive:true});
const frame = now => {
const progress = Math.min(1, Math.max(0, (now - start) / 300));
window.scrollTo({top:from + (destination - from) * (1 - Math.pow(1 - progress, 3)), behavior:'instant'});
if (progress < 1) pageFrame = requestAnimationFrame(frame);
else { stopPageMotion(); alignmentQuietUntil = now + 180; }
};
pageFrame = requestAnimationFrame(frame);
return true;
}
function stopWheelMotion() {
if (!wheelFrame) return;
cancelAnimationFrame(wheelFrame);
wheelFrame = 0;
track.style.scrollSnapType = wheelSnap;
}
function moveWithWheel(left) {
const from = track.scrollLeft, start = performance.now();
wheelSnap = track.style.scrollSnapType;
track.style.scrollSnapType = 'none';
const frame = now => {
const progress = Math.min(1, Math.max(0, (now - start) / 300));
const eased = 1 - Math.pow(1 - progress, 3);
track.scrollTo({left: from + (left - from) * eased, behavior:'instant'});
if (progress < 1) wheelFrame = requestAnimationFrame(frame);
else { wheelFrame = 0; track.style.scrollSnapType = wheelSnap; }
};
wheelFrame = requestAnimationFrame(frame);
}
function state() {
prev.disabled = fits || active === 0;
next.disabled = fits || active === items.length - 1;
count.textContent = fits ? `${items.length} / ${items.length}` : `${active + 1} / ${items.length}`;
root.querySelector('[data-carousel-controls]').hidden = items.length < 2;
items.forEach((item, i) => {
item.classList.toggle('current', i === active);
if (i !== active && !fits) item.querySelectorAll('video').forEach(v => v.pause());
});
}
function go(index, smooth = true, wheelMotion = false) {
stopPageMotion();
stopWheelMotion();
active = Math.max(0, Math.min(items.length - 1, index));
const left = fits ? 0 : center(items[active]);
if (wheelMotion && smooth && !fits) moveWithWheel(left);
else track.scrollTo({left, behavior: smooth && !reduced.matches ? 'smooth' : 'instant'});
state();
}
function layout() {
const available = root.clientWidth;
// Media already has a fixed aspect ratio. A load or height-only resize must
// never interrupt native touch momentum or an in-flight smooth scroll.
if (!available || available === layoutWidth) return;
layoutWidth = available;
const gap = parseFloat(getComputedStyle(track).columnGap) || 0;
const width = items.reduce((sum, item) => sum + item.offsetWidth, 0) + gap * Math.max(0, items.length - 1);
fits = width <= available - 32;
track.dataset.fits = String(fits);
go(active, false);
}
if (!items.length) { root.hidden = true; return; }
prev.addEventListener('click', () => go(active - 1));
next.addEventListener('click', () => go(active + 1));
root.addEventListener('keydown', event => {
if (event.target.matches('input,textarea,select,video')) return;
const target = {ArrowLeft:active-1, ArrowRight:active+1, Home:0, End:items.length-1}[event.key];
if (target !== undefined) { event.preventDefault(); go(target); }
});
track.addEventListener('scroll', () => {
clearTimeout(settle);
settle = setTimeout(() => {
if (fits || dragging || wheelFrame) return;
active = items.reduce((best, item, i) => Math.abs(center(item)-track.scrollLeft) < Math.abs(center(items[best])-track.scrollLeft) ? i : best, 0);
state();
}, 100);
}, {passive:true});
// Touch uses native horizontal scrolling; vertical gestures continue down the page.
track.addEventListener('pointerdown', event => {
stopPageMotion();
stopWheelMotion();
if (event.pointerType !== 'mouse' || fits || event.target.closest('video,button')) return;
dragging = {x:event.clientX, left:track.scrollLeft, moved:false};
});
window.addEventListener('pointermove', event => {
if (!dragging) return;
const dx = event.clientX-dragging.x;
if (Math.abs(dx)>5) {dragging.moved=true;track.classList.add('is-dragging');track.scrollLeft=dragging.left-dx;}
});
window.addEventListener('pointerup', () => {
if (!dragging) return;
const moved=dragging.moved;dragging=null;track.classList.remove('is-dragging');
if (moved) {active=items.reduce((best,item,i)=>Math.abs(center(item)-track.scrollLeft)<Math.abs(center(items[best])-track.scrollLeft)?i:best,0);go(active);track.dataset.dragged='true';setTimeout(()=>delete track.dataset.dragged,0);}
});
track.addEventListener('click', event => {if(track.dataset.dragged){event.preventDefault();event.stopPropagation();}},true);
track.addEventListener('dragstart', event => event.preventDefault());
// Prevent legacy page smooth-scroll from converting horizontal trackpad input.
track.addEventListener('wheel', event => { if(Math.abs(event.deltaX)>Math.abs(event.deltaY)) event.stopPropagation(); },{passive:true});
if (!applePointer) {
let lastStep = -Infinity, lastDirection = 0, continuousUntil = 0, lastPageWheel = -Infinity;
track.addEventListener('wheel', event => {
if (!finePointer.matches || fits || dragging || event.defaultPrevented || !event.cancelable ||
event.ctrlKey || event.metaKey || event.altKey || event.shiftKey ||
event.target.closest('input,textarea,select,[contenteditable="true"],[role="slider"]')) return;
const mode = event.deltaMode, dy = event.deltaY, now = performance.now();
if (!dy || !Number.isFinite(dy)) return;
// Coarse vertical steps include fractional deltas from browser scaling.
// Fine/diagonal samples mark a continuous gesture, including its tail.
const discrete = !event.deltaX && (mode === 1 || mode === 2 ||
(mode === 0 && Math.abs(dy) >= 40));
if (!discrete) { stopPageMotion(); stopWheelMotion(); continuousUntil = now + 250; return; }
if (now < continuousUntil) return;
const direction = Math.sign(dy);
// The arrival gesture aligns the page only; it must not spend its tail
// on horizontal slides. Reversing cancels alignment and releases the page.
if (pageFrame || now < alignmentQuietUntil) {
if (direction !== alignmentDirection) {
stopPageMotion(); alignmentQuietUntil = 0; lastPageWheel = now; return;
}
event.preventDefault(); event.stopPropagation();
alignmentQuietUntil = now + 180;
return;
}
const target = active + direction;
if (target < 0 || target >= items.length) return;
// Hover is not enough: first let the reader bring the media into view.
const media = items[active].querySelector('.carousel-media') || items[active];
const rect = media.getBoundingClientRect();
const top = 64, bottom = window.innerHeight - 32;
const visible = Math.max(0, Math.min(rect.bottom, bottom) - Math.max(rect.top, top));
const offset = (rect.top + rect.bottom - top - bottom) / 2;
const distance = Math.abs(offset);
const near = distance <= Math.min(240, (bottom - top) * 0.3) &&
visible >= Math.min(rect.height, bottom - top) * 0.65;
if (near && distance > 8 && (offset * direction > 0 || distance <= 80) && alignPage(offset, direction)) {
event.preventDefault(); event.stopPropagation(); return;
}
const centered = distance <= 80;
if (!centered || visible < Math.min(rect.height, bottom - top) * 0.95 || now - lastPageWheel < 180) {
lastPageWheel = now;
return;
}
// Consume a short burst while moving, but allow reversal immediately.
if (now - lastStep < 220 && direction === lastDirection) {
event.preventDefault(); event.stopPropagation(); return;
}
event.preventDefault(); event.stopPropagation();
lastStep = now; lastDirection = direction;
// User-requested wheel navigation remains smooth even with reduced
// decorative motion. Native gestures and other controls retain their policy.
go(target, true, true);
}, {passive:false});
}
new ResizeObserver(layout).observe(root);
const observer=new IntersectionObserver(entries=>entries.forEach(entry=>{if(!entry.isIntersecting)root.querySelectorAll('video').forEach(v=>v.pause());}));observer.observe(root);
layout();
}
function init(){document.querySelectorAll('[data-carousel]').forEach(bind);}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
})();