From baa25612e967739a9b348205c2aa871d6b72c945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20Gastinel?= <264859180+gastinelt@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:23:21 +0100 Subject: [PATCH] News et newsletter : page /news/ (5 langues), bouton News, reglages (theme clair par defaut, sombre au choix), formulaire newsletter Repris des copies site-principal-news et site-principal-reglages. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + CONSIGNES-AGENTS.md | 7 + data/actus.json | 110 +++++++++ index.html | 20 +- modification-news.diff | 543 +++++++++++++++++++++++++++++++++++++++++ news/actus.js | 365 +++++++++++++++++++++++++++ news/de/index.html | 89 +++++++ news/en/index.html | 89 +++++++ news/es/index.html | 89 +++++++ news/index.html | 89 +++++++ news/it/index.html | 89 +++++++ news/newsletter.js | 182 ++++++++++++++ news/reglages.js | 451 ++++++++++++++++++++++++++++++++++ tools/add-news.js | 137 +++++++++++ tools/build.js | 5 +- 15 files changed, 2264 insertions(+), 3 deletions(-) create mode 100644 CONSIGNES-AGENTS.md create mode 100644 data/actus.json create mode 100644 modification-news.diff create mode 100644 news/actus.js create mode 100644 news/de/index.html create mode 100644 news/en/index.html create mode 100644 news/es/index.html create mode 100644 news/index.html create mode 100644 news/it/index.html create mode 100644 news/newsletter.js create mode 100644 news/reglages.js create mode 100644 tools/add-news.js diff --git a/.gitignore b/.gitignore index 6babfc7..7e71462 100644 --- a/.gitignore +++ b/.gitignore @@ -64,3 +64,5 @@ id_ed25519* *.mkv *.wav *.flac +*.bak +node_modules diff --git a/CONSIGNES-AGENTS.md b/CONSIGNES-AGENTS.md new file mode 100644 index 0000000..ab00fae --- /dev/null +++ b/CONSIGNES-AGENTS.md @@ -0,0 +1,7 @@ +# Consignes pour les agents (règle de Théo) +- Accueil, Portfolio, Réalisations et « L'envers du décor » : contenu d'origine uniquement. Aucun widget, lien, bloc ou entrée News sans accord explicite de Théo. +- Le « Carnet de bord » (#news, `data/news.json`, `tools/admin-news.js`) ne contient QUE des sorties audiovisuelles : ne pas le modifier ni le mélanger. +- Le nouveau flux News utilise `data/actus.json`, `news/actus.js`, `tools/add-news.js`, classes/id `actus-*` : jamais `news-*`. +- Emplacement du widget : en attente de la réponse de Théo. Ne le placer nulle part d'ici là. +- Pas de déploiement, pas de push, pas d'accès VPS/Hub sans demande de Théo. +- Bouton Paramètres (`news/reglages.js`, fixe en bas à droite, ajouté en fin de body) : il reste hors des quatre onglets. Ne pas y ajouter de contenu des onglets gardés. Connexion Hub et abonnement mail : pas encore codés. diff --git a/data/actus.json b/data/actus.json new file mode 100644 index 0000000..313f48f --- /dev/null +++ b/data/actus.json @@ -0,0 +1,110 @@ +[ + { + "id": 1, + "date": "2026-10-26", + "themes": [ + "site" + ], + "short": { + "title": "Nouvelle version du site", + "text": "Le site est maintenant disponible en plusieurs langues, et une page News arrive." + }, + "levels": { + "simple": { + "title": "Le site change", + "text": "Le site existe maintenant en anglais, allemand, italien et espagnol. Les nouveautés sont réunies ici, sur la page News." + }, + "normal": { + "title": "Nouvelle version du site : langues et page News", + "text": "Le site est maintenant disponible en français, anglais, allemand, italien et espagnol. Une page News réunit désormais les nouveautés. Les paramètres d’accessibilité sont en bas de chaque page." + }, + "developpeur": { + "title": "Nouvelle version du site : traductions et flux News", + "text": "Ajout de quatre traductions (en, de, it, es) avec hreflang, et d’une page News qui lit un flux JSON statique filtrable par niveau de détail et par thème. Les réglages restent dans le navigateur (localStorage) ; seul le thème est aussi gardé dans un cookie de préférence, 13 mois au plus." + } + }, + "link": "/news/", + "i18n": { + "en": { + "short": { + "title": "New version of the site", + "text": "The site is now available in several languages, and a News page is here." + }, + "levels": { + "simple": { + "title": "The site is changing", + "text": "The site now exists in English, German, Italian and Spanish. All the news is gathered here, on the News page." + }, + "normal": { + "title": "New version of the site: languages and News page", + "text": "The site is now available in French, English, German, Italian and Spanish. A News page now gathers all the updates. Accessibility settings are at the bottom of every page." + }, + "developpeur": { + "title": "New version of the site: translations and News feed", + "text": "Four translations added (en, de, it, es) with hreflang, plus a News page that reads a static JSON feed filtered by level of detail and topic. Settings stay in the browser (localStorage); only the theme is also kept in a preference cookie, for 13 months at most." + } + } + }, + "de": { + "short": { + "title": "Neue Version der Website", + "text": "Die Website gibt es jetzt in mehreren Sprachen, und es gibt eine News-Seite." + }, + "levels": { + "simple": { + "title": "Die Website ändert sich", + "text": "Die Website gibt es jetzt auf Englisch, Deutsch, Italienisch und Spanisch. Alle Neuigkeiten findest du hier, auf der News-Seite." + }, + "normal": { + "title": "Neue Version der Website: Sprachen und News-Seite", + "text": "Die Website ist jetzt auf Französisch, Englisch, Deutsch, Italienisch und Spanisch verfügbar. Eine News-Seite sammelt jetzt alle Neuigkeiten. Die Einstellungen zur Barrierefreiheit stehen unten auf jeder Seite." + }, + "developpeur": { + "title": "Neue Version der Website: Übersetzungen und News-Feed", + "text": "Vier Übersetzungen hinzugefügt (en, de, it, es) mit hreflang, dazu eine News-Seite, die einen statischen JSON-Feed liest, filterbar nach Detailstufe und Thema. Die Einstellungen bleiben im Browser (localStorage); nur das Design wird zusätzlich in einem Präferenz-Cookie gespeichert, höchstens 13 Monate." + } + } + }, + "it": { + "short": { + "title": "Nuova versione del sito", + "text": "Il sito ora è disponibile in più lingue, e c’è una pagina News." + }, + "levels": { + "simple": { + "title": "Il sito cambia", + "text": "Il sito ora esiste in inglese, tedesco, italiano e spagnolo. Tutte le novità sono qui, nella pagina News." + }, + "normal": { + "title": "Nuova versione del sito: lingue e pagina News", + "text": "Il sito ora è disponibile in francese, inglese, tedesco, italiano e spagnolo. Una pagina News raccoglie ora tutte le novità. Le impostazioni di accessibilità sono in fondo a ogni pagina." + }, + "developpeur": { + "title": "Nuova versione del sito: traduzioni e feed News", + "text": "Aggiunte quattro traduzioni (en, de, it, es) con hreflang, e una pagina News che legge un feed JSON statico filtrabile per livello di dettaglio e tema. Le impostazioni restano nel browser (localStorage); solo il tema è salvato anche in un cookie di preferenza, per 13 mesi al massimo." + } + } + }, + "es": { + "short": { + "title": "Nueva versión del sitio", + "text": "El sitio ya está disponible en varios idiomas, y llega una página News." + }, + "levels": { + "simple": { + "title": "El sitio cambia", + "text": "El sitio ya existe en inglés, alemán, italiano y español. Todas las novedades están aquí, en la página News." + }, + "normal": { + "title": "Nueva versión del sitio: idiomas y página News", + "text": "El sitio ya está disponible en francés, inglés, alemán, italiano y español. Una página News reúne ahora todas las novedades. Los ajustes de accesibilidad están al final de cada página." + }, + "developpeur": { + "title": "Nueva versión del sitio: traducciones y feed News", + "text": "Se añaden cuatro traducciones (en, de, it, es) con hreflang, y una página News que lee un feed JSON estático filtrable por nivel de detalle y tema. Los ajustes se quedan en el navegador (localStorage); solo el tema se guarda también en una cookie de preferencia, 13 meses como máximo." + } + } + } + } + } +] diff --git a/index.html b/index.html index 14f32a3..d940a30 100644 --- a/index.html +++ b/index.html @@ -459,6 +459,18 @@ body.spa-nav-hidden .spa-nav { display:none; } #accueil .carousel-progress-bar { height:100%; width:0%; background:#fff; position:relative; border-radius:2px; transition:background-color .3s; } #accueil .carousel-progress-dot { position:absolute; right:-6px; top:-5px; width:13px; height:13px; border-radius:50%; background:#fff; border:2px solid #000; box-shadow:0 1px 4px rgba(0,0,0,.25); box-sizing:border-box; transition:background-color .3s; } #accueil .extra-projects-section { background:#fbfbfb; padding:90px 20px; text-align:center; border-bottom:1px solid #eaeaea; } +/* Bouton News (exception autorisée par Théo le 25/10/2026) : même effet que « Explorer la galerie » du portfolio */ +#accueil .actus-bouton-zone { max-width:900px; width:calc(100% - 40px); height:84px; margin:80px auto 10px auto; position:relative; z-index:3; box-sizing:border-box; } +#accueil .actus-bouton { position:relative; width:100%; height:100%; background:#fff; border:2px solid #111; display:flex; align-items:center; justify-content:center; overflow:hidden; box-sizing:border-box; text-decoration:none; transition:box-shadow .4s ease,transform .4s ease; } +#accueil .actus-defile { position:absolute; top:0; left:0; height:100%; display:flex; align-items:center; pointer-events:none; z-index:1; animation:actusDefile 30s linear infinite; } +#accueil .actus-defile-texte { display:flex; white-space:nowrap; font-family:var(--font-sans); font-size:1.4rem; font-weight:600; color:#d1d1d1; letter-spacing:4px; } +#accueil .actus-etiquette { position:relative; z-index:2; font-family:var(--font-sans); font-size:clamp(.9rem,4vw,1.3rem); font-weight:700; color:#111; background:#fff; padding:10px 25px; letter-spacing:1px; box-shadow:0 0 30px 20px #fff; transition:transform .3s ease; } +#accueil .actus-bouton:hover, #accueil .actus-bouton:focus-visible { box-shadow:0 10px 25px rgba(0,0,0,.1); transform:translateY(-2px); } +#accueil .actus-bouton:hover .actus-etiquette, #accueil .actus-bouton:focus-visible .actus-etiquette { transform:scale(1.05); } +#accueil .actus-bouton:focus-visible { outline:3px solid #38bdf8; outline-offset:3px; } +@keyframes actusDefile { from { transform:translateX(0); } to { transform:translateX(-50%); } } +@media (prefers-reduced-motion:reduce){ #accueil .actus-defile { animation:none; } } +@media (max-width:600px){ #accueil .actus-bouton-zone { height:68px; } #accueil .actus-defile-texte { font-size:1.1rem; } } #accueil .extra-projects-title { font-family:var(--font-sans); font-size:1.4rem; text-transform:uppercase; letter-spacing:3px; margin-bottom:65px; color:#888; } #accueil .floating-cards-container { display:flex; justify-content:center; align-items:center; gap:40px; flex-wrap:wrap; max-width:1100px; margin:0 auto; position:relative; } #accueil .floating-card { background:#fff; border:1px solid #e2e2e2; border-radius:8px; padding:35px 30px; width:340px; text-align:left; text-decoration:none; color:#111; box-sizing:border-box; transition:border-color .3s,box-shadow .3s; box-shadow:0 5px 15px rgba(0,0,0,.02); transform-style:preserve-3d; will-change:transform; } @@ -727,9 +739,10 @@ body.spa-nav-hidden .spa-nav { display:none; } ++ ++ ++ ++
++

News

++

Ici, tu trouves les dernières nouveautés : vidéos et photos, projets techniques, sorties d'applications et mises à jour du site.

++
Brouillon. Les news affichées sont des exemples ([EXEMPLE]). Elles seront remplacées par de vraies news avant la mise en ligne.
++
++ ++
++ ++ ++ ++ +diff --git a/tools/add-news.js b/tools/add-news.js +new file mode 100644 +index 0000000..3772b33 +--- /dev/null ++++ b/tools/add-news.js +@@ -0,0 +1,100 @@ ++#!/usr/bin/env node ++/** ++ * tools/add-news.js — ajoute une entrée à data/actus.json, après validation. ++ * ++ * Exemple : ++ * node tools/add-news.js --category technique --title "Nouvelle version de GWS" \ ++ * --summary "Le logiciel gère maintenant les exports PDF." --link /gws/ [--date 2026-11-02] \ ++ * [--image /assets/img/photo.webp --image-alt "Description de l'image"] [--dry-run] ++ * ++ * Catégories : audiovisuel, technique, application, site. ++ * Zéro dépendance. N'écrit rien si une règle n'est pas respectée. ++ */ ++'use strict'; ++const fs = require('fs'); ++const path = require('path'); ++ ++const FILE = path.resolve(__dirname, '..', 'data', 'actus.json'); ++const CATS = ['audiovisuel', 'technique', 'application', 'site']; ++const LIMITS = { title: 120, summary: 280 }; ++ ++function parseArgs(argv) { ++ const out = {}; ++ for (let i = 0; i < argv.length; i++) { ++ const a = argv[i]; ++ if (!a.startsWith('--')) throw new Error(`Argument inattendu : ${a}`); ++ const key = a.slice(2); ++ if (key === 'dry-run' || key === 'help') { out[key] = true; continue; } ++ const v = argv[++i]; ++ if (v === undefined || v.startsWith('--')) throw new Error(`Valeur manquante pour --${key}`); ++ out[key] = v; ++ } ++ return out; ++} ++ ++function todayLocal() { ++ const d = new Date(); ++ const p = (n) => String(n).padStart(2, '0'); ++ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; ++} ++ ++function validDate(s) { ++ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false; ++ const d = new Date(s + 'T12:00:00Z'); ++ return !isNaN(d) && d.toISOString().slice(0, 10) === s; ++} ++ ++function validUrl(u) { return /^\/(?!\/)\S*$/.test(u) || /^https:\/\/\S+$/i.test(u); } ++ ++function main() { ++ const a = parseArgs(process.argv.slice(2)); ++ if (a.help) { ++ console.log('Usage : node tools/add-news.js --category --title "..." --summary "..." [--link URL] [--image URL --image-alt "..."] [--date AAAA-MM-JJ] [--dry-run]'); ++ return; ++ } ++ const errors = []; ++ const category = a.category; ++ const title = (a.title || '').trim(); ++ const summary = (a.summary || '').trim(); ++ const date = a.date || todayLocal(); ++ ++ if (!CATS.includes(category)) errors.push(`--category doit être : ${CATS.join(', ')}`); ++ if (!title) errors.push('--title est obligatoire'); ++ else if (title.length > LIMITS.title) errors.push(`--title : ${LIMITS.title} caractères maximum (${title.length})`); ++ if (!summary) errors.push('--summary est obligatoire'); ++ else if (summary.length > LIMITS.summary) errors.push(`--summary : ${LIMITS.summary} caractères maximum (${summary.length})`); ++ if (!validDate(date)) errors.push('--date doit être une vraie date au format AAAA-MM-JJ'); ++ if (a.link && !validUrl(a.link)) errors.push('--link doit commencer par / (page du site) ou https://'); ++ if (a.image && !validUrl(a.image)) errors.push('--image doit commencer par / ou https://'); ++ if (a.image && !a['image-alt']) errors.push('--image-alt est obligatoire quand il y a une image (accessibilité)'); ++ if (errors.length) { console.error('Entrée refusée :\n- ' + errors.join('\n- ')); process.exit(1); } ++ ++ let list = []; ++ if (fs.existsSync(FILE)) { ++ try { list = JSON.parse(fs.readFileSync(FILE, 'utf8')); } ++ catch (e) { console.error(`${FILE} n'est pas un JSON valide : ${e.message}`); process.exit(1); } ++ if (!Array.isArray(list)) { console.error('actus.json doit contenir un tableau.'); process.exit(1); } ++ } ++ if (list.some((n) => n && n.title === title && n.date === date)) { ++ console.error('Une news avec le même titre et la même date existe déjà : rien écrit.'); ++ process.exit(1); ++ } ++ ++ const id = list.reduce((m, n) => Math.max(m, Number(n && n.id) || 0), 0) + 1; ++ const entry = { id, date, category, title, summary }; ++ if (a.link) entry.link = a.link; ++ if (a.image) { entry.image = a.image; entry.imageAlt = a['image-alt']; } ++ ++ list.unshift(entry); ++ list.sort((x, y) => (x.date === y.date ? y.id - x.id : x.date < y.date ? 1 : -1)); ++ const text = JSON.stringify(list, null, 2) + '\n'; ++ JSON.parse(text); // contrôle final ++ ++ if (a['dry-run']) { console.log('[essai] rien écrit. Entrée :\n' + JSON.stringify(entry, null, 2)); return; } ++ fs.copyFileSync(FILE, FILE + '.bak'); ++ fs.writeFileSync(FILE, text, 'utf8'); ++ console.log(`News n°${id} ajoutée (${date}, ${category}). Sauvegarde : data/actus.json.bak`); ++ console.log('Suite : node tools/build.js puis node tools/deploy.js (lancés par toi).'); ++} ++ ++try { main(); } catch (e) { console.error(e.message); process.exit(1); } +diff --git a/tools/build.js b/tools/build.js +index adea648..2e07478 100644 +--- a/tools/build.js ++++ b/tools/build.js +@@ -39,10 +39,12 @@ const DIST = path.join(ROOT, 'dist'); + const BUILD_DIR = 'assets/build'; + // Sections retirées du HTML initial (lourdes, peu utiles au référencement). + const FRAGMENTS = ['termes']; +-const COPY_AS_IS =['llms.txt', 'robots.txt', 'sitemap.xml', 'data/news.json', ++const COPY_AS_IS =['llms.txt', 'robots.txt', 'sitemap.xml', 'data/news.json', 'data/actus.json', + 'favicon.svg', 'favicon.ico', + // Pages de contenu (SEO) : brouillons noindex tant que les [À VÉRIFIER] ne sont pas levés. + 'meteo-lans/index.html', 'stations-romma/index.html', 'qui-suis-je/index.html', 'projets/index.html', ++ // Section News : page de liste + script du widget (brouillon noindex tant qu'il y a des [EXEMPLE]). ++ 'news/index.html', 'news/actus.js', + // Traductions informatives (hreflang) : copiées telles quelles, chemins d'assets absolus. + 'en/index.html', 'de/index.html', 'it/index.html', 'es/index.html']; + const COMPRESSIBLE = new Set(['.html', '.css', '.js', '.json', '.txt', '.xml', '.svg']); diff --git a/news/actus.js b/news/actus.js new file mode 100644 index 0000000..68f9de2 --- /dev/null +++ b/news/actus.js @@ -0,0 +1,365 @@ +/* news/actus.js : composant News autonome (sans bibliothèque). + * Deux usages : + * -> les 3 dernières news, en version courte + *
-> liste complète (page /news/), au niveau choisi + * Les données viennent de /data/actus.json (attribut data-src pour changer). + * Réglages du visiteur (niveau + thèmes) : lus dans localStorage (clé « gastinel-actus »). + * Sans réglage : niveau « normal », tous les thèmes. Sans localStorage : même chose, la page marche. + * Le panneau de réglages (news/reglages.js) prévient ce composant par l'évènement « gastinel:prefs ». + * Si le fichier manque ou est invalide : le widget reste caché, la page ne casse pas. + */ +(function () { + 'use strict'; + /* Langue de la page (attribut lang), français par défaut. Textes de l'interface par langue (26/10). */ + var LANG = String(document.documentElement.getAttribute('lang') || 'fr').slice(0, 2).toLowerCase(); + var I18N = { + fr: { themes: ['Audiovisuel', 'Applications', 'Technique et projets', 'Mises à jour du site', 'Météo', 'Minecraft', 'Mind et IA', 'Hub et comptes', 'Vie locale à Lans'], + levels: ['Simple', 'Normal', 'Développeur'], locale: 'fr-FR', loading: 'Chargement des news…', none: 'Il n’y a pas encore de news.', + flux: function (lv, n) { return 'Ton flux : niveau ' + lv.toLowerCase() + ', ' + (n ? n + (n > 1 ? ' thèmes choisis' : ' thème choisi') : 'tous les thèmes') + '.'; }, + change: 'Changer mon flux', count: function (n) { return n + (n > 1 ? ' news affichées.' : ' news affichée.'); }, + empty: 'Aucune news pour les thèmes choisis. Change ton flux pour en voir plus.', error: 'Les news ne sont pas disponibles pour le moment. Reviens un peu plus tard.', + back: '← Toutes les news', latest: 'Dernières news', all: 'Toutes les news', emptyW: 'Aucune news pour tes thèmes pour le moment.' }, + en: { themes: ['Audiovisual', 'Apps', 'Tech and projects', 'Site updates', 'Weather', 'Minecraft', 'Mind and AI', 'Hub and accounts', 'Local life in Lans'], + levels: ['Simple', 'Normal', 'Developer'], locale: 'en-GB', loading: 'Loading news…', none: 'No news yet.', + flux: function (lv, n) { return 'Your feed: ' + lv.toLowerCase() + ' level, ' + (n ? n + (n > 1 ? ' topics chosen' : ' topic chosen') : 'all topics') + '.'; }, + change: 'Change my feed', count: function (n) { return n + (n > 1 ? ' news items shown.' : ' news item shown.'); }, + empty: 'No news for the chosen topics. Change your feed to see more.', error: 'News is not available right now. Please come back a little later.', + back: '← All news', latest: 'Latest news', all: 'All news', emptyW: 'No news for your topics yet.' }, + de: { themes: ['Audiovisuell', 'Apps', 'Technik und Projekte', 'Website-Updates', 'Wetter', 'Minecraft', 'Mind und KI', 'Hub und Konten', 'Lokales aus Lans'], + levels: ['Einfach', 'Normal', 'Entwickler'], locale: 'de-DE', loading: 'News werden geladen…', none: 'Noch keine News.', + flux: function (lv, n) { return 'Dein Feed: Stufe ' + lv + ', ' + (n ? n + (n > 1 ? ' Themen gewählt' : ' Thema gewählt') : 'alle Themen') + '.'; }, + change: 'Feed ändern', count: function (n) { return n + ' News angezeigt.'; }, + empty: 'Keine News für die gewählten Themen. Ändere deinen Feed, um mehr zu sehen.', error: 'Die News sind gerade nicht verfügbar. Schau etwas später wieder vorbei.', + back: '← Alle News', latest: 'Neueste News', all: 'Alle News', emptyW: 'Noch keine News für deine Themen.' }, + it: { themes: ['Audiovisivo', 'App', 'Tecnica e progetti', 'Aggiornamenti del sito', 'Meteo', 'Minecraft', 'Mind e IA', 'Hub e account', 'Vita locale a Lans'], + levels: ['Semplice', 'Normale', 'Sviluppatore'], locale: 'it-IT', loading: 'Caricamento delle news…', none: 'Non ci sono ancora news.', + flux: function (lv, n) { return 'Il tuo feed: livello ' + lv.toLowerCase() + ', ' + (n ? n + (n > 1 ? ' temi scelti' : ' tema scelto') : 'tutti i temi') + '.'; }, + change: 'Cambia il mio feed', count: function (n) { return n + ' news ' + (n > 1 ? 'mostrate.' : 'mostrata.'); }, + empty: 'Nessuna news per i temi scelti. Cambia il feed per vederne di più.', error: 'Le news non sono disponibili al momento. Torna un po’ più tardi.', + back: '← Tutte le news', latest: 'Ultime news', all: 'Tutte le news', emptyW: 'Ancora nessuna news per i tuoi temi.' }, + es: { themes: ['Audiovisual', 'Apps', 'Técnica y proyectos', 'Novedades del sitio', 'Tiempo', 'Minecraft', 'Mind e IA', 'Hub y cuentas', 'Vida local en Lans'], + levels: ['Simple', 'Normal', 'Desarrollador'], locale: 'es-ES', loading: 'Cargando las news…', none: 'Todavía no hay news.', + flux: function (lv, n) { return 'Tu feed: nivel ' + lv.toLowerCase() + ', ' + (n ? n + (n > 1 ? ' temas elegidos' : ' tema elegido') : 'todos los temas') + '.'; }, + change: 'Cambiar mi feed', count: function (n) { return n + ' news ' + (n > 1 ? 'mostradas.' : 'mostrada.'); }, + empty: 'No hay news para los temas elegidos. Cambia tu feed para ver más.', error: 'Las news no están disponibles por ahora. Vuelve un poco más tarde.', + back: '← Todas las news', latest: 'Últimas news', all: 'Todas las news', emptyW: 'Todavía no hay news para tus temas.' } + }; + if (!Object.prototype.hasOwnProperty.call(I18N, LANG)) LANG = 'fr'; + var TX = I18N[LANG]; + var THEMES = {}, LEVELS = {}; + ['audiovisuel', 'applications', 'technique', 'site', 'meteo', 'minecraft', 'mind', 'hub', 'vie-locale'].forEach(function (k, i) { THEMES[k] = TX.themes[i]; }); + ['simple', 'normal', 'developpeur'].forEach(function (k, i) { LEVELS[k] = TX.levels[i]; }); + var LEGACY = { 'application': 'applications' }; + var STORE_KEY = 'gastinel-actus'; + var DEFAULT_SRC = '/data/actus.json'; + var NEWS_URL = LANG === 'fr' ? '/news/' : '/news/' + LANG + '/'; + var has = function (o, k) { return Object.prototype.hasOwnProperty.call(o, k); }; + + /* ---------- Réglages (lecture seule ici) ---------- */ + var prefs = readPrefs(); + + function normalizePrefs(p) { + var level = p && typeof p.level === 'string' && has(LEVELS, p.level) ? p.level : 'normal'; + var themes = null; /* null = tous les thèmes */ + if (p && Array.isArray(p.themes)) { + var list = p.themes.filter(function (t) { return typeof t === 'string' && has(THEMES, t); }); + if (list.length) themes = list; + } + return { level: level, themes: themes }; + } + function readPrefs() { + try { + var raw = window.localStorage.getItem(STORE_KEY); + return normalizePrefs(raw ? JSON.parse(raw) : null); + } catch (e) { return normalizePrefs(null); } + } + + /* ---------- Utilitaires ---------- */ + var CSS = '' + + '.actus-widget{background:#fafafa;border-top:1px solid #eaeaea;padding:48px 20px 72px;font-family:var(--font-sans,Inter,system-ui,sans-serif);color:#111}' + + '.actus-widget[hidden]{display:none}' + + '.actus-wrap{max-width:1120px;margin:0 auto}' + + '.actus-head{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:8px 16px;margin-bottom:22px}' + + '.actus-title{font-size:1.6rem;font-weight:700;letter-spacing:-.02em;margin:0;color:#111}' + + '.actus-all{font-weight:600;font-size:.95rem;color:#111;text-decoration:underline;text-underline-offset:3px;padding:8px 0}' + + '.actus-all:hover{color:#1e4d8b}' + + '.actus-all:focus-visible{outline:3px solid #1e4d8b;outline-offset:3px}' + + '.actus-list{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(3,1fr);gap:22px}' + + '.actus-list.actus-full{grid-template-columns:repeat(auto-fill,minmax(280px,1fr))}' + + '@media(max-width:900px){.actus-list{grid-template-columns:1fr}.actus-widget{padding:36px 16px 72px}}' + + '.actus-card{position:relative;display:flex;flex-direction:column;background:#fff;border:1px solid #d9d9d9;border-radius:8px;padding:22px 20px;height:100%;box-sizing:border-box}' + + '.actus-card:hover{border-color:#111;box-shadow:0 8px 22px rgba(0,0,0,.08)}' + + '.actus-card:focus-within{outline:3px solid #1e4d8b;outline-offset:2px}' + + '.actus-img{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:6px;margin:0 0 14px;background:#eee;display:block}' + + '.actus-meta{display:flex;flex-wrap:wrap;gap:8px 12px;align-items:center;margin-bottom:10px;font-size:.82rem}' + + '.actus-cat{background:#eceef1;color:#1a1d21;font-weight:700;padding:3px 10px;border-radius:4px;text-transform:uppercase;letter-spacing:.03em;font-size:.74rem}' + + '.actus-date{color:#4b5563}' + + '.actus-card-title{font-size:1.05rem;line-height:1.35;font-weight:700;margin:0 0 8px;color:#111}' + + '.actus-card-title a{color:inherit;text-decoration:none}' + + '.actus-card-title a::after{content:"";position:absolute;inset:0;border-radius:8px}' + + '.actus-card-title a:hover{text-decoration:underline}' + + '.actus-card-title a:focus-visible{outline:none}' + + '.actus-sum{margin:0;color:#3f4650;font-size:.92rem;line-height:1.55}' + + '.actus-flux{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px;margin:0 0 16px;font-size:.95rem;color:#3f4650}' + + '.actus-flux-btn{font:inherit;font-size:.9rem;font-weight:600;padding:9px 16px;min-height:44px;border-radius:999px;border:2px solid #242424;background:#fff;color:#242424;cursor:pointer}' + + '.actus-flux-btn:hover{background:#eceef1}' + + '.actus-flux-btn:focus-visible{outline:3px solid #1e4d8b;outline-offset:3px}' + + '.actus-status{margin:0 0 16px;color:#4b5563;font-size:.92rem}'; + + function injectCss() { + if (document.getElementById('actus-css')) return; + var s = document.createElement('style'); + s.id = 'actus-css'; + s.textContent = CSS; + document.head.appendChild(s); + } + + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; + } + + /* Seuls les liens relatifs (/...) et https sont acceptés. */ + function safeUrl(u) { + if (typeof u !== 'string') return ''; + return (/^\/(?!\/)/.test(u) || /^https:\/\//i.test(u)) ? u : ''; + } + + function str(v) { return typeof v === 'string' ? v.trim() : ''; } + + /* Lit une version {title,text} ; renvoie null si inutilisable. */ + function readVersion(v) { + if (!v || typeof v !== 'object') return null; + var t = str(v.title), x = str(v.text); + return (t || x) ? { title: t, text: x } : null; + } + + function firstSentence(t) { + var m = t.match(/^.*?[.!?](\s|$)/); + var s = (m ? m[0] : t).trim(); + return s.length > 160 ? s.slice(0, 159).replace(/\s+\S*$/, '') + '…' : s; + } + + /* Garde les entrées au bon format. Accepte aussi l'ancien format (category + summary). */ + function clean(raw) { + if (!Array.isArray(raw)) return []; + var out = []; + raw.forEach(function (n) { + if (!n || typeof n !== 'object') return; + if (typeof n.date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(n.date)) return; + var levels = {}; + /* Traduction de l'article si elle existe (champ i18n.), sinon le français. */ + var tr = LANG !== 'fr' && n.i18n && typeof n.i18n === 'object' && n.i18n[LANG] && typeof n.i18n[LANG] === 'object' ? n.i18n[LANG] : null; + if (tr) n = { id: n.id, date: n.date, themes: n.themes, link: n.link, image: n.image, imageAlt: n.imageAlt, short: tr.short, levels: tr.levels }; + if (n.levels && typeof n.levels === 'object') { + Object.keys(LEVELS).forEach(function (k) { var v = readVersion(n.levels[k]); if (v) levels[k] = v; }); + } else if (str(n.title)) { /* ancien format */ + levels.normal = { title: str(n.title), text: str(n.summary) }; + } + var normal = levels.normal; + if (!normal || !normal.title) return; /* « normal » est obligatoire */ + var themes = []; + var src = Array.isArray(n.themes) ? n.themes : [n.category]; + src.forEach(function (t) { + t = has(LEGACY, t) ? LEGACY[t] : t; + if (typeof t === 'string' && has(THEMES, t) && themes.indexOf(t) < 0) themes.push(t); + }); + if (!themes.length) return; + var short = readVersion(n.short) || { title: normal.title, text: firstSentence(normal.text) }; + if (!short.title) short.title = normal.title; + out.push({ + id: n.id, date: n.date, themes: themes, levels: levels, short: short, + link: safeUrl(n.link), image: safeUrl(n.image), imageAlt: typeof n.imageAlt === 'string' ? n.imageAlt : '' + }); + }); + out.sort(function (a, b) { + if (a.date !== b.date) return a.date < b.date ? 1 : -1; + return (Number(b.id) || 0) - (Number(a.id) || 0); + }); + return out; + } + + /* Version du bon niveau ; repli sur « normal » si elle manque, titre compris. */ + function versionFor(n, level) { + var v = n.levels[level] || n.levels.normal; + return { title: v.title || n.levels.normal.title, text: v.text || n.levels.normal.text }; + } + + function matches(n) { + if (!prefs.themes) return true; + return n.themes.some(function (t) { return prefs.themes.indexOf(t) >= 0; }); + } + + function fmtDate(iso) { + try { + return new Date(iso + 'T12:00:00').toLocaleDateString(TX.locale, { day: 'numeric', month: 'long', year: 'numeric' }); + } catch (e) { return iso; } + } + + function card(n, mode) { + var full = mode === 'full'; + var v = full ? versionFor(n, prefs.level) : n.short; + var li = el('li'); + var art = el('article', 'actus-card'); + if (full && n.image) { + var img = el('img', 'actus-img'); + img.src = n.image; img.alt = n.imageAlt; img.loading = 'lazy'; img.decoding = 'async'; + img.onerror = function () { img.remove(); }; + art.appendChild(img); + } + var meta = el('div', 'actus-meta'); + n.themes.forEach(function (t) { meta.appendChild(el('span', 'actus-cat', THEMES[t])); }); + var d = el('time', 'actus-date', fmtDate(n.date)); + d.setAttribute('datetime', n.date); + meta.appendChild(d); + art.appendChild(meta); + var h = el('h3', 'actus-card-title'); + if (full) { /* page News : le titre ouvre l'article en grand */ + var ao = el('a', null, v.title); + ao.href = '#n-' + n.id; + h.appendChild(ao); + } else if (n.link) { + var a = el('a', null, v.title); + a.href = n.link; + if (/^https:/i.test(n.link)) a.rel = 'noopener'; + h.appendChild(a); + } else { + h.textContent = v.title; + } + art.appendChild(h); + if (v.text) art.appendChild(el('p', 'actus-sum', v.text)); + li.appendChild(art); + return li; + } + + function load(src) { + return fetch(src, { credentials: 'same-origin' }) + .then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }) + .then(clean); + } + + function describe() { + return TX.flux(LEVELS[prefs.level], prefs.themes ? prefs.themes.length : 0); + } + + function onPrefs(fn) { + document.addEventListener('gastinel:prefs', function (e) { + prefs = normalizePrefs(e && e.detail ? e.detail : readPrefs()); + fn(); + }); + } + + /* ---------- Widget ---------- */ + function initWidget(root) { + injectCss(); + var items = []; + var wrap = null, ul = null, empty = null; + + function render() { + var shown = items.filter(matches); + ul.textContent = ''; + shown.slice(0, 3).forEach(function (n) { ul.appendChild(card(n, 'short')); }); + empty.hidden = shown.length > 0; + } + + load(root.getAttribute('data-src') || DEFAULT_SRC).then(function (list) { + if (!list.length) return; /* rien à montrer : reste caché */ + items = list; + root.className = 'actus-widget'; + root.setAttribute('aria-labelledby', 'actus-widget-title'); + wrap = el('div', 'actus-wrap'); + var head = el('div', 'actus-head'); + var h = el('h2', 'actus-title', TX.latest); + h.id = 'actus-widget-title'; + head.appendChild(h); + var all = el('a', 'actus-all', TX.all); + all.href = NEWS_URL; + head.appendChild(all); + wrap.appendChild(head); + empty = el('p', 'actus-status', TX.emptyW); + empty.hidden = true; + wrap.appendChild(empty); + ul = el('ul', 'actus-list'); + wrap.appendChild(ul); + root.appendChild(wrap); + render(); + root.hidden = false; + onPrefs(render); + }).catch(function () { /* fichier absent ou invalide : le widget reste caché */ }); + } + + /* ---------- Page de liste ---------- */ + function initList(root) { + injectCss(); + root.classList.add('actus-wrap'); + var status = el('p', 'actus-status'); + status.setAttribute('role', 'status'); + status.setAttribute('aria-live', 'polite'); + status.textContent = TX.loading; + root.appendChild(status); + + load(root.getAttribute('data-src') || DEFAULT_SRC).then(function (items) { + if (!items.length) { status.textContent = TX.none; return; } + var bar = el('div', 'actus-flux'); + var info = el('span', 'actus-flux-info'); + info.id = 'actus-flux-info'; + bar.appendChild(info); + var btn = el('button', 'actus-flux-btn', TX.change); + btn.type = 'button'; + btn.setAttribute('data-actus-open-settings', ''); + btn.addEventListener('click', function () { + document.dispatchEvent(new CustomEvent('gastinel:open-reglages')); + }); + bar.appendChild(btn); + var ul = el('ul', 'actus-list actus-full'); + root.insertBefore(bar, status); + root.appendChild(ul); + + /* Article ouvert en grand : adresse « #n- » (retour avec le bouton ou le retour du navigateur). */ + var view = el('article', 'actus-article'); view.style.display = 'none'; + root.appendChild(view); + function article(n) { + var v = versionFor(n, prefs.level); + view.textContent = ''; + var back = el('a', 'actus-back', TX.back); back.href = '#'; + view.appendChild(back); + var meta = el('div', 'actus-meta'); + n.themes.forEach(function (t) { meta.appendChild(el('span', 'actus-cat', THEMES[t])); }); + var d = el('time', 'actus-date', fmtDate(n.date)); d.setAttribute('datetime', n.date); + meta.appendChild(d); view.appendChild(meta); + view.appendChild(el('h2', 'actus-article-title', v.title)); + if (n.image) { var img = el('img', 'actus-article-img'); img.src = n.image; img.alt = n.imageAlt; view.appendChild(img); } + if (v.text) view.appendChild(el('p', 'actus-article-text', v.text)); + } + function route() { + var m = /^#n-(.+)$/.exec(location.hash); + var n = m ? items.filter(function (x) { return String(x.id) === decodeURIComponent(m[1]); })[0] : null; + view.style.display = n ? '' : 'none'; + [bar, ul, status].forEach(function (x) { x.style.display = n ? 'none' : ''; }); + if (n) { article(n); window.scrollTo(0, 0); var t = view.querySelector('h2'); if (t) { t.tabIndex = -1; t.focus({ preventScroll: true }); } } + } + window.addEventListener('hashchange', route); + + function render() { + ul.textContent = ''; + var shown = items.filter(matches); + shown.forEach(function (n) { ul.appendChild(card(n, 'full')); }); + info.textContent = describe(); + status.textContent = shown.length === 0 ? TX.empty : TX.count(shown.length); + route(); + } + render(); + onPrefs(render); + }).catch(function () { + status.textContent = TX.error; + }); + } + + function start() { + Array.prototype.forEach.call(document.querySelectorAll('[data-actus-widget]'), initWidget); + Array.prototype.forEach.call(document.querySelectorAll('[data-actus-list]'), initList); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start(); +})(); diff --git a/news/de/index.html b/news/de/index.html new file mode 100644 index 0000000..d119626 --- /dev/null +++ b/news/de/index.html @@ -0,0 +1,89 @@ + + + + + +News — Théo Gastinel: Videos, Projekte und Apps + + + + + + + + + + + + + + + + + + + + +
+

News

+

Hier findest du die neuesten Neuigkeiten: Videos und Fotos, technische Projekte, App-Veröffentlichungen und Website-Updates.

+
+ +
+ + + + + + diff --git a/news/en/index.html b/news/en/index.html new file mode 100644 index 0000000..bb64847 --- /dev/null +++ b/news/en/index.html @@ -0,0 +1,89 @@ + + + + + +News — Théo Gastinel: videos, projects and apps + + + + + + + + + + + + + + + + + + + + +
+

News

+

Here you will find the latest updates: videos and photos, technical projects, app releases and site updates.

+
+ +
+ + + + + + diff --git a/news/es/index.html b/news/es/index.html new file mode 100644 index 0000000..95e52e7 --- /dev/null +++ b/news/es/index.html @@ -0,0 +1,89 @@ + + + + + +News — Théo Gastinel: vídeos, proyectos y aplicaciones + + + + + + + + + + + + + + + + + + + + +
+

News

+

Aquí encontrarás las últimas novedades: vídeos y fotos, proyectos técnicos, lanzamientos de apps y novedades del sitio.

+
+ +
+ + + + + + diff --git a/news/index.html b/news/index.html new file mode 100644 index 0000000..2e76a34 --- /dev/null +++ b/news/index.html @@ -0,0 +1,89 @@ + + + + + +News — Théo Gastinel : vidéos, projets et applications + + + + + + + + + + + + + + + + + + + + +
+

News

+

Ici, tu trouves les dernières nouveautés : vidéos et photos, projets techniques, sorties d'applications et mises à jour du site.

+
+ +
+ + + + + + diff --git a/news/it/index.html b/news/it/index.html new file mode 100644 index 0000000..3f1da30 --- /dev/null +++ b/news/it/index.html @@ -0,0 +1,89 @@ + + + + + +News — Théo Gastinel: video, progetti e app + + + + + + + + + + + + + + + + + + + + +
+

News

+

Qui trovi le ultime novità: video e foto, progetti tecnici, uscite di app e aggiornamenti del sito.

+
+ +
+ + + + + + diff --git a/news/newsletter.js b/news/newsletter.js new file mode 100644 index 0000000..805bdcf --- /dev/null +++ b/news/newsletter.js @@ -0,0 +1,182 @@ +/* news/newsletter.js : bouton « Newsletter » (en haut à droite de la page News) + fenêtre d'inscription. + * Envoie prénom, nom, adresse, langue, niveau et thèmes (réglages News du navigateur) au service + * /api/newsletter/inscription. Sans bibliothèque. Thème clair. « Se connecter avec Gastinel » : à venir (Hub). + */ +(function () { + 'use strict'; + var T = { + fr: { btn: 'Newsletter', title: 'Recevoir les News par mail', intro: 'Un mail à chaque nouvel article, selon ton niveau et tes thèmes.', + hub: 'Se connecter avec Gastinel', soon: 'bientôt', or: 'ou', prenom: 'Prénom', nom: 'Nom (facultatif)', email: 'Adresse mail', + send: 'M’inscrire', close: 'Fermer', minor: 'Moins de 15 ans : demande l’accord d’un parent avant de t’inscrire.', + privacy: 'Données utilisées seulement pour t’envoyer les News. Désabonnement en un clic dans chaque mail.', more: 'En savoir plus', + ok: 'C’est presque fini : ouvre le mail de confirmation que tu viens de recevoir.', wait: 'Envoi…', + err: { email: 'Cette adresse mail n’est pas valide.', prenom: 'Le prénom ne doit contenir que des lettres.', nom: 'Le nom ne doit contenir que des lettres.', + trop: 'Trop de demandes. Réessaie dans une heure.', autre: 'L’inscription n’a pas marché. Réessaie un peu plus tard.' } }, + en: { btn: 'Newsletter', title: 'Get the News by email', intro: 'One email for each new article, matching your level and topics.', + hub: 'Sign in with Gastinel', soon: 'coming soon', or: 'or', prenom: 'First name', nom: 'Last name (optional)', email: 'Email address', + send: 'Subscribe', close: 'Close', minor: 'Under 15: ask a parent before subscribing.', + privacy: 'Your data is only used to send you the News. One-click unsubscribe in every email.', more: 'Learn more', + ok: 'Almost done: open the confirmation email you just received.', wait: 'Sending…', + err: { email: 'This email address is not valid.', prenom: 'The first name may only contain letters.', nom: 'The last name may only contain letters.', + trop: 'Too many requests. Try again in an hour.', autre: 'Subscription failed. Please try again later.' } }, + de: { btn: 'Newsletter', title: 'News per E-Mail erhalten', intro: 'Eine E-Mail pro neuem Artikel, passend zu deiner Stufe und deinen Themen.', + hub: 'Mit Gastinel anmelden', soon: 'bald', or: 'oder', prenom: 'Vorname', nom: 'Nachname (optional)', email: 'E-Mail-Adresse', + send: 'Abonnieren', close: 'Schließen', minor: 'Unter 15: Frag vor dem Abonnieren ein Elternteil.', + privacy: 'Deine Daten dienen nur dem Versand der News. Abmelden mit einem Klick in jeder E-Mail.', more: 'Mehr erfahren', + ok: 'Fast fertig: Öffne die Bestätigungs-E-Mail, die du gerade erhalten hast.', wait: 'Wird gesendet…', + err: { email: 'Diese E-Mail-Adresse ist ungültig.', prenom: 'Der Vorname darf nur Buchstaben enthalten.', nom: 'Der Nachname darf nur Buchstaben enthalten.', + trop: 'Zu viele Anfragen. Versuch es in einer Stunde erneut.', autre: 'Das Abonnement hat nicht geklappt. Versuch es später erneut.' } }, + it: { btn: 'Newsletter', title: 'Ricevi le News via email', intro: 'Una email per ogni nuovo articolo, secondo il tuo livello e i tuoi temi.', + hub: 'Accedi con Gastinel', soon: 'presto', or: 'oppure', prenom: 'Nome', nom: 'Cognome (facoltativo)', email: 'Indirizzo email', + send: 'Iscrivimi', close: 'Chiudi', minor: 'Meno di 15 anni: chiedi il permesso a un genitore prima di iscriverti.', + privacy: 'I tuoi dati servono solo a inviarti le News. Disiscrizione con un clic in ogni email.', more: 'Per saperne di più', + ok: 'Quasi fatto: apri l’email di conferma che hai appena ricevuto.', wait: 'Invio…', + err: { email: 'Questo indirizzo email non è valido.', prenom: 'Il nome può contenere solo lettere.', nom: 'Il cognome può contenere solo lettere.', + trop: 'Troppe richieste. Riprova tra un’ora.', autre: 'L’iscrizione non è riuscita. Riprova più tardi.' } }, + es: { btn: 'Newsletter', title: 'Recibir las News por correo', intro: 'Un correo por cada nuevo artículo, según tu nivel y tus temas.', + hub: 'Iniciar sesión con Gastinel', soon: 'pronto', or: 'o', prenom: 'Nombre', nom: 'Apellido (opcional)', email: 'Correo electrónico', + send: 'Suscribirme', close: 'Cerrar', minor: 'Menos de 15 años: pide permiso a un padre o madre antes de suscribirte.', + privacy: 'Tus datos solo sirven para enviarte las News. Baja con un clic en cada correo.', more: 'Más información', + ok: 'Casi listo: abre el correo de confirmación que acabas de recibir.', wait: 'Enviando…', + err: { email: 'Esta dirección de correo no es válida.', prenom: 'El nombre solo puede contener letras.', nom: 'El apellido solo puede contener letras.', + trop: 'Demasiadas solicitudes. Inténtalo dentro de una hora.', autre: 'La suscripción no ha funcionado. Inténtalo más tarde.' } } + }; + var lang = String(document.documentElement.getAttribute('lang') || 'fr').slice(0, 2).toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(T, lang)) lang = 'fr'; + var L = T[lang]; + /* Aperçu LAN : l'API est celle du site en ligne (autorisée par CORS). */ + var API = location.hostname === 'news.gastinel.me' ? '/api/newsletter/inscription' : 'https://news.gastinel.me/api/newsletter/inscription'; + var POLITIQUE = 'https://gastinel.me/#legal-rgpd'; + + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; + } + function prefs() { + try { + var p = JSON.parse(window.localStorage.getItem('gastinel-actus') || '{}'); + return { niveau: p.level || 'normal', themes: Array.isArray(p.themes) ? p.themes : [] }; + } catch (e) { return { niveau: 'normal', themes: [] }; } + } + + var CSS = '' + + '.nl-btn{margin-left:auto;font:inherit;font-weight:600;font-size:.95rem;padding:8px 16px;border:2px solid #111;background:#111;color:#fff;cursor:pointer}' + + '.nl-btn:hover{background:#fff;color:#111}.nl-btn:focus-visible{outline:3px solid #1e4d8b;outline-offset:3px}' + + '.nl-veil{position:fixed;inset:0;z-index:9700;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;padding:16px}' + + '.nl-veil[hidden]{display:none}' + + '.nl-box{background:#fff;color:#111;width:440px;max-width:100%;max-height:calc(100vh - 32px);overflow-y:auto;border:2px solid #111;padding:22px 22px 20px;box-sizing:border-box;font:16px/1.5 var(--font-sans,Inter,system-ui,sans-serif)}' + + '.nl-box *{box-sizing:border-box}.nl-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}' + + '.nl-h{font-size:1.3rem;margin:0 0 6px;line-height:1.3}.nl-x{font:inherit;font-size:1.4rem;width:44px;height:44px;border:2px solid #111;background:#fff;cursor:pointer;flex:none}' + + '.nl-p{margin:0 0 14px;color:#4b5563;font-size:.95rem}' + + '.nl-hub{width:100%;font:inherit;font-weight:600;min-height:46px;border:2px solid #d1d5db;background:#f3f4f6;color:#6b7280;cursor:not-allowed}' + + '.nl-or{text-align:center;color:#6b7280;font-size:.85rem;margin:12px 0}' + + '.nl-f label{display:block;font-weight:600;font-size:.9rem;margin:10px 0 4px}' + + '.nl-f input{width:100%;font:inherit;padding:10px 12px;border:2px solid #111;background:#fff;color:#111}' + + '.nl-f input:focus-visible{outline:3px solid #1e4d8b;outline-offset:1px}' + + '.nl-piege{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}' + + '.nl-send{width:100%;margin-top:16px;font:inherit;font-weight:700;min-height:48px;border:2px solid #111;background:#111;color:#fff;cursor:pointer}' + + '.nl-send[disabled]{opacity:.6;cursor:wait}' + + '.nl-small{font-size:.82rem;color:#4b5563;margin:12px 0 0}.nl-small a{color:#111}' + + '.nl-msg{margin:12px 0 0;padding:10px 12px;font-size:.95rem}.nl-msg.ok{background:#ecfdf3;border-left:4px solid #15803d}.nl-msg.ko{background:#fef2f2;border-left:4px solid #b91c1c}' + + '@media(max-width:600px){.nl-veil{align-items:flex-end;padding:0}.nl-box{width:100%;border-width:2px 0 0}}'; + + var veil, box, form, msg, send, opener; + + function close() { + veil.hidden = true; + document.removeEventListener('keydown', onKey, true); + if (opener) try { opener.focus(); } catch (e) { /* rien */ } + } + function onKey(e) { + if (e.key === 'Escape') { e.preventDefault(); close(); return; } + if (e.key !== 'Tab') return; + var f = box.querySelectorAll('a[href],button:not([disabled]),input:not([tabindex="-1"])'); + if (!f.length) return; + var a = document.activeElement, first = f[0], last = f[f.length - 1]; + if (e.shiftKey && a === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); } + } + function field(name, label, type, auto, required) { + var id = 'nl-' + name; + var lab = el('label', null, label); lab.htmlFor = id; + var inp = el('input'); inp.id = id; inp.name = name; inp.type = type; inp.autocomplete = auto; inp.maxLength = name === 'email' ? 254 : 60; + if (required) inp.required = true; + form.appendChild(lab); form.appendChild(inp); + } + function show(text, ok) { + msg.textContent = text; msg.className = 'nl-msg ' + (ok ? 'ok' : 'ko'); msg.hidden = false; + } + + function build() { + var st = el('style'); st.textContent = CSS; document.head.appendChild(st); + veil = el('div', 'nl-veil'); veil.hidden = true; + veil.addEventListener('mousedown', function (e) { if (e.target === veil) close(); }); + box = el('div', 'nl-box'); box.setAttribute('role', 'dialog'); box.setAttribute('aria-modal', 'true'); box.setAttribute('aria-labelledby', 'nl-title'); + var top = el('div', 'nl-top'); + var h = el('h2', 'nl-h', L.title); h.id = 'nl-title'; top.appendChild(h); + var x = el('button', 'nl-x', '×'); x.type = 'button'; x.setAttribute('aria-label', L.close); x.addEventListener('click', close); top.appendChild(x); + box.appendChild(top); + box.appendChild(el('p', 'nl-p', L.intro)); + var hub = el('button', 'nl-hub', L.hub + ' (' + L.soon + ')'); hub.type = 'button'; hub.disabled = true; + box.appendChild(hub); + box.appendChild(el('p', 'nl-or', L.or)); + form = el('form', 'nl-f'); form.noValidate = true; + field('prenom', L.prenom, 'text', 'given-name', true); + field('nom', L.nom, 'text', 'family-name', false); + field('email', L.email, 'email', 'email', true); + var piege = el('div', 'nl-piege'); piege.setAttribute('aria-hidden', 'true'); + var pi = el('input'); pi.name = 'site'; pi.tabIndex = -1; pi.autocomplete = 'off'; piege.appendChild(pi); form.appendChild(piege); + send = el('button', 'nl-send', L.send); send.type = 'submit'; form.appendChild(send); + msg = el('p', 'nl-msg'); msg.hidden = true; msg.setAttribute('role', 'status'); form.appendChild(msg); + form.addEventListener('submit', submit); + box.appendChild(form); + box.appendChild(el('p', 'nl-small', L.minor)); + var pr = el('p', 'nl-small', L.privacy + ' '); + var a = el('a', null, L.more); a.href = POLITIQUE; a.setAttribute('data-main', ''); pr.appendChild(a); + box.appendChild(pr); + veil.appendChild(box); + document.body.appendChild(veil); + } + + function submit(e) { + e.preventDefault(); + var p = prefs(); + var data = { + prenom: form.prenom.value.trim(), nom: form.nom.value.trim(), email: form.email.value.trim(), + site: form.site.value, langue: lang, niveau: p.niveau, themes: p.themes + }; + if (!data.prenom) { show(L.err.prenom, false); form.prenom.focus(); return; } + send.disabled = true; send.textContent = L.wait; msg.hidden = true; + fetch(API, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) + .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return { code: r.status, j: j }; }); }) + .then(function (r) { + if (r.code === 200) { show(L.ok, true); form.reset(); return; } + if (r.code === 429) { show(L.err.trop, false); return; } + var k = r.j && r.j.erreur; + show(L.err[k] || L.err.autre, false); + if (form[k]) form[k].focus(); + }) + .catch(function () { show(L.err.autre, false); }) + .then(function () { send.disabled = false; send.textContent = L.send; }); + } + + function open(from) { + if (!veil) build(); + opener = from; msg.hidden = true; veil.hidden = false; + document.addEventListener('keydown', onKey, true); + form.prenom.focus(); + } + + function start() { + var nav = document.querySelector('nav'); + if (!nav) return; + nav.style.alignItems = 'center'; + var b = el('button', 'nl-btn', L.btn); b.type = 'button'; b.setAttribute('aria-haspopup', 'dialog'); + b.addEventListener('click', function () { open(b); }); + nav.appendChild(b); + var st = el('style'); st.textContent = '.nl-btn{margin-left:auto;font:inherit;font-weight:600;font-size:.95rem;padding:8px 16px;border:2px solid #111;background:#111;color:#fff;cursor:pointer}.nl-btn:hover{background:#fff;color:#111}'; + document.head.appendChild(st); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start(); +})(); diff --git a/news/reglages.js b/news/reglages.js new file mode 100644 index 0000000..d14f237 --- /dev/null +++ b/news/reglages.js @@ -0,0 +1,451 @@ +/* news/reglages.js : bouton Paramètres (engrenage) + panneau de réglages. Sans bibliothèque. + * Placé dans le DOM à la fin de , jamais dans Accueil / Portfolio / Réalisations / L'envers du décor. + * Contenu : (a) flux News (niveau + thèmes), (b) langue. Pas de thème sombre, pas de « fun fact ». + * Les choix sont mémorisés dans localStorage (clé « gastinel-actus »), avec try/catch : sans stockage, tout marche + * pour la page en cours. Le composant News (news/actus.js) est prévenu par l'évènement « gastinel:prefs ». + * Première visite de /news/ : une invite « Quel flux veux-tu ? » s'ouvre une fois, puis se range. + * À venir (non codé) : connexion Gastinel Hub et abonnement par mail, voir le rapport. + */ +(function () { + 'use strict'; + var STORE_KEY = 'gastinel-actus'; + var THEME_IDS = ['audiovisuel', 'applications', 'technique', 'site', 'meteo', 'minecraft', 'mind', 'hub', 'vie-locale']; + var LEVEL_IDS = ['simple', 'normal', 'developpeur']; + var LANGS = [['fr', '/', 'Français'], ['en', '/en/', 'English'], ['de', '/de/', 'Deutsch'], ['it', '/it/', 'Italiano'], ['es', '/es/', 'Español']]; + + var T = { + fr: { + themeH: 'Thème', themes2: [['clair', 'Clair', 'Par défaut.'], ['sombre', 'Sombre', 'Fond foncé, moins de lumière le soir.']], + foot: 'Paramètres d’accessibilité', btn: 'Paramètres', close: 'Fermer', title: 'Paramètres', + newsH: 'Flux News', levelH: 'Niveau de détail', themesH: 'Thèmes', allThemes: 'Tous les thèmes', + levels: { simple: ['Simple', 'Des mots faciles, très court.'], normal: ['Normal', 'Pour tout le monde (par défaut).'], developpeur: ['Développeur', 'Plus de détails techniques.'] }, + themes: ['Audiovisuel', 'Applications', 'Technique et projets', 'Mises à jour du site', 'Météo', 'Minecraft', 'Mind et IA', 'Hub et comptes', 'Vie locale à Lans'], + note: 'Tes choix restent dans ce navigateur. Sans choix : niveau normal, tous les thèmes.', + noStore: 'Ton navigateur ne peut pas mémoriser tes choix : ils valent seulement jusqu’à la fermeture de cette page.', + noneChecked: 'Aucun thème coché : tous les thèmes sont affichés.', + langH: 'Langue', newsLink: 'Voir les news', frOnly: '', + inviteTitle: 'Quel flux veux-tu ?', inviteIntro: 'Choisis le niveau et les thèmes des news. Tu pourras changer plus tard avec le bouton Paramètres.', + ok: 'Valider', later: 'Plus tard' + }, + en: { + themeH: 'Theme', themes2: [['clair', 'Light', 'Default.'], ['sombre', 'Dark', 'Dark background, less light at night.']], + foot: 'Accessibility settings', btn: 'Settings', close: 'Close', title: 'Settings', + newsH: 'News feed', levelH: 'Level of detail', themesH: 'Topics', allThemes: 'All topics', + levels: { simple: ['Simple', 'Easy words, very short.'], normal: ['Normal', 'For everyone (default).'], developpeur: ['Developer', 'More technical details.'] }, + themes: ['Audiovisual', 'Apps', 'Tech and projects', 'Site updates', 'Weather', 'Minecraft', 'Mind and AI', 'Hub and accounts', 'Local life in Lans'], + note: 'Your choices stay in this browser. By default: normal level, all topics.', + noStore: 'Your browser cannot remember your choices: they only last until you close this page.', + noneChecked: 'No topic ticked: all topics are shown.', + langH: 'Language', newsLink: 'See the news', frOnly: 'The News page is in French.', + inviteTitle: 'Which feed do you want?', inviteIntro: 'Choose the level and topics of the news. You can change them later with the Settings button.', + ok: 'Save', later: 'Later' + }, + de: { + themeH: 'Design', themes2: [['clair', 'Hell', 'Standard.'], ['sombre', 'Dunkel', 'Dunkler Hintergrund, weniger Licht am Abend.']], + foot: 'Einstellungen zur Barrierefreiheit', btn: 'Einstellungen', close: 'Schließen', title: 'Einstellungen', + newsH: 'News-Feed', levelH: 'Detailstufe', themesH: 'Themen', allThemes: 'Alle Themen', + levels: { simple: ['Einfach', 'Leichte Wörter, ganz kurz.'], normal: ['Normal', 'Für alle (Standard).'], developpeur: ['Entwickler', 'Mehr technische Details.'] }, + themes: ['Audiovisuell', 'Apps', 'Technik und Projekte', 'Website-Updates', 'Wetter', 'Minecraft', 'Mind und KI', 'Hub und Konten', 'Lokales aus Lans'], + note: 'Deine Auswahl bleibt in diesem Browser. Standard: Stufe Normal, alle Themen.', + noStore: 'Dein Browser kann deine Auswahl nicht speichern: sie gilt nur, bis du diese Seite schließt.', + noneChecked: 'Kein Thema gewählt: Es werden alle Themen angezeigt.', + langH: 'Sprache', newsLink: 'News ansehen', frOnly: 'Die News-Seite ist auf Französisch.', + inviteTitle: 'Welchen Feed möchtest du?', inviteIntro: 'Wähle Stufe und Themen der News. Du kannst sie später über die Schaltfläche Einstellungen ändern.', + ok: 'Speichern', later: 'Später' + }, + it: { + themeH: 'Tema', themes2: [['clair', 'Chiaro', 'Predefinito.'], ['sombre', 'Scuro', 'Sfondo scuro, meno luce la sera.']], + foot: 'Impostazioni di accessibilità', btn: 'Impostazioni', close: 'Chiudi', title: 'Impostazioni', + newsH: 'Feed News', levelH: 'Livello di dettaglio', themesH: 'Temi', allThemes: 'Tutti i temi', + levels: { simple: ['Semplice', 'Parole facili, molto breve.'], normal: ['Normale', 'Per tutti (predefinito).'], developpeur: ['Sviluppatore', 'Più dettagli tecnici.'] }, + themes: ['Audiovisivo', 'App', 'Tecnica e progetti', 'Aggiornamenti del sito', 'Meteo', 'Minecraft', 'Mind e IA', 'Hub e account', 'Vita locale a Lans'], + note: 'Le tue scelte restano in questo browser. Predefinito: livello normale, tutti i temi.', + noStore: 'Il tuo browser non può ricordare le scelte: valgono solo fino alla chiusura di questa pagina.', + noneChecked: 'Nessun tema selezionato: vengono mostrati tutti i temi.', + langH: 'Lingua', newsLink: 'Vedi le news', frOnly: 'La pagina News è in francese.', + inviteTitle: 'Quale feed vuoi?', inviteIntro: 'Scegli il livello e i temi delle news. Potrai cambiarli dopo con il pulsante Impostazioni.', + ok: 'Salva', later: 'Più tardi' + }, + es: { + themeH: 'Tema', themes2: [['clair', 'Claro', 'Por defecto.'], ['sombre', 'Oscuro', 'Fondo oscuro, menos luz por la noche.']], + foot: 'Ajustes de accesibilidad', btn: 'Ajustes', close: 'Cerrar', title: 'Ajustes', + newsH: 'Feed de News', levelH: 'Nivel de detalle', themesH: 'Temas', allThemes: 'Todos los temas', + levels: { simple: ['Simple', 'Palabras fáciles, muy breve.'], normal: ['Normal', 'Para todos (por defecto).'], developpeur: ['Desarrollador', 'Más detalles técnicos.'] }, + themes: ['Audiovisual', 'Apps', 'Técnica y proyectos', 'Novedades del sitio', 'Tiempo', 'Minecraft', 'Mind e IA', 'Hub y cuentas', 'Vida local en Lans'], + note: 'Tus elecciones se quedan en este navegador. Por defecto: nivel normal, todos los temas.', + noStore: 'Tu navegador no puede recordar tus elecciones: solo valen hasta cerrar esta página.', + noneChecked: 'Ningún tema marcado: se muestran todos los temas.', + langH: 'Idioma', newsLink: 'Ver las news', frOnly: 'La página News está en francés.', + inviteTitle: '¿Qué feed quieres?', inviteIntro: 'Elige el nivel y los temas de las news. Podrás cambiarlos luego con el botón Ajustes.', + ok: 'Guardar', later: 'Más tarde' + } + }; + + var lang = String(document.documentElement.getAttribute('lang') || 'fr').slice(0, 2).toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(T, lang)) lang = 'fr'; + var L = T[lang]; + var onNewsPage = document.documentElement.hasAttribute('data-news') || /^\/news(\/|$)/.test(location.pathname); + + /* News a son propre sous-domaine (aperçu LAN : port 8772 ; site : port 8779). Les liens « /news/… » du site + * et « / » ou « /#… » de la page News sont réécrits au clic vers l'autre adresse. */ + var lan = location.port === '8779' || location.port === '8772'; + var NEWS_URL = lan ? location.protocol + '//' + location.hostname + ':8772/' : 'https://news.gastinel.me/'; + var MAIN_URL = lan ? location.protocol + '//' + location.hostname + ':8779/' : 'https://gastinel.me/'; + document.addEventListener('click', function (e) { + var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; + if (!a) return; + var h = a.getAttribute('href'); + if (onNewsPage && (a.hasAttribute('data-main') || h === '/' || h.indexOf('/#') === 0)) a.href = MAIN_URL + h.slice(1); + else if (!onNewsPage && h.indexOf('/news/') === 0) a.href = NEWS_URL + h.slice(6); + }, true); + + /* ---------- Réglages ---------- */ + var storageOk = true; + var state = { level: 'normal', themes: null, asked: false, theme: 'clair' }; + + /* Thème : clé à part, commune à tous les sites Gastinel (« gastinel-theme » = « clair » ou « sombre »). */ + var THEME_KEY = 'gastinel-theme'; + /* Cookie de préférence (même nom) partagé par les sous-domaines de gastinel.me : exempté de consentement + * selon la CNIL (réglage demandé par la personne), durée limitée à moins de 13 mois (390 jours). */ + var ON_GASTINEL = /(^|\.)gastinel\.me$/.test(location.hostname); + function readThemeCookie() { + var m = document.cookie.match(/(?:^|;\s*)gastinel-theme=(clair|sombre)/); + return m ? m[1] : null; + } + function writeThemeCookie(v) { + if (!ON_GASTINEL) return; + document.cookie = THEME_KEY + '=' + v + '; domain=.gastinel.me; path=/; max-age=' + (390 * 86400) + '; SameSite=Lax; Secure'; + } + + function load() { + var c = readThemeCookie(); + if (c) state.theme = c; + else try { if (window.localStorage.getItem(THEME_KEY) === 'sombre') state.theme = 'sombre'; } catch (e) { storageOk = false; } + try { + var raw = window.localStorage.getItem(STORE_KEY); + if (!raw) return; + var p = JSON.parse(raw); + if (p && typeof p === 'object') { + if (LEVEL_IDS.indexOf(p.level) >= 0) state.level = p.level; + if (Array.isArray(p.themes)) { + var list = p.themes.filter(function (t) { return THEME_IDS.indexOf(t) >= 0; }); + state.themes = list.length ? list : null; + } + state.asked = p.asked === true; + } + } catch (e) { storageOk = false; } + } + function probeStorage() { + try { + window.localStorage.setItem('gastinel-probe', '1'); + window.localStorage.removeItem('gastinel-probe'); + } catch (e) { storageOk = false; } + } + function save() { + try { + window.localStorage.setItem(STORE_KEY, JSON.stringify({ level: state.level, themes: state.themes, asked: state.asked })); + window.localStorage.setItem(THEME_KEY, state.theme); + } catch (e) { storageOk = false; } + writeThemeCookie(state.theme); + try { + document.dispatchEvent(new CustomEvent('gastinel:prefs', { detail: { level: state.level, themes: state.themes } })); + } catch (e) { /* vieux navigateur : le composant relira le stockage au prochain chargement */ } + } + + /* ---------- Petits outils DOM ---------- */ + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; + } + var SVGNS = 'http://www.w3.org/2000/svg'; + function gear() { + var s = document.createElementNS(SVGNS, 'svg'); + s.setAttribute('viewBox', '0 0 24 24'); + s.setAttribute('aria-hidden', 'true'); + s.setAttribute('focusable', 'false'); + var p = document.createElementNS(SVGNS, 'path'); + p.setAttribute('d', 'M19.14 12.94c.04-.3.06-.61.06-.94s-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'); + s.appendChild(p); + return s; + } + + var CSS = '' + + '.rg-btn{position:fixed;right:max(14px,env(safe-area-inset-right));bottom:max(14px,env(safe-area-inset-bottom));z-index:9500;width:46px;height:46px;padding:0;border-radius:50%;border:2px solid #242424;background:#fff;color:#242424;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 4px 14px rgba(0,0,0,.22);opacity:.88;transition:opacity .2s,background .2s,color .2s}' + + '.rg-foot{color:#fff;font:inherit;text-decoration:none;cursor:pointer}.rg-foot:hover{text-decoration:underline}.rg-foot:focus-visible{outline:2px solid #fff;outline-offset:2px}' + + '.rg-btn:hover,.rg-btn:focus-visible{opacity:1;background:#242424;color:#fff}' + + '.rg-btn:focus-visible{outline:3px solid #1e4d8b;outline-offset:3px}' + + '.rg-btn svg{width:24px;height:24px;fill:currentColor}' + + '.rg-veil{position:fixed;inset:0;z-index:9600;background:rgba(0,0,0,.4);display:flex;align-items:flex-end;justify-content:flex-end;padding:14px}' + + '.rg-veil[hidden]{display:none}' + + '.rg-dialog{background:#fff;color:#1a1d21;font:16px/1.5 var(--font-sans,Inter,system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif);width:380px;max-width:100%;max-height:calc(100vh - 28px);max-height:calc(100dvh - 28px);overflow-y:auto;border-radius:12px;border:2px solid #242424;box-shadow:0 12px 40px rgba(0,0,0,.35);padding:18px 20px 20px;box-sizing:border-box;text-align:left}' + + '.rg-dialog *{box-sizing:border-box}' + + '.rg-dialog:focus{outline:none}' + + '.rg-top{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:6px}' + + '.rg-h{font-size:1.25rem;font-weight:700;margin:0;line-height:1.3;color:#1a1d21;letter-spacing:0;text-transform:none}' + + '.rg-x{font:inherit;font-size:1.4rem;line-height:1;width:44px;height:44px;border-radius:50%;border:2px solid #242424;background:#fff;color:#242424;cursor:pointer;flex:none;padding:0}' + + '.rg-x:hover{background:#eceef1}' + + '.rg-sec{margin:14px 0 0;padding:14px 0 0;border:0;border-top:1px solid #e5e7eb;min-width:0}' + + '.rg-sec:first-of-type{border-top:0;padding-top:0}' + + '.rg-sh{font-size:1rem;font-weight:700;margin:0 0 8px;padding:0;color:#1a1d21;text-transform:none;letter-spacing:0}' + + '.rg-fs{border:0;margin:0 0 10px;padding:0;min-width:0}' + + '.rg-lg{font-size:.9rem;font-weight:700;color:#4b5563;padding:0;margin:0 0 4px}' + + '.rg-opt{display:flex;align-items:flex-start;gap:10px;padding:8px 6px;min-height:44px;border-radius:8px;cursor:pointer}' + + '.rg-opt:hover{background:#f3f4f6}' + + '.rg-opt input{width:20px;height:20px;margin:2px 0 0;flex:none;accent-color:#242424;cursor:pointer}' + + '.rg-opt input:focus-visible{outline:3px solid #1e4d8b;outline-offset:2px}' + + '.rg-opt span{display:block}.rg-opt small{display:block;color:#4b5563;font-size:.85rem;line-height:1.35}' + + '.rg-note{font-size:.85rem;color:#4b5563;margin:8px 0 0}' + + '.rg-warn{font-size:.85rem;color:#7a4b00;background:#fff4d6;border-left:4px solid #e0b100;padding:8px 10px;border-radius:4px;margin:8px 0 0}' + + '.rg-langs{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:8px}' + + '.rg-langs a{display:inline-flex;align-items:center;min-height:44px;padding:8px 14px;border-radius:999px;border:2px solid #242424;color:#242424;background:#fff;text-decoration:none;font-weight:600;font-size:.95rem}' + + '.rg-langs a:hover{background:#eceef1}' + + '.rg-langs a[aria-current="true"]{background:#242424;color:#fff}' + + '.rg-langs a:focus-visible,.rg-link:focus-visible,.rg-act:focus-visible,.rg-x:focus-visible{outline:3px solid #1e4d8b;outline-offset:3px}' + + '.rg-link{display:inline-block;margin-top:8px;padding:8px 0;color:#1e4d8b;font-weight:600}' + + '.rg-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:16px}' + + '.rg-act{font:inherit;font-weight:700;min-height:44px;padding:9px 20px;border-radius:999px;border:2px solid #242424;background:#fff;color:#242424;cursor:pointer}' + + '.rg-act.rg-primary{background:#242424;color:#fff}' + + '@media(max-width:600px){.rg-veil{padding:0}.rg-dialog{width:100%;border-radius:14px 14px 0 0;max-height:88vh;max-height:88dvh;border-width:2px 0 0}}' + + '@media(prefers-reduced-motion:reduce){.rg-btn{transition:none}}' + + '@media print{.rg-btn,.rg-veil{display:none!important}}' + + 'html.theme-sombre{filter:invert(.92) hue-rotate(180deg);background:#fff}' + + 'html.theme-sombre img,html.theme-sombre video,html.theme-sombre iframe,html.theme-sombre picture,html.theme-sombre .rg-photo,html.theme-sombre [style*="background-image"],html.theme-sombre .leaflet-container{filter:invert(1) hue-rotate(180deg)}' + + 'html.theme-sombre .global-footer,html.theme-sombre .actus-bouton-zone{filter:invert(1) hue-rotate(180deg)}'; + + /* ---------- Panneau ---------- */ + var btn, veil, dialog, opener = null, mode = 'settings', built = false; + var levelInputs = {}, themeInputs = {}, allBtn = null, warnEl = null, noneEl = null; + + function syncForm() { + LEVEL_IDS.forEach(function (id) { levelInputs[id].checked = state.level === id; }); + THEME_IDS.forEach(function (id) { themeInputs[id].checked = !state.themes || state.themes.indexOf(id) >= 0; }); + if (noneEl) noneEl.hidden = true; + } + function readThemes() { + var sel = THEME_IDS.filter(function (id) { return themeInputs[id].checked; }); + if (sel.length === 0) { noneEl.hidden = false; state.themes = null; } + else { noneEl.hidden = true; state.themes = sel.length === THEME_IDS.length ? null : sel; } + } + + function newsSection() { + var sec = el('section', 'rg-sec'); + sec.setAttribute('aria-labelledby', 'rg-news-h'); + var h = el('h3', 'rg-sh', L.newsH); h.id = 'rg-news-h'; + sec.appendChild(h); + + var fs1 = el('fieldset', 'rg-fs'); + fs1.appendChild(el('legend', 'rg-lg', L.levelH)); + LEVEL_IDS.forEach(function (id) { + var lab = el('label', 'rg-opt'); + var inp = el('input'); inp.type = 'radio'; inp.name = 'rg-level'; inp.value = id; + inp.addEventListener('change', function () { if (inp.checked) { state.level = id; save(); } }); + levelInputs[id] = inp; + var tx = el('span'); tx.appendChild(document.createTextNode(L.levels[id][0])); + tx.appendChild(el('small', null, L.levels[id][1])); + lab.appendChild(inp); lab.appendChild(tx); + fs1.appendChild(lab); + }); + sec.appendChild(fs1); + + var fs2 = el('fieldset', 'rg-fs'); + fs2.appendChild(el('legend', 'rg-lg', L.themesH)); + THEME_IDS.forEach(function (id, i) { + var lab = el('label', 'rg-opt'); + var inp = el('input'); inp.type = 'checkbox'; inp.value = id; + inp.addEventListener('change', function () { readThemes(); save(); }); + themeInputs[id] = inp; + lab.appendChild(inp); lab.appendChild(el('span', null, L.themes[i])); + fs2.appendChild(lab); + }); + allBtn = el('button', 'rg-act', L.allThemes); + allBtn.type = 'button'; + allBtn.addEventListener('click', function () { + state.themes = null; syncForm(); save(); + }); + fs2.appendChild(allBtn); + noneEl = el('p', 'rg-note', L.noneChecked); noneEl.hidden = true; noneEl.setAttribute('role', 'status'); + fs2.appendChild(noneEl); + sec.appendChild(fs2); + + sec.appendChild(el('p', 'rg-note', L.note)); + warnEl = el('p', 'rg-warn', L.noStore); warnEl.hidden = storageOk; warnEl.setAttribute('role', 'status'); + sec.appendChild(warnEl); + return sec; + } + + /* Thème : clair par défaut, sombre seulement si la personne le choisit (proposition du 26/10). */ + function applyTheme() { + document.documentElement.classList.toggle('theme-sombre', state.theme === 'sombre'); + if (state.theme !== 'sombre') return; + /* Les photos posées en fond CSS (carrousel, bandeaux) sont remises à l'endroit. */ + Array.prototype.forEach.call(document.querySelectorAll('body *'), function (e) { + if (e.classList.contains('rg-photo') || e.closest('.rg-photo')) return; + var bg = getComputedStyle(e).backgroundImage; + if (bg && bg.indexOf('url(') >= 0) e.classList.add('rg-photo'); + }); + } + function themeSection() { + var sec = el('section', 'rg-sec'); + sec.setAttribute('aria-labelledby', 'rg-theme-h'); + var h = el('h3', 'rg-sh', L.themeH); h.id = 'rg-theme-h'; + sec.appendChild(h); + L.themes2.forEach(function (t) { + var lab = el('label', 'rg-opt'); + var inp = el('input'); inp.type = 'radio'; inp.name = 'rg-theme'; inp.value = t[0]; + inp.checked = state.theme === t[0]; + inp.addEventListener('change', function () { if (inp.checked) { state.theme = t[0]; applyTheme(); save(); } }); + var tx = el('span'); tx.appendChild(document.createTextNode(t[1])); tx.appendChild(el('small', null, t[2])); + lab.appendChild(inp); lab.appendChild(tx); sec.appendChild(lab); + }); + return sec; + } + + function langSection() { + var sec = el('section', 'rg-sec'); + sec.setAttribute('aria-labelledby', 'rg-lang-h'); + var h = el('h3', 'rg-sh', L.langH); h.id = 'rg-lang-h'; + sec.appendChild(h); + var ul = el('ul', 'rg-langs'); + LANGS.forEach(function (l) { + var li = el('li'); + var a = el('a', null, l[2]); + a.href = l[1]; a.setAttribute('hreflang', l[0]); a.setAttribute('lang', l[0]); + if (l[0] === lang) a.setAttribute('aria-current', 'true'); + li.appendChild(a); ul.appendChild(li); + }); + sec.appendChild(ul); + if (L.frOnly) sec.appendChild(el('p', 'rg-note', L.frOnly)); + if (!onNewsPage) { + var a2 = el('a', 'rg-link', L.newsLink); a2.href = '/news/'; + if (lang !== 'fr') a2.setAttribute('lang', 'fr'); + sec.appendChild(a2); + } + return sec; + } + + function build() { + if (built) return; + built = true; + var st = el('style'); st.id = 'rg-css'; st.textContent = CSS; document.head.appendChild(st); + + /* Page News : petit bouton rond en bas à droite. Ailleurs : lien texte dans le pied de page (demande de Théo, 26/10). */ + var foot = onNewsPage ? null : document.querySelector('.footer-bottom'); + if (foot) { + btn = el('a', 'rg-foot', L.foot); + btn.href = '#'; + btn.setAttribute('role', 'button'); + foot.appendChild(document.createTextNode(' | ')); + foot.appendChild(btn); + btn.addEventListener('click', function (e) { e.preventDefault(); openPanel('settings', btn); }); + } else { + btn = el('button', 'rg-btn'); + btn.type = 'button'; + btn.setAttribute('aria-label', L.btn); + btn.setAttribute('title', L.btn); + btn.appendChild(gear()); + btn.addEventListener('click', function () { openPanel('settings', btn); }); + document.body.appendChild(btn); + } + btn.setAttribute('aria-haspopup', 'dialog'); + btn.setAttribute('aria-expanded', 'false'); + + veil = el('div', 'rg-veil'); veil.hidden = true; + veil.addEventListener('mousedown', function (e) { if (e.target === veil) closePanel(); }); + dialog = el('div', 'rg-dialog'); + dialog.setAttribute('role', 'dialog'); + dialog.setAttribute('aria-modal', 'true'); + dialog.setAttribute('aria-labelledby', 'rg-title'); + dialog.tabIndex = -1; + veil.appendChild(dialog); + document.body.appendChild(veil); + } + + /* (Re)construit le contenu du panneau selon le mode : « settings » ou « invite ». */ + function fill() { + dialog.textContent = ''; + levelInputs = {}; themeInputs = {}; + var top = el('div', 'rg-top'); + var h = el('h2', 'rg-h', mode === 'invite' ? L.inviteTitle : (onNewsPage ? L.title : L.foot)); h.id = 'rg-title'; + top.appendChild(h); + var x = el('button', 'rg-x'); x.type = 'button'; x.setAttribute('aria-label', L.close); x.textContent = '×'; + x.addEventListener('click', closePanel); + top.appendChild(x); + dialog.appendChild(top); + if (mode === 'invite') dialog.appendChild(el('p', 'rg-note', L.inviteIntro)); + if (onNewsPage || mode === 'invite') dialog.appendChild(newsSection()); + if (mode === 'invite') { + var act = el('div', 'rg-actions'); + var ok = el('button', 'rg-act rg-primary', L.ok); ok.type = 'button'; + ok.addEventListener('click', closePanel); + var later = el('button', 'rg-act', L.later); later.type = 'button'; + later.addEventListener('click', closePanel); + act.appendChild(ok); act.appendChild(later); + dialog.appendChild(act); + } else { + dialog.appendChild(themeSection()); + /* Sites sans traductions (ex. statistiques) : = thème seulement. */ + if (document.documentElement.getAttribute('data-reglages') !== 'theme') dialog.appendChild(langSection()); + } + if (onNewsPage || mode === 'invite') syncForm(); + } + + function focusables() { + var nodes = dialog.querySelectorAll('a[href],button:not([disabled]),input:not([disabled])'); + return Array.prototype.filter.call(nodes, function (n) { return n.offsetParent !== null || n === document.activeElement; }); + } + + function onKey(e) { + if (veil.hidden) return; + if (e.key === 'Escape' || e.key === 'Esc') { e.preventDefault(); closePanel(); return; } + if (e.key !== 'Tab') return; + var f = focusables(); + if (!f.length) { e.preventDefault(); dialog.focus(); return; } + var first = f[0], last = f[f.length - 1], a = document.activeElement; + if (!dialog.contains(a)) { e.preventDefault(); first.focus(); } + else if (e.shiftKey && (a === first || a === dialog)) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); } + } + + function openPanel(m, from) { + build(); + if (!veil.hidden) return; + mode = m; + opener = from || document.activeElement; + fill(); + veil.hidden = false; + btn.setAttribute('aria-expanded', 'true'); + var target = levelInputs[state.level] || dialog.querySelector('input:checked') || dialog; + target.focus(); + document.addEventListener('keydown', onKey, true); + } + + function closePanel() { + if (veil.hidden) return; + var wasInvite = mode === 'invite'; + veil.hidden = true; + btn.setAttribute('aria-expanded', 'false'); + document.removeEventListener('keydown', onKey, true); + if (wasInvite || !state.asked) { state.asked = true; save(); } + var back = opener && opener !== document.body && document.contains(opener) ? opener : btn; + try { back.focus(); } catch (e) { /* rien */ } + opener = null; + } + + /* Le composant News peut demander l'ouverture (bouton « Changer mon flux »). */ + document.addEventListener('gastinel:open-reglages', function () { build(); openPanel('settings', document.activeElement); }); + + function start() { + probeStorage(); + load(); + applyTheme(); + window.addEventListener('load', applyTheme); + build(); + if (onNewsPage && storageOk && !state.asked) { + /* première visite de /news/ : l'invite s'ouvre une fois, puis se range */ + openPanel('invite', null); + } + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start(); +})(); diff --git a/tools/add-news.js b/tools/add-news.js new file mode 100644 index 0000000..97d4c35 --- /dev/null +++ b/tools/add-news.js @@ -0,0 +1,137 @@ +#!/usr/bin/env node +/** + * tools/add-news.js : ajoute une entrée à data/actus.json, après validation. + * + * Chaque entrée porte des thèmes, un texte court (pour les listes) et une version par niveau : + * normal (obligatoire), simple et developpeur (facultatifs, repli sur « normal »). + * + * Exemple : + * node tools/add-news.js --themes technique,applications \ + * --title "Nouvelle version de GWS" --text "Le logiciel sait maintenant exporter en PDF." \ + * --simple-text "Tu peux maintenant enregistrer tes résultats en PDF." \ + * --dev-title "GWS : export PDF" --dev-text "Ajout d'un export PDF des rapports." \ + * --short-title "GWS exporte en PDF" --short-text "Une nouveauté pour garder tes résultats." \ + * --link /gws/ [--date 2026-11-02] [--image /assets/img/photo.webp --image-alt "Description"] [--dry-run] + * + * Thèmes : audiovisuel, applications, technique, site, meteo, minecraft, mind, hub, vie-locale. + * Zéro dépendance. N'écrit rien si une règle n'est pas respectée. + */ +'use strict'; +const fs = require('fs'); +const path = require('path'); + +const FILE = path.resolve(__dirname, '..', 'data', 'actus.json'); +const THEMES = ['audiovisuel', 'applications', 'technique', 'site', 'meteo', 'minecraft', 'mind', 'hub', 'vie-locale']; +const LIMITS = { title: 120, text: 600, shortTitle: 80, shortText: 160 }; + +function parseArgs(argv) { + const out = {}; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (!a.startsWith('--')) throw new Error(`Argument inattendu : ${a}`); + const key = a.slice(2); + if (key === 'dry-run' || key === 'help') { out[key] = true; continue; } + const v = argv[++i]; + if (v === undefined || v.startsWith('--')) throw new Error(`Valeur manquante pour --${key}`); + out[key] = v; + } + return out; +} + +function todayLocal() { + const d = new Date(); + const p = (n) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; +} + +function validDate(s) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false; + const d = new Date(s + 'T12:00:00Z'); + return !isNaN(d) && d.toISOString().slice(0, 10) === s; +} + +function validUrl(u) { return /^\/(?!\/)\S*$/.test(u) || /^https:\/\/\S+$/i.test(u); } + +/* Première phrase, coupée à n caractères au plus. */ +function firstSentence(t, n) { + const m = t.match(/^.*?[.!?](\s|$)/); + let s = (m ? m[0] : t).trim(); + if (s.length > n) s = s.slice(0, n - 1).replace(/\s+\S*$/, '') + '…'; + return s; +} + +function checkLen(errors, label, v, max) { + if (v.length > max) errors.push(`${label} : ${max} caractères maximum (${v.length})`); +} + +function main() { + const a = parseArgs(process.argv.slice(2)); + if (a.help) { + console.log('Usage : node tools/add-news.js --themes t1,t2 --title "..." --text "..." [--simple-title ".." --simple-text ".."] [--dev-title ".." --dev-text ".."] [--short-title ".." --short-text ".."] [--link URL] [--image URL --image-alt "..."] [--date AAAA-MM-JJ] [--dry-run]\nThèmes : ' + THEMES.join(', ')); + return; + } + const errors = []; + const date = a.date || todayLocal(); + const themes = (a.themes || '').split(',').map((s) => s.trim()).filter(Boolean); + const title = (a.title || '').trim(); + const text = (a.text || '').trim(); + + if (!themes.length) errors.push('--themes est obligatoire (au moins un thème)'); + themes.forEach((t) => { if (!THEMES.includes(t)) errors.push(`thème inconnu « ${t} » (valides : ${THEMES.join(', ')})`); }); + if (new Set(themes).size !== themes.length) errors.push('--themes : thème répété'); + if (!title) errors.push('--title (niveau normal) est obligatoire'); + else checkLen(errors, '--title', title, LIMITS.title); + if (!text) errors.push('--text (niveau normal) est obligatoire'); + else checkLen(errors, '--text', text, LIMITS.text); + + const levels = { normal: { title, text } }; + [['simple', 'simple'], ['developpeur', 'dev']].forEach(([lvl, p]) => { + const t = (a[p + '-title'] || '').trim(); + const x = (a[p + '-text'] || '').trim(); + if (!t && !x) return; + if (!x) { errors.push(`--${p}-text est obligatoire si --${p}-title est donné`); return; } + checkLen(errors, `--${p}-title`, t, LIMITS.title); + checkLen(errors, `--${p}-text`, x, LIMITS.text); + levels[lvl] = { title: t || title, text: x }; + }); + + const sTitle = (a['short-title'] || '').trim() || title; + const sText = (a['short-text'] || '').trim() || firstSentence(text, LIMITS.shortText); + checkLen(errors, '--short-title', sTitle, LIMITS.shortTitle); + checkLen(errors, '--short-text', sText, LIMITS.shortText); + + if (!validDate(date)) errors.push('--date doit être une vraie date au format AAAA-MM-JJ'); + if (a.link && !validUrl(a.link)) errors.push('--link doit commencer par / (page du site) ou https://'); + if (a.image && !validUrl(a.image)) errors.push('--image doit commencer par / ou https://'); + if (a.image && !a['image-alt']) errors.push('--image-alt est obligatoire quand il y a une image (accessibilité)'); + if (errors.length) { console.error('Entrée refusée :\n- ' + errors.join('\n- ')); process.exit(1); } + + let list = []; + if (fs.existsSync(FILE)) { + try { list = JSON.parse(fs.readFileSync(FILE, 'utf8')); } + catch (e) { console.error(`${FILE} n'est pas un JSON valide : ${e.message}`); process.exit(1); } + if (!Array.isArray(list)) { console.error('actus.json doit contenir un tableau.'); process.exit(1); } + } + if (list.some((n) => n && n.date === date && n.levels && n.levels.normal && n.levels.normal.title === title)) { + console.error('Une news avec le même titre et la même date existe déjà : rien écrit.'); + process.exit(1); + } + + const id = list.reduce((m, n) => Math.max(m, Number(n && n.id) || 0), 0) + 1; + const entry = { id, date, themes, short: { title: sTitle, text: sText }, levels }; + if (a.link) entry.link = a.link; + if (a.image) { entry.image = a.image; entry.imageAlt = a['image-alt']; } + + list.unshift(entry); + list.sort((x, y) => (x.date === y.date ? y.id - x.id : x.date < y.date ? 1 : -1)); + const out = JSON.stringify(list, null, 2) + '\n'; + JSON.parse(out); // contrôle final + + if (a['dry-run']) { console.log('[essai] rien écrit. Entrée :\n' + JSON.stringify(entry, null, 2)); return; } + fs.copyFileSync(FILE, FILE + '.bak'); + fs.writeFileSync(FILE, out, 'utf8'); + console.log(`News n°${id} ajoutée (${date}, thèmes : ${themes.join(', ')}). Sauvegarde : data/actus.json.bak`); + console.log('Suite : node tools/build.js puis node tools/deploy.js (lancés par toi).'); +} + +try { main(); } catch (e) { console.error(e.message); process.exit(1); } diff --git a/tools/build.js b/tools/build.js index d1d75a0..1ab8c2c 100644 --- a/tools/build.js +++ b/tools/build.js @@ -39,7 +39,10 @@ const DIST = path.join(ROOT, 'dist'); const BUILD_DIR = 'assets/build'; // Sections retirées du HTML initial (lourdes, peu utiles au référencement). const FRAGMENTS = ['termes']; -const COPY_AS_IS =['llms.txt', 'robots.txt', 'sitemap.xml', 'data/news.json']; +const COPY_AS_IS =['llms.txt', 'robots.txt', 'sitemap.xml', 'data/news.json', 'data/actus.json', + // Section News : page de liste, traductions et scripts (actus, réglages/thème, newsletter). + 'news/index.html', 'news/en/index.html', 'news/de/index.html', 'news/it/index.html', 'news/es/index.html', + 'news/actus.js', 'news/reglages.js', 'news/newsletter.js']; const COMPRESSIBLE = new Set(['.html', '.css', '.js', '.json', '.txt', '.xml', '.svg']); const hash = (buf) => crypto.createHash('sha256').update(buf).digest('hex').slice(0, 10);