/* 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(); })();