32 lines
1.1 KiB
TypeScript
32 lines
1.1 KiB
TypeScript
// Smooth scroll Lenis — import dynamique, une seule instance, gate reduced-motion.
|
|||
|
|
import { prefersReducedMotion } from './tokens';
|
||
|
|
|
||
|
|
type Lenis = { raf: (t: number) => void; destroy: () => void; scrollTo: (t: unknown, o?: unknown) => void };
|
||
|
|
|
||
|
|
let lenis: Lenis | null = null;
|
||
|
|
let rafId = 0;
|
||
|
|
|
||
|
|
export async function initSmoothScroll(): Promise<() => void> {
|
||
|
|
if (prefersReducedMotion() || typeof window === 'undefined') return () => {};
|
||
|
|
const { default: Lenis } = await import('lenis');
|
||
|
|
lenis = new Lenis({ lerp: 0.11, wheelMultiplier: 1, smoothWheel: true }) as unknown as Lenis;
|
||
|
|
const loop = (t: number) => {
|
||
|
|
lenis?.raf(t);
|
||
|
|
rafId = requestAnimationFrame(loop);
|
||
|
|
};
|
||
|
|
rafId = requestAnimationFrame(loop);
|
||
|
|
return () => {
|
||
|
|
cancelAnimationFrame(rafId);
|
||
|
|
lenis?.destroy();
|
||
|
|
lenis = null;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Défilement vers une ancre (#id) en respectant Lenis si actif. */
|
||
|
|
export function scrollToAnchor(hash: string): void {
|
||
|
|
const el = document.querySelector(hash);
|
||
|
|
if (!el) return;
|
||
|
|
if (lenis) lenis.scrollTo(el, { offset: -80 });
|
||
|
|
else el.scrollIntoView({ behavior: 'smooth' });
|
||
|
|
}
|