91 lines
3.1 KiB
TypeScript
91 lines
3.1 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect } from 'react';
|
|
import Lenis from 'lenis';
|
|
import { scrollBus } from '@/lib/scrollBus';
|
|
import { scrollEnv } from '@/lib/scrollEnv';
|
|
|
|
const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
|
|
|
|
/**
|
|
* Lenis smooth scrolling + the original sP camera-progress computation
|
|
* (banner/footer section geometry):
|
|
* f1 = clamp((vh - bannerBottom) / max(1, vh - .25vh), 0, 1)
|
|
* f2 = footer ? clamp(footerTop / vh, 0, 1) : 1
|
|
* sP = f1 * f2
|
|
* f2 measures the footer's distance ABOVE: it is 1 while the footer is
|
|
* further than one viewport away and falls to 0 as the footer top reaches
|
|
* the viewport top. Until the footer section exists we keep f2 at 1 —
|
|
* matching the original's behavior for most of the page (sP → 1 after
|
|
* ~0.75 viewport of scroll, which drives the dot-overlay fade and the
|
|
* camera pull-back).
|
|
*/
|
|
export default function SmoothScroller() {
|
|
useEffect(() => {
|
|
// Refresh must always start at the top (original behavior: no anchor
|
|
// → scroll to 0; also re-asserted on bfcache pageshow).
|
|
if ('scrollRestoration' in window.history) {
|
|
window.history.scrollRestoration = 'manual';
|
|
}
|
|
const resetScroll = () => {
|
|
if (window.location.hash) return;
|
|
window.scrollTo(0, 0);
|
|
requestAnimationFrame(() => window.scrollTo(0, 0));
|
|
};
|
|
resetScroll();
|
|
const onPageShow = (e: PageTransitionEvent) => {
|
|
if (e.persisted) resetScroll();
|
|
};
|
|
window.addEventListener('pageshow', onPageShow);
|
|
|
|
const updateCameraProgress = () => {
|
|
const vh = Math.max(1, window.innerHeight);
|
|
const banner = document.querySelector('[data-section="banner"]');
|
|
const footer = document.querySelector('[data-section="footer"]');
|
|
if (!banner) {
|
|
scrollBus.sP = 0;
|
|
return;
|
|
}
|
|
const bannerRect = banner.getBoundingClientRect();
|
|
const f1 = clamp01((vh - bannerRect.bottom) / Math.max(1, vh - 0.25 * vh));
|
|
const f2 = footer
|
|
? clamp01(footer.getBoundingClientRect().top / vh)
|
|
: 1;
|
|
scrollBus.sP = f1 * f2;
|
|
};
|
|
|
|
const lenis = new Lenis({
|
|
lerp: 0.1,
|
|
smoothWheel: true,
|
|
});
|
|
scrollEnv.setLenis(lenis);
|
|
|
|
lenis.scrollTo(0, { immediate: true });
|
|
|
|
lenis.on('scroll', (e: any) => {
|
|
scrollBus.current = e.scroll;
|
|
scrollBus.velocity = e.velocity;
|
|
scrollBus.progress = e.progress;
|
|
updateCameraProgress();
|
|
});
|
|
window.addEventListener('resize', updateCameraProgress);
|
|
updateCameraProgress();
|
|
|
|
function raf(time: number) {
|
|
lenis.raf(time);
|
|
requestAnimationFrame(raf);
|
|
}
|
|
|
|
requestAnimationFrame(raf);
|
|
|
|
return () => {
|
|
window.removeEventListener('resize', updateCameraProgress);
|
|
window.removeEventListener('pageshow', onPageShow);
|
|
scrollEnv.setLenis(null);
|
|
lenis.destroy();
|
|
};
|
|
}, []);
|
|
|
|
return null;
|
|
}
|