From 6cac9a170439aa5fd28d135e45f172e8d0c3b8aa Mon Sep 17 00:00:00 2001 From: SILVER Date: Thu, 12 Nov 2026 18:00:57 +0300 Subject: [PATCH] Avoid early carousel wheel capture and smooth explicit wheel navigation --- assets/custom/js/carousel.js | 48 ++++++++++++++++--- .../2026-11-12-carousel-wheel-alignment.md | 23 +++++++++ index.html | 2 +- templates/pages/home/shell.html | 2 +- test/carousel.test.mjs | 33 ++++++++++--- 5 files changed, 94 insertions(+), 14 deletions(-) create mode 100644 docs/incidents/2026-11-12-carousel-wheel-alignment.md diff --git a/assets/custom/js/carousel.js b/assets/custom/js/carousel.js index 2173c21..bb95f09 100644 --- a/assets/custom/js/carousel.js +++ b/assets/custom/js/carousel.js @@ -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); diff --git a/docs/incidents/2026-11-12-carousel-wheel-alignment.md b/docs/incidents/2026-11-12-carousel-wheel-alignment.md new file mode 100644 index 0000000..d14f211 --- /dev/null +++ b/docs/incidents/2026-11-12-carousel-wheel-alignment.md @@ -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. diff --git a/index.html b/index.html index 869506c..e04fe26 100644 --- a/index.html +++ b/index.html @@ -53,7 +53,7 @@ background: #000 !important; background-image: none !important; } -
+
+