Files
photobooth-qr/src/galerie/gallery.js
T

296 lines
10 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Écran galerie invité — photobooth-qr
//
// Contrat backend : GET {SUPABASE_URL}/functions/v1/public-gallery?slug=<slug>
// (Edge Function publique, aucun token requis — cf. docs/decisions.md
// 2026-09-18 : les invités voient désormais toutes les photos de
// l'événement, même modèle de confiance que l'upload : le slug n'est pas
// un secret, il circule via QR code).
//
// Rafraîchissement par sondage (polling), pas de Supabase Realtime : le
// schéma photobooth est volontairement jamais exposé et Realtime respecte
// les policies RLS (aucune pour anon), l'activer aurait demandé de rouvrir
// ce verrou pour un gain marginal sur un usage V1 (événements de taille
// raisonnable). Compromis assumé : chaque poll régénère des URLs signées
// pour toutes les photos, pour tous les invités qui ont la page ouverte —
// acceptable pour un mariage, à revisiter si le produit vise un jour des
// événements à très fort trafic simultané.
const POLL_INTERVAL_MS = 25_000;
// Les URLs signées durent 10 min (GALLERY_SIGNED_URL_TTL_SECONDS dans
// public-gallery) : marge de 2 min pour qu'une image lazy démarre son
// chargement avant expiration.
const URL_REFRESH_AFTER_MS = 8 * 60_000;
const eventNameEl = document.getElementById("event-name");
const eventMetaEl = document.getElementById("event-meta");
const loadingBlock = document.getElementById("status-loading");
const errorBlock = document.getElementById("status-error");
const errorMessageEl = document.getElementById("status-error-message");
const retryBtn = document.getElementById("retry-btn");
const emptyStateEl = document.getElementById("empty-state");
const gridEl = document.getElementById("polaroid-grid");
const ERROR_MESSAGES = {
"config-missing":
"Cette page n'est pas configurée correctement. Préviens l'organisateur de l'événement.",
"event-not-found":
"Cet événement n'existe pas, ou le lien utilisé est incorrect. Vérifie le QR code ou le lien.",
network:
"La connexion a été coupée. Vérifie ta connexion internet et réessaie.",
"server-overloaded":
"Le service est momentanément surchargé. Réessaie dans quelques minutes.",
unknown: "Une erreur inattendue est survenue. Réessaie, ou reviens un peu plus tard.",
};
function appError(code, cause) {
const err = new Error(code);
err.code = code;
err.cause = cause;
return err;
}
function getConfig() {
const cfg = window.__PHOTOBOOTH_CONFIG__;
if (!cfg || !cfg.SUPABASE_URL || !cfg.SUPABASE_ANON_KEY) {
throw appError("config-missing");
}
return cfg;
}
function getSlugFromPath() {
const match = window.location.pathname.match(/\/galerie\/([^/]+)\/?$/);
return match ? decodeURIComponent(match[1]) : null;
}
// Rotation aléatoire -4°/+4° (skill photobooth-da), figée par photo (Map
// id -> degré) pour que la grille ne "tremble" pas à chaque poll — seules
// les photos réellement nouvelles reçoivent une rotation fraîche.
const rotationById = new Map();
function rotationFor(id) {
if (!rotationById.has(id)) {
rotationById.set(id, (Math.random() * 8 - 4).toFixed(2));
}
return rotationById.get(id);
}
const renderedIds = new Set();
function buildCaption(photo) {
const parts = [];
if (photo.nom_invite) parts.push(photo.nom_invite);
if (photo.message) parts.push(photo.message);
return parts;
}
function setPhotoSrc(img, url) {
img.src = url;
img.dataset.signedAt = String(Date.now());
}
// Miniature (thumb_url) par défaut ; original si pas de miniature (photo
// d'avant les miniatures) ou si elle échoue à charger (repli unique, cf.
// onerror dans renderPolaroid).
function showPhoto(img, photo) {
img.dataset.original = photo.signed_url || "";
if (!photo.thumb_url) img.dataset.fallback = "1";
const url = img.dataset.fallback ? photo.signed_url : photo.thumb_url;
if (url) setPhotoSrc(img, url);
}
// Un nouveau src = nouveau token = nouveau téléchargement complet : on ne
// le change que si l'image n'est pas déjà affichée.
function needsFreshUrl(img, now) {
if (img.complete && img.naturalWidth > 0) return false; // chargée : le navigateur garde l'image
if (img.complete) return true; // pas de src, ou chargement en échec (URL expirée, réseau)
return now - Number(img.dataset.signedAt) > URL_REFRESH_AFTER_MS; // lazy pas encore chargée
}
function renderPolaroid(photo, { animate = false } = {}) {
const li = document.createElement("li");
li.className = "polaroid" + (animate ? " polaroid--dropping" : "");
li.style.setProperty("--rot", `${rotationFor(photo.id)}deg`);
li.dataset.photoId = photo.id;
const img = document.createElement("img");
img.className = "polaroid__photo";
img.onerror = () => {
if (img.dataset.fallback || !img.dataset.original) return;
console.warn(`[galerie] miniature indisponible pour ${photo.id}, repli sur l'original`);
img.dataset.fallback = "1";
setPhotoSrc(img, img.dataset.original);
};
showPhoto(img, photo);
img.alt = photo.nom_invite
? `Photo envoyée par ${photo.nom_invite}`
: "Photo envoyée par un invité";
img.loading = "lazy";
const captionParts = buildCaption(photo);
const caption = document.createElement("p");
caption.className = "polaroid__caption";
if (captionParts.length === 0) {
// Sans prénom ni mot : l'heure d'envoi (« 22 h 14 »), en heure de Paris.
caption.classList.add("polaroid__caption--empty");
const sentAt = new Date(photo.uploaded_at);
if (!Number.isNaN(sentAt.getTime())) {
caption.textContent = new Intl.DateTimeFormat("fr-FR", {
hour: "numeric",
minute: "2-digit",
timeZone: "Europe/Paris",
})
.format(sentAt)
.replace(":", " h ");
}
} else {
caption.textContent = captionParts.join(" — ");
}
li.append(img, caption);
return li;
}
function showLoading() {
loadingBlock.hidden = false;
errorBlock.hidden = true;
emptyStateEl.hidden = true;
gridEl.hidden = true;
}
function showError(rawErr, retryAction) {
const err = rawErr && rawErr.code ? rawErr : appError("unknown", rawErr);
loadingBlock.hidden = true;
errorBlock.hidden = false;
errorMessageEl.textContent = ERROR_MESSAGES[err.code] || ERROR_MESSAGES.unknown;
retryBtn.hidden = !retryAction;
retryBtn.onclick = retryAction || null;
if (err.cause) console.error(`[galerie:${err.code}]`, err.cause);
}
async function fetchGallery(slug) {
const { SUPABASE_URL, SUPABASE_ANON_KEY } = getConfig();
let res;
try {
res = await fetch(
`${SUPABASE_URL}/functions/v1/public-gallery?slug=${encodeURIComponent(slug)}`,
{
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
},
}
);
} catch (err) {
throw appError("network", err);
}
if (res.status === 404) throw appError("event-not-found");
if (res.status >= 500) throw appError("server-overloaded");
if (!res.ok) throw appError("unknown", await res.text().catch(() => null));
return res.json();
}
function formatEventMeta(event) {
const date = new Date(event.date_evenement);
const dateLabel = Number.isNaN(date.getTime())
? null
: date.toLocaleDateString("fr-FR", { day: "numeric", month: "long", year: "numeric" });
const parts = [];
if (dateLabel) parts.push(dateLabel);
parts.push(`${event.photo_count} photo${event.photo_count > 1 ? "s" : ""}`);
return parts.join(" · ");
}
function renderGallery(data) {
eventNameEl.textContent = data.event.nom || "Galerie de l'événement";
eventMetaEl.textContent = formatEventMeta(data.event);
loadingBlock.hidden = true;
errorBlock.hidden = true;
if (data.photos.length === 0) {
emptyStateEl.hidden = false;
gridEl.hidden = true;
return;
}
emptyStateEl.hidden = true;
gridEl.hidden = false;
// Plus récent en premier. On ne reconstruit pas tout le DOM à chaque
// poll (perdrait l'état d'animation/scroll) : seules les photos dont
// l'id n'a jamais été vu sont insérées, avec l'effet "chute".
const photosDesc = [...data.photos].reverse();
const incomingIds = new Set(photosDesc.map((p) => p.id));
// Retire les photos qui auraient disparu côté serveur (rare : édition
// manuelle en base, ou event modifié) pour rester cohérent.
[...gridEl.children].forEach((li) => {
if (!incomingIds.has(li.dataset.photoId)) {
li.remove();
renderedIds.delete(li.dataset.photoId);
}
});
photosDesc.forEach((photo, index) => {
if (renderedIds.has(photo.id)) {
// Déjà rendue : URL fraîche seulement si l'image n'est pas affichée
// (sinon chaque poll retéléchargerait toute la galerie).
const existing = gridEl.querySelector(`[data-photo-id="${photo.id}"] .polaroid__photo`);
if (existing && photo.signed_url && needsFreshUrl(existing, Date.now())) {
showPhoto(existing, photo);
} else if (existing) {
existing.dataset.original = photo.signed_url || ""; // repli éventuel avec un jeton frais
}
return;
}
const card = renderPolaroid(photo, { animate: true });
if (index === 0) {
gridEl.prepend(card);
} else {
const prevSibling = gridEl.children[index - 1];
prevSibling ? prevSibling.after(card) : gridEl.appendChild(card);
}
renderedIds.add(photo.id);
});
}
let pollTimer = null;
async function loadOnce({ showSpinner } = { showSpinner: false }) {
const slug = getSlugFromPath();
if (!slug) {
showError(appError("event-not-found"));
return;
}
if (showSpinner) showLoading();
try {
const data = await fetchGallery(slug);
renderGallery(data);
} catch (err) {
showError(err, () => loadOnce({ showSpinner: true }));
}
}
function startPolling() {
if (pollTimer) return;
pollTimer = setInterval(() => loadOnce({ showSpinner: false }), POLL_INTERVAL_MS);
}
// Pas de sondage pendant que l'onglet est masqué (économie réseau/batterie,
// cohérent avec l'esprit sobriété du projet) ; on refait un chargement
// immédiat au retour au premier plan pour ne pas attendre un cycle entier.
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
} else {
loadOnce({ showSpinner: false });
startPolling();
}
});
loadOnce({ showSpinner: true }).then(startPolling);