Repris des copies site-principal-news et site-principal-reglages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lignes
13 KiB
JavaScript
183 lignes
13 KiB
JavaScript
/* 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();
|
||
})();
|