Avoid early carousel wheel capture and smooth explicit wheel navigation
This commit is contained in:
@@ -13,7 +13,27 @@
|
||||
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 = '';
|
||||
const center = item => item.offsetLeft + item.offsetWidth / 2 - track.clientWidth / 2;
|
||||
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;
|
||||
@@ -24,9 +44,12 @@
|
||||
if (i !== active && !fits) item.querySelectorAll('video').forEach(v => v.pause());
|
||||
});
|
||||
}
|
||||
function go(index, smooth = true) {
|
||||
function go(index, smooth = true, wheelMotion = false) {
|
||||
stopWheelMotion();
|
||||
active = Math.max(0, Math.min(items.length - 1, index));
|
||||
track.scrollTo({left: fits ? 0 : center(items[active]), behavior: smooth && !reduced.matches ? 'smooth' : 'instant'});
|
||||
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() {
|
||||
@@ -52,13 +75,14 @@
|
||||
track.addEventListener('scroll', () => {
|
||||
clearTimeout(settle);
|
||||
settle = setTimeout(() => {
|
||||
if (fits || dragging) return;
|
||||
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 => {
|
||||
stopWheelMotion();
|
||||
if (event.pointerType !== 'mouse' || fits || event.target.closest('video,button')) return;
|
||||
dragging = {x:event.clientX, left:track.scrollLeft, moved:false};
|
||||
});
|
||||
@@ -77,7 +101,7 @@
|
||||
// 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;
|
||||
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 ||
|
||||
@@ -88,8 +112,18 @@
|
||||
// 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) { continuousUntil = now + 250; return; }
|
||||
if (!discrete) { stopWheelMotion(); continuousUntil = now + 250; return; }
|
||||
if (now < continuousUntil) 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 centered = Math.abs((rect.top + rect.bottom - top - bottom) / 2) <= 80;
|
||||
if (!centered || visible < Math.min(rect.height, bottom - top) * 0.95 || now - lastPageWheel < 180) {
|
||||
lastPageWheel = now;
|
||||
return;
|
||||
}
|
||||
const direction = Math.sign(dy);
|
||||
// Consume a short burst while moving, but allow reversal immediately.
|
||||
if (now - lastStep < 220 && direction === lastDirection) {
|
||||
@@ -99,7 +133,9 @@
|
||||
if (target < 0 || target >= items.length) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
lastStep = now; lastDirection = direction;
|
||||
go(target);
|
||||
// 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);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Плавное колесо только после подхода к галерее
|
||||
|
||||
Уточнение к первоначальному исправлению колеса (f24c881) в ветке fix/carousel-mouse-wheel. Пользователь обнаружил ранний перехват: курсор уже над изображением, но страница ещё не опущена до галереи. Также reduced motion делал переход мгновенным.
|
||||
|
||||
## Новое условие входа
|
||||
|
||||
Колесо переключает слайды только когда центр активного изображения находится в пределах 80 px от центра доступного окна и видно минимум 95% высоты изображения (либо 95% доступного окна для слишком высокого изображения). Верхние 64 px и нижние 32 px зарезервированы под интерфейс страницы. До этого колесо остаётся прокруткой страницы. Текущая серия вертикальной прокрутки не перехватывается: после последнего пропущенного wheel должно пройти 180 мс.
|
||||
|
||||
Никакого автоматического вертикального перемещения или привязки страницы к секции не добавлено. Горизонтальный слайд доводится до центра, как и прежде. Выход за первый/последний слайд сохраняет прокрутку страницы.
|
||||
|
||||
## Плавность
|
||||
|
||||
В текущем Chrome Windows даже явный scrollTo с behavior smooth при системном уменьшении движения дал единственное событие scroll сразу в конечной позиции. Поэтому только сценарий колеса получил собственный переход requestAnimationFrame длительностью 300 мс с кубическим замедлением. На время перехода CSS snap отключается и затем возвращается. Цикл существует только во время перехода; в простое кадров и таймеров анимации нет.
|
||||
|
||||
Переход отменяется новым go(), изменением ширины, нажатием указателя (включая touch) и сменой колеса на непрерывный жест. Обработчик settle не заменяет целевой индекс промежуточным во время анимации. Mac по-прежнему исключён из нового wheel-сценария; нативные свайпы и прежняя reduced-motion-политика стрелок/клавиатуры сохранены. Исправление видимости заголовков не меняется.
|
||||
|
||||
## Проверки и поставка
|
||||
|
||||
15 тестов проходят, включая частично показанную/уходящую галерею, непрерывную вертикальную прокрутку, промежуточные положения анимации, завершение без активного кадра, восстановление snap и отмену касанием. Прежние проверки тачпада, свайпов, поздних загрузок и заголовков сохранены.
|
||||
|
||||
В Chrome Windows на локальной копии текущего экспорта: первый шаг колеса оставляет 1/7 и опускает страницу; следующий после паузы переводит на 2/7. Зафиксированы промежуточные горизонтальные позиции 183, 365, 527, 667, 790, 895, 986, 1121, 1170, 1258, 1272, 1281, 1285, 1287, 1288 px — переход действительно плавный. Диагностика не входит в архив.
|
||||
|
||||
Архив содержит 217 записей, изменены только carousel.js, index.html и templates/pages/home/shell.html; остальные 214 сохранены побайтно. Версия carousel.js: 1c1b1398921b. Оригинал для отката: D:/_PROJ/NODEDC/Last_back/carousel-alignment-2026-11-12/before.zip.
|
||||
+1
-1
@@ -53,7 +53,7 @@
|
||||
background: #000 !important;
|
||||
background-image: none !important;
|
||||
}
|
||||
</style><style id="node-dc-localization">.ndc-badge{display:none!important}</style><link rel="stylesheet" href="./assets/custom/css/carousel.css?v=7f6630cae11a"><script defer src="./assets/custom/js/carousel.js?v=0bd0f1b6032c"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
|
||||
</style><style id="node-dc-localization">.ndc-badge{display:none!important}</style><link rel="stylesheet" href="./assets/custom/css/carousel.css?v=7f6630cae11a"><script defer src="./assets/custom/js/carousel.js?v=1c1b1398921b"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
|
||||
|
||||
<style>
|
||||
[debug] {
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
background: #000 !important;
|
||||
background-image: none !important;
|
||||
}
|
||||
</style><style id="node-dc-localization">.ndc-badge{display:none!important}</style><link rel="stylesheet" href="./assets/custom/css/carousel.css?v=7f6630cae11a"><script defer src="./assets/custom/js/carousel.js?v=0bd0f1b6032c"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
|
||||
</style><style id="node-dc-localization">.ndc-badge{display:none!important}</style><link rel="stylesheet" href="./assets/custom/css/carousel.css?v=7f6630cae11a"><script defer src="./assets/custom/js/carousel.js?v=1c1b1398921b"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
|
||||
|
||||
<style>
|
||||
[debug] {
|
||||
|
||||
+27
-6
@@ -5,18 +5,20 @@ import fs from 'node:fs';
|
||||
const source=fs.readFileSync(process.env.CAROUSEL_SOURCE || new URL('../assets/custom/js/carousel.js',import.meta.url),'utf8');
|
||||
function fixture({width=390,size=330,length=5,platform='Win32',fine=true,reduced=false}={}) {
|
||||
const timers=new Map();let timer=0, resize;
|
||||
const frames=new Map();let frameId=0;
|
||||
let now=1000;
|
||||
const mediaRect={top:100,bottom:900,height:800};
|
||||
const target=()=>({listeners:{},dataset:{},classList:{toggle(){},add(){},remove(){}},addEventListener(n,f){(this.listeners[n]??=[]).push(f);},emit(n,e={}){for(const f of this.listeners[n]||[])f(e);}});
|
||||
const images=Array.from({length},()=>({...target(),tagName:'IMG'}));
|
||||
const root={...target(),clientWidth:width};
|
||||
const items=images.map((image,i)=>({...target(),get offsetWidth(){return size;},get offsetLeft(){return (root.clientWidth-size)/2+i*(size+24);},querySelectorAll(){return [];}}));
|
||||
const items=images.map((image,i)=>({...target(),get offsetWidth(){return size;},get offsetLeft(){return (root.clientWidth-size)/2+i*(size+24);},querySelector(){return {getBoundingClientRect:()=>mediaRect};},querySelectorAll(){return [];}}));
|
||||
const calls=[];
|
||||
const track={...target(),children:items,scrollLeft:0,get clientWidth(){return root.clientWidth;},querySelectorAll(){return images;},scrollTo(o){calls.push(o);if(o.behavior!=='smooth')this.scrollLeft=o.left;}};
|
||||
const track={...target(),style:{scrollSnapType:''},children:items,scrollLeft:0,get clientWidth(){return root.clientWidth;},querySelectorAll(){return images;},scrollTo(o){calls.push(o);if(o.behavior!=='smooth')this.scrollLeft=o.left;}};
|
||||
const prev=target(),next=target(),count={},controls={};
|
||||
root.querySelector=s=>({'[data-carousel-track]':track,'[data-carousel-prev]':prev,'[data-carousel-next]':next,'[data-carousel-count]':count,'[data-carousel-controls]':controls}[s]);
|
||||
root.querySelectorAll=()=>[];
|
||||
vm.runInNewContext(source,{navigator:{platform},performance:{now:()=>now},matchMedia:q=>({matches:q.includes('reduced-motion')?reduced:fine}),getComputedStyle:()=>({columnGap:'24'}),document:{readyState:'complete',querySelectorAll:()=>[root]},window:target(),setTimeout:f=>{timers.set(++timer,f);return timer;},clearTimeout:id=>timers.delete(id),ResizeObserver:class{constructor(f){resize=f;}observe(){}},IntersectionObserver:class{observe(){}}});
|
||||
return {root,track,images,prev,next,count,calls,resize:()=>resize(),advance(ms=300){now+=ms;},wheel(props={}){const e={deltaX:0,deltaY:100,deltaMode:0,cancelable:true,defaultPrevented:false,stopped:false,target:{closest(){return null;}},preventDefault(){this.defaultPrevented=true;},stopPropagation(){this.stopped=true;},...props};track.emit('wheel',e);return e;},settle(){const pending=[...timers.values()];timers.clear();pending.forEach(f=>f());},swipe(left){track.scrollLeft=left;track.emit('scroll');}};
|
||||
vm.runInNewContext(source,{requestAnimationFrame:f=>{frames.set(++frameId,f);return frameId;},cancelAnimationFrame:id=>frames.delete(id),navigator:{platform},performance:{now:()=>now},matchMedia:q=>({matches:q.includes('reduced-motion')?reduced:fine}),getComputedStyle:()=>({columnGap:'24'}),document:{readyState:'complete',querySelectorAll:()=>[root]},window:{...target(),innerHeight:1000},setTimeout:f=>{timers.set(++timer,f);return timer;},clearTimeout:id=>timers.delete(id),ResizeObserver:class{constructor(f){resize=f;}observe(){}},IntersectionObserver:class{observe(){}}});
|
||||
return {root,track,images,prev,next,count,calls,mediaRect,frames,resize:()=>resize(),tick(ms){now+=ms;const pending=[...frames.values()];frames.clear();pending.forEach(f=>f(now));},advance(ms=300){now+=ms;},wheel(props={}){const e={deltaX:0,deltaY:100,deltaMode:0,cancelable:true,defaultPrevented:false,stopped:false,target:{closest(){return null;}},preventDefault(){this.defaultPrevented=true;},stopPropagation(){this.stopped=true;},...props};track.emit('wheel',e);return e;},settle(){const pending=[...timers.values()];timers.clear();pending.forEach(f=>f());},swipe(left){track.scrollLeft=left;track.emit('scroll');}};
|
||||
}
|
||||
|
||||
test('mouse wheel steps once per burst, reverses, and releases page at both ends',()=>{
|
||||
@@ -29,12 +31,31 @@ test('mouse wheel steps once per burst, reverses, and releases page at both ends
|
||||
f.wheel({deltaY:-120});assert.equal(f.count.textContent,'2 / 3');
|
||||
f.wheel({deltaY:120});assert.equal(f.count.textContent,'3 / 3');
|
||||
});
|
||||
test('line/page wheels work and reduced motion uses instant scrolling',()=>{
|
||||
test('explicit wheel navigation is smooth independently of decorative reduced motion',()=>{
|
||||
const f=fixture({reduced:true});
|
||||
f.wheel({deltaMode:1,deltaY:3});assert.equal(f.count.textContent,'2 / 5');assert.equal(f.calls.at(-1).behavior,'instant');
|
||||
f.wheel({deltaMode:1,deltaY:3});assert.equal(f.count.textContent,'2 / 5');
|
||||
f.tick(100);assert.ok(f.track.scrollLeft>0&&f.track.scrollLeft<354,'transition has intermediate frames');
|
||||
f.tick(200);assert.equal(f.track.scrollLeft,354);assert.equal(f.frames.size,0);assert.equal(f.track.style.scrollSnapType,'');
|
||||
f.advance();f.wheel({deltaMode:2,deltaY:1});assert.equal(f.count.textContent,'3 / 5');
|
||||
f.advance();f.wheel({deltaY:98.53334554036458});assert.equal(f.count.textContent,'4 / 5','scaled mouse deltas need not be integers');
|
||||
});
|
||||
test('pointer interaction cancels wheel motion and restores native snapping',()=>{
|
||||
const f=fixture();f.wheel();f.tick(80);const left=f.track.scrollLeft;
|
||||
f.track.emit('pointerdown',{pointerType:'touch'});f.tick(500);
|
||||
assert.equal(f.track.scrollLeft,left);assert.equal(f.frames.size,0);assert.equal(f.track.style.scrollSnapType,'');
|
||||
});
|
||||
test('partial galleries and uninterrupted page scrolling do not capture the wheel',()=>{
|
||||
const f=fixture();f.mediaRect.top=350;f.mediaRect.bottom=1150;
|
||||
assert.equal(f.wheel().defaultPrevented,false);assert.equal(f.count.textContent,'1 / 5');
|
||||
f.mediaRect.top=100;f.mediaRect.bottom=900;f.advance(80);
|
||||
assert.equal(f.wheel().defaultPrevented,false,'do not take over the ongoing page gesture');
|
||||
f.advance(200);assert.equal(f.wheel().defaultPrevented,true);assert.equal(f.count.textContent,'2 / 5');
|
||||
});
|
||||
test('partially exited galleries release wheel; other controls retain reduced-motion policy',()=>{
|
||||
const f=fixture({reduced:true});f.next.emit('click');assert.equal(f.calls.at(-1).behavior,'instant');
|
||||
f.mediaRect.top=-400;f.mediaRect.bottom=400;
|
||||
assert.equal(f.wheel({deltaY:-100}).defaultPrevented,false);
|
||||
});
|
||||
test('macOS, touch devices, fitting galleries, zoom and form controls retain native input',()=>{
|
||||
for(const settings of [{platform:'MacIntel'},{fine:false},{width:1920,size:560,length:2}]){
|
||||
const f=fixture(settings),n=f.calls.length;assert.equal(f.wheel().defaultPrevented,false);assert.equal(f.calls.length,n);
|
||||
|
||||
Reference in New Issue
Block a user