ajout d'un decompte jusqu'a la date de l'evennement
This commit is contained in:
@@ -0,0 +1,175 @@
|
|||||||
|
/**
|
||||||
|
* Décompte jusqu'à la prochaine édition, affiché à côté du titre sur toutes les pages.
|
||||||
|
* La date est enregistrée sur le serveur : tout le monde voit le même décompte, en direct.
|
||||||
|
*
|
||||||
|
* - pas de date (ou date dépassée) : « date à définir pour la prochaine édition des saucissons Murats »
|
||||||
|
* - le jour même : « C'est le jour J ! »
|
||||||
|
* - avant : « Prochaine édition : dans 2 mois et 12 jours »
|
||||||
|
*/
|
||||||
|
(() => {
|
||||||
|
const PLACEHOLDER = "date à définir pour la prochaine édition des saucissons Murats";
|
||||||
|
|
||||||
|
// ---------- Calcul du décompte (jours calendaires, sans heure ni fuseau) ----------
|
||||||
|
|
||||||
|
// Ajoute n mois à une date en ramenant le jour au dernier jour du mois si besoin (31 janvier + 1 mois = 28 février)
|
||||||
|
function ajouterMois(annee, mois, jour, n) {
|
||||||
|
const total = annee * 12 + mois + n;
|
||||||
|
const a = Math.floor(total / 12);
|
||||||
|
const m = total % 12;
|
||||||
|
const dernierJour = new Date(Date.UTC(a, m + 1, 0)).getUTCDate();
|
||||||
|
return Date.UTC(a, m, Math.min(jour, dernierJour));
|
||||||
|
}
|
||||||
|
|
||||||
|
function etatEdition(dateIso, maintenant) {
|
||||||
|
if (typeof dateIso !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(dateIso)) {
|
||||||
|
return { type: "vide", texte: PLACEHOLDER };
|
||||||
|
}
|
||||||
|
|
||||||
|
const [a, m, j] = dateIso.split("-").map(Number);
|
||||||
|
const cible = Date.UTC(a, m - 1, j);
|
||||||
|
const aA = maintenant.getFullYear();
|
||||||
|
const mA = maintenant.getMonth();
|
||||||
|
const jA = maintenant.getDate();
|
||||||
|
const aujourdhui = Date.UTC(aA, mA, jA);
|
||||||
|
|
||||||
|
if (cible < aujourdhui) return { type: "vide", texte: PLACEHOLDER }; // date dépassée
|
||||||
|
if (cible === aujourdhui) return { type: "jour", texte: "C'est le jour J !" };
|
||||||
|
|
||||||
|
// Nombre de mois entiers, puis jours restants
|
||||||
|
let mois = (a - aA) * 12 + (m - 1 - mA);
|
||||||
|
if (ajouterMois(aA, mA, jA, mois) > cible) mois--;
|
||||||
|
const jours = Math.round((cible - ajouterMois(aA, mA, jA, mois)) / 86400000);
|
||||||
|
|
||||||
|
const morceaux = [];
|
||||||
|
if (mois > 0) morceaux.push(`${mois} mois`);
|
||||||
|
if (jours > 0) morceaux.push(`${jours} jour${jours > 1 ? "s" : ""}`);
|
||||||
|
return { type: "compte", texte: "dans " + morceaux.join(" et ") };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pour les tests en ligne de commande
|
||||||
|
if (typeof module !== "undefined" && module.exports) module.exports = { etatEdition, PLACEHOLDER };
|
||||||
|
|
||||||
|
// ---------- Affichage à côté du titre ----------
|
||||||
|
function demarrer() {
|
||||||
|
const titre = document.querySelector(".topbar h1");
|
||||||
|
if (!titre) return;
|
||||||
|
|
||||||
|
// La puce entière est cliquable : un vrai champ date, invisible, la recouvre (le sélecteur natif s'ouvre au toucher)
|
||||||
|
const puce = document.createElement("label");
|
||||||
|
puce.className = "edition";
|
||||||
|
puce.hidden = true; // cachée jusqu'à la réponse du serveur : pas de faux « date à définir » au chargement
|
||||||
|
|
||||||
|
const etiquette = document.createElement("span");
|
||||||
|
etiquette.className = "edition-label";
|
||||||
|
etiquette.textContent = "Prochaine édition :";
|
||||||
|
|
||||||
|
const texte = document.createElement("span");
|
||||||
|
texte.className = "edition-texte";
|
||||||
|
texte.setAttribute("aria-live", "polite");
|
||||||
|
|
||||||
|
const champ = document.createElement("input");
|
||||||
|
champ.type = "date";
|
||||||
|
champ.setAttribute("aria-label", "Date de la prochaine édition des saucissons Murats");
|
||||||
|
|
||||||
|
const effacer = document.createElement("button");
|
||||||
|
effacer.type = "button";
|
||||||
|
effacer.className = "edition-clear";
|
||||||
|
effacer.textContent = "✕";
|
||||||
|
effacer.title = "Effacer la date";
|
||||||
|
effacer.setAttribute("aria-label", "Effacer la date");
|
||||||
|
|
||||||
|
puce.append(etiquette, texte, champ, effacer);
|
||||||
|
titre.after(puce);
|
||||||
|
|
||||||
|
let date = null; // date affichée (AAAA-MM-JJ ou null)
|
||||||
|
let connue = null; // dernière date confirmée par le serveur
|
||||||
|
let message = null; // message d'erreur temporaire
|
||||||
|
|
||||||
|
function afficher() {
|
||||||
|
const info = etatEdition(date, new Date());
|
||||||
|
puce.dataset.etat = info.type;
|
||||||
|
etiquette.hidden = info.type !== "compte" || !!message;
|
||||||
|
texte.textContent = message || info.texte;
|
||||||
|
effacer.hidden = info.type === "vide";
|
||||||
|
champ.value = date || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function charger() {
|
||||||
|
try {
|
||||||
|
const reponse = await fetch("/api/edition", { cache: "no-store" });
|
||||||
|
if (reponse.ok) {
|
||||||
|
connue = date = (await reponse.json()).date;
|
||||||
|
message = null; // une donnée fraîche du serveur remplace un éventuel message d'erreur
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* hors ligne : on garde ce qu'on a */
|
||||||
|
}
|
||||||
|
puce.hidden = false;
|
||||||
|
afficher();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enregistrer(nouvelle) {
|
||||||
|
date = nouvelle;
|
||||||
|
afficher();
|
||||||
|
try {
|
||||||
|
const reponse = await fetch("/api/edition", {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ date: nouvelle }),
|
||||||
|
});
|
||||||
|
if (!reponse.ok) throw new Error("HTTP " + reponse.status);
|
||||||
|
connue = nouvelle;
|
||||||
|
} catch {
|
||||||
|
date = connue; // on revient à la date réellement enregistrée
|
||||||
|
message = "Enregistrement impossible, réessaie.";
|
||||||
|
afficher();
|
||||||
|
setTimeout(() => {
|
||||||
|
message = null;
|
||||||
|
afficher();
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Changement fait par quelqu'un d'autre : mise à jour en direct
|
||||||
|
function ecouter() {
|
||||||
|
if (typeof EventSource === "undefined") return;
|
||||||
|
const flux = new EventSource("/api/edition/events");
|
||||||
|
flux.onmessage = (e) => {
|
||||||
|
try {
|
||||||
|
connue = date = JSON.parse(e.data).date;
|
||||||
|
message = null;
|
||||||
|
puce.hidden = false;
|
||||||
|
afficher();
|
||||||
|
} catch {
|
||||||
|
/* message illisible : on ignore */
|
||||||
|
}
|
||||||
|
};
|
||||||
|
flux.onerror = () => {
|
||||||
|
if (flux.readyState === EventSource.CLOSED) setTimeout(ecouter, 3000);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
champ.addEventListener("change", () => enregistrer(champ.value || null));
|
||||||
|
champ.addEventListener("click", () => {
|
||||||
|
try {
|
||||||
|
champ.showPicker(); // ordinateur : ouvre le calendrier au clic
|
||||||
|
} catch {
|
||||||
|
/* déjà ouvert, ou non supporté : le navigateur gère */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
effacer.addEventListener("click", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
enregistrer(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
setInterval(afficher, 60 * 1000); // le décompte passe à minuit tout seul
|
||||||
|
document.addEventListener("visibilitychange", () => {
|
||||||
|
if (document.visibilityState === "visible") charger(); // retour sur l'onglet : on se remet à jour
|
||||||
|
});
|
||||||
|
|
||||||
|
charger();
|
||||||
|
ecouter();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof document !== "undefined") demarrer();
|
||||||
|
})();
|
||||||
+62
-4
@@ -54,15 +54,21 @@ body {
|
|||||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.18);
|
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.18);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Ligne du titre : titre à gauche, récapitulatif / statut à droite, puce de date en dessous (téléphone) ou à côté du titre (écran large) */
|
||||||
.topbar-row {
|
.topbar-row {
|
||||||
display: flex;
|
display: grid;
|
||||||
|
grid-template-columns: 1fr auto;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
column-gap: 12px;
|
||||||
gap: 12px;
|
row-gap: 6px;
|
||||||
min-height: 40px;
|
|
||||||
}
|
}
|
||||||
|
.topbar-row > h1 { grid-column: 1; grid-row: 1; }
|
||||||
|
.topbar-row > :not(h1):not(.edition) { grid-column: 2; grid-row: 1; }
|
||||||
|
|
||||||
.topbar h1 {
|
.topbar h1 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 40px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-family: Georgia, "Times New Roman", serif;
|
font-family: Georgia, "Times New Roman", serif;
|
||||||
font-size: 1.15rem;
|
font-size: 1.15rem;
|
||||||
@@ -92,6 +98,58 @@ body {
|
|||||||
.menu a { flex: 0 0 auto; padding: 0 22px; }
|
.menu a { flex: 0 0 auto; padding: 0 22px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Décompte de la prochaine édition (créé par assets/edition.js) */
|
||||||
|
.edition {
|
||||||
|
position: relative;
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
grid-row: 2;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 2px 6px;
|
||||||
|
min-height: 36px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
padding: 5px 40px 5px 12px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.35);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(255, 255, 255, 0.14);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
line-height: 1.25;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.edition-label { opacity: 0.8; }
|
||||||
|
.edition-texte { font-weight: 700; }
|
||||||
|
.edition[data-etat="vide"] .edition-texte { font-weight: 400; font-style: italic; opacity: 0.9; }
|
||||||
|
.edition[data-etat="jour"] { background: #fff; border-color: #fff; color: var(--accent); }
|
||||||
|
.edition[data-etat="jour"] .edition-texte { font-size: 1.05rem; }
|
||||||
|
.edition:focus-within { box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.5); }
|
||||||
|
|
||||||
|
/* Le vrai champ date recouvre la puce, invisible : on touche la puce, le calendrier s'ouvre */
|
||||||
|
.edition input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; padding: 0; border: 0; opacity: 0; cursor: pointer; }
|
||||||
|
.edition-clear {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 2;
|
||||||
|
right: 2px;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.edition-clear:active { background: rgba(0, 0, 0, 0.12); }
|
||||||
|
|
||||||
|
@media (min-width: 600px) {
|
||||||
|
.topbar-row { grid-template-columns: auto 1fr auto; }
|
||||||
|
.topbar-row > :not(h1):not(.edition) { grid-column: 3; }
|
||||||
|
.edition { grid-column: 2; grid-row: 1; justify-self: start; margin-bottom: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/* ---------- 3. Composants communs ---------- */
|
/* ---------- 3. Composants communs ---------- */
|
||||||
.card {
|
.card {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<meta name="theme-color" content="#8c2f2f" />
|
<meta name="theme-color" content="#8c2f2f" />
|
||||||
<title>Calculateur d'épices</title>
|
<title>Calculateur d'épices</title>
|
||||||
<link rel="stylesheet" href="assets/style.css" />
|
<link rel="stylesheet" href="assets/style.css" />
|
||||||
|
<script src="assets/edition.js" defer></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<meta name="theme-color" content="#8c2f2f" />
|
<meta name="theme-color" content="#8c2f2f" />
|
||||||
<title>To-do – Calcul des épices</title>
|
<title>To-do – Calcul des épices</title>
|
||||||
<link rel="stylesheet" href="assets/style.css" />
|
<link rel="stylesheet" href="assets/style.css" />
|
||||||
|
<script src="assets/edition.js" defer></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
|
|||||||
@@ -47,17 +47,64 @@ function sauvegarder() {
|
|||||||
fs.renameSync(tmp, DATA_FILE); // écriture atomique
|
fs.renameSync(tmp, DATA_FILE); // écriture atomique
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- Date de la prochaine édition (partagée par tout le monde) ----------
|
||||||
|
const CONFIG_FILE = process.env.CONFIG_FILE || path.join(path.dirname(DATA_FILE), "config.json");
|
||||||
|
|
||||||
|
function dateValide(valeur) {
|
||||||
|
if (typeof valeur !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(valeur)) return false;
|
||||||
|
const d = new Date(valeur + "T00:00:00Z");
|
||||||
|
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === valeur; // refuse le 31 février, etc.
|
||||||
|
}
|
||||||
|
|
||||||
|
function chargerEdition() {
|
||||||
|
try {
|
||||||
|
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
|
||||||
|
return { date: dateValide(config.date) ? config.date : null };
|
||||||
|
} catch {
|
||||||
|
return { date: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let edition = chargerEdition();
|
||||||
|
|
||||||
|
function sauvegarderEdition() {
|
||||||
|
fs.mkdirSync(path.dirname(CONFIG_FILE), { recursive: true });
|
||||||
|
const tmp = CONFIG_FILE + ".tmp";
|
||||||
|
fs.writeFileSync(tmp, JSON.stringify(edition));
|
||||||
|
fs.renameSync(tmp, CONFIG_FILE);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- Temps réel (Server-Sent Events) ----------
|
// ---------- Temps réel (Server-Sent Events) ----------
|
||||||
const clients = new Set();
|
const clients = new Set(); // flux de la to-do list
|
||||||
|
const clientsEdition = new Set(); // flux de la date de l'édition
|
||||||
|
|
||||||
function diffuser() {
|
function diffuser() {
|
||||||
const message = `data: ${JSON.stringify(todos)}\n\n`;
|
const message = `data: ${JSON.stringify(todos)}\n\n`;
|
||||||
for (const res of clients) res.write(message);
|
for (const res of clients) res.write(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function diffuserEdition() {
|
||||||
|
const message = `data: ${JSON.stringify(edition)}\n\n`;
|
||||||
|
for (const res of clientsEdition) res.write(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ouvrirFlux(req, res, ensemble, donnees) {
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": "text/event-stream",
|
||||||
|
"Cache-Control": "no-cache, no-transform",
|
||||||
|
Connection: "keep-alive",
|
||||||
|
"X-Accel-Buffering": "no",
|
||||||
|
});
|
||||||
|
res.write("retry: 3000\n\n");
|
||||||
|
res.write(`data: ${JSON.stringify(donnees)}\n\n`);
|
||||||
|
ensemble.add(res);
|
||||||
|
req.on("close", () => ensemble.delete(res));
|
||||||
|
}
|
||||||
|
|
||||||
// Un signe de vie régulier empêche les proxys de couper la connexion
|
// Un signe de vie régulier empêche les proxys de couper la connexion
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
for (const res of clients) res.write(": ping\n\n");
|
for (const res of clients) res.write(": ping\n\n");
|
||||||
|
for (const res of clientsEdition) res.write(": ping\n\n");
|
||||||
}, 25000);
|
}, 25000);
|
||||||
|
|
||||||
// ---------- Utilitaires HTTP ----------
|
// ---------- Utilitaires HTTP ----------
|
||||||
@@ -97,17 +144,23 @@ async function api(req, res, url) {
|
|||||||
const [, ressource, id, action] = url.pathname.split("/").filter(Boolean); // /api/<ressource>/<id>/<action>
|
const [, ressource, id, action] = url.pathname.split("/").filter(Boolean); // /api/<ressource>/<id>/<action>
|
||||||
|
|
||||||
if (ressource === "events" && req.method === "GET") {
|
if (ressource === "events" && req.method === "GET") {
|
||||||
res.writeHead(200, {
|
return ouvrirFlux(req, res, clients, todos);
|
||||||
"Content-Type": "text/event-stream",
|
}
|
||||||
"Cache-Control": "no-cache, no-transform",
|
|
||||||
Connection: "keep-alive",
|
// Date de la prochaine édition : GET / PUT { date: "AAAA-MM-JJ" | null } / flux /api/edition/events
|
||||||
"X-Accel-Buffering": "no",
|
if (ressource === "edition") {
|
||||||
});
|
if (id === "events" && req.method === "GET") return ouvrirFlux(req, res, clientsEdition, edition);
|
||||||
res.write("retry: 3000\n\n");
|
if (!id && req.method === "GET") return envoyerJson(res, 200, edition);
|
||||||
res.write(`data: ${JSON.stringify(todos)}\n\n`);
|
if (!id && req.method === "PUT") {
|
||||||
clients.add(res);
|
const corps = await lireJson(req);
|
||||||
req.on("close", () => clients.delete(res));
|
if (corps.date === null || corps.date === "") edition = { date: null };
|
||||||
return;
|
else if (dateValide(corps.date)) edition = { date: corps.date };
|
||||||
|
else return envoyerJson(res, 400, { erreur: "Date invalide (format AAAA-MM-JJ)" });
|
||||||
|
sauvegarderEdition();
|
||||||
|
diffuserEdition();
|
||||||
|
return envoyerJson(res, 200, edition);
|
||||||
|
}
|
||||||
|
return envoyerJson(res, 405, { erreur: "Méthode non autorisée" });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ressource !== "todos") return envoyerJson(res, 404, { erreur: "Introuvable" });
|
if (ressource !== "todos") return envoyerJson(res, 404, { erreur: "Introuvable" });
|
||||||
|
|||||||
Reference in New Issue
Block a user