85 lines
2.8 KiB
JavaScript
85 lines
2.8 KiB
JavaScript
/**
|
|
* motion.js — Micro-animations sobres et barre de progression de lecture
|
|
* =============================================================================
|
|
* - Indicateur de progression de lecture fixé en haut de page
|
|
* - Révélation douce des sections au défilement via IntersectionObserver
|
|
* - Respect strict de prefers-reduced-motion: reduce
|
|
* - Révélation immédiate avant impression (beforeprint) pour garantir qu'aucun
|
|
* bloc ne reste invisible sur le PDF
|
|
*/
|
|
|
|
/**
|
|
* Force la visibilité de tous les éléments animés.
|
|
* @param {NodeListOf<HTMLElement>} elements
|
|
* @returns {void}
|
|
*/
|
|
export function revealAll(elements) {
|
|
elements.forEach((el) => {
|
|
el.dataset.revealed = "true";
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Initialise la barre de progression de lecture et la révélation au scroll.
|
|
*
|
|
* @param {object} [options]
|
|
* @param {HTMLElement | null} [options.progressBar] - Conteneur de la barre.
|
|
* @param {NodeListOf<HTMLElement>} [options.revealNodes] - Éléments [data-reveal].
|
|
* @returns {{ revealAll: () => void }}
|
|
*/
|
|
export function initMotion({ progressBar, revealNodes } = {}) {
|
|
const nodes = revealNodes ?? document.querySelectorAll("[data-reveal]");
|
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
|
|
/* --- 1. Révélation au défilement ------------------------------------ */
|
|
if (reducedMotion || !("IntersectionObserver" in window)) {
|
|
revealAll(nodes);
|
|
} else if (nodes.length > 0) {
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
entries.forEach((entry) => {
|
|
if (!entry.isIntersecting) return;
|
|
entry.target.dataset.revealed = "true";
|
|
observer.unobserve(entry.target);
|
|
});
|
|
},
|
|
{
|
|
rootMargin: "0px 0px -8% 0px",
|
|
threshold: 0.05,
|
|
}
|
|
);
|
|
|
|
nodes.forEach((node) => observer.observe(node));
|
|
}
|
|
|
|
// Avant impression (y compris via Ctrl+P / Cmd+P), tout est révélé.
|
|
window.addEventListener("beforeprint", () => revealAll(nodes));
|
|
|
|
/* --- 2. Barre de progression de lecture ----------------------------- */
|
|
if (progressBar && !reducedMotion) {
|
|
let ticking = false;
|
|
|
|
const updateProgress = () => {
|
|
ticking = false;
|
|
const doc = document.documentElement;
|
|
const scrollable = doc.scrollHeight - window.innerHeight;
|
|
const ratio = scrollable > 0 ? Math.min(1, Math.max(0, window.scrollY / scrollable)) : 0;
|
|
progressBar.style.setProperty("--scroll-progress", ratio.toFixed(4));
|
|
};
|
|
|
|
const onScroll = () => {
|
|
if (ticking) return;
|
|
ticking = true;
|
|
window.requestAnimationFrame(updateProgress);
|
|
};
|
|
|
|
window.addEventListener("scroll", onScroll, { passive: true });
|
|
window.addEventListener("resize", onScroll, { passive: true });
|
|
updateProgress();
|
|
}
|
|
|
|
return {
|
|
revealAll: () => revealAll(nodes),
|
|
};
|
|
}
|