TTA v2.1.1 - extension Chrome de suivi temps réel des trains sur RNE TIS
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# fichiers locaux / de travail
|
||||
_preview.html
|
||||
*.zip
|
||||
node_modules/
|
||||
|
||||
# système
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
.DS_Store
|
||||
@@ -0,0 +1,201 @@
|
||||
TTA - TRAIN TIME ACCURACY (extension Chrome, v2.1) - powered by SIBELIT
|
||||
By LinkAtPlug Co. (c) 2026
|
||||
=========================================================================
|
||||
Suivi en temps réel des trains TIS (RNE) pour la régulation / le real time :
|
||||
retard, position, dernier pointage, prochain point, départ, arrivée, causes de retard,
|
||||
alertes sonores, consignes par train et rapport de relève.
|
||||
|
||||
TOUT-EN-UN : rien d'autre à installer ni à lancer (pas de serveur, pas de Node.js,
|
||||
pas d'onglet TIS à garder ouvert). Fonctionne avec Google Chrome (et Edge, Brave).
|
||||
|
||||
|
||||
1. INSTALLATION (une seule fois)
|
||||
--------------------------------
|
||||
1. Dézippe le dossier "tis-extension" à un endroit où il restera (ex : C:\tis-extension).
|
||||
2. Chrome : chrome://extensions > active "Mode développeur" (en haut à droite)
|
||||
> "Charger l'extension non empaquetée" > choisis le dossier "tis-extension".
|
||||
3. Épingle l'icône TTA (icône puzzle de Chrome).
|
||||
MISE À JOUR : remplace les fichiers du dossier, puis "Recharger l'extension" (bandeau de la
|
||||
page TTA) ou chrome://extensions > ↻.
|
||||
|
||||
|
||||
2. CONNEXION À TIS (intégrée)
|
||||
-----------------------------
|
||||
Bouton "Se connecter à TIS" : une petite fenêtre Microsoft s'ouvre, tu te connectes, elle se
|
||||
ferme toute seule. Si la session expire, TTA tente une reconnexion automatique ; sinon une
|
||||
notification "Connexion TIS requise" ouvre la fenêtre d'un clic.
|
||||
TTA ne voit jamais ton mot de passe.
|
||||
|
||||
|
||||
3. LES LISTES DE TRAINS (sélecteur à gauche de la barre + bouton ✎)
|
||||
--------------------------------------------------------------------
|
||||
LISTES INTÉGRÉES (prêtes à l'emploi, non modifiables) :
|
||||
- "Mes trains · SIBELIT" (par défaut) : les 5 entités SIBELIT dans TIS.
|
||||
- "Mes trains · Lineas" : les 19 entités Lineas (BE, FR, LU, DE, AT, IT, NL, Intermodal).
|
||||
- "Liste manuelle" : uniquement les numéros que tu tapes.
|
||||
Une liste par entreprise affiche automatiquement :
|
||||
- tous ses trains EN CIRCULATION,
|
||||
- + ceux qui PARTENT DANS LES 60 PROCHAINES MINUTES (bleu "Pas parti · dans X min"),
|
||||
- + ceux PAS PARTIS À L'HEURE, jusqu'à 3 h après l'heure prévue ("ETD +X min").
|
||||
(durées réglables dans Réglages)
|
||||
|
||||
MES LISTES (bouton ✎ "Gérer mes listes") :
|
||||
- "Nouvelle liste" ou "Copier" une liste intégrée pour partir de ses entreprises.
|
||||
- Chercher une entreprise par nom ou code (ex. "Lineas", "0088.2188") et l'ajouter
|
||||
("Ajouter les N résultats" pour tout prendre d'un coup).
|
||||
- Ajouter des numéros de train à la liste.
|
||||
- "Modifier", "Supprimer" (2 clics pour confirmer), "Utiliser".
|
||||
- Tes filtres enregistrés dans TIS sont aussi proposés ("Filtre TIS · ...").
|
||||
|
||||
TRAINS EN PLUS (champ texte de la barre) : numéros suivis EN PLUS de la liste active,
|
||||
JAMAIS filtrés par entreprise (n'importe quel train de TIS). Chaque liste a les siens.
|
||||
Jour précis (optionnel, sinon le train du jour / en cours) : 42920@27/10 ou 42920@27/10/2026
|
||||
|
||||
|
||||
4. LIRE LA PAGE
|
||||
---------------
|
||||
Chaque ligne : STATUT · TRAIN · ITINÉRAIRE · POSITION + DERNIER POINTAGE · PROCHAIN POINT ·
|
||||
DÉPART · ARRIVÉE.
|
||||
- Colonne COMPO (véh-m-t) : la composition en grand, ex. 31-653-902 = 31 véhicules,
|
||||
653 m, 902 t (POIDS DU TRAIN, pas le poids freiné), tirée de l'onglet « Train composition »
|
||||
de TIS ; détail « 31 véh · 653 m · 902 t » en dessous. Si TIS n'en a pas : « Compo non
|
||||
trouvée » (orange). « chargement » pendant la première minute. Si le train change de
|
||||
composition en route (une par section / gestionnaire d'infrastructure), c'est celle de la
|
||||
section où il se trouve (survol = quelle section).
|
||||
- Sous le numéro : "⇄ 42921" = autres numéros du même train (le numéro change en route, souvent à
|
||||
la frontière ; survol = toute la chaîne 42920 → 42921). « Voyageurs » n'est indiqué que pour
|
||||
les trains de voyageurs (le fret, cas général, n'est plus répété partout),
|
||||
"📅 27/10" = jour choisi, "📝" = une consigne est notée sur ce train.
|
||||
- COULEURS : rouge ≥ 15 min ou interrompu · jaune 5-15 min · vert en circulation à l'heure ·
|
||||
bleu pas encore parti · gris inactif / non trouvé.
|
||||
- TRAINS ARRIVÉS : rangés à part, dans la section « 🏁 Arrivés (N) » en bas du tableau,
|
||||
repliable d'un clic (le choix est gardé). Repliée, elle montre le résumé : « 2 à l'heure ·
|
||||
1 en retard · 1 gros retard ». Chaque arrivée a une barre HACHURÉE, le drapeau 🏁 et le
|
||||
RETARD À L'ARRIVÉE en grand, coloré : vert à l'heure / en avance, jaune en retard (5-15 min),
|
||||
rouge gros retard (≥ 15 min), gris si inconnu. Colonne Arrivée : heure réelle + écart.
|
||||
Les plus récentes en premier.
|
||||
- PASTILLE DU DERNIER POINTAGE : elle juge l'HORAIRE, pas l'âge du pointage. On regarde l'heure
|
||||
attendue au PROCHAIN POINT (ou, à défaut, à l'arrivée) :
|
||||
bleue = rien d'anormal,
|
||||
jaune = heure attendue dépassée de plus de 5 min sans nouveau pointage,
|
||||
rouge = dépassée de plus de 15 min (« ⚠ attendu 13:25, +30 min »),
|
||||
⏸ grise = STAND-BY : train arrêté depuis longtemps (relais, attente de reprise) mais son
|
||||
prochain point n'est pas encore dû (« arrêt depuis 1 h 29 · reprise 14:24 »).
|
||||
Seuils réglables dans Réglages.
|
||||
- ARRÊT EN GARE / FAISCEAU : quand TIS donne deux fois le même lieu (arrivée puis départ, ex.
|
||||
Thionville-Faisceau Est 13:23 → 16:01), TTA le traite comme un arrêt : la 1re ligne est
|
||||
l'arrivée, la dernière le départ. TIS ne pointe souvent pas l'arrivée en faisceau : une fois
|
||||
l'heure d'arrivée passée, le train est affiché « ⏸ à l'arrêt · départ 16:04 » et n'est
|
||||
signalé en retard qu'après l'heure de départ.
|
||||
- DERNIÈRE CAUSE DE RETARD : sous l'itinéraire (ex. « ⚠ +6 · 92 · Occupation de voie (autre
|
||||
train) »). Toutes les causes (comme l'onglet Statistiques de TIS) sont dans la fiche du train.
|
||||
- PROCHAIN POINT : avec « dans 23 min » ou « dépassé 30 min ». TTA remet les étapes TIS dans
|
||||
l'ordre du parcours (TIS les envoie par sections, pas dans l'ordre) et ignore les prévisions
|
||||
isolées sans heure prévue.
|
||||
- HEURES ESTIMÉES « ≈ » : TIS fournit des heures estimées, mais elles sont parfois périmées
|
||||
(calculées avec un ancien retard : ex. un train qui vient de pointer à +63 « estimé » à +34 au
|
||||
point suivant). Quand l'estimation TIS est plus de 15 min en avance sur « heure prévue + retard
|
||||
actuel », TTA affiche cette projection précédée de « ≈ » (survol = explication et heure TIS).
|
||||
Sinon c'est l'heure TIS (elle peut intégrer un rattrapage). Valable pour le prochain point,
|
||||
l'arrivée et l'horaire imprimé.
|
||||
- JOURS : une heure qui n'est pas aujourd'hui porte un repère « J+1 », « J−1 » ou la date
|
||||
(« 27/10 ») ; survol = jour complet.
|
||||
- TENDANCE "▲8" / "▼2" à côté du retard (10 min). Retard prévu à l'arrivée en couleur.
|
||||
- Clic sur un compteur coloré = n'afficher que ces trains.
|
||||
|
||||
RECHERCHE (barre « 🔍 Rechercher » au-dessus du tableau, raccourci : touche / ) :
|
||||
filtre la liste pendant que tu tapes ; ce qui ne correspond pas disparaît (trains arrivés compris).
|
||||
Cherche dans : numéros (y compris les numéros liés), gares d'origine / destination, position,
|
||||
prochain point, composition, cause de retard, consignes. Plusieurs mots = tous doivent
|
||||
correspondre (ex. « basel 1663 »). Accents et majuscules ignorés. « 5 / 15 trains » indique le
|
||||
résultat. Échap ou ✕ efface.
|
||||
|
||||
CLIC SUR LE NUMÉRO D'UN TRAIN : ouvre directement sa page dans TIS.
|
||||
CLIC AILLEURS SUR LA LIGNE : ouvre la FICHE DU TRAIN (volet à droite) :
|
||||
- "Ouvrir dans TIS ↗", "Masquer 24 h" / "Retirer de la liste",
|
||||
- horaires complets, tous les numéros du train (ex. 42920 → 42921),
|
||||
- JOUR DU TRAIN : les autres jours trouvés dans TIS (clic pour suivre ce jour-là),
|
||||
ou une date au choix ; "Automatique" pour revenir au train du jour,
|
||||
(pour un train d'une liste par entreprise : "Ajouter" le suit un autre jour en plus),
|
||||
- COMPOSITION de chaque section (ex. Gallarate → Chiasso 18-552-1540, Chiasso → Basel
|
||||
18-571-1630…), la section actuelle surlignée,
|
||||
- CAUSES DE RETARD déclarées dans TIS (codes UIC, ex. "64 · Locomotive / engin moteur"),
|
||||
- CONSIGNE / NOTE de suivi (gardée, reprise dans le rapport de relève).
|
||||
Échap ferme la fiche.
|
||||
|
||||
IMPRIMER L'HORAIRE (bouton 🖨 sous la croix de chaque train, ou « Imprimer l'horaire » dans la
|
||||
fiche) : TTA récupère l'horaire complet du train dans TIS. Tout est MODULABLE (choix mémorisés) :
|
||||
- Tronçon : « De » tel point « à » tel point (chaque point avec son jour), ou « Depuis la position
|
||||
actuelle » / « Tout le parcours ».
|
||||
- Horaire : « Théorique seul » (heures prévues uniquement) ou « Avec réel / prévisions » ;
|
||||
seulement départ / arrêts / arrivée ; masquer les points techniques (aiguilles, bif., postes…,
|
||||
seulement des passages, jamais un arrêt).
|
||||
- Colonnes : Date · Type · Heures réelles / estimées · Écart · Gestionnaire (GI).
|
||||
- Informations en tête : départ et arrivée du train avec DATES COMPLÈTES (ex. lun. 26/10/2026
|
||||
07:58 → mar. 27/10/2026 01:11) · composition · retard actuel · dernier pointage.
|
||||
Une information non disponible (ex. pas de composition) n'est pas imprimée.
|
||||
- DATES : colonne Date avec un trait de séparation à chaque changement de jour (trains de plusieurs
|
||||
jours, passage de minuit) ; si l'arrivée et le départ d'un arrêt tombent sur deux jours, la date
|
||||
est rappelée à côté de l'heure.
|
||||
- « Imprimer » ouvre directement la boîte d'impression (sans onglet « about:blank », sans date ni
|
||||
titre ajoutés par le navigateur). Si ton Chrome les ajoute quand même : décoche « En-têtes et
|
||||
pieds de page » dans la boîte d'impression. « Copier le texte » donne la même chose en texte.
|
||||
|
||||
LA CROIX (x) : 1er clic = elle devient "Retirer ?" / "Masquer ?" au même endroit,
|
||||
2e clic = confirmé (4 secondes pour confirmer, sinon elle revient).
|
||||
|
||||
TRAIN NON TROUVÉ / PARITÉ : le numéro d'un train change souvent en route, en particulier à la
|
||||
frontière (ex. 42920 au départ de Belgique devient 42921 en France). TTA :
|
||||
- reconnaît un train par TOUS ses numéros (chercher 42921 trouve le train 42920 → 42921),
|
||||
- si un numéro est introuvable, essaie automatiquement son jumeau de parité (42920 ↔ 42921,
|
||||
776 ↔ 777) et l'indique ("trouvé sous le n° 42921 : le numéro change de parité"),
|
||||
- sinon affiche "Introuvable dans TIS, ni sous 42920 ni sous 42921" : vérifie le numéro
|
||||
ou choisis un autre jour.
|
||||
|
||||
|
||||
5. RAPPORT DE RELÈVE (bouton 📋 Relève)
|
||||
---------------------------------------
|
||||
État complet des circulations pour l'équipe suivante (3x8), prêt à copier ou imprimer :
|
||||
retards importants / interrompus, pas partis à l'heure, retards, départs à venir, en
|
||||
circulation à l'heure, arrivés, non trouvés — avec position, dernier pointage, arrivée
|
||||
estimée, composition (véhicules-longueur-poids, ou « compo non trouvée »), cause de retard et
|
||||
consignes. Zone "Remarques" gardée d'une relève à l'autre.
|
||||
|
||||
|
||||
6. ALERTES (sons + notifications, tout est réglable dans ⚙ Réglages)
|
||||
--------------------------------------------------------------------
|
||||
Départ · Retard ≥ +10 min · Pas parti (ETD +5 min) · Retard important / interruption ·
|
||||
Arrivée · Connexion TIS requise. Bouton 🔊 = couper/rétablir les sons. ▶ = écouter.
|
||||
Badge sur l'icône TTA : nombre de trains en rouge (sinon en jaune), "!" si TIS injoignable.
|
||||
|
||||
|
||||
7. SIGNALER UN BUG
|
||||
------------------
|
||||
Bouton « 🐞 Signaler un bug » (en bas à droite, et dans Réglages) : ouvre un NOUVEAU MAIL dans ta
|
||||
messagerie (Outlook si c'est ta messagerie par défaut), adressé à maxime@rousseaux.link, sujet
|
||||
« Signalement TIS », avec les infos techniques utiles déjà en bas. Tu décris le problème et tu
|
||||
envoies toi-même. Messagerie sur le web : bouton « Outlook Web » dans Réglages.
|
||||
Pour joindre le journal détaillé : Réglages > Mode debug > « Copier », puis colle-le dans le mail.
|
||||
|
||||
|
||||
8. MODE DEBUG
|
||||
-------------
|
||||
Réglages > "Mode debug" : état et journal détaillé. "Copier" = tout le journal, à m'envoyer.
|
||||
|
||||
|
||||
9. CHARGE SUR TIS
|
||||
-----------------
|
||||
Liste par entreprise : 2 recherches légères / minute. Trains en plus : 1 recherche / minute
|
||||
(+1 si un numéro est introuvable, pour sa parité). Détail d'itinéraire : toutes les 3 min par
|
||||
train, au plus 4 trains par minute. Composition : toutes les 15 min par train, au plus 4 trains
|
||||
par minute (~10-20 Ko). Horaire à imprimer : 1 requête (~100 Ko) seulement quand tu cliques 🖨.
|
||||
Liste des entreprises TIS : chargée une fois par semaine.
|
||||
"Actualiser" : 1 fois toutes les 10 secondes au maximum.
|
||||
|
||||
|
||||
CONFIDENTIALITÉ / BON USAGE
|
||||
---------------------------
|
||||
Aucune donnée n'est envoyée ailleurs que vers tis-prod.rne.eu ; tout reste dans ton navigateur
|
||||
(listes, notes et relève comprises). Ni mot de passe ni cookie lus ou enregistrés par TTA.
|
||||
Chaque personne utilise son propre compte TIS. TTA utilise l'API INTERNE du site TIS, pas
|
||||
l'API officielle de RNE : pour un usage durable ou partagé, demande l'accès API officiel.
|
||||
@@ -0,0 +1,264 @@
|
||||
<p align="center">
|
||||
<img src="logo.svg" width="96" alt="TTA">
|
||||
</p>
|
||||
|
||||
<h1 align="center">TTA – Train Time Accuracy</h1>
|
||||
|
||||
<p align="center">
|
||||
Suivi en temps réel des trains fret sur <b>RNE TIS</b>, directement dans Chrome.<br>
|
||||
<i>powered by SIBELIT · By LinkAtPlug Co. © 2026</i>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="version" src="https://img.shields.io/badge/version-2.1.1-0b2a5b">
|
||||
<img alt="Chrome MV3" src="https://img.shields.io/badge/Chrome-Manifest%20V3-f2b705">
|
||||
<img alt="tests" src="https://img.shields.io/badge/tests-131%20OK-2e9e5b">
|
||||
<img alt="dépendances" src="https://img.shields.io/badge/d%C3%A9pendances-aucune-555">
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Sommaire
|
||||
|
||||
- [Pourquoi](#pourquoi)
|
||||
- [Fonctionnalités](#fonctionnalités)
|
||||
- [Installation](#installation)
|
||||
- [Architecture](#architecture)
|
||||
- [Accès à TIS sans API publique](#accès-à-tis-sans-api-publique)
|
||||
- [Appels TIS et charge sur le serveur](#appels-tis-et-charge-sur-le-serveur)
|
||||
- [Règles métier](#règles-métier)
|
||||
- [Stockage](#stockage)
|
||||
- [Structure du dépôt](#structure-du-dépôt)
|
||||
- [Tests](#tests)
|
||||
- [Sécurité et confidentialité](#sécurité-et-confidentialité)
|
||||
- [Historique des versions](#historique-des-versions)
|
||||
|
||||
---
|
||||
|
||||
## Pourquoi
|
||||
|
||||
Le régulateur temps réel (3×8) suit des dizaines de trains fret internationaux dans
|
||||
[RNE TIS](https://tis-prod.rne.eu). TIS n'offre pas d'API publique et oblige à ouvrir les trains un par un.
|
||||
|
||||
**TTA** affiche **toute la flotte sur un seul écran**, se rafraîchit seul chaque minute et alerte
|
||||
(son + notification Windows) dès qu'un train dérape : retard qui se creuse, départ non effectué,
|
||||
pointage manquant au point suivant.
|
||||
|
||||
Aucun serveur, aucune commande, aucune installation de logiciel : **une extension Chrome**, et on se
|
||||
connecte à TIS avec son propre compte, comme d'habitude.
|
||||
|
||||
## Fonctionnalités
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Flotte en un écran** | ~10 trains visibles sans défiler (1366×768 compris), section « Arrivés » repliable juste sous la liste. |
|
||||
| **Listes** | « Mes trains · SIBELIT » (par défaut), « Lineas », « Liste manuelle » (intégrées, non modifiables) + listes personnelles. Ajout de numéros hors filtre, avec jour précis (`42920@27/10`). |
|
||||
| **Statut couleur** | rouge ≥ 15 min · jaune ≥ 5 min · vert à l'heure / en avance · bleu pas encore parti · gris arrivé / inactif. |
|
||||
| **Pointage** | Pastille rouge / jaune si l'heure attendue au **prochain point** est dépassée, ⏸ stand-by pour un arrêt normal (relais, faisceau). |
|
||||
| **Prochain point** | Étapes TIS remises dans l'ordre, estimation corrigée quand l'heure TIS est périmée (affichée `≈`). |
|
||||
| **Composition** | Colonne dédiée `véhicules-longueur-poids` (poids du train) de la section en cours, ou « Compo non trouvée ». |
|
||||
| **Causes de retard** | Dernière cause sous l'itinéraire, liste complète (codes UIC) dans la fiche du train. |
|
||||
| **Numéros liés / parité** | 42920 ⇄ 42921, changement de numéro en route, message « parité » si non trouvé. |
|
||||
| **Alertes** | Départ, retard ≥ 10 min, ETD +5 min, train au rouge, session perdue. Son et notifications désactivables. |
|
||||
| **Fiche train** | Clic sur la ligne : horaires, état, composition, choix du jour, causes de retard, note libre. |
|
||||
| **Impression** | Horaire du train de tel point à tel point, colonnes et infos à la carte, « théorique seul » ou « avec réel ». |
|
||||
| **Relève** | Rapport de fin de poste prêt à copier / imprimer, avec remarques transmises d'une équipe à l'autre. |
|
||||
| **Recherche** | Filtre instantané (numéro, gare, compo, cause, note…). |
|
||||
| **Connexion intégrée** | Fenêtre de connexion TIS (Microsoft) + reconnexion silencieuse. |
|
||||
| **Divers** | Thème clair / sombre / auto, badge sur l'icône, mode debug, bouton « Signaler un bug ». |
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="docs/screenshots/train-panel.png" alt="Fiche train"><br><sub>Fiche train : arrêt en faisceau, causes de retard</sub></td>
|
||||
<td><img src="docs/screenshots/print.png" alt="Impression"><br><sub>Impression de l'horaire, modulable</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="docs/screenshots/handover.png" alt="Relève"><br><sub>Rapport de relève</sub></td>
|
||||
<td><img src="docs/screenshots/lists.png" alt="Listes"><br><sub>Listes intégrées et personnelles</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="docs/screenshots/overview-light.png" alt="Thème clair"><br><sub>Thème clair</sub></td>
|
||||
<td><img src="docs/screenshots/arrived.png" alt="Arrivés"><br><sub>Recherche + section « Arrivés »</sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Installation
|
||||
|
||||
1. Télécharger le dépôt (ou le zip) et le décompresser, par ex. `C:\TTA`.
|
||||
2. Ouvrir `chrome://extensions`, activer **Mode développeur** (en haut à droite).
|
||||
3. **Charger l'extension non empaquetée** → choisir le dossier qui contient `manifest.json`.
|
||||
4. Épingler l'icône TTA, cliquer dessus → **Se connecter à TIS** → se connecter avec son compte habituel.
|
||||
|
||||
Mise à jour : remplacer les fichiers puis cliquer ↻ sur la carte de l'extension
|
||||
(le tableau de bord propose aussi de recharger le moteur s'il détecte une ancienne version).
|
||||
|
||||
Le guide utilisateur complet est dans [`LISEZMOI.txt`](LISEZMOI.txt).
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Chrome
|
||||
BG["background.js<br/>service worker<br/>(poll 1 min)"]
|
||||
CORE["core.js<br/>logique métier pure"]
|
||||
ST[("chrome.storage.local<br/>source de vérité")]
|
||||
UI["dashboard.html / .js<br/>tableau de bord"]
|
||||
OFF["offscreen.html<br/>sons"]
|
||||
NOTIF["notifications<br/>+ badge"]
|
||||
end
|
||||
TIS["tis-prod.rne.eu<br/>API interne TIS"]
|
||||
|
||||
BG -- "fetch (cookie de session)" --> TIS
|
||||
BG --> CORE
|
||||
BG -- "écrit" --> ST
|
||||
ST -- "onChanged" --> UI
|
||||
UI -- "messages<br/>(forcer, listes, horaire…)" --> BG
|
||||
BG --> OFF
|
||||
BG --> NOTIF
|
||||
```
|
||||
|
||||
- **`core.js`** : fonctions pures (classement, prochain point, estimations, composition, listes, alertes).
|
||||
Chargée par le service worker (`importScripts`), par la page et par les tests Node.
|
||||
- **`background.js`** : planification (`chrome.alarms`), appels TIS, cache, alertes, connexion.
|
||||
Il écrit le résultat dans `chrome.storage.local`.
|
||||
- **`dashboard.*`** : la page ne fait **aucun appel réseau** ; elle lit le stockage et se redessine
|
||||
à chaque changement (regroupé / anti-rebond). Plusieurs onglets ouverts = zéro requête en plus.
|
||||
- **`offscreen.*` + `sounds.js`** : un service worker ne peut pas jouer de son ; un document offscreen
|
||||
(`AUDIO_PLAYBACK`) génère les sonneries (Web Audio, aucun fichier audio).
|
||||
|
||||
## Accès à TIS sans API publique
|
||||
|
||||
TIS est une application web (Angular) qui appelle sa propre API REST interne
|
||||
`https://tis-prod.rne.eu/tis2020api/api/…`, authentifiée par un **cookie de session HttpOnly**
|
||||
posé après la connexion Microsoft.
|
||||
|
||||
1. **Permission d'hôte** : le manifeste déclare `host_permissions: ["https://tis-prod.rne.eu/*"]`.
|
||||
Le service worker peut alors appeler l'API avec `fetch(…, { credentials: 'include' })` :
|
||||
Chrome joint lui-même le cookie de session de l'utilisateur, sans contrainte CORS.
|
||||
L'extension **ne lit jamais** le cookie et ne voit jamais le mot de passe.
|
||||
2. **Repli** : si l'appel direct échoue, la requête est exécutée dans un onglet TIS ouvert
|
||||
(`chrome.scripting.executeScript`), exactement comme le ferait la page TIS.
|
||||
3. **Connexion** : « Se connecter » ouvre `tis-prod.rne.eu/search` dans une petite fenêtre ;
|
||||
`tabs.onUpdated` sonde `GET accounts/self` jusqu'à ce que la session soit valide, puis ferme la fenêtre.
|
||||
À l'expiration, une **reconnexion silencieuse** (fenêtre réduite, 1 min max) est tentée ; sinon une
|
||||
notification invite à se reconnecter.
|
||||
|
||||
> L'extension fait exactement ce que fait l'utilisateur dans TIS, avec ses droits, sans rien
|
||||
> contourner : mêmes requêtes, même session, même périmètre de données.
|
||||
|
||||
## Appels TIS et charge sur le serveur
|
||||
|
||||
| Appel | Usage | Cadence |
|
||||
|---|---|---|
|
||||
| `POST trainsearches` (`ruCodes`, `onlyRunning`) | Flotte du filtre : trains en circulation | 1 / min |
|
||||
| `POST trainsearches` (`ruCodes`, `departureTimeFrom/To`) | Départs dans l'heure + pas partis en retard | 1 / min |
|
||||
| `POST trainsearches` (`trainNumbers`) | Numéros ajoutés à la main (+ jumeau de parité si non trouvé) | 1 / min |
|
||||
| `POST trainsearches` + `withSectionsAndDetails` | Détail d'itinéraire : prochain point, causes de retard | ≤ 4 trains / cycle, 1× / 3 min / train |
|
||||
| `GET train-compositions?trainId=` | Composition (véhicules, longueur, poids) | ≤ 4 trains / cycle, 1× / 15 min / train |
|
||||
| `GET trains/{id}` | Horaire complet pour l'impression | à la demande |
|
||||
| `GET accounts/self` | Vérification de session | connexion uniquement |
|
||||
| `GET trainsearchfilter/self`, `GET companies` | Filtres enregistrés, noms d'entreprises | à la demande |
|
||||
|
||||
Garde-fous : un seul cycle à la fois, « Actualiser » limité à 1 fois / 10 s, cache négatif
|
||||
(un train sans détail n'est pas redemandé avant 3 min), réponses compactées avant stockage,
|
||||
champs d'affichage retirés des filtres TIS (sinon HTTP 400).
|
||||
|
||||
## Règles métier
|
||||
|
||||
**Classement** (`classify`) : `waiting` (pas parti) · `running` · `arrived`, puis couleur selon le retard
|
||||
(`yellowFromMin` 5, `redFromMin` 15, réglables). Un train pas parti dont l'heure est dépassée prend
|
||||
son ETD comme retard (« ETD +22 min »).
|
||||
|
||||
**Ordre des étapes** : TIS renvoie les sections dans le désordre ; les étapes sont triées sur l'heure
|
||||
**prévue** (l'heure réelle classerait la position d'un train en retard après des points non atteints).
|
||||
Les prévisions isolées sans heure prévue sont ignorées.
|
||||
|
||||
**Estimation périmée** (`estimateAt`) : si l'heure calculée par TIS est plus de 15 min en avance sur
|
||||
« heure prévue + retard actuel », TTA affiche la projection, marquée `≈`.
|
||||
|
||||
**Pointage** : la pastille compare l'heure **attendue au prochain point** (sinon à l'arrivée) à l'heure
|
||||
actuelle : jaune > 5 min, rouge > 15 min. Un train arrêté longtemps dont le point suivant n'est pas
|
||||
encore dû est en **stand-by** (⏸).
|
||||
|
||||
**Arrêt (lieu répété)** : quand le même lieu apparaît deux fois de suite (arrivée puis départ, ex.
|
||||
Thionville-Faisceau Est 13:23 → 16:01), la première ligne est l'arrivée, la dernière le départ.
|
||||
Une fois l'heure d'arrivée passée, le train est considéré **à l'arrêt** (TIS ne pointe souvent pas
|
||||
l'arrivée en faisceau) et n'est signalé qu'après l'heure de départ.
|
||||
|
||||
**Numéros** : un train porte plusieurs numéros (`operationalTrainNumbers`, `referenceOtns`) ; la recherche
|
||||
porte sur tous. Jumeau de parité : `n % 2 ? n − 1 : n + 1`.
|
||||
|
||||
**Composition** : section de composition choisie selon le gestionnaire d'infrastructure de la position
|
||||
actuelle et les lieux déjà franchis ; affichage `véhicules-longueur-poids` (poids du train, pas freiné).
|
||||
|
||||
**Causes de retard** : `trainDelays` de chaque étape du détail (codes UIC 10-99), fusionnés sans doublon,
|
||||
triés dans le temps ; libellés et familles (GI, EF, externes…) dans `DELAY_CAUSES` / `DELAY_FAMILY`.
|
||||
|
||||
## Stockage
|
||||
|
||||
Tout est dans `chrome.storage.local`, sur le poste :
|
||||
|
||||
| Clé | Contenu |
|
||||
|---|---|
|
||||
| `data`, `trains` | Dernier résultat (lignes classées) et numéros suivis |
|
||||
| `details`, `compos`, `locNames` | Caches : détail d'itinéraire + causes, compositions, noms de lieux |
|
||||
| `lists`, `extras`, `pins`, `hidden` | Listes personnelles, numéros ajoutés, jours choisis, trains masqués 24 h |
|
||||
| `prefs`, `cfg` | Réglages (sons, seuils, thème, colonnes d'impression…) |
|
||||
| `alerts`, `prev` | Historique des alertes, état précédent (détection des changements) |
|
||||
| `notes`, `handoverNote` | Notes par train et par jour, remarques de relève |
|
||||
| `session`, `stats`, `debug` | État de connexion, compteurs, journal de debug (300 entrées) |
|
||||
|
||||
## Structure du dépôt
|
||||
|
||||
```
|
||||
manifest.json Manifest V3 : permissions, service worker, icônes
|
||||
background.js Service worker : planification, appels TIS, cache, alertes, connexion
|
||||
core.js Logique métier pure (partagée worker / page / tests)
|
||||
dashboard.html Tableau de bord (page de l'extension)
|
||||
dashboard.js Rendu, fiche train, listes, impression, relève, recherche
|
||||
dashboard.css Thèmes clair / sombre, grille, impression
|
||||
offscreen.html/.js Lecture des sons (document offscreen)
|
||||
sounds.js Sonneries générées (Web Audio)
|
||||
logo.svg, icon*.png Identité visuelle
|
||||
LISEZMOI.txt Guide utilisateur
|
||||
tests/ Tests Node (faux chrome + faux TIS)
|
||||
docs/screenshots/ Captures d'écran
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
Node.js ≥ 18, aucune dépendance :
|
||||
|
||||
```bash
|
||||
node tests/run.js
|
||||
```
|
||||
|
||||
Les tests chargent `core.js` et `background.js` dans une VM Node avec un faux objet `chrome`
|
||||
et un faux TIS, et rejouent des cas réels (sections dans le désordre, estimations périmées, arrêt
|
||||
en faisceau, parité, connexion, alertes, composition, impression…) : **131 vérifications**.
|
||||
|
||||
## Sécurité et confidentialité
|
||||
|
||||
- Aucun mot de passe ni cookie manipulé par l'extension : la connexion se fait sur la page TIS officielle.
|
||||
- Données envoyées **uniquement** à `tis-prod.rne.eu`. Aucun serveur tiers, aucune télémétrie.
|
||||
- Données stockées localement dans Chrome (`chrome.storage.local`).
|
||||
- « Signaler un bug » ouvre un brouillon d'e-mail ; c'est l'utilisateur qui l'écrit et l'envoie.
|
||||
|
||||
## Historique des versions
|
||||
|
||||
| Version | Principales évolutions |
|
||||
|---|---|
|
||||
| 2.1.1 | « Arrivés » suit la liste · arrêt en faisceau (lieu répété) · causes de retard complètes |
|
||||
| 2.1.0 | Impression modulable (théorique / réel, colonnes, dates, pages A4 propres) |
|
||||
| 2.0.x | Impression de l'horaire · estimations TIS périmées corrigées · ordre des étapes |
|
||||
| 1.8 – 1.9 | Prochain point fiabilisé · pastille par point attendu · stand-by · recherche · « Signaler un bug » |
|
||||
| 1.6 – 1.7 | Composition `véhicules-longueur-poids` · section « Arrivés » |
|
||||
| 1.5 | Numéros liés / parité · listes intégrées et personnelles · fiche train |
|
||||
| 1.3 | Extension tout-en-un : connexion TIS intégrée, filtres prédéfinis |
|
||||
| 1.0 – 1.2 | Suivi temps réel, alertes, sons, thèmes, debug |
|
||||
|
||||
---
|
||||
|
||||
<p align="center"><sub>TTA – Train Time Accuracy · powered by SIBELIT · By LinkAtPlug Co. © 2026 · Tous droits réservés</sub></p>
|
||||
@@ -0,0 +1,660 @@
|
||||
// Service worker : interroge TIS 1x/minute avec TA session Chrome, calcule les couleurs, notifie.
|
||||
importScripts('core.js'); // logique commune (couleurs, alertes, tendances, DEFAULT_PREFS)
|
||||
|
||||
const API = 'https://tis-prod.rne.eu/tis2020api/api/trainsearches';
|
||||
const TIS_URL = 'https://tis-prod.rne.eu/';
|
||||
const POLL_MIN = 1; // 1 requête légère par minute pour toute la liste
|
||||
const DETAIL_EVERY_MS = 3 * 60000; // détail d'itinéraire (lourd) : toutes les 3 min, trains en circulation seulement
|
||||
const MIN_FORCE_GAP_MS = 10000; // anti-flood : un forçage toutes les 10 s maximum
|
||||
const DEFAULT_CFG = { yellowFromMin: 5, redFromMin: 15 };
|
||||
const DEBUG_MAX = 300; // entrées gardées dans le journal de debug
|
||||
|
||||
let running = false;
|
||||
|
||||
// ---------- Journal de debug + statistiques : regroupés, une seule écriture par cycle ----------
|
||||
const dbgBuf = [];
|
||||
const pendingStats = { set: {}, inc: {} };
|
||||
const dbg = (l, m, d) => { dbgBuf.push({ t: Date.now(), l, m, d }); };
|
||||
const stat = (set, inc) => {
|
||||
Object.assign(pendingStats.set, set || {});
|
||||
for (const [k, v] of Object.entries(inc || {})) pendingStats.inc[k] = (pendingStats.inc[k] || 0) + v;
|
||||
};
|
||||
async function flushDbg() {
|
||||
const hasStats = Object.keys(pendingStats.set).length || Object.keys(pendingStats.inc).length;
|
||||
if (!dbgBuf.length && !hasStats) return;
|
||||
try {
|
||||
const s = await chrome.storage.local.get(['debug', 'stats']);
|
||||
const out = {};
|
||||
if (dbgBuf.length) out.debug = [...(s.debug || []), ...dbgBuf.splice(0)].slice(-DEBUG_MAX);
|
||||
if (hasStats) {
|
||||
const st = { ...(s.stats || {}), ...pendingStats.set, version: chrome.runtime.getManifest().version };
|
||||
for (const [k, v] of Object.entries(pendingStats.inc)) st[k] = (st[k] || 0) + v;
|
||||
pendingStats.set = {}; pendingStats.inc = {};
|
||||
out.stats = st;
|
||||
}
|
||||
await chrome.storage.local.set(out);
|
||||
} catch (e) { dbgBuf.length = 0; }
|
||||
}
|
||||
|
||||
const load = async () => {
|
||||
const s = await chrome.storage.local.get(['trains', 'cfg', 'data', 'details', 'detailTried', 'locNames', 'prev', 'lastRun', 'alerts', 'prefs',
|
||||
'hidden', 'tisFilter', 'tisFilters', 'lists', 'extras', 'pins', 'compos']);
|
||||
const prefs = { ...DEFAULT_PREFS, ...(s.prefs || {}), ev: { ...DEFAULT_PREFS.ev, ...((s.prefs || {}).ev || {}) } };
|
||||
const lists = s.lists || [], tisFilters = s.tisFilters || [];
|
||||
const active = resolveList(prefs, { lists, tisFilters, tisFilter: s.tisFilter });
|
||||
// Numéros « en plus » : propres à chaque liste, jamais filtrés par entreprise.
|
||||
// (versions précédentes : une seule liste « trains » → reprise dans la liste active)
|
||||
const extras = s.extras || (s.trains && s.trains.length ? { [active.id]: s.trains } : {});
|
||||
return { cfg: { ...DEFAULT_CFG, ...(s.cfg || {}) }, data: s.data || null, prefs, lists, tisFilters, active, extras,
|
||||
trains: extras[active.id] || [], pins: s.pins || {}, compos: s.compos || {},
|
||||
details: s.details || {}, detailTried: s.detailTried || {}, locNames: s.locNames || {}, prev: s.prev || {},
|
||||
lastRun: s.lastRun || 0, alerts: s.alerts || [], hidden: s.hidden || {},
|
||||
tisFilter: active.definition ? { name: active.name, definition: active.definition } : null,
|
||||
fleetMode: !!active.definition };
|
||||
};
|
||||
|
||||
// « 42920, 42921@27/10, 40146@27/10/2026 » → numéros + jours choisis (AAAA-MM-JJ).
|
||||
function parseNumbers(text) {
|
||||
const nums = [], pins = {};
|
||||
const y = new Date().getFullYear();
|
||||
for (const tok of String(text || '').split(/[\s,;]+/)) {
|
||||
const m = tok.match(/^(\d{1,10})(?:@(\d{1,2})[\/.-](\d{1,2})(?:[\/.-](\d{2,4}))?)?$/);
|
||||
if (!m) continue;
|
||||
if (!nums.includes(m[1])) nums.push(m[1]);
|
||||
if (m[2]) {
|
||||
const yy = m[4] ? (m[4].length === 2 ? 2000 + Number(m[4]) : Number(m[4])) : y;
|
||||
pins[m[1]] = `${yy}-${String(m[3]).padStart(2, '0')}-${String(m[2]).padStart(2, '0')}`;
|
||||
}
|
||||
}
|
||||
return { nums: nums.slice(0, 100), pins };
|
||||
}
|
||||
|
||||
// Sonnerie : un document caché (offscreen) joue le son, même si la page de suivi est fermée.
|
||||
async function playSound(kind) {
|
||||
try {
|
||||
const open = await chrome.runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'] });
|
||||
if (!open.length) {
|
||||
await chrome.offscreen.createDocument({ url: 'offscreen.html', reasons: ['AUDIO_PLAYBACK'], justification: 'Alertes sonores de suivi des trains' });
|
||||
dbg('info', 'document audio créé');
|
||||
}
|
||||
await chrome.runtime.sendMessage({ target: 'offscreen', type: 'play', kind });
|
||||
dbg('info', `son joué : ${kind}`);
|
||||
} catch (e) { dbg('warn', 'son impossible : ' + e.message); }
|
||||
}
|
||||
|
||||
// Notifications Windows / Chrome (silencieuses : le son est géré par TTA) + son de l'alerte la plus importante.
|
||||
async function emit(alerts, prefs) {
|
||||
if (prefs.desktop) for (const a of alerts) {
|
||||
const opts = { type: 'basic', iconUrl: 'icon128.png', title: a.title, message: a.body || '', priority: 2, silent: true };
|
||||
// une notification « session » ouvre directement la fenêtre de connexion quand on clique dessus
|
||||
if (a.kind === 'session') chrome.notifications.create('tta-login-' + Date.now(), { ...opts, requireInteraction: true });
|
||||
else chrome.notifications.create(opts);
|
||||
}
|
||||
const kinds = alerts.map(a => a.kind);
|
||||
const loudest = KIND_PRIORITY.find(k => kinds.includes(k));
|
||||
if (loudest && prefs.sound) await playSound(loudest);
|
||||
else if (loudest) dbg('info', `son coupé dans les réglages (alerte ${loudest})`);
|
||||
}
|
||||
|
||||
// Badge sur l'icône : nombre de trains en rouge (sinon en jaune), « ! » si TIS est injoignable.
|
||||
function updateBadge(rows, error) {
|
||||
const red = rows.filter(t => t.color === 'red').length, yellow = rows.filter(t => t.color === 'yellow').length;
|
||||
let text = '', color = '#2fb36b';
|
||||
if (error) { text = '!'; color = '#6b7685'; }
|
||||
else if (red) { text = String(red); color = '#ef4444'; }
|
||||
else if (yellow) { text = String(yellow); color = '#e5b020'; }
|
||||
chrome.action.setBadgeText({ text });
|
||||
chrome.action.setBadgeBackgroundColor({ color });
|
||||
chrome.action.setTitle({ title: error ? `TTA – ${error}` : `TTA – ${red} en retard important, ${yellow} en retard, ${rows.length} suivi(s)` });
|
||||
}
|
||||
|
||||
const searchBody = (nums, details, onlyRunning) => ({
|
||||
withSectionsAndDetails: details, withInterruptionInfo: true, withInterruptionInfoInHeaderOnly: false,
|
||||
filter: { onlyRunning, maxNumberOfResults: 200, trainNumbers: nums },
|
||||
});
|
||||
|
||||
// 1) appel direct avec la session Chrome (permission d'hôte) ; 2) sinon via un onglet TIS ouvert.
|
||||
async function callTis(body, label) {
|
||||
const t0 = Date.now();
|
||||
const kb = r => Math.round(JSON.stringify(r).length / 1024);
|
||||
try {
|
||||
const r = await fetch(API, {
|
||||
method: 'POST', credentials: 'include',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-PAGE-URL': '/search#multiple' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (r.ok) {
|
||||
const j = await r.json().catch(() => null);
|
||||
if (j && j.data && j.data.result) {
|
||||
dbg('info', `TIS ${label} : OK direct (HTTP ${r.status})`, { ms: Date.now() - t0, ko: kb(j.data.result), trains: (j.data.result.trains || []).length });
|
||||
return { ok: true, result: j.data.result, route: 'direct', status: r.status, ms: Date.now() - t0 };
|
||||
}
|
||||
dbg('warn', `TIS ${label} : réponse directe non exploitable (probablement page de connexion)`, { ms: Date.now() - t0 });
|
||||
} else if (r.status !== 401 && r.status !== 403) {
|
||||
dbg('error', `TIS ${label} : HTTP ${r.status}`);
|
||||
return { ok: false, error: `TIS a répondu HTTP ${r.status}`, status: r.status, route: 'direct', ms: Date.now() - t0 };
|
||||
} else dbg('warn', `TIS ${label} : direct refusé (HTTP ${r.status}), essai via onglet TIS`);
|
||||
} catch (e) { dbg('warn', `TIS ${label} : appel direct impossible (${e.message}), essai via onglet TIS`); }
|
||||
|
||||
const tabs = await chrome.tabs.query({ url: TIS_URL + '*' });
|
||||
if (!tabs.length) {
|
||||
dbg('error', `TIS ${label} : aucun onglet TIS ouvert pour le plan B`);
|
||||
return { ok: false, auth: true, error: 'Pas connecté à TIS : clique sur « Se connecter à TIS ».', status: 401, route: 'aucune', ms: Date.now() - t0 };
|
||||
}
|
||||
try {
|
||||
const [res] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tabs[0].id },
|
||||
func: async (b) => {
|
||||
const r = await fetch('/tis2020api/api/trainsearches', {
|
||||
method: 'POST', credentials: 'include',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-PAGE-URL': '/search#multiple' },
|
||||
body: JSON.stringify(b),
|
||||
});
|
||||
return { status: r.status, json: r.ok ? await r.json() : null };
|
||||
},
|
||||
args: [body],
|
||||
});
|
||||
const out = res && res.result;
|
||||
if (out && out.json && out.json.data) {
|
||||
dbg('info', `TIS ${label} : OK via onglet TIS (HTTP ${out.status})`, { ms: Date.now() - t0, ko: kb(out.json.data.result), trains: (out.json.data.result.trains || []).length });
|
||||
return { ok: true, result: out.json.data.result, route: 'onglet', status: out.status, ms: Date.now() - t0 };
|
||||
}
|
||||
if (out && (out.status === 401 || out.status === 403)) {
|
||||
dbg('error', `TIS ${label} : session expirée (HTTP ${out.status})`);
|
||||
return { ok: false, auth: true, error: 'Session TIS expirée : clique sur « Se connecter à TIS ».', status: out.status, route: 'onglet', ms: Date.now() - t0 };
|
||||
}
|
||||
dbg('error', `TIS ${label} : HTTP ${out ? out.status : '?'} via onglet`);
|
||||
return { ok: false, error: `TIS a répondu HTTP ${out ? out.status : '?'}`, status: out && out.status, route: 'onglet', ms: Date.now() - t0 };
|
||||
} catch (e) {
|
||||
dbg('error', `TIS ${label} : échec via onglet (${e.message})`);
|
||||
return { ok: false, error: 'Impossible d\'interroger TIS : ' + e.message, route: 'onglet', ms: Date.now() - t0 };
|
||||
}
|
||||
}
|
||||
|
||||
const DETAIL_BATCH = 4; // détail d'itinéraire : au plus 4 trains par cycle (les autres aux cycles suivants)
|
||||
const COMPO_EVERY_MS = 15 * 60000; // composition (véhicules, longueur, poids) : change rarement → toutes les 15 min par train
|
||||
const COMPO_BATCH = 4; // … au plus 4 trains par cycle
|
||||
const pad2 = n => String(n).padStart(2, '0');
|
||||
// Format d'heure attendu par TIS : heure locale « yyyy-MM-ddTHH:mm:ss ».
|
||||
const tisTime = ms => { const d = new Date(ms); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`; };
|
||||
// Filtre TIS enregistré, nettoyé des réglages propres à l'écran de TIS (sinon TIS répond 400).
|
||||
function cleanDef(def) {
|
||||
const d = { ...(def || {}) };
|
||||
for (const k of ['timeframe', 'timeFramePast', 'timeFrameFuture', 'timeFrameBaseTime', 'timeFrameBaseTimeType', 'cttLine', 'realLine',
|
||||
'splitLocations', 'mobileTimeFrame', 'departureTimeFrom', 'departureTimeTo', 'trainNumbers']) delete d[k];
|
||||
return d;
|
||||
}
|
||||
const filterBody = filter => ({ withSectionsAndDetails: false, withInterruptionInfo: true, withInterruptionInfoInHeaderOnly: false, filter });
|
||||
|
||||
// Trains à afficher. Mode « filtre TIS » : trains du filtre en circulation + départs des X prochaines minutes
|
||||
// (et ceux pas encore partis jusqu'à Y min après l'heure prévue) ; plus les numéros saisis à la main.
|
||||
// Renvoie l'échec du premier appel TIS, ou { ok, fleet:[trains], extra:[trains]|null, all:[trains] }.
|
||||
async function gather(s) {
|
||||
const out = { ok: true, fleet: [], extra: null, all: [] };
|
||||
const absorb = res => { for (const l of res.locations || []) s.locNames[l.id] = l.name; const tr = res.trains || []; out.all.push(...tr); return tr; };
|
||||
let first = null;
|
||||
if (s.fleetMode) {
|
||||
const def = cleanDef(s.tisFilter.definition), name = s.tisFilter.name;
|
||||
const r1 = await callTis(filterBody({ ...def, onlyRunning: true, maxNumberOfResults: 1000 }), `filtre « ${name} » en circulation`);
|
||||
if (!r1.ok) return r1;
|
||||
first = r1;
|
||||
const now = Date.now();
|
||||
const r2 = await callTis(filterBody({ ...def, onlyRunning: false, maxNumberOfResults: 500,
|
||||
departureTimeFrom: tisTime(now - s.prefs.lateLookbackMin * 60000), departureTimeTo: tisTime(now + s.prefs.upcomingMin * 60000) }), `filtre « ${name} » départs`);
|
||||
stat({}, { requests: 1 });
|
||||
const runningT = absorb(r1.result);
|
||||
// des départs, on ne garde que les trains PAS ENCORE partis (les autres sont déjà dans « en circulation »)
|
||||
const upcomingT = r2.ok ? absorb(r2.result).filter(t => { const h = t.header; return !h.running && !(h.origin || {}).actualTime && !(h.destination || {}).actualTime; }) : [];
|
||||
if (!r2.ok) dbg('warn', 'départs à venir indisponibles ce cycle');
|
||||
out.fleet = [...runningT, ...upcomingT].filter(t => !t.header.archive);
|
||||
dbg('info', `filtre « ${name} » : ${runningT.length} en circulation, ${upcomingT.length} pas encore parti(s) (départ ≤ ${s.prefs.upcomingMin} min ou en retard)`);
|
||||
}
|
||||
if (s.trains.length) {
|
||||
const r = await callTis(searchBody(s.trains, false, false), s.fleetMode ? 'trains en plus' : 'liste');
|
||||
if (!r.ok && !first) return r;
|
||||
if (first) stat({}, { requests: 1 }); else first = r;
|
||||
if (r.ok) out.extra = absorb(r.result); else dbg('warn', 'trains en plus indisponibles ce cycle');
|
||||
}
|
||||
return { ...out, route: first.route, status: first.status, ms: first.ms };
|
||||
}
|
||||
|
||||
// Composition d'un train (GET train-compositions?trainId=…), réduite à l'essentiel.
|
||||
async function getComposition(id, archive) {
|
||||
try {
|
||||
const r = await fetch(`https://tis-prod.rne.eu/tis2020api/api/train-compositions?trainId=${id}`, {
|
||||
credentials: 'include', headers: { Accept: 'application/json', ...(archive ? { Archive: 'true' } : {}) },
|
||||
});
|
||||
if (!r.ok) { dbg('warn', `composition ${id} : HTTP ${r.status}`); return { ok: false }; }
|
||||
const j = await r.json().catch(() => null);
|
||||
return { ok: true, list: compactCompositions(j && j.data) };
|
||||
} catch (e) { dbg('warn', `composition ${id} : ${e.message}`); return { ok: false }; }
|
||||
}
|
||||
|
||||
async function poll(reason = 'alarme') {
|
||||
if (running) { dbg('info', `cycle ignoré (${reason}) : un cycle est déjà en cours`); await flushDbg(); return; }
|
||||
running = true;
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const s = await load();
|
||||
dbg('info', `── cycle (${reason}) : liste « ${s.active.name} »${s.fleetMode ? ` (${(s.tisFilter.definition.ruCodes || []).length || '?'} entreprise(s))` : ''}${s.trains.length ? ` + ${s.trains.length} numéro(s) en plus` : ''}`);
|
||||
if (!s.trains.length && !s.fleetMode) {
|
||||
await chrome.storage.local.set({ lastRun: Date.now(), data: { updatedAt: new Date().toISOString(), error: null, rows: [] } });
|
||||
updateBadge([], null);
|
||||
dbg('info', 'liste vide : rien à interroger');
|
||||
return;
|
||||
}
|
||||
|
||||
const r = await gather(s);
|
||||
stat({ lastRoute: r.route, lastStatus: r.status ?? null, lastMs: r.ms }, { requests: 1 });
|
||||
if (!r.ok) {
|
||||
const prevRows = s.data ? s.data.rows : [];
|
||||
// Session expirée (une fois par épisode) : reconnexion automatique silencieuse si activée,
|
||||
// sinon alerte « connexion requise » tout de suite.
|
||||
const stamped = [];
|
||||
if (r.auth) await chrome.storage.local.set({ session: { ok: false, checkedAt: Date.now() } });
|
||||
if (r.auth && !(s.data && s.data.auth)) {
|
||||
if (s.prefs.autoLogin) { dbg('info', 'session expirée : tentative de reconnexion automatique'); await startLogin(true); }
|
||||
else if (s.prefs.ev.session) stamped.push(sessionAlert());
|
||||
}
|
||||
if (stamped.length) { dbg('info', 'ALERTE session : connexion TIS requise'); await emit(stamped, s.prefs); }
|
||||
await chrome.storage.local.set({
|
||||
lastRun: Date.now(),
|
||||
data: { updatedAt: s.data ? s.data.updatedAt : null, checkedAt: new Date().toISOString(), error: r.error, auth: !!r.auth, rows: prevRows },
|
||||
...(stamped.length ? { alerts: [...stamped, ...s.alerts].slice(0, 50) } : {}),
|
||||
});
|
||||
updateBadge(prevRows, r.error);
|
||||
stat({ lastError: r.error, lastErrorAt: new Date().toISOString() }, { errors: 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
const mkCtx = () => ({ cfg: s.cfg, locName: id => s.locNames[id] || (id ? `#${id}` : '?'), details: s.details, compos: s.compos, now: Date.now() });
|
||||
// Numéros saisis introuvables : on essaie le numéro de parité opposée (42920 ↔ 42921),
|
||||
// car le numéro change souvent en passant une frontière.
|
||||
let twinTrains = null;
|
||||
const lost = buildRows([], r.extra, s.trains, mkCtx(), s.pins).filter(t => t.phase === 'notfound' && !t.pinned).map(t => t.query);
|
||||
if (lost.length) {
|
||||
const rt = await callTis(searchBody(lost.map(twinNumber), false, false), 'parité');
|
||||
stat({}, { requests: 1 });
|
||||
if (rt.ok) {
|
||||
for (const l of rt.result.locations || []) s.locNames[l.id] = l.name;
|
||||
twinTrains = rt.result.trains || [];
|
||||
r.all.push(...twinTrains);
|
||||
}
|
||||
}
|
||||
const withTwins = row => {
|
||||
if (row.src !== 'list' || row.phase !== 'notfound' || row.pinned) return row;
|
||||
const twin = twinNumber(row.query);
|
||||
const alt = twinTrains && pickPerNumber(twinTrains, [twin], mkCtx())[0];
|
||||
if (alt && alt.phase !== 'notfound') {
|
||||
return { ...alt, src: 'list', query: row.query, parityFrom: row.query,
|
||||
reason: `Trouvé sous le n° ${twin} : le numéro change de parité en route (souvent à la frontière)` };
|
||||
}
|
||||
return { ...row, twin, reason: `Introuvable dans TIS, ni sous le n° ${row.query} ni sous le n° ${twin} (parité). Vérifie le numéro ou choisis un autre jour.` };
|
||||
};
|
||||
const build = () => buildRows(r.fleet, r.extra, s.trains, mkCtx(), s.pins).map(withTwins).filter(t => !(t.id && s.hidden[t.id] > Date.now()));
|
||||
|
||||
// Détail d'itinéraire (prochain point) : trains en circulation dont le cache est périmé, au plus
|
||||
// DETAIL_BATCH par cycle (les plus anciens d'abord), et pas plus d'une tentative / 3 min par numéro.
|
||||
let rows = build();
|
||||
const fresh = v => v && Date.now() - (typeof v === 'number' ? v : Date.parse(v)) < DETAIL_EVERY_MS;
|
||||
const need = [...new Set(rows.filter(t => t.phase === 'running' && !fresh(t.detailAt) && !fresh(s.detailTried[t.otn]))
|
||||
.sort((a, b) => (Date.parse(a.detailAt || 0) || 0) - (Date.parse(b.detailAt || 0) || 0)).map(t => t.otn))].slice(0, DETAIL_BATCH);
|
||||
if (need.length) {
|
||||
dbg('info', `détail d'itinéraire demandé pour : ${need.join(', ')}`);
|
||||
for (const n of need) s.detailTried[n] = Date.now();
|
||||
const d = await callTis(searchBody(need, true, true), 'détail');
|
||||
stat({}, { requests: 1, detailRequests: 1 });
|
||||
if (d.ok) {
|
||||
let got = 0;
|
||||
for (const l of d.result.locations || []) s.locNames[l.id] = l.name;
|
||||
for (const t of d.result.trains || []) {
|
||||
const pts = compactDetails(t);
|
||||
if (pts) { s.details[t.header.id] = { at: new Date().toISOString(), points: pts, passed: passedLocations(t), causes: compactCauses(t) }; got++; }
|
||||
}
|
||||
dbg(got ? 'info' : 'warn', `détail reçu pour ${got} train(s) sur ${need.length} demandé(s)${got ? '' : ' — nouvel essai dans 3 min'}`);
|
||||
rows = build();
|
||||
}
|
||||
}
|
||||
// Composition (onglet « Train composition » de TIS) : au plus COMPO_BATCH trains par cycle, toutes les 15 min.
|
||||
const compoNeed = rows.filter(t => t.id && ['running', 'waiting', 'arrived'].includes(t.phase)
|
||||
&& !(s.compos[t.id] && Date.now() - s.compos[t.id].at < COMPO_EVERY_MS))
|
||||
.sort((a, b) => (s.compos[a.id] ? s.compos[a.id].at : 0) - (s.compos[b.id] ? s.compos[b.id].at : 0)).slice(0, COMPO_BATCH);
|
||||
if (compoNeed.length) {
|
||||
let got = 0;
|
||||
for (const t of compoNeed) {
|
||||
const c = await getComposition(t.id, t.archive);
|
||||
stat({}, { requests: 1, compoRequests: 1 });
|
||||
if (c.ok) { s.compos[t.id] = { at: Date.now(), list: c.list }; if (c.list.length) got++; }
|
||||
else s.compos[t.id] = { at: Date.now() - COMPO_EVERY_MS + 3 * 60000, list: (s.compos[t.id] || {}).list || [] }; // échec : nouvel essai dans 3 min
|
||||
}
|
||||
dbg('info', `composition demandée pour ${compoNeed.length} train(s) : ${got} disponible(s)`);
|
||||
rows = build();
|
||||
}
|
||||
// Ménage des caches : seulement ce qui sert encore aux trains affichés.
|
||||
const keep = new Set(rows.map(t => String(t.id))), shownOtns = new Set(rows.map(t => t.otn));
|
||||
for (const id of Object.keys(s.compos)) if (!keep.has(id)) delete s.compos[id];
|
||||
for (const id of Object.keys(s.details)) if (!keep.has(id)) delete s.details[id];
|
||||
for (const n of Object.keys(s.detailTried)) if (!shownOtns.has(n)) delete s.detailTried[n];
|
||||
for (const id of Object.keys(s.hidden)) if (s.hidden[id] < Date.now()) delete s.hidden[id];
|
||||
const usedLocs = usedLocations(r.all, s.details);
|
||||
for (const id of Object.keys(s.locNames)) if (!usedLocs.has(id)) delete s.locNames[id];
|
||||
|
||||
applyTrends(rows, s.prev, Date.now());
|
||||
const count = c => rows.filter(t => t.color === c).length;
|
||||
dbg('info', `résultat : ${rows.length} ligne(s) — rouge ${count('red')}, jaune ${count('yellow')}, vert ${count('green')}, bleu ${count('blue')}, gris ${count('grey')}`);
|
||||
for (const t of rows.filter(t => t.phase === 'notfound')) dbg('warn', `train ${t.otn} : non trouvé dans TIS`);
|
||||
|
||||
const { alerts, next } = diffAlerts(rows, s.prev, s.prefs);
|
||||
const stamped = alerts.map(a => ({ ...a, at: new Date().toISOString() }));
|
||||
for (const a of stamped) dbg('info', `ALERTE ${a.kind} : ${a.title}`, { corps: a.body });
|
||||
if (s.data && s.data.auth) dbg('info', 'session TIS rétablie');
|
||||
await emit(stamped, s.prefs);
|
||||
|
||||
await chrome.storage.local.set({
|
||||
lastRun: Date.now(),
|
||||
data: { updatedAt: new Date().toISOString(), error: null, rows, hiddenCount: Object.keys(s.hidden).length },
|
||||
details: s.details, detailTried: s.detailTried, locNames: s.locNames, prev: next, hidden: s.hidden, compos: s.compos,
|
||||
...(stamped.length ? { alerts: [...stamped, ...s.alerts].slice(0, 50) } : {}),
|
||||
});
|
||||
updateBadge(rows, null);
|
||||
const sess = (await chrome.storage.local.get('session')).session;
|
||||
if (!sess || !sess.ok) await checkSession(); // récupère le nom affiché après une (re)connexion
|
||||
stat({ lastOkAt: new Date().toISOString(), lastCycleMs: Date.now() - t0 }, { okCycles: 1 });
|
||||
} catch (e) {
|
||||
dbg('error', 'ERREUR inattendue dans le cycle : ' + (e && e.stack || e));
|
||||
stat({ lastError: String(e && e.message || e), lastErrorAt: new Date().toISOString() }, { errors: 1 });
|
||||
} finally {
|
||||
running = false;
|
||||
await flushDbg();
|
||||
}
|
||||
}
|
||||
|
||||
function schedule() { chrome.alarms.create('poll', { periodInMinutes: POLL_MIN, delayInMinutes: 0.1 }); }
|
||||
chrome.runtime.onInstalled.addListener(details => {
|
||||
schedule(); dbg('info', `extension installée / mise à jour (v${chrome.runtime.getManifest().version})`); flushDbg();
|
||||
if (details.reason === 'install') openDashboard(); // première installation : on ouvre TTA directement
|
||||
});
|
||||
chrome.runtime.onStartup.addListener(() => { schedule(); dbg('info', 'Chrome démarré'); flushDbg(); });
|
||||
chrome.alarms.onAlarm.addListener(a => { if (a.name === 'poll') poll('alarme'); });
|
||||
|
||||
// Ouvre (ou ramène au premier plan) la page de suivi : icône de l'extension ou clic sur une notification.
|
||||
async function openDashboard() {
|
||||
const url = chrome.runtime.getURL('dashboard.html');
|
||||
const tabs = await chrome.tabs.query({ url });
|
||||
if (tabs.length) { await chrome.tabs.update(tabs[0].id, { active: true }); await chrome.windows.update(tabs[0].windowId, { focused: true }); }
|
||||
else await chrome.tabs.create({ url });
|
||||
}
|
||||
chrome.action.onClicked.addListener(openDashboard);
|
||||
chrome.notifications.onClicked.addListener(id => {
|
||||
chrome.notifications.clear(id);
|
||||
if (id.startsWith('tta-login')) startLogin(false); else openDashboard();
|
||||
});
|
||||
|
||||
// ---------- Connexion TIS intégrée ----------
|
||||
// TIS se connecte via Microsoft (login.microsoftonline.com) : impossible à afficher dans la page de l'extension.
|
||||
// On ouvre donc une petite fenêtre TIS ; l'utilisateur s'y connecte lui-même (l'extension ne voit jamais
|
||||
// le mot de passe). Dès que TIS répond « connecté », la fenêtre se ferme et le suivi reprend.
|
||||
const SELF_URL = 'https://tis-prod.rne.eu/tis2020api/api/accounts/self';
|
||||
const LOGIN_URL = 'https://tis-prod.rne.eu/search';
|
||||
const SILENT_TIMEOUT_MIN = 1; // reconnexion silencieuse : abandon après 1 min
|
||||
const VISIBLE_TIMEOUT_MIN = 15; // fenêtre visible : on arrête de la surveiller après 15 min
|
||||
|
||||
function sessionAlert() {
|
||||
return { kind: 'session', level: 'red', title: 'TTA : connexion TIS requise', body: 'Clique ici pour te reconnecter à TIS et reprendre le suivi.', at: new Date().toISOString() };
|
||||
}
|
||||
|
||||
// true = connecté, false = non connecté, null = indéterminé (réseau…). Ne garde que le nom affiché.
|
||||
async function checkSession() {
|
||||
try {
|
||||
const r = await fetch(SELF_URL, { credentials: 'include', headers: { Accept: 'application/json' } });
|
||||
if (r.ok) {
|
||||
const j = await r.json().catch(() => null);
|
||||
const u = (j && (j.data || j)) || {};
|
||||
const name = [u.firstName || u.firstname, u.lastName || u.lastname].filter(Boolean).join(' ') || u.displayName || u.name || '';
|
||||
await chrome.storage.local.set({ session: { ok: true, name: String(name).slice(0, 60), checkedAt: Date.now() } });
|
||||
return true;
|
||||
}
|
||||
if (r.status === 401 || r.status === 403) { await chrome.storage.local.set({ session: { ok: false, checkedAt: Date.now() } }); return false; }
|
||||
} catch (e) { dbg('warn', 'vérification de session impossible : ' + e.message); }
|
||||
return null;
|
||||
}
|
||||
|
||||
async function startLogin(silent) {
|
||||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||||
if (cur) {
|
||||
try {
|
||||
await chrome.windows.get(cur.id);
|
||||
if (!silent) { // fenêtre déjà ouverte (même réduite) : on la montre
|
||||
await chrome.windows.update(cur.id, { state: 'normal', focused: true });
|
||||
await chrome.storage.local.set({ loginWin: { ...cur, silent: false } });
|
||||
chrome.alarms.create('loginTimeout', { delayInMinutes: VISIBLE_TIMEOUT_MIN });
|
||||
}
|
||||
return;
|
||||
} catch (e) { /* fenêtre fermée entre-temps */ }
|
||||
}
|
||||
const w = await chrome.windows.create(silent
|
||||
? { url: LOGIN_URL, type: 'normal', state: 'minimized', focused: false }
|
||||
: { url: LOGIN_URL, type: 'popup', width: 520, height: 780, focused: true });
|
||||
await chrome.storage.local.set({ loginWin: { id: w.id, silent: !!silent, at: Date.now() } });
|
||||
chrome.alarms.create('loginTimeout', { delayInMinutes: silent ? SILENT_TIMEOUT_MIN : VISIBLE_TIMEOUT_MIN });
|
||||
dbg('info', silent ? 'reconnexion automatique : fenêtre TIS réduite ouverte' : 'fenêtre de connexion TIS ouverte');
|
||||
await flushDbg();
|
||||
}
|
||||
|
||||
async function finishLogin(cur) {
|
||||
await chrome.storage.local.remove('loginWin');
|
||||
chrome.alarms.clear('loginTimeout');
|
||||
try { await chrome.windows.remove(cur.id); } catch (e) { /* déjà fermée */ }
|
||||
dbg('info', cur.silent ? 'reconnexion automatique réussie' : 'connecté à TIS');
|
||||
if (!cur.silent) chrome.notifications.create({ type: 'basic', iconUrl: 'icon128.png', title: 'TTA : connecté à TIS', message: 'Le suivi des trains reprend.', priority: 0, silent: true });
|
||||
await poll('connexion');
|
||||
}
|
||||
|
||||
// Chaque page chargée dans la fenêtre de connexion : si on est revenu sur TIS, on vérifie la session.
|
||||
// Après Microsoft, TIS revient sur sa page d'accueil puis échange le code en arrière-plan : on vérifie
|
||||
// plusieurs fois sur quelques secondes (la page change d'adresse sans forcément se « recharger »).
|
||||
let probing = false;
|
||||
chrome.tabs.onUpdated.addListener(async (_tabId, info, tab) => {
|
||||
if (!(info.status === 'complete' || info.url) || !tab.url || !tab.url.startsWith('https://tis-prod.rne.eu/') || tab.url.includes('/login')) return;
|
||||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||||
if (!cur || tab.windowId !== cur.id || probing) return;
|
||||
probing = true;
|
||||
try {
|
||||
for (const wait of [0, 1500, 3000, 6000]) {
|
||||
if (wait) await new Promise(r => setTimeout(r, wait));
|
||||
if (!(await chrome.storage.local.get('loginWin')).loginWin) return; // déjà terminé ailleurs
|
||||
if (await checkSession()) return finishLogin(cur);
|
||||
}
|
||||
} finally { probing = false; }
|
||||
});
|
||||
|
||||
// L'utilisateur ferme la fenêtre lui-même : on regarde si la connexion a abouti.
|
||||
chrome.windows.onRemoved.addListener(async id => {
|
||||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||||
if (!cur || cur.id !== id) return;
|
||||
await chrome.storage.local.remove('loginWin');
|
||||
chrome.alarms.clear('loginTimeout');
|
||||
if (await checkSession()) { dbg('info', 'connecté à TIS (fenêtre fermée)'); await poll('connexion'); }
|
||||
else { dbg('warn', 'fenêtre de connexion fermée sans connexion'); await flushDbg(); }
|
||||
});
|
||||
|
||||
// Délai dépassé : la reconnexion silencieuse n'a pas suffi → on ferme et on demande à l'utilisateur.
|
||||
chrome.alarms.onAlarm.addListener(async a => {
|
||||
if (a.name !== 'loginTimeout') return;
|
||||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||||
if (!cur) return;
|
||||
if (await checkSession()) return finishLogin(cur);
|
||||
await chrome.storage.local.remove('loginWin');
|
||||
if (cur.silent) {
|
||||
try { await chrome.windows.remove(cur.id); } catch (e) { /* déjà fermée */ }
|
||||
dbg('warn', 'reconnexion automatique impossible (Microsoft demande une action) : connexion manuelle requise');
|
||||
const s = await load();
|
||||
if (s.prefs.ev.session) {
|
||||
const al = sessionAlert();
|
||||
await emit([al], s.prefs);
|
||||
await chrome.storage.local.set({ alerts: [al, ...s.alerts].slice(0, 50) });
|
||||
}
|
||||
}
|
||||
await flushDbg();
|
||||
});
|
||||
|
||||
// Messages de la page de suivi.
|
||||
chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
|
||||
if (msg && msg.target === 'offscreen') return; // destiné au document audio
|
||||
(async () => {
|
||||
const s = await load();
|
||||
if (msg.type === 'force') {
|
||||
const gap = Date.now() - s.lastRun;
|
||||
if (gap < MIN_FORCE_GAP_MS) { dbg('info', `forçage refusé (anti-flood, ${Math.ceil((MIN_FORCE_GAP_MS - gap) / 1000)} s restantes)`); await flushDbg(); return reply({ ok: false, error: `Trop rapide : attends ${Math.ceil((MIN_FORCE_GAP_MS - gap) / 1000)} s` }); }
|
||||
reply({ ok: true }); await poll('forçage'); return;
|
||||
}
|
||||
if (msg.type === 'setTrains') {
|
||||
// Numéros « en plus » de la liste active (hors filtre), avec jour optionnel : 42920@27/10.
|
||||
// On garde la mémoire des états (prev) : un train déjà suivi ne perd pas ses alertes en cours.
|
||||
const { nums, pins } = parseNumbers(msg.numbers);
|
||||
const extras = { ...s.extras, [s.active.id]: nums };
|
||||
await chrome.storage.local.set({ extras, pins: { ...s.pins, ...pins }, trains: [] });
|
||||
dbg('info', `numéros (${s.active.name}) : ${nums.join(', ') || '(aucun)'}${Object.keys(pins).length ? ' · jours : ' + Object.entries(pins).map(([k, v]) => k + '@' + v).join(', ') : ''}`);
|
||||
reply({ ok: true, trains: nums }); await poll('liste modifiée'); return;
|
||||
}
|
||||
if (msg.type === 'remove') {
|
||||
const otn = String(msg.otn);
|
||||
const list = s.trains.filter(n => n !== otn);
|
||||
const pins = { ...s.pins }; delete pins[otn];
|
||||
const rows = s.data ? s.data.rows.filter(t => !(t.src === 'list' && (t.query || t.otn) === otn)) : [];
|
||||
await chrome.storage.local.set({ extras: { ...s.extras, [s.active.id]: list }, pins, trains: [], data: { ...(s.data || {}), rows } });
|
||||
updateBadge(rows, s.data && s.data.error);
|
||||
dbg('info', `train ${otn} retiré de la liste`); await flushDbg();
|
||||
return reply({ ok: true, trains: list });
|
||||
}
|
||||
// Jour choisi pour un numéro (date = AAAA-MM-JJ, ou null = automatique).
|
||||
if (msg.type === 'pin') {
|
||||
const pins = { ...s.pins };
|
||||
if (msg.date) pins[String(msg.otn)] = msg.date; else delete pins[String(msg.otn)];
|
||||
await chrome.storage.local.set({ pins });
|
||||
dbg('info', `train ${msg.otn} : jour ${msg.date || 'automatique'}`);
|
||||
reply({ ok: true }); await poll('jour modifié'); return;
|
||||
}
|
||||
// Suivre un train vu dans un filtre à une autre date : il passe dans les numéros en plus, avec ce jour.
|
||||
if (msg.type === 'track') {
|
||||
const otn = String(msg.otn), list = s.trains.includes(otn) ? s.trains : [...s.trains, otn];
|
||||
await chrome.storage.local.set({ extras: { ...s.extras, [s.active.id]: list }, pins: msg.date ? { ...s.pins, [otn]: msg.date } : s.pins });
|
||||
reply({ ok: true }); await poll('train ajouté'); return;
|
||||
}
|
||||
// ---------- Listes ----------
|
||||
if (msg.type === 'setList') {
|
||||
const prefs = { ...s.prefs, activeList: String(msg.id), sourceChosen: true };
|
||||
if (String(msg.id).startsWith('tis-')) {
|
||||
const f = s.tisFilters.find(x => 'tis-' + x.id === String(msg.id));
|
||||
if (!f) return reply({ ok: false, error: 'Filtre TIS introuvable' });
|
||||
await chrome.storage.local.set({ tisFilter: { id: f.id, name: f.name, definition: f.definition } });
|
||||
}
|
||||
await chrome.storage.local.set({ prefs });
|
||||
dbg('info', `liste active : ${resolveList(prefs, { lists: s.lists, tisFilters: s.tisFilters }).name}`);
|
||||
reply({ ok: true }); await poll('liste changée'); return;
|
||||
}
|
||||
if (msg.type === 'saveList') {
|
||||
const l = msg.list || {};
|
||||
const name = String(l.name || '').trim().slice(0, 40);
|
||||
if (!name) return reply({ ok: false, error: 'Donne un nom à la liste' });
|
||||
const ruCodes = [...new Set((l.ruCodes || []).map(String).filter(Boolean))].slice(0, 80);
|
||||
const { nums, pins } = parseNumbers(l.trains || '');
|
||||
const id = l.id && !String(l.id).startsWith('preset-') ? String(l.id) : 'list-' + Date.now();
|
||||
const lists = [...s.lists.filter(x => x.id !== id), { id, name, ruCodes }];
|
||||
await chrome.storage.local.set({ lists, extras: { ...s.extras, [id]: nums }, pins: { ...s.pins, ...pins } });
|
||||
dbg('info', `liste « ${name} » enregistrée (${ruCodes.length} entreprise(s), ${nums.length} numéro(s))`);
|
||||
reply({ ok: true, id });
|
||||
if (s.active.id === id) await poll('liste modifiée'); else await flushDbg();
|
||||
return;
|
||||
}
|
||||
if (msg.type === 'deleteList') {
|
||||
const id = String(msg.id);
|
||||
if (id.startsWith('preset-')) return reply({ ok: false, error: 'Les listes intégrées ne peuvent pas être supprimées' });
|
||||
const extras = { ...s.extras }; delete extras[id];
|
||||
const prefs = s.active.id === id ? { ...s.prefs, activeList: 'preset-sibelit' } : s.prefs;
|
||||
await chrome.storage.local.set({ lists: s.lists.filter(x => x.id !== id), extras, prefs });
|
||||
dbg('info', `liste supprimée`);
|
||||
reply({ ok: true }); if (s.active.id === id) await poll('liste supprimée'); else await flushDbg();
|
||||
return;
|
||||
}
|
||||
// Entreprises ferroviaires de TIS (pour composer une liste) : chargées une fois, gardées 7 jours.
|
||||
// Horaire complet d'un train (GET trains/<id>), pour l'impression « de tel point à tel point ».
|
||||
if (msg.type === 'timetable') {
|
||||
try {
|
||||
const r = await fetch(`https://tis-prod.rne.eu/tis2020api/api/trains/${msg.id}`, {
|
||||
credentials: 'include', headers: { Accept: 'application/json', 'With-polylines': 'false', ...(msg.archive ? { Archive: 'true' } : {}) },
|
||||
});
|
||||
if (!r.ok) { dbg('warn', `horaire ${msg.id} : HTTP ${r.status}`); await flushDbg(); return reply({ ok: false, error: `TIS a répondu HTTP ${r.status}` }); }
|
||||
const data = ((await r.json()) || {}).data || {};
|
||||
const names = Object.fromEntries((data.locations || []).map(l => [l.id, l.name]));
|
||||
const train = (data.trains || [])[0];
|
||||
if (!train) return reply({ ok: false, error: 'Train introuvable dans TIS' });
|
||||
const rows = buildTimetable(train, id => names[id] || `#${id}`);
|
||||
dbg('info', `horaire du train ${train.header.otn} : ${rows.length} étapes`); await flushDbg();
|
||||
return reply({ ok: true, rows, numbers: trainNumbers(train.header) });
|
||||
} catch (e) { return reply({ ok: false, error: e.message }); }
|
||||
}
|
||||
if (msg.type === 'companies') {
|
||||
const c = (await chrome.storage.local.get('companies')).companies;
|
||||
if (c && c.at && Date.now() - c.at < 7 * 86400e3 && !msg.refresh) return reply({ ok: true, list: c.list });
|
||||
try {
|
||||
const r = await fetch('https://tis-prod.rne.eu/tis2020api/api/companies', { credentials: 'include', headers: { Accept: 'application/json' } });
|
||||
if (!r.ok) return reply({ ok: false, error: `TIS HTTP ${r.status}` });
|
||||
const list = ((await r.json()).data || []).filter(x => x.displayType === 'RAILWAY_UNDERTAKING' && x.code)
|
||||
.map(x => ({ c: x.code, n: x.name || x.shortName || '', cc: x.countryCode || '' }));
|
||||
await chrome.storage.local.set({ companies: { at: Date.now(), list } });
|
||||
dbg('info', `entreprises ferroviaires TIS chargées : ${list.length}`); await flushDbg();
|
||||
return reply({ ok: true, list });
|
||||
} catch (e) { return reply({ ok: false, error: e.message }); }
|
||||
}
|
||||
if (msg.type === 'setCfg') {
|
||||
await chrome.storage.local.set({ cfg: { yellowFromMin: Number(msg.yellowFromMin) || 5, redFromMin: Number(msg.redFromMin) || 15 } });
|
||||
return reply({ ok: true });
|
||||
}
|
||||
if (msg.type === 'login') { await startLogin(false); return reply({ ok: true }); }
|
||||
// Filtres de recherche enregistrés dans TIS (ex. « Sib » = tes entreprises ferroviaires).
|
||||
if (msg.type === 'listFilters') {
|
||||
try {
|
||||
const r = await fetch('https://tis-prod.rne.eu/tis2020api/api/trainsearchfilter/self', { credentials: 'include', headers: { Accept: 'application/json' } });
|
||||
if (!r.ok) { dbg('warn', `filtres TIS indisponibles (HTTP ${r.status})`); await flushDbg(); return reply({ ok: false, auth: r.status === 401 || r.status === 403, error: `TIS HTTP ${r.status}` }); }
|
||||
const list = ((await r.json()).data || {}).trainSearchFilters || [];
|
||||
const filters = list.map(f => ({ id: f.id, name: f.name, isDefault: !!f.isDefault, definition: f.definition, ruCount: ((f.definition || {}).ruCodes || []).length }));
|
||||
await chrome.storage.local.set({ tisFilters: filters });
|
||||
dbg('info', `filtres TIS : ${filters.map(f => f.name).join(', ') || 'aucun'}`); await flushDbg();
|
||||
return reply({ ok: true, filters });
|
||||
} catch (e) { dbg('warn', 'filtres TIS illisibles : ' + e.message); await flushDbg(); return reply({ ok: false, error: e.message }); }
|
||||
}
|
||||
if (msg.type === 'setSource') { // compatibilité : ancienne façon de choisir la source
|
||||
const id = msg.source !== 'filter' ? 'preset-manual' : String(msg.filterId).startsWith('preset-') ? String(msg.filterId) : 'tis-' + msg.filterId;
|
||||
if (id.startsWith('tis-')) {
|
||||
const f = s.tisFilters.find(x => 'tis-' + x.id === id);
|
||||
if (!f) return reply({ ok: false, error: 'Filtre introuvable' });
|
||||
await chrome.storage.local.set({ tisFilter: { id: f.id, name: f.name, definition: f.definition } });
|
||||
}
|
||||
await chrome.storage.local.set({ prefs: { ...s.prefs, activeList: id, sourceChosen: true, source: id === 'preset-manual' ? 'list' : 'filter' } });
|
||||
dbg('info', `source : ${id}`);
|
||||
reply({ ok: true }); await poll('source modifiée'); return;
|
||||
}
|
||||
// Mode filtre : masquer un train (24 h) au lieu de le retirer d'une liste.
|
||||
if (msg.type === 'hide') {
|
||||
const hidden = { ...s.hidden, [msg.id]: Date.now() + 24 * 3600e3 };
|
||||
const rows = s.data ? s.data.rows.filter(t => String(t.id) !== String(msg.id)) : [];
|
||||
await chrome.storage.local.set({ hidden, data: { ...(s.data || {}), rows, hiddenCount: Object.keys(hidden).length } });
|
||||
updateBadge(rows, s.data && s.data.error);
|
||||
dbg('info', `train ${msg.otn || msg.id} masqué pour 24 h`); await flushDbg();
|
||||
return reply({ ok: true });
|
||||
}
|
||||
if (msg.type === 'unhideAll') { await chrome.storage.local.set({ hidden: {} }); reply({ ok: true }); await poll('trains réaffichés'); return; }
|
||||
if (msg.type === 'checkSession') {
|
||||
const ok = await checkSession();
|
||||
reply({ ok });
|
||||
const cur = (await chrome.storage.local.get('loginWin')).loginWin;
|
||||
if (ok && cur) await finishLogin(cur); // filet de sécurité : la page TTA vérifie aussi pendant la connexion
|
||||
return;
|
||||
}
|
||||
if (msg.type === 'dbg') { dbg(msg.level || 'info', String(msg.text || '').slice(0, 500)); await flushDbg(); return reply({ ok: true }); }
|
||||
if (msg.type === 'clearDebug') { dbgBuf.length = 0; pendingStats.set = {}; pendingStats.inc = {}; await chrome.storage.local.set({ debug: [], stats: { version: chrome.runtime.getManifest().version } }); return reply({ ok: true }); }
|
||||
reply({ ok: false });
|
||||
})();
|
||||
return true; // réponse asynchrone
|
||||
});
|
||||
@@ -0,0 +1,425 @@
|
||||
// Logique commune (service worker + tests). Aucune dépendance.
|
||||
// ctx = { cfg:{yellowFromMin,redFromMin}, locName(id), details: { [idTrain]: {at, points[]} }, now }
|
||||
|
||||
function minutesBetween(a, b) { return Math.round((a - b) / 60000); }
|
||||
const pad0 = n => String(n).padStart(2, '0');
|
||||
// Date locale « AAAA-MM-JJ » (jour du départ prévu, pour choisir le bon train d'un numéro).
|
||||
function localDate(iso) { const d = new Date(iso); return `${d.getFullYear()}-${pad0(d.getMonth() + 1)}-${pad0(d.getDate())}`; }
|
||||
// Numéro « jumeau » de parité : en traversant une frontière, 42920 devient souvent 42921 (et inversement).
|
||||
function twinNumber(n) { const x = Number(n); return String(x % 2 ? x - 1 : x + 1); }
|
||||
|
||||
// Tous les numéros portés par un train, dans l'ordre du parcours (origine → destination).
|
||||
// Ex. [32280, 42920, 42921] : le numéro change en route (frontière, parité).
|
||||
function trainNumbers(h) {
|
||||
const o = h.originOtn != null ? String(h.originOtn) : null, d = h.destinationOtn != null ? String(h.destinationOtn) : null;
|
||||
const all = [...new Set([h.otn, h.referenceOtn, ...(h.operationalTrainNumbers || []), ...(h.referenceOtns || [])].filter(x => x != null).map(String))];
|
||||
return [...new Set([...(o ? [o] : []), ...all.filter(x => x !== o && x !== d), ...(d ? [d] : [])])];
|
||||
}
|
||||
const matchesNumber = (h, num) => trainNumbers(h).includes(String(num));
|
||||
|
||||
// Composition TIS (onglet « Train composition ») réduite à l'essentiel, dans l'ordre du parcours.
|
||||
// Une composition par section (souvent une par gestionnaire d'infrastructure).
|
||||
function compactCompositions(data) {
|
||||
const comps = (data && data.compositions) || [];
|
||||
if (!comps.length) return [];
|
||||
const order = ((data && data.activeCompositions) || []).map(a => a.compositionId);
|
||||
const names = Object.fromEntries(((data && data.activeCompositions) || []).map(a => [a.compositionId, [a.locFromName, a.locToName]]));
|
||||
const active = order.length ? order.map(id => comps.find(c => c.id === id)).filter(Boolean) : comps;
|
||||
return active.map(c => ({
|
||||
id: c.id, from: c.fromLocationId, to: c.toLocationId, fromName: (names[c.id] || [])[0] || null, toName: (names[c.id] || [])[1] || null,
|
||||
im: c.responsibleImCode || null, veh: c.vehicleCount ?? null, len: c.length ?? null, w: c.weight ?? null, // poids du train (pas le poids freiné)
|
||||
}));
|
||||
}
|
||||
// Composition de la section où se trouve le train : même gestionnaire d'infrastructure que la position
|
||||
// actuelle (origine si pas parti, destination si arrivé). Libellé « véhicules-longueur-poids » : 31-653-902.
|
||||
function currentComposition(h, phase, ctx) {
|
||||
const c = (ctx.compos || {})[h.id], list = (c && c.list) || [];
|
||||
if (!list.length) return null;
|
||||
const pt = phase === 'arrived' ? h.destination : phase === 'waiting' ? h.origin : h.current;
|
||||
const im = (pt || {}).responsibleImCode, here = (pt || {}).locationId;
|
||||
// lieux déjà franchis (détail d'itinéraire) + position actuelle
|
||||
const det = (ctx.details || {})[h.id], passed = new Set((det && det.passed) || []);
|
||||
if (here != null) passed.add(here);
|
||||
let cands = list.filter(x => x.im && x.im === im);
|
||||
if (!cands.length) cands = list;
|
||||
let cur;
|
||||
if (phase === 'arrived') cur = cands[cands.length - 1];
|
||||
else if (phase === 'waiting') cur = cands[0];
|
||||
else {
|
||||
const started = cands.filter(x => passed.has(x.from)); // sections déjà commencées
|
||||
cur = started[started.length - 1] || cands.find(x => x.to === here) || cands[0];
|
||||
}
|
||||
const label = [cur.veh, cur.len, cur.w].every(v => v != null) ? `${cur.veh}-${cur.len}-${cur.w}` : null;
|
||||
return label ? { ...cur, label, sections: list } : null;
|
||||
}
|
||||
// Horaire complet d'un train (pour l'impression) : étapes remises dans l'ordre du parcours, prévisions isolées
|
||||
// écartées, arrivée + départ au même lieu fusionnés en une ligne. kind : origin | stop | pass | dest.
|
||||
function buildTimetable(train, locName) {
|
||||
const seen = new Set();
|
||||
const when = d => Date.parse(d.plannedTime || d.actualTime || 0) || 0;
|
||||
const pts = (train.sections || []).flatMap(s => s.trainDetails || [])
|
||||
.filter(d => (d.plannedTime || d.actualTime) && !seen.has(d.id) && seen.add(d.id))
|
||||
.sort((a, b) => when(a) - when(b));
|
||||
const isArr = st => /ARRIVAL/.test(st || ''), isDep = st => /DEPARTURE/.test(st || '');
|
||||
const rows = [];
|
||||
for (const d of pts) {
|
||||
const st = d.plannedStatus || d.calculatedStatus || d.actualStatus || '';
|
||||
const t = { p: d.plannedTime || null, a: d.actualTime || null, c: d.calculatedTime || null };
|
||||
const delta = d.runningDeltaForDisplay ?? d.forecastDeltaForDisplay ?? null;
|
||||
const prev = rows[rows.length - 1];
|
||||
// départ qui suit l'arrivée au même lieu : même ligne (Arr. / Dép.)
|
||||
if (prev && prev.loc === d.locationId && isDep(st) && prev.arr && !prev.dep) {
|
||||
prev.dep = t; prev.kind = 'stop'; if (delta != null) prev.delay = delta; if (d.currentLocation) prev.current = true;
|
||||
continue;
|
||||
}
|
||||
const row = { loc: d.locationId, name: locName(d.locationId), im: d.responsibleImCode || null, delay: delta, current: !!d.currentLocation,
|
||||
kind: st === 'DEPARTURE_FROM_ORIGIN' ? 'origin' : st === 'ARRIVAL_AT_DESTINATION' ? 'dest' : isArr(st) || isDep(st) ? 'stop' : 'pass',
|
||||
arr: isArr(st) ? t : null, dep: isArr(st) ? null : t };
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Lieux déjà franchis par le train (pour savoir dans quelle section de composition il se trouve).
|
||||
function passedLocations(train) {
|
||||
return [...new Set((train.sections || []).flatMap(s => s.trainDetails || []).filter(d => d.actualTime).map(d => d.locationId))];
|
||||
}
|
||||
|
||||
// Causes de retard déclarées dans TIS (codes UIC) pour ce train.
|
||||
// Causes de retard : celles de l'en-tête + toutes celles du détail d'itinéraire (onglet « Statistiques » de TIS),
|
||||
// sans doublon, de la plus ancienne à la plus récente.
|
||||
function delayCauses(h, locName, cached = []) {
|
||||
const seen = new Set(), out = [];
|
||||
const add = x => {
|
||||
if (x.id != null && seen.has(x.id)) return;
|
||||
seen.add(x.id);
|
||||
out.push({ delay: x.delay ?? null, code: x.delayCauseCode || x.delayCause || null, at: locName(x.locationId), time: x.time || null, im: x.locationImCode || null });
|
||||
};
|
||||
for (const p of [h.origin, h.current, h.destination]) for (const x of (p && p.trainDelays) || []) add(x);
|
||||
for (const x of cached || []) add(x);
|
||||
return out.sort((a, b) => (Date.parse(a.time) || 0) - (Date.parse(b.time) || 0));
|
||||
}
|
||||
// Toutes les causes de retard d'un train complet (sections → étapes → trainDelays), forme compacte pour le cache.
|
||||
function compactCauses(train) {
|
||||
return (train.sections || []).flatMap(s => s.trainDetails || []).flatMap(d => d.trainDelays || [])
|
||||
.map(x => ({ id: x.id, delay: x.delay, delayCauseCode: x.delayCauseCode || x.delayCause, locationId: x.locationId, locationImCode: x.locationImCode, time: x.time }));
|
||||
}
|
||||
|
||||
// Prochain point de passage d'après le détail d'itinéraire en cache.
|
||||
// Heure estimée d'un point pas encore atteint. TIS fournit une heure calculée, mais elle est parfois périmée
|
||||
// (calculée avec un ancien retard : ex. Bertrix « estimé » +34 alors que le train vient de pointer à +63).
|
||||
// Si l'heure TIS est nettement plus tôt (> 15 min) que « heure prévue + retard actuel », on utilise cette
|
||||
// projection (src 'tta', affichée avec ≈). Sinon on garde l'heure TIS (src 'tis').
|
||||
function estimateAt(planned, calc, delay) {
|
||||
if (!planned) return { t: calc || null, src: calc ? 'tis' : null };
|
||||
if (delay == null) return { t: calc || planned, src: 'tis' };
|
||||
const proj = Date.parse(planned) + delay * 60000;
|
||||
if (calc && Date.parse(calc) >= proj - 15 * 60000) return { t: calc, src: 'tis' };
|
||||
return { t: new Date(proj).toISOString(), src: 'tta' };
|
||||
}
|
||||
|
||||
// Le cache est trié dans l'ordre du parcours (voir compactDetails). Si la position actuelle n'y est plus
|
||||
// (cache plus ancien que le dernier pointage), on prend le premier point non franchi après l'heure du pointage.
|
||||
function nextStop(h, ctx, delay = null) {
|
||||
const cache = ctx.details[h.id];
|
||||
if (!cache) return null;
|
||||
const cur = h.current || {}, pingAt = Date.parse(cur.actualTime || 0) || 0;
|
||||
const i = cache.points.findIndex(p => p.id === cur.id);
|
||||
// repli : points dont l'heure prévue + retard actuel vient après le dernier pointage
|
||||
const rest = i >= 0 ? cache.points.slice(i + 1) : cache.points.filter(p => Date.parse(p.pt || p.ct) + (delay || 0) * 60000 >= pingAt - 5 * 60000);
|
||||
const k = rest.findIndex(x => !x.at && x.loc !== cur.locationId && (x.pt || x.ct));
|
||||
if (k < 0) return null;
|
||||
const p = rest[k];
|
||||
const est = estimateAt(p.pt, p.ct, delay);
|
||||
const out = { name: ctx.locName(p.loc), plannedTime: p.pt || null, estimatedTime: est.t || p.pt || null, estSrc: est.src, tisTime: p.ct || null, status: p.st, deltaMin: p.fd ?? null };
|
||||
// Même lieu répété (arrivée puis départ) = arrêt : la 1re ligne est l'arrivée, la dernière le départ.
|
||||
// TIS ne pointe souvent pas l'arrivée en faisceau : une fois l'heure d'arrivée passée, le train est
|
||||
// considéré à l'arrêt et n'est « en retard » qu'après son heure de départ.
|
||||
let j = k;
|
||||
while (rest[j + 1] && rest[j + 1].loc === p.loc && !rest[j + 1].at) j++;
|
||||
const q = rest[j];
|
||||
if (j > k && q.pt && p.pt && Date.parse(q.pt) > Date.parse(p.pt)) {
|
||||
const dep = estimateAt(q.pt, q.ct, null); // le stationnement absorbe souvent le retard : heure TIS
|
||||
out.stop = { arrPlanned: p.pt, arrEst: out.estimatedTime, depPlanned: q.pt, depEst: dep.t || q.pt, depTis: q.ct || null };
|
||||
if (ctx.now >= Date.parse(out.estimatedTime || p.pt)) {
|
||||
out.atStop = true;
|
||||
out.plannedTime = q.pt; out.estimatedTime = dep.t || q.pt; out.estSrc = 'tis'; out.tisTime = q.ct || null;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function classify(h, ctx) {
|
||||
const now = ctx.now, cfg = ctx.cfg, locName = ctx.locName;
|
||||
const o = h.origin || {}, c = h.current || {}, d = h.destination || {};
|
||||
const plannedDep = o.plannedTime ? Date.parse(o.plannedTime) : null;
|
||||
const departed = !!o.actualTime;
|
||||
const arrived = !!d.actualTime;
|
||||
let phase, delay = null, reason = '';
|
||||
let etdLate = 0, startsInMin = null, stale = false;
|
||||
|
||||
if (arrived) {
|
||||
phase = 'arrived';
|
||||
// retard à l'arrivée : celui de TIS, sinon heure réelle - heure prévue (si l'écart est plausible)
|
||||
const calc = d.plannedTime ? minutesBetween(Date.parse(d.actualTime), Date.parse(d.plannedTime)) : null;
|
||||
delay = d.runningDeltaForDisplay ?? d.forecastDeltaForDisplay ?? (calc != null && Math.abs(calc) <= 720 ? calc : null);
|
||||
reason = 'Arrivé';
|
||||
} else if (h.running || departed) {
|
||||
phase = 'running';
|
||||
delay = c.runningDeltaForDisplay ?? c.forecastDeltaForDisplay ?? o.runningDeltaForDisplay ?? 0;
|
||||
reason = 'En circulation';
|
||||
} else {
|
||||
phase = 'waiting';
|
||||
const late = plannedDep ? minutesBetween(now, plannedDep) : 0; // > 0 : heure de départ prévue dépassée
|
||||
const fc = o.forecastDeltaForDisplay > 0 ? o.forecastDeltaForDisplay : 0; // retard annoncé par TIS avant le départ
|
||||
if (late > 720) {
|
||||
// plus de 12 h après l'heure prévue : date TIS douteuse ou train périmé, on ne l'alerte pas
|
||||
stale = true; delay = 0;
|
||||
reason = 'Départ prévu depuis plus de 12 h (données TIS douteuses)';
|
||||
} else {
|
||||
etdLate = late > 0 ? late : 0;
|
||||
startsInMin = late <= 0 ? -late : null;
|
||||
delay = Math.max(etdLate, fc);
|
||||
reason = etdLate > 0 ? `Pas parti de l'origine (prévu il y a ${etdLate} min)`
|
||||
: fc > 0 ? `Pas encore parti · retard annoncé +${fc} min` : 'Pas encore parti';
|
||||
}
|
||||
}
|
||||
|
||||
// vert = en circulation à l'heure ; bleu = pas encore parti (à l'heure) ; gris = arrivé / inactif
|
||||
let color = phase === 'waiting' ? 'blue' : 'green';
|
||||
if (phase === 'arrived' || stale) color = 'grey';
|
||||
else if (delay >= cfg.redFromMin) color = 'red';
|
||||
else if (delay >= cfg.yellowFromMin) color = 'yellow';
|
||||
if (h.interrupted && phase !== 'arrived') { color = 'red'; reason += ' · INTERROMPU'; }
|
||||
|
||||
const next = phase === 'running' ? nextStop(h, ctx, delay) : null;
|
||||
// arrivée estimée : même règle (TIS si cohérent avec le retard actuel, sinon prévu + retard)
|
||||
const arrEst = phase === 'arrived' ? { t: d.calculatedTime || null, src: 'tis' } : estimateAt(d.plannedTime, d.calculatedTime, phase === 'running' || phase === 'waiting' ? delay : null);
|
||||
const expectAt = next ? (next.estimatedTime || next.plannedTime) : (arrEst.t || d.plannedTime || null);
|
||||
return {
|
||||
otn: String(h.otn), id: h.id, type: h.type, phase, color, delay, reason, etdLate, startsInMin,
|
||||
interrupted: !!h.interrupted,
|
||||
origin: locName(o.locationId), destination: locName(d.locationId),
|
||||
current: phase === 'running' ? locName(c.locationId) : null,
|
||||
plannedDeparture: o.plannedTime || null, actualDeparture: o.actualTime || null,
|
||||
plannedArrival: d.plannedTime || null, forecastArrival: arrEst.t || d.calculatedTime || null, arrEstSrc: arrEst.src,
|
||||
lastEvent: d.actualTime || c.actualTime || o.actualTime || null,
|
||||
lastPingPlace: c.actualTime ? locName(c.locationId) : (o.actualTime ? locName(o.locationId) : null),
|
||||
lastPingAt: c.actualTime || o.actualTime || null,
|
||||
next: phase === 'running' ? next : null,
|
||||
// minutes de dépassement de l'heure attendue au prochain point (sinon à l'arrivée) ; ≤ 0 = pas encore en retard
|
||||
overdueMin: phase === 'running' && expectAt ? minutesBetween(now, Date.parse(expectAt)) : null,
|
||||
overdueOn: phase === 'running' && expectAt ? (next ? 'next' : 'arrival') : null,
|
||||
detailAt: (ctx.details[h.id] || {}).at || null,
|
||||
numbers: trainNumbers(h),
|
||||
delays: delayCauses(h, locName, (ctx.details[h.id] || {}).causes),
|
||||
compo: currentComposition(h, phase, ctx),
|
||||
compoKnown: !!(ctx.compos || {})[h.id], // composition déjà demandée à TIS (sinon : chargement en cours)
|
||||
archive: !!h.archive,
|
||||
};
|
||||
}
|
||||
|
||||
// Pour chaque numéro : le(s) train(s) en circulation, sinon le plus proche pas encore arrivé.
|
||||
// Le numéro est cherché parmi TOUS les numéros du train (il change parfois en route).
|
||||
// pins = { numéro: 'AAAA-MM-JJ' } : jour choisi à la main (départ prévu ce jour-là).
|
||||
function pickPerNumber(trains, numbers, ctx, pins = {}) {
|
||||
const now = ctx.now;
|
||||
return numbers.flatMap(num => {
|
||||
const all = trains.filter(t => matchesNumber(t.header, num) && !t.header.archive);
|
||||
// les autres jours de ce numéro, pour pouvoir en choisir un autre dans la fiche du train
|
||||
const alts = all.map(t => t.header).filter(h => (h.origin || {}).plannedTime)
|
||||
.sort((a, b) => Date.parse(a.origin.plannedTime) - Date.parse(b.origin.plannedTime)).slice(-14)
|
||||
.map(h => ({ id: h.id, dep: h.origin.plannedTime, date: localDate(h.origin.plannedTime),
|
||||
state: (h.destination || {}).actualTime ? 'arrivé' : (h.running || h.origin.actualTime) ? 'en circulation' : 'pas parti' }));
|
||||
const pin = pins[num] || null;
|
||||
const tag = row => ({ ...row, query: num, alts, pinned: pin });
|
||||
let cands = all;
|
||||
if (pin) {
|
||||
cands = all.filter(t => localDate(t.header.origin.plannedTime || 0) === pin);
|
||||
if (!cands.length) return [tag({ otn: num, phase: 'notfound', color: 'grey', delay: null, reason: `Aucun train ${num} au départ le ${pin.split('-').reverse().join('/')} dans TIS` })];
|
||||
} else {
|
||||
const active = cands.filter(t => t.header.running && !(t.header.destination || {}).actualTime);
|
||||
if (active.length > 1) return active.map(t => tag(classify(t.header, ctx)));
|
||||
}
|
||||
const score = t => {
|
||||
const h = t.header, d = h.destination || {}, o = h.origin || {};
|
||||
if (d.actualTime) return 1e12 + (now - Date.parse(d.actualTime));
|
||||
if (h.running || o.actualTime) return 0;
|
||||
return Math.abs(Date.parse(o.plannedTime || now) - now);
|
||||
};
|
||||
cands.sort((a, b) => score(a) - score(b));
|
||||
if (!cands.length) return [tag({ otn: num, phase: 'notfound', color: 'grey', delay: null, reason: 'Numéro introuvable dans TIS' })];
|
||||
const best = classify(cands[0].header, ctx);
|
||||
if (!pin && best.phase === 'arrived' && now - Date.parse(best.lastEvent || 0) > 12 * 3600e3)
|
||||
return [tag({ otn: num, phase: 'unknown', color: 'grey', delay: null, reason: 'Aucun train actif (dernier arrivé il y a plus de 12 h) : choisis un autre jour dans la fiche du train' })];
|
||||
return [tag(best)];
|
||||
});
|
||||
}
|
||||
|
||||
// Points d'itinéraire compacts (à partir de la position actuelle) pour le cache.
|
||||
// TIS envoie les étapes par sections, PAS dans l'ordre du parcours, et parfois des prévisions isolées
|
||||
// (heure calculée sans heure prévue, ex. un autre trajet du même numéro) : on les écarte et on trie par heure.
|
||||
function compactDetails(train) {
|
||||
// Trier sur l'heure PRÉVUE : c'est elle qui suit l'ordre du parcours. (Trier sur l'heure réelle classait la
|
||||
// position actuelle d'un train en retard APRÈS des points qu'il n'a pas encore atteints.)
|
||||
const when = d => Date.parse(d.plannedTime || d.calculatedTime || d.actualTime || 0) || 0;
|
||||
const all = (train.sections || []).flatMap(s => s.trainDetails || [])
|
||||
.filter(d => d.plannedTime || d.actualTime || d.currentLocation)
|
||||
.sort((a, b) => when(a) - when(b));
|
||||
let i = all.findIndex(d => d.currentLocation);
|
||||
if (i < 0) { const done = all.filter(d => d.actualTime); i = done.length ? all.indexOf(done[done.length - 1]) : all.findIndex(d => !d.actualTime); }
|
||||
if (i < 0) return null;
|
||||
return all.slice(Math.max(0, i), i + 20).map(d => ({
|
||||
id: d.id, loc: d.locationId, pt: d.plannedTime, ct: d.calculatedTime, at: d.actualTime,
|
||||
st: d.plannedStatus || d.calculatedStatus, fd: d.forecastDeltaForDisplay ?? d.runningDeltaForDisplay ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
const DEFAULT_PREFS = {
|
||||
sound: true, desktop: true,
|
||||
delayAlertMin: 10, // alerte "retard" à partir de +10 min
|
||||
etdMin: 5, // alerte "heure de départ dépassée" : +5 min après l'ETD sans départ
|
||||
staleOn: true, pingYellowMin: 5, pingRedMin: 10, // (ancien réglage, remplacé par overdue*)
|
||||
// pastille du pointage : jaune si l'heure du prochain point (ou de l'arrivée) est dépassée de 5 min, rouge au-delà de 15 min.
|
||||
// Un train arrêté longtemps mais dont le prochain point n'est pas encore dû est « en stand-by », pas en alerte.
|
||||
overdueYellowMin: 5, overdueRedMin: 15, standbyMin: 10,
|
||||
debug: false, // affiche le panneau de debug (journal + état) sur la page
|
||||
autoLogin: true, // session expirée : tentative de reconnexion automatique (fenêtre réduite)
|
||||
theme: 'auto', // auto | dark | light
|
||||
source: 'list', // list = numéros saisis | filter = filtre TIS enregistré (« mes trains »)
|
||||
upcomingMin: 60, // mode filtre : ajoute les trains qui partent dans les 60 prochaines minutes
|
||||
lateLookbackMin: 180, // … et ceux pas encore partis jusqu'à 3 h après l'heure prévue (alertes ETD)
|
||||
ev: { depart: true, delay10: true, etd5: true, red: true, arrive: true, session: true },
|
||||
arrivedOpen: false, // section « Arrivés » dépliée ou repliée
|
||||
};
|
||||
// Filtre intégré à l'app (prêt à l'emploi) : entreprises ferroviaires SIBELIT / CFL Cargo dans TIS.
|
||||
// Les codes sont modifiables dans Réglages (prefs.presetRu).
|
||||
const SIBELIT_RU = ['0087.08987', '0087.08900', '0088.0682', '0082.SIBEL', '0082.8987'];
|
||||
// Lineas : toutes ses entités dans TIS (BE, FR, LU, DE, AT, IT, NL, Intermodal).
|
||||
const LINEAS_RU = ['0088.2188', '0088.3276', '9988.2188', '0087.08944', '0087.02188', '0087.3220', '0087.09218', '0087.09144', '0087.09118',
|
||||
'0082.LINEA', '0080.2188', '0080.3627', '0080.D3340', '0080.D3136', '0081.2188', '0083.3628', '0084.2188', '0084.3539', '0084.3629'];
|
||||
// Listes intégrées (non modifiables). « Liste manuelle » = uniquement les numéros saisis.
|
||||
const PRESET_LISTS = [
|
||||
{ id: 'preset-sibelit', name: 'SIBELIT', preset: true, ruCodes: SIBELIT_RU },
|
||||
{ id: 'preset-lineas', name: 'Lineas', preset: true, ruCodes: LINEAS_RU },
|
||||
{ id: 'preset-manual', name: 'Liste manuelle', preset: true, ruCodes: [] },
|
||||
];
|
||||
const PRESET_FILTERS = PRESET_LISTS.filter(l => l.ruCodes.length).map(l => ({ id: l.id, name: l.name, preset: true, definition: { ruCodes: l.ruCodes } }));
|
||||
|
||||
// Liste active : choix explicite (prefs.activeList), sinon réglage des versions précédentes, sinon SIBELIT.
|
||||
function activeListId(prefs, tisFilter) {
|
||||
if (prefs && prefs.activeList) return prefs.activeList;
|
||||
if (prefs && prefs.sourceChosen) {
|
||||
if (prefs.source === 'list') return 'preset-manual';
|
||||
if (tisFilter && tisFilter.id != null) return String(tisFilter.id).startsWith('preset-') ? String(tisFilter.id) : 'tis-' + tisFilter.id;
|
||||
}
|
||||
return 'preset-sibelit';
|
||||
}
|
||||
// Décrit la liste active : { id, name, kind: preset|custom|tis, definition (filtre TIS) ou null si pas de filtre }.
|
||||
function resolveList(prefs, { lists = [], tisFilters = [], tisFilter = null } = {}) {
|
||||
const id = activeListId(prefs, tisFilter);
|
||||
const l = PRESET_LISTS.find(x => x.id === id) || lists.find(x => x.id === id);
|
||||
if (l) {
|
||||
let ru = l.ruCodes || [];
|
||||
if (l.id === 'preset-sibelit' && prefs && Array.isArray(prefs.presetRu) && prefs.presetRu.length) ru = prefs.presetRu;
|
||||
return { id: l.id, name: l.name, kind: l.preset ? 'preset' : 'custom', definition: ru.length ? { ruCodes: ru } : null };
|
||||
}
|
||||
if (id.startsWith('tis-')) {
|
||||
const f = tisFilters.find(x => 'tis-' + x.id === id) || (tisFilter && 'tis-' + tisFilter.id === id ? tisFilter : null);
|
||||
if (f && f.definition) return { id, name: f.name, kind: 'tis', definition: f.definition };
|
||||
}
|
||||
return resolveList({ ...(prefs || {}), activeList: 'preset-sibelit' });
|
||||
}
|
||||
|
||||
// Causes de retard UIC (libellés TIS en français, quelques traductions corrigées).
|
||||
const DELAY_CAUSES = {
|
||||
10: 'Élaboration des horaires', 11: 'Composition du train par le GI', 12: 'Erreurs de procédure opérationnelle', 13: 'Mauvaise application des priorités',
|
||||
18: 'Personnel (GI)', 19: 'Autres causes (GI)', 20: 'Signalisation', 21: 'Signalisation aux passages à niveau', 22: 'Télécommunications',
|
||||
23: 'Alimentation électrique', 24: 'Voie', 25: 'Ouvrages d\'art', 28: 'Personnel (GI)', 29: 'Autres causes (GI)', 30: 'Travaux prévus',
|
||||
31: 'Irrégularités lors de travaux', 32: 'Ralentissement pour défaut de voie', 38: 'Personnel (GI)', 39: 'Autres causes (GI)',
|
||||
40: 'Causé par le GI suivant', 41: 'Causé par le GI précédent', 50: 'Dépassement du temps d\'arrêt', 51: 'Demande de l\'EF', 52: 'Opérations de chargement',
|
||||
53: 'Irrégularités de chargement', 54: 'Préparation commerciale du train', 58: 'Personnel (EF)', 59: 'Autres causes (EF)', 60: 'Roulements / réorganisation',
|
||||
61: 'Composition du train par l\'EF', 62: 'Voitures (voyageurs)', 63: 'Wagons (fret)', 64: 'Locomotive / engin moteur', 68: 'Personnel (EF)', 69: 'Autres causes (EF)',
|
||||
70: 'Causé par l\'EF suivante', 71: 'Causé par l\'EF précédente', 80: 'Grève', 81: 'Formalités administratives', 82: 'Influence extérieure',
|
||||
83: 'Météo / causes naturelles', 84: 'Causes externes sur le réseau suivant', 89: 'Autres causes externes', 90: 'Incident, accident, danger',
|
||||
91: 'Occupation de voie (retard de ce train)', 92: 'Occupation de voie (autre train)', 93: 'Rebroussement / retournement', 94: 'Correspondance',
|
||||
95: 'Analyse plus poussée nécessaire', 96: 'Suppression sans justification', 99: 'Autres causes (secondaires)',
|
||||
};
|
||||
const DELAY_FAMILY = c => { const n = Number(c); return n < 40 ? 'Gestionnaire d\'infrastructure' : n < 50 ? 'GI (réseau voisin)' : n < 80 ? 'Entreprise ferroviaire' : n < 90 ? 'Causes externes' : 'Causes secondaires'; };
|
||||
const delayLabel = c => c == null ? 'cause non précisée' : `${c} · ${DELAY_CAUSES[Number(c)] || 'code UIC ' + c}`;
|
||||
|
||||
// Priorité du son quand plusieurs alertes tombent au même moment (une seule sonnerie par cycle).
|
||||
const KIND_PRIORITY = ['session', 'red', 'etd5', 'delay10', 'depart', 'arrive'];
|
||||
const TREND_SHOW_MS = 10 * 60000; // une évolution du retard reste affichée 10 min
|
||||
|
||||
// Tendance du retard : écart avec la valeur précédente, conservé tant qu'il n'a pas changé à nouveau.
|
||||
function applyTrends(rows, prev, now) {
|
||||
for (const t of rows) {
|
||||
const p = prev[t.otn + ':' + (t.id || '')];
|
||||
if (!p || t.delay == null || p.delay == null) { t.trend = null; t.trendAt = null; continue; }
|
||||
if (t.delay !== p.delay) { t.trend = t.delay - p.delay; t.trendAt = now; }
|
||||
else { t.trend = p.trend ?? null; t.trendAt = p.trendAt ?? null; }
|
||||
if (t.trendAt && now - t.trendAt > TREND_SHOW_MS) { t.trend = null; t.trendAt = null; }
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Alertes à émettre quand un train change d'état. prev : { [otn:id]: {color, phase, flags} }.
|
||||
// Les drapeaux (retard >= seuil, ETD dépassé) se réarment quand la condition disparaît.
|
||||
// Un train vu pour la première fois n'alerte pas.
|
||||
function diffAlerts(rows, prev, prefsIn) {
|
||||
const prefs = { ...DEFAULT_PREFS, ...(prefsIn || {}), ev: { ...DEFAULT_PREFS.ev, ...((prefsIn || {}).ev || {}) } };
|
||||
const alerts = [], next = {};
|
||||
const push = (kind, level, title, body) => { if (prefs.ev[kind]) alerts.push({ kind, level, title, body }); };
|
||||
for (const t of rows) {
|
||||
const key = t.otn + ':' + (t.id || '');
|
||||
const p = prev[key];
|
||||
const flags = {
|
||||
d10: t.delay != null && t.phase !== 'arrived' && t.delay >= prefs.delayAlertMin,
|
||||
etd5: t.phase === 'waiting' && t.etdLate >= prefs.etdMin,
|
||||
};
|
||||
if (p) {
|
||||
const fmt = t.delay == null ? '' : (t.delay > 0 ? '+' : '') + t.delay + ' min';
|
||||
const route = t.origin && t.destination ? `${t.origin} → ${t.destination}` : '';
|
||||
if (p.phase === 'waiting' && t.phase === 'running') push('depart', t.color, `Train ${t.otn} : parti`, `${t.origin} · ${fmt}`);
|
||||
if (p.flags) {
|
||||
if (flags.etd5 && !p.flags.etd5) push('etd5', 'red', `Train ${t.otn} : pas parti`, `Prévu il y a ${t.etdLate} min · ${route}`);
|
||||
if (flags.d10 && !p.flags.d10) push('delay10', t.color, `Train ${t.otn} : retard ${fmt}`, route);
|
||||
}
|
||||
if (t.color === 'red' && p.color !== 'red' && t.phase !== 'waiting') push('red', 'red', `Train ${t.otn} : retard important`, `${t.reason} · ${fmt}`);
|
||||
if (p.phase !== 'arrived' && t.phase === 'arrived') push('arrive', 'grey', `Train ${t.otn} : arrivé`, `${t.destination} · ${fmt}`);
|
||||
}
|
||||
next[key] = { color: t.color, phase: t.phase, flags, delay: t.delay ?? null, trend: t.trend ?? null, trendAt: t.trendAt ?? null };
|
||||
}
|
||||
const kinds = alerts.map(a => a.kind);
|
||||
const loudest = KIND_PRIORITY.find(k => kinds.includes(k)) || null;
|
||||
return { alerts, next, loudest };
|
||||
}
|
||||
|
||||
// Lignes à afficher : trains du filtre TIS (chacun une ligne, marqués src='filter') puis les numéros saisis
|
||||
// à la main (le meilleur train par numéro), sans doublon.
|
||||
function buildRows(fleet, extra, numbers, ctx, pins = {}) {
|
||||
const rows = [], seen = new Set();
|
||||
for (const t of fleet || []) {
|
||||
if (seen.has(t.header.id)) continue;
|
||||
seen.add(t.header.id);
|
||||
rows.push({ ...classify(t.header, ctx), src: 'filter' });
|
||||
}
|
||||
if (extra) for (const row of pickPerNumber(extra, numbers, ctx, pins)) {
|
||||
if (row.id && seen.has(row.id)) continue;
|
||||
if (row.id) seen.add(row.id);
|
||||
rows.push({ ...row, src: 'list' });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Identifiants de lieux encore utiles (pour ne pas laisser grossir le cache des noms).
|
||||
function usedLocations(trains, details) {
|
||||
const ids = new Set();
|
||||
for (const t of trains) for (const k of ['origin', 'current', 'destination']) { const l = (t.header[k] || {}).locationId; if (l != null) ids.add(String(l)); }
|
||||
for (const d of Object.values(details)) for (const p of d.points || []) if (p.loc != null) ids.add(String(p.loc));
|
||||
return ids;
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined') module.exports = { estimateAt, delayCauses, compactCauses, classify, pickPerNumber, buildRows, nextStop, compactDetails, diffAlerts, applyTrends, usedLocations, resolveList, activeListId,
|
||||
trainNumbers, matchesNumber, twinNumber, localDate, compactCompositions, currentComposition, passedLocations, buildTimetable, delayLabel, DELAY_FAMILY, PRESET_LISTS, PRESET_FILTERS, DEFAULT_PREFS };
|
||||
@@ -0,0 +1,405 @@
|
||||
/* ===================== TTA – thèmes ===================== */
|
||||
:root, :root[data-theme="dark"] {
|
||||
--bg:#0b1220; --panel:#121a2b; --panel2:#18233a; --line:#25324c; --text:#eef3fb; --muted:#a3b3ca; --faint:#6f819c;
|
||||
--red:#f25656; --yellow:#f2b72b; --green:#2ec37a; --blue:#5b95ff; --grey:#7d8aa0; --orange:#ff9f1a;
|
||||
--accent:#F4B400; --accent-ink:#14305E; --brand-ink:#ffffff; --brand-sub:#F4B400; --shadow:0 10px 30px rgba(0,0,0,.4); --tint:16%;
|
||||
--navy:#14305E; --sun:#F4B400; --brand-red:#D62828;
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--bg:#eef2f7; --panel:#ffffff; --panel2:#f5f8fc; --line:#d8e0eb; --text:#0f1b2d; --muted:#4f5f76; --faint:#7d8ba0;
|
||||
--red:#d42c2c; --yellow:#b07a00; --green:#12864a; --blue:#1d5fd1; --grey:#66748a; --orange:#c96a00;
|
||||
--accent:#14305E; --accent-ink:#ffffff; --brand-ink:#14305E; --brand-sub:#14305E; --shadow:0 10px 30px rgba(20,35,60,.14); --tint:12%;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root[data-theme="auto"] {
|
||||
--bg:#eef2f7; --panel:#ffffff; --panel2:#f5f8fc; --line:#d8e0eb; --text:#0f1b2d; --muted:#4f5f76; --faint:#7d8ba0;
|
||||
--red:#d42c2c; --yellow:#b07a00; --green:#12864a; --blue:#1d5fd1; --grey:#66748a; --orange:#c96a00;
|
||||
--accent:#14305E; --accent-ink:#ffffff; --brand-ink:#14305E; --brand-sub:#14305E; --shadow:0 10px 30px rgba(20,35,60,.14); --tint:12%;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing:border-box; }
|
||||
html, body { height:100%; }
|
||||
body { margin:0; background:var(--bg); color:var(--text); font:15px/1.35 "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, sans-serif; overflow:hidden; -webkit-font-smoothing:antialiased; }
|
||||
button, input { font:inherit; color:inherit; }
|
||||
.app { height:100vh; display:flex; flex-direction:column; gap:12px; padding:14px 20px 10px; max-width:1920px; margin:0 auto; position:relative; }
|
||||
.num-font, .live-time, .n, .pill .v { font-variant-numeric:tabular-nums; }
|
||||
|
||||
/* ===================== En-tête ===================== */
|
||||
.top { display:grid; grid-template-columns:1fr auto 1fr; gap:20px; align-items:center; }
|
||||
.brand { display:flex; align-items:center; gap:12px; }
|
||||
.logo-tile { width:54px; height:54px; flex:none; background:#fff; border-radius:14px; display:grid; place-items:center; box-shadow:0 0 0 1px rgba(20,48,94,.18), 0 6px 16px rgba(0,0,0,.18); }
|
||||
.logo-tile img { width:50px; height:50px; display:block; }
|
||||
.logo-tile.big { width:76px; height:76px; border-radius:19px; margin:0 auto 12px; } .logo-tile.big img { width:70px; height:70px; }
|
||||
.brand-name { font:900 30px/0.95 "Arial Black", "Segoe UI Black", "Segoe UI", sans-serif; letter-spacing:1px; color:var(--brand-ink); }
|
||||
.brand-sub { color:var(--brand-sub); font-size:11.5px; font-weight:800; margin-top:4px; letter-spacing:1.3px; }
|
||||
.partner { display:flex; flex-direction:column; align-items:flex-start; gap:1px; margin-left:6px; padding-left:14px; border-left:1px solid var(--line); }
|
||||
.partner .pb { font-size:11px; font-style:italic; color:var(--muted); }
|
||||
.partner .sib { background:#fff; color:#1F3C99; border:1.5px solid #1F3C99; border-radius:5px; padding:1px 8px 0; font:900 13px/1.35 "Arial Black", "Segoe UI Black", sans-serif; letter-spacing:.8px;
|
||||
box-shadow:inset 0 -2.5px 0 var(--brand-red); }
|
||||
|
||||
.live { min-width:340px; text-align:center; background:var(--panel); border:1px solid var(--line); border-radius:16px; padding:8px 24px 9px; --lc:var(--green); border-bottom:3px solid var(--lc); }
|
||||
.live.stale { --lc:var(--yellow); } .live.dead { --lc:var(--red); }
|
||||
.live-label { display:flex; justify-content:center; align-items:center; gap:8px; color:var(--muted); font-size:11.5px; text-transform:uppercase; letter-spacing:1.2px; font-weight:700; }
|
||||
.live-time { font-size:32px; line-height:1.08; font-weight:800; letter-spacing:1px; color:var(--lc); }
|
||||
.live-sub { color:var(--muted); font-size:13px; min-height:18px; display:flex; justify-content:center; gap:14px; }
|
||||
.dot { width:9px; height:9px; border-radius:50%; background:var(--lc); animation:pulse 2s infinite; }
|
||||
.live.stale .dot, .live.dead .dot { animation:none; }
|
||||
@keyframes pulse { 0% { box-shadow:0 0 0 0 color-mix(in srgb, var(--lc) 60%, transparent); } 70%,100% { box-shadow:0 0 0 8px transparent; } }
|
||||
.progress { height:3px; background:var(--line); border-radius:3px; margin-top:6px; overflow:hidden; }
|
||||
.progress i { display:block; height:100%; width:0; background:var(--lc); transition:width 1s linear; }
|
||||
|
||||
.actions { display:flex; gap:8px; justify-self:end; align-items:center; }
|
||||
.btn { background:var(--panel); border:1px solid var(--line); padding:9px 15px; border-radius:11px; cursor:pointer; transition:.15s; font-weight:600; }
|
||||
.btn:hover { border-color:var(--muted); background:var(--panel2); }
|
||||
.btn.icon { padding:9px 12px; font-size:16px; line-height:1; }
|
||||
.btn.primary { background:var(--accent); border-color:var(--accent); color:var(--accent-ink); font-weight:700; }
|
||||
.btn.primary:hover { filter:brightness(1.08); }
|
||||
.btn.off { opacity:.5; }
|
||||
.btn.mini { padding:4px 11px; font-size:12.5px; border-radius:8px; }
|
||||
.session { display:flex; align-items:center; gap:8px; background:var(--panel); border:1px solid var(--line); border-radius:999px; padding:8px 14px; cursor:pointer; font-weight:600; font-size:13.5px; max-width:300px; --sc:var(--grey); }
|
||||
.session span:last-child { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.session.ok { --sc:var(--green); } .session.ko { --sc:var(--red); border-color:color-mix(in srgb, var(--red) 55%, var(--line)); background:color-mix(in srgb, var(--red) var(--tint), var(--panel)); }
|
||||
.session:hover { border-color:var(--muted); }
|
||||
.sdot { width:9px; height:9px; border-radius:50%; background:var(--sc); flex:none; }
|
||||
|
||||
/* ===================== Barre : liste + compteurs ===================== */
|
||||
.bar { display:grid; grid-template-columns:minmax(320px,1fr) auto; gap:16px; align-items:stretch; }
|
||||
.editor { display:flex; gap:8px; }
|
||||
.editor input { flex:1; min-width:0; background:var(--panel); border:1px solid var(--line); border-radius:11px; padding:0 16px; font-size:15px; }
|
||||
.source { background:var(--panel); color:var(--text); border:1px solid var(--line); border-radius:11px; padding:0 12px; font:inherit; font-weight:700; max-width:240px; cursor:pointer; }
|
||||
.source option { background:var(--panel); color:var(--text); }
|
||||
.source.on { border-color:var(--accent); color:var(--accent); background:color-mix(in srgb, var(--accent) var(--tint), var(--panel)); }
|
||||
.source:focus { outline:2px solid var(--accent); outline-offset:-1px; }
|
||||
.editor input:focus { outline:2px solid var(--accent); outline-offset:-1px; }
|
||||
.tiles { display:flex; gap:8px; }
|
||||
.tile { background:var(--panel); border:1px solid var(--line); border-radius:11px; padding:6px 14px; min-width:104px; display:flex; align-items:center; gap:10px; cursor:pointer; text-align:left; transition:.15s; position:relative; overflow:hidden; }
|
||||
.tile::before { content:""; position:absolute; left:0; top:0; bottom:0; width:4px; background:var(--c); }
|
||||
.tile b { font-size:24px; line-height:1; color:var(--c); font-variant-numeric:tabular-nums; }
|
||||
.tile span { color:var(--muted); font-size:12.5px; line-height:1.15; font-weight:600; }
|
||||
.tile:hover { border-color:var(--c); }
|
||||
.tile.active { background:color-mix(in srgb, var(--c) var(--tint), var(--panel)); border-color:var(--c); }
|
||||
.tile.zero { opacity:.45; }
|
||||
.red { --c:var(--red); } .yellow { --c:var(--yellow); } .green { --c:var(--green); } .blue { --c:var(--blue); } .grey { --c:var(--grey); }
|
||||
|
||||
.hiddenbar { display:flex; align-items:center; gap:10px; color:var(--muted); font-size:13.5px; padding:0 4px; }
|
||||
.hiddenbar[hidden] { display:none; }
|
||||
.hiddenbar button { background:none; border:0; color:var(--blue); font-weight:700; cursor:pointer; padding:0; }
|
||||
.muted { color:var(--muted); font-size:13.5px; }
|
||||
.ruset { display:flex; flex-wrap:wrap; align-items:center; gap:6px; padding:4px 0; }
|
||||
.rus { flex:1; min-width:220px; background:var(--panel2); border:1px solid var(--line); border-radius:7px; padding:4px 8px; font:12.5px ui-monospace, Consolas, monospace; }
|
||||
#banner { display:flex; flex-direction:column; gap:8px; } #banner:empty { display:none; }
|
||||
.banner { display:flex; align-items:center; justify-content:space-between; gap:14px; padding:11px 16px; border-radius:12px; font-weight:600;
|
||||
background:color-mix(in srgb, var(--red) var(--tint), var(--panel)); border:1px solid color-mix(in srgb, var(--red) 50%, var(--line)); }
|
||||
.banner.info { background:color-mix(in srgb, var(--blue) var(--tint), var(--panel)); border-color:color-mix(in srgb, var(--blue) 50%, var(--line)); }
|
||||
.filterbar { display:flex; align-items:center; gap:10px; color:var(--muted); font-size:13px; }
|
||||
|
||||
/* ===================== Tableau ===================== */
|
||||
.board { flex:1; min-height:0; display:flex; flex-direction:column; gap:7px;
|
||||
--cols:6px 150px 122px 140px minmax(180px,1.15fr) minmax(200px,1.25fr) minmax(170px,1.1fr) 112px 132px 34px; }
|
||||
.cols { display:grid; grid-template-columns:var(--cols); gap:16px; align-items:center; }
|
||||
.cols.head { color:var(--faint); font-size:11.5px; text-transform:uppercase; letter-spacing:1px; font-weight:700; padding-right:12px; }
|
||||
.rows { flex:1; min-height:0; display:flex; flex-direction:column; gap:7px; overflow:auto; padding-right:2px; }
|
||||
|
||||
.row { flex:1 1 0; min-height:62px; max-height:96px; display:grid; grid-template-columns:var(--cols); gap:16px; align-items:center;
|
||||
background:var(--panel); border:1px solid var(--line); border-radius:14px; padding-right:12px; overflow:hidden; transition:border-color .15s, background .15s; }
|
||||
.row:hover { border-color:color-mix(in srgb, var(--c) 55%, var(--line)); }
|
||||
.row .bar-c { align-self:stretch; background:var(--c); }
|
||||
.row.red { background:linear-gradient(90deg, color-mix(in srgb, var(--red) var(--tint), transparent), transparent 45%), var(--panel); }
|
||||
|
||||
.cell { min-width:0; }
|
||||
.cell .m { font-size:16px; font-weight:650; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.cell .s { color:var(--muted); font-size:13.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }
|
||||
.cell .s b { color:var(--text); font-weight:650; }
|
||||
.n { font-size:21px; font-weight:800; letter-spacing:.4px; }
|
||||
.cell .t { color:var(--faint); font-size:12px; font-weight:600; text-transform:uppercase; letter-spacing:.6px; }
|
||||
|
||||
/* Pastille de statut (colonne de gauche) */
|
||||
.pill { overflow:hidden; display:flex; flex-direction:column; justify-content:center; align-items:flex-start; gap:1px; padding:6px 12px; border-radius:11px; min-height:48px;
|
||||
background:color-mix(in srgb, var(--c) var(--tint), transparent); border:1px solid color-mix(in srgb, var(--c) 45%, transparent); }
|
||||
.pill .v { font-size:24px; font-weight:800; color:var(--c); line-height:1.05; white-space:nowrap; }
|
||||
.pill .v small { font-size:13px; font-weight:700; margin-left:2px; }
|
||||
.pill .v.word { font-size:17px; }
|
||||
.pill .l { font-size:12px; font-weight:700; color:var(--c); opacity:.9; white-space:nowrap; text-transform:uppercase; letter-spacing:.4px; }
|
||||
.trend { font-weight:800; font-size:13px; margin-left:8px; vertical-align:3px; letter-spacing:0; } .trend.up { color:var(--red); } .trend.down { color:var(--green); }
|
||||
|
||||
.warn { color:var(--red) !important; font-weight:700; } .mid { color:var(--yellow) !important; font-weight:700; } .okc { color:var(--green) !important; font-weight:700; }
|
||||
.soft { color:var(--blue) !important; font-weight:600; }
|
||||
.tag-int { display:inline-block; background:var(--red); color:#fff; font-size:11px; font-weight:800; border-radius:5px; padding:1px 6px; margin-left:6px; letter-spacing:.5px; vertical-align:1px; }
|
||||
|
||||
/* Pastille du dernier pointage : bleu / jaune / rouge (clignote) */
|
||||
.ping-dot { display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:7px; vertical-align:0; cursor:help; }
|
||||
.ping-dot.ping-blue { background:var(--blue); } .ping-dot.ping-yellow { background:var(--yellow); }
|
||||
.ping-dot.ping-red { background:var(--red); animation:blink 1.2s ease-in-out infinite; }
|
||||
.ping-txt.ping-blue { color:var(--blue) !important; } .ping-txt.ping-yellow { color:var(--yellow) !important; font-weight:700; } .ping-txt.ping-red { color:var(--red) !important; font-weight:800; }
|
||||
@keyframes blink { 50% { opacity:.3; } }
|
||||
|
||||
.del { border:0; background:transparent; color:var(--faint); width:30px; height:30px; border-radius:9px; cursor:pointer; font-size:15px; }
|
||||
.del:hover { color:#fff; background:var(--red); }
|
||||
|
||||
/* Cartes d'accueil (connexion, liste vide) */
|
||||
.empty { margin:auto; text-align:center; max-width:520px; background:var(--panel); border:1px solid var(--line); border-radius:18px; padding:28px 32px; box-shadow:var(--shadow); }
|
||||
|
||||
.empty h2 { margin:0 0 6px; font-size:21px; } .empty p { margin:0 0 16px; color:var(--muted); line-height:1.5; }
|
||||
|
||||
/* ===================== Pied ===================== */
|
||||
.foot { display:flex; justify-content:space-between; align-items:center; gap:16px; color:var(--faint); font-size:12.5px; }
|
||||
.ticker { background:transparent; border:0; display:flex; align-items:center; gap:10px; cursor:pointer; min-width:0; text-align:left; padding:3px 0; }
|
||||
.ticker .tag { background:var(--panel); border:1px solid var(--line); border-radius:6px; padding:1px 8px; font-size:11px; text-transform:uppercase; letter-spacing:.7px; font-weight:700; color:var(--muted); flex:none; }
|
||||
.ticker #ticker { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; color:var(--text); font-weight:600; }
|
||||
.legal { white-space:nowrap; }
|
||||
|
||||
/* ===================== Fenêtres flottantes ===================== */
|
||||
.pop { position:absolute; z-index:20; background:var(--panel); border:1px solid var(--line); border-radius:16px; box-shadow:var(--shadow); padding:16px 18px; }
|
||||
.pop[hidden] { display:none; }
|
||||
.pop h3 { margin:0 0 6px; font-size:16px; }
|
||||
.pop h4 { margin:16px 0 6px; font-size:11.5px; text-transform:uppercase; letter-spacing:1px; color:var(--faint); }
|
||||
#alertsPop { left:20px; bottom:42px; width:min(600px,calc(100vw - 40px)); max-height:55vh; overflow:auto; }
|
||||
#log div { padding:7px 0; border-bottom:1px dashed var(--line); font-size:14px; }
|
||||
#log time { color:var(--muted); margin-right:8px; font-variant-numeric:tabular-nums; }
|
||||
.settings { top:76px; right:20px; width:min(460px,calc(100vw - 40px)); max-height:calc(100vh - 96px); overflow:auto; }
|
||||
.row-set { display:flex; align-items:center; justify-content:space-between; gap:10px; padding:4px 0; }
|
||||
.sw { display:flex; align-items:center; gap:10px; padding:5px 0; cursor:pointer; flex:1; font-size:14px; }
|
||||
.sw input[type=checkbox] { width:17px; height:17px; accent-color:var(--accent); flex:none; }
|
||||
.ev { display:flex; align-items:center; gap:6px; }
|
||||
.test { background:var(--panel2); border:1px solid var(--line); border-radius:8px; width:30px; height:28px; cursor:pointer; font-size:11px; }
|
||||
.test:hover { border-color:var(--accent); }
|
||||
.num { width:54px; background:var(--panel2); border:1px solid var(--line); border-radius:7px; padding:2px 6px; text-align:center; }
|
||||
.thr { display:flex; gap:16px; flex-wrap:wrap; font-size:14px; padding:3px 0; } .thr label { display:flex; align-items:center; gap:6px; }
|
||||
.thr.indent { margin-left:27px; }
|
||||
.sq { display:inline-block; width:11px; height:11px; border-radius:3px; margin-right:2px; }
|
||||
.sq.y { background:var(--yellow); } .sq.r { background:var(--red); } .sq.b { background:var(--blue); }
|
||||
.seg { display:inline-flex; border:1px solid var(--line); border-radius:9px; overflow:hidden; }
|
||||
.seg button { border:0; background:var(--panel2); padding:5px 12px; cursor:pointer; font-size:13px; font-weight:600; }
|
||||
.seg button + button { border-left:1px solid var(--line); }
|
||||
.seg button.on { background:var(--accent); color:var(--accent-ink); }
|
||||
|
||||
/* ===================== Debug ===================== */
|
||||
.debug { position:fixed; z-index:15; left:0; right:0; bottom:0; height:var(--dbg-h); background:var(--panel); border-top:1px solid var(--line); box-shadow:var(--shadow);
|
||||
display:grid; grid-template-columns:minmax(300px,440px) 1fr; grid-template-rows:auto minmax(0,1fr); gap:8px 12px; padding:10px 20px 12px; --dbg-h:min(38vh,340px); }
|
||||
.debug[hidden] { display:none; }
|
||||
.debug-head { grid-column:1 / -1; display:flex; align-items:center; gap:8px; } .debug-head .sp { flex:1; }
|
||||
.sw.small { font-size:12.5px; flex:none; padding:0; gap:6px; color:var(--muted); }
|
||||
.kvs { display:grid; grid-template-columns:auto 1fr; gap:3px 12px; font-size:12.5px; background:var(--panel2); border:1px solid var(--line); border-radius:10px; padding:8px 10px; overflow:auto; align-content:start; }
|
||||
.kvs span { color:var(--muted); } .kvs b { font-weight:600; word-break:break-word; font-variant-numeric:tabular-nums; } .kvs .bad { color:var(--red); }
|
||||
.debug-log { min-height:0; overflow:auto; font:12px/1.45 ui-monospace, Consolas, monospace; background:var(--bg); border:1px solid var(--line); border-radius:10px; padding:6px 8px; }
|
||||
.debug-log div { padding:1px 0; white-space:pre-wrap; word-break:break-word; }
|
||||
.debug-log .t { color:var(--muted); margin-right:6px; }
|
||||
.debug-log .warn { color:var(--yellow); } .debug-log .error { color:var(--red); font-weight:600; }
|
||||
.debug-log .d { color:var(--muted); }
|
||||
body.debug-on .app { padding-bottom:calc(min(38vh,340px) + 10px); }
|
||||
|
||||
/* ===================== Écrans plus petits ===================== */
|
||||
@media (max-width:1380px) {
|
||||
.board { --cols:6px 128px 100px 132px minmax(130px,1.1fr) minmax(150px,1.2fr) minmax(130px,1fr) 92px 112px 28px; }
|
||||
.cols, .row { gap:12px; }
|
||||
.tile span { display:none; } .tile { min-width:62px; }
|
||||
.partner .pb { display:none; }
|
||||
.cell .m { font-size:15px; } .pill .v { font-size:21px; }
|
||||
}
|
||||
@media (max-width:1050px) {
|
||||
body { overflow:auto; } .app { height:auto; min-height:100vh; }
|
||||
.top { grid-template-columns:1fr; gap:10px; } .live { justify-self:stretch; } .actions { justify-self:start; flex-wrap:wrap; }
|
||||
.bar { grid-template-columns:1fr; } .tiles { flex-wrap:wrap; }
|
||||
.cols.head { display:none; } .rows { overflow:visible; }
|
||||
.row { flex:none; max-height:none; grid-template-columns:6px 120px 1fr 30px; grid-template-areas:"b s n x" "b c c x" "b r r x" "b p p x" "b q q x"; row-gap:4px; padding:10px 8px 10px 0; }
|
||||
.row > .bar-c { grid-area:b; } .row > .c-stat { grid-area:s; } .row > .c-num { grid-area:n; } .row > .del { grid-area:x; }
|
||||
.row > .c-route { grid-area:r; } .row > .c-compo { grid-area:c; } .row > .c-pos { grid-area:p; } .row > .c-next { grid-area:q; }
|
||||
.row > .c-dep, .row > .c-arr { display:none; }
|
||||
.debug { grid-template-columns:1fr; grid-template-rows:auto auto minmax(0,1fr); --dbg-h:50vh; } body.debug-on .app { padding-bottom:calc(50vh + 10px); }
|
||||
}
|
||||
|
||||
/* ===================== Écrans peu hauts (portables 768–900 px) : mode compact automatique ===================== */
|
||||
@media (max-height:900px) and (min-width:1051px) {
|
||||
.app { gap:8px; padding-top:10px; }
|
||||
.logo-tile:not(.big) { width:44px; height:44px; border-radius:12px; } .logo-tile:not(.big) img { width:40px; height:40px; } .brand-name { font-size:25px; }
|
||||
.live { padding:5px 20px 6px; } .live-time { font-size:25px; } .live-sub { font-size:12px; }
|
||||
.board, .rows { gap:5px; }
|
||||
.row { min-height:46px; border-radius:11px; }
|
||||
.pill { min-height:38px; padding:3px 10px; } .pill .v { font-size:19px; } .pill .v.word { font-size:15px; } .pill .l { font-size:10.5px; }
|
||||
.n { font-size:18px; } .cell .m { font-size:14.5px; } .cell .s { font-size:12.5px; margin-top:0; }
|
||||
.tile { padding:4px 12px; } .tile b { font-size:20px; }
|
||||
.editor input { font-size:14px; }
|
||||
}
|
||||
|
||||
/* ===================== v1.5 : lignes cliquables, croix en 2 clics ===================== */
|
||||
.row { position:relative; cursor:pointer; }
|
||||
.row.sel { border-color:var(--accent); box-shadow:0 0 0 1px var(--accent) inset; }
|
||||
.tis { color:inherit; text-decoration:none; cursor:pointer; border-bottom:2px dotted color-mix(in srgb, var(--text) 35%, transparent); }
|
||||
.tis:hover { color:var(--accent); border-bottom-color:var(--accent); }
|
||||
.note-ic { font-size:14px; margin-left:6px; cursor:help; vertical-align:2px; }
|
||||
.del.confirm { position:absolute; right:8px; top:50%; transform:translateY(-50%); width:auto; height:34px; padding:0 14px; z-index:3;
|
||||
background:var(--red); color:#fff; font-weight:800; font-size:13px; border-radius:10px; box-shadow:0 4px 14px rgba(0,0,0,.35); animation:pop .15s ease-out; }
|
||||
@keyframes pop { from { transform:translateY(-50%) scale(.85); } to { transform:translateY(-50%) scale(1); } }
|
||||
.c-num .t { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.btn.danger { background:var(--red); border-color:var(--red); color:#fff; }
|
||||
.small { font-size:12px; }
|
||||
.chip { display:inline-flex; align-items:center; gap:4px; background:var(--panel2); border:1px solid var(--line); border-radius:999px; padding:1px 9px; font-size:12px; font-weight:700; color:var(--text); text-transform:none; letter-spacing:0; }
|
||||
.chip.soft { color:var(--muted); font-weight:600; }
|
||||
|
||||
/* ===================== Fiche du train (volet droit) ===================== */
|
||||
.panel { position:fixed; z-index:22; top:0; right:0; bottom:0; width:min(460px,100vw); background:var(--panel); border-left:1px solid var(--line);
|
||||
box-shadow:var(--shadow); padding:16px 18px 20px; overflow:auto; animation:slide .18s ease-out; }
|
||||
.panel[hidden] { display:none; }
|
||||
@keyframes slide { from { transform:translateX(30px); opacity:.4; } to { transform:none; opacity:1; } }
|
||||
.p-head { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; margin-bottom:10px; }
|
||||
.p-num { font:900 24px/1.1 "Arial Black", "Segoe UI Black", sans-serif; letter-spacing:.5px; }
|
||||
.p-status { display:flex; gap:14px; align-items:center; background:var(--panel2); border:1px solid var(--line); border-left:5px solid var(--c); border-radius:12px; padding:10px 12px; }
|
||||
.p-status .pill { min-width:120px; }
|
||||
.p-route { display:flex; flex-direction:column; min-width:0; } .p-route b { font-size:16px; } .p-route span { color:var(--muted); }
|
||||
.p-reason { background:color-mix(in srgb, var(--blue) var(--tint), var(--panel)); border:1px solid color-mix(in srgb, var(--blue) 45%, var(--line)); border-radius:10px; padding:8px 12px; margin:10px 0 0; font-size:13.5px; }
|
||||
.p-actions { display:flex; gap:8px; margin:12px 0 4px; flex-wrap:wrap; }
|
||||
.panel h4 { margin:16px 0 6px; font-size:11.5px; text-transform:uppercase; letter-spacing:1px; color:var(--faint); display:flex; align-items:center; gap:8px; }
|
||||
.p-kv { font-size:13.5px; }
|
||||
.alts { display:flex; flex-wrap:wrap; gap:6px; }
|
||||
.alt { background:var(--panel2); border:1px solid var(--line); border-radius:9px; padding:5px 10px; cursor:pointer; text-align:left; font-weight:700; font-size:13px; }
|
||||
.alt small { display:block; font-weight:500; color:var(--muted); font-size:11px; }
|
||||
.alt:hover { border-color:var(--accent); } .alt.on { border-color:var(--accent); background:color-mix(in srgb, var(--accent) var(--tint), var(--panel)); }
|
||||
.p-day { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-top:8px; }
|
||||
.num.wide { width:auto; }
|
||||
.causes { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:6px; }
|
||||
.causes li { background:var(--panel2); border:1px solid var(--line); border-radius:9px; padding:6px 10px; font-size:13.5px; }
|
||||
.causes li small { display:block; color:var(--muted); font-size:12px; }
|
||||
.note { width:100%; background:var(--panel2); border:1px solid var(--line); border-radius:10px; padding:8px 10px; font:inherit; font-size:14px; resize:vertical; color:var(--text); }
|
||||
.note:focus, .field:focus { outline:2px solid var(--accent); outline-offset:-1px; }
|
||||
|
||||
/* ===================== Fenêtres (listes, relève) ===================== */
|
||||
.modal { position:fixed; inset:0; z-index:30; background:rgba(5,10,20,.55); display:grid; place-items:center; padding:20px; }
|
||||
.modal[hidden] { display:none; }
|
||||
.modal-box { background:var(--panel); border:1px solid var(--line); border-radius:18px; box-shadow:var(--shadow); padding:18px 20px; width:min(560px,100%); max-height:calc(100vh - 40px); overflow:auto; }
|
||||
.modal-box.wide { width:min(1000px,100%); }
|
||||
.modal-head { display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; } .modal-head h3 { margin:0; font-size:18px; }
|
||||
.modal-foot { display:flex; gap:8px; align-items:center; margin-top:12px; flex-wrap:wrap; }
|
||||
.lists-grid { display:grid; grid-template-columns:minmax(260px,1fr) 1.3fr; gap:18px; }
|
||||
.lists-col h4, .lists-edit h4 { margin:10px 0 6px; font-size:11.5px; text-transform:uppercase; letter-spacing:1px; color:var(--faint); }
|
||||
.li { display:flex; justify-content:space-between; align-items:center; gap:8px; padding:8px 10px; border:1px solid var(--line); border-radius:11px; margin-bottom:6px; background:var(--panel2); }
|
||||
.li small { display:block; color:var(--muted); font-size:12px; } .li.on { border-color:var(--accent); } .li.editing { box-shadow:0 0 0 2px var(--accent) inset; }
|
||||
.li-act { display:flex; gap:5px; align-items:center; flex-wrap:wrap; justify-content:flex-end; }
|
||||
.lists-edit { border-left:1px solid var(--line); padding-left:18px; display:flex; flex-direction:column; gap:6px; }
|
||||
.field { width:100%; background:var(--panel2); border:1px solid var(--line); border-radius:10px; padding:8px 12px; font:inherit; color:var(--text); }
|
||||
.chips { display:flex; flex-wrap:wrap; gap:6px; min-height:28px; }
|
||||
.chip.co button { border:0; background:none; color:var(--muted); cursor:pointer; font-size:15px; padding:0 0 0 2px; line-height:1; }
|
||||
.chip.co button:hover { color:var(--red); }
|
||||
.sugg { display:flex; flex-direction:column; gap:3px; max-height:220px; overflow:auto; }
|
||||
.sg { display:flex; justify-content:space-between; gap:10px; text-align:left; background:var(--panel2); border:1px solid var(--line); border-radius:8px; padding:5px 10px; cursor:pointer; font-size:13px; }
|
||||
.sg span { color:var(--muted); white-space:nowrap; } .sg:hover { border-color:var(--accent); } .sg.all { justify-content:center; font-weight:700; }
|
||||
.report { background:var(--bg); border:1px solid var(--line); border-radius:12px; padding:12px 14px; font:12.5px/1.5 ui-monospace, Consolas, monospace; white-space:pre-wrap; max-height:52vh; overflow:auto; margin:10px 0 0; }
|
||||
@media (max-width:820px) { .lists-grid { grid-template-columns:1fr; } .lists-edit { border-left:0; padding-left:0; } }
|
||||
|
||||
/* ===================== v1.6 : composition « véhicules-longueur-poids » ===================== */
|
||||
.compo { color:var(--text); font-weight:800; letter-spacing:.3px; font-variant-numeric:tabular-nums; text-transform:none; }
|
||||
.compos { display:flex; flex-direction:column; gap:6px; }
|
||||
.cs { background:var(--panel2); border:1px solid var(--line); border-radius:9px; padding:6px 10px; display:grid; grid-template-columns:auto 1fr; column-gap:12px; align-items:baseline; font-size:13.5px; }
|
||||
.cs b { font-size:16px; font-variant-numeric:tabular-nums; grid-row:span 2; align-self:center; }
|
||||
.cs small { color:var(--muted); font-size:12px; }
|
||||
.cs.on { border-color:var(--accent); background:color-mix(in srgb, var(--accent) var(--tint), var(--panel)); }
|
||||
|
||||
/* ===================== v1.7 : trains arrivés (code couleur + section repliable) ===================== */
|
||||
.arr-sec { flex:none; display:flex; flex-direction:column; gap:6px; }
|
||||
#arrived:empty { display:none; }
|
||||
.arr-head { display:flex; align-items:center; gap:10px; width:100%; background:var(--panel); border:1px dashed var(--line); border-radius:12px;
|
||||
padding:9px 14px; cursor:pointer; text-align:left; font-size:14.5px; }
|
||||
.arr-head:hover { border-color:var(--muted); }
|
||||
.arr-sec.open .arr-head { border-style:solid; }
|
||||
.arr-head .chev { color:var(--muted); width:12px; }
|
||||
.arr-n { background:var(--panel2); border:1px solid var(--line); border-radius:999px; padding:0 9px; font-weight:800; font-variant-numeric:tabular-nums; }
|
||||
.arr-sum { margin-left:auto; display:flex; align-items:center; gap:6px; color:var(--muted); font-size:13px; font-weight:600; }
|
||||
.arr-sum i { width:10px; }
|
||||
.dotc { width:10px; height:10px; border-radius:50%; background:var(--c); display:inline-block; }
|
||||
.arr-list { display:flex; flex-direction:column; gap:6px; max-height:34vh; overflow:auto; padding-right:2px; }
|
||||
.row.arrived { flex:none; min-height:54px; }
|
||||
.row.arrived { background:color-mix(in srgb, var(--c) 6%, var(--panel)); }
|
||||
.row.arrived .bar-c { background:repeating-linear-gradient(-45deg, var(--c) 0 4px, transparent 4px 8px); }
|
||||
.row.arrived .pill { border-style:dashed; }
|
||||
.row.arrived .pill .v { font-size:20px; }
|
||||
.row.arrived .c-arr .m { color:var(--c); }
|
||||
.row.red.arrived { background:color-mix(in srgb, var(--red) 9%, var(--panel)); }
|
||||
|
||||
/* ===================== v1.7 : colonne Composition ===================== */
|
||||
.c-compo .m.compo { font-size:18px; font-weight:800; letter-spacing:.4px; font-variant-numeric:tabular-nums; }
|
||||
.c-compo .nocompo { color:var(--orange) !important; font-size:13.5px; font-weight:800; white-space:normal; line-height:1.15; }
|
||||
.c-compo .s { font-size:12px; }
|
||||
|
||||
.cols.head .hint { font-size:10px; letter-spacing:.3px; text-transform:none; font-weight:600; opacity:.8; }
|
||||
.actions .btn { white-space:nowrap; }
|
||||
@media (max-width:1380px) {
|
||||
.c-compo .m.compo { font-size:16px; letter-spacing:0; }
|
||||
.cols.head .hint { display:none; }
|
||||
.actions { gap:6px; } .actions .btn { padding:8px 11px; } .session { max-width:200px; }
|
||||
}
|
||||
|
||||
/* ===================== v1.8 : numéros liés, jours, stand-by ===================== */
|
||||
.nums { margin-top:2px; display:flex; gap:6px; align-items:center; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; min-width:0; }
|
||||
.otns { font-size:13.5px; font-weight:700; color:var(--text); opacity:.82; font-variant-numeric:tabular-nums; overflow:hidden; text-overflow:ellipsis; }
|
||||
.tag-vo { font-size:11px; font-weight:800; color:var(--blue); text-transform:uppercase; letter-spacing:.4px; }
|
||||
.pin { font-size:12px; font-weight:700; color:var(--muted); }
|
||||
.day { display:inline-block; margin-left:4px; padding:0 5px; border-radius:5px; font-size:10.5px; font-weight:800; line-height:15px; vertical-align:1px;
|
||||
background:color-mix(in srgb, var(--muted) 22%, transparent); color:var(--text); letter-spacing:.2px; cursor:help; }
|
||||
.day.fut { background:color-mix(in srgb, var(--blue) 28%, transparent); }
|
||||
.rel { font-size:12px; font-weight:700; color:var(--blue); margin-left:4px; white-space:nowrap; }
|
||||
.rel.late { color:var(--red); }
|
||||
.ping-dot.ping-stand { background:transparent; border:2px solid var(--muted); width:10px; height:10px; box-sizing:border-box; }
|
||||
.ping-txt.ping-stand { color:var(--muted) !important; font-weight:700; }
|
||||
.indent-p { margin:2px 0 6px 27px; }
|
||||
|
||||
/* ===================== v1.9 : recherche + signaler un bug ===================== */
|
||||
.toolbar2 { display:flex; align-items:center; gap:12px; min-height:36px; }
|
||||
.search { display:flex; align-items:center; gap:8px; flex:0 1 520px; background:var(--panel); border:1px solid var(--line); border-radius:11px; padding:0 10px; height:36px; cursor:text; }
|
||||
.search:focus-within { outline:2px solid var(--accent); outline-offset:-1px; }
|
||||
.search input { flex:1; min-width:0; border:0; background:transparent; font-size:14.5px; height:100%; outline:none; }
|
||||
.search input::-webkit-search-cancel-button { display:none; }
|
||||
.s-ic { opacity:.7; font-size:14px; }
|
||||
.q-x { border:0; background:var(--panel2); color:var(--muted); border-radius:7px; width:24px; height:24px; cursor:pointer; }
|
||||
.q-x:hover { color:#fff; background:var(--red); }
|
||||
.q-count { color:var(--muted); font-weight:700; font-size:13px; white-space:nowrap; }
|
||||
.toolbar2 .hiddenbar { margin-left:auto; }
|
||||
.foot-r { display:flex; align-items:center; gap:14px; }
|
||||
.bug { color:var(--muted); text-decoration:none; font-weight:700; border:1px solid var(--line); border-radius:8px; padding:2px 10px; white-space:nowrap; }
|
||||
.bug:hover { color:var(--text); border-color:var(--muted); }
|
||||
a.btn { text-decoration:none; display:inline-block; }
|
||||
@media (max-height:900px) and (min-width:1051px) { .toolbar2 { min-height:32px; } .search { height:32px; } }
|
||||
|
||||
/* ===================== v2.0 : imprimer l'horaire ===================== */
|
||||
.acts { display:flex; flex-direction:column; align-items:center; gap:2px; }
|
||||
.prt { border:1px solid var(--line); background:var(--panel2); color:var(--text); width:30px; height:26px; border-radius:8px; cursor:pointer; font-size:15px; line-height:1; }
|
||||
.prt:hover { color:#fff; background:var(--accent); }
|
||||
.pr-ctrl { display:flex; flex-direction:column; gap:8px; margin-bottom:10px; }
|
||||
.pr-range { display:flex; flex-wrap:wrap; align-items:center; gap:10px; }
|
||||
.pr-range label { display:flex; align-items:center; gap:6px; font-weight:700; }
|
||||
.pr-range select { background:var(--panel2); color:var(--text); border:1px solid var(--line); border-radius:8px; padding:5px 8px; font:inherit; max-width:340px; }
|
||||
.pr-opts { display:flex; flex-wrap:wrap; gap:4px 18px; }
|
||||
.pr-prev { max-height:52vh; overflow:auto; border:1px solid var(--line); border-radius:12px; }
|
||||
.tt { width:100%; border-collapse:collapse; font-size:13px; }
|
||||
.tt th { position:sticky; top:0; background:var(--panel2); color:var(--faint); text-align:left; font-size:11px; text-transform:uppercase; letter-spacing:.6px; padding:7px 10px; border-bottom:1px solid var(--line); }
|
||||
.tt td { padding:5px 10px; border-bottom:1px solid var(--line); font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.tt td:first-child { white-space:normal; }
|
||||
.tt tr.pass td { color:var(--muted); }
|
||||
.tt tr.origin td, .tt tr.dest td, .tt tr.stop td { font-weight:700; color:var(--text); }
|
||||
.tt tr.here td { background:color-mix(in srgb, var(--accent) var(--tint), transparent); }
|
||||
.here-tag { color:var(--accent); font-size:12px; }
|
||||
.tt i { color:var(--muted); }
|
||||
|
||||
/* ===================== v2.1 : impression modulable ===================== */
|
||||
.pr-groups { display:grid; grid-template-columns:repeat(3, minmax(0,1fr)); gap:6px 22px; background:var(--panel2); border:1px solid var(--line); border-radius:12px; padding:10px 14px; }
|
||||
.pr-groups h5 { margin:0 0 6px; font-size:11px; text-transform:uppercase; letter-spacing:.9px; color:var(--faint); }
|
||||
.pr-groups .sw.small { padding:3px 0; }
|
||||
.pr-groups .seg { margin-bottom:6px; }
|
||||
.pr-info { padding:10px 12px 8px; font-size:13px; line-height:1.55; border-bottom:1px solid var(--line); }
|
||||
.pr-info b { color:var(--text); }
|
||||
.tt td.dcol { font-weight:800; white-space:nowrap; color:var(--accent); }
|
||||
.tt tr.newday td { border-top:2px solid color-mix(in srgb, var(--accent) 55%, var(--line)); }
|
||||
.tt .dd { font-size:11px; font-weight:800; color:var(--blue); }
|
||||
@media (max-width:1050px) { .pr-groups { grid-template-columns:1fr; } }
|
||||
|
||||
/* ===================== v2.1.1 : la section « Arrivés » suit la liste (plus de vide au milieu) ===================== */
|
||||
/* la liste ne prend que la hauteur de ses lignes (et défile s'il y en a trop) ; « Arrivés » vient juste dessous */
|
||||
.board .rows { flex:0 1 auto; }
|
||||
.rows .row { flex:0 0 auto; }
|
||||
.rows:has(.empty) { flex:1 1 auto; }
|
||||
|
||||
/* v2.1.1 : dernière cause de retard (sous l'itinéraire) + détail dans la fiche */
|
||||
.row .c-route .cause { font-size:11.5px; line-height:1.25; color:var(--yellow); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }
|
||||
.row .c-route .cause b { font-weight:700; }
|
||||
.causes li.c-total { background:none; border:none; padding:0 2px; font-size:12.5px; color:var(--muted); }
|
||||
.causes li.last { border-color:var(--yellow); }
|
||||
.causes .c-code { display:inline-block; min-width:22px; padding:0 5px; border-radius:5px; background:var(--line); font-size:12px; font-weight:700; text-align:center; }
|
||||
@@ -0,0 +1,184 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>TTA – Train Time Accuracy</title>
|
||||
<link rel="icon" href="icon32.png">
|
||||
<link rel="stylesheet" href="dashboard.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
|
||||
<!-- ===== En-tête ===== -->
|
||||
<header class="top">
|
||||
<div class="brand">
|
||||
<div class="logo-tile"><img src="logo.svg" alt="TTA"></div>
|
||||
<div class="brand-txt">
|
||||
<div class="brand-name">TTA</div>
|
||||
<div class="brand-sub">TRAIN TIME ACCURACY</div>
|
||||
</div>
|
||||
<div class="partner" title="TTA powered by SIBELIT"><span class="pb">powered by</span><span class="sib">SIBELIT</span></div>
|
||||
</div>
|
||||
|
||||
<div class="live" id="live" title="Heure de la dernière réponse de TIS">
|
||||
<div class="live-label"><span class="dot"></span>Mise à jour TIS</div>
|
||||
<div class="live-time" id="updated">--:--:--</div>
|
||||
<div class="live-sub"><span id="age"></span><span id="countdown"></span></div>
|
||||
<div class="progress"><i id="progress"></i></div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="session" id="session" title="Connexion TIS"><span class="sdot"></span><span id="sessionTxt">TIS…</span></button>
|
||||
<button id="handoverBtn" class="btn" title="Rapport de relève : état complet des circulations, à copier ou imprimer">📋 Relève</button>
|
||||
<button id="force" class="btn" title="Interroger TIS maintenant (1 fois toutes les 10 s)">↻ Actualiser</button>
|
||||
<button id="soundBtn" class="btn icon" title="Activer / couper les sons">🔊</button>
|
||||
<button id="settingsBtn" class="btn icon" title="Réglages">⚙</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- ===== Liste + compteurs ===== -->
|
||||
<section class="bar">
|
||||
<form class="editor" id="editor" autocomplete="off">
|
||||
<select id="source" class="source" title="Quelle liste de trains suivre ?" aria-label="Liste de trains"></select>
|
||||
<button type="button" class="btn icon" id="listsBtn" title="Gérer mes listes (créer, modifier, supprimer)">✎</button>
|
||||
<input id="numbers" placeholder="Trains en plus (hors filtre) : 40146, 42920@27/10 …" aria-label="Numéros de train en plus" title="Numéros à suivre en plus de la liste, même hors filtre. Jour précis : 42920@27/10">
|
||||
<button class="btn primary" type="submit">Enregistrer</button>
|
||||
</form>
|
||||
<div class="tiles" id="summary"></div>
|
||||
</section>
|
||||
|
||||
<div id="banner"></div>
|
||||
<div class="toolbar2">
|
||||
<label class="search" title="Filtre la liste pendant que tu tapes (raccourci : /)">
|
||||
<span class="s-ic">🔍</span>
|
||||
<input id="q" type="search" placeholder="Rechercher : numéro, gare, prochain point, compo, note…" aria-label="Rechercher dans la liste" autocomplete="off" spellcheck="false">
|
||||
<button type="button" id="qClear" class="q-x" title="Effacer (Échap)" hidden>✕</button>
|
||||
</label>
|
||||
<span id="qCount" class="q-count"></span>
|
||||
<div class="hiddenbar" id="hiddenbar" hidden></div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Tableau ===== -->
|
||||
<section class="board">
|
||||
<div class="cols head" aria-hidden="true">
|
||||
<span></span><span>Statut</span><span>Train</span><span title="Composition : nombre de véhicules - longueur (m) - poids du train (t)">Compo <small class="hint">véh-m-t</small></span><span>Itinéraire</span><span>Position · dernier pointage</span><span>Prochain point</span><span>Départ</span><span>Arrivée</span><span></span>
|
||||
</div>
|
||||
<div class="rows" id="list"></div>
|
||||
<div id="arrived"></div>
|
||||
</section>
|
||||
|
||||
<footer class="foot">
|
||||
<button class="ticker" id="tickerBtn" title="Historique des alertes"><span class="tag">Alertes</span><span id="ticker">Aucune alerte pour le moment</span></button>
|
||||
<div class="foot-r">
|
||||
<a class="bug" id="bugBtn" href="#" title="Ouvre un nouveau mail (sujet « Signalement TIS ») pour décrire le problème">🐞 Signaler un bug</a>
|
||||
<div class="legal">TTA – Train Time Accuracy · By LinkAtPlug Co. © 2026 · <span id="ver"></span></div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- ===== Debug ===== -->
|
||||
<aside class="debug" id="debug" hidden>
|
||||
<div class="debug-head">
|
||||
<b>🐞 Debug</b>
|
||||
<label class="sw small"><input type="checkbox" id="dbgErrOnly"><span>Problèmes seulement</span></label>
|
||||
<span class="sp"></span>
|
||||
<button class="btn mini" id="dbgCopy">Copier</button>
|
||||
<button class="btn mini" id="dbgClear">Vider</button>
|
||||
<button class="btn mini" id="dbgClose" title="Masquer le debug">✕</button>
|
||||
</div>
|
||||
<div class="kvs" id="dbgStats"></div>
|
||||
<div class="debug-log" id="dbgLog"></div>
|
||||
</aside>
|
||||
|
||||
<!-- ===== Historique des alertes ===== -->
|
||||
<div class="pop" id="alertsPop" hidden>
|
||||
<h3>Historique des alertes</h3>
|
||||
<div id="log"></div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Réglages ===== -->
|
||||
<div class="pop settings" id="settingsPop" hidden>
|
||||
<h3>Réglages</h3>
|
||||
|
||||
<h4>Connexion TIS</h4>
|
||||
<div class="row-set"><span id="setSession">—</span><button class="btn mini" id="setLogin">Se connecter</button></div>
|
||||
<label class="sw"><input type="checkbox" id="pAutoLogin"><span>Reconnexion automatique quand la session expire</span></label>
|
||||
|
||||
<h4>Listes par entreprise</h4>
|
||||
<div class="row-set"><span class="muted">SIBELIT, Lineas, tes listes…</span><button class="btn mini" id="setLists">Gérer les listes</button></div>
|
||||
<div class="thr"><label>Départs dans les <input type="number" min="0" max="720" id="pUpcoming" class="num"> prochaines min</label></div>
|
||||
<div class="thr"><label>Garder les trains pas partis jusqu'à <input type="number" min="0" max="720" id="pLate" class="num"> min après l'heure prévue</label></div>
|
||||
<div class="row-set"><span class="muted">Liste de tes filtres enregistrés dans TIS</span><button class="btn mini" id="refreshFilters">Actualiser</button></div>
|
||||
|
||||
<h4>Affichage</h4>
|
||||
<div class="row-set"><span>Thème</span>
|
||||
<div class="seg" id="themeSeg"><button data-theme="auto">Auto</button><button data-theme="light">Clair</button><button data-theme="dark">Sombre</button></div>
|
||||
</div>
|
||||
<label class="sw"><input type="checkbox" id="pStaleOn"><span>Pastille du dernier pointage, selon l'heure attendue au prochain point (ou à l'arrivée) :</span></label>
|
||||
<div class="thr indent">
|
||||
<label><i class="sq y"></i>jaune si dépassée de plus de <input type="number" min="0" max="600" id="pYellow" class="num"> min</label>
|
||||
<label><i class="sq r"></i>rouge au-delà de <input type="number" min="1" max="600" id="pRed" class="num"> min</label>
|
||||
</div>
|
||||
<p class="muted small indent-p">Bleu = à l'heure · ⏸ gris = stand-by (arrêt prolongé, relais, attente de reprise : le prochain point n'est pas encore dû).</p>
|
||||
<div class="thr">
|
||||
<label><i class="sq y"></i>Retard jaune dès <input type="number" min="1" max="600" id="cYellow" class="num"> min</label>
|
||||
<label><i class="sq r"></i>rouge dès <input type="number" min="1" max="600" id="cRed" class="num"> min</label>
|
||||
</div>
|
||||
|
||||
<h4>Alertes</h4>
|
||||
<label class="sw"><input type="checkbox" id="pSound"><span>Sons</span></label>
|
||||
<label class="sw"><input type="checkbox" id="pDesktop"><span>Notifications Windows / Chrome</span></label>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="depart"><span>Départ du train</span></label><button class="test" data-test="depart" title="Écouter">▶</button></div>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="delay10"><span>Retard à partir de <input type="number" min="1" max="600" id="pDelay" class="num"> min</span></label><button class="test" data-test="delay10" title="Écouter">▶</button></div>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="etd5"><span>Pas parti : ETD dépassé de <input type="number" min="1" max="600" id="pEtd" class="num"> min</span></label><button class="test" data-test="etd5" title="Écouter">▶</button></div>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="red"><span>Retard important (rouge) / interruption</span></label><button class="test" data-test="red" title="Écouter">▶</button></div>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="arrive"><span>Arrivée</span></label><button class="test" data-test="arrive" title="Écouter">▶</button></div>
|
||||
<div class="ev"><label class="sw"><input type="checkbox" data-ev="session"><span>Connexion TIS requise</span></label><button class="test" data-test="session" title="Écouter">▶</button></div>
|
||||
|
||||
<h4>Diagnostic</h4>
|
||||
<label class="sw"><input type="checkbox" id="pDebug"><span>Mode debug (journal et état de l'extension)</span></label>
|
||||
<div class="row-set"><span class="muted">Un problème ? Un mail prérempli s'ouvre, tu décris et tu envoies.</span>
|
||||
<span><a class="btn mini" id="bugBtn2" href="#">🐞 Signaler un bug</a> <a class="btn mini" id="bugWeb" href="#" target="_blank" rel="noopener" title="Si ta messagerie est Outlook sur le web">Outlook Web</a></span></div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Fiche du train (volet à droite) ===== -->
|
||||
<aside class="panel" id="panel" hidden aria-label="Fiche du train"></aside>
|
||||
|
||||
<!-- ===== Gestion des listes ===== -->
|
||||
<div class="modal" id="listsModal" hidden>
|
||||
<div class="modal-box wide">
|
||||
<div class="modal-head"><h3>Mes listes de trains</h3><button class="btn mini" data-close>✕</button></div>
|
||||
<div class="lists-grid">
|
||||
<div class="lists-col" id="listsCol"></div>
|
||||
<div class="lists-edit" id="listEdit"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Imprimer l'horaire d'un train ===== -->
|
||||
<div class="modal" id="printModal" hidden>
|
||||
<div class="modal-box wide">
|
||||
<div class="modal-head"><h3 id="prTitle">🖨 Horaire</h3><button class="btn mini" data-close>✕</button></div>
|
||||
<div class="pr-ctrl" id="prCtrl"></div>
|
||||
<div class="pr-prev" id="prPrev"><p class="muted">Chargement de l'horaire depuis TIS…</p></div>
|
||||
<div class="modal-foot"><button class="btn primary" id="prPrint">🖨 Imprimer</button><button class="btn" id="prCopy">Copier le texte</button><span class="muted" id="prInfo"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Rapport de relève ===== -->
|
||||
<div class="modal" id="handoverModal" hidden>
|
||||
<div class="modal-box wide">
|
||||
<div class="modal-head"><h3>📋 Rapport de relève</h3><button class="btn mini" data-close>✕</button></div>
|
||||
<label class="muted" for="handoverNote">Remarques pour l'équipe suivante (gardées d'une relève à l'autre) :</label>
|
||||
<textarea id="handoverNote" class="note" rows="3" placeholder="Ex. : 42921 loco changée à Bettembourg, conducteur relevé à Thionville…"></textarea>
|
||||
<pre class="report" id="handoverText"></pre>
|
||||
<div class="modal-foot"><button class="btn primary" id="hoCopy">Copier</button><button class="btn" id="hoPrint">Imprimer</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="core.js"></script>
|
||||
<script src="sounds.js"></script>
|
||||
<script src="dashboard.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 239 KiB |
|
After Width: | Height: | Size: 239 KiB |
|
After Width: | Height: | Size: 238 KiB |
|
After Width: | Height: | Size: 300 KiB |
|
After Width: | Height: | Size: 285 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 9.8 KiB |
|
After Width: | Height: | Size: 794 B |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||
<!-- TTA – version simplifiée pour les petites tailles (16–32 px) : cadran épais, train, flèche -->
|
||||
<path d="M118 226 A100 100 0 0 1 118 30" fill="none" stroke="#14305E" stroke-width="34" stroke-linecap="round"/>
|
||||
<path d="M146 31.6 A100 100 0 0 1 146 224.4" fill="none" stroke="#F4B400" stroke-width="34" stroke-linecap="round"/>
|
||||
<g transform="translate(130 136) rotate(-18) translate(-130 -136)">
|
||||
<path d="M14 182 L196 170 L196 152 L250 178 L196 204 L196 188 Z" fill="#14305E"/>
|
||||
<path d="M56 106 L178 106 Q214 108 232 144 L234 160 L56 160 Z" fill="#C9CED6" stroke="#14305E" stroke-width="10" stroke-linejoin="round"/>
|
||||
<path d="M170 106 L178 106 Q214 108 232 144 L234 160 L170 160 Z" fill="#F4B400" stroke="#14305E" stroke-width="10" stroke-linejoin="round"/>
|
||||
<path d="M182 118 Q204 120 218 140 L184 140 Z" fill="#14305E"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 957 B |
@@ -0,0 +1,79 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||
<!-- TTA – Train Time Accuracy : cadran bleu/jaune, locomotive lancée, flèche.
|
||||
Palette : bleu foncé #14305E, jaune #F4B400, gris #C9CED6, blanc. -->
|
||||
<defs>
|
||||
<linearGradient id="tta-body" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#F6F8FB"/>
|
||||
<stop offset=".5" stop-color="#D3D8E0"/>
|
||||
<stop offset="1" stop-color="#8F99A8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="tta-nose" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#FFD54F"/>
|
||||
<stop offset="1" stop-color="#E6A400"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- cadran : moitié gauche bleu foncé, moitié droite jaune -->
|
||||
<path d="M121.6 219.8 A92 92 0 0 1 121.6 36.2" fill="none" stroke="#14305E" stroke-width="17" stroke-linecap="round"/>
|
||||
<path d="M144 37.4 A92 92 0 0 1 144 218.6" fill="none" stroke="#F4B400" stroke-width="17" stroke-linecap="round"/>
|
||||
|
||||
<!-- graduations -->
|
||||
<g stroke="#14305E" stroke-linecap="round">
|
||||
<g stroke-width="6">
|
||||
<line x1="128" y1="52" x2="128" y2="65"/>
|
||||
<line x1="52" y1="128" x2="65" y2="128"/>
|
||||
<line x1="128" y1="204" x2="128" y2="191"/>
|
||||
</g>
|
||||
<g stroke-width="4">
|
||||
<line x1="166" y1="62" x2="162" y2="69"/>
|
||||
<line x1="194" y1="90" x2="187" y2="94"/>
|
||||
<line x1="166" y1="194" x2="162" y2="187"/>
|
||||
<line x1="90" y1="194" x2="94" y2="187"/>
|
||||
<line x1="62" y1="166" x2="69" y2="162"/>
|
||||
<line x1="62" y1="90" x2="69" y2="94"/>
|
||||
<line x1="90" y1="62" x2="94" y2="69"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- aiguilles en boussole -->
|
||||
<path d="M128 60 L134 116 L128 128 L122 116 Z" fill="#14305E"/>
|
||||
<path d="M78 100 L123 119 L124 130 L115 125 Z" fill="#14305E"/>
|
||||
|
||||
<!-- locomotive + flèche, lancées vers le haut à droite -->
|
||||
<g transform="translate(134 150) rotate(-16) scale(.86) translate(-128 -148)">
|
||||
<!-- flèche sous le train -->
|
||||
<path d="M6 192 L200 180 L200 168 L246 186 L200 204 L200 193 Z" fill="#14305E"/>
|
||||
<!-- traînées de vitesse -->
|
||||
<path d="M0 136 L70 128 L70 134 Z" fill="#F4B400"/>
|
||||
<path d="M6 150 L70 141 L70 148 Z" fill="#14305E"/>
|
||||
<path d="M18 165 L70 157 L70 162 Z" fill="#F4B400"/>
|
||||
<path d="M30 178 L72 171 L72 175 Z" fill="#14305E"/>
|
||||
<!-- caisse profilée (arrière gris, nez jaune) -->
|
||||
<path d="M64 114 Q64 108 70 108 L184 108 Q212 110 230 136 Q238 148 236 164 L64 164 Z" fill="url(#tta-body)" stroke="#14305E" stroke-width="3.5" stroke-linejoin="round"/>
|
||||
<path d="M178 108 L184 108 Q212 110 230 136 Q238 148 236 164 L178 164 Z" fill="url(#tta-nose)" stroke="#14305E" stroke-width="3.5" stroke-linejoin="round"/>
|
||||
<!-- pare-brise -->
|
||||
<path d="M188 115 Q206 117 221 136 L190 136 Z" fill="#14305E"/>
|
||||
<path d="M192 119 Q204 121 212 129 L194 129 Z" fill="#3E5F99" opacity=".8"/>
|
||||
<!-- bande jaune + fenêtres -->
|
||||
<rect x="66" y="148" width="114" height="5" fill="#F4B400"/>
|
||||
<g fill="#14305E">
|
||||
<rect x="78" y="122" width="16" height="11" rx="2.5"/>
|
||||
<rect x="100" y="122" width="16" height="11" rx="2.5"/>
|
||||
<rect x="122" y="122" width="16" height="11" rx="2.5"/>
|
||||
<rect x="144" y="122" width="16" height="11" rx="2.5"/>
|
||||
</g>
|
||||
<line x1="168" y1="116" x2="168" y2="158" stroke="#14305E" stroke-width="3"/>
|
||||
<!-- phare -->
|
||||
<path d="M222 152 L232 152 L231 158 L222 158 Z" fill="#FFFFFF" stroke="#14305E" stroke-width="2"/>
|
||||
<!-- châssis + bogies -->
|
||||
<rect x="68" y="163" width="160" height="7" rx="3" fill="#14305E"/>
|
||||
<g fill="#14305E">
|
||||
<rect x="80" y="168" width="40" height="7" rx="3"/>
|
||||
<rect x="176" y="168" width="40" height="7" rx="3"/>
|
||||
</g>
|
||||
<g fill="#C9CED6" stroke="#14305E" stroke-width="2.5">
|
||||
<circle cx="88" cy="176" r="5"/><circle cx="112" cy="176" r="5"/>
|
||||
<circle cx="184" cy="176" r="5"/><circle cx="208" cy="176" r="5"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "TTA - Train Time Accuracy",
|
||||
"version": "2.1.1",
|
||||
"description": "TTA - Train Time Accuracy, powered by SIBELIT (By LinkAtPlug Co.) : suivi temps réel des trains TIS - retards, position, prochain point, alertes. Connexion TIS intégrée, filtre SIBELIT prêt à l'emploi.",
|
||||
"permissions": ["storage", "alarms", "notifications", "scripting", "tabs", "offscreen"],
|
||||
"host_permissions": ["https://tis-prod.rne.eu/*"],
|
||||
"background": { "service_worker": "background.js" },
|
||||
"action": {
|
||||
"default_title": "TTA - Train Time Accuracy",
|
||||
"default_icon": { "16": "icon16.png", "32": "icon32.png", "48": "icon48.png", "128": "icon128.png" }
|
||||
},
|
||||
"icons": { "16": "icon16.png", "32": "icon32.png", "48": "icon48.png", "128": "icon128.png" }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>TTA audio</title>
|
||||
<script src="sounds.js"></script>
|
||||
<script src="offscreen.js"></script>
|
||||
@@ -0,0 +1,4 @@
|
||||
// Document caché : joue les sonneries d'alerte même quand la page de suivi est fermée.
|
||||
chrome.runtime.onMessage.addListener(msg => {
|
||||
if (msg && msg.target === 'offscreen' && msg.type === 'play') ttaPlay(msg.kind);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// Sonneries (Web Audio, aucun fichier audio). Utilisé par la page de suivi (aperçu) et par offscreen.html (alertes).
|
||||
// [fréquence Hz, durée s] ; fréquence 0 = silence.
|
||||
const TTA_TONES = {
|
||||
depart: [[523, .12], [784, .22]], // montée douce : le train est parti
|
||||
delay10: [[660, .16], [0, .07], [660, .16]], // deux bips : retard
|
||||
etd5: [[880, .11], [0, .05], [880, .11], [0, .05], [880, .11]], // trois bips vifs : pas parti à l'heure
|
||||
red: [[392, .30], [0, .06], [294, .45]], // grave et long : retard important
|
||||
arrive: [[784, .10], [988, .26]], // carillon léger
|
||||
session: [[523, .14], [0, .05], [392, .14], [0, .05], [262, .32]], // descente : session TIS expirée
|
||||
};
|
||||
|
||||
function ttaPlay(kind) {
|
||||
try {
|
||||
const seq = TTA_TONES[kind] || TTA_TONES.delay10;
|
||||
const AC = globalThis.AudioContext || globalThis.webkitAudioContext;
|
||||
const ctx = new AC();
|
||||
let t = ctx.currentTime + 0.02;
|
||||
for (const [f, d] of seq) {
|
||||
if (f > 0) {
|
||||
const o = ctx.createOscillator(), g = ctx.createGain();
|
||||
o.type = 'triangle'; o.frequency.value = f;
|
||||
g.gain.setValueAtTime(0.0001, t);
|
||||
g.gain.exponentialRampToValueAtTime(0.22, t + 0.015);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t + d);
|
||||
o.connect(g); g.connect(ctx.destination);
|
||||
o.start(t); o.stop(t + d + 0.02);
|
||||
}
|
||||
t += d;
|
||||
}
|
||||
setTimeout(() => ctx.close(), (t - ctx.currentTime) * 1000 + 300);
|
||||
} catch (e) { /* audio indisponible : on ignore */ }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Test v1.1 : couleur "pas parti", alertes départ / retard 10 / ETD +5, sons désactivables, journal debug.
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
const base = Date.now(), iso = ms => new Date(ms).toISOString();
|
||||
let clock = base; // horloge simulée
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
|
||||
const store = {}; const notifs = [], sounds = []; let handlers = {};
|
||||
const chrome = {
|
||||
storage: { local: { async get(keys) { keys = Array.isArray(keys) ? keys : [keys]; const o = {}; for (const k of keys) if (k in store) o[k] = JSON.parse(JSON.stringify(store[k])); return o; }, async remove(k) { delete store[k]; }, async set(o) { for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: { addListener() {} } },
|
||||
notifications: { create: (a, b) => notifs.push(b || a), onClicked: { addListener() {} }, clear() {} },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: { addListener() {} } }, windows: { update: async () => {}, create: async () => ({ id: 1 }), get: async () => { throw new Error('x'); }, remove: async () => {}, onRemoved: { addListener() {} } },
|
||||
scripting: {}, action: { onClicked: { addListener() {} }, setBadgeText(){}, setBadgeBackgroundColor(){}, setTitle(){} }, offscreen: { createDocument: async () => {} },
|
||||
runtime: { onInstalled: { addListener() {} }, onStartup: { addListener() {} }, getURL: p => p, getManifest: () => ({ version: 'test' }),
|
||||
getContexts: async () => [{}], sendMessage: async m => { if (m.target === 'offscreen') sounds.push(m.kind); }, onMessage: { addListener: f => handlers.msg = f } },
|
||||
};
|
||||
|
||||
// Scénario TIS : 111 en circulation, 222 pas parti (départ prévu dans 20 min), 333 en circulation.
|
||||
let S = {};
|
||||
const hdr = (id, o) => ({ header: Object.assign({ id, otn: id, type: 'FREIGHT', running: false, interrupted: false, archive: false,
|
||||
origin: { locationId: 1 }, current: { id: 900 + id, locationId: 2 }, destination: { locationId: 3, plannedTime: iso(clock + 6e6) } }, o) });
|
||||
async function fakeFetch(url, opts) {
|
||||
if (!opts || !opts.body) return { ok: false, status: 401, json: async () => null };
|
||||
const b = JSON.parse(opts.body); const n = b.filter.trainNumbers; const trains = [];
|
||||
if (b.withSectionsAndDetails) {
|
||||
for (const x of n) trains.push({ header: { id: Number(x) }, sections: [{ trainDetails: [
|
||||
{ id: 900 + Number(x), locationId: 2, currentLocation: true, actualTime: iso(clock - 1e5) },
|
||||
{ id: 5, locationId: 4, plannedTime: iso(clock + 6e5), calculatedTime: iso(clock + 7e5), plannedStatus: 'RUN_THROUGH' }] }] });
|
||||
} else {
|
||||
if (n.includes('111')) trains.push(hdr(111, { running: true, origin: { locationId: 1, plannedTime: iso(clock - 3e6), actualTime: iso(clock - 2.9e6) }, current: { id: 1011, locationId: 2, actualTime: iso(clock - 6e4), runningDeltaForDisplay: S.d111 } }));
|
||||
if (n.includes('222')) {
|
||||
if (S.departed222) trains.push(hdr(222, { running: true, origin: { locationId: 1, plannedTime: iso(S.dep222), actualTime: iso(clock - 6e4) }, current: { id: 1022, locationId: 2, actualTime: iso(clock - 3e4), runningDeltaForDisplay: 6 } }));
|
||||
else trains.push(hdr(222, { origin: { locationId: 1, plannedTime: iso(S.dep222) } }));
|
||||
}
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: { locations: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, { id: 4, name: 'D' }], trains } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout, navigator: {},
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
|
||||
const send = msg => new Promise(res => handlers.msg(msg, null, res));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const cycle = async () => { store.lastRun = 0; await send({ type: 'force' }); await new Promise(r => setTimeout(r, 30)); };
|
||||
const row = otn => store.data.rows.find(t => t.otn === otn);
|
||||
|
||||
(async () => {
|
||||
store.prefs = { source: 'list', sourceChosen: true };
|
||||
S = { d111: 2, dep222: base + 20 * 60e3, departed222: false };
|
||||
await send({ type: 'setTrains', numbers: '111 222' }); await new Promise(r => setTimeout(r, 30));
|
||||
ok(row('111').color === 'green', '111 en circulation à l\'heure = vert');
|
||||
ok(row('222').color === 'blue' && row('222').phase === 'waiting', '222 pas parti, à l\'heure = BLEU (pas vert)');
|
||||
ok(row('222').startsInMin === 20, '222 : départ dans 20 min');
|
||||
ok(notifs.length === 0 && sounds.length === 0, 'aucune alerte au premier passage');
|
||||
|
||||
// +12 min : retard >= 10 pour 111
|
||||
S.d111 = 12; clock += 60e3; await cycle();
|
||||
ok(notifs.some(n => /111.*retard \+12/.test(n.title)), 'alerte retard +10 : ' + notifs.map(n => n.title));
|
||||
ok(sounds.includes('delay10'), 'son delay10 joué');
|
||||
ok(notifs.every(n => n.silent === true), 'notifications silencieuses (le son vient de TTA)');
|
||||
const n1 = notifs.length; clock += 60e3; await cycle();
|
||||
ok(notifs.length === n1, 'pas de ré-alerte tant que le retard reste >= 10');
|
||||
|
||||
// 222 : ETD dépassé de 6 min sans départ
|
||||
clock = S.dep222 + 6 * 60e3; await cycle();
|
||||
ok(row('222').etdLate === 6 && row('222').color === 'yellow', '222 ETD +6 min = jaune');
|
||||
ok(notifs.some(n => /222.*pas parti/.test(n.title)), 'alerte ETD +5 : ' + notifs.map(n => n.title).join(' | '));
|
||||
ok(sounds.includes('etd5'), 'son etd5 joué');
|
||||
|
||||
// 222 part
|
||||
S.departed222 = true; clock += 60e3; await cycle();
|
||||
ok(row('222').phase === 'running', '222 en circulation');
|
||||
ok(notifs.some(n => /222.*parti$/.test(n.title)), 'alerte départ');
|
||||
ok(sounds.includes('depart'), 'son départ joué');
|
||||
|
||||
// sons coupés + une alerte départ désactivée
|
||||
const snd = sounds.length; await chrome.storage.local.set({ prefs: { source: 'list', sourceChosen: true, sound: false, ev: { delay10: true } } });
|
||||
S.d111 = 3; clock += 60e3; await cycle(); S.d111 = 14; clock += 60e3; await cycle();
|
||||
ok(sounds.length === snd, 'son coupé : aucune sonnerie');
|
||||
ok(notifs.some(n => /111.*retard \+14/.test(n.title)), 'notification visuelle toujours présente');
|
||||
const kinds = store.debug.map(e => e.m).join('\n');
|
||||
ok(/son coupé dans les réglages/.test(kinds), 'journal debug : "son coupé" noté');
|
||||
ok(store.debug.length > 10 && store.stats.requests > 5, `journal debug (${store.debug.length} lignes) et stats (${store.stats.requests} requêtes)`);
|
||||
await send({ type: 'clearDebug' });
|
||||
ok(store.debug.length === 0, 'journal vidable');
|
||||
})();
|
||||
@@ -0,0 +1,78 @@
|
||||
// Test v1.2 : cache négatif du détail, tendance, alerte session, badge, prev conservé, ménage des noms de lieux, écritures groupées.
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
const base = Date.now(), iso = ms => new Date(ms).toISOString();
|
||||
let clock = base;
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
|
||||
const store = {}; const notifs = [], sounds = [], badge = {}; let handlers = {}; let writes = 0;
|
||||
const chrome = {
|
||||
storage: { local: { async get(keys) { keys = Array.isArray(keys) ? keys : [keys]; const o = {}; for (const k of keys) if (k in store) o[k] = JSON.parse(JSON.stringify(store[k])); return o; }, async remove(k) { delete store[k]; }, async set(o) { writes++; for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: { addListener() {} } },
|
||||
notifications: { create: (a, b) => notifs.push(b || a), onClicked: { addListener() {} }, clear() {} },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: { addListener() {} } }, windows: { update: async () => {}, create: async () => ({ id: 1 }), get: async () => { throw new Error('x'); }, remove: async () => {}, onRemoved: { addListener() {} } },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} },
|
||||
action: { onClicked: { addListener() {} }, setBadgeText: o => badge.text = o.text, setBadgeBackgroundColor: o => badge.color = o.color, setTitle: o => badge.title = o.title },
|
||||
runtime: { onInstalled: { addListener() {} }, onStartup: { addListener() {} }, getURL: p => p, getManifest: () => ({ version: 'test' }),
|
||||
getContexts: async () => [{}], sendMessage: async m => { if (m.target === 'offscreen') sounds.push(m.kind); }, onMessage: { addListener: f => handlers.msg = f } },
|
||||
};
|
||||
|
||||
let S = { d111: 2, auth: false, detailEmpty: true, extraLocs: 0 }; let detailCalls = 0;
|
||||
async function fakeFetch(url, opts) {
|
||||
if (!opts || !opts.body) return { ok: false, status: 401, json: async () => null };
|
||||
if (S.auth) return { ok: false, status: 401, json: async () => null };
|
||||
const b = JSON.parse(opts.body);
|
||||
const locations = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, { id: 4, name: 'D' }];
|
||||
for (let i = 0; i < S.extraLocs; i++) locations.push({ id: 1000 + i, name: 'X' + i });
|
||||
if (b.withSectionsAndDetails) { detailCalls++; return { ok: true, status: 200, json: async () => ({ data: { result: S.detailEmpty ? { locations: [] } : { locations, trains: [{ header: { id: 111 }, sections: [{ trainDetails: [{ id: 1011, locationId: 2, currentLocation: true, actualTime: iso(clock) }, { id: 5, locationId: 4, plannedTime: iso(clock + 6e5) }] }] }] } } }) }; }
|
||||
const trains = b.filter.trainNumbers.includes('111') ? [{ header: { id: 111, otn: 111, running: true, archive: false, origin: { locationId: 1, plannedTime: iso(clock - 3e6), actualTime: iso(clock - 2.9e6) }, current: { id: 1011, locationId: 2, actualTime: iso(clock - 6e4), runningDeltaForDisplay: S.d111 }, destination: { locationId: 3, plannedTime: iso(clock + 6e6) } } }] : [];
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: { locations, trains } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout,
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
const send = msg => new Promise(res => handlers.msg(msg, null, res));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const cycle = async () => { store.lastRun = 0; await send({ type: 'force' }); await new Promise(r => setTimeout(r, 30)); };
|
||||
|
||||
(async () => {
|
||||
store.prefs = { source: 'list', sourceChosen: true };
|
||||
S.extraLocs = 500;
|
||||
await send({ type: 'setTrains', numbers: '111' }); await new Promise(r => setTimeout(r, 30));
|
||||
ok(detailCalls === 1, 'détail demandé une fois (TIS ne renvoie rien)');
|
||||
ok(Object.keys(store.locNames).length <= 4, `noms de lieux élagués : ${Object.keys(store.locNames).length} gardés sur 504 reçus`);
|
||||
clock += 60e3; await cycle(); clock += 60e3; await cycle();
|
||||
ok(detailCalls === 1, 'pas de nouvelle demande de détail avant 3 min (cache négatif)');
|
||||
clock += 2 * 60e3; S.detailEmpty = false; await cycle();
|
||||
ok(detailCalls === 2, 'nouvel essai après 3 min');
|
||||
ok(store.data.rows[0].next && store.data.rows[0].next.name === 'D', 'prochain point obtenu au 2e essai');
|
||||
|
||||
// tendance
|
||||
S.d111 = 7; clock += 60e3; await cycle();
|
||||
ok(store.data.rows[0].trend === 5, 'tendance ▲ +5 détectée');
|
||||
clock += 60e3; await cycle();
|
||||
ok(store.data.rows[0].trend === 5, 'tendance conservée tant que le retard ne bouge pas');
|
||||
clock += 11 * 60e3; await cycle();
|
||||
ok(store.data.rows[0].trend == null, 'tendance effacée après 10 min');
|
||||
|
||||
// badge
|
||||
ok(badge.text === '1' && badge.color === '#e5b020', `badge jaune "1" (retard 7) : ${badge.text} ${badge.color}`);
|
||||
|
||||
// prev conservé quand on modifie la liste
|
||||
const prevKeys = Object.keys(store.prev).length;
|
||||
await send({ type: 'setTrains', numbers: '111 222' }); await new Promise(r => setTimeout(r, 30));
|
||||
ok(prevKeys > 0 && store.prev['111:111'], 'mémoire des états conservée après modification de la liste');
|
||||
|
||||
await chrome.storage.local.set({ prefs: { source: 'list', sourceChosen: true, autoLogin: false } }); // (la reconnexion auto est testée dans test-ext4)
|
||||
// session expirée : une seule alerte
|
||||
const n0 = notifs.length; S.auth = true; clock += 60e3; await cycle(); clock += 60e3; await cycle();
|
||||
ok(notifs.length === n0 + 1 && /connexion TIS requise/.test(notifs[notifs.length - 1].title), 'alerte "session expirée" émise une seule fois');
|
||||
ok(sounds.includes('session'), 'son session joué');
|
||||
ok(badge.text === '!', 'badge "!" quand la session est expirée');
|
||||
S.auth = false; clock += 60e3; await cycle();
|
||||
ok(store.data.error == null && badge.text !== '!', 'reprise normale après reconnexion');
|
||||
|
||||
// écritures groupées
|
||||
writes = 0; clock += 60e3; await cycle();
|
||||
ok(writes <= 3, `écritures de stockage par cycle : ${writes} (avant : 5 à 6)`);
|
||||
})();
|
||||
@@ -0,0 +1,95 @@
|
||||
// Test v1.3 : connexion TIS intégrée (fenêtre, détection, fermeture, reconnexion silencieuse, délai, clic notification).
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
let clock = Date.now(); const iso = ms => new Date(ms).toISOString();
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
|
||||
const store = {}, notifs = [], windows = {}, L = {};
|
||||
let nextWin = 10, loggedIn = true;
|
||||
const on = name => ({ addListener: f => (L[name] = L[name] || []).push(f) });
|
||||
const fire = async (name, ...a) => { for (const f of L[name] || []) await f(...a); };
|
||||
const chrome = {
|
||||
storage: { local: {
|
||||
async get(keys) { keys = Array.isArray(keys) ? keys : [keys]; const o = {}; for (const k of keys) if (k in store) o[k] = JSON.parse(JSON.stringify(store[k])); return o; },
|
||||
async set(o) { for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); },
|
||||
async remove(k) { delete store[k]; } } },
|
||||
alarms: { create: (n, o) => { store['_alarm_' + n] = o; }, clear: n => { delete store['_alarm_' + n]; }, onAlarm: on('alarm') },
|
||||
notifications: { create: (a, b) => notifs.push(b ? { id: a, ...b } : a), clear() {}, onClicked: on('notifClick') },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: on('tabUpd') },
|
||||
windows: {
|
||||
create: async o => { const id = nextWin++; windows[id] = o; return { id }; },
|
||||
get: async id => { if (!windows[id]) throw new Error('no window'); return { id }; },
|
||||
update: async (id, o) => { Object.assign(windows[id], o); },
|
||||
remove: async id => { delete windows[id]; },
|
||||
onRemoved: on('winRemoved') },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} },
|
||||
action: { onClicked: on('action'), setBadgeText() {}, setBadgeBackgroundColor() {}, setTitle() {} },
|
||||
runtime: { onInstalled: on('installed'), onStartup: on('startup'), getURL: p => p, getManifest: () => ({ version: 'test' }),
|
||||
getContexts: async () => [{}], sendMessage: async () => {}, onMessage: on('msg') },
|
||||
};
|
||||
async function fakeFetch(url, opts) {
|
||||
if (url.endsWith('/accounts/self')) return loggedIn ? { ok: true, status: 200, json: async () => ({ data: { firstName: 'Maxime', lastName: 'R.', email: 'x@y.z' } }) } : { ok: false, status: 401, json: async () => null };
|
||||
if (!loggedIn) return { ok: false, status: 401, json: async () => null };
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: { locations: [{ id: 1, name: 'A' }], trains: [{ header: { id: 7, otn: 777, running: true, archive: false, origin: { locationId: 1, plannedTime: iso(clock - 3e6), actualTime: iso(clock - 3e6) }, current: { id: 1, locationId: 1, actualTime: iso(clock - 6e4), runningDeltaForDisplay: 1 }, destination: { locationId: 1, plannedTime: iso(clock + 3e6) } } }] } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout: (f, ms) => setTimeout(f, Math.min(ms, 5)),
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
const send = msg => new Promise(res => L.msg[0](msg, null, res));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const wait = ms => new Promise(r => setTimeout(r, ms));
|
||||
const cycle = async () => { store.lastRun = 0; await send({ type: 'force' }); await wait(40); };
|
||||
|
||||
(async () => {
|
||||
store.prefs = { source: 'list', sourceChosen: true };
|
||||
await send({ type: 'setTrains', numbers: '777' }); await wait(40);
|
||||
ok(store.data.rows[0].otn === '777' && store.session && store.session.ok && store.session.name === 'Maxime R.', `connecté, nom affiché : "${store.session && store.session.name}" (l'email n'est pas gardé : ${!JSON.stringify(store.session).includes('@')})`);
|
||||
|
||||
// 1) La session expire → reconnexion silencieuse (fenêtre réduite), pas encore d'alerte
|
||||
loggedIn = false; clock += 60e3; await cycle();
|
||||
const w1 = store.loginWin;
|
||||
ok(w1 && w1.silent && windows[w1.id] && windows[w1.id].state === 'minimized', 'session expirée → fenêtre TIS RÉDUITE ouverte (reconnexion silencieuse)');
|
||||
ok(!notifs.some(n => /connexion TIS requise/.test(n.title)), 'pas encore d\'alerte pendant la tentative silencieuse');
|
||||
ok(store.session.ok === false, 'état « déconnecté » enregistré');
|
||||
clock += 60e3; await cycle();
|
||||
ok(Object.keys(windows).length === 1, 'pas de 2e fenêtre au cycle suivant');
|
||||
|
||||
// 2) Microsoft demande une action → délai dépassé → fenêtre fermée + alerte cliquable
|
||||
await fire('alarm', { name: 'loginTimeout' }); await wait(20);
|
||||
ok(!windows[w1.id] && !store.loginWin, 'délai dépassé : fenêtre silencieuse fermée');
|
||||
const al = notifs.find(n => /connexion TIS requise/.test(n.title));
|
||||
ok(al && String(al.id).startsWith('tta-login'), 'alerte « connexion TIS requise » avec clic → connexion');
|
||||
|
||||
// 3) Clic sur la notification → fenêtre de connexion VISIBLE
|
||||
await fire('notifClick', al.id); await wait(20);
|
||||
const w2 = store.loginWin;
|
||||
ok(w2 && !w2.silent && windows[w2.id].type === 'popup' && windows[w2.id].focused, 'clic → fenêtre de connexion visible (popup)');
|
||||
|
||||
// 4) Pages Microsoft : rien ne se passe ; retour sur TIS connecté → fermeture + reprise
|
||||
await fire('tabUpd', 1, { status: 'complete' }, { windowId: w2.id, url: 'https://login.microsoftonline.com/xyz' }); await wait(20);
|
||||
ok(store.loginWin, 'page Microsoft : on attend');
|
||||
loggedIn = true;
|
||||
await fire('tabUpd', 1, { status: 'complete' }, { windowId: w2.id, url: 'https://tis-prod.rne.eu/search' }); await wait(60);
|
||||
ok(!windows[w2.id] && !store.loginWin, 'retour sur TIS connecté → fenêtre fermée automatiquement');
|
||||
ok(store.data.error == null && store.session.ok, 'suivi repris, session OK');
|
||||
ok(notifs.some(n => /connecté à TIS/.test(n.title)), 'notification « connecté à TIS »');
|
||||
|
||||
// 5) Reconnexion silencieuse qui réussit toute seule (Microsoft se souvient)
|
||||
loggedIn = false; clock += 60e3; await cycle();
|
||||
const w3 = store.loginWin; loggedIn = true;
|
||||
await fire('tabUpd', 1, { url: 'https://tis-prod.rne.eu/' }, { windowId: w3.id, url: 'https://tis-prod.rne.eu/' }); await wait(60);
|
||||
ok(!windows[w3.id] && !store.loginWin && store.data.error == null, 'reconnexion silencieuse réussie : fenêtre fermée, suivi repris, sans rien faire');
|
||||
|
||||
// 6) Bouton « Se connecter » de la page + fermeture manuelle de la fenêtre
|
||||
await send({ type: 'login' }); const w4 = store.loginWin;
|
||||
ok(w4 && !w4.silent, 'bouton « Se connecter » → fenêtre visible');
|
||||
await send({ type: 'login' });
|
||||
ok(Object.keys(windows).length === 1, 'deuxième clic : pas de 2e fenêtre (on remet la même au premier plan)');
|
||||
delete windows[w4.id]; await fire('winRemoved', w4.id); await wait(40);
|
||||
ok(!store.loginWin, 'fenêtre fermée à la main : état nettoyé');
|
||||
|
||||
// 7) Reconnexion auto désactivée → alerte immédiate
|
||||
await chrome.storage.local.set({ prefs: { source: 'list', sourceChosen: true, autoLogin: false } });
|
||||
loggedIn = false; const n0 = notifs.length; clock += 60e3; await cycle();
|
||||
ok(!store.loginWin && notifs.length === n0 + 1, 'reconnexion auto désactivée : alerte immédiate, pas de fenêtre');
|
||||
})();
|
||||
@@ -0,0 +1,107 @@
|
||||
// Test v1.3 « Mes trains TIS » : filtre enregistré, en circulation + départs dans l'heure, trains en plus, masquage, détail limité.
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
let clock = Date.parse('2026-10-26T07:45:00+01:00'); const iso = ms => new Date(ms).toISOString();
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
const store = {}, notifs = [], L = {}, bodies = [];
|
||||
const on = n => ({ addListener: f => (L[n] = L[n] || []).push(f) });
|
||||
const chrome = {
|
||||
storage: { local: { async get(k) { k = Array.isArray(k) ? k : [k]; const o = {}; for (const x of k) if (x in store) o[x] = JSON.parse(JSON.stringify(store[x])); return o; },
|
||||
async set(o) { for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); }, async remove(k) { delete store[k]; } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: on('alarm') }, notifications: { create: (a, b) => notifs.push(b || a), clear() {}, onClicked: on('nc') },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: on('tu') },
|
||||
windows: { create: async () => ({ id: 1 }), get: async () => { throw new Error(); }, update: async () => {}, remove: async () => {}, onRemoved: on('wr') },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} },
|
||||
action: { onClicked: on('ac'), setBadgeText() {}, setBadgeBackgroundColor() {}, setTitle() {} },
|
||||
runtime: { onInstalled: on('i'), onStartup: on('st'), getURL: p => p, getManifest: () => ({ version: 't' }), getContexts: async () => [{}], sendMessage: async () => {}, onMessage: on('msg') },
|
||||
};
|
||||
const H = (id, otn, o) => ({ header: Object.assign({ id, otn, type: 'FREIGHT', running: false, archive: false, interrupted: false, origin: { locationId: 1 }, current: { id: id * 10, locationId: 2 }, destination: { locationId: 3, plannedTime: iso(clock + 5 * 3600e3) } }, o) });
|
||||
const RUNNING = [
|
||||
H(1, 45705, { running: true, origin: { locationId: 1, plannedTime: iso(clock - 3600e3), actualTime: iso(clock - 3500e3) }, current: { id: 10, locationId: 2, actualTime: iso(clock - 60e3), runningDeltaForDisplay: 3 } }),
|
||||
H(2, 40366, { running: true, origin: { locationId: 1, plannedTime: iso(clock - 7200e3), actualTime: iso(clock - 7000e3) }, current: { id: 20, locationId: 2, actualTime: iso(clock - 120e3), runningDeltaForDisplay: 18 } }),
|
||||
...[3, 4, 5, 6, 7].map(i => H(i, 40000 + i, { running: true, origin: { locationId: 1, plannedTime: iso(clock - 3600e3), actualTime: iso(clock - 3600e3) }, current: { id: i * 10, locationId: 2, actualTime: iso(clock - 60e3), runningDeltaForDisplay: 0 } })),
|
||||
];
|
||||
const DEPARTURES = [
|
||||
RUNNING[0], // déjà parti : doublon à ignorer
|
||||
H(8, 45708, { origin: { locationId: 1, plannedTime: iso(clock + 40 * 60e3) } }), // part dans 40 min
|
||||
H(9, 45710, { origin: { locationId: 1, plannedTime: iso(clock - 12 * 60e3) } }), // devait partir il y a 12 min : pas parti
|
||||
H(10, 45711, { origin: { locationId: 1, plannedTime: iso(clock - 50 * 60e3), actualTime: iso(clock - 45 * 60e3) }, destination: { locationId: 3, actualTime: iso(clock - 5 * 60e3) } }), // déjà arrivé
|
||||
];
|
||||
async function fakeFetch(url, opts) {
|
||||
if (url.includes('trainsearchfilter/self')) return { ok: true, status: 200, json: async () => ({ data: { trainSearchFilters: [{ id: 96463, name: 'Sib', isDefault: true,
|
||||
definition: { ruCodes: ['0087.08987', '0082.SIBEL'], onlyRunning: true, timeframe: 4, timeFramePast: 360, timeFrameFuture: 240, cttLine: false, realLine: true, splitLocations: false, maxNumberOfResults: 10000 } }] } }) };
|
||||
if (url.includes('accounts/self')) return { ok: true, status: 200, json: async () => ({ data: { firstName: 'M' } }) };
|
||||
const b = JSON.parse(opts.body); bodies.push(b);
|
||||
let trains;
|
||||
if (b.withSectionsAndDetails) trains = b.filter.trainNumbers.map(n => ({ header: { id: RUNNING.find(t => String(t.header.otn) === n).header.id }, sections: [{ trainDetails: [{ id: 1, locationId: 2, currentLocation: true, actualTime: iso(clock) }, { id: 2, locationId: 4, plannedTime: iso(clock + 6e5) }] }] }));
|
||||
else if (b.filter.trainNumbers) trains = [...(b.filter.trainNumbers.includes('45705') ? [RUNNING[0]] : []), ...(b.filter.trainNumbers.includes('12345') ? [H(99, 12345, { running: true, origin: { locationId: 1, plannedTime: iso(clock - 3600e3), actualTime: iso(clock - 3600e3) }, current: { id: 990, locationId: 2, actualTime: iso(clock - 60e3), runningDeltaForDisplay: 1 } })] : [])];
|
||||
else if (b.filter.onlyRunning) trains = RUNNING;
|
||||
else trains = DEPARTURES;
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: { locations: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, { id: 4, name: 'D' }], trains } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout: (f, ms) => setTimeout(f, Math.min(ms, 5)),
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
const send = m => new Promise(r => L.msg[0](m, null, r));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const wait = ms => new Promise(r => setTimeout(r, ms));
|
||||
const rows = () => store.data.rows;
|
||||
|
||||
(async () => {
|
||||
// 0) Première ouverture : rien de configuré → filtre SIBELIT intégré, actif tout seul
|
||||
store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
const b0 = bodies.find(b => !b.withSectionsAndDetails && b.filter.onlyRunning);
|
||||
ok(b0 && JSON.stringify(b0.filter.ruCodes) === JSON.stringify(['0087.08987', '0087.08900', '0088.0682', '0082.SIBEL', '0082.8987']),
|
||||
'première ouverture : filtre SIBELIT intégré utilisé d\'office (5 entreprises), rien à configurer');
|
||||
ok(store.data.rows.length === 9 && store.data.rows.every(t => t.src === 'filter'), 'trains SIBELIT affichés directement (9 lignes)');
|
||||
// codes personnalisés dans Réglages
|
||||
await chrome.storage.local.set({ prefs: { presetRu: ['0082.SIBEL'] } }); bodies.length = 0;
|
||||
clock += 60e3; store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
ok(JSON.stringify(bodies.find(b => b.filter.onlyRunning).filter.ruCodes) === '["0082.SIBEL"]', 'codes entreprises modifiables (Réglages) pris en compte');
|
||||
await chrome.storage.local.set({ prefs: {} });
|
||||
const ps = await send({ type: 'setSource', source: 'filter', filterId: 'preset-sibelit' }); await wait(40);
|
||||
ok(ps.ok && store.prefs.sourceChosen && store.prefs.activeList === 'preset-sibelit', 'choix explicite du filtre intégré mémorisé');
|
||||
clock -= 60e3; for (const k of ['details', 'detailTried', 'prev', 'data']) delete store[k]; // scénario suivant : repart de zéro
|
||||
|
||||
const lf = await send({ type: 'listFilters' });
|
||||
ok(lf.ok && lf.filters[0].name === 'Sib' && lf.filters[0].ruCount === 2, 'filtres TIS lus : « Sib » (2 entreprises)');
|
||||
bodies.length = 0;
|
||||
await send({ type: 'setSource', source: 'filter', filterId: 96463 }); await wait(40);
|
||||
const [b1, b2] = bodies.filter(b => !b.withSectionsAndDetails);
|
||||
ok(b1 && b1.filter.onlyRunning === true && b1.filter.ruCodes.length === 2 && !('timeFramePast' in b1.filter) && !('timeframe' in b1.filter), 'recherche « en circulation » : ruCodes gardés, réglages d\'écran retirés (évite l\'erreur 400)');
|
||||
ok(b2 && b2.filter.onlyRunning === false && b2.filter.departureTimeFrom === '2026-10-26T04:45:00' && b2.filter.departureTimeTo === '2026-10-26T08:45:00',
|
||||
`recherche « départs » : de -3 h à +60 min, heure locale TIS (${b2 && b2.filter.departureTimeFrom} → ${b2 && b2.filter.departureTimeTo})`);
|
||||
const otns = rows().map(t => t.otn);
|
||||
ok(otns.length === 9, `9 lignes : 7 en circulation + 2 pas partis (${otns.join(', ')})`);
|
||||
ok(otns.filter(o => o === '45705').length === 1, 'pas de doublon pour un train déjà parti présent dans les deux recherches');
|
||||
ok(!otns.includes('45711'), 'train déjà arrivé (dans la fenêtre de départs) ignoré');
|
||||
const r8 = rows().find(t => t.otn === '45708'), r9 = rows().find(t => t.otn === '45710');
|
||||
ok(r8.color === 'blue' && r8.startsInMin === 40, '45708 : bleu, départ dans 40 min');
|
||||
ok(r9.phase === 'waiting' && r9.etdLate === 12 && r9.color === 'yellow', '45710 : pas parti, ETD +12 → jaune');
|
||||
ok(rows().every(t => t.src === 'filter'), 'lignes marquées « filtre » (✕ = masquer)');
|
||||
const detailReq = bodies.filter(b => b.withSectionsAndDetails);
|
||||
ok(detailReq.length === 1 && detailReq[0].filter.trainNumbers.length === 4, `détail limité à 4 trains par cycle (${detailReq[0] && detailReq[0].filter.trainNumbers.length})`);
|
||||
bodies.length = 0; clock += 60e3; store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
const d2 = bodies.filter(b => b.withSectionsAndDetails);
|
||||
ok(d2.length === 1 && d2[0].filter.trainNumbers.length === 3, 'cycle suivant : détail pour les 3 trains restants');
|
||||
|
||||
// trains en plus saisis à la main
|
||||
await send({ type: 'setTrains', numbers: '12345 45705' }); await wait(40);
|
||||
const extra = rows().filter(t => t.src === 'list');
|
||||
ok(extra.length === 1 && extra[0].otn === '12345', 'train en plus 12345 ajouté (45705 déjà dans le filtre : pas de doublon)');
|
||||
|
||||
// masquer
|
||||
const id = rows().find(t => t.otn === '40366').id;
|
||||
await send({ type: 'hide', id, otn: '40366' });
|
||||
ok(!rows().some(t => t.otn === '40366') && store.data.hiddenCount === 1, '40366 masqué immédiatement');
|
||||
clock += 60e3; store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
ok(!rows().some(t => t.otn === '40366'), 'reste masqué aux cycles suivants');
|
||||
clock += 25 * 3600e3; store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
ok(rows().some(t => t.otn === '40366'), 'masquage expire après 24 h');
|
||||
await send({ type: 'hide', id, otn: '40366' }); await send({ type: 'unhideAll' }); await wait(40);
|
||||
ok(store.data.hiddenCount === 0, '« Tout réafficher »');
|
||||
|
||||
// retour en liste manuelle
|
||||
bodies.length = 0; await send({ type: 'setSource', source: 'list' }); await wait(40);
|
||||
ok(bodies.every(b => b.filter.trainNumbers) && rows().every(t => t.src === 'list'), 'retour en « liste manuelle » : seulement les numéros saisis');
|
||||
})();
|
||||
@@ -0,0 +1,104 @@
|
||||
// Test v1.5 : numéros liés (parité), jumeau de parité, jour choisi, listes (intégrées / perso), ajouts hors filtre, causes de retard.
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
let clock = Date.parse('2026-10-26T08:00:00+01:00'); const iso = ms => new Date(ms).toISOString();
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
const store = {}, L = {}, bodies = [];
|
||||
const on = n => ({ addListener: f => (L[n] = L[n] || []).push(f) });
|
||||
const chrome = {
|
||||
storage: { local: { async get(k) { k = Array.isArray(k) ? k : [k]; const o = {}; for (const x of k) if (x in store) o[x] = JSON.parse(JSON.stringify(store[x])); return o; },
|
||||
async set(o) { for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); }, async remove(k) { delete store[k]; } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: on('a') }, notifications: { create() {}, clear() {}, onClicked: on('n') },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: on('t') },
|
||||
windows: { create: async () => ({ id: 1 }), get: async () => { throw new Error(); }, update: async () => {}, remove: async () => {}, onRemoved: on('w') },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} },
|
||||
action: { onClicked: on('ac'), setBadgeText() {}, setBadgeBackgroundColor() {}, setTitle() {} },
|
||||
runtime: { onInstalled: on('i'), onStartup: on('s'), getURL: p => p, getManifest: () => ({ version: 't' }), getContexts: async () => [{}], sendMessage: async () => {}, onMessage: on('msg') },
|
||||
};
|
||||
const day = (d, h) => Date.parse(`2026-10-${d}T${h}:00+01:00`);
|
||||
// Trains « 42920 → 42921 » sur plusieurs jours (comme dans TIS) + un train 777 qui n'existe que sous 778 (parité)
|
||||
const RUN = (id, d, extra) => ({ header: Object.assign({ id, otn: 42920, referenceOtn: 42921, originOtn: 42920, destinationOtn: 42921, operationalTrainNumbers: [42920, 42921], referenceOtns: [42920, 42921],
|
||||
type: 'FREIGHT', running: false, archive: false, origin: { locationId: 1, plannedTime: iso(day(d, '19:48')) }, current: { id: id * 10, locationId: 1 }, destination: { locationId: 2, plannedTime: iso(day(d, '23:59') + 8 * 3600e3) } }, extra) });
|
||||
const TRAINS = [RUN(1, 26), RUN(2, 27), RUN(3, 28),
|
||||
RUN(4, 25, { running: true, origin: { locationId: 1, plannedTime: iso(day(25, '19:48')), actualTime: iso(day(25, '20:30')), trainDelays: [{ id: 9, delay: 42, delayCauseCode: '64', locationId: 1, time: iso(day(25, '20:30')) }] },
|
||||
current: { id: 40, locationId: 2, actualTime: iso(clock - 6e4), runningDeltaForDisplay: 42 } })];
|
||||
const T778 = { header: { id: 50, otn: 776, originOtn: 776, destinationOtn: 776, operationalTrainNumbers: [776], type: 'FREIGHT', running: true, archive: false,
|
||||
origin: { locationId: 1, plannedTime: iso(clock - 3600e3), actualTime: iso(clock - 3600e3) }, current: { id: 500, locationId: 2, actualTime: iso(clock - 6e4), runningDeltaForDisplay: 0 }, destination: { locationId: 2 } } };
|
||||
async function fakeFetch(url, opts) {
|
||||
if (url.includes('accounts/self')) return { ok: true, status: 200, json: async () => ({ data: { firstName: 'M' } }) };
|
||||
if (url.includes('/companies')) return { ok: true, status: 200, json: async () => ({ data: [{ code: '0088.2188', name: 'Lineas NV/SA', displayType: 'RAILWAY_UNDERTAKING', countryCode: 'BE' }, { code: '0088', name: 'Infrabel', displayType: 'INFRASTRUCTURE_MANAGER' }] }) };
|
||||
const b = JSON.parse(opts.body); bodies.push(b);
|
||||
let trains = [];
|
||||
if (b.filter.ruCodes) trains = b.filter.onlyRunning ? [T778] : [];
|
||||
else if (b.filter.trainNumbers) {
|
||||
const n = b.filter.trainNumbers;
|
||||
trains = [...TRAINS.filter(t => n.some(x => t.header.operationalTrainNumbers.map(String).includes(x))), ...(n.includes('776') ? [T778] : [])];
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: trains.length ? { locations: [{ id: 1, name: 'ANTWERPEN-NOORD' }, { id: 2, name: 'Basel' }], trains } : { locations: [] } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout: (f, ms) => setTimeout(f, Math.min(ms, 5)),
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
const send = m => new Promise(r => L.msg[0](m, null, r));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const wait = ms => new Promise(r => setTimeout(r, ms));
|
||||
const rows = () => store.data.rows;
|
||||
const listRow = q => rows().find(t => t.src === 'list' && t.query === q);
|
||||
|
||||
(async () => {
|
||||
// Liste manuelle
|
||||
await send({ type: 'setList', id: 'preset-manual' }); await wait(30);
|
||||
await send({ type: 'setTrains', numbers: '42921, 777, 40000' }); await wait(60);
|
||||
const r1 = listRow('42921');
|
||||
ok(r1 && r1.phase === 'running' && r1.id === 4, '42921 trouvé alors que le numéro principal TIS est 42920 (numéros liés)');
|
||||
ok(JSON.stringify(r1.numbers) === '["42920","42921"]', `numéros du train affichés : ${r1 && r1.numbers.join(' → ')}`);
|
||||
ok(r1.delays.length === 1 && r1.delays[0].code === '64', 'cause de retard UIC lue (64 = locomotive)');
|
||||
ok(r1.alts.length === 4 && r1.alts.map(a => a.date).join(',') === '2026-10-25,2026-10-26,2026-10-27,2026-10-28', 'autres jours proposés (25 → 28/10)');
|
||||
const r777 = listRow('777');
|
||||
ok(r777 && r777.phase === 'running' && r777.parityFrom === '777' && r777.otn === '776', '777 introuvable → trouvé sous 776 (parité 776/777), avec explication');
|
||||
const r4 = listRow('40000');
|
||||
ok(r4 && r4.phase === 'notfound' && /ni sous le n° 40000 ni sous le n° 40001/.test(r4.reason), 'vraiment introuvable : message qui parle de la parité (40000 / 40001)');
|
||||
|
||||
// Jour choisi
|
||||
await send({ type: 'pin', otn: '42921', date: '2026-10-27' }); await wait(40);
|
||||
const r2 = listRow('42921');
|
||||
ok(r2.id === 2 && r2.pinned === '2026-10-27' && r2.color === 'blue', 'jour choisi (27/10) : le bon train, « pas parti »');
|
||||
await send({ type: 'setTrains', numbers: '42921@28/10, 777' }); await wait(40);
|
||||
ok(listRow('42921').id === 3 && store.pins['42921'] === '2026-10-28', 'saisie « 42921@28/10 » dans le champ');
|
||||
await send({ type: 'pin', otn: '42921', date: null }); await wait(40);
|
||||
ok(listRow('42921').id === 4 && !listRow('42921').pinned, '« Automatique » : retour au train en cours');
|
||||
await send({ type: 'pin', otn: '42921', date: '2026-11-15' }); await wait(40);
|
||||
ok(listRow('42921').phase === 'notfound' && /15\/11/.test(listRow('42921').reason), 'jour sans train : message clair');
|
||||
await send({ type: 'pin', otn: '42921', date: null }); await wait(40);
|
||||
|
||||
// Listes intégrées et perso ; ajouts hors filtre
|
||||
await send({ type: 'setList', id: 'preset-lineas' }); await wait(40);
|
||||
const bl = bodies.filter(b => b.filter.ruCodes).pop();
|
||||
ok(bl && bl.filter.ruCodes.includes('0088.2188') && bl.filter.ruCodes.length === 19, 'liste intégrée Lineas : 19 codes Lineas');
|
||||
ok(rows().every(t => t.src === 'filter'), 'chaque liste a ses propres numéros en plus (Lineas : aucun pour l\'instant)');
|
||||
await send({ type: 'setTrains', numbers: '42921' }); await wait(40);
|
||||
const extraBody = bodies.filter(b => b.filter.trainNumbers && !b.withSectionsAndDetails).pop();
|
||||
ok(listRow('42921') && !extraBody.filter.ruCodes, 'numéro ajouté en plus : cherché SANS filtre entreprise (hors filtre)');
|
||||
const del = await send({ type: 'deleteList', id: 'preset-lineas' });
|
||||
ok(!del.ok, 'liste intégrée : suppression refusée');
|
||||
const sv = await send({ type: 'saveList', list: { name: 'Shift nuit BE', ruCodes: ['0088.2188', '0088.0682'], trains: '42921@27/10, 777' } }); await wait(40);
|
||||
ok(sv.ok && store.lists.length === 1 && store.extras[sv.id].join() === '42921,777' && store.pins['42921'] === '2026-10-27', 'liste perso créée (entreprises + numéros + jour)');
|
||||
await send({ type: 'setList', id: sv.id }); await wait(40);
|
||||
ok(bodies.filter(b => b.filter.ruCodes).pop().filter.ruCodes.join() === '0088.2188,0088.0682', 'liste perso utilisée : ses entreprises');
|
||||
ok(listRow('42921') && listRow('42921').id === 2, 'liste perso : ses numéros en plus, au jour choisi');
|
||||
await send({ type: 'saveList', list: { id: sv.id, name: 'Shift nuit', ruCodes: ['0088.0682'], trains: '777' } }); await wait(40);
|
||||
ok(store.lists[0].name === 'Shift nuit' && bodies.filter(b => b.filter.ruCodes).pop().filter.ruCodes.join() === '0088.0682', 'liste perso modifiée et rechargée');
|
||||
await send({ type: 'deleteList', id: sv.id }); await wait(40);
|
||||
ok(!store.lists.length && store.prefs.activeList === 'preset-sibelit', 'liste perso supprimée → retour sur SIBELIT');
|
||||
|
||||
// Entreprises ferroviaires (pour composer une liste)
|
||||
const co = await send({ type: 'companies' });
|
||||
ok(co.ok && co.list.length === 1 && co.list[0].n === 'Lineas NV/SA', 'liste des entreprises ferroviaires (sans les gestionnaires d\'infra)');
|
||||
|
||||
// Compatibilité : ancien utilisateur en « liste manuelle » avec l'ancienne clé « trains »
|
||||
for (const k of Object.keys(store)) delete store[k];
|
||||
store.prefs = { source: 'list', sourceChosen: true }; store.trains = ['42921']; const mark = bodies.length;
|
||||
clock += 60e3; store.lastRun = 0; await send({ type: 'force' }); await wait(40);
|
||||
|
||||
ok(listRow('42921') && !bodies.slice(mark).some(b => b.filter.ruCodes), 'mise à jour depuis v1.4 : liste manuelle et numéros conservés');
|
||||
})();
|
||||
@@ -0,0 +1,65 @@
|
||||
// Test v1.6 : composition « véhicules-longueur-poids » (poids du train, pas le poids freiné), section actuelle, cadence.
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
let clock = Date.parse('2026-10-26T09:00:00+01:00'); const iso = ms => new Date(ms).toISOString();
|
||||
class FakeDate extends Date { constructor(...a) { a.length ? super(...a) : super(clock); } static now() { return clock; } }
|
||||
const store = {}, L = {}, compoCalls = [];
|
||||
const on = n => ({ addListener: f => (L[n] = L[n] || []).push(f) });
|
||||
const chrome = {
|
||||
storage: { local: { async get(k) { k = Array.isArray(k) ? k : [k]; const o = {}; for (const x of k) if (x in store) o[x] = JSON.parse(JSON.stringify(store[x])); return o; },
|
||||
async set(o) { for (const [k, v] of Object.entries(o)) store[k] = JSON.parse(JSON.stringify(v)); }, async remove(k) { delete store[k]; } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: on('a') }, notifications: { create() {}, clear() {}, onClicked: on('n') },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: on('t') },
|
||||
windows: { create: async () => ({ id: 1 }), get: async () => { throw new Error(); }, update: async () => {}, remove: async () => {}, onRemoved: on('w') },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} },
|
||||
action: { onClicked: on('ac'), setBadgeText() {}, setBadgeBackgroundColor() {}, setTitle() {} },
|
||||
runtime: { onInstalled: on('i'), onStartup: on('s'), getURL: p => p, getManifest: () => ({ version: 't' }), getContexts: async () => [{}], sendMessage: async () => {}, onMessage: on('msg') },
|
||||
};
|
||||
// 6 trains SIBELIT en circulation ; le 1 change de composition à la frontière (Infrabel puis SNCF Réseau)
|
||||
const H = (id, im, cur) => ({ header: { id, otn: 40000 + id, type: 'FREIGHT', running: true, archive: false,
|
||||
origin: { locationId: 1, plannedTime: iso(clock - 7200e3), actualTime: iso(clock - 7000e3), responsibleImCode: '0088' },
|
||||
current: { id: id * 10, locationId: cur, actualTime: iso(clock - 6e4), runningDeltaForDisplay: 0, responsibleImCode: im },
|
||||
destination: { locationId: 9, plannedTime: iso(clock + 7200e3), responsibleImCode: '0087' } } });
|
||||
const TRAINS = [H(1, '0087', 5), ...[2, 3, 4, 5, 6].map(i => H(i, '0088', 2))];
|
||||
const COMPO = {
|
||||
1: { activeCompositions: [{ compositionId: 11, locFromName: 'ANTWERPEN-NOORD', locToName: 'AUBANGE-FRONTIERE' }, { compositionId: 12, locFromName: 'Aubange', locToName: 'Thionville' }],
|
||||
compositions: [
|
||||
{ id: 12, fromLocationId: 4, toLocationId: 9, responsibleImCode: '0087', vehicleCount: 30, length: 640, weight: 1850, brakeWeight: 1700 },
|
||||
{ id: 11, fromLocationId: 1, toLocationId: 4, responsibleImCode: '0088', vehicleCount: 31, length: 653, weight: 902, brakeWeight: 908 }] },
|
||||
2: { activeCompositions: [{ compositionId: 21 }], compositions: [{ id: 21, fromLocationId: 1, toLocationId: 9, responsibleImCode: '0088', vehicleCount: 2, length: 50, weight: 200, brakeWeight: 180 }] },
|
||||
};
|
||||
async function fakeFetch(url, opts) {
|
||||
if (url.includes('accounts/self')) return { ok: true, status: 200, json: async () => ({ data: { firstName: 'M' } }) };
|
||||
const m = url.match(/train-compositions\?trainId=(\d+)/);
|
||||
if (m) { compoCalls.push(Number(m[1])); return { ok: true, status: 200, json: async () => ({ data: COMPO[m[1]] || {} }) }; }
|
||||
const b = JSON.parse(opts.body);
|
||||
const trains = b.withSectionsAndDetails ? [] : b.filter.onlyRunning ? TRAINS : [];
|
||||
return { ok: true, status: 200, json: async () => ({ data: { result: { locations: [{ id: 1, name: 'A' }], trains } } }) };
|
||||
}
|
||||
const ctx = vm.createContext({ chrome, fetch: fakeFetch, console, Date: FakeDate, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout: (f, ms) => setTimeout(f, Math.min(ms, 5)),
|
||||
importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
const send = m => new Promise(r => L.msg[0](m, null, r));
|
||||
const ok = (c, m) => { console.log((c ? 'OK ' : 'FAIL ') + m); if (!c) process.exitCode = 1; };
|
||||
const wait = ms => new Promise(r => setTimeout(r, ms));
|
||||
const cycle = async () => { store.lastRun = 0; await send({ type: 'force' }); await wait(40); };
|
||||
const row = id => store.data.rows.find(t => t.id === id);
|
||||
|
||||
(async () => {
|
||||
await cycle();
|
||||
ok(compoCalls.length === 4, `composition demandée pour 4 trains max par cycle (${compoCalls.length})`);
|
||||
ok(row(2).compo && row(2).compo.label === '2-50-200', `exemple : 2 véhicules, 50 m, 200 t → « ${row(2).compo && row(2).compo.label} »`);
|
||||
ok(row(1).compo.label === '30-640-1850', `train 1 en France : section SNCF Réseau → « ${row(1).compo.label} » (pas le poids freiné 1700)`);
|
||||
ok(row(1).compo.sections.length === 2 && row(1).compo.sections[0].id === 11, 'les 2 sections, dans l\'ordre du parcours');
|
||||
ok(row(3).compo === null, 'pas de composition dans TIS → rien affiché');
|
||||
compoCalls.length = 0; clock += 60e3; await cycle();
|
||||
ok(compoCalls.length === 2 && compoCalls.every(id => [5, 6].includes(id)), 'cycle suivant : les 2 trains restants seulement');
|
||||
compoCalls.length = 0; clock += 60e3; await cycle();
|
||||
ok(compoCalls.length === 0 && row(2).compo.label === '2-50-200', 'ensuite : pas de rechargement avant 15 min, composition gardée');
|
||||
clock += 15 * 60e3; compoCalls.length = 0; await cycle();
|
||||
ok(compoCalls.length === 4, 'après 15 min : rechargement (par lots de 4)');
|
||||
// le train 1 revient en Belgique (même GI que la 1re section) → section Infrabel
|
||||
TRAINS[0].header.current.responsibleImCode = '0088'; TRAINS[0].header.current.locationId = 2;
|
||||
clock += 60e3; await cycle();
|
||||
ok(row(1).compo.label === '31-653-902', `position chez Infrabel → section Infrabel « ${row(1).compo.label} »`);
|
||||
})();
|
||||
@@ -0,0 +1,44 @@
|
||||
// Test v1.8 : prochain point avec sections TIS dans le désordre + prévision parasite (cas réel 42926), dépassement.
|
||||
const path = require('path');
|
||||
const c = require(path.join(process.argv[2], 'core.js'));
|
||||
const ok = (b, m) => { console.log((b ? 'OK ' : 'FAIL ') + m); if (!b) process.exitCode = 1; };
|
||||
const T = s => new Date(`2026-10-26T${s}:00+01:00`).toISOString();
|
||||
const now = Date.parse('2026-10-26T13:53:00+01:00');
|
||||
const names = { 1: 'Mulhouse-Nord Relais', 2: 'Lutterbach', 3: 'Ébange', 4: 'Thionville', 5: 'Thionville-Faisceau Est', 6: 'Hagondange', 7: 'Conflans-Jarny', 8: 'Mont-St-Martin', 9: 'Aubange', 10: 'Zeebrugge' };
|
||||
// Sections comme TIS les envoie pour le 42926 : la section 1 (42927) est une prévision isolée sans heures prévues,
|
||||
// la section 3 (continuation Hagondange → Conflans) arrive en dernier.
|
||||
const train = { header: { id: 42926, current: { id: 'th', locationId: 4, actualTime: T('13:19') } }, sections: [
|
||||
{ trainDetails: [
|
||||
{ id: 'mu', locationId: 1, plannedTime: T('07:32'), actualTime: T('07:32') },
|
||||
{ id: 'lu0', locationId: 2, plannedTime: T('07:39'), actualTime: T('08:11') },
|
||||
{ id: 'eb', locationId: 3, plannedTime: T('13:17'), actualTime: T('13:16') },
|
||||
{ id: 'th', locationId: 4, plannedTime: T('13:21'), actualTime: T('13:19'), currentLocation: true },
|
||||
{ id: 'tf', locationId: 5, plannedTime: T('13:23'), calculatedTime: T('13:23') }] },
|
||||
{ trainDetails: [ // prévision parasite (autre trajet du 42927) : heures calculées, aucune heure prévue
|
||||
{ id: 'lu1', locationId: 2, calculatedTime: T('08:11') }, { id: 'bo', locationId: 99, calculatedTime: T('08:36') },
|
||||
{ id: 'ms', locationId: 8, plannedTime: T('18:01'), calculatedTime: T('18:01') }] },
|
||||
{ trainDetails: [{ id: 'au', locationId: 9, plannedTime: T('17:44') }, { id: 'ze', locationId: 10, plannedTime: '2026-10-27T00:47:00+01:00' }] },
|
||||
{ trainDetails: [{ id: 'ha', locationId: 6, plannedTime: T('16:28'), calculatedTime: T('16:28') }, { id: 'cj', locationId: 7, plannedTime: T('17:00') }] },
|
||||
] };
|
||||
const pts = c.compactDetails(train);
|
||||
ok(pts[0].id === 'th', 'le cache commence à la position actuelle (Thionville)');
|
||||
ok(!pts.some(p => p.id === 'lu1' || p.id === 'bo'), 'prévision parasite sans heure prévue (Lutterbach 08:11) écartée');
|
||||
ok(pts.map(p => p.id).join() === 'th,tf,ha,cj,au,ms,ze', `étapes remises dans l'ordre du temps : ${pts.map(p => names[p.loc] || p.loc).join(' → ')}`);
|
||||
const ctx = { now, cfg: { yellowFromMin: 5, redFromMin: 15 }, locName: id => names[id] || '#' + id, details: { 42926: { points: pts, passed: c.passedLocations(train) } } };
|
||||
const n = c.nextStop(train.header, ctx);
|
||||
ok(n && n.name === 'Thionville-Faisceau Est', `prochain point : ${n && n.name} (et plus Lutterbach)`);
|
||||
// classify : dépassement de l'heure attendue au prochain point
|
||||
const h = { ...train.header, otn: 42926, running: true, origin: { locationId: 1, plannedTime: T('07:32'), actualTime: T('07:32') },
|
||||
current: { ...train.header.current, runningDeltaForDisplay: -1 }, destination: { locationId: 7, plannedTime: T('17:00') } };
|
||||
const r = c.classify(h, ctx);
|
||||
ok(r.overdueMin === 30 && r.overdueOn === 'next', `Thionville-Faisceau Est attendu 13:23, il est 13:53 → dépassé de ${r.overdueMin} min`);
|
||||
// train au relais : arrêté depuis longtemps mais prochain point pas encore dû → pas en retard
|
||||
const ctx2 = { ...ctx, details: { 42926: { points: pts.filter(p => p.id !== 'tf') } } };
|
||||
const r2 = c.classify(h, ctx2);
|
||||
ok(r2.next.name === 'Hagondange' && r2.overdueMin < 0, `sans le faisceau : prochain Hagondange 16:28 → pas dû (${r2.overdueMin} min) = stand-by`);
|
||||
// cache périmé (position actuelle absente) : premier point non franchi après l'heure du pointage
|
||||
const ctx3 = { ...ctx, details: { 42926: { points: [{ id: 'old', loc: 2, pt: T('07:39'), at: null }, { id: 'ha', loc: 6, pt: T('16:28'), ct: T('16:28') }] } } };
|
||||
ok(c.nextStop(train.header, ctx3).name === 'Hagondange', 'cache ancien : on ignore les points antérieurs au dernier pointage');
|
||||
// pas d'information de prochain point : on se rabat sur l'arrivée
|
||||
const r4 = c.classify(h, { ...ctx, details: {} });
|
||||
ok(r4.overdueOn === 'arrival' && r4.overdueMin < 0, 'sans détail : dépassement calculé sur l\'arrivée prévue');
|
||||
@@ -0,0 +1,46 @@
|
||||
// Test v2.0 : horaire d'un train pour l'impression (ordre, fusion arr./dép., sections multiples, message moteur).
|
||||
const fs = require('fs'), vm = require('vm'), path = require('path');
|
||||
const dir = process.argv[2];
|
||||
const c = require(path.join(dir, 'core.js'));
|
||||
const ok = (b, m) => { console.log((b ? 'OK ' : 'FAIL ') + m); if (!b) process.exitCode = 1; };
|
||||
const T = s => new Date(`2026-10-26T${s}:00+01:00`).toISOString();
|
||||
const N = { 1: 'Mulhouse-Nord - Relais', 2: 'Mulhouse-Nord - Aig Km 1,4', 3: 'Bollwiller', 4: 'Thionville-Faisceau Est', 5: 'Hagondange', 6: 'Lutterbach', 7: 'Zeebrugge' };
|
||||
const train = { header: { id: 1, otn: 42926, originOtn: 42926, destinationOtn: 42927, operationalTrainNumbers: [42926, 42927] }, sections: [
|
||||
{ trainDetails: [
|
||||
{ id: 'a', locationId: 1, plannedStatus: 'DEPARTURE_FROM_ORIGIN', plannedTime: T('07:32'), actualTime: T('07:33'), runningDeltaForDisplay: 1, responsibleImCode: '0087' },
|
||||
{ id: 'b', locationId: 2, plannedStatus: 'RUN_THROUGH', plannedTime: T('07:36') },
|
||||
{ id: 'c1', locationId: 3, plannedStatus: 'ARRIVAL', plannedTime: T('07:48'), actualTime: T('07:50') },
|
||||
{ id: 'c2', locationId: 3, plannedStatus: 'DEPARTURE', plannedTime: T('07:57'), actualTime: T('08:00'), runningDeltaForDisplay: 3 },
|
||||
{ id: 'd1', locationId: 4, plannedStatus: 'ARRIVAL', plannedTime: T('13:23'), currentLocation: true },
|
||||
{ id: 'd2', locationId: 4, plannedStatus: 'DEPARTURE', plannedTime: T('16:01'), calculatedTime: T('16:05') }] },
|
||||
{ trainDetails: [{ id: 'x', locationId: 6, calculatedTime: T('08:11') }] }, // prévision parasite : écartée
|
||||
{ trainDetails: [{ id: 'z', locationId: 7, plannedStatus: 'ARRIVAL_AT_DESTINATION', plannedTime: '2026-10-27T00:47:00+01:00' }] },
|
||||
{ trainDetails: [{ id: 'e', locationId: 5, plannedStatus: 'RUN_THROUGH', plannedTime: T('16:28') }, { id: 'a', locationId: 1, plannedStatus: 'DEPARTURE_FROM_ORIGIN', plannedTime: T('07:32') }] },
|
||||
] };
|
||||
const rows = c.buildTimetable(train, id => N[id]);
|
||||
ok(rows.map(r => N[r.loc]).join(' > ') === 'Mulhouse-Nord - Relais > Mulhouse-Nord - Aig Km 1,4 > Bollwiller > Thionville-Faisceau Est > Hagondange > Zeebrugge',
|
||||
'étapes dans l\'ordre du parcours, sans doublon ni prévision parasite');
|
||||
const bol = rows[2], thi = rows[3];
|
||||
ok(bol.kind === 'stop' && bol.arr.p === T('07:48') && bol.dep.p === T('07:57') && bol.dep.a === T('08:00') && bol.delay === 3, 'arrêt Bollwiller : arrivée + départ sur une seule ligne, retard 3');
|
||||
ok(thi.kind === 'stop' && thi.current && thi.dep.c === T('16:05'), 'Thionville-Faisceau : arrêt 13:23 → 16:01 (estimé 16:05), position actuelle repérée');
|
||||
ok(rows[0].kind === 'origin' && rows[1].kind === 'pass' && rows[5].kind === 'dest', 'types : départ, passage, arrêt, arrivée');
|
||||
|
||||
// message moteur « timetable »
|
||||
const store = {}, L = {};
|
||||
const on = n => ({ addListener: f => (L[n] = L[n] || []).push(f) });
|
||||
const chrome = {
|
||||
storage: { local: { async get(k) { k = Array.isArray(k) ? k : [k]; const o = {}; for (const x of k) if (x in store) o[x] = store[x]; return o; }, async set(o) { Object.assign(store, o); }, async remove(k) { delete store[k]; } } },
|
||||
alarms: { create() {}, clear() {}, onAlarm: on('a') }, notifications: { create() {}, clear() {}, onClicked: on('n') },
|
||||
tabs: { query: async () => [], create: async () => {}, update: async () => {}, onUpdated: on('t') },
|
||||
windows: { create: async () => ({ id: 1 }), get: async () => { throw new Error(); }, update: async () => {}, remove: async () => {}, onRemoved: on('w') },
|
||||
scripting: {}, offscreen: { createDocument: async () => {} }, action: { onClicked: on('ac'), setBadgeText() {}, setBadgeBackgroundColor() {}, setTitle() {} },
|
||||
runtime: { onInstalled: on('i'), onStartup: on('s'), getURL: p => p, getManifest: () => ({ version: 't' }), getContexts: async () => [{}], sendMessage: async () => {}, onMessage: on('msg') },
|
||||
};
|
||||
let asked = null;
|
||||
const fetch = async (url, o) => { asked = { url, o }; return { ok: true, status: 200, json: async () => ({ data: { locations: Object.entries(N).map(([id, name]) => ({ id: Number(id), name })), trains: [train] } }) }; };
|
||||
const ctx = vm.createContext({ chrome, fetch, console, Date, JSON, Math, Object, Array, Set, Number, String, Promise, setTimeout, importScripts: f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx) });
|
||||
vm.runInContext(fs.readFileSync(path.join(dir, 'background.js'), 'utf8'), ctx);
|
||||
L.msg[0]({ type: 'timetable', id: 603220622 }, null, r => {
|
||||
ok(asked.url.endsWith('/trains/603220622'), 'appel TIS : GET trains/<id>');
|
||||
ok(r.ok && r.rows.length === 6 && r.rows[3].name === 'Thionville-Faisceau Est' && r.numbers.join() === '42926,42927', `horaire renvoyé à la page (${r.rows && r.rows.length} lignes, numéros ${r.numbers && r.numbers.join(' → ')})`);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// Test v2.0.1 : cas réel 42821 (+63) — ordre des étapes d'un train en retard, estimations TIS périmées.
|
||||
const path = require('path');
|
||||
const c = require(path.join(process.argv[2], 'core.js'));
|
||||
const ok = (b, m) => { console.log((b ? 'OK ' : 'FAIL ') + m); if (!b) process.exitCode = 1; };
|
||||
const T = s => new Date(`2026-10-26T${s}:00+01:00`).toISOString();
|
||||
const hm = iso => new Date(iso).toLocaleTimeString('fr-BE', { hour: '2-digit', minute: '2-digit' });
|
||||
const N = { 1: 'CARLSBOURG', 2: 'PALISEUL', 3: 'RACC.JEHONVILLE-M.D.N.', 4: 'BERTRIX', 5: 'STRAIMONT', 6: 'AUBANGE-FRONTIERE-LUXEMBOURG', 7: 'Pétange secteur Rodange', 8: 'Uckange - Faisceau' };
|
||||
// heures de la capture TIS : prévu / réel / calculé (TIS calcule encore avec +34 → périmé)
|
||||
const P = (id, loc, pt, at, ct, cur) => ({ id, locationId: loc, plannedTime: T(pt), actualTime: at ? T(at) : undefined, calculatedTime: ct ? T(ct) : undefined, currentLocation: !!cur });
|
||||
const train = { header: { id: 9, otn: 42821, running: true,
|
||||
origin: { locationId: 1, plannedTime: T('03:05'), actualTime: T('03:24') },
|
||||
current: { id: 'j', locationId: 3, actualTime: T('14:10'), runningDeltaForDisplay: 63 },
|
||||
destination: { locationId: 8, plannedTime: T('15:40'), calculatedTime: T('15:40') } },
|
||||
sections: [{ trainDetails: [P('c', 1, '12:59', '14:03'), P('p', 2, '13:01', '14:05'), P('j', 3, '13:07', '14:10', null, true),
|
||||
P('b', 4, '13:09', null, '13:43'), P('s', 5, '13:17', null, '13:51'), P('a', 6, '14:03', null, '15:02')] },
|
||||
{ trainDetails: [P('r', 7, '14:06', null, '14:34'), P('u', 8, '15:40', null, '15:40')] }] };
|
||||
const pts = c.compactDetails(train);
|
||||
ok(pts[0].id === 'j' && pts[1].id === 'b', `ordre : la position actuelle (Jehonville, réel 14:10) reste AVANT Bertrix (prévu 13:09) → ${pts.map(p => N[p.loc]).join(' > ')}`);
|
||||
const ctx = { now: Date.parse(T('14:12')), cfg: { yellowFromMin: 5, redFromMin: 15 }, locName: id => N[id], details: { 9: { points: pts } } };
|
||||
const r = c.classify(train.header, ctx);
|
||||
ok(r.delay === 63 && r.next.name === 'BERTRIX', `prochain point : ${r.next.name} (et plus Pétange)`);
|
||||
ok(r.next.estSrc === 'tta' && hm(r.next.estimatedTime) === '14:12', `Bertrix : TIS dit 13:43 (périmé, +34) → estimé ≈${hm(r.next.estimatedTime)} = prévu 13:09 + 63`);
|
||||
ok(r.overdueMin === 0, `pas de faux « dépassé » : ${r.overdueMin} min`);
|
||||
ok(r.arrEstSrc === 'tta' && hm(r.forecastArrival) === '16:43', `arrivée Uckange : TIS 15:40 (périmé) → ≈${hm(r.forecastArrival)}`);
|
||||
// estimation TIS cohérente (un peu de rattrapage) : on garde TIS
|
||||
const e = c.estimateAt(T('15:00'), T('15:50'), 63);
|
||||
ok(e.src === 'tis' && hm(e.t) === '15:50', 'rattrapage plausible (TIS +50 alors que +63 actuel) : on garde l\'heure TIS');
|
||||
ok(c.estimateAt(T('15:00'), T('16:30'), 63).src === 'tis', 'TIS prévoit plus de retard : on garde TIS');
|
||||
@@ -0,0 +1,40 @@
|
||||
// Test v2.1.1 : cas réel 42926 → 42927 à Thionville : même lieu répété (arrivée 13:23 puis départ 16:01) = arrêt.
|
||||
const path = require('path');
|
||||
const c = require(path.join(process.argv[2], 'core.js'));
|
||||
const ok = (b, m) => { console.log((b ? 'OK ' : 'FAIL ') + m); if (!b) process.exitCode = 1; };
|
||||
const T = s => new Date(`2026-10-26T${s}:00+01:00`).toISOString();
|
||||
const hm = iso => new Date(iso).toLocaleTimeString('fr-BE', { hour: '2-digit', minute: '2-digit' });
|
||||
const N = { 1: 'Ébange - Accès Sud', 2: 'Ébange - Jonction Nord', 3: 'Thionville - Bât Voyageurs', 4: 'Thionville-Faisceau Est', 5: 'Thionville - Bif L3/L7', 9: 'Conflans-Jarny' };
|
||||
const P = (id, loc, pt, at, ct, st, cur) => ({ id, locationId: loc, plannedTime: T(pt), actualTime: at ? T(at) : undefined, calculatedTime: ct ? T(ct) : undefined, plannedStatus: st, currentLocation: !!cur });
|
||||
const train = { header: { id: 7, otn: 42926, running: true,
|
||||
origin: { locationId: 1, plannedTime: T('07:32'), actualTime: T('07:32') },
|
||||
current: { id: 'v', locationId: 3, actualTime: T('13:19'), runningDeltaForDisplay: -1 },
|
||||
destination: { locationId: 9, plannedTime: T('17:00'), calculatedTime: T('17:00') } },
|
||||
sections: [{ trainDetails: [P('a', 1, '13:17', '13:16', null, 'PASSING'), P('j', 2, '13:18', '13:17', null, 'PASSING'), P('v', 3, '13:21', '13:19', null, 'PASSING', true)] },
|
||||
{ trainDetails: [P('fa', 4, '13:23', null, '13:26', 'ARRIVAL'), P('fd', 4, '16:01', null, '16:04', 'DEPARTURE'), P('b', 5, '16:09', null, '16:12', 'PASSING')] }] };
|
||||
const pts = c.compactDetails(train);
|
||||
const at = now => c.classify(train.header, { now: Date.parse(T(now)), cfg: { yellowFromMin: 5, redFromMin: 15 }, locName: id => N[id], details: { 7: { points: pts } } });
|
||||
|
||||
let r = at('13:22');
|
||||
ok(r.next.name === 'Thionville-Faisceau Est' && !r.next.atStop && r.next.stop && hm(r.next.stop.depPlanned) === '16:01', '13:22 : prochain point = arrivée Faisceau Est, arrêt jusqu\'à 16:01');
|
||||
r = at('14:22');
|
||||
ok(r.next.atStop && hm(r.next.estimatedTime) === '16:04', `14:22 (arrivée non pointée) : à l'arrêt, départ attendu ${hm(r.next.estimatedTime)}`);
|
||||
ok(r.overdueMin < 0, `14:22 : plus de faux « dépassé 59 min » (overdue ${r.overdueMin})`);
|
||||
r = at('16:25');
|
||||
ok(r.next.atStop && r.overdueMin === 21, `16:25 sans pointage : en retard sur le départ de ${r.overdueMin} min`);
|
||||
// lieu non répété : comportement inchangé
|
||||
const t2 = JSON.parse(JSON.stringify(train)); t2.sections[1].trainDetails.splice(1, 1);
|
||||
const r2 = c.classify(t2.header, { now: Date.parse(T('14:22')), cfg: { yellowFromMin: 5, redFromMin: 15 }, locName: id => N[id], details: { 7: { points: c.compactDetails(t2) } } });
|
||||
ok(!r2.next.stop && r2.overdueMin > 50, 'passage simple non pointé : toujours signalé dépassé');
|
||||
// causes de retard : toutes celles du détail (onglet Statistiques), triées, sans doublon avec l'en-tête
|
||||
const D = (id, d, code, loc, t) => ({ id, delay: d, delayCauseCode: code, delayCause: code, locationId: loc, locationImCode: '0087', time: T(t) });
|
||||
const full = JSON.parse(JSON.stringify(train));
|
||||
full.sections[0].trainDetails[0].trainDelays = [D(1, 32, '61', 1, '08:11')];
|
||||
full.sections[0].trainDetails[1].trainDelays = [D(2, 7, '92', 2, '08:36'), D(3, 6, '92', 2, '10:44')];
|
||||
full.header.current.trainDelays = [D(3, 6, '92', 2, '10:44')];
|
||||
const causes = c.compactCauses(full);
|
||||
const cl = c.delayCauses(full.header, id => N[id], causes);
|
||||
ok(causes.length === 3 && cl.length === 3, `3 causes lues dans le détail, doublon de l'en-tête ignoré (${cl.length})`);
|
||||
ok(cl[0].code === '61' && cl[2].code === '92' && cl[2].delay === 6, 'triées de la plus ancienne à la plus récente (dernière : +6 · 92)');
|
||||
const rc = c.classify(full.header, { now: Date.parse(T('14:22')), cfg: { yellowFromMin: 5, redFromMin: 15 }, locName: id => N[id], details: { 7: { points: pts, causes } } });
|
||||
ok(rc.delays.length === 3, 'classify : les causes du cache arrivent dans la ligne');
|
||||
@@ -0,0 +1,17 @@
|
||||
// Lance tous les tests : node tests/run.js
|
||||
// Chaque test charge le code de l'extension (core.js / background.js) avec un faux « chrome » et un faux TIS.
|
||||
const { execFileSync } = require('child_process');
|
||||
const fs = require('fs'), path = require('path');
|
||||
const root = path.join(__dirname, '..');
|
||||
let ok = 0, ko = 0;
|
||||
for (const f of fs.readdirSync(__dirname).filter(f => f.endsWith('.test.js')).sort()) {
|
||||
let out;
|
||||
try { out = execFileSync(process.execPath, [path.join(__dirname, f), root], { encoding: 'utf8' }); }
|
||||
catch (e) { out = (e.stdout || '') + (e.stderr || ''); if (!/FAIL/.test(out)) out += '\nFAIL (erreur d\'exécution)'; }
|
||||
const pass = (out.match(/^OK/gm) || []).length, fail = (out.match(/FAIL/g) || []).length;
|
||||
ok += pass; ko += fail;
|
||||
console.log(`${fail ? '✗' : '✓'} ${f.padEnd(32)} ${pass} OK${fail ? ` · ${fail} échec(s)` : ''}`);
|
||||
if (fail) console.log(out.split('\n').filter(l => /FAIL/.test(l)).map(l => ' ' + l).join('\n'));
|
||||
}
|
||||
console.log(`\n${ok} OK · ${ko} échec(s)`);
|
||||
process.exitCode = ko ? 1 : 0;
|
||||