Align the page to nearby carousels before wheel slide navigation

This commit is contained in:
2026-11-12 18:59:50 +03:00
parent ffe83740e1
commit 4c5095e62a
5 changed files with 102 additions and 14 deletions
+54 -5
View File
@@ -14,7 +14,37 @@
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);
@@ -45,6 +75,7 @@
});
}
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]);
@@ -82,6 +113,7 @@
}, {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};
@@ -112,25 +144,42 @@
// 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) { stopWheelMotion(); continuousUntil = now + 250; return; }
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 centered = Math.abs((rect.top + rect.bottom - top - bottom) / 2) <= 80;
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;
}
const direction = Math.sign(dy);
// Consume a short burst while moving, but allow reversal immediately.
if (now - lastStep < 220 && direction === lastDirection) {
event.preventDefault(); event.stopPropagation(); return;
}
const target = active + direction;
if (target < 0 || target >= items.length) return;
event.preventDefault(); event.stopPropagation();
lastStep = now; lastDirection = direction;
// User-requested wheel navigation remains smooth even with reduced
@@ -0,0 +1,21 @@
# Магнит страницы и горизонтального слайда
Пользователь уточнил, что нужны оба вида центрирования: страница подводится к галерее, затем слайды доводятся до горизонтального центра. Это продолжение исправления ffe8374 в ветке fix/carousel-mouse-wheel репозитория NODEDC_SITE.
## Поведение
Только существующий сценарий дискретного колеса на desktop Windows/Linux получил вертикальный подвод. Mac и мобильные жесты не подключаются к этому сценарию. При близкой галерее (не дальше 240 px/30% доступной высоты от центра и видно не меньше 65% изображения/доступного окна) первый жест выравнивает центр изображения по центру окна между верхним отступом 64 px и нижним 32 px. Дальние галереи не притягиваются. При движении прочь от уже пройденной галереи подвод назад допустим только в зоне 80 px от центра.
Подвод страницы занимает 300 мс и не переключает слайды. События той же серии поглощаются до окончания подвода и паузы 180 мс; только новый жест переключает слайд. Горизонтальный переход остаётся плавным, 300 мс, с точным центрированием. Обратное колесо отменяет подвод, отдавая управление странице. На первом/последнем слайде движение наружу не притягивает страницу обратно.
Колесо вне ленты, нажатие указателя, клавиатура, переход стрелками, изменение ширины и непрерывный жест отменяют вертикальное движение. Слушатели отмены существуют только во время подвода и удаляются при завершении/отмене. Нет постоянного цикла кадров или таймера. Целевая позиция ограничена границами документа.
## Проверка
17 тестов проходят: промежуточные кадры вертикального и горизонтального движения, сохранение первого слайда во время подвода и хвоста жеста, новый жест после паузы, отмена разворотом/клавиатурой, свободный выход на краях, сохранение поведения Mac/касания, прежние регрессии каруселей и заголовков.
В Chrome Windows на локальной копии текущего экспорта первый жест сохранил 1/7 и переместил верх изображения с 252.17 до 113.5 px. Центр изображения 508.56 px при целевом центре окна 508.5 px. Следующий жест переключил на 2/7. Физические Mac/телефон недоступны; их новый сценарий не затрагивает.
## Поставка
Свежий бэкап CMS содержал 217 записей. Изменены carousel.js, index.html и templates/pages/home/shell.html; остальные 214 записей побайтно сохранены. Версия carousel.js: 01d298fd2fd5. Бэкап для отката: D:/_PROJ/NODEDC/Last_back/carousel-magnet-2026-11-12/before.zip. Временные панели диагностики preview не входят в архив.
+1 -1
View File
@@ -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=1c1b1398921b"></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=01d298fd2fd5"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
<style>
[debug] {
+1 -1
View File
@@ -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=1c1b1398921b"></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=01d298fd2fd5"></script></head><body><div class="w-embed"><link rel="stylesheet" href="./assets/custom/css/app.css?v=27a8f15dc429">
<style>
[debug] {
+25 -7
View File
@@ -7,8 +7,9 @@ function fixture({width=390,size=330,length=5,platform='Win32',fine=true,reduced
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 mediaRect={top:116,bottom:916,height:800};
const target=()=>({listeners:{},dataset:{},classList:{toggle(){},add(){},remove(){}},addEventListener(n,f){(this.listeners[n]??=[]).push(f);},removeEventListener(n,f){this.listeners[n]=(this.listeners[n]||[]).filter(fn=>fn!==f);},emit(n,e={}){for(const f of this.listeners[n]||[])f(e);}});
const page={...target(),innerHeight:1000,scrollY:1000,scrollTo({top}){const delta=top-this.scrollY;this.scrollY=top;mediaRect.top-=delta;mediaRect.bottom-=delta;}};
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);},querySelector(){return {getBoundingClientRect:()=>mediaRect};},querySelectorAll(){return [];}}));
@@ -17,8 +18,8 @@ function fixture({width=390,size=330,length=5,platform='Win32',fine=true,reduced
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,{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');}};
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:{documentElement:{scrollHeight:6000},readyState:'complete',querySelectorAll:()=>[root]},window:page,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,page,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',()=>{
@@ -44,13 +45,30 @@ test('pointer interaction cancels wheel motion and restores native snapping',()=
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;
test('distant galleries and uninterrupted page scrolling do not capture the wheel',()=>{
const f=fixture();f.mediaRect.top=500;f.mediaRect.bottom=1300;
assert.equal(f.wheel().defaultPrevented,false);assert.equal(f.count.textContent,'1 / 5');
f.mediaRect.top=100;f.mediaRect.bottom=900;f.advance(80);
f.mediaRect.top=116;f.mediaRect.bottom=916;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('page magnet aligns media smoothly before allowing a fresh gesture to advance slides',()=>{
const f=fixture();f.mediaRect.top=250;f.mediaRect.bottom=1050;
assert.equal(f.wheel().defaultPrevented,true);assert.equal(f.count.textContent,'1 / 5');
f.tick(100);assert.ok(f.page.scrollY>1000&&f.page.scrollY<1134);
f.wheel();assert.equal(f.count.textContent,'1 / 5','arrival burst cannot advance slides');
f.tick(200);assert.equal(f.page.scrollY,1134);assert.equal(f.mediaRect.top,116);
f.wheel();assert.equal(f.count.textContent,'1 / 5','tail immediately after arrival is consumed');
f.advance(200);f.wheel();assert.equal(f.count.textContent,'2 / 5');
assert.equal(f.page.listeners.keydown.length,0,'temporary input hooks are cleaned up');
});
test('reverse or keyboard input cancels the page magnet; end slides never pull the page back',()=>{
const f=fixture();f.mediaRect.top=250;f.mediaRect.bottom=1050;f.wheel();f.tick(100);
const y=f.page.scrollY;assert.equal(f.wheel({deltaY:-100}).defaultPrevented,false);f.tick(500);assert.equal(f.page.scrollY,y);
const g=fixture();g.mediaRect.top=250;g.mediaRect.bottom=1050;g.wheel();g.tick(50);g.page.emit('keydown',{type:'keydown'});const stopped=g.page.scrollY;g.tick(400);assert.equal(g.page.scrollY,stopped);assert.equal(g.frames.size,0);
const end=fixture({length:2});end.next.emit('click');end.mediaRect.top=250;end.mediaRect.bottom=1050;
assert.equal(end.wheel().defaultPrevented,false);assert.equal(end.page.scrollY,1000);
});
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;