Files
2026-04-02 14:15:26 +02:00

271 lines
9.5 KiB
Plaintext

<app>
<!--
Composant racine — routeur SPA basé sur les ancres URL (#/)
3 vues : 'search' | 'detail' | 'comparateur'
-->
<header class="site-header">
<div class="header-inner">
<a class="logo" href="#/">
<span class="logo-icon"></span>
<span class="logo-text">Parcoursup <span class="logo-light">Explorer</span></span>
</a>
<div class="header-right">
<!-- Badge cliquable vers le comparateur, visible si au moins 1 formation sélectionnée -->
<a href="#/comparateur" class="header-badge badge-clickable" if={ state.selectedFormations.length > 0 }>
{ state.selectedFormations.length } sélection(s)
</a>
<auth-panel user={ state.user } onauth={ surConnexion } onlogout={ surDeconnexion }></auth-panel>
</div>
</div>
</header>
<div class="page">
<!-- VUE RECHERCHE -->
<div if={ state.view === 'search' }>
<search-bar onsearch={ lancerRecherche }></search-bar>
<p class="result-count" if={ state.hasSearched && !state.loading }>
<b>{ state.query }</b> — { state.total } résultat(s)
</p>
<map-view results={ state.results }></map-view>
<div class="layout">
<div>
<result-list
results={ state.results }
hasSearched={ state.hasSearched }
loading={ state.loading }
ondetail={ afficherDetail }
onselect={ ajouterSelection }>
</result-list>
<!-- Pagination (visible si plus de résultats que la limite) -->
<div class="pagination" if={ state.total > state.limit }>
<button class="btn btn-outline" onclick={ pagePrecedente } disabled={ state.page === 1 }>
← Précédent
</button>
<span class="page-info">Page { state.page } / { nombreTotalPages() }</span>
<button class="btn btn-outline" onclick={ pageSuivante } disabled={ state.page === nombreTotalPages() }>
Suivant →
</button>
</div>
</div>
</div>
</div>
<!-- VUE DÉTAIL -->
<div if={ state.view === 'detail' && state.selected }>
<detail-view formation={ state.selected } onback={ retourRecherche }></detail-view>
</div>
<div if={ state.view === 'detail' && !state.selected } class="message">
Chargement de la formation...
</div>
<!-- VUE COMPARATEUR -->
<div if={ state.view === 'comparateur' }>
<button class="btn btn-outline" onclick={ retourRecherche } style="margin-bottom: 16px;">← Retour à la recherche</button>
<comparateur-view
formations={ state.selectedFormations }
onretirer={ retirerSelection }
onvider={ viderSelection }>
</comparateur-view>
</div>
</div>
<script>
export default {
state: {
view: 'search',
loading: false,
hasSearched: false,
results: [],
selected: null,
selectedFormations: [],
query: '',
filters: {},
page: 1,
limit: 20,
total: 0,
user: null
},
onMounted() {
var saved = localStorage.getItem('selectionFormations');
var soi = this;
// Restaurer la sélection depuis le localStorage
if (saved) {
try { this.state.selectedFormations = JSON.parse(saved); }
catch (e) { console.error('Erreur localStorage :', e); }
}
// Écouter les changements de session Firebase
window.firebaseServices.onUserChanged(function(user) {
soi.update({ user: user });
// À la connexion, on charge la sélection depuis Firestore
if (user) {
window.firebaseServices.loadUserData(user.uid)
.then(function(donnees) {
if (donnees && donnees.selection) {
soi.update({ selectedFormations: donnees.selection });
localStorage.setItem('selectionFormations', JSON.stringify(donnees.selection));
}
})
.catch(function(err) { console.error('Erreur Firestore :', err); });
}
});
// Écouter les changements d'URL pour le routage
window.addEventListener('hashchange', function() { soi.gererRoute(); });
this.gererRoute();
},
surConnexion() {
// Géré automatiquement par onUserChanged ci-dessus
},
surDeconnexion() {
this.update({ selectedFormations: [] });
localStorage.removeItem('selectionFormations');
},
// Sauvegarde la sélection en local ET dans Firestore si connecté
async sauvegarderSelection(selection) {
localStorage.setItem('selectionFormations', JSON.stringify(selection));
if (this.state.user) {
try { await window.firebaseServices.saveUserData(this.state.user.uid, { selection }); }
catch (err) { console.error('Erreur sauvegarde :', err); }
}
},
// Lit l'ancre URL et affiche la vue correspondante
gererRoute() {
var ancre = window.location.hash || '#/';
var chemin = ancre.slice(1) || '/';
if (chemin.startsWith('/formation/')) {
var id = decodeURIComponent(chemin.replace('/formation/', ''));
this.update({ view: 'detail' });
this.chargerFormationParId(id);
} else if (chemin === '/comparateur') {
this.update({ view: 'comparateur', selected: null });
} else {
this.update({ view: 'search', selected: null });
}
},
// Cherche la formation dans le cache (résultats / sélection) avant de faire un appel API
async chargerFormationParId(id) {
var i;
for (i = 0; i < this.state.results.length; i++) {
if (this.state.results[i].id === id) { this.update({ selected: this.state.results[i] }); return; }
}
for (i = 0; i < this.state.selectedFormations.length; i++) {
if (this.state.selectedFormations[i].id === id) { this.update({ selected: this.state.selectedFormations[i] }); return; }
}
// En dernier recours : appel API avec un mot-clé extrait de l'ID
try {
var motCle = id.split('-').slice(1).join(' ').substring(0, 30);
if (motCle) {
var donnees = await window.chargerFormations(motCle, 10, 0);
if (donnees.results && donnees.results.length > 0) {
for (i = 0; i < donnees.results.length; i++) {
var f = window.creerFormation(donnees.results[i]);
if (f.id === id) { this.update({ selected: f }); return; }
}
this.update({ selected: window.creerFormation(donnees.results[0]) });
}
}
} catch (erreur) { console.error('Erreur chargement formation :', erreur); }
},
afficherDetail(index) {
var formation = this.state.results[index];
this.update({ selected: formation, view: 'detail' });
window.location.hash = '#/formation/' + encodeURIComponent(formation.id);
},
retourRecherche() {
window.location.hash = '#/';
},
async lancerRecherche(requete, filtres) {
this.update({ loading: true, hasSearched: true, selected: null, view: 'search', query: requete, filters: filtres || {}, page: 1 });
window.location.hash = '#/';
await this.chargerPage(1);
},
// Charge la page demandée en calculant l'offset (décalage) correspondant
async chargerPage(page) {
this.update({ loading: true });
try {
var decalage = (page - 1) * this.state.limit;
var donnees = await window.chargerFormations(this.state.query, this.state.limit, decalage, this.state.filters);
var formations = [];
if (donnees.results) {
for (var i = 0; i < donnees.results.length; i++) {
formations.push(window.creerFormation(donnees.results[i]));
}
}
this.update({ results: formations, total: donnees.total_count || 0, page, loading: false });
} catch (erreur) {
console.error(erreur);
this.update({ results: [], total: 0, loading: false });
}
},
nombreTotalPages() {
return Math.ceil(this.state.total / this.state.limit);
},
async pageSuivante() {
if (this.state.page < this.nombreTotalPages()) { await this.chargerPage(this.state.page + 1); }
},
async pagePrecedente() {
if (this.state.page > 1) { await this.chargerPage(this.state.page - 1); }
},
// Ajoute la formation au comparateur si elle n'y est pas déjà
ajouterSelection(index) {
var formation = this.state.results[index];
var selection = this.state.selectedFormations.slice();
for (var i = 0; i < selection.length; i++) {
if (selection[i].id === formation.id) { return; } // doublon
}
selection.push(formation);
this.update({ selectedFormations: selection });
this.sauvegarderSelection(selection);
},
// Retire la formation avec cet id de la sélection
retirerSelection(id) {
var nouvelle = this.state.selectedFormations.filter(function(f) { return f.id !== id; });
this.update({ selectedFormations: nouvelle });
this.sauvegarderSelection(nouvelle);
},
viderSelection() {
this.update({ selectedFormations: [] });
this.sauvegarderSelection([]);
}
};
</script>
</app>