Files
courrier/app/static/app.js
T

664 lines
46 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Courrier : interface v1 (lecture seule). Tout le texte passe par textContent, aucun balisage injecté. */
(function () {
'use strict';
var TZ = 'Africa/Tunis';
var API = '/api/v1';
var NS = 'http://www.w3.org/2000/svg';
var ICONES = {
tri: 'M22 12h-6l-2 3h-4l-2-3H2|M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z',
categories: 'M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z|M7.5 7.5h.01',
regles: 'M3 6h18|M7 12h10|M10 18h4',
recherche: 'm21 21-4.34-4.34|M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16',
courses: 'M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z|M12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6',
suivi: 'M12 6v6l4 2|M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
pj: 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48',
groupes: 'M3 7h7v7H3z|M14 7h7v7h-7z|M3 17h18',
telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
};
var NAV = [
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['regles', 'Règles', true],
['recherche', 'Recherche', false], ['courses', 'Courses pour Tunis', false], ['suivi', 'Suivi des demandes', false], ['pj', 'Pièces jointes', false]
];
var BIENTOT = {
recherche: ['Recherche', 'Retrouver un mail par expéditeur, objet ou date, dans tout le courrier lu.'],
courses: ['Courses pour Tunis', 'Préparer les courses à partir des mails classés « Tunis ».'],
suivi: ['Suivi des demandes', 'Suivre les demandes envoyées et celles qui attendent une réponse.'],
pj: ['Pièces jointes', 'Lister et rechercher les pièces jointes des mails.']
};
var COULEUR_NOM = { 'Tunis': 1, 'Demande FB': 2, 'CI': 3, 'Câbles': 4, 'Sans objet': 5, 'À classer': 0 };
var SYSTEME = 'À classer';
var S = { chargeA: 0, chargeJour: '', vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '', groupe: { jours: 7, cat: null, etq: null, mails: [], etat: 'chargement' } };
/* ---------- Utilitaires ---------- */
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
function d2(n) { return (n < 10 ? '0' : '') + n; }
function dateUTC(s) { var p = s.split('-'); return new Date(Date.UTC(+p[0], +p[1] - 1, +p[2], 12)); }
function versISO(d) { return d.getUTCFullYear() + '-' + d2(d.getUTCMonth() + 1) + '-' + d2(d.getUTCDate()); }
function fr(s) { var p = s.split('-'); return p[2] + '/' + p[1] + '/' + p[0]; }
function nomJour(s) { var n = new Intl.DateTimeFormat('fr-FR', { weekday: 'long', timeZone: 'UTC' }).format(dateUTC(s)); return n.charAt(0).toUpperCase() + n.slice(1); }
function heureTunis(v) {
if (!v) return '--:--';
var d = new Date(v);
if (isNaN(d.getTime())) { var m = String(v).match(/(\d{2}):(\d{2})/); return m ? m[1] + ':' + m[2] : '--:--'; }
return new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: TZ }).format(d);
}
function couleur(nom, id) {
if (Object.prototype.hasOwnProperty.call(COULEUR_NOM, nom)) return COULEUR_NOM[nom];
return 6 + ((id || 0) % 3);
}
function h(tag, attrs) {
var el = document.createElement(tag);
if (attrs) for (var k in attrs) {
var v = attrs[k];
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'text') el.textContent = v;
else if (k.slice(0, 2) === 'on') el.addEventListener(k.slice(2), v);
else el.setAttribute(k, v === true ? '' : v);
}
for (var i = 2; i < arguments.length; i++) {
var c = arguments[i];
if (c === null || c === undefined || c === false) continue;
el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
}
return el;
}
function icone(cle, taille) {
var svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('fill', 'none'); svg.setAttribute('stroke', 'currentColor');
svg.setAttribute('stroke-width', '2'); svg.setAttribute('stroke-linecap', 'round'); svg.setAttribute('stroke-linejoin', 'round');
svg.setAttribute('aria-hidden', 'true');
if (taille) { svg.setAttribute('width', taille); svg.setAttribute('height', taille); }
ICONES[cle].split('|').forEach(function (d) { var p = document.createElementNS(NS, 'path'); p.setAttribute('d', d); svg.appendChild(p); });
return svg;
}
function pastille(c, extra) { return h('span', { class: 'pt c' + c + (extra ? ' ' + extra : ''), 'aria-hidden': 'true' }); }
function annoncer(t) { var a = document.getElementById('annonce'); a.textContent = ''; setTimeout(function () { a.textContent = t; }, 30); }
/* ---------- API ---------- */
function api(chemin, opts) {
opts = opts || {};
var init = { method: opts.method || 'GET', credentials: 'same-origin', redirect: 'manual', headers: { 'Accept': 'application/json' } };
if (opts.body !== undefined) { init.headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(opts.body); }
return fetch(API + chemin, init).then(function (r) {
if (r.type === 'opaqueredirect' || r.status === 401 || r.status === 403) { sessionExpiree(); throw new Error('session'); }
if (!r.ok) throw new Error('http ' + r.status);
var ct = r.headers.get('content-type') || '';
if (ct.indexOf('application/json') === -1) { sessionExpiree(); throw new Error('session'); }
return r.json();
});
}
/* ---------- Données ---------- */
function nomExp(brut) {
var x = String(brut || '').match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);
if (!x) return brut || '(expéditeur inconnu)';
return x[1].trim() || x[2];
}
function normaliser(m) {
var c = m.classement || m;
var cat = c.categorie || SYSTEME;
return {
id: m.message_id, exp: nomExp(m.expediteur || c.expediteur || ''), expBrut: m.expediteur || c.expediteur || '', objet: m.objet || c.objet || '',
date: m.date || c.date_mail || '', cat: cat, source: c.source || 'regle', traite: !!c.traite, etiquettes: m.etiquettes || []
};
}
function chargerCats() {
return api('/categories').then(function (r) {
var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name }; });
l.sort(function (a, b) { return (a.nom === SYSTEME) - (b.nom === SYSTEME) || a.id - b.id; });
S.cats = l;
});
}
function chargerMails() {
S.etat = 'chargement'; S.miroirErreur = false; rendre();
var jour = S.jour;
return Promise.all([chargerCats(), api('/mails?date=' + jour + '&n=200')]).then(function (rs) {
if (jour !== S.jour) return;
var r = rs[1];
S.miroirErreur = !!r.miroir_erreur;
S.mails = (r.mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
S.etat = 'ok'; S.majHeure = heureTunis(new Date().toISOString()); S.chargeA = Date.now(); S.chargeJour = jour;
rendre();
}).catch(function (e) { if (e.message === 'session') return; if (jour !== S.jour) return; S.etat = 'erreur'; rendre(); });
}
function chargerGroupe() {
var G = S.groupe, jours = G.jours;
G.etat = 'chargement'; rendre();
return Promise.all([chargerCats(), api('/mails/periode?jours=' + jours)]).then(function (rs) {
if (jours !== G.jours) return;
G.mails = (rs[1].mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
G.miroirErreur = !!rs[1].miroir_erreur; G.etat = 'ok'; rendre();
}).catch(function (e) { if (e.message === 'session') return; if (jours !== G.jours) return; G.etat = 'erreur'; rendre(); });
}
function chargerRegles() {
S.reglesEtat = 'chargement'; rendre();
return Promise.all([chargerCats(), api('/regles')]).then(function (rs) {
S.regles = rs[1].regles || []; S.reglesEtat = 'ok'; rendre();
}).catch(function (e) { if (e.message === 'session') return; S.reglesEtat = 'erreur'; rendre(); });
}
/* ---------- Actions ---------- */
function flash(t) { S.notif = t; rendre(); annoncer(t); clearTimeout(flash.t); flash.t = setTimeout(function () { S.notif = null; rendre(); }, 5000); }
function changerJour(delta) {
var d = dateUTC(S.jour); d.setUTCDate(d.getUTCDate() + delta); var j = versISO(d);
if (j > auj()) return;
S.jour = j; S.filtre = null; S.banniere = null; chargerMails(); annoncer(nomJour(j) + ' ' + fr(j));
}
function allerA(vue) {
S.vue = vue; S.banniere = null;
if (vue === 'tri' || vue === 'categories') {
if (S.etat === 'ok' && S.chargeJour === S.jour && Date.now() - S.chargeA < 30000) rendre(); else chargerMails();
}
else if (vue === 'groupes') chargerGroupe();
else if (vue === 'regles') chargerRegles();
else rendre();
document.getElementById('principal').focus();
}
function basculerTraite(m, val) {
var avant = m.traite; m.traite = val; rendre();
api('/classements/' + encodeURIComponent(m.id) + '/traite', { method: 'PATCH', body: { traite: val } }).catch(function (e) {
if (e.message === 'session') return; m.traite = avant; rendre(); flash('Impossible d\'enregistrer le statut « traité ». Réessayez.');
});
}
function corriger(m, cat) {
var avant = { cat: m.cat, source: m.source };
m.cat = cat; m.source = 'manuel'; S.banniere = null; rendre();
api('/classements/' + encodeURIComponent(m.id), { method: 'POST', body: { categorie: cat, mail_info: { message_id: m.id, expediteur: m.expBrut || m.exp, objet: m.objet, date: m.date, etiquettes: m.etiquettes } } })
.then(function (r) {
var rp = r.regle_proposee;
if (rp && rp.id) {
var autres = (S.vue === 'groupes' ? S.groupe.mails : S.mails).filter(function (x) { return x.exp === m.exp && x.id !== m.id && x.source !== 'manuel' && x.cat !== cat; }).length;
S.banniere = { id: rp.id, exp: m.exp, cat: cat, autres: autres }; rendre();
}
}).catch(function (e) { if (e.message === 'session') return; m.cat = avant.cat; m.source = avant.source; rendre(); flash('La correction n\'a pas été enregistrée. Réessayez.'); });
}
function confirmerRegle() {
var b = S.banniere; if (!b) return;
api('/regles/' + b.id + '/confirmer', { method: 'POST' }).then(function () { S.banniere = null; flash('Règle créée : ' + b.exp + ' → ' + b.cat + '.'); return chargerMails(); })
.catch(function (e) { if (e.message !== 'session') flash('La règle n\'a pas pu être créée. Réessayez.'); });
}
function ignorerRegle() {
var b = S.banniere; S.banniere = null; rendre();
if (b) api('/regles/' + b.id, { method: 'DELETE' }).catch(function () {});
}
function basculerRegle(r) {
var req = r.statut === 'active' ? api('/regles/' + r.id, { method: 'PUT', body: { statut: 'proposee' } }) : api('/regles/' + r.id + '/confirmer', { method: 'POST' });
req.then(function () { return chargerRegles(); }).then(function () { annoncer(r.statut === 'active' ? 'Règle désactivée' : 'Règle activée'); })
.catch(function (e) { if (e.message !== 'session') flash('La règle n\'a pas pu être modifiée. Réessayez.'); });
}
/* ---------- Dialogues ---------- */
var dialogue = null;
function ouvrir(construire) {
fermer(true);
var retour = document.activeElement;
var voile = h('div', { class: 'voile leger' });
var boite = construire(function () { fermer(); });
voile.appendChild(boite);
document.getElementById('calque').appendChild(voile);
document.getElementById('app').setAttribute('inert', '');
dialogue = { voile: voile, retour: retour, etiquette: retour && retour.getAttribute ? retour.getAttribute('aria-label') : null };
var premier = boite.querySelector('[data-focus]') || boite.querySelector('input,button');
if (premier) premier.focus();
voile.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { e.preventDefault(); fermer(); return; }
if (e.key === 'Tab') {
var f = boite.querySelectorAll('button:not([hidden]),input,select,[href],summary,[tabindex="0"]'); if (!f.length) return;
var a = f[0], z = f[f.length - 1];
if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
}
});
return boite;
}
function fermer(sansRetour) {
if (!dialogue) return;
dialogue.voile.remove(); document.getElementById('app').removeAttribute('inert');
var r = dialogue.retour, et = dialogue.etiquette; dialogue = null;
if (sansRetour) return;
if (r && !document.body.contains(r) && et) r = document.querySelector('[aria-label="' + et.replace(/"/g, '\\"') + '"]');
if (r && document.body.contains(r)) r.focus();
}
function dialogueCategorie(cat) {
var nouveau = !cat, systeme = cat && cat.nom === SYSTEME;
ouvrir(function (clore) {
var champ = h('input', { id: 'cat-nom', type: 'text', maxlength: '100', 'data-focus': '', autocomplete: 'off', value: cat ? cat.nom : '' });
if (systeme) { champ.setAttribute('readonly', ''); }
var err = h('div', { class: 'err', role: 'alert' });
function enregistrer() {
var nom = champ.value.trim();
if (!nom) { err.textContent = 'Saisissez un nom de catégorie.'; champ.focus(); return; }
if (S.cats.some(function (c) { return c.nom.toLowerCase() === nom.toLowerCase() && (!cat || c.id !== cat.id); })) { err.textContent = 'Cette catégorie existe déjà.'; champ.focus(); return; }
var req = nouveau ? api('/categories', { method: 'POST', body: { name: nom } }) : api('/categories/' + cat.id, { method: 'PUT', body: { name: nom } });
req.then(function () { clore(); return chargerMails(); }).then(function () { flash(nouveau ? 'Catégorie ajoutée.' : 'Catégorie renommée.'); })
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Enregistrement impossible. Réessayez.'; });
}
champ.addEventListener('keydown', function (e) { if (e.key === 'Enter' && !systeme) { e.preventDefault(); enregistrer(); } });
var acts = h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: clore }, 'Annuler'),
systeme ? null : h('button', { type: 'button', class: 'btn-plein', onclick: enregistrer }, nouveau ? 'Ajouter' : 'Enregistrer'));
var pied = null;
if (cat && !systeme) pied = h('div', { class: 'pave' }, h('button', { type: 'button', class: 'btn-danger-ligne', onclick: function () { clore(); dialogueSuppression(cat); } }, 'Supprimer la catégorie'));
return h('section', { class: 'boite', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'dlg-t' },
h('h2', { id: 'dlg-t' }, nouveau ? 'Nouvelle catégorie' : systeme ? SYSTEME : 'Modifier la catégorie'),
systeme ? h('p', null, '« À classer » reçoit les mails qu\'aucune règle ne reconnaît. Elle ne peut être ni renommée ni supprimée.') : null,
h('div', { class: 'champ' }, h('label', { for: 'cat-nom' }, 'Nom'), champ, err), acts, pied);
});
}
function dialogueSuppression(cat) {
ouvrir(function (clore) {
var err = h('div', { class: 'err', role: 'alert' });
return h('section', { class: 'boite', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'sup-t', 'aria-describedby': 'sup-p' },
h('h2', { id: 'sup-t' }, 'Supprimer « ' + cat.nom + ' » ?'),
h('p', { id: 'sup-p' }, 'La catégorie disparaît de la liste. Ses mails repassent dans « À classer » et ses règles sont supprimées. Votre messagerie n\'est pas modifiée.'),
err,
h('div', { class: 'acts' },
h('button', { type: 'button', class: 'btn-ligne', 'data-focus': '', onclick: clore }, 'Annuler'),
h('button', { type: 'button', class: 'btn-danger', onclick: function () {
api('/categories/' + cat.id, { method: 'DELETE' }).then(function () { clore(); return chargerMails(); }).then(function () { flash('Catégorie supprimée.'); })
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Suppression impossible. Réessayez.'; });
} }, 'Supprimer')));
});
}
function sessionExpiree() {
if (document.getElementById('sess')) return;
fermer(true);
var btn = h('button', { type: 'button', class: 'btn-plein', id: 'sess-b', 'data-focus': '', onclick: function () { location.reload(); } }, 'Se reconnecter');
var voile = h('div', { class: 'voile', id: 'sess' }, h('section', { class: 'boite', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'sess-t' },
h('h2', { id: 'sess-t' }, 'Session expirée'),
h('p', null, 'La connexion à la messagerie a pris fin. Vos corrections et vos règles sont conservées.'), btn));
document.getElementById('calque').appendChild(voile);
document.getElementById('app').setAttribute('inert', '');
btn.focus();
voile.addEventListener('keydown', function (e) { if (e.key === 'Tab') { e.preventDefault(); btn.focus(); } });
}
/* ---------- Rendu ---------- */
function rendreNav() {
var bureau = document.getElementById('nav-bureau'), mobile = document.getElementById('nav-mobile');
bureau.textContent = ''; mobile.textContent = '';
function bouton(n) {
return h('button', { type: 'button', class: 'nav-btn', 'aria-current': S.vue === n[0] ? 'page' : null, onclick: function () { allerA(n[0]); } }, icone(n[0]), h('span', null, n[1]));
}
var liste = h('div', { class: 'nav-liste' });
NAV.forEach(function (n, i) {
if (i === 4) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
liste.appendChild(bouton(n));
if (n[2]) mobile.appendChild(bouton(n));
});
bureau.appendChild(h('div', { class: 'marque' }, h('b', null, 'Courrier'), h('span', null, 'Lecture seule')));
bureau.appendChild(liste);
bureau.appendChild(h('div', { class: 'pied-nyora' }, 'Nyora'));
}
function enteteJour() {
var estAuj = S.jour === auj();
return h('header', { class: 'entete' },
h('div', null, h('h1', null, 'Tri du jour'), h('div', { class: 'maj' }, estAuj ? 'Dernière mise à jour à ' + (S.majHeure || '--:--') + ' · heure de Tunis' : 'Journée close')),
h('div', { class: 'jour' },
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Jour précédent', onclick: function () { changerJour(-1); } }, icone('gauche')),
h('div', { class: 'jour-carte' }, h('span', null, nomJour(S.jour)), h('span', { class: 'num' }, fr(S.jour))),
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Jour suivant', disabled: estAuj, onclick: function () { changerJour(1); } }, icone('droite')),
estAuj ? null : h('button', { type: 'button', class: 'btn-lien', onclick: function () { S.jour = auj(); S.filtre = null; S.banniere = null; chargerMails(); } }, 'Aujourd\'hui')));
}
function selecteur(m) {
var c = S.cats.find(function (x) { return x.nom === m.cat; });
var sel = h('select', { 'aria-label': 'Catégorie : ' + m.exp + ', ' + (m.objet || 'sans objet'), onchange: function (e) { corriger(m, e.target.value); } });
var noms = S.cats.map(function (x) { return x.nom; });
if (noms.indexOf(m.cat) === -1) noms.push(m.cat);
noms.forEach(function (n) { var o = h('option', { value: n }, n); if (n === m.cat) o.selected = true; sel.appendChild(o); });
return h('div', { class: 'sel' }, pastille(couleur(m.cat, c && c.id)), sel, h('span', { class: 'chev' }, icone('bas')));
}
/* ---------- Lecture d'un mail (texte seul, lecture seule) ---------- */
var RUPT_FORT = /^\s*(?:-{3,}\s*(?:Original Message|Message d.origine)|Le\s.{5,140}\sa\s+écrit\s?:|On\s.{5,140}\swrote:)/i;
var RUPT_ENTETE = /^\s*(?:De|From)\s?:/i;
var SUITE_ENTETE = /^\s*(?:Envoy[ée]|Sent|Date|Objet|Subject|À|To)\s?:/i;
var URL_RE = /(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?])/g;
function debutHistorique(l) {
for (var i = 1; i < l.length; i++) {
if (RUPT_FORT.test(l[i])) return i;
if (RUPT_ENTETE.test(l[i])) { for (var k = i + 1; k <= i + 4 && k < l.length; k++) if (SUITE_ENTETE.test(l[k])) return i; }
}
return -1;
}
function avecLiens(el, ligne) {
ligne.split(URL_RE).forEach(function (t, i) {
if (!t) return;
if (i % 2 === 1) el.appendChild(h('a', { href: t, target: '_blank', rel: 'noopener noreferrer nofollow', text: t }));
else el.appendChild(document.createTextNode(t));
});
}
function blocsTexte(texte) {
var sortie = h('div', { class: 'lect-texte' }), para = [], cit = false;
function vider() {
if (!para.length) return;
var el = h(cit ? 'blockquote' : 'p');
para.forEach(function (l, i) { if (i) el.appendChild(h('br')); avecLiens(el, l); });
sortie.appendChild(el); para = [];
}
texte.split('\n').forEach(function (l) {
if (!l.trim()) { vider(); return; }
var estCit = /^\s*>/.test(l);
if (estCit !== cit) vider();
cit = estCit;
para.push(estCit ? l.replace(/^(\s*>)+\s?/, '') : l);
});
vider();
return sortie;
}
function decouperAdresses(s) { return String(s || '').split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (x) { return x.trim(); }).filter(Boolean); }
function pastilleAdresse(a) {
var m = a.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/), nom = m ? m[1].trim() : '', adr = m ? m[2].trim() : a.trim();
return h('span', { class: 'qui' }, nom ? h('span', { class: 'nom', text: nom }) : null, nom ? ' ' : null, h('span', { class: nom ? 'adr' : 'nom', text: nom ? '<' + adr + '>' : adr }));
}
function listeAdresses(s) {
var l = decouperAdresses(s);
if (!l.length) return null;
var dd = h('dd', { class: 'adrs' });
l.forEach(function (a, i) { var e = pastilleAdresse(a); if (i >= 3) e.setAttribute('hidden', ''); dd.appendChild(e); });
if (l.length > 3) {
var b = h('button', { type: 'button', class: 'btn-petit plus' }, '+ ' + (l.length - 3) + (l.length - 3 > 1 ? ' autres' : ' autre'));
b.addEventListener('click', function () {
dd.querySelectorAll('[hidden]').forEach(function (x) { x.removeAttribute('hidden'); }); b.remove();
var z = document.querySelector('.lect-scroll'); if (z) z.focus();
});
dd.appendChild(b);
}
return dd;
}
function tailleLisible(n) {
n = Number(n) || 0;
if (n < 1024) return n + ' o';
if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0).replace('.', ',') + ' Ko';
return (n / 1048576).toFixed(1).replace('.', ',') + ' Mo';
}
function dateLongue(v) {
var iso = String(v || '').slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return String(v || '');
return nomJour(iso).toLowerCase() + ' ' + fr(iso) + ' à ' + heureTunis(v);
}
function estSignature(p) {
return /^image\//.test(p.type || '') && Number(p.taille) < 20480 && !p.bloquee;
}
function telechargerPiece(id, p, bt) {
bt.disabled = true; annoncer('Téléchargement de ' + p.nom + ' en cours');
fetch(API + '/mail/piece?id=' + encodeURIComponent(id) + '&nom=' + encodeURIComponent(p.nom), { credentials: 'same-origin', redirect: 'manual' })
.then(function (rep) {
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
if (rep.status === 403) throw new Error('Ce type de fichier est bloqué par sécurité.');
if (rep.status === 413) throw new Error('Pièce jointe trop volumineuse (25 Mo maximum).');
if (!rep.ok) throw new Error('Pièce jointe indisponible pour le moment.');
return rep.blob();
})
.then(function (blob) {
var url = URL.createObjectURL(blob), a = document.createElement('a');
a.href = url; a.download = p.nom; document.body.appendChild(a); a.click(); a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
annoncer(p.nom + ' téléchargé');
})
.catch(function (e) { if (e.message !== 'session') annoncer(e.message); })
.then(function () { bt.disabled = false; });
}
function afficherMail(cont, m, r, c) {
var badges = h('div', { class: 'lect-badges' }, h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat));
(m.etiquettes || []).forEach(function (t) { badges.appendChild(h('span', { class: 'etq', text: t })); });
var meta = h('dl', { class: 'lect-meta' });
function ligne(lib, dd) { if (!dd) return; meta.appendChild(h('dt', { text: lib })); meta.appendChild(dd); }
ligne('De', listeAdresses(r.de || m.expBrut)); ligne('À', listeAdresses(r.a)); ligne('Cc', listeAdresses(r.cc));
ligne('Date', h('dd', { text: dateLongue(m.date || r.date) }));
var lignes = String(r.corps || '').replace(/\r\n?/g, '\n').replace(/ /g, ' ').split('\n');
var cut = debutHistorique(lignes), principal = lignes, histo = null;
if (cut > 0) {
principal = lignes.slice(0, cut); histo = lignes.slice(cut);
while (principal.length && /^[\s_\-=]*$/.test(principal[principal.length - 1])) principal.pop();
}
var corps = principal.join('\n').trim() ? blocsTexte(principal.join('\n')) : h('p', { class: 'lect-vide', text: 'Ce mail ne contient pas de texte à afficher.' });
cont.appendChild(badges); cont.appendChild(meta); cont.appendChild(corps);
if (histo && histo.join('\n').trim()) {
cont.appendChild(h('details', { class: 'lect-histo' }, h('summary', null, 'Afficher l\'historique de la conversation'), blocsTexte(histo.join('\n'))));
}
if (r.tronque) cont.appendChild(h('p', { class: 'lect-note', text: 'Le texte est très long : seul le début est affiché.' }));
var pj = r.pieces_jointes || [];
var signature = pj.filter(estSignature), utiles = pj.filter(function (p) { return !estSignature(p); });
function extDe(p) { var e = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; return e && e.length <= 5 ? e + ' · ' : ''; }
if (utiles.length) {
var ul = h('ul');
utiles.forEach(function (p) {
var action;
if (p.bloquee) action = h('span', { class: 'info bloquee', text: 'Bloquée par sécurité' });
else {
var bt = h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Télécharger ' + p.nom, title: 'Télécharger' }, icone('telecharger'));
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
action = bt;
}
ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }),
h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action));
});
cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + utiles.length + ')' }), ul));
}
if (signature.length) {
var us = h('ul');
signature.forEach(function (p) { us.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), h('span', { class: 'info', text: tailleLisible(p.taille) }))); });
cont.appendChild(h('details', { class: 'lect-histo lect-sig' }, h('summary', null, 'Images intégrées au message (' + signature.length + ')'), us));
}
cont.appendChild(h('p', { class: 'lect-note', text: 'Lecture seule : le mail n\'est pas modifié dans votre messagerie.' }));
}
function lireMail(m) {
var c = S.cats.find(function (x) { return x.nom === m.cat; });
ouvrir(function (clore) {
var defil = h('div', { class: 'lect-scroll', tabindex: '0', 'data-focus': '', role: 'region', 'aria-label': 'Contenu du mail' });
var boite = h('section', { class: 'boite lecture', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'lect-t' },
h('div', { class: 'lect-tete' }, h('h2', { id: 'lect-t', text: m.objet || '(sans objet)' }),
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Fermer la lecture', onclick: clore }, icone('fermer'))),
defil);
function charger() {
defil.textContent = ''; defil.setAttribute('aria-busy', 'true'); defil.focus();
defil.appendChild(h('div', { class: 'lect-etat', role: 'status' }, h('p', { text: 'Ouverture du mail…' }), h('span', { class: 'lect-sq' }), h('span', { class: 'lect-sq court' }), h('span', { class: 'lect-sq' })));
api('/mail?id=' + encodeURIComponent(m.id)).then(function (r) {
if (!document.body.contains(boite)) return;
defil.removeAttribute('aria-busy'); defil.textContent = '';
afficherMail(defil, m, r, c);
}).catch(function (e) {
if (e.message === 'session' || !document.body.contains(boite)) return;
defil.removeAttribute('aria-busy'); defil.textContent = '';
defil.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du mail impossible'),
h('p', null, 'Le service de lecture n\'a pas répondu. Le mail reste intact dans votre messagerie.'),
h('button', { type: 'button', class: 'btn-plein', onclick: charger }, 'Réessayer')));
});
}
charger();
return boite;
});
}
function reperes(m) {
if (!m.etiquettes || !m.etiquettes.length) return null;
var d = h('div', { class: 'etqs', 'aria-label': 'Étiquettes du miroir' });
m.etiquettes.forEach(function (t) { d.appendChild(h('span', { class: 'etq', text: t })); });
return d;
}
function ligneMail(m) {
var orig = m.source === 'manuel' ? 'manuel' : (m.cat === SYSTEME ? 'sans règle' : 'règle');
var origCls = orig === 'manuel' ? ' manuel' : orig === 'sans règle' ? ' sansregle' : '';
var objetAff = m.objet || '(sans objet)';
var etq = 'Traité : ' + m.exp + ', ' + (m.objet || 'sans objet');
var libLire = 'Lire le mail de ' + m.exp + ' : ' + (m.objet || 'sans objet');
var cb = h('input', { type: 'checkbox', 'aria-label': etq, onchange: function (e) { basculerTraite(m, e.target.checked); } });
cb.checked = m.traite;
return h('div', { class: 'ligne' + (m.traite ? ' fait' : ''), role: 'listitem' },
h('label', { class: 'coche' }, cb),
h('div', { class: 'corps d' }, h('div', { class: 'exp coupe', title: m.expBrut, text: m.exp })),
h('div', { class: 'corps d' }, h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } }, h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff })), reperes(m)),
h('div', { class: 'heure d', text: heureTunis(m.date) }),
h('div', { class: 'd' }, h('span', { class: 'origine' + origCls, text: orig })),
h('div', { class: 'm-corps' },
h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } },
h('span', { class: 'exp coupe', title: m.expBrut, text: m.exp }), h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff }),
h('span', { class: 'm-meta' }, h('span', { class: 'heure', text: heureTunis(m.date) }), ' · ', h('span', { class: 'o' + (orig === 'manuel' ? ' manuel' : ''), text: orig }))), reperes(m)),
selecteur(m));
}
function vueTri() {
var frag = document.createDocumentFragment();
frag.appendChild(enteteJour());
if (S.etat === 'chargement') {
var sq = h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture du courrier du ' + fr(S.jour) + '…' }));
for (var i = 0; i < 8; i++) sq.appendChild(h('div', { class: 'sq-ligne' }, h('span'), h('span'), h('span'), h('span'), h('span'), h('span')));
frag.appendChild(sq); return frag;
}
if (S.etat === 'erreur') {
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'),
h('p', null, 'Le service de lecture n\'a pas répondu pour le ' + fr(S.jour) + '. Vos corrections et vos règles sont conservées.'),
h('button', { type: 'button', class: 'btn-plein', onclick: chargerMails }, 'Réessayer')));
return frag;
}
if (S.miroirErreur) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Lecture du courrier momentanément indisponible', h('small', null, 'Affichage des derniers classements enregistrés.'))));
var tous = S.mails, nbT = tous.filter(function (m) { return m.traite; }).length;
var compte = {}; tous.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
var puces = h('div', { class: 'puces', role: 'group', 'aria-label': 'Filtrer par catégorie' });
var defs = [{ nom: 'Tous', c: -1, n: tous.length, filtre: null }].concat(S.cats.map(function (c, i) { return { nom: c.nom, c: couleur(c.nom, c.id), n: compte[c.nom] || 0, filtre: c.nom, rang: i }; }).sort(function (x, y) { return y.n - x.n || x.rang - y.rang; }));
defs.forEach(function (p) {
var actif = S.filtre === p.filtre;
puces.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (p.c === 0 ? ' vide' : '') + (p.c > 0 ? ' t' + p.c : ''), onclick: function () { S.filtre = actif ? null : p.filtre; rendre(); } },
h('span', { class: 'pt ' + (p.c === -1 ? 'tous' : 'c' + p.c), 'aria-hidden': 'true' }), h('span', { text: p.nom }), h('span', { class: 'n', text: d2(p.n) })));
});
var barre = h('div', null); barre.style.width = tous.length ? Math.round(nbT / tous.length * 100) + '%' : '0%';
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Répartition du jour' }, h('h2', null, 'Répartition du jour'), puces,
h('div', { class: 'avancement' }, h('div', { class: 'barre' }, barre), h('span', null, 'Traités ', h('b', { text: d2(nbT) + '/' + d2(tous.length) })))));
if (S.banniere) {
var b = S.banniere;
frag.appendChild(h('div', { class: 'bandeau', role: 'region', 'aria-label': 'Règle proposée' },
h('div', { class: 'txt' }, 'Toujours classer les mails de « ' + b.exp + ' » dans « ' + b.cat + ' » ?',
h('small', null, (b.autres ? b.autres + ' autre' + (b.autres > 1 ? 's' : '') + ' mail' + (b.autres > 1 ? 's' : '') + ' de ce jour ser' + (b.autres > 1 ? 'ont' : 'a') + ' aussi reclassé' + (b.autres > 1 ? 's' : '') + '. ' : '') + 'Votre messagerie n\'est pas modifiée.')),
h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-plein', onclick: confirmerRegle }, 'Confirmer la règle'), h('button', { type: 'button', class: 'btn-ligne', onclick: ignorerRegle }, 'Pas maintenant'))));
}
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
var visibles = tous.filter(function (m) { return !S.filtre || m.cat === S.filtre; });
var liste = h('div', { role: 'list' });
var carte = h('section', { class: 'carte', 'aria-label': 'Mails du jour' });
carte.appendChild(h('div', { class: 'liste-entete', 'aria-hidden': 'true' }, h('span'), h('span', null, 'Expéditeur'), h('span', null, 'Objet'), h('span', null, 'Heure'), h('span', null, 'Origine'), h('span', null, 'Catégorie')));
visibles.forEach(function (m) { liste.appendChild(ligneMail(m)); });
carte.appendChild(liste);
if (tous.length === 0) carte.appendChild(h('div', { class: 'etat' }, icone('tri', 28), h('h2', null, 'Aucun mail ce jour'), h('p', null, 'Rien n\'est arrivé le ' + fr(S.jour) + '.')));
else if (visibles.length === 0) carte.appendChild(h('div', { class: 'etat-filtre' }, 'Aucun mail dans « ' + S.filtre + ' » ce jour.', h('button', { type: 'button', class: 'btn-lien', onclick: function () { S.filtre = null; rendre(); } }, 'Tout afficher')));
frag.appendChild(carte);
return frag;
}
function vueCategories() {
var frag = document.createDocumentFragment();
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Catégories'), h('button', { type: 'button', class: 'btn-plein', onclick: function () { dialogueCategorie(null); } }, 'Ajouter une catégorie')));
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
if (S.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les catégories n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerMails }, 'Réessayer'))); return frag; }
var compte = {}; S.mails.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
var carte = h('section', { class: 'carte limite', 'aria-label': 'Catégories' });
S.cats.forEach(function (c) {
carte.appendChild(h('div', { class: 'rang' }, pastille(couleur(c.nom, c.id)), h('span', { class: 'nom', text: c.nom }),
h('span', { class: 'nb' }, h('b', { text: d2(compte[c.nom] || 0) }), ' ce jour'),
h('button', { type: 'button', class: 'btn-petit', 'aria-label': (c.nom === SYSTEME ? 'Détails de ' : 'Modifier ') + c.nom, onclick: function () { dialogueCategorie(c); } }, c.nom === SYSTEME ? 'Détails' : 'Modifier')));
});
if (S.etat === 'chargement') carte.appendChild(h('div', { class: 'sq-statut', role: 'status', text: 'Chargement…' }));
frag.appendChild(carte); return frag;
}
function critere(r) {
var p = [];
if (r.expediteur) p.push(['Expéditeur', r.expediteur]);
if (r.mot_cle) p.push(['Mot-clé', r.mot_cle]);
if (r.etiquette_miroir) p.push(['Étiquette', r.etiquette_miroir]);
return p.length ? p : [['Règle', '']];
}
function vueRegles() {
var frag = document.createDocumentFragment();
var act = S.regles.filter(function (r) { return r.statut === 'active'; }).length, prop = S.regles.length - act;
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'Règles'), h('div', { class: 'maj', text: act + ' active' + (act > 1 ? 's' : '') + (prop ? ' · ' + prop + ' à confirmer' : '') }))));
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
if (S.reglesEtat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les règles n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerRegles }, 'Réessayer'))); return frag; }
var carte = h('section', { class: 'carte limite-l', 'aria-label': 'Règles de classement' });
var flv = icone('fleche', 16); flv.classList.add('fl');
carte.appendChild(h('div', { class: 'regle' }, h('span', { class: 'crit' }, 'Objet ', h('b', { text: 'vide' })), flv, h('span', { class: 'cat' }, pastille(5), 'Sans objet'), h('span', { class: 'etiq active', text: 'règle de départ' }), h('span')));
var tri = S.regles.slice().sort(function (a, b) { return (a.statut === 'active') - (b.statut === 'active') || a.id - b.id; });
tri.forEach(function (r) {
var c = S.cats.find(function (x) { return x.nom === r.categorie; });
var crit = h('span', { class: 'crit' });
critere(r).forEach(function (p, i) { if (i) crit.appendChild(document.createTextNode(' · ')); crit.appendChild(document.createTextNode(p[0] + ' ')); crit.appendChild(h('b', { text: p[1] })); });
var actif = r.statut === 'active';
var sw = h('button', { type: 'button', class: 'interrupteur', role: 'switch', 'aria-checked': actif ? 'true' : 'false', 'aria-label': 'Règle ' + critere(r).map(function (p) { return p.join(' '); }).join(', ') + ' vers ' + r.categorie, onclick: function () { basculerRegle(r); } }, h('span', { class: 'piste' }, h('span', { class: 'bouton' })));
carte.appendChild(h('div', { class: 'regle' + (actif ? '' : ' propose') }, crit, icone('fleche', 16), h('span', { class: 'cat' }, pastille(couleur(r.categorie, c && c.id)), r.categorie),
h('span', { class: 'etiq ' + (actif ? 'active' : 'propose'), text: actif ? 'règle active' : 'à confirmer' }), sw));
carte.lastChild.querySelector('svg').classList.add('fl');
});
if (S.reglesEtat === 'chargement') carte.appendChild(h('div', { class: 'sq-statut', role: 'status', text: 'Chargement…' }));
else if (!S.regles.length) carte.appendChild(h('div', { class: 'etat' }, h('h2', null, 'Aucune règle'), h('p', null, 'Corrigez la catégorie d\'un mail pour en proposer une.')));
frag.appendChild(carte);
frag.appendChild(h('p', { class: 'note' }, 'Une règle activée s\'applique aux mails du jour qui n\'ont pas été corrigés à la main.'));
return frag;
}
function vueGroupes() {
var G = S.groupe, frag = document.createDocumentFragment();
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'Groupes'), h('div', { class: 'maj' }, 'Un seul groupe, sur plusieurs jours · heure de Tunis'))));
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
var per = h('div', { class: 'puces', role: 'group', 'aria-label': 'Période' });
[[7, '7 jours'], [30, '30 jours']].forEach(function (p) {
per.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': G.jours === p[0] ? 'true' : 'false', onclick: function () { if (G.jours !== p[0]) { G.jours = p[0]; chargerGroupe(); } } }, h('span', { text: p[1] })));
});
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Choisir un groupe' }, h('h2', null, 'Période'), per));
if (G.etat === 'erreur') {
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'), h('p', null, 'Le service de lecture n\'a pas répondu.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerGroupe }, 'Réessayer')));
return frag;
}
if (G.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des ' + G.jours + ' derniers jours…' }))); return frag; }
if (G.miroirErreur) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Lecture du courrier momentanément indisponible')));
var cc = {}, ce = {};
G.mails.forEach(function (m) { cc[m.cat] = (cc[m.cat] || 0) + 1; (m.etiquettes || []).forEach(function (t) { ce[t] = (ce[t] || 0) + 1; }); });
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Catégorie' });
S.cats.map(function (c, i) { return { c: c, rang: i }; }).sort(function (x, y) { return (cc[y.c.nom] || 0) - (cc[x.c.nom] || 0) || x.rang - y.rang; }).forEach(function (o) {
var c = o.c, k = couleur(c.nom, c.id), actif = G.cat === c.nom;
pc.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (k === 0 ? ' vide' : '') + (k > 0 ? ' t' + k : ''), onclick: function () { G.cat = actif ? null : c.nom; rendre(); } },
h('span', { class: 'pt c' + k, 'aria-hidden': 'true' }), h('span', { text: c.nom }), h('span', { class: 'n', text: d2(cc[c.nom] || 0) })));
});
var pe = h('div', { class: 'puces', role: 'group', 'aria-label': 'Étiquette du miroir' });
Object.keys(ce).sort(function (a, b) { return ce[b] - ce[a] || a.localeCompare(b); }).forEach(function (t) {
var actif = G.etq === t;
pe.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce', onclick: function () { G.etq = actif ? null : t; rendre(); } }, h('span', { text: t }), h('span', { class: 'n', text: d2(ce[t]) })));
});
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Groupes' }, h('h2', null, 'Catégorie'), pc, h('h2', null, 'Étiquette du miroir'), pe));
if (!G.cat && !G.etq) {
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('groupes', 28), h('h2', null, 'Choisissez un groupe'), h('p', null, G.mails.length + ' mails sur ' + G.jours + ' jours. Touchez une catégorie ou une étiquette pour ne voir que celle-ci.'))));
return frag;
}
var vis = G.mails.filter(function (m) { return (!G.cat || m.cat === G.cat) && (!G.etq || (m.etiquettes || []).indexOf(G.etq) !== -1); });
var titreG = [G.cat, G.etq].filter(Boolean).join(' + ');
if (!vis.length) {
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat-filtre' }, 'Aucun mail dans « ' + titreG + ' » sur ' + G.jours + ' jours.', h('button', { type: 'button', class: 'btn-lien', onclick: function () { G.cat = null; G.etq = null; rendre(); } }, 'Changer de groupe'))));
return frag;
}
frag.appendChild(h('h2', { class: 'titre-groupe', text: titreG + ' · ' + vis.length + (vis.length > 1 ? ' mails' : ' mail') }));
var jours = [], par = {};
vis.forEach(function (m) { var j = String(m.date).slice(0, 10); if (!par[j]) { par[j] = []; jours.push(j); } par[j].push(m); });
jours.forEach(function (j) {
var carte = h('section', { class: 'carte', 'aria-label': nomJour(j) + ' ' + fr(j) });
carte.appendChild(h('div', { class: 'jour-titre' }, h('span', { text: nomJour(j) + ' ' + fr(j) }), h('span', { class: 'nb', text: par[j].length + (par[j].length > 1 ? ' mails' : ' mail') })));
var liste = h('div', { role: 'list' }); par[j].forEach(function (m) { liste.appendChild(ligneMail(m)); });
carte.appendChild(liste); frag.appendChild(carte);
});
return frag;
}
function vueBientot(k) {
var t = BIENTOT[k];
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
h('section', { class: 'carte limite' }, h('div', { class: 'bientot-ecran' }, h('span', { class: 'badge-bientot' }, 'Prochainement'), h('p', { class: 'note', text: t[1] }))));
}
function rendre() {
var pos = document.getElementById('principal').scrollTop;
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
rendreNav();
var p = document.getElementById('principal'); p.textContent = '';
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : vueBientot(S.vue);
p.appendChild(v); p.scrollTop = pos;
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : S.vue === 'groupes' ? 'Groupes' : BIENTOT[S.vue][0];
document.title = titre + ' · Courrier';
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
}
rendre();
chargerMails();
})();