Files
CoHaiSe/frontend/web/app/lib/gsap.ts
T
Gitea Actions 723b68ea80
deploy / deploy (push) Successful in 1m24s
feat: migrate showcase to Next.js and overhaul CRM UI
rebuild the public site on the Next.js App Router with static export,

per-section SEO pages, metadata, sitemap, robots and a generated OG image

add full-screen scroll-snap regions, staged scroll reveals, a hash-free

tab navigation with a sliding indicator and region-by-region menu scrolling

replace the theme text toggle with animated sun/moon icons

restructure the CRM API into config, middleware, models, routes, services

and utils layers

redesign the CRM shell with a single surface, tab rail, full-width blurred

DataTable, record dialogs and mask-based icons

update Docker/Nginx publishing, Makefile targets, shared UI polish and docs

Co-authored-by: Gitea Actions <-[email protected]>
2026-11-16 00:08:17 +00:00

198 lines
5.8 KiB
TypeScript

import { gsap } from "gsap";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";
gsap.registerPlugin(ScrollToPlugin);
export { gsap };
export const prefersReducedMotion = (): boolean =>
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/*
Le menu ne touche plus à l'URL : pour ramener un visiteur d'une page SEO vers
une région de l'accueil, on mémorise la cible le temps de la navigation.
`sessionStorage` survit au montage de la nouvelle page et reste limité à
l'onglet courant.
*/
const PENDING_SECTION_KEY = "cohaise:pending-section";
export const setPendingSection = (id: string): void => {
try {
window.sessionStorage.setItem(PENDING_SECTION_KEY, id);
} catch {
// Stockage indisponible : le lien ramènera simplement en haut de l'accueil.
}
};
export const takePendingSection = (): string | null => {
try {
const id = window.sessionStorage.getItem(PENDING_SECTION_KEY);
if (id !== null) window.sessionStorage.removeItem(PENDING_SECTION_KEY);
return id;
} catch {
return null;
}
};
/** Position de scroll maximale de la page. */
const maxScroll = (): number =>
Math.max(0, document.documentElement.scrollHeight - window.innerHeight);
/** Début de chaque région, plus le haut de page, sans doublon. */
const scrollStops = (): number[] => {
const limit = maxScroll();
const regions = Array.from(
document.querySelectorAll<HTMLElement>(
"main[data-scroll-snap] > [data-region]",
),
);
const tops = regions.map((region) => {
const top = region.getBoundingClientRect().top + window.scrollY;
return Math.round(Math.min(Math.max(top, 0), limit));
});
return [...new Set([0, ...tops])].sort((a, b) => a - b);
};
/** Index du dernier point d'arrêt situé au-dessus de la position courante. */
const stopAtOrAbove = (stops: number[], y: number): number => {
let index = 0;
for (let i = 0; i < stops.length; i += 1) {
const stop = stops[i];
if (stop === undefined || stop > y + 2) break;
index = i;
}
return index;
};
/*
Un saut de menu ne téléporte plus la page : elle est animée région par
région, avec une courte respiration entre chaque étape. Le snap obligatoire
est suspendu pendant la séquence (`html[data-scroll-anim]`), sinon le
navigateur reprend la main et saute directement à la destination.
*/
const STEP_DURATION = 0.45;
const STEP_GAP = 0.06;
let sequence: gsap.core.Timeline | null = null;
/**
* Anime le défilement vers une section, sans toucher à l'URL.
*
* @returns la durée de la séquence en millisecondes (0 si aucun mouvement).
*/
export const scrollToSection = (hash: string): number => {
const target = document.querySelector<HTMLElement>(hash);
if (!target) return 0;
/*
Une région est l'unité de snap : une ancre imbriquée (About partage la
région de Stack) doit viser la région entière, sinon le snap obligatoire
choisit un bord et peut sauter par-dessus le contenu visé.
*/
const anchor = target.closest<HTMLElement>("[data-region]") ?? target;
if (prefersReducedMotion()) {
sequence?.kill();
sequence = null;
delete document.documentElement.dataset.scrollAnim;
anchor.scrollIntoView({ behavior: "auto" });
return 0;
}
const limit = maxScroll();
const targetTop = Math.round(
Math.min(
Math.max(anchor.getBoundingClientRect().top + window.scrollY, 0),
limit,
),
);
if (Math.abs(window.scrollY - targetTop) < 2) return 0;
const stops = scrollStops();
const from = stopAtOrAbove(stops, window.scrollY);
const to = stops.reduce((best, stop, index) => {
const bestStop = stops[best];
if (bestStop === undefined) return index;
return Math.abs(stop - targetTop) < Math.abs(bestStop - targetTop)
? index
: best;
}, 0);
// Chaque région traversée est une étape : le mouvement reste lisible et
// n'expédie jamais le visiteur d'un bord à l'autre de la page.
const path: number[] = [];
if (to > from) {
for (let i = from + 1; i <= to; i += 1) {
const stop = stops[i];
if (stop !== undefined) path.push(stop);
}
} else {
for (let i = from - 1; i >= to; i -= 1) {
const stop = stops[i];
if (stop !== undefined) path.push(stop);
}
}
if (path.length === 0) path.push(targetTop);
sequence?.kill();
const root = document.documentElement;
root.dataset.scrollAnim = "";
/*
Un geste de défilement pendant la séquence doit reprendre la main
immédiatement : on coupe l'animation plutôt que de lutter contre le
visiteur. Les événements souris/tactiles arrivent après le clic qui a lancé
la séquence, donc ils ne l'annulent pas elle-même.
*/
const scrollKeys = new Set([
"ArrowUp",
"ArrowDown",
"PageUp",
"PageDown",
"Home",
"End",
" ",
]);
const interrupt = () => {
sequence?.kill();
};
const onKeyDown = (event: KeyboardEvent) => {
if (scrollKeys.has(event.key)) interrupt();
};
const finish = () => {
delete root.dataset.scrollAnim;
window.removeEventListener("wheel", interrupt);
window.removeEventListener("touchmove", interrupt);
window.removeEventListener("keydown", onKeyDown);
if (sequence === timeline) sequence = null;
};
const timeline = gsap.timeline({ onComplete: finish, onInterrupt: finish });
window.addEventListener("wheel", interrupt, { passive: true });
window.addEventListener("touchmove", interrupt, { passive: true });
window.addEventListener("keydown", onKeyDown);
path.forEach((top, index) => {
timeline.to(
window,
{
scrollTo: { y: top, autoKill: false },
duration: STEP_DURATION,
ease: "power2.inOut",
},
index === 0 ? 0 : `+=${STEP_GAP}`,
);
});
sequence = timeline;
return Math.round(timeline.duration() * 1000);
};