diff --git a/assets/custom/js/carousel.js b/assets/custom/js/carousel.js index bb95f09..a1e435b 100644 --- a/assets/custom/js/carousel.js +++ b/assets/custom/js/carousel.js @@ -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 diff --git a/docs/incidents/2026-11-12-carousel-page-magnet.md b/docs/incidents/2026-11-12-carousel-page-magnet.md new file mode 100644 index 0000000..4b0beb1 --- /dev/null +++ b/docs/incidents/2026-11-12-carousel-page-magnet.md @@ -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 не входят в архив. diff --git a/index.html b/index.html index e04fe26..43d10ad 100644 --- a/index.html +++ b/index.html @@ -53,7 +53,7 @@ background: #000 !important; background-image: none !important; } -
+
+