Files

1203 lines
90 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Page de suivi TTA : lit le stockage de l'extension (alimenté par background.js) et l'affiche.
const $ = id => document.getElementById(id);
const RANK = { red: 0, yellow: 1, green: 2, blue: 3, grey: 4 };
const TILES = [['red', 'Retard important'], ['yellow', 'Retard'], ['green', 'À l\'heure'], ['blue', 'Pas parti'], ['grey', 'Inactif / non trouvé']];
// Couleur d'un train arrivé, selon son retard à l'arrivée (mêmes seuils que les trains en circulation)
const arrColor = t => t.delay == null ? 'grey' : t.delay >= st.cfg.redFromMin ? 'red' : t.delay >= st.cfg.yellowFromMin ? 'yellow' : 'green';
const isArrived = t => t.phase === 'arrived';
const POLL_MS = 60000;
const VERSION = chrome.runtime.getManifest().version;
const TIS = 'https://tis-prod.rne.eu';
let st = { trains: [], data: null, alerts: [], prefs: DEFAULT_PREFS, cfg: { yellowFromMin: 5, redFromMin: 15 }, debug: [], stats: {}, session: null,
loginWin: null, tisFilters: [], tisFilter: null, lists: [], extras: {}, pins: {}, notes: {}, handoverNote: '', active: PRESET_LISTS[0] };
let editing = false;
let filter = null; // couleur filtrée (clic sur un compteur)
let pendingDel = null; // { key, until } : croix cliquée une fois, en attente du 2e clic
let panelKey = null; // train affiché dans la fiche
let companies = null; // entreprises ferroviaires TIS (pour composer une liste)
let editList = null; // liste en cours d'édition
let query = ''; // recherche dans la liste (filtre dynamique)
let pr = null; // fenêtre d'impression : { t, rows, numbers, from, to } (options : prefs.printOpts)
// ---------- Recherche : chaque mot doit se retrouver dans le train (numéros, gares, prochain point, compo, note…) ----------
const norm = s => String(s ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
function matches(t) {
const words = norm(query).split(/\s+/).filter(Boolean);
if (!words.length) return true;
const hay = norm([mainNum(t), t.otn, ...(t.numbers || []), t.origin, t.destination, t.current, t.lastPingPlace, t.next && t.next.name,
t.compo && t.compo.label, t.reason, t.type === 'PASSENGER' ? 'voyageurs' : 'fret', st.notes[noteKey(t)],
...((t.delays || []).map(x => x.code ? delayLabel(x.code) : ''))].filter(Boolean).join(' | '));
return words.every(w => hay.includes(w));
}
// ---------- Signaler un bug : mail prérempli (la personne décrit et envoie elle-même) ----------
const BUG_TO = 'maxime@rousseaux.link', BUG_SUBJECT = 'Signalement TIS';
function bugBody() {
const s = st.stats || {}, d = st.data || {};
return `Bonjour,
Décris ici le problème (ce que tu faisais, ce qui s'est passé, le ou les trains concernés) :
— Infos techniques (à laisser) —
TTA v${VERSION} (moteur ${s.version || '?'}) · ${new Date().toLocaleString('fr-BE')}
Liste : ${st.active.name} · trains affichés : ${(d.rows || []).length}
Session TIS : ${st.session && st.session.ok ? 'connecté' : 'non connecté'} · dernière mise à jour : ${d.updatedAt ? new Date(d.updatedAt).toLocaleTimeString('fr-BE') : '—'}
Dernière erreur : ${s.lastError || 'aucune'}${d.error ? ' · état : ' + d.error : ''}
Navigateur : ${navigator.userAgent}
Astuce : pour joindre le journal détaillé, TTA > Réglages > Mode debug > « Copier », puis colle-le ici.`;
}
const bugMailto = () => `mailto:${BUG_TO}?subject=${encodeURIComponent(BUG_SUBJECT)}&body=${encodeURIComponent(bugBody())}`;
const bugOutlookWeb = () => `https://outlook.office.com/mail/deeplink/compose?to=${encodeURIComponent(BUG_TO)}&subject=${encodeURIComponent(BUG_SUBJECT)}&body=${encodeURIComponent(bugBody())}`;
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const send = msg => chrome.runtime.sendMessage(msg);
const pad = n => String(n).padStart(2, '0');
// Heure courte : HH:MM aujourd'hui, jj/mm HH:MM sinon.
function hm(iso) {
if (!iso) return '–';
const d = new Date(iso), n = new Date();
const t = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
return d.toDateString() === n.toDateString() ? t : `${pad(d.getDate())}/${pad(d.getMonth() + 1)} ${t}`;
}
const dayLabel = iso => new Date(iso).toLocaleDateString('fr-BE', { weekday: 'short', day: '2-digit', month: '2-digit' });
// Heure + repère de jour bien visible quand ce n'est pas aujourd'hui : « 06:00 J+1 », « 23:40 J-1 », « 05:10 25/10 ».
function hmd(iso) {
if (!iso) return '–';
const d = new Date(iso), n = new Date();
const t = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
const days = Math.round((new Date(d.getFullYear(), d.getMonth(), d.getDate()) - new Date(n.getFullYear(), n.getMonth(), n.getDate())) / 86400e3);
if (!days) return t;
const full = d.toLocaleDateString('fr-BE', { weekday: 'long', day: '2-digit', month: '2-digit' });
const tag = Math.abs(days) === 1 ? `J${days > 0 ? '+' : '−'}1` : `${pad(d.getDate())}/${pad(d.getMonth() + 1)}`;
return `${t}<span class="day${days > 0 ? ' fut' : ''}" title="${full}">${tag}</span>`;
}
const rel = min => min == null ? '' : min > 0 ? `dans ${dur(min)}` : min < 0 ? `il y a ${dur(-min)}` : 'maintenant';
const ddmm = ymd => ymd ? ymd.split('-').reverse().slice(0, 2).join('/') : '';
const dur = min => min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${pad(min % 60)}`;
const ageMin = iso => Math.max(0, Math.floor((Date.now() - Date.parse(iso)) / 60000));
const fmtDelay = d => d == null ? '–' : (d > 0 ? '+' : d < 0 ? '−' : '') + Math.abs(d);
// Noms TIS souvent en MAJUSCULES : « ZEEBRUGGE-BUNDEL PELIKAAN » → « Zeebrugge-Bundel Pelikaan ».
// Les sigles courts sans voyelle (SBB, RB, GR) restent en majuscules.
const LOWER_WORDS = new Set(['de', 'du', 'des', 'la', 'le', 'les', 'en', 'et', 'sur', 'sous', 'aux', 'au', 'am', 'an', 'im', 'bei', 'di', 'da', 'del', 'van', 'von', 'der', 'den', 'op', 'aan']);
function nice(s) {
if (!s || s !== s.toUpperCase() || !/\p{L}/u.test(s)) return s || '';
return s.toLowerCase().replace(/[\p{L}\d]+/gu, (w, i) => {
if (i > 0 && LOWER_WORDS.has(w)) return w;
if (w.length <= 3 && !/[aeiouyàâäéèêëîïôöûü]/.test(w) && !['st', 'ste'].includes(w)) return w.toUpperCase();
return w[0].toUpperCase() + w.slice(1);
});
}
// « 31-653-902 » = 31 véhicules, 653 m, 902 t (poids du train, pas le poids freiné)
const compoTip = c => `Composition : ${c.veh} véhicules · ${c.len} m · ${c.w} t (poids du train)${c.sections && c.sections.length > 1 ? ` — section ${nice(c.fromName) || '?'} → ${nice(c.toName) || '?'} (${c.sections.length} sections)` : ''}`;
// Identifiants d'un train affiché
const rowKey = t => t.id ? 'id:' + t.id : 'q:' + (t.query || t.otn);
const mainNum = t => t.query || t.otn;
const noteKey = t => `${mainNum(t)}|${t.plannedDeparture ? localDate(t.plannedDeparture) : ''}`;
const tisUrl = t => t.id ? `${TIS}/search/train/${t.id}${t.archive ? '?archive=true' : ''}` : `${TIS}/search`;
const openTis = t => chrome.tabs.create({ url: tisUrl(t) });
const isFleet = () => !!(st.active && st.active.definition);
// Après un changement de jour, le train a un autre identifiant TIS : on le retrouve par son numéro.
const findRow = key => {
const rows = (st.data && st.data.rows) || [];
return rows.find(t => rowKey(t) === key) || (key && key.startsWith('q:') ? rows.find(t => t.src === 'list' && mainNum(t) === key.slice(2)) : null);
};
// ---------- En-tête : dernière mise à jour + connexion ----------
function tickLive() {
const d = st.data, live = $('live');
if (!d || !d.updatedAt) {
$('updated').textContent = '--:--:--'; $('age').textContent = '';
$('countdown').textContent = d && d.error ? '' : 'en attente de TIS…'; live.className = 'live dead'; $('progress').style.width = '0';
return;
}
const t = new Date(d.updatedAt);
$('updated').textContent = `${pad(t.getHours())}:${pad(t.getMinutes())}:${pad(t.getSeconds())}`;
const age = Math.round((Date.now() - t) / 1000);
$('age').textContent = age < 60 ? `il y a ${age} s` : `il y a ${Math.floor(age / 60)} min ${pad(age % 60)} s`;
const left = Math.round((t.getTime() + POLL_MS - Date.now()) / 1000);
$('countdown').textContent = d.error ? '⚠ échec de la dernière tentative' : left > 0 ? `prochaine dans ${left} s` : 'mise à jour imminente…';
live.className = 'live' + (age > 300 || d.error ? ' dead' : age > 150 ? ' stale' : '');
$('progress').style.width = Math.min(100, Math.max(0, age / (POLL_MS / 1000) * 100)) + '%';
}
function renderSession() {
const s = st.session, el = $('session');
let cls = '', txt = 'TIS : état inconnu';
if (st.loginWin) { txt = 'Connexion en cours…'; }
else if (s && s.ok) { cls = 'ok'; txt = s.name ? `Connecté · ${s.name}` : 'Connecté à TIS'; }
else if (s && s.ok === false) { cls = 'ko'; txt = 'Déconnecté · Se connecter'; }
el.className = 'session ' + cls; $('sessionTxt').textContent = txt;
el.title = s && s.ok ? 'Connecté à TIS – cliquer pour ouvrir une fenêtre TIS' : 'Cliquer pour se connecter à TIS';
$('setSession').textContent = st.loginWin ? 'Connexion en cours…' : s && s.ok ? (s.name ? `Connecté : ${s.name}` : 'Connecté') : 'Non connecté';
$('setLogin').textContent = s && s.ok ? 'Se reconnecter' : 'Se connecter';
}
// ---------- Pastille de statut (ligne + fiche) ----------
function statusPill(t) {
const cfg = st.cfg, wait = t.phase === 'waiting', done = t.phase === 'arrived', lost = t.phase === 'notfound' || t.phase === 'unknown';
let v, l, word = true;
if (lost) { v = '?'; l = t.phase === 'notfound' ? 'Non trouvé' : 'Inactif'; }
else if (done) {
if (t.delay == null) { v = '🏁 Arrivé'; l = 'Retard inconnu'; }
else { word = false; v = `🏁 ${t.delay === 0 ? '0' : fmtDelay(t.delay)}<small>min</small>`; l = t.delay >= cfg.redFromMin ? 'Gros retard' : t.delay >= cfg.yellowFromMin ? 'En retard' : t.delay < 0 ? 'En avance' : 'À l\'heure'; }
}
else if (wait && t.color === 'blue') { v = 'Pas parti'; l = t.startsInMin != null ? `dans ${dur(t.startsInMin)}` : ''; }
else if (t.stuck) {
// retard minimum déduit (aucun pointage au point attendu) : « ≥ », le retard TIS est dans l'infobulle
word = false; v = `≥${fmtDelay(t.delay)}<small>min</small>`; l = t.stuck.atStop ? 'Pas reparti' : 'Sans pointage';
}
else if (t.dwell) {
// à l'arrêt en attente du départ : la couleur suit le retard prévu au départ, pas celui d'arrivée
v = '⏸ À l\'arrêt'; l = t.dwell.depDelay ? `départ +${t.dwell.depDelay} min` : 'départ à l\'heure';
}
else if (t.delay === 0 && !wait) { v = 'À l\'heure'; l = ''; }
else {
word = false;
v = `${fmtDelay(t.delay)}<small>min</small>`;
l = t.interrupted ? 'Interrompu' : wait ? 'Pas parti' : t.delay >= cfg.redFromMin ? 'Retard important' : t.delay >= cfg.yellowFromMin ? 'Retard' : t.delay < 0 ? 'En avance' : 'À l\'heure';
}
const trend = t.trend ? `<span class="trend ${t.trend > 0 ? 'up' : 'down'}" title="Le retard a changé à ${hm(new Date(t.trendAt).toISOString())}">${t.trend > 0 ? '▲' : '▼'}${Math.abs(t.trend)}</span>` : '';
const tip = t.stuck ? ` title="${esc(`${t.reason}. Retard minimum : il augmente tant que le train ne pointe pas.`)}"` : t.dwell ? ` title="${esc(t.reason)}"` : '';
return `<div class="pill${t.stuck ? ' stuck' : ''}"${tip}><div class="v${word ? ' word' : ''}">${word ? esc(v) : v}${trend}</div><div class="l">${esc(l)}</div></div>`;
}
// ---------- Alertes à l'écran, historique, taille d'affichage ----------
// Chaque alerte sonne ET s'affiche en bas à droite (petite carte, disparaît seule ; reste tant que la souris est
// dessus ; le compte à rebours ne démarre que quand l'onglet est visible). Clic = fiche du train.
// La cloche 🔔 du haut compte les alertes pas encore vues et ouvre l'historique.
let alertsSeen = null; // date de la dernière alerte vue dans l'historique
let alertsHl = null; // historique ouvert : alertes surlignées (celles qui n'avaient pas encore été vues)
let toastLast = null; // date de la dernière alerte déjà affichée à l'écran
const flashUntil = new Map(); // numéro de train → fin du clignotement de sa ligne
const ZOOM_MIN = 0.6, ZOOM_MAX = 1.6, TOAST_MAX = 4;
const TOAST_MS = { red: 45000, default: 15000 };
const ALERT_ICON = { depart: '🚆', delay10: '⏱', etd5: '⏳', red: '🔴', arrive: '🏁', session: '🔑' };
const alertLevel = a => ['red', 'yellow', 'green', 'blue', 'grey'].includes(a.level) ? a.level : 'grey';
const alertTime = iso => {
const d = new Date(iso), today = localDate(new Date().toISOString()) === localDate(iso);
return `${today ? '' : `${pad(d.getDate())}/${pad(d.getMonth() + 1)} `}${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
const unreadAlerts = () => st.alerts.filter(a => a.at > (alertsSeen || '')).length;
function renderAlerts() {
const n = unreadAlerts();
$('alertsBadge').hidden = !n;
$('alertsBadge').textContent = n > 99 ? '99+' : n;
$('alertsBtn').classList.toggle('has', n > 0);
$('alertsBtn').title = n ? `${n} nouvelle${n > 1 ? 's' : ''} alerte${n > 1 ? 's' : ''} : clic pour voir l'historique` : 'Alertes : historique (ce qui a sonné)';
$('logCount').textContent = st.alerts.length ? `(${st.alerts.length})` : '';
$('log').innerHTML = st.alerts.length ? st.alerts.map((a, i) => `
<button class="al lv-${alertLevel(a)}${a.at > (alertsHl ?? alertsSeen ?? '') ? ' unread' : ''}" data-al="${i}" title="${a.otn ? 'Ouvrir la fiche du train ' + esc(a.otn) : ''}">
<time>${esc(alertTime(a.at))}</time><span class="ic">${ALERT_ICON[a.kind] || '•'}</span>
<span class="tx"><b>${esc(a.title)}</b>${a.body ? `<small>${esc(a.body)}</small>` : ''}</span>
</button>`).join('') : '<p class="muted">Aucune alerte pour le moment.</p>';
}
function toggleAlerts(where) {
$('settingsPop').hidden = true;
const pop = $('alertsPop'), open = pop.hidden || !pop.classList.contains('at-' + where);
pop.classList.toggle('at-top', where === 'top');
pop.classList.toggle('at-bottom', where !== 'top');
pop.hidden = !open;
alertsHl = open ? alertsSeen : null;
renderAlerts();
if (open && st.alerts.length) {
// ouvrir l'historique = tout est vu (les nouvelles restent surlignées tant qu'il est ouvert)
alertsSeen = st.alerts[0].at;
chrome.storage.local.set({ alertsSeen });
}
}
// Fiche du train de l'alerte (et sa ligne qui clignote) ; l'alerte « session » ouvre la connexion.
function openAlert(a) {
if (!a) return;
if (a.kind === 'session') return login();
const rows = (st.data && st.data.rows) || [];
const t = rows.find(x => a.id && x.id === a.id) || rows.find(x => String(x.otn) === String(a.otn) || (x.numbers || []).includes(String(a.otn)));
if (!t) { toggleAlerts('top'); return; }
if (isArrived(t) && !st.prefs.arrivedOpen) savePrefs({ arrivedOpen: true });
panelKey = rowKey(t);
flashUntil.set(mainNum(t), Date.now() + 6000);
render();
const el = document.querySelector(`.row[data-key="${CSS.escape(panelKey)}"]`);
if (el) el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
function dismissToast(el) {
clearTimeout(el._t);
el.classList.add('out');
setTimeout(() => el.remove(), 250);
}
function addToast(a, extra) {
const box = $('toasts'), el = document.createElement('div');
const lv = a ? alertLevel(a) : 'grey';
el.className = `toast lv-${lv}`;
el.innerHTML = a
? `<span class="ic">${ALERT_ICON[a.kind] || '•'}</span><div class="tx"><b>${esc(a.title)}</b>${a.body ? `<small>${esc(a.body)}</small>` : ''}<time>${esc(alertTime(a.at))}${a.otn ? ' · clic : fiche du train' : ''}</time></div><button class="x" data-tclose title="Fermer">✕</button>`
: `<span class="ic">🔔</span><div class="tx"><b>+${extra} autre${extra > 1 ? 's' : ''} alerte${extra > 1 ? 's' : ''}</b><small>Voir l'historique (cloche en haut)</small></div><button class="x" data-tclose title="Fermer">✕</button>`;
el._alert = a || null;
if (!a) el.onclick = () => toggleAlerts('top');
const ms = TOAST_MS[lv] || TOAST_MS.default;
el._arm = () => { if (document.hidden) return; clearTimeout(el._t); el._t = setTimeout(() => dismissToast(el), ms); };
el.onmouseenter = () => clearTimeout(el._t);
el.onmouseleave = el._arm;
box.prepend(el);
while (box.children.length > TOAST_MAX + 1) box.lastElementChild.remove();
el._arm();
}
// Nouvelles alertes depuis le dernier passage : cartes à l'écran + ligne qui clignote. Au chargement de la page,
// les alertes déjà connues ne sont pas réaffichées (elles sont dans l'historique).
function showToasts() {
if (!st.alerts.length) return;
const newest = st.alerts[0].at;
if (toastLast == null) { toastLast = newest; return; }
const fresh = st.alerts.filter(a => a.at > toastLast);
toastLast = newest;
if (!fresh.length) return;
for (const a of fresh) if (a.otn) flashUntil.set(String(a.otn), Date.now() + 8000);
if (fresh.some(a => a.otn)) render();
if (st.prefs.toasts === false) return;
const shown = fresh.slice(0, TOAST_MAX);
if (fresh.length > TOAST_MAX) addToast(null, fresh.length - TOAST_MAX);
for (const a of shown.reverse()) addToast(a);
}
function applyZoom() {
const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, Number(st.prefs.zoom) || 1));
document.documentElement.style.setProperty('--z', z);
$('zoomVal').textContent = Math.round(z * 100) + '%';
$('zoomOut').disabled = z <= ZOOM_MIN; $('zoomIn').disabled = z >= ZOOM_MAX;
}
// ---------- État du dernier pointage ----------
// Le pointage n'est en alerte que si l'heure attendue au prochain point (ou, à défaut, à l'arrivée) est dépassée :
// jaune au-delà de overdueYellowMin, rouge au-delà de overdueRedMin. Un train arrêté longtemps dont le prochain
// point n'est pas encore dû (relais, attente de reprise) est « en stand-by ».
function pingState(t) {
const p = st.prefs, age = t.lastPingAt ? ageMin(t.lastPingAt) : null;
const expect = t.next ? (t.next.estimatedTime || t.next.plannedTime) : t.forecastArrival || t.plannedArrival || null;
const over = expect ? Math.round((Date.now() - Date.parse(expect)) / 60000) : null;
const where = t.next ? (t.next.atStop ? `au départ de ${nice(t.next.name)}` : `au prochain point (${nice(t.next.name)})`) :'à l\'arrivée';
let lvl, tip;
if (over != null && over > p.overdueRedMin) { lvl = 'red'; tip = `Attendu ${where} à ${hm(expect)} : dépassé de ${dur(over)} sans pointage`; }
else if (over != null && over > p.overdueYellowMin) { lvl = 'yellow'; tip = `Attendu ${where} à ${hm(expect)} : dépassé de ${dur(over)}`; }
else if (t.next && t.next.atStop) { lvl = 'stand'; tip = `À l'arrêt à ${nice(t.next.name)} (arrivée prévue ${hm(t.next.stop.arrEst)}, non pointée par TIS) · départ attendu ${hm(expect)}, ${rel(-over)}`; }
else if (age != null && age >= p.standbyMin && over != null) { lvl = 'stand'; tip = `À l'arrêt depuis ${dur(age)} (relais / attente de reprise) : prochain point attendu à ${hm(expect)}, ${rel(-over)}`; }
else if (age != null) { lvl = 'blue'; tip = `Dernier pointage il y a ${dur(age)}${expect ? ` · prochain point attendu ${hm(expect)}` : ''}`; }
return { lvl, tip, age, over, expect };
}
// couleur d'un retard (texte)
const arrCls = d => d == null ? '' : d >= st.cfg.redFromMin ? 'warn' : d >= st.cfg.yellowFromMin ? 'mid' : d < 0 ? 'okc' : '';
// ---------- Une ligne de train ----------
function rowHtml(t) {
const p = st.prefs, cfg = st.cfg;
const run = t.phase === 'running', wait = t.phase === 'waiting', done = t.phase === 'arrived', lost = t.phase === 'notfound' || t.phase === 'unknown';
const n = t.next, key = rowKey(t);
// Train : numéro (lien direct vers TIS), numéros liés (parité), jour choisi, note
const others = (t.numbers || []).filter(x => x !== mainNum(t));
const sub = [t.type === 'PASSENGER' ? 'Voyageurs' : '', others.length ? `⇄ ${others.join(' · ')}` : '', t.pinned ? `📅 ${ddmm(t.pinned)}` : ''].filter(Boolean).join(' · ');
const subHtml = [
others.length ? `<span class="otns" title="${esc('Numéros de ce train (le numéro change en route) : ' + (t.numbers || []).join(' → '))}">⇄ ${others.map(esc).join(' · ')}</span>` : '',
t.type === 'PASSENGER' ? '<span class="tag-vo">Voyageurs</span>' : '',
t.pinned ? `<span class="pin" title="Jour choisi">📅 ${ddmm(t.pinned)}</span>` : ''].filter(Boolean).join('');
// Colonne Composition : « véhicules-longueur-poids » en grand, ou « Compo non trouvée »
let compoCell;
if (t.compo) {
const multi = t.compo.sections && t.compo.sections.length > 1 ? ` · section ${t.compo.sections.findIndex(x => x.id === t.compo.id) + 1}/${t.compo.sections.length}` : '';
compoCell = `<div class="m compo" title="${esc(compoTip(t.compo) + multi)}">${esc(t.compo.label)}</div><div class="s" title="${esc(compoTip(t.compo) + multi)}">${t.compo.veh} véh · ${t.compo.len} m · ${t.compo.w} t</div>`;
} else if (!t.id || t.phase === 'notfound' || t.phase === 'unknown') compoCell = '<div class="m muted">—</div>';
else if (!t.compoKnown) compoCell = '<div class="m muted">…</div><div class="s">chargement</div>';
else compoCell = '<div class="m nocompo">Compo non trouvée</div><div class="s">absente de TIS</div>';
const note = st.notes[noteKey(t)] ? `<span class="note-ic" title="${esc(st.notes[noteKey(t)])}">📝</span>` : '';
// Itinéraire
const origin = nice(t.origin), dest = nice(t.destination);
const routeM = lost ? (t.phase === 'notfound' ? 'Train non trouvé' : 'Aucun train actif') : esc(origin);
const routeS = lost ? esc(t.reason) : t.parityFrom ? `→ ${esc(dest)} <span class="soft">· parité ${esc(t.parityFrom)}→${esc(t.otn)}</span>` : `→ ${esc(dest)}`;
// dernière cause de retard déclarée (toutes dans la fiche du train)
const lastCause = lost ? null : (t.delays || []).filter(x => x.code).pop();
const causeHtml = lastCause ? `<div class="cause" title="${esc(`Dernière cause de retard : ${delayLabel(lastCause.code)} (${nice(lastCause.at)}${lastCause.time ? ' · ' + hm(lastCause.time) : ''})` + ((t.delays || []).length > 1 ? `\n${t.delays.length} causes déclarées : clic sur la ligne pour le détail` : ''))}">⚠ ${lastCause.delay != null ? `<b>${fmtDelay(lastCause.delay)}</b> · ` : ''}${esc(delayLabel(lastCause.code))}</div>` : '';
const routeTip = lost ? t.reason :t.parityFrom ? `${origin} → ${dest} — ${t.reason}` : `${origin} → ${dest}`;
// Position + fraîcheur du dernier pointage
let posM = '—', posS = '';
if (run) {
const pg = pingState(t);
posM = `${p.staleOn && pg.lvl ? `<span class="ping-dot ping-${pg.lvl}" title="${esc(pg.tip)}"></span>` : ''}${esc(nice(t.current || t.lastPingPlace) || '—')}`;
if (n && n.atStop) posM = `${p.staleOn && pg.lvl ? `<span class="ping-dot ping-${pg.lvl}" title="${esc(pg.tip)}"></span>` : ''}${esc(nice(n.name))}`;
posS = !t.lastPingAt ? 'aucun pointage'
: n && n.atStop && pg.lvl === 'stand' ? `<span class="ping-txt ping-stand" title="${esc(pg.tip)}">⏸ arrivé ${t.dwell && t.dwell.arrPinged ? '' : '≈'}${hmd(n.stop.arrEst)}${t.dwell ? ` <b class="${arrCls(t.dwell.arrDelay)}">(${t.dwell.arrDelay ? fmtDelay(t.dwell.arrDelay) : 'à l\'heure'})</b>` : ''} · départ ${hmd(pg.expect)}</span>`
: n && n.atStop ? `<span class="ping-txt ping-${pg.lvl}" title="${esc(pg.tip)}">⚠ départ attendu ${hmd(pg.expect)} (+${dur(pg.over)})</span>`
: pg.lvl === 'stand' ? `<span class="ping-txt ping-stand" title="${esc(pg.tip)}">⏸ arrêt depuis ${dur(pg.age)} · reprise ${hmd(pg.expect)}</span>`
: `pointé <b>${hmd(t.lastPingAt)}</b> · <span class="${p.staleOn ? 'ping-txt ping-' + pg.lvl : ''}" title="${esc(pg.tip)}">${p.staleOn && (pg.lvl === 'red' || pg.lvl === 'yellow') ? `⚠ prochain point attendu ${hmd(pg.expect)} (+${dur(pg.over)})` : `il y a ${dur(pg.age)}`}</span>`;
} else if (wait) { posM = esc(origin || '—'); posS = 'à l\'origine, en attente du départ'; }
else if (done) { posM = esc(dest || '—'); posS = `arrivé à <b>${hmd(t.lastEvent)}</b>`; }
// Prochain point de passage
let nextM = '—', nextS = '';
if (run && n) {
const dl = n.plannedTime && n.estimatedTime ? Math.round((Date.parse(n.estimatedTime) - Date.parse(n.plannedTime)) / 60000) : null;
const inMin = n.estimatedTime || n.plannedTime ? Math.round((Date.parse(n.estimatedTime || n.plannedTime) - Date.now()) / 60000) : null;
nextM = `${n.atStop ? '<span class="soft">Départ</span> ' : ''}${esc(nice(n.name))}${inMin != null ? ` <span class="rel${inMin < 0 ? ' late' : ''}">${inMin < 0 ? 'dépassé ' + dur(-inMin) : rel(inMin)}</span>` : ''}`;
const estTip = n.estSrc === 'tta' ? `Estimation TTA : heure prévue + retard actuel (${fmtDelay(t.delay)} min). L'heure calculée par TIS (${hm(n.tisTime)}) est périmée.` : 'Heure calculée par TIS';
nextS = `${n.plannedTime ? `prévu <b>${hmd(n.plannedTime)}</b> · ` : ''}<span title="${esc(estTip)}">est. <b>${n.estSrc === 'tta' ? '≈' : ''}${hmd(n.estimatedTime)}</b></span>${dl ? ` <span class="${dl >= cfg.redFromMin ? 'warn' : dl >= cfg.yellowFromMin ? 'mid' : dl < 0 ? 'okc' : ''}">(${dl > 0 ? '+' : '−'}${Math.abs(dl)})</span>` : ''}${n.stop && !n.atStop ? ` · <span class="soft" title="Arrêt : départ prévu ${esc(hmd(n.stop.depPlanned))}">arrêt → ${hmd(n.stop.depPlanned)}</span>` : ''}`;
} else if (run) nextS = t.detailAt ? 'pas d\'information' : 'chargement…';
else if (t.delays && t.delays.length && t.delays[0].code) { nextM = '<span class="muted">cause</span>'; nextS = esc(delayLabel(t.delays[t.delays.length - 1].code)); }
// Départ
let depS = '';
if (run || done) depS = `réel <b>${hmd(t.actualDeparture)}</b>`;
else if (wait) depS = t.etdLate > 0 ? `<span class="warn" title="Heure de départ dépassée de ${t.etdLate} min">ETD +${t.etdLate} min</span>` : t.startsInMin != null ? `<span class="soft">dans ${dur(t.startsInMin)}</span>` : '';
// Arrivée : heure estimée en grand, retard prévu en couleur (ignoré si l'écart est absurde : dates TIS décalées)
const arrDelta = t.forecastArrival && t.plannedArrival && !done ? Math.round((Date.parse(t.forecastArrival) - Date.parse(t.plannedArrival)) / 60000) : null;
const arrTag = arrDelta != null && arrDelta !== 0 && Math.abs(arrDelta) <= 720
? ` <span class="${arrDelta >= cfg.redFromMin ? 'warn' : arrDelta >= cfg.yellowFromMin ? 'mid' : arrDelta < 0 ? 'okc' : ''}">${arrDelta > 0 ? '+' : '−'}${Math.abs(arrDelta)}</span>` : '';
// Croix : 1er clic = « Confirmer », 2e clic au même endroit = action (masquer 24 h ou retirer)
const confirming = pendingDel && pendingDel.key === key && pendingDel.until > Date.now();
const delTitle = t.src === 'filter' ? `Masquer le train ${mainNum(t)} pendant 24 h` : `Retirer le train ${mainNum(t)} de la liste`;
const del = `<button class="del${confirming ? ' confirm' : ''}" data-del="${esc(key)}" title="${confirming ? 'Cliquer encore pour confirmer' : delTitle}">${confirming ? (t.src === 'filter' ? 'Masquer ?' : 'Retirer ?') : '✕'}</button>`;
return `
<div class="row ${done ? 'arrived ' + arrColor(t) : t.color}${panelKey === key ? ' sel' : ''}${(flashUntil.get(mainNum(t)) || flashUntil.get(String(t.otn)) || 0) > Date.now() ? ' flash' : ''}" data-key="${esc(key)}" title="Clic : fiche du train · clic sur le numéro : ouvrir dans TIS">
<div class="bar-c"></div>
<div class="cell c-stat">${statusPill(t)}</div>
<div class="cell c-num"><div class="n"><a class="tis" data-tis="${esc(key)}" title="Ouvrir le train ${esc(mainNum(t))} dans TIS">${esc(mainNum(t))}</a>${note}</div><div class="nums" title="${esc(sub)}">${subHtml}</div></div>
<div class="cell c-compo">${compoCell}</div>
<div class="cell c-route" title="${esc(routeTip)}"><div class="m">${routeM}${t.interrupted ? '<span class="tag-int">INTERROMPU</span>' : ''}</div><div class="s">${routeS}</div>${causeHtml}</div>
<div class="cell c-pos"><div class="m">${posM}</div><div class="s">${posS}</div></div>
<div class="cell c-next"><div class="m">${nextM}</div><div class="s">${nextS}</div></div>
<div class="cell c-dep"><div class="m">${t.plannedDeparture ? hmd(t.plannedDeparture) : '–'}</div><div class="s">${depS}</div></div>
<div class="cell c-arr"><div class="m">${done ? `🏁 ${hmd(t.lastEvent)}` : t.forecastArrival || t.plannedArrival ? `<span title="${esc(t.arrEstSrc === 'tta' ? `Estimation TTA : arrivée prévue + retard actuel (${fmtDelay(t.delay)} min) — l'estimation TIS est périmée` : 'Arrivée estimée par TIS')}">${t.arrEstSrc === 'tta' ? '≈' : ''}${hmd(t.forecastArrival || t.plannedArrival)}</span>` : '–'}</div><div class="s">${t.plannedArrival ? `prévue <b>${hmd(t.plannedArrival)}</b>${done && t.delay ? ` <span class="${arrColor(t) === 'red' ? 'warn' : arrColor(t) === 'yellow' ? 'mid' : 'okc'}">${fmtDelay(t.delay)}</span>` : arrTag}` : ''}</div></div>
<div class="acts">${del}${t.id ? `<button class="prt" data-print="${esc(key)}" title="Imprimer l'horaire du train ${esc(mainNum(t))} (de tel point à tel point)">🖨</button>` : ''}</div>
</div>`;
}
// ---------- Fiche du train (volet de droite) ----------
function renderPanel() {
const el = $('panel');
if (!panelKey) { el.hidden = true; return; }
const t = findRow(panelKey);
el.hidden = false;
if (!t) { el.innerHTML = `<div class="p-head"><b>Train</b><button class="btn mini" data-pclose>✕</button></div><p class="muted">Ce train n'est plus affiché (masqué, retiré ou plus dans la liste).</p>`; return; }
const kv = (k, v) => v ? `<span>${k}</span><b>${v}</b>` : '';
const nums = t.numbers && t.numbers.length ? t.numbers : [mainNum(t)];
const age = t.lastPingAt ? ageMin(t.lastPingAt) : null;
const canPick = t.src === 'list';
const alts = (t.alts || []).map(a => {
const on = t.id === a.id;
return `<button class="alt${on ? ' on' : ''}" data-alt="${esc(a.date)}" title="${esc(a.state)}">${esc(dayLabel(a.dep))} ${esc(hm(a.dep).slice(-5))}<small>${esc(a.state)}</small></button>`;
}).join('');
// causes de retard : la plus récente en haut, total déclaré en tête
const dl = (t.delays || []).slice().reverse();
const declared = dl.reduce((s, x) => s + (x.delay > 0 ? x.delay : 0), 0);
const causes = dl.length
? (declared ? `<li class="c-total">${dl.length} cause${dl.length > 1 ? 's' : ''} · <b>${fmtDelay(declared)} min</b> déclarées</li>` : '')
+ dl.map((x, i) => `<li${i === 0 ? ' class="last"' : ''}><b>${x.delay != null ? fmtDelay(x.delay) + ' min' : ''}</b> ${x.code ? `<span class="c-code">${esc(x.code)}</span> ${esc(DELAY_CAUSES[Number(x.code)] || 'code UIC')}` : esc(delayLabel(x.code))}<small>${x.code ? esc(DELAY_FAMILY(x.code)) + ' · ' : ''}${esc(nice(x.at))}${x.time ? ' · ' + hmd(x.time) : ''}${i === 0 ? ' · dernière' : ''}</small></li>`).join('')
: '<li class="muted">Aucune cause de retard déclarée dans TIS.</li>';
el.innerHTML = `
<div class="p-head">
<div><div class="p-num">${esc(nums.join(' → '))}</div><div class="muted">${t.type === 'FREIGHT' ? 'Fret' : t.type === 'PASSENGER' ? 'Voyageurs' : ''}${t.id ? ' · id TIS ' + esc(t.id) : ''}${t.src === 'filter' ? ' · liste « ' + esc(st.active.name) + ' »' : ' · ajouté à la main'}</div></div>
<button class="btn mini" data-pclose title="Fermer (Échap)">✕</button>
</div>
<div class="p-status ${t.color}">${statusPill(t)}<div class="p-route"><b>${esc(nice(t.origin) || '—')}</b><span>→ ${esc(nice(t.destination) || '—')}</span></div></div>
${t.reason && (t.phase === 'notfound' || t.parityFrom || t.phase === 'unknown') ? `<p class="p-reason">${esc(t.reason)}</p>` : ''}
<div class="p-actions">
<button class="btn primary" data-ptis>Ouvrir dans TIS ↗</button>
${t.id ? '<button class="btn" data-proute title="Horaire complet : prévu, réel / estimé, écart à chaque point">🧭 Parcours</button><button class="btn" data-pprint>🖨 Imprimer l\'horaire</button>' : ''}
<button class="btn${pendingDel && pendingDel.key === 'p:' + panelKey && pendingDel.until > Date.now() ? ' danger' : ''}" data-pdel>${pendingDel && pendingDel.key === 'p:' + panelKey && pendingDel.until > Date.now() ? 'Confirmer ?' : t.src === 'filter' ? 'Masquer 24 h' : 'Retirer de la liste'}</button>
</div>
<h4>Horaires</h4>
<div class="kvs p-kv">
${kv('Départ prévu', t.plannedDeparture ? hmd(t.plannedDeparture) : '')}
${kv('Départ réel', t.actualDeparture ? hmd(t.actualDeparture) : t.etdLate > 0 ? `<span class="warn">pas parti · ETD +${t.etdLate} min</span>` : t.startsInMin != null ? `dans ${dur(t.startsInMin)}` : '')}
${t.dwell && !t.stuck ? kv('À l\'arrêt', `<b>${esc(nice(t.dwell.place))}</b> · arrivé ${t.dwell.arrPinged ? '' : '≈'}${hmd(t.dwell.arrAt)} <span class="${arrCls(t.dwell.arrDelay)}">(${t.dwell.arrDelay ? fmtDelay(t.dwell.arrDelay) + ' min' : 'à l\'heure'})</span> · départ prévu ${hmd(t.dwell.depPlanned)}${t.dwell.depDelay ? ` <span class="${arrCls(t.dwell.depDelay)}">(+${t.dwell.depDelay} min)</span>` : ' <span class="okc">à l\'heure</span>'}`) : ''}
${t.stuck ? kv(t.stuck.atStop ? 'Pas reparti' : 'Sans pointage', `<span class="warn">${t.stuck.atStop ? 'départ de' : 'attendu à'} ${esc(nice(t.stuck.place))} (prévu ${hmd(t.stuck.plannedAt)}) : retard au moins ${fmtDelay(t.delay)} min</span> · TIS : ${fmtDelay(t.stuck.tisDelay)} min au dernier pointage`) : ''}
${kv('Dernier pointage', t.lastPingAt ? `${esc(nice(t.lastPingPlace))} · ${hmd(t.lastPingAt)} (il y a ${dur(age)})` : '')}
${t.phase === 'running' && t.lastPingAt ? kv('État', (() => { const pg = pingState(t); return `<span class="ping-txt ping-${pg.lvl}">${pg.lvl === 'stand' ? '⏸ stand-by' : pg.lvl === 'red' || pg.lvl === 'yellow' ? '⚠ en retard sur l\'horaire' : 'normal'}</span> · ${esc(pg.tip)}`; })()) : ''}
${kv('Prochain point', t.next ? `${t.next.atStop ? 'Départ de ' : ''}${esc(nice(t.next.name))} · prévu ${hmd(t.next.plannedTime)} · est. ${hmd(t.next.estimatedTime)}` : '')}
${kv('Arrivée prévue', t.plannedArrival ? hmd(t.plannedArrival) : '')}
${kv('Arrivée estimée', t.forecastArrival ? hmd(t.forecastArrival) : '')}
</div>
<h4>Composition <span class="muted small">véhicules-longueur-poids</span></h4>
${t.compo ? `<div class="compos">${t.compo.sections.map(x => {
const on = x.id === t.compo.id, ok = [x.veh, x.len, x.w].every(v => v != null);
return `<div class="cs${on ? ' on' : ''}"><b>${ok ? esc(`${x.veh}-${x.len}-${x.w}`) : '—'}</b><span>${esc(nice(x.fromName) || '?')} → ${esc(nice(x.toName) || '?')}</span><small>${ok ? `${x.veh} véhicules · ${x.len} m · ${x.w} t` : 'incomplète'}${on ? ' · section actuelle' : ''}</small></div>`;
}).join('')}</div>` : `<p class="muted">${t.id ? 'Pas de composition disponible dans TIS (ou pas encore chargée).' : '—'}</p>`}
<h4>Jour du train ${t.pinned ? `<span class="chip">📅 ${ddmm(t.pinned)}</span>` : '<span class="chip soft">automatique</span>'}</h4>
${alts ? `<div class="alts">${alts}</div>` : `<p class="muted">${t.src === 'filter' ? 'Train issu de la liste : il suit le jour en cours.' : 'Aucun autre jour trouvé dans TIS pour ce numéro.'}</p>`}
<div class="p-day">
<label class="muted">${canPick ? 'Autre date de départ' : 'Suivre ce numéro un autre jour'} : <input type="date" id="pDate" class="num wide" value="${esc(t.pinned || (t.plannedDeparture ? localDate(t.plannedDeparture) : ''))}"></label>
<button class="btn mini" data-pdate>${canPick ? 'Appliquer' : 'Ajouter'}</button>
${canPick && t.pinned ? '<button class="btn mini" data-pauto>Automatique</button>' : ''}
</div>
<h4>Causes de retard (TIS)</h4>
<ul class="causes">${causes}</ul>
<h4>Consigne / note de suivi</h4>
<textarea id="pNote" class="note" rows="3" placeholder="Ex. : loco changée à Bettembourg, client prévenu à 06:10…">${esc(st.notes[noteKey(t)] || '')}</textarea>
<p class="muted small">La note est reprise dans le rapport de relève.</p>`;
}
// ---------- Liste active (sélecteur) ----------
function renderSource() {
const sel = $('source');
const opt = (v, l) => `<option value="${esc(v)}">${esc(l)}</option>`;
const html =
`<optgroup label="Listes intégrées">${PRESET_LISTS.map(l => opt(l.id, l.ruCodes.length ? `Mes trains · ${l.name}` : l.name)).join('')}</optgroup>` +
(st.lists.length ? `<optgroup label="Mes listes">${st.lists.map(l => opt(l.id, l.name)).join('')}</optgroup>` : '') +
(st.tisFilters.length ? `<optgroup label="Filtres enregistrés dans TIS">${st.tisFilters.map(f => opt('tis-' + f.id, 'Filtre TIS · ' + f.name)).join('')}</optgroup>` : '');
if (sel.dataset.html !== html) { sel.innerHTML = html; sel.dataset.html = html; }
sel.value = st.active.id;
sel.classList.toggle('on', isFleet());
sel.title = isFleet() ? `Trains de « ${st.active.name} » en circulation + départs dans les ${st.prefs.upcomingMin} min, plus les numéros ajoutés` : 'Uniquement les numéros saisis';
$('numbers').placeholder = isFleet() ? 'Trains en plus (hors filtre) : 40146, 42920@27/10 …' : 'Numéros de train : 40146, 42920@27/10 …';
}
// Champ texte : numéros en plus de la liste active, avec le jour choisi (42920@27/10)
const extrasText = () => st.trains.map(n => st.pins[n] ? `${n}@${ddmm(st.pins[n])}` : n).join(', ');
// Le moteur (service worker) ne se recharge pas tout seul quand on remplace les fichiers : on le détecte.
function engineOutdated() {
const rows = (st.data && st.data.rows) || [];
const old = rows.some(r => r.phase && r.phase !== 'notfound' && r.phase !== 'unknown' && !('etdLate' in r));
const v = st.stats && st.stats.version;
return old || (!!v && v !== VERSION);
}
const sortRows = rows => [...rows].sort((a, b) =>
RANK[a.color] - RANK[b.color] ||
(a.color === 'blue' ? (a.startsInMin ?? 1e9) - (b.startsInMin ?? 1e9) : (b.delay ?? 0) - (a.delay ?? 0)));
function render() {
const d = st.data, s = st.session;
document.documentElement.dataset.theme = st.prefs.theme || 'auto';
document.querySelectorAll('#themeSeg button').forEach(b => b.classList.toggle('on', b.dataset.theme === (st.prefs.theme || 'auto')));
renderSession();
const loginBtn = '<button class="btn primary" data-login>Se connecter à TIS</button>';
$('banner').innerHTML =
(engineOutdated() ? `<div class="banner"><span>🔄 Le moteur de l'extension tourne encore avec une ancienne version.</span><button class="btn primary" id="reloadExt">Recharger l'extension</button></div>` : '') +
(st.loginWin ? `<div class="banner info"><span>🔑 Termine la connexion dans la fenêtre TIS : elle se fermera toute seule et le suivi reprendra.</span><button class="btn" data-login>Afficher la fenêtre</button></div>`
: d && d.error ? `<div class="banner"><span>⚠️ ${esc(d.error)}</span>${d.auth ? loginBtn : ''}</div>` : '');
if ($('reloadExt')) $('reloadExt').onclick = () => chrome.runtime.reload();
if (!editing) $('numbers').value = extrasText();
tickLive();
const everything = sortRows((d && d.rows) || []);
const all = everything.filter(t => !isArrived(t));
const arrivedAll = everything.filter(isArrived).sort((a, b) => Date.parse(b.lastEvent || 0) - Date.parse(a.lastEvent || 0));
const arrived = arrivedAll.filter(matches);
const counts = Object.fromEntries(TILES.map(([k]) => [k, 0]));
all.forEach(t => counts[t.color]++);
if (filter && !counts[filter]) filter = null;
$('summary').innerHTML = TILES.map(([k, label]) =>
`<button class="tile ${k}${counts[k] ? '' : ' zero'}${filter === k ? ' active' : ''}" data-filter="${k}" title="${filter === k ? 'Tout afficher' : 'Afficher seulement : ' + label}"><b>${counts[k]}</b><span>${label}</span></button>`).join('');
const rows = (filter ? all.filter(t => t.color === filter) : all).filter(matches);
// compteur de la recherche
const shown = rows.length + arrived.length, total = all.length + arrivedAll.length;
$('qCount').textContent = query.trim() ? `${shown} / ${total} train${total > 1 ? 's' : ''}` : '';
$('qClear').hidden = !query;
// Cartes d'accueil : pas connecté / liste vide
let html = rows.map(rowHtml).join(''), arrHtml = '';
if (query.trim() && !shown && total) html = `<div class="empty"><h2>Aucun train ne correspond</h2><p>Rien pour « ${esc(query.trim())} » dans « ${esc(st.active.name)} ». <button class="btn" data-qclear>Effacer la recherche</button></p></div>`;
if (arrived.length) {
const ac = k => arrived.filter(t => arrColor(t) === k).length;
const open = !!st.prefs.arrivedOpen || (!!query.trim() && arrived.length > 0);
arrHtml = `<div class="arr-sec${open ? ' open' : ''}">
<button class="arr-head" data-arrtoggle title="${open ? 'Replier' : 'Déplier'} la liste des trains arrivés">
<span class="chev">${open ? '▾' : '▸'}</span><b>🏁 Arrivés</b><span class="arr-n">${arrived.length}</span>
<span class="arr-sum">${[['green', 'à l\'heure'], ['yellow', 'en retard'], ['red', 'gros retard'], ['grey', 'retard inconnu']].filter(([k]) => ac(k))
.map(([k, l]) => `<span class="dotc ${k}"></span>${ac(k)} ${l}`).join('<i></i>')}</span>
</button>
${open ? `<div class="arr-list">${arrived.map(rowHtml).join('')}</div>` : ''}
</div>`;
}
const fleet = isFleet();
if (fleet && !everything.length && !(s && s.ok === false)) {
html = `<div class="empty"><span class="logo-tile big"><img src="logo.svg" alt=""></span><h2>Aucun train en ce moment</h2>
<p>Aucun train de « ${esc(st.active.name)} » n'est en circulation ni au départ dans les ${st.prefs.upcomingMin} prochaines minutes.</p></div>`;
} else if (!fleet && !st.trains.length) {
html = `<div class="empty"><span class="logo-tile big"><img src="logo.svg" alt=""></span><h2>Liste « ${esc(st.active.name)} » vide</h2>
<p>${s && s.ok === false ? 'Commence par te connecter à TIS, puis ajoute' : 'Ajoute'} des numéros de train dans le champ en haut (séparés par des virgules ; jour précis : 42920@27/10), puis « Enregistrer ».
Ou choisis une liste par entreprise : <button class="btn primary" data-uselist="preset-sibelit">Mes trains · SIBELIT</button> <button class="btn" data-uselist="preset-lineas">Lineas</button></p>
${s && s.ok === false ? loginBtn : ''}</div>`;
} else if (!everything.length && s && s.ok === false) {
html = `<div class="empty"><span class="logo-tile big"><img src="logo.svg" alt=""></span><h2>Connexion à TIS requise</h2>
<p>TTA utilise ton compte TIS. Une petite fenêtre de connexion Microsoft va s'ouvrir : connecte-toi, elle se fermera toute seule.</p>${loginBtn}</div>`;
}
$('list').innerHTML = html;
$('arrived').innerHTML = arrHtml;
const hc = (d && d.hiddenCount) || 0;
$('hiddenbar').hidden = !(fleet && hc);
if (fleet && hc) $('hiddenbar').innerHTML = `👁 ${hc} train${hc > 1 ? 's' : ''} masqué${hc > 1 ? 's' : ''} (24 h) <button id="unhide">Tout réafficher</button>`;
renderSource();
document.querySelector('.cols.head').style.visibility = rows.length || arrived.length ? '' : 'hidden';
const last = st.alerts[0];
$('ticker').textContent = last ? `${new Date(last.at).toLocaleTimeString('fr-BE')} · ${last.title}${last.body ? ' · ' + last.body : ''}` : 'Aucune alerte pour le moment';
renderAlerts();
$('soundBtn').textContent = st.prefs.sound ? '🔊' : '🔇';
$('soundBtn').classList.toggle('off', !st.prefs.sound);
if (!(document.activeElement && document.activeElement.id === 'pNote')) renderPanel(); // ne pas écraser une note en cours de saisie
if (!$('handoverModal').hidden) renderHandover();
renderDebug();
}
// ---------- Rapport de relève ----------
function handoverText() {
const d = st.data || {}, rows = sortRows(d.rows || []), now = new Date();
const who = st.session && st.session.name ? ` — ${st.session.name}` : '';
const c = k => rows.filter(t => t.color === k).length;
const line = t => {
const parts = [`${(t.numbers && t.numbers.length > 1 ? t.numbers.join('→') : mainNum(t)).padEnd(7)}`];
if (t.phase === 'notfound' || t.phase === 'unknown') return `• ${parts[0]} ${t.reason}`;
parts.push(`${nice(t.origin)} → ${nice(t.destination)}`);
if (t.phase === 'waiting') parts.push(t.etdLate > 0 ? `PAS PARTI, ETD +${t.etdLate} min (prévu ${hm(t.plannedDeparture)})` : `départ prévu ${hm(t.plannedDeparture)}${t.startsInMin != null ? ` (dans ${dur(t.startsInMin)})` : ''}`);
else if (t.phase === 'arrived') parts.push(`arrivé ${hm(t.lastEvent)} · ${t.delay != null ? `${t.delay > 0 ? 'retard ' : t.delay < 0 ? 'avance ' : 'à l\'heure '}${t.delay ? fmtDelay(t.delay) + ' min' : ''}` : 'retard inconnu'} (prévu ${hm(t.plannedArrival)})`);
else {
parts.push(t.stuck ? `${t.stuck.atStop ? 'PAS REPARTI' : 'SANS POINTAGE'} : retard au moins ${fmtDelay(t.delay)} min (TIS ${fmtDelay(t.stuck.tisDelay)} au dernier pointage)`
: t.dwell ? `À L'ARRÊT à ${nice(t.dwell.place)} : arrivé ${t.dwell.arrDelay ? fmtDelay(t.dwell.arrDelay) + ' min' : 'à l\'heure'}, départ ${hm(t.dwell.depPlanned)} ${t.dwell.depDelay ? `+${t.dwell.depDelay} min` : 'à l\'heure'}`
: `${fmtDelay(t.delay)} min${t.trend ? ` (${t.trend > 0 ? '▲' : '▼'}${Math.abs(t.trend)})` : ''}${t.interrupted ? ' INTERROMPU' : ''}`);
if (t.lastPingAt) {
const pg = pingState(t);
parts.push(`pointé ${nice(t.lastPingPlace)} ${hm(t.lastPingAt)} (il y a ${dur(ageMin(t.lastPingAt))})${pg.lvl === 'stand' ? ` STAND-BY, reprise ${hm(pg.expect)}` : pg.lvl === 'red' || pg.lvl === 'yellow' ? ` ⚠ attendu ${hm(pg.expect)}, dépassé de ${dur(pg.over)}` : ''}`);
}
if (t.next) parts.push(`prochain ${nice(t.next.name)} ${hm(t.next.estimatedTime || t.next.plannedTime)}`);
if (t.forecastArrival) parts.push(`arr. est. ${hm(t.forecastArrival)}`);
}
if (t.phase !== 'notfound' && t.phase !== 'unknown') parts.push(t.compo ? `compo ${t.compo.label}` : t.compoKnown ? 'compo non trouvée' : 'compo en chargement');
const cause = (t.delays || []).filter(x => x.code).pop();
if (cause && t.phase !== 'arrived') parts.push(`cause ${delayLabel(cause.code)}`);
const note = st.notes[noteKey(t)];
return `• ${parts.join(' · ')}${note ? `\n 📝 ${note.replace(/\n/g, ' / ')}` : ''}`;
};
const section = (title, list) => list.length ? `\n${title} (${list.length})\n${list.map(line).join('\n')}\n` : '';
const isLost = t => t.phase === 'notfound' || t.phase === 'unknown';
return [
`RELÈVE TTA — ${now.toLocaleDateString('fr-BE', { weekday: 'long', day: '2-digit', month: '2-digit', year: 'numeric' })} ${hm(now.toISOString())}${who}`,
`Liste : ${st.active.name} · situation TIS de ${d.updatedAt ? new Date(d.updatedAt).toLocaleTimeString('fr-BE') : '—'}${d.error ? ' (⚠ ' + d.error + ')' : ''}`,
`${rows.length} train(s) : ${c('red')} retard important · ${c('yellow')} retard · ${c('green')} à l'heure · ${c('blue')} pas parti · ${c('grey')} arrivé/inactif`,
section('🔴 RETARD IMPORTANT / INTERROMPU', rows.filter(t => t.color === 'red' && t.phase !== 'waiting')),
section('⏳ PAS PARTIS À L\'HEURE', rows.filter(t => t.phase === 'waiting' && t.etdLate > 0)),
section('🟡 RETARD', rows.filter(t => t.color === 'yellow' && t.phase !== 'waiting')),
section('🔵 DÉPARTS À VENIR', rows.filter(t => t.phase === 'waiting' && !(t.etdLate > 0))),
section('🟢 EN CIRCULATION À L\'HEURE', rows.filter(t => t.color === 'green')),
section('🏁 ARRIVÉS', rows.filter(t => t.phase === 'arrived').sort((a, b) => Date.parse(b.lastEvent || 0) - Date.parse(a.lastEvent || 0))),
section('❓ NON TROUVÉS / INACTIFS', rows.filter(isLost)),
st.handoverNote.trim() ? `\nREMARQUES DE RELÈVE\n${st.handoverNote.trim()}\n` : '',
`\n— TTA Train Time Accuracy`,
].join('\n').replace(/\n{3,}/g, '\n\n');
}
function renderHandover() {
$('handoverText').textContent = handoverText();
if (document.activeElement !== $('handoverNote')) $('handoverNote').value = st.handoverNote;
}
// ---------- Impression de l'horaire d'un train (de tel point à tel point) ----------
const KIND = { origin: 'Départ', stop: 'Arrêt', pass: 'Passage', dest: 'Arrivée' };
// points techniques : seulement des PASSAGES (aiguilles, bifurcations, postes, signaux…) ; les arrêts restent toujours
const TECH = /(?<![a-zà-ÿ])(aig|aiguille|bif|bifurcation|carr[eé]|signal|jonction|acc[eè]s|poste|abzw|spw|ite|km\s?\d|rooster|evit|blokpost|block|pk|sortie|entr[eé]e)(?![a-zà-ÿ])/i;
// Options d'impression (mémorisées) : tout est modulable
const PRINT_DEFAULTS = {
onlyStops: false, hideTech: true, // lignes
colDate: true, colType: true, colReal: true, colGap: true, colIm: true, // colonnes (sans Réel/Écart = horaire théorique seul)
infoTrip: true, infoCompo: true, infoDelay: true, infoPing: true, // informations en tête
viewHideTech: false, // Parcours (écran) : points techniques affichés
};
const po = () => ({ ...PRINT_DEFAULTS, ...(st.prefs.printOpts || {}) });
const PRINT_LABELS = {
colDate: 'Date', colType: 'Type (départ, arrêt…)', colReal: 'Heures réelles / estimées', colGap: 'Écart (retard / avance)', colIm: 'Gestionnaire (GI)',
infoTrip: 'Départ et arrivée du train (dates complètes)', infoCompo: 'Composition', infoDelay: 'Retard actuel', infoPing: 'Dernier pointage',
};
// view = true : « Parcours » (consultation à l'écran) ; sinon impression
async function openPrint(t, view = false) {
pr = { t, rows: null, from: null, to: null, view, q: '', scrolled: false };
$('printModal').hidden = false;
prModeUi();
$('prCtrl').innerHTML = ''; $('prPrev').innerHTML = '<p class="muted">Chargement de l\'horaire depuis TIS…</p>'; $('prInfo').textContent = '';
const r = await send({ type: 'timetable', id: t.id, archive: t.archive }).catch(e => ({ ok: false, error: e.message }));
if (!pr || pr.t !== t) return;
if (!r || !r.ok) { $('prPrev').innerHTML = `<p class="warn">Impossible de récupérer l'horaire : ${esc((r && r.error) || 'erreur')}</p>`; return; }
pr.rows = r.rows.map((x, i) => ({ ...x, i }));
pr.numbers = r.numbers;
pr.from = 0; pr.to = pr.rows.length - 1;
renderPrint();
}
function prModeUi() {
const nums = (pr.t.numbers && pr.t.numbers.length ? pr.t.numbers : [mainNum(pr.t)]).join(' → ');
$('prTitle').textContent = pr.view ? `🧭 Parcours du train ${nums}` : `🖨 Horaire du train ${nums}`;
$('prPrint').textContent = pr.view ? '🖨 Imprimer…' : '🖨 Imprimer';
$('printModal').classList.toggle('route', pr.view);
}
const prVisible = () => { const o = po(); return pr.rows.filter(x => x.kind !== 'pass' || (!o.onlyStops && !(o.hideTech && TECH.test(x.name)))); };
const prSelected = () => prVisible().filter(x => x.i >= pr.from && x.i <= pr.to);
const tPlan = x => (x.dep || x.arr || {}).p;
const gap = x => { if (x.delay != null) return x.delay; const v = x.dep || x.arr || {}; return v.p && v.a ? Math.round((Date.parse(v.a) - Date.parse(v.p)) / 60000) : null; };
const hhmm = iso => { if (!iso) return ''; const d = new Date(iso); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; };
const ddmmShort = iso => { const d = new Date(iso); return `${d.toLocaleDateString('fr-BE', { weekday: 'short' })} ${pad(d.getDate())}/${pad(d.getMonth() + 1)}`; };
const fullDate = iso => iso ? `${new Date(iso).toLocaleDateString('fr-BE', { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric' })} ${hhmm(iso)}` : '';
// heure d'une cellule : HH:MM, et la date entre parenthèses si elle diffère de celle de la ligne (passage de minuit)
const cellTime = (iso, rowDay) => !iso ? '' : `${hhmm(iso)}${rowDay && localDate(iso) !== rowDay ? ` <small class="dd">(${pad(new Date(iso).getDate())}/${pad(new Date(iso).getMonth() + 1)})</small>` : ''}`;
// heure réelle / estimée d'un point (même règle que la liste : ≈ = estimation TTA si TIS est périmé)
function realOf(x) {
const v = x.dep || x.arr || {};
if (v.a) return { t: v.a, src: 'real' };
const e = estimateAt(v.p, v.c, pr.t.phase === 'running' || pr.t.phase === 'waiting' ? pr.t.delay : null);
return e.t && e.t !== v.p ? { t: e.t, src: e.src } : null;
}
function prTable(list, o = po()) {
const cur = pr.rows.find(x => x.current);
const th = [o.colDate && '<th>Date</th>', '<th>Lieu</th>', o.colType && '<th>Type</th>', '<th>Arr. prévue</th>', '<th>Dép. / passage prévu</th>',
o.colReal && '<th>Réel / estimé</th>', o.colGap && '<th>Écart</th>', o.colIm && '<th>GI</th>'].filter(Boolean).join('');
let lastDay = null;
const body = list.map(x => {
const day = localDate(tPlan(x) || (x.dep || x.arr || {}).a), newDay = day !== lastDay; lastDay = day;
const rl = o.colReal || o.colGap ? realOf(x) : null;
const g = (x.dep || x.arr || {}).a ? gap(x) : rl && tPlan(x) ? Math.round((Date.parse(rl.t) - Date.parse(tPlan(x))) / 60000) : null;
const realTxt = rl ? `${rl.src === 'real' ? '' : '<i>'}${rl.src === 'tta' ? '≈' : ''}${cellTime(rl.t, day)}${rl.src === 'real' ? '' : '</i>'}` : '';
return `<tr class="${x.kind}${cur && x.i === cur.i ? ' here' : ''}${newDay ? ' newday' : ''}">
${o.colDate ? `<td class="dcol">${newDay ? ddmmShort(tPlan(x)) : ''}</td>` : ''}
<td>${esc(nice(x.name))}${cur && x.i === cur.i ? ' <b class="here-tag">◀ position actuelle</b>' : ''}</td>
${o.colType ? `<td>${KIND[x.kind]}</td>` : ''}
<td>${x.arr ? cellTime(x.arr.p, day) : ''}</td><td>${x.dep ? cellTime(x.dep.p, day) : ''}</td>
${o.colReal ? `<td>${realTxt}</td>` : ''}
${o.colGap ? `<td class="${g >= st.cfg.redFromMin ? 'warn' : g >= st.cfg.yellowFromMin ? 'mid' : g < 0 ? 'okc' : ''}">${g == null ? '' : g ? fmtDelay(g) : '0'}</td>` : ''}
${o.colIm ? `<td>${esc(x.im || '')}</td>` : ''}</tr>`;
}).join('');
return `<table class="tt"><thead><tr>${th}</tr></thead><tbody>${body}</tbody></table>`;
}
// Informations en tête (chacune activable ; absente = non imprimée)
function prInfoLines() {
const o = po(), t = pr.t, list = prSelected(), a = list[0], b = list[list.length - 1];
const first = pr.rows[0], last = pr.rows[pr.rows.length - 1], lines = [];
if (a && b) lines.push(`Tronçon : de <b>${esc(nice(a.name))}</b> (${fullDate(tPlan(a))}) à <b>${esc(nice(b.name))}</b> (${fullDate(tPlan(b))})`);
if (o.infoTrip && first && last) {
const dep = first.dep || {}, arr = last.arr || last.dep || {};
const arrEst = o.colReal && !arr.a && t.forecastArrival && t.forecastArrival !== arr.p ? ` · estimée ${t.arrEstSrc === 'tta' ? '≈' : ''}${fullDate(t.forecastArrival)}` : '';
lines.push(`Départ du train : <b>${esc(nice(first.name))}</b> ${fullDate(dep.p)}${o.colReal && dep.a ? ` (réel ${fullDate(dep.a)})` : ''}`);
lines.push(`Arrivée du train : <b>${esc(nice(last.name))}</b> ${fullDate(arr.p)}${o.colReal && arr.a ? ` (réelle ${fullDate(arr.a)})` : arrEst}`);
}
if (o.infoCompo && t.compo) lines.push(`Composition : <b>${esc(t.compo.label)}</b> (${t.compo.veh} véhicules · ${t.compo.len} m · ${t.compo.w} t)`);
if (o.infoDelay && t.delay != null && (t.phase === 'running' || t.phase === 'waiting')) lines.push(`Retard actuel : <b>${fmtDelay(t.delay)} min</b>`);
if (o.infoPing && t.lastPingAt) lines.push(`Dernier pointage : <b>${esc(nice(t.lastPingPlace))}</b> ${fullDate(t.lastPingAt)}`);
return lines;
}
// Parcours : tout l'horaire à l'écran (toutes les colonnes), recherche d'un lieu, position actuelle centrée
const ROUTE_COLS = { colDate: true, colType: true, colReal: true, colGap: true, colIm: true };
const fold = s => (s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
function routeRows() {
const o = po(), q = fold(pr.q).trim();
return pr.rows.filter(x => !(x.kind === 'pass' && o.viewHideTech && TECH.test(x.name)) && (!q || fold(x.name).includes(q)));
}
function renderRoute() {
const o = po(), t = pr.t, cur = pr.rows.find(x => x.current);
if (!$('prQ')) $('prCtrl').innerHTML = `
<div class="pr-range route-bar">
<input id="prQ" type="search" placeholder="Chercher un lieu (ex. Chatelet, Bettembourg…)" autocomplete="off" spellcheck="false">
<label class="sw small"><input type="checkbox" data-po="viewHideTech"${o.viewHideTech ? ' checked' : ''}><span>Masquer les points techniques</span></label>
${cur ? '<button class="btn mini" data-prgo>◀ Position actuelle</button>' : ''}
</div>
<div class="pr-info route-info" id="prRouteInfo"></div>`;
const info = [
t.lastPingAt ? `Dernier pointage : <b>${esc(nice(t.lastPingPlace))}</b> ${fullDate(t.lastPingAt)}` : '',
t.delay != null && (t.phase === 'running' || t.phase === 'waiting') ? `Retard actuel : <b>${fmtDelay(t.delay)} min</b>` : '',
t.next ? `${t.next.atStop ? 'Départ de' : 'Prochain point'} : <b>${esc(nice(t.next.name))}</b> ${hmd(t.next.estimatedTime || t.next.plannedTime)}` : '',
t.phase === 'arrived' ? `Arrivé à <b>${esc(nice(t.destination))}</b> ${fullDate(t.lastEvent)}` : '',
].filter(Boolean).join(' · ');
const list = routeRows();
$('prRouteInfo').innerHTML = info;
$('prRouteInfo').hidden = !info;
$('prPrev').innerHTML = `${list.length ? prTable(list, { ...o, ...ROUTE_COLS })
: `<p class="muted pr-none">Aucun lieu ne correspond à « ${esc(pr.q)} ».</p>`}`;
$('prInfo').textContent = `${list.length} point${list.length > 1 ? 's' : ''} sur ${pr.rows.length} étapes TIS${pr.q.trim() ? ` · filtre « ${pr.q.trim()} »` : ''}`;
if (!pr.scrolled) {
pr.scrolled = true;
const h = $('prPrev').querySelector('tr.here');
const box = $('prPrev');
if (h) box.scrollTop += h.getBoundingClientRect().top - box.getBoundingClientRect().top - box.clientHeight / 2;
}
}
function renderPrint() {
if (!pr || !pr.rows) return;
if (pr.view) return renderRoute();
const o = po(), vis = prVisible();
// « De » / « À » masqués par une option : on se recale sur le point visible le plus proche
if (vis.length && !vis.some(x => x.i === pr.from)) pr.from = (vis.find(x => x.i >= pr.from) || vis[vis.length - 1]).i;
if (vis.length && !vis.some(x => x.i === pr.to)) pr.to = ([...vis].reverse().find(x => x.i <= pr.to) || vis[0]).i;
const opt = (x, sel) => `<option value="${x.i}"${sel ? ' selected' : ''}>${esc(ddmmShort(tPlan(x)))} ${esc(hhmm(tPlan(x)))} · ${esc(nice(x.name))}${x.kind !== 'pass' ? ' (' + KIND[x.kind].toLowerCase() + ')' : ''}</option>`;
const opts = sel => vis.map(x => opt(x, x.i === sel)).join('');
const cur = pr.rows.find(x => x.current);
const cb = (k, dis) => `<label class="sw small"><input type="checkbox" data-po="${k}"${o[k] ? ' checked' : ''}${dis ? ' disabled' : ''}><span>${PRINT_LABELS[k] || k}</span></label>`;
const theo = !o.colReal && !o.colGap;
$('prCtrl').innerHTML = `
<div class="pr-range">
<label>De <select id="prFrom">${opts(pr.from)}</select></label>
<label>à <select id="prTo">${opts(pr.to)}</select></label>
${cur ? '<button class="btn mini" data-prhere>Depuis la position actuelle</button>' : ''}
<button class="btn mini" data-prall>Tout le parcours</button>
</div>
<div class="pr-groups">
<div><h5>Horaire</h5>
<div class="seg" id="prMode"><button data-mode="theo" class="${theo ? 'on' : ''}">Théorique seul</button><button data-mode="full" class="${!theo ? 'on' : ''}">Avec réel / prévisions</button></div>
<label class="sw small"><input type="checkbox" data-po="onlyStops"${o.onlyStops ? ' checked' : ''}><span>Seulement départ, arrêts et arrivée</span></label>
<label class="sw small"><input type="checkbox" data-po="hideTech"${o.hideTech ? ' checked' : ''}${o.onlyStops ? ' disabled' : ''}><span>Masquer les points techniques</span></label></div>
<div><h5>Colonnes</h5>${['colDate', 'colType', 'colReal', 'colGap', 'colIm'].map(k => cb(k)).join('')}</div>
<div><h5>Informations en tête</h5>${cb('infoTrip')}${cb('infoCompo', !pr.t.compo)}${cb('infoDelay')}${cb('infoPing', !pr.t.lastPingAt)}</div>
</div>`;
const list = prSelected();
$('prPrev').innerHTML = `<div class="pr-info">${prInfoLines().map(l => `<div>${l}</div>`).join('')}</div>${prTable(list)}`;
$('prInfo').textContent = `${list.length} ligne${list.length > 1 ? 's' : ''} sur ${pr.rows.length} étapes TIS`;
}
function printHtml() {
const t = pr.t, list = prSelected();
const logo = chrome.runtime.getURL('logo.svg');
return `<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>Horaire ${esc((pr.numbers || [mainNum(t)]).join(' - '))}</title><style>
/* marges du navigateur à 0 : Chrome n'imprime plus « about:blank », la date et le titre ; marges dans la page */
@page { size: A4; margin: 0 }
html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
body { font: 11.5px/1.35 "Segoe UI", Arial, sans-serif; color: #111; margin: 0; padding: 12mm 12mm 10mm; }
header { display: flex; align-items: center; gap: 12px; border-bottom: 2px solid #14305E; padding-bottom: 8px; margin-bottom: 8px; }
header img { width: 42px; height: 42px } h1 { font-size: 18px; margin: 0; color: #14305E } .sub { color: #444; font-size: 12px }
.info { margin: 0 0 8px; font-size: 11.5px; line-height: 1.5 } .info b { color: #14305E }
table { width: 100%; border-collapse: collapse } th { background: #14305E; color: #fff; text-align: left; font-size: 10.5px; padding: 4px 6px }
td { padding: 3px 6px; border-bottom: 1px solid #ddd; font-variant-numeric: tabular-nums; vertical-align: top }
tr.pass td { color: #555 } tr.origin td, tr.dest td, tr.stop td { font-weight: 700 } tr.here td { background: #fff3c4 } .here-tag { color: #b07a00 }
tr.newday td { border-top: 2px solid #14305E } td.dcol { font-weight: 800; color: #14305E; white-space: nowrap }
.dd { font-size: 9.5px; color: #14305E; font-weight: 800 }
.warn { color: #c00; font-weight: 700 } .mid { color: #a06a00; font-weight: 700 } .okc { color: #0a7a3a; font-weight: 700 } i { color: #555 }
footer { margin-top: 10px; color: #666; font-size: 9.5px; border-top: 1px solid #ccc; padding-top: 5px }
tr { page-break-inside: avoid } thead { display: table-header-group }
</style></head><body>
<header><img src="${logo}" alt=""><div><h1>Horaire du train ${esc((pr.numbers && pr.numbers.length ? pr.numbers : [mainNum(t)]).join(' → '))}</h1>
<div class="sub">${esc(nice(t.origin) || '')} → ${esc(nice(t.destination) || '')}${t.type === 'PASSENGER' ? ' · Voyageurs' : t.type === 'FREIGHT' ? ' · Fret' : ''}</div></div></header>
<div class="info">${prInfoLines().map(l => `<div>${l}</div>`).join('')}</div>
${prTable(list)}
<footer>Imprimé le ${fullDate(new Date().toISOString())} · données TIS (RNE) · TTA – Train Time Accuracy${!po().colReal && !po().colGap ? ' · horaire théorique' : ''}</footer>
</body></html>`;
}
// Impression sans ouvrir d'onglet : cadre caché dans la page, puis boîte d'impression du navigateur
function printNow() {
let f = $('prFrame');
if (f) f.remove();
f = document.createElement('iframe');
f.id = 'prFrame';
f.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden';
document.body.appendChild(f);
f.onload = () => setTimeout(() => { f.contentWindow.focus(); f.contentWindow.print(); }, 250); // laisse le logo se charger
f.srcdoc = printHtml();
}
function printText() {
const o = po(), list = prSelected();
const head = [`Horaire du train ${(pr.numbers || [mainNum(pr.t)]).join(' → ')} — ${nice(pr.t.origin)} → ${nice(pr.t.destination)}`,
...prInfoLines().map(l => l.replace(/<[^>]+>/g, ''))];
let lastDay = null;
return [...head, '', ...list.map(x => {
const day = localDate(tPlan(x)), nd = day !== lastDay; lastDay = day;
const rl = o.colReal ? realOf(x) : null, g = o.colGap ? gap(x) : null;
return `${o.colDate ? (nd ? ddmmShort(tPlan(x)) : '').padEnd(11) : ''}${(x.arr ? hhmm(x.arr.p) : '').padEnd(6)} ${(x.dep ? hhmm(x.dep.p) : '').padEnd(6)} ${o.colType ? KIND[x.kind].padEnd(8) : ''} ${nice(x.name)}${rl ? ` [${rl.src === 'real' ? 'réel' : 'est.'} ${rl.src === 'tta' ? '≈' : ''}${hhmm(rl.t)}${g ? ' ' + fmtDelay(g) : ''}]` : ''}`;
})].join('\n');
}
// ---------- Gestion des listes ----------
function renderLists() {
const item = (l, preset) => `
<div class="li${st.active.id === l.id ? ' on' : ''}${editList && editList.id === l.id ? ' editing' : ''}">
<div><b>${esc(l.name)}</b><small>${preset ? 'intégrée · ' : ''}${(l.ruCodes || []).length ? `${l.ruCodes.length} entreprise(s)` : 'sans filtre'}${!preset && (st.extras[l.id] || []).length ? ` · ${st.extras[l.id].length} n°` : ''}</small></div>
<div class="li-act">
${st.active.id === l.id ? '<span class="chip">active</span>' : `<button class="btn mini" data-luse="${esc(l.id)}">Utiliser</button>`}
${preset ? `<button class="btn mini" data-ldup="${esc(l.id)}" title="Créer une copie modifiable">Copier</button>`
: `<button class="btn mini" data-ledit="${esc(l.id)}">Modifier</button>${(() => { const arm = pendingDel && pendingDel.key === 'list:' + l.id && pendingDel.until > Date.now(); return `<button class="btn mini${arm ? ' danger' : ''}" data-ldel="${esc(l.id)}">${arm ? 'Confirmer ?' : 'Supprimer'}</button>`; })()}`}
</div>
</div>`;
$('listsCol').innerHTML = `<h4>Listes intégrées <small class="muted">(non modifiables)</small></h4>${PRESET_LISTS.map(l => item(l, true)).join('')}
<h4>Mes listes</h4>${st.lists.map(l => item(l, false)).join('') || '<p class="muted">Aucune liste personnelle pour l\'instant.</p>'}
<button class="btn primary" data-lnew>+ Nouvelle liste</button>`;
renderListEdit();
}
function renderListEdit() {
const el = $('listEdit');
if (!editList) { el.innerHTML = `<p class="muted">Choisis « Nouvelle liste », « Copier » (à partir d'une liste intégrée) ou « Modifier ».<br><br>
Une liste = des <b>entreprises ferroviaires</b> (tous leurs trains en circulation et au départ dans l'heure) et/ou des <b>numéros de train</b>
(ajoutés en plus, jamais filtrés ; jour précis possible : 42920@27/10).</p>`; return; }
const name = c => (companies || []).find(x => x.c === c);
el.innerHTML = `
<label class="muted">Nom de la liste</label>
<input id="leName" class="field" maxlength="40" value="${esc(editList.name)}" placeholder="Ex. : Lineas Belgique, Shift nuit…">
<label class="muted">Entreprises ferroviaires (laisser vide pour une liste de numéros seulement)</label>
<div class="chips">${editList.ruCodes.map(c => `<span class="chip co" title="${esc((name(c) || {}).n || '')}">${esc(c)}${name(c) ? ' · ' + esc(name(c).n) : ''}<button data-lrm="${esc(c)}" title="Retirer">×</button></span>`).join('') || '<span class="muted small">aucune</span>'}</div>
<input id="leSearch" class="field" placeholder="${companies ? 'Chercher une entreprise : nom ou code (ex. Lineas, 0088.2188)…' : 'Chargement de la liste des entreprises TIS…'}" ${companies ? '' : 'disabled'}>
<div class="sugg" id="leSugg"></div>
<label class="muted">Numéros de train en plus (hors filtre), jour optionnel : 42920@27/10</label>
<input id="leTrains" class="field" value="${esc(editList.trains)}" placeholder="40146, 42920@27/10 …">
<div class="modal-foot"><button class="btn primary" data-lsave>Enregistrer${st.active.id === editList.id ? '' : ' et utiliser'}</button><button class="btn" data-lcancel>Annuler</button><span class="muted" id="leMsg"></span></div>`;
$('leSearch') && ($('leSearch').oninput = () => renderSugg());
}
function renderSugg() {
const q = $('leSearch').value.trim().toLowerCase();
if (!q || !companies) { $('leSugg').innerHTML = ''; return; }
const hits = companies.filter(x => !editList.ruCodes.includes(x.c) && (x.n.toLowerCase().includes(q) || x.c.toLowerCase().includes(q))).slice(0, 40);
$('leSugg').innerHTML = hits.map(x => `<button class="sg" data-ladd="${esc(x.c)}"><b>${esc(x.n)}</b><span>${esc(x.c)} · ${esc(x.cc)}</span></button>`).join('')
+ (hits.length > 1 ? `<button class="sg all" data-laddall="1">+ Ajouter les ${hits.length} résultats</button>` : '')
|| '<p class="muted small">Aucune entreprise trouvée.</p>';
}
async function openLists() {
$('listsModal').hidden = false; renderLists();
if (!companies) {
const r = await send({ type: 'companies' }).catch(() => null);
companies = r && r.ok ? r.list : [];
if (editList) renderListEdit();
}
}
// ---------- Panneau debug ----------
const fmtAgo = iso => { if (!iso) return '—'; const s = Math.round((Date.now() - Date.parse(iso)) / 1000); return `${new Date(iso).toLocaleTimeString('fr-BE')} (il y a ${s < 90 ? s + ' s' : Math.round(s / 60) + ' min'})`; };
function renderDebug() {
const on = !!st.prefs.debug;
$('debug').hidden = !on;
document.body.classList.toggle('debug-on', on);
if (!on) return;
const s = st.stats || {}, d = st.data || {}, ss = st.session || {};
const kv = (k, v, bad) => `<span>${k}</span><b class="${bad ? 'bad' : ''}">${esc(v)}</b>`;
$('dbgStats').innerHTML = [
kv('Version (fichiers / moteur)', `${VERSION} / ${s.version || '?'}`, s.version && s.version !== VERSION),
kv('Session TIS', st.loginWin ? 'connexion en cours' : ss.ok ? `connecté${ss.name ? ' · ' + ss.name : ''}` : ss.ok === false ? 'NON CONNECTÉ' : 'inconnue', ss.ok === false),
kv('Liste active', `${st.active.name}${st.active.definition ? ` (${(st.active.definition.ruCodes || []).length} entreprises)` : ' (numéros seulement)'}`),
kv('Dernière mise à jour réussie', fmtAgo(d.updatedAt)),
kv('Dernier cycle', s.lastCycleMs != null ? `${s.lastCycleMs} ms` : '—'),
kv('Dernier appel TIS', s.lastRoute ? `${s.lastRoute} · HTTP ${s.lastStatus ?? '?'} · ${s.lastMs ?? '?'} ms` : '—'),
kv('Requêtes TIS', `${s.requests || 0} (dont détail : ${s.detailRequests || 0}, composition : ${s.compoRequests || 0})`),
kv('Cycles réussis / erreurs', `${s.okCycles || 0} / ${s.errors || 0}`, (s.errors || 0) > 0),
kv('Dernière erreur', s.lastError ? `${s.lastError} — ${fmtAgo(s.lastErrorAt)}` : 'aucune', !!s.lastError),
kv('État actuel', d.error ? 'ERREUR : ' + d.error : 'OK', !!d.error),
kv('Numéros en plus', extrasText() || '—'),
].join('');
const errOnly = $('dbgErrOnly').checked;
const lines = [...st.debug].reverse().filter(e => !errOnly || e.l !== 'info');
$('dbgLog').replaceChildren(...lines.map(e => {
const div = document.createElement('div');
if (e.l !== 'info') div.className = e.l;
const tm = document.createElement('span'); tm.className = 't'; tm.textContent = new Date(e.t).toLocaleTimeString('fr-BE');
div.append(tm, e.m);
if (e.d) { const x = document.createElement('span'); x.className = 'd'; x.textContent = ' ' + JSON.stringify(e.d); div.append(x); }
return div;
}));
if (!lines.length) $('dbgLog').textContent = 'Journal vide.';
}
function fillSettings() {
const p = st.prefs;
$('pSound').checked = p.sound; $('pDesktop').checked = p.desktop; $('pToasts').checked = p.toasts !== false; $('pDebug').checked = p.debug; $('pAutoLogin').checked = p.autoLogin;
$('pDelay').value = p.delayAlertMin; $('pEtd').value = p.etdMin; $('pYellow').value = p.overdueYellowMin; $('pRed').value = p.overdueRedMin; $('pStaleOn').checked = p.staleOn;
document.querySelectorAll('[data-ev]').forEach(c => c.checked = !!p.ev[c.dataset.ev]);
$('cYellow').value = st.cfg.yellowFromMin; $('cRed').value = st.cfg.redFromMin;
$('pUpcoming').value = p.upcomingMin; $('pLate').value = p.lateLookbackMin;
}
async function reload() {
const s = await chrome.storage.local.get(['trains', 'data', 'alerts', 'prefs', 'cfg', 'debug', 'stats', 'session', 'loginWin', 'tisFilters', 'tisFilter',
'lists', 'extras', 'pins', 'notes', 'handoverNote', 'alertsSeen']);
// alertes déjà vues (partagé entre les onglets TTA ouverts) ; première ouverture : rien n'est « nouveau »
if (alertsSeen == null) alertsSeen = s.alertsSeen || ((s.alerts || [])[0] || {}).at || '';
else if (s.alertsSeen && s.alertsSeen > alertsSeen) alertsSeen = s.alertsSeen;
st = {
data: s.data || null, alerts: s.alerts || [], debug: s.debug || [], stats: s.stats || {},
session: s.session || null, loginWin: s.loginWin || null, tisFilters: s.tisFilters || [], tisFilter: s.tisFilter || null,
lists: s.lists || [], pins: s.pins || {}, notes: s.notes || {}, handoverNote: s.handoverNote || '',
prefs: { ...DEFAULT_PREFS, ...(s.prefs || {}), ev: { ...DEFAULT_PREFS.ev, ...((s.prefs || {}).ev || {}) } },
cfg: { yellowFromMin: 5, redFromMin: 15, ...(s.cfg || {}) },
};
st.active = resolveList(st.prefs, { lists: st.lists, tisFilters: st.tisFilters, tisFilter: st.tisFilter });
st.extras = s.extras || (s.trains && s.trains.length ? { [st.active.id]: s.trains } : {});
st.trains = st.extras[st.active.id] || [];
applyZoom();
render();
showToasts();
if ($('settingsPop').hidden) fillSettings();
if (!$('listsModal').hidden && !(document.activeElement && /^le/.test(document.activeElement.id))) renderLists();
}
const savePrefs = patch => chrome.storage.local.set({ prefs: { ...st.prefs, ...patch, ev: { ...st.prefs.ev, ...(patch.ev || {}) } } });
const num = (el, min, max, fb) => { const v = Math.round(Number(el.value)); return v >= min && v <= max ? v : fb; };
const login = () => send({ type: 'login' });
const closeAll = () => { $('settingsPop').hidden = true; $('alertsPop').hidden = true; };
// Croix et suppressions : 1er clic arme, 2e clic au même endroit confirme (4 s pour confirmer).
function armOrRun(key, action) {
if (pendingDel && pendingDel.key === key && pendingDel.until > Date.now()) { pendingDel = null; action(); return; }
pendingDel = { key, until: Date.now() + 4000 };
render(); if (!$('listsModal').hidden) renderLists();
setTimeout(() => { if (pendingDel && pendingDel.key === key && pendingDel.until <= Date.now()) { pendingDel = null; render(); if (!$('listsModal').hidden) renderLists(); } }, 4100);
}
function removeRow(t) {
if (panelKey === rowKey(t)) panelKey = null;
return t.src === 'filter' ? send({ type: 'hide', id: t.id, otn: mainNum(t) }) : send({ type: 'remove', otn: mainNum(t) });
}
// ---------- Événements ----------
$('numbers').addEventListener('focus', () => editing = true);
$('numbers').addEventListener('blur', () => setTimeout(() => editing = false, 200));
$('editor').addEventListener('submit', async e => { e.preventDefault(); editing = false; await send({ type: 'setTrains', numbers: $('numbers').value }); });
$('force').onclick = async () => {
const r = await send({ type: 'force' });
$('countdown').textContent = r && !r.ok ? '⏱ ' + r.error : '⏳ mise à jour demandée…';
};
$('list').addEventListener('click', e => {
const u = e.target.closest('[data-uselist]');
if (u) return send({ type: 'setList', id: u.dataset.uselist });
const del = e.target.closest('[data-del]');
if (del) { e.stopPropagation(); const t = findRow(del.dataset.del); if (t) armOrRun(del.dataset.del, () => removeRow(t)); return; }
const tl = e.target.closest('[data-tis]');
if (tl) { e.stopPropagation(); const t = findRow(tl.dataset.tis); if (t) openTis(t); return; }
const pb = e.target.closest('[data-print]');
if (pb) { e.stopPropagation(); const t = findRow(pb.dataset.print); if (t) openPrint(t); return; }
const row = e.target.closest('.row[data-key]');
if (row) { panelKey = panelKey === row.dataset.key ? null : row.dataset.key; render(); }
});
// Fiche du train
$('panel').addEventListener('click', e => {
const t = findRow(panelKey);
if (e.target.closest('[data-pclose]')) { panelKey = null; render(); return; }
if (!t) return;
if (e.target.closest('[data-ptis]')) return openTis(t);
if (e.target.closest('[data-pprint]')) return openPrint(t);
if (e.target.closest('[data-proute]')) return openPrint(t, true);
if (e.target.closest('[data-pdel]')) { armOrRun('p:' + panelKey, () => removeRow(t)); return; }
const alt = e.target.closest('[data-alt]');
if (alt) {
if (t.src === 'list') send({ type: 'pin', otn: mainNum(t), date: alt.dataset.alt });
else send({ type: 'track', otn: mainNum(t), date: alt.dataset.alt });
panelKey = t.src === 'list' ? 'q:' + mainNum(t) : panelKey; return;
}
if (e.target.closest('[data-pdate]')) {
const v = $('pDate').value;
if (!v) return;
if (t.src === 'list') { send({ type: 'pin', otn: mainNum(t), date: v }); panelKey = 'q:' + mainNum(t); }
else { send({ type: 'track', otn: mainNum(t), date: v }); panelKey = 'q:' + mainNum(t); }
return;
}
if (e.target.closest('[data-pauto]')) send({ type: 'pin', otn: mainNum(t), date: null });
});
let noteTimer = null;
$('panel').addEventListener('input', e => {
if (e.target.id !== 'pNote') return;
const t = findRow(panelKey); if (!t) return;
const k = noteKey(t), v = e.target.value;
clearTimeout(noteTimer);
noteTimer = setTimeout(() => { const notes = { ...st.notes }; if (v.trim()) notes[k] = v; else delete notes[k]; chrome.storage.local.set({ notes }); }, 400);
});
// Section « Arrivés » (repliable) : mêmes clics que la liste principale
$('arrived').addEventListener('click', e => {
if (e.target.closest('[data-arrtoggle]')) return savePrefs({ arrivedOpen: !st.prefs.arrivedOpen });
const del = e.target.closest('[data-del]');
if (del) { const t = findRow(del.dataset.del); if (t) armOrRun(del.dataset.del, () => removeRow(t)); return; }
const tl = e.target.closest('[data-tis]');
if (tl) { const t = findRow(tl.dataset.tis); if (t) openTis(t); return; }
const pb = e.target.closest('[data-print]');
if (pb) { const t = findRow(pb.dataset.print); if (t) openPrint(t); return; }
const row = e.target.closest('.row[data-key]');
if (row) { panelKey = panelKey === row.dataset.key ? null : row.dataset.key; render(); }
});
$('hiddenbar').addEventListener('click', e => { if (e.target.id === 'unhide') send({ type: 'unhideAll' }); });
// Recherche dynamique
const setQuery = v => { query = v; $('q').value = v; render(); };
$('q').addEventListener('input', e => { query = e.target.value; render(); });
$('q').addEventListener('keydown', e => { if (e.key === 'Escape') { e.stopPropagation(); setQuery(''); $('q').blur(); } });
$('qClear').onclick = () => { setQuery(''); $('q').focus(); };
document.addEventListener('click', e => { if (e.target.closest('[data-qclear]')) setQuery(''); });
document.addEventListener('keydown', e => {
const typing = /INPUT|TEXTAREA|SELECT/.test((document.activeElement || {}).tagName || '');
if (e.key === '/' && !typing) { e.preventDefault(); $('q').focus(); $('q').select(); }
});
// Signaler un bug : le lien reçoit le mail prérempli au moment du clic
for (const id of ['bugBtn', 'bugBtn2']) $(id).addEventListener('click', e => { e.currentTarget.href = bugMailto(); });
$('bugWeb').addEventListener('click', e => { e.currentTarget.href = bugOutlookWeb(); });
$('source').onchange = e => send({ type: 'setList', id: e.target.value });
const loadFilters = () => send({ type: 'listFilters' }).catch(() => {});
$('refreshFilters').onclick = loadFilters;
$('pUpcoming').onchange = e => savePrefs({ upcomingMin: num(e.target, 0, 720, 60) });
$('pLate').onchange = e => savePrefs({ lateLookbackMin: num(e.target, 0, 720, 180) });
$('summary').addEventListener('click', e => {
const t = e.target.closest('[data-filter]');
if (!t) return;
filter = filter === t.dataset.filter ? null : t.dataset.filter;
render();
});
document.addEventListener('click', e => { if (e.target.closest('[data-login]')) login(); });
$('session').onclick = login;
$('setLogin').onclick = login;
// Listes
$('listsBtn').onclick = openLists;
$('setLists').onclick = () => { closeAll(); openLists(); };
$('listsModal').addEventListener('click', async e => {
const b = e.target.closest('button'); if (!b) { if (e.target === $('listsModal')) $('listsModal').hidden = true; return; }
const d = b.dataset;
if ('close' in d) { $('listsModal').hidden = true; editList = null; return; }
if (d.luse) { await send({ type: 'setList', id: d.luse }); return; }
if ('lnew' in d) { editList = { id: null, name: '', ruCodes: [], trains: '' }; return renderLists(); }
if (d.ldup) { const l = PRESET_LISTS.find(x => x.id === d.ldup); editList = { id: null, name: l.name + ' (copie)', ruCodes: [...l.ruCodes], trains: '' }; return renderLists(); }
if (d.ledit) { const l = st.lists.find(x => x.id === d.ledit); editList = { id: l.id, name: l.name, ruCodes: [...(l.ruCodes || [])], trains: (st.extras[l.id] || []).map(n => st.pins[n] ? `${n}@${ddmm(st.pins[n])}` : n).join(', ') }; return renderLists(); }
if (d.ldel) return armOrRun('list:' + d.ldel, async () => { if (editList && editList.id === d.ldel) editList = null; await send({ type: 'deleteList', id: d.ldel }); });
if (d.lrm) { editList.ruCodes = editList.ruCodes.filter(c => c !== d.lrm); editList.name = $('leName').value; editList.trains = $('leTrains').value; return renderListEdit(); }
if (d.ladd) { editList.ruCodes.push(d.ladd); editList.name = $('leName').value; editList.trains = $('leTrains').value; const q = $('leSearch').value; renderListEdit(); $('leSearch').value = q; $('leSearch').focus(); return renderSugg(); }
if (d.laddall) { const q = $('leSearch').value.trim().toLowerCase(); for (const x of companies.filter(x => !editList.ruCodes.includes(x.c) && (x.n.toLowerCase().includes(q) || x.c.toLowerCase().includes(q))).slice(0, 40)) editList.ruCodes.push(x.c); editList.name = $('leName').value; editList.trains = $('leTrains').value; return renderListEdit(); }
if ('lcancel' in d) { editList = null; return renderLists(); }
if ('lsave' in d) {
const r = await send({ type: 'saveList', list: { id: editList.id, name: $('leName').value, ruCodes: editList.ruCodes, trains: $('leTrains').value } });
if (!r || !r.ok) { $('leMsg').textContent = (r && r.error) || 'Erreur'; return; }
const wasActive = st.active.id === editList.id;
editList = null;
if (!wasActive) await send({ type: 'setList', id: r.id });
renderLists();
}
});
// Impression de l'horaire
const savePo = patch => savePrefs({ printOpts: { ...po(), ...patch } });
$('printModal').addEventListener('click', e => {
if (e.target === $('printModal') || e.target.closest('[data-close]')) { $('printModal').hidden = true; pr = null; return; }
if (!pr || !pr.rows) return;
if (e.target.closest('[data-prgo]')) { pr.q = ''; $('prQ').value = ''; pr.scrolled = false; return renderRoute(); }
if (e.target.closest('[data-prall]')) { pr.from = 0; pr.to = pr.rows.length - 1; return renderPrint(); }
if (e.target.closest('[data-prhere]')) { const c = pr.rows.find(x => x.current); if (c) pr.from = c.i; return renderPrint(); }
const m = e.target.closest('[data-mode]');
if (m) { const full = m.dataset.mode === 'full'; savePo({ colReal: full, colGap: full }).then(renderPrint); }
});
$('printModal').addEventListener('change', e => {
if (!pr || !pr.rows) return;
if (e.target.id === 'prFrom') { pr.from = Number(e.target.value); if (pr.to < pr.from) pr.to = pr.rows.length - 1; return renderPrint(); }
if (e.target.id === 'prTo') { pr.to = Number(e.target.value); if (pr.from > pr.to) pr.from = 0; return renderPrint(); }
const k = e.target.dataset && e.target.dataset.po;
if (k) savePo({ [k]: e.target.checked }).then(renderPrint);
});
$('printModal').addEventListener('input', e => {
if (e.target.id !== 'prQ' || !pr || !pr.rows) return;
pr.q = e.target.value;
renderRoute();
});
// En mode Parcours, « Imprimer… » passe aux options d'impression (tout le parcours sélectionné)
$('prPrint').onclick = () => {
if (!pr || !pr.rows) return;
if (pr.view) { pr.view = false; prModeUi(); $('prCtrl').innerHTML = ''; return renderPrint(); }
printNow();
};
$('prCopy').onclick = async () => {
if (!pr || !pr.rows) return;
try { await navigator.clipboard.writeText(printText()); $('prCopy').textContent = 'Copié ✓'; } catch { $('prCopy').textContent = 'Échec'; }
setTimeout(() => $('prCopy').textContent = 'Copier le texte', 1500);
};
// Relève
$('handoverBtn').onclick = () => { closeAll(); $('handoverModal').hidden = false; renderHandover(); };
$('handoverModal').addEventListener('click', e => { if (e.target === $('handoverModal') || e.target.closest('[data-close]')) $('handoverModal').hidden = true; });
$('handoverNote').addEventListener('input', e => { st.handoverNote = e.target.value; $('handoverText').textContent = handoverText(); chrome.storage.local.set({ handoverNote: e.target.value }); });
$('hoCopy').onclick = async () => {
try { await navigator.clipboard.writeText(handoverText()); $('hoCopy').textContent = 'Copié ✓'; } catch { $('hoCopy').textContent = 'Échec'; }
setTimeout(() => $('hoCopy').textContent = 'Copier', 1500);
};
$('hoPrint').onclick = () => {
const w = window.open('', '_blank');
w.document.write(`<!doctype html><meta charset="utf-8"><title>Relève TTA</title><pre style="font:13px/1.5 Consolas,monospace;white-space:pre-wrap">${esc(handoverText())}</pre>`);
w.document.close(); w.focus(); w.print();
};
$('soundBtn').onclick = () => savePrefs({ sound: !st.prefs.sound });
$('settingsBtn').onclick = e => { e.stopPropagation(); $('alertsPop').hidden = true; fillSettings(); $('settingsPop').hidden = !$('settingsPop').hidden; };
$('tickerBtn').onclick = e => { e.stopPropagation(); toggleAlerts('bottom'); };
$('alertsBtn').onclick = e => { e.stopPropagation(); toggleAlerts('top'); };
$('alertsPop').addEventListener('click', e => {
if (e.target.closest('[data-popclose]')) { $('alertsPop').hidden = true; return; }
const it = e.target.closest('[data-al]');
if (it) { $('alertsPop').hidden = true; openAlert(st.alerts[Number(it.dataset.al)]); }
});
$('toasts').addEventListener('click', e => {
const el = e.target.closest('.toast');
if (!el) return;
if (!e.target.closest('[data-tclose]') && el._alert) openAlert(el._alert);
dismissToast(el);
});
document.addEventListener('visibilitychange', () => { if (!document.hidden) document.querySelectorAll('#toasts .toast').forEach(el => el._arm && el._arm()); });
// Taille d'affichage : − / 100 % / + (mémorisée)
const setZoom = z => savePrefs({ zoom: Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, Math.round(z * 10) / 10)) });
$('zoomIn').onclick = () => setZoom((st.prefs.zoom || 1) + 0.1);
$('zoomOut').onclick = () => setZoom((st.prefs.zoom || 1) - 0.1);
$('zoomVal').onclick = () => setZoom(1);
document.addEventListener('click', e => {
if (!e.target.closest('.pop') && !e.target.closest('#settingsBtn') && !e.target.closest('#tickerBtn') && !e.target.closest('#alertsBtn')) closeAll();
});
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
closeAll();
if (!$('printModal').hidden) { $('printModal').hidden = true; pr = null; }
else if (!$('listsModal').hidden) { $('listsModal').hidden = true; editList = null; }
else if (!$('handoverModal').hidden) $('handoverModal').hidden = true;
else if (panelKey) { panelKey = null; render(); }
});
$('themeSeg').addEventListener('click', e => { const b = e.target.closest('[data-theme]'); if (b) savePrefs({ theme: b.dataset.theme }); });
$('pSound').onchange = e => savePrefs({ sound: e.target.checked });
$('pDesktop').onchange = e => savePrefs({ desktop: e.target.checked });
$('pToasts').onchange = e => savePrefs({ toasts: e.target.checked });
$('pAutoLogin').onchange = e => savePrefs({ autoLogin: e.target.checked });
$('pStaleOn').onchange = e => savePrefs({ staleOn: e.target.checked });
$('pDebug').onchange = e => savePrefs({ debug: e.target.checked });
$('pDelay').onchange = e => savePrefs({ delayAlertMin: num(e.target, 1, 600, 10) });
$('pEtd').onchange = e => savePrefs({ etdMin: num(e.target, 1, 600, 5) });
$('pYellow').onchange = e => { const y = num(e.target, 0, 600, 5); savePrefs({ overdueYellowMin: y, overdueRedMin: Math.max(y + 1, st.prefs.overdueRedMin) }); };
$('pRed').onchange = e => savePrefs({ overdueRedMin: Math.max(st.prefs.overdueYellowMin + 1, num(e.target, 1, 600, 15)) });
document.querySelectorAll('[data-ev]').forEach(c => c.onchange = () => savePrefs({ ev: { [c.dataset.ev]: c.checked } }));
document.querySelectorAll('[data-test]').forEach(b => b.onclick = () => ttaPlay(b.dataset.test)); // aperçu du son (même si les sons sont coupés)
const saveCfg = () => chrome.storage.local.set({ cfg: { yellowFromMin: num($('cYellow'), 1, 600, 5), redFromMin: num($('cRed'), 1, 600, 15) } });
$('cYellow').onchange = saveCfg; $('cRed').onchange = saveCfg;
$('dbgClose').onclick = () => savePrefs({ debug: false });
$('dbgErrOnly').onchange = renderDebug;
$('dbgClear').onclick = () => send({ type: 'clearDebug' });
$('dbgCopy').onclick = async () => {
const s = st.stats || {}, d = st.data || {};
const head = `TTA v${VERSION} (moteur ${s.version || '?'}) · ${new Date().toLocaleString('fr-BE')}\nsession: ${st.session && st.session.ok ? 'connecté' : 'non connecté'}\nliste: ${st.active.name} · en plus: ${extrasText()}\nétat: ${d.error || 'OK'}\nstats: ${JSON.stringify(s)}\nlignes: ${JSON.stringify((d.rows || []).map(r => ({ otn: r.otn, q: r.query, nums: r.numbers, phase: r.phase, color: r.color, delay: r.delay, ping: r.lastPingAt, next: r.next && r.next.name })))}\n\n`;
const body = [...st.debug].map(e => `${new Date(e.t).toLocaleTimeString('fr-BE')} [${e.l}] ${e.m}${e.d ? ' ' + JSON.stringify(e.d) : ''}`).join('\n');
try { await navigator.clipboard.writeText(head + body); $('dbgCopy').textContent = 'Copié ✓'; } catch { $('dbgCopy').textContent = 'Échec'; }
setTimeout(() => $('dbgCopy').textContent = 'Copier', 1500);
};
// Erreurs de la page elle-même : envoyées au journal pour les voir dans le debug.
window.addEventListener('error', e => send({ type: 'dbg', level: 'error', text: `page : ${e.message} (${(e.filename || '').split('/').pop()}:${e.lineno})` }).catch(() => {}));
window.addEventListener('unhandledrejection', e => send({ type: 'dbg', level: 'error', text: `page : promesse rejetée : ${e.reason && e.reason.message || e.reason}` }).catch(() => {}));
// Le moteur écrit plusieurs clés par cycle : un seul rafraîchissement, et on ignore ses caches internes.
const VIEW_KEYS = ['alertsSeen', 'trains', 'data', 'alerts', 'prefs', 'cfg', 'debug', 'stats', 'session', 'loginWin', 'tisFilters', 'tisFilter', 'lists', 'extras', 'pins', 'notes'];
let reloadTimer = null;
chrome.storage.onChanged.addListener(changes => {
const keys = Object.keys(changes);
if (!keys.some(k => VIEW_KEYS.includes(k))) return;
if (!st.prefs.debug && keys.every(k => k === 'debug')) return; // journal masqué : inutile de redessiner
clearTimeout(reloadTimer);
reloadTimer = setTimeout(reload, 120);
});
$('ver').textContent = 'v' + VERSION;
setInterval(tickLive, 1000);
setInterval(render, 30000); // rafraîchit les « il y a X min » même sans nouvelle donnée
// Pendant une connexion, la page vérifie aussi la session (filet de sécurité si la fenêtre ne se ferme pas seule).
setInterval(() => { if (st.loginWin) send({ type: 'checkSession' }).catch(() => {}); }, 3000);
reload().then(async () => {
if (!st.session || !st.session.checkedAt || Date.now() - st.session.checkedAt > 5 * 60000) await send({ type: 'checkSession' }).catch(() => {});
if (!st.session || st.session.ok !== false) loadFilters();
});