Compare commits

..
10 Commits
Author SHA1 Message Date
Gitea ActionsandEsiah 92b868d966 feat: redesign events gallery and polish site UX (#1)
Deploy React Site / build-and-deploy (push) Successful in 11s
- Events: render each year as a horizontal band of media at native ratio with a chapter card, lightbox (keyboard nav + close), and a progress bar.

- Add a route transition overlay that preloads the destination hero image and shows a typed "Unis par le cœur" loading bar; hide the header while active and sync page entrance animations until the transition ends.

- Add proper favicon set (favicon.ico, Apple touch icon, Android/PWA icon) and web manifest; fix the icon MIME type.

- Mobile menu: replace hover-only feedback with an :active tap state (color + scale), remove sticky hover.

- Privacy policy: document server-side relay of Meta content, add hosting/logs and GDPR rights sections.

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #1
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-10-19 21:59:09 +00:00
Esiah 1c445fdcd2 fix: play nav intro animation once per page load
Deploy React Site / build-and-deploy (push) Successful in 10s
Guard the initial load animation with a ref so it no longer replays on client-side route changes. Replay it when the page is restored from the back-forward cache (pageshow persisted).
2026-10-19 21:41:07 +02:00
Esiah 97dd2f87f1 fix: serve Facebook images through path-based proxy URL
Deploy React Site / build-and-deploy (push) Successful in 11s
nginx does not percent-decode $arg_ variables, so pass the encoded image URL in the path (nginx decodes $uri). Mirror the Meta CDN whitelist in the Vite dev middleware.
2026-10-19 21:34:16 +02:00
Esiah 61c9f8d614 fix: proxy d'images Facebook en prod (même origine)
Deploy React Site / build-and-deploy (push) Successful in 10s
Les visuels de posts étaient chargés directement depuis *.fbcdn.net, bloqués
côté navigateur (protection anti-pistage/GPC), en mixed-content ou en 403.
Ils passent désormais par /api/proxy-image (nginx en prod, Vite en dev).
2026-10-19 20:54:35 +02:00
Esiah c093708ca6 fix: ID de page Facebook géré côté serveur (fin de la config de build)
Deploy React Site / build-and-deploy (push) Successful in 11s
Le build CI ne fournissait pas VITE_FACEBOOK_PAGE_ID, ce qui rendait le
garde-fou toujours vrai et faisait supprimer tout le fetch par le bundler
(code mort) : aucune requête n'était émise. L'ID de page et le token sont
désormais injectés côté serveur (proxy Vite en dev, nginx en prod) et le
front appelle /api/facebook/posts.
2026-10-19 20:35:51 +02:00
Esiah eef33aed0d feat: consentement cookies + proxy Facebook côté serveur
Deploy React Site / build-and-deploy (push) Successful in 11s
- Bannière de consentement (localStorage) et blocage du contenu tiers
  Facebook tant que l'utilisateur n'a pas accepté ; lien « Gérer les cookies ».
- Le token Facebook n'est plus exposé au navigateur : le front appelle
  /api/facebook, injecté côté serveur (proxy Vite en dev, nginx en prod).
- Mise à jour de la politique de confidentialité.
2026-10-19 20:18:43 +02:00
Esiah 9a69f31758 ci: scope LFS auth header to batch endpoint to avoid duplicate Authorization
Deploy React Site / build-and-deploy (push) Successful in 11s
2026-10-19 19:43:57 +02:00
Esiah 1c86f35fde ci: fetch Git LFS objects during deploy
Deploy React Site / build-and-deploy (push) Failing after 2m24s
2026-10-19 19:39:49 +02:00
Esiah d838dc9ac3 assets: version media files via Git LFS
Deploy React Site / build-and-deploy (push) Successful in 9s
2026-10-19 19:30:03 +02:00
Esiah ccf2325257 chore: configure Git LFS for media 2026-10-19 19:30:03 +02:00
22 changed files with 816 additions and 235 deletions
+11
View File
@@ -0,0 +1,11 @@
# --- Variables lues uniquement côté serveur (jamais dans le bundle) ---
# En dev : par le proxy de Vite (vite.config.ts)
# En prod : par nginx (proxy vers l'API Graph)
#
# IMPORTANT : ne PAS préfixer par VITE_, sinon elles seraient exposées.
# ID public de la page Facebook (non sensible)
FACEBOOK_PAGE_ID=819434444588954
# Jeton d'accès à la page Facebook (SECRET)
FACEBOOK_ACCESS_TOKEN=
+15
View File
@@ -12,6 +12,14 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Fetch Git LFS objects
run: |
git lfs install --local
AUTH="$(git config --local "http.${{ github.server_url }}/.extraheader")"
git config --local --unset "http.${{ github.server_url }}/.extraheader"
git config --local "http.${{ github.server_url }}/${{ github.repository }}.git/info/lfs/objects/batch.extraheader" "$AUTH"
git lfs pull
- uses: actions/setup-node@v4
with:
node-version: "20"
@@ -20,4 +28,11 @@ jobs:
- run: npm run build
- name: Verify no LFS pointer files remain
run: |
if grep -rl "git-lfs.github.com/spec/v1" dist/; then
echo "::error::LFS pointers found in dist/ - git-lfs was not fetched."
exit 1
fi
- run: rsync -av --delete dist/ /srv/apps/websites/coeur-ua-pam.org/
+52
View File
@@ -0,0 +1,52 @@
name: PR — Ouverture automatique
on:
push:
branches-ignore: [main]
workflow_dispatch:
jobs:
create-pr:
runs-on: coeur-ua-pam
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Ouvrir (ou vérifier) la pull request
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1
REPO: ${{ github.repository }}
BRANCH: ${{ github.ref_name }}
run: |
set -eu
if [ "$BRANCH" = "main" ]; then
echo "main est la base : aucune PR à ouvrir."
exit 0
fi
title=$(git log -1 --pretty=%s)
body=$(git log -1 --pretty=%b)
[ -n "$body" ] || body="PR automatique de $BRANCH vers main."
open=$(curl -fsS -H "Authorization: token $GITEA_TOKEN" \
"$API/repos/$REPO/pulls?state=open&limit=50" \
| python3 -c 'import json,os,sys; b=os.environ["BRANCH"]; print(sum(1 for p in json.load(sys.stdin) if p.get("head", {}).get("ref") == b))')
if [ "$open" -gt 0 ]; then
echo "Une PR est déjà ouverte pour $BRANCH."
exit 0
fi
python3 - "$BRANCH" "$title" "$body" <<'PY' | curl -fsS -X POST \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @- \
"$API/repos/$REPO/pulls"
import json, sys
branch, title, body = sys.argv[1], sys.argv[2], sys.argv[3]
print(json.dumps({"base": "main", "head": branch, "title": title, "body": body}))
PY
echo "PR créée."
+4 -1
View File
@@ -2,7 +2,10 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/logo.png" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/png" sizes="192x192" href="/android-chrome-192x192.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Coeur UA PAM - Unis par le coeur</title>
<link
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+19
View File
@@ -0,0 +1,19 @@
{
"name": "Cœur UA PAM",
"short_name": "Cœur UA PAM",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/logo.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#1a247f",
"background_color": "#f7f0e5",
"display": "standalone"
}
+2
View File
@@ -6,11 +6,13 @@ import Events from "./pages/Events";
import Historic from "./pages/Historic";
import Privacy from "./pages/Privacy";
import ScrollToTop from "./components/ScrollToTop";
import PageTransition from "./components/PageTransition";
function App() {
return (
<BrowserRouter>
<ScrollToTop />
<PageTransition />
<Routes>
<Route path="/" element={<MainLayout />}>
<Route path="/" element={<Home />} />
+7 -1
View File
@@ -1,6 +1,7 @@
import React, { useRef, useEffect } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { runAfterTransition } from "../lib/transition";
gsap.registerPlugin(ScrollTrigger);
@@ -96,15 +97,20 @@ const AnimatedContent: React.FC<AnimatedContentProps> = ({
ease,
});
let stopWaiting = () => {};
const st = ScrollTrigger.create({
trigger: el,
scroller: scrollerTarget || window,
start: `top ${startPct}%`,
once: true,
onEnter: () => tl.play(),
onEnter: () => {
stopWaiting = runAfterTransition(() => tl.play());
},
});
return () => {
stopWaiting();
st.kill();
tl.kill();
};
+58
View File
@@ -0,0 +1,58 @@
import { motion, AnimatePresence } from "framer-motion";
import { Link } from "react-router-dom";
import { useCookieConsent } from "../context/CookieConsent";
export default function CookieBanner() {
const { consent, accept, refuse } = useCookieConsent();
return (
<AnimatePresence>
{consent === null && (
<motion.div
initial={{ y: 120, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: 120, opacity: 0 }}
transition={{ duration: 0.35, ease: "easeOut" }}
className="fixed inset-x-0 bottom-0 z-[100] p-4 md:p-6"
role="dialog"
aria-live="polite"
aria-label="Préférences de cookies"
>
<div className="mx-auto max-w-3xl rounded-[24px] bg-white shadow-2xl border border-primary/10 p-6 md:p-8 flex flex-col md:flex-row md:items-center gap-6">
<div className="flex-1">
<h2 className="text-lg font-bold text-primary mb-2">
Contenu Facebook
</h2>
<p className="text-sm text-site-text/80 leading-relaxed">
Nous affichons les actualités de notre page Facebook. En
acceptant, vous autorisez le chargement de ce contenu tiers
(Meta) qui peut déposer des cookies. Vous pouvez refuser et
consulter la page Facebook via un lien direct.{" "}
<Link
to="/politique-confidentialite"
className="text-primary underline hover:text-hover-nav"
>
En savoir plus
</Link>
</p>
</div>
<div className="flex flex-col sm:flex-row gap-3 shrink-0">
<button
onClick={refuse}
className="px-6 py-3 rounded-full border-2 border-primary/20 text-primary font-semibold uppercase tracking-wider text-xs hover:bg-bg-2 transition-colors"
>
Continuer sans accepter
</button>
<button
onClick={accept}
className="px-6 py-3 rounded-full bg-primary text-white font-bold uppercase tracking-wider text-xs hover:bg-heading-accent transition-colors shadow-lg"
>
Accepter
</button>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
);
}
+49 -67
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useCookieConsent } from "../context/CookieConsent";
// Modèle de données pour un post Facebook
interface FacebookPost {
@@ -27,14 +28,6 @@ interface FacebookApiPost {
};
}
// Interface pour la récupération des comptes (pages)
interface FacebookAccountResponse {
data: Array<{
id: string;
access_token: string;
}>;
}
// Composant Spinner
const LoadingSpinner = () => (
<div className="flex items-center justify-center h-full w-full">
@@ -58,6 +51,35 @@ const ErrorMessage = () => (
</div>
);
// Affiché tant que l'utilisateur n'a pas consenti au chargement du contenu tiers
const ConsentPlaceholder = ({ onAccept }: { onAccept: () => void }) => (
<div className="flex flex-col items-center justify-center h-full w-full text-primary font-medium p-6 text-center">
<div className="w-12 h-12 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-xl mb-5">
f
</div>
<p className="mb-6 italic text-lg text-site-text/70 max-w-md">
Pour afficher nos actualités Facebook, nous avons besoin de votre accord
pour charger ce contenu tiers.
</p>
<div className="flex flex-col sm:flex-row items-center gap-3">
<button
onClick={onAccept}
className="px-8 py-3 rounded-full bg-primary text-white font-bold uppercase tracking-wider hover:bg-heading-accent transition-all shadow-lg text-sm"
>
Activer Facebook
</button>
<a
href="https://www.facebook.com/profile.php?id=819434444588954"
target="_blank"
rel="noopener noreferrer"
className="px-8 py-3 rounded-full border-2 border-primary/20 text-primary font-semibold uppercase tracking-wider hover:bg-bg-2 transition-all text-sm"
>
Voir la page Facebook
</a>
</div>
</div>
);
// Utilitaire pour formater la date (ex: "Il y a 2 jours")
const timeAgo = (dateString: string) => {
const date = new Date(dateString);
@@ -77,6 +99,7 @@ const timeAgo = (dateString: string) => {
};
export default function FacebookCarousel() {
const { consent, accept } = useCookieConsent();
const [posts, setPosts] = useState<FacebookPost[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [loading, setLoading] = useState(true);
@@ -96,68 +119,23 @@ export default function FacebookCarousel() {
}, [loading, error, posts.length, isPaused]);
useEffect(() => {
if (consent !== "accepted") return;
const fetchFacebookPosts = async () => {
const pageId = import.meta.env.VITE_FACEBOOK_PAGE_ID;
const accessToken = import.meta.env.VITE_FACEBOOK_ACCESS_TOKEN;
if (!accessToken || accessToken.includes("ton_token")) {
setLoading(false);
setError(true);
return;
}
const baseUrl = import.meta.env.DEV
? "/api/facebook"
: "https://graph.facebook.com/v19.0";
const fields =
"id,created_time,message,full_picture,permalink_url,attachments";
try {
let url = `${baseUrl}/${pageId}/posts?fields=${fields}&limit=6&access_token=${accessToken}`;
// Ni le token ni l'ID de page ne sont exposés au navigateur :
// - en dev, le proxy de Vite les injecte côté serveur
// - en prod, nginx les injecte côté serveur
const url = `/api/facebook/posts?fields=${fields}&limit=6`;
// 'credentials: omit' évite d'envoyer des cookies tiers, ce qui réduit les blocages CORS/Pistage
let response = await fetch(url, {
const response = await fetch(url, {
mode: "cors",
credentials: "omit",
});
let data = await response.json();
// --- MODE DEV UNIQUEMENT : Récupération automatique du Page Token ---
// Si l'API rejette le token (Code 190 = Invalid OAuth, souvent car c'est un User Token au lieu d'un Page Token)
if (
import.meta.env.DEV &&
data.error &&
(data.error.code === 190 || data.error.code === 100)
) {
console.log(
"🔄 Token rejeté. Tentative de récupération du Page Token via l'API...",
);
try {
const accountsRes = await fetch(
`${baseUrl}/me/accounts?access_token=${accessToken}`,
);
const accountsData =
(await accountsRes.json()) as FacebookAccountResponse;
const pageData = accountsData.data?.find((p) => p.id === pageId);
if (pageData?.access_token) {
console.log(
"%c✅ SUCCÈS ! Voici le TOKEN DE PAGE à mettre dans votre .env :",
"color: green; font-weight: bold; font-size: 12px;",
);
console.log(pageData.access_token);
// On réessaie la requête avec le bon token
url = `${baseUrl}/${pageId}/posts?fields=${fields}&limit=6&access_token=${pageData.access_token}`;
response = await fetch(url);
data = await response.json();
}
} catch {
console.warn(
"Impossible de récupérer le Page Token automatiquement.",
);
}
}
const data = await response.json();
if (!response.ok || data.error) {
console.error(
@@ -175,9 +153,11 @@ export default function FacebookCarousel() {
post.attachments?.data[0]?.media?.image?.src ||
"/logo.png";
// En DEV : On passe par le proxy pour éviter le blocage "Tracking Protection" du navigateur
if (import.meta.env.DEV && imageSrc.startsWith("http")) {
imageSrc = `/api/proxy-image?url=${encodeURIComponent(imageSrc)}`;
// On passe par le proxy même origine (nginx en prod, Vite en dev)
// pour éviter le blocage de pistage du navigateur, le mixed-content
// et les 403 du CDN Facebook.
if (imageSrc.startsWith("http")) {
imageSrc = `/api/proxy-image/${encodeURIComponent(imageSrc)}`;
}
return {
@@ -205,7 +185,7 @@ export default function FacebookCarousel() {
};
fetchFacebookPosts();
}, []);
}, [consent]);
const nextPost = () => {
setCurrentIndex((prev) => (prev === posts.length - 1 ? 0 : prev + 1));
@@ -229,7 +209,7 @@ export default function FacebookCarousel() {
</div>
{/* Flèches de navigation */}
{posts.length > 0 && !loading && !error && (
{consent === "accepted" && posts.length > 0 && !loading && !error && (
<div className="flex gap-4">
<button
onClick={prevPost}
@@ -255,7 +235,9 @@ export default function FacebookCarousel() {
onMouseEnter={() => setIsPaused(true)}
onMouseLeave={() => setIsPaused(false)}
>
{loading ? (
{consent !== "accepted" ? (
<ConsentPlaceholder onAccept={accept} />
) : loading ? (
<LoadingSpinner />
) : error || posts.length === 0 ? (
<ErrorMessage />
+131
View File
@@ -0,0 +1,131 @@
import { useLayoutEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import logo from "/logo.png";
import { markTransitionStart, markTransitionEnd } from "../lib/transition";
const HERO_IMAGES: Record<string, string> = {
"/": "/hero-section/accueil.webp",
"/a-propos": "/hero-section/a-propos.webp",
"/notre-histoire": "/hero-section/historique.webp",
"/evenements": "/hero-section/evenements.webp",
};
const FADE_IN_MS = 220;
const BAR_MS = 750;
const MIN_VISIBLE_MS = 750;
const MAX_WAIT_MS = 2500;
const PageTransition = () => {
const { pathname } = useLocation();
const overlayRef = useRef<HTMLDivElement>(null);
const fillRef = useRef<HTMLDivElement>(null);
const textRef = useRef<HTMLSpanElement>(null);
useLayoutEffect(() => {
const overlay = overlayRef.current;
const fill = fillRef.current;
const text = textRef.current;
if (!overlay || !fill || !text) return;
markTransitionStart();
document.documentElement.classList.add("is-transitioning");
overlay.style.transition = "none";
overlay.style.opacity = "0";
overlay.style.visibility = "visible";
overlay.style.pointerEvents = "auto";
fill.style.transition = "none";
fill.style.width = "0%";
text.style.transition = "none";
text.style.clipPath = "inset(0 100% 0 0)";
void overlay.offsetWidth;
overlay.style.transition = `opacity ${FADE_IN_MS}ms ease-in-out`;
overlay.style.opacity = "1";
fill.style.transition = `width ${BAR_MS}ms ease-out`;
fill.style.width = "100%";
text.style.transition = `clip-path ${BAR_MS}ms ease-out`;
text.style.clipPath = "inset(0 0% 0 0)";
const startedAt = performance.now();
let done = false;
const reveal = () => {
if (done) return;
done = true;
markTransitionEnd();
document.documentElement.classList.remove("is-transitioning");
overlay.style.transition = "none";
overlay.style.opacity = "0";
overlay.style.visibility = "hidden";
overlay.style.pointerEvents = "none";
};
const finishAfterMinimum = () => {
const remaining = MIN_VISIBLE_MS - (performance.now() - startedAt);
window.setTimeout(reveal, Math.max(0, remaining));
};
const maxTimer = window.setTimeout(reveal, MAX_WAIT_MS);
const src = HERO_IMAGES[pathname];
if (src) {
let handled = false;
const onReady = () => {
if (handled) return;
handled = true;
window.clearTimeout(maxTimer);
finishAfterMinimum();
};
const image = new Image();
image.onload = onReady;
image.onerror = onReady;
image.src = src;
if (image.complete) onReady();
} else {
window.clearTimeout(maxTimer);
finishAfterMinimum();
}
return () => {
window.clearTimeout(maxTimer);
document.documentElement.classList.remove("is-transitioning");
};
}, [pathname]);
return (
<div
ref={overlayRef}
aria-hidden="true"
style={{ opacity: 0, visibility: "hidden", pointerEvents: "none" }}
className="fixed inset-0 z-[2000] bg-bg-1"
>
<div className="flex h-full items-center justify-center">
<img
src={logo}
alt=""
className="h-40 w-40 animate-pulse md:h-56 md:w-56"
/>
</div>
<div className="absolute inset-x-0 bottom-0 h-16 overflow-hidden bg-primary/10">
<span className="absolute inset-0 flex items-center justify-center whitespace-nowrap text-sm font-semibold uppercase tracking-[0.3em] text-primary/25">
Unis par le cœur
</span>
<div
ref={fillRef}
style={{ width: "0%" }}
className="absolute inset-y-0 left-0 bg-primary"
/>
<span
ref={textRef}
style={{ clipPath: "inset(0 100% 0 0)" }}
className="absolute inset-0 flex items-center justify-center whitespace-nowrap text-sm font-semibold uppercase tracking-[0.3em] text-white"
>
Unis par le cœur
</span>
</div>
</div>
);
};
export default PageTransition;
+19 -25
View File
@@ -52,6 +52,8 @@ const PillNav: React.FC<PillNavProps> = ({
const logoRef = useRef<HTMLAnchorElement | HTMLElement | null>(null);
const isInitialMount = useRef(true);
const hasPlayedIntro = useRef(false);
const [introTick, setIntroTick] = useState(0);
// --- 1. Gestion du Menu Mobile avec GSAP ---
useEffect(() => {
@@ -207,7 +209,8 @@ const PillNav: React.FC<PillNavProps> = ({
document.fonts.ready.then(layout).catch(() => {});
}
if (initialLoadAnimation) {
if (initialLoadAnimation && !hasPlayedIntro.current) {
hasPlayedIntro.current = true;
const logo = logoRef.current;
const navItems = navItemsRef.current;
if (logo) {
@@ -221,7 +224,18 @@ const PillNav: React.FC<PillNavProps> = ({
}
return () => window.removeEventListener("resize", onResize);
}, [items, ease, initialLoadAnimation]);
}, [items, ease, initialLoadAnimation, introTick]);
useEffect(() => {
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted) {
hasPlayedIntro.current = false;
setIntroTick((t) => t + 1);
}
};
window.addEventListener("pageshow", onPageShow);
return () => window.removeEventListener("pageshow", onPageShow);
}, []);
const handleEnter = (i: number) => {
const tl = tlRefs.current[i];
@@ -448,7 +462,7 @@ const PillNav: React.FC<PillNavProps> = ({
onClick={toggleMobileMenu}
aria-label="Toggle menu"
aria-expanded={isMobileMenuOpen}
className="md:hidden rounded-full border-0 flex flex-col items-center justify-center gap-1 cursor-pointer p-0 relative"
className="md:hidden rounded-full border-0 flex flex-col items-center justify-center gap-1 cursor-pointer p-0 relative transition-transform duration-150 active:scale-90"
style={{
width: "var(--nav-h)",
height: "var(--nav-h)",
@@ -474,22 +488,8 @@ const PillNav: React.FC<PillNavProps> = ({
>
<ul className="list-none m-0 flex flex-col gap-2">
{items.map((item) => {
const defaultStyle: React.CSSProperties = {
background: "var(--pill-bg)",
color: "var(--pill-text)",
};
const hoverIn = (e: React.MouseEvent<HTMLAnchorElement>) => {
e.currentTarget.style.background = "var(--color-bg-2)";
e.currentTarget.style.color = "var(--color-heading-accent)";
};
const hoverOut = (e: React.MouseEvent<HTMLAnchorElement>) => {
e.currentTarget.style.background = "var(--pill-bg)";
e.currentTarget.style.color = "var(--pill-text)";
};
const linkClasses =
"block py-4 px-6 text-[16px] font-semibold rounded-b-[20px] transition-all duration-200 uppercase tracking-wide text-center shadow-md";
"mobile-menu-link block py-4 px-6 text-[16px] font-semibold rounded-b-[20px] transition-all duration-200 uppercase tracking-wide text-center shadow-md";
return (
<li key={item.href}>
@@ -497,10 +497,7 @@ const PillNav: React.FC<PillNavProps> = ({
<Link
to={item.href}
className={linkClasses}
style={defaultStyle}
onMouseEnter={hoverIn}
onMouseLeave={hoverOut}
onClick={closeMobileMenu} // On appelle bien notre fonction qui modifie l'état et lance l'animation de fermeture
onClick={closeMobileMenu}
>
{item.label}
</Link>
@@ -508,9 +505,6 @@ const PillNav: React.FC<PillNavProps> = ({
<a
href={item.href}
className={linkClasses}
style={defaultStyle}
onMouseEnter={hoverIn}
onMouseLeave={hoverOut}
onClick={closeMobileMenu}
>
{item.label}
+56
View File
@@ -0,0 +1,56 @@
import { createContext, useContext, useState } from "react";
import type { ReactNode } from "react";
export type ConsentValue = "accepted" | "refused" | null;
const STORAGE_KEY = "cup-cookie-consent";
interface CookieConsentContextValue {
consent: ConsentValue;
accept: () => void;
refuse: () => void;
reset: () => void;
}
const CookieConsentContext = createContext<
CookieConsentContextValue | undefined
>(undefined);
const readStoredConsent = (): ConsentValue => {
if (typeof window === "undefined") return null;
const stored = window.localStorage.getItem(STORAGE_KEY);
return stored === "accepted" || stored === "refused" ? stored : null;
};
export const CookieConsentProvider = ({ children }: { children: ReactNode }) => {
const [consent, setConsent] = useState<ConsentValue>(readStoredConsent);
const persist = (value: Exclude<ConsentValue, null>) => {
window.localStorage.setItem(STORAGE_KEY, value);
setConsent(value);
};
const accept = () => persist("accepted");
const refuse = () => persist("refused");
const reset = () => {
window.localStorage.removeItem(STORAGE_KEY);
setConsent(null);
};
return (
<CookieConsentContext.Provider value={{ consent, accept, refuse, reset }}>
{children}
</CookieConsentContext.Provider>
);
};
// eslint-disable-next-line react-refresh/only-export-components
export const useCookieConsent = () => {
const context = useContext(CookieConsentContext);
if (!context) {
throw new Error(
"useCookieConsent doit être utilisé dans un CookieConsentProvider",
);
}
return context;
};
+21
View File
@@ -18,6 +18,27 @@
text-orientation: mixed;
transform: rotate(180deg);
}
.site-header {
transition: opacity 150ms ease-out;
}
.mobile-menu-link {
background-color: var(--pill-bg);
color: var(--pill-text);
-webkit-tap-highlight-color: transparent;
touch-action: manipulation;
}
.mobile-menu-link:active {
background-color: var(--color-bg-2);
color: var(--color-heading-accent);
transform: scale(0.96);
}
}
.is-transitioning .site-header {
opacity: 0;
}
body {
+13 -1
View File
@@ -1,9 +1,12 @@
import { Outlet, useLocation } from "react-router-dom";
import PillNav from "../components/PillNav";
import CookieBanner from "../components/CookieBanner";
import { useCookieConsent } from "../context/CookieConsent";
import logo from "/logo.png";
export const MainLayout = () => {
const location = useLocation();
const { reset: resetConsent } = useCookieConsent();
const themeColors = {
primary: "#1a247f", // Bleu profond
@@ -15,7 +18,7 @@ export const MainLayout = () => {
return (
<div className="flex flex-col min-h-screen bg-bg-1 font-sans text-site-text">
{/* NAVIGATION */}
<div className="fixed top-0 left-0 w-full z-50 flex justify-center pt-4 md:pt-6 pointer-events-none px-4 md:px-0">
<div className="site-header fixed top-0 left-0 w-full z-50 flex justify-center pt-4 md:pt-6 pointer-events-none px-4 md:px-0">
<div className="pointer-events-auto flex items-center justify-between w-full md:w-auto md:justify-center gap-4 max-w-400">
<PillNav
logo={logo}
@@ -72,6 +75,13 @@ export const MainLayout = () => {
>
Politique de confidentialité
</a>
<button
type="button"
onClick={resetConsent}
className="text-[10px] text-primary/40 hover:text-primary mt-1 transition-colors underline"
>
Gérer les cookies
</button>
</div>
{/* Contact & Réseaux */}
@@ -108,6 +118,8 @@ export const MainLayout = () => {
</div>
</div>
</footer>
<CookieBanner />
</div>
);
};
+28
View File
@@ -0,0 +1,28 @@
const TRANSITION_END_EVENT = "cup:transition-end";
let transitionActive = false;
export const markTransitionStart = () => {
transitionActive = true;
};
export const markTransitionEnd = () => {
if (!transitionActive) return;
transitionActive = false;
window.dispatchEvent(new Event(TRANSITION_END_EVENT));
};
export const runAfterTransition = (callback: () => void): (() => void) => {
if (!transitionActive) {
callback();
return () => {};
}
const handler = () => {
window.removeEventListener(TRANSITION_END_EVENT, handler);
callback();
};
window.addEventListener(TRANSITION_END_EVENT, handler);
return () => window.removeEventListener(TRANSITION_END_EVENT, handler);
};
+4 -1
View File
@@ -3,9 +3,12 @@ import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { CookieConsentProvider } from "./context/CookieConsent";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
<CookieConsentProvider>
<App />
</CookieConsentProvider>
</StrictMode>,
);
+233 -117
View File
@@ -1,4 +1,4 @@
import { useLayoutEffect, useRef, useState, useCallback } from "react";
import { useLayoutEffect, useRef, useState, useCallback, useEffect } from "react";
import AnimatedContent from "../components/AnimatedContent";
import SEO from "../components/SEO";
@@ -29,14 +29,137 @@ interface Category {
history: HistoryItem[];
}
interface YearGroupImage {
item: EventImage;
index: number;
}
interface YearGroup {
year: string;
title: string;
bg: string;
text: string;
images: EventImage[];
images: YearGroupImage[];
}
const isVideo = (src?: string) => !!src && /\.(mp4|webm)$/i.test(src);
// ============================================================================
// SOUS-COMPOSANT : Lightbox plein écran (images + vidéos)
// ============================================================================
const Lightbox = ({
items,
index,
onClose,
onNavigate,
}: {
items: EventImage[];
index: number;
onClose: () => void;
onNavigate: (index: number) => void;
}) => {
const item = items[index];
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
else if (event.key === "ArrowRight")
onNavigate((index + 1) % items.length);
else if (event.key === "ArrowLeft")
onNavigate((index - 1 + items.length) % items.length);
};
window.addEventListener("keydown", onKey);
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = previousOverflow;
};
}, [index, items.length, onClose, onNavigate]);
if (!item) return null;
const previous = () => onNavigate((index - 1 + items.length) % items.length);
const next = () => onNavigate((index + 1) % items.length);
return (
<div
className="fixed inset-0 z-[1500] flex items-center justify-center bg-black/90 p-4 backdrop-blur-sm md:p-10"
onClick={onClose}
role="dialog"
aria-modal="true"
>
<button
type="button"
aria-label="Fermer"
onClick={onClose}
className="absolute right-4 top-4 z-10 flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-2xl text-white transition-colors hover:bg-white/25 md:right-8 md:top-6"
>
×
</button>
{items.length > 1 && (
<>
<button
type="button"
aria-label="Média précédent"
onClick={(event) => {
event.stopPropagation();
previous();
}}
className="absolute left-3 z-10 flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-2xl text-white transition-colors hover:bg-white/25 md:left-8"
>
‹
</button>
<button
type="button"
aria-label="Média suivant"
onClick={(event) => {
event.stopPropagation();
next();
}}
className="absolute right-3 z-10 flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-2xl text-white transition-colors hover:bg-white/25 md:right-8"
>
›
</button>
</>
)}
<figure
className="flex max-h-[88vh] max-w-[92vw] flex-col items-center gap-4"
onClick={(event) => event.stopPropagation()}
>
{isVideo(item.src) ? (
<video
src={item.src}
controls
autoPlay
loop
playsInline
className="max-h-[80vh] max-w-[92vw] rounded-xl shadow-2xl"
/>
) : (
<img
src={item.src}
alt={item.alt}
className="max-h-[80vh] max-w-[92vw] rounded-xl object-contain shadow-2xl"
/>
)}
{(item.imageTitle || item.imageDesc) && (
<figcaption className="max-w-2xl text-center text-white/85">
{item.imageTitle && (
<div className="text-lg font-semibold">{item.imageTitle}</div>
)}
{item.imageDesc && (
<div className="text-sm text-white/70">{item.imageDesc}</div>
)}
</figcaption>
)}
</figure>
</div>
);
};
// ============================================================================
// SOUS-COMPOSANT : Gère l'effet "Scroll Vertical -> Glissement Horizontal"
// ============================================================================
@@ -45,10 +168,16 @@ const CategoryHorizontalScroll = ({ category }: { category: Category }) => {
const trackRef = useRef<HTMLDivElement>(null);
const [progress, setProgress] = useState(0);
const [maxTranslate, setMaxTranslate] = useState(0);
const [trackHeight, setTrackHeight] = useState("100vh");
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
const media = category.history.filter(
(item): item is EventImage => item.type === "image",
);
// 1. On regroupe les images par année
const groupedHistory: YearGroup[] = [];
let currentYear: YearGroup | null = null;
let mediaIndex = 0;
category.history.forEach((item: HistoryItem) => {
if (item.type === "intro") {
@@ -62,171 +191,158 @@ const CategoryHorizontalScroll = ({ category }: { category: Category }) => {
groupedHistory.push(newYearGroup);
currentYear = newYearGroup;
} else if (item.type === "image" && currentYear) {
currentYear.images.push(item);
currentYear.images.push({ item, index: mediaIndex });
mediaIndex += 1;
}
});
// 2. Logique de calcul du scroll
const handleScroll = useCallback(() => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const windowHeight = window.innerHeight;
const maxScroll = rect.height - windowHeight;
const currentScroll = -rect.top;
let p = currentScroll / maxScroll;
p = Math.max(0, Math.min(1, p));
const maxScroll = rect.height - window.innerHeight;
if (maxScroll <= 0) {
setProgress(0);
return;
}
const p = Math.max(0, Math.min(1, -rect.top / maxScroll));
setProgress(p);
}, []);
useLayoutEffect(() => {
const updateMeasurements = () => {
if (trackRef.current) {
const max = trackRef.current.scrollWidth - window.innerWidth + 80;
setMaxTranslate(max > 0 ? max : 0);
}
const track = trackRef.current;
if (!track) return;
const measure = () => {
const max = Math.max(0, track.scrollWidth - window.innerWidth + 80);
setMaxTranslate(max);
setTrackHeight(`${window.innerHeight + max}px`);
};
updateMeasurements();
window.addEventListener("resize", updateMeasurements);
measure();
const observer = new ResizeObserver(measure);
observer.observe(track);
window.addEventListener("resize", measure);
window.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
const raf = requestAnimationFrame(handleScroll);
return () => {
window.removeEventListener("resize", updateMeasurements);
cancelAnimationFrame(raf);
observer.disconnect();
window.removeEventListener("resize", measure);
window.removeEventListener("scroll", handleScroll);
};
}, [handleScroll]);
const containerHeight = `${(groupedHistory.length + 1) * 80}vh`;
return (
<section
ref={containerRef}
style={{ height: containerHeight }}
style={{ height: trackHeight }}
className="relative w-full"
>
<div className="sticky top-0 h-screen w-full flex items-center overflow-hidden bg-bg-1">
<div className="sticky top-0 flex h-screen w-full items-center overflow-hidden bg-bg-1">
<div
ref={trackRef}
className="flex items-center gap-12 md:gap-24 w-max px-6 md:px-20 will-change-transform"
className="flex w-max items-center gap-10 px-6 will-change-transform md:gap-16 md:px-20"
style={{
transform: `translate3d(-${progress * maxTranslate}px, 0, 0)`,
}}
>
<div className="w-[85vw] md:w-[40vw] shrink-0 pl-2">
<div className="w-[78vw] shrink-0 md:w-[32vw]">
<h2
className={`text-5xl md:text-7xl lg:text-8xl font-black tracking-tight mb-6 ${category.themeColor}`}
className={`mb-6 text-4xl font-black tracking-tight md:text-6xl lg:text-7xl ${category.themeColor}`}
>
{category.title}
</h2>
<div className="w-20 h-2 bg-heading-accent rounded-full mb-8"></div>
<p className="text-xl md:text-2xl text-site-text/80 leading-relaxed font-light">
<div className="mb-8 h-2 w-20 rounded-full bg-heading-accent" />
<p className="text-xl font-light leading-relaxed text-site-text/80 md:text-2xl">
{category.description}
</p>
<p className="mt-6 text-xs uppercase tracking-[0.25em] text-site-text/40">
{groupedHistory.length} année
{groupedHistory.length > 1 ? "s" : ""} · {media.length} média
{media.length > 1 ? "s" : ""}
</p>
</div>
{groupedHistory.map((yearGroup, index) => (
{groupedHistory.map((yearGroup) => (
<div
key={index}
className={`w-[85vw] md:w-[65vw] lg:w-[50vw] h-[65vh] md:h-[75vh] shrink-0 rounded-[40px] shadow-2xl flex flex-col p-6 md:p-10 border border-black/5 ${yearGroup.bg} ${yearGroup.text}`}
key={yearGroup.year}
className="flex shrink-0 items-center gap-6 md:gap-10"
>
<div className="mb-6 flex flex-col gap-1">
<h3 className="text-6xl md:text-7xl font-black opacity-90 tracking-tighter">
<div
className={`flex h-[46vh] w-24 shrink-0 flex-col items-center justify-center gap-3 rounded-[28px] border border-black/5 px-2 text-center shadow-lg md:h-[54vh] md:w-32 ${yearGroup.bg} ${yearGroup.text}`}
>
<span className="text-2xl font-black tracking-tighter md:text-3xl">
{yearGroup.year}
</h3>
<p className="text-2xl md:text-3xl font-medium">
{yearGroup.title}
</p>
</span>
{yearGroup.title && (
<span className="text-[10px] font-medium leading-snug md:text-xs">
{yearGroup.title}
</span>
)}
<span className="text-[10px] uppercase tracking-widest opacity-60">
{yearGroup.images.length} média
{yearGroup.images.length > 1 ? "s" : ""}
</span>
</div>
<div className="grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4 flex-1">
{yearGroup.images.map((img, idx) => {
const total = yearGroup.images.length;
let spanClass = "col-span-1 row-span-1";
if (total === 1) {
spanClass = "col-span-2 md:col-span-3 row-span-2";
} else if (total === 2) {
spanClass =
idx === 0
? "col-span-2 md:col-span-2"
: "col-span-2 md:col-span-1";
} else if (total >= 3) {
if (idx === 0) {
spanClass = "col-span-2 row-span-2";
} else {
let mobileSpan = "col-span-1";
let desktopSpan = "md:col-span-1";
if (idx === total - 1) {
if (total % 2 === 0) mobileSpan = "col-span-2";
if ((total - 3) % 3 === 1)
desktopSpan = "md:col-span-3";
if ((total - 3) % 3 === 2)
desktopSpan = "md:col-span-2";
}
spanClass = `${mobileSpan} ${desktopSpan} row-span-1`;
}
}
const isVideo =
img.src?.toLowerCase().endsWith(".mp4") ||
img.src?.toLowerCase().endsWith(".webm");
return (
<div
key={idx}
className={`relative rounded-2xl overflow-hidden bg-black/10 ${spanClass} group`}
>
{isVideo ? (
<div className="flex shrink-0 items-center gap-4 md:gap-6">
{yearGroup.images.map(({ item, index }) => (
<button
key={index}
type="button"
aria-label={item.alt || "Agrandir le média"}
onClick={() => setLightboxIndex(index)}
className="group relative shrink-0 cursor-zoom-in overflow-hidden rounded-2xl shadow-xl"
>
{isVideo(item.src) ? (
<>
<video
src={img.src}
autoPlay
loop
src={item.src}
muted
loop
playsInline
preload="metadata"
className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
className="block h-[46vh] w-auto max-w-[75vw] object-cover transition-transform duration-700 group-hover:scale-105 md:h-[54vh]"
/>
) : img.src ? (
<img
src={img.src}
alt={img.alt}
loading="lazy"
decoding="async"
className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
/>
) : (
<div className="absolute inset-0 flex items-center justify-center text-sm opacity-50 bg-white/10">
Pas de média
</div>
)}
{(img.imageTitle || img.imageDesc) && (
<div className="absolute bottom-0 left-0 w-full p-4 md:p-6 bg-linear-to-t from-black/90 via-black/40 to-transparent">
{img.imageTitle && (
<h4 className="text-white font-bold text-base md:text-lg mb-1 drop-shadow-md">
{img.imageTitle}
</h4>
)}
{img.imageDesc && (
<p className="text-white/90 text-sm md:text-base leading-snug hidden md:block drop-shadow-sm">
{img.imageDesc}
</p>
)}
</div>
)}
</div>
);
})}
<span className="pointer-events-none absolute inset-0 flex items-center justify-center">
<span className="flex h-12 w-12 items-center justify-center rounded-full bg-black/50 text-white">
▶
</span>
</span>
</>
) : (
<img
src={item.src}
alt={item.alt}
loading="lazy"
decoding="async"
className="block h-[46vh] w-auto max-w-[75vw] object-cover transition-transform duration-700 group-hover:scale-105 md:h-[54vh]"
/>
)}
</button>
))}
</div>
</div>
))}
</div>
<div className="absolute bottom-0 left-0 h-1 w-full bg-black/5">
<div
className="h-full bg-heading-accent"
style={{ width: `${progress * 100}%` }}
/>
</div>
</div>
{lightboxIndex !== null && (
<Lightbox
items={media}
index={lightboxIndex}
onClose={() => setLightboxIndex(null)}
onNavigate={setLightboxIndex}
/>
)}
</section>
);
};
@@ -379,7 +495,7 @@ export default function Events() {
type: "intro",
year: "2022",
title: "Notre premier rassemblement",
bg: "bg-[#f7f0e5]",
bg: "bg-white",
text: "text-[#1a247f]",
},
{
@@ -455,7 +571,7 @@ export default function Events() {
type: "intro",
year: "2024",
title: "Un Noël de Solidarité",
bg: "bg-[#f7f0e5]",
bg: "bg-white",
text: "text-[#1a247f]",
},
{
+49 -15
View File
@@ -1,11 +1,7 @@
import AnimatedContent from "../components/AnimatedContent";
const Privacy = () => {
const lastUpdate = new Date().toLocaleDateString("fr-FR", {
year: "numeric",
month: "long",
day: "numeric",
});
const lastUpdate = "19 octobre 2026";
return (
<div className="w-full pt-32 pb-20 bg-bg-1 min-h-screen">
@@ -50,6 +46,7 @@ const Privacy = () => {
<li>Aucun formulaire d'inscription.</li>
<li>Aucun système de commentaire.</li>
<li>Aucune inscription à une newsletter.</li>
<li>Aucun profil de navigation ni mesure d'audience.</li>
</ul>
</section>
</AnimatedContent>
@@ -62,14 +59,16 @@ const Privacy = () => {
<p>
Ce site n'utilise{" "}
<strong>aucun cookie publicitaire ou de traçage</strong> (Google
Analytics, Pixels, etc.). Vous pouvez naviguer en toute
tranquillité sans être suivi.
Analytics, Pixels, etc.). L'actualité de notre page Facebook —
textes et images — est relayée par notre propre serveur et n'est
affichée{" "}
<strong>qu'après votre consentement explicite</strong> via la
bannière prévue à cet effet.
</p>
<p className="mt-2 text-sm text-site-text/70">
<em>
Note : Si cela venait à changer à l'avenir pour des besoins de
statistiques, une bannière de consentement vous en informerait
immédiatement.
Vous pouvez modifier ou retirer votre choix à tout moment via
le lien « Gérer les cookies » en bas de chaque page.
</em>
</p>
</section>
@@ -78,7 +77,7 @@ const Privacy = () => {
<AnimatedContent distance={20} direction="vertical" delay={0.4}>
<section>
<h2 className="text-2xl font-bold text-primary mb-4">
4. Services Tiers
4. Contenus et services tiers
</h2>
<p className="mb-4">
Notre site utilise certaines fonctionnalités externes pour
@@ -87,9 +86,13 @@ const Privacy = () => {
<ul className="list-disc pl-6 space-y-4 marker:text-hover-nav">
<li>
<strong>Facebook / Meta :</strong> Nous affichons les
actualités publiques de notre page Facebook. Aucune donnée
vous concernant n'est envoyée à Facebook tant que vous ne
cliquez pas sur les liens pour visiter la plateforme.
actualités publiques de notre page Facebook. Pour protéger
votre vie privée, les publications et les images ne sont pas
chargées directement depuis les serveurs de Meta : elles
transitent par notre propre serveur. Aucune donnée vous
concernant n'est transmise à Meta tant que vous n'avez pas
accepté, et vous pouvez à tout moment consulter la page via un
lien direct sans charger le contenu intégré.
</li>
<li>
<strong>HelloAsso / Leetchi :</strong> Les boutons de don
@@ -104,7 +107,38 @@ const Privacy = () => {
<AnimatedContent distance={20} direction="vertical" delay={0.5}>
<section>
<h2 className="text-2xl font-bold text-primary mb-4">
5. Contact
5. Hébergement et journaux
</h2>
<p>
Le site est hébergé sur une infrastructure dédiée située dans
l'Union européenne. Comme la plupart des serveurs web, celui-ci
peut enregistrer des données techniques (adresse IP, type de
navigateur, date et heure de connexion) à des fins de sécurité
et de bon fonctionnement. Ces journaux ne sont ni exploités à
des fins commerciales, ni cédés à des tiers.
</p>
</section>
</AnimatedContent>
<AnimatedContent distance={20} direction="vertical" delay={0.6}>
<section>
<h2 className="text-2xl font-bold text-primary mb-4">
6. Vos droits
</h2>
<p>
Conformément au Règlement Général sur la Protection des Données
(RGPD), vous disposez d'un droit d'accès, de rectification,
d'effacement et d'opposition sur les données vous concernant.
Pour exercer ces droits, vous pouvez nous contacter à l'adresse
indiquée ci-dessous.
</p>
</section>
</AnimatedContent>
<AnimatedContent distance={20} direction="vertical" delay={0.7}>
<section>
<h2 className="text-2xl font-bold text-primary mb-4">
7. Contact
</h2>
<p>
Pour toute question concernant cette politique ou l'association,
+39 -7
View File
@@ -1,9 +1,18 @@
import { defineConfig } from "vite";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
// https://vite.dev/config/
export default defineConfig({
plugins: [
export default defineConfig(({ mode }) => {
// Charge TOUTES les variables d'env (y compris sans préfixe VITE_).
// Le token Facebook n'est jamais exposé au navigateur : il est injecté ici,
// côté serveur de développement uniquement.
const env = loadEnv(mode, process.cwd(), "");
const fbToken =
env.FACEBOOK_ACCESS_TOKEN || env.VITE_FACEBOOK_ACCESS_TOKEN || "";
const fbPageId = env.FACEBOOK_PAGE_ID || env.VITE_FACEBOOK_PAGE_ID || "";
return {
plugins: [
react(),
// Middleware personnalisé pour le proxy d'images (plus robuste que server.proxy)
{
@@ -11,9 +20,15 @@ export default defineConfig({
configureServer(server) {
server.middlewares.use("/api/proxy-image", async (req, res) => {
try {
// req.url contient uniquement la partie après /api/proxy-image (ex: /?url=...)
const urlObj = new URL(req.url || "", `http://${req.headers.host}`);
const targetUrl = urlObj.searchParams.get("url");
// req.url contient uniquement la partie après /api/proxy-image,
// l'URL cible y est encodée (ex: /https%3A%2F%2Fscontent...).
const raw = (req.url || "").replace(/^\//, "");
const targetUrl = decodeURIComponent(raw);
const allowed =
/^https?:\/\/[a-z0-9.-]+\.(fbcdn\.net|fbsbx\.com|facebook\.com)([/?]|$)/i.test(
targetUrl,
);
if (!targetUrl) {
res.statusCode = 400;
@@ -21,6 +36,12 @@ export default defineConfig({
return;
}
if (!allowed) {
res.statusCode = 403;
res.end("Forbidden");
return;
}
// On récupère l'image avec un User-Agent "normal" pour éviter les blocages 403/404
const response = await fetch(targetUrl, {
headers: {
@@ -57,8 +78,19 @@ export default defineConfig({
"/api/facebook": {
target: "https://graph.facebook.com/v19.0",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api\/facebook/, ""),
rewrite: (path) => {
// path (front) : /api/facebook/posts?fields=...
// cible : https://graph.facebook.com/v19.0/<pageId>/posts?...&access_token=...
const clean = path.replace(/^\/api\/facebook/, "");
let out = fbPageId ? `/${fbPageId}${clean}` : clean;
if (fbToken) {
const sep = out.includes("?") ? "&" : "?";
out += `${sep}access_token=${fbToken}`;
}
return out;
},
},
},
},
};
});