import { api } from './core/api.js'; import { h, mount, qs } from './core/dom.js'; import { onStatus, resetSubscriptions, startLive } from './core/live.js'; import { activePath, highlight } from './core/nav.js'; import { bindPalette, openPalette } from './core/palette.js'; import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js'; /** Shell, navigation and hash routing of the dashboard (M16-T11). */ const LEVELS = { USER: 0, STAFF: 1, DEV: 2, OWNER: 3 }; /** * `module` is imported on demand, so a view is only downloaded when visited. * `level` hides a page the visitor could not use anyway; the server enforces it too. */ const ROUTES = [ { path: '', icon: '◎', label: 'Vue d’ensemble', group: 'Pilotage', module: './views/overview.js', level: LEVELS.STAFF, }, { path: 'tasks', icon: '✓', label: 'Mes tâches', group: 'Pilotage', module: './views/tasks.js', level: LEVELS.STAFF, }, { path: 'org', icon: '⬡', label: 'Organisation', group: 'Pilotage', module: './views/organization.js', level: LEVELS.STAFF, }, { path: 'projects', icon: '▦', label: 'Projets', group: 'Pilotage', module: './views/projects.js', level: LEVELS.STAFF, }, { path: 'repos', icon: '◫', label: 'Dépôts', group: 'Code', module: './views/repositories.js', level: LEVELS.STAFF, }, { path: 'releases', icon: '⬀', label: 'Releases', group: 'Code', module: './views/releases.js', level: LEVELS.STAFF, }, { path: 'deploy', icon: '⚙', label: 'Déploiements', group: 'Code', module: './views/deployments.js', level: LEVELS.STAFF, }, { path: 'discord', icon: '☰', label: 'Serveur Discord', group: 'Communauté', module: './views/discord.js', level: LEVELS.STAFF, }, { path: 'community', icon: '✦', label: 'Tickets & vocaux', group: 'Communauté', module: './views/community.js', level: LEVELS.STAFF, }, { path: 'wiki', icon: '📖', label: 'Wiki', group: 'Communauté', module: './views/wiki.js', level: LEVELS.STAFF, }, { path: 'logs', icon: '≡', label: 'Journaux', group: 'Système', module: './views/logs.js', level: LEVELS.STAFF, advanced: true, }, { path: 'settings', icon: '⚒', label: 'Paramètres', group: 'Système', module: './views/settings.js', level: LEVELS.STAFF, }, { path: 'setup', icon: '✎', label: 'Configuration .env', group: 'Système', module: './views/setup.js', level: LEVELS.OWNER, }, ]; export const state = { me: null, config: null, mode: localStorage.getItem('fws.mode') ?? 'simple', theme: localStorage.getItem('fws.theme') ?? 'dark', /** Repository selected in the Releases and Deployments pages. */ repository: localStorage.getItem('fws.repository') ?? '', }; export function setMode(mode) { state.mode = mode; localStorage.setItem('fws.mode', mode); document.body.dataset.mode = mode; render(); } export function setTheme(theme) { state.theme = theme; localStorage.setItem('fws.theme', theme); document.documentElement.dataset.theme = theme; } export function setRepository(fullName) { state.repository = fullName; localStorage.setItem('fws.repository', fullName); } export const navigate = (path) => { window.location.hash = `#/${path}`; }; const currentRoute = () => { const raw = window.location.hash.replace(/^#\/?/, ''); const [path] = raw.split('?'); const segments = path.split('/').filter(Boolean); return { segments, path, active: activePath(window.location.hash) }; }; /** * Marks the current entry in the sidebar and retitles the tab. * * Navigation only swaps the main area, so the highlight has to be refreshed on * its own — otherwise it keeps pointing at the page you arrived on. */ function highlightNav(scope = document) { const active = highlight(scope, window.location.hash); const route = ROUTES.find((entry) => entry.path === active); document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot'; } const LIVE_LABELS = { live: 'À jour en direct', connecting: 'Connexion…', reconnecting: 'Reconnexion…', polling: 'Rafraîchissement périodique', paused: 'En pause (onglet en arrière-plan)', idle: 'Hors ligne', }; let stopWatchingStatus = null; /** Small footer badge: says whether the page is following the bot live. */ function liveIndicator() { const dot = h('span', { class: 'live-dot' }); const label = h('span', { text: LIVE_LABELS.idle }); const node = h('div', { class: 'live', title: 'État de la mise à jour automatique' }, dot, label); stopWatchingStatus?.(); stopWatchingStatus = onStatus(({ status, lastEventAt }) => { node.dataset.status = status; label.textContent = LIVE_LABELS[status] ?? status; if (lastEventAt) { node.title = `Dernière mise à jour à ${lastEventAt.toLocaleTimeString('fr-FR')}`; } }); return node; } /** * Pages the visitor can actually reach. Shared with the palette so a search * never offers a page that would answer with « niveau d’accès supérieur ». */ function visibleRoutes() { return ROUTES.filter( (route) => (state.me?.accessLevel ?? 0) >= route.level && (!route.advanced || state.mode === 'advanced'), ); } const SHORTCUT = navigator.userAgent.includes('Mac') ? '⌘K' : 'Ctrl+K'; function sidebar() { const visible = visibleRoutes(); const groups = []; for (const route of visible) { let group = groups.find((entry) => entry.name === route.group); if (!group) groups.push((group = { name: route.group, routes: [] })); group.routes.push(route); } return h( 'aside', { class: 'sidebar' }, h( 'a', { class: 'brand', href: '#/' }, h('img', { src: 'favicon.svg', alt: '' }), h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })), ), h( 'button', { class: 'nav-search', type: 'button', onClick: () => openPalette(visibleRoutes()), title: `Recherche globale (${SHORTCUT})`, }, h('span', { class: 'nav-icon', text: '⌕' }), h('span', { text: 'Rechercher' }), h('kbd', { text: SHORTCUT }), ), h( 'nav', { class: 'nav' }, groups.map((group) => [ h('div', { class: 'nav-group', text: group.name }), group.routes.map((route) => h( 'a', { href: `#/${route.path}`, dataset: { route: route.path } }, h('span', { class: 'nav-icon', text: route.icon }), h('span', { text: route.label }), // A page you have to open to know whether it needs you is a page // you stop opening; the count is what makes it a morning habit. route.path === 'tasks' && h('span', { class: 'nav-count', hidden: true }), ), ), ]), ), h( 'div', { class: 'sidebar-foot' }, h( 'div', { class: 'mode-switch', role: 'group', 'aria-label': 'Mode d’affichage' }, button('Simple', () => setMode('simple'), {}), button('Avancé', () => setMode('advanced'), {}), ), liveIndicator(), h('div', { class: 'build muted', text: '…' }), h( 'div', { class: 'viewer' }, state.me.avatar && h('img', { src: state.me.avatar, alt: '' }), h( 'div', {}, h('strong', { text: state.me.displayName ?? state.me.username ?? 'Invité' }), h('span', { class: 'muted', text: ACCESS_LABELS[state.me.accessLevel] ?? '—' }), ), ), h( 'div', { class: 'row' }, button( state.theme === 'dark' ? '☀ Clair' : '☾ Sombre', () => { setTheme(state.theme === 'dark' ? 'light' : 'dark'); render(); }, { tone: 'ghost' }, ), button( 'Déconnexion', async () => { await api.post('/api/auth/logout'); window.location.reload(); }, { tone: 'ghost' }, ), ), ), ); } function applyModeButtons(node) { for (const control of node.querySelectorAll('.mode-switch button')) { control.classList.toggle( 'active', control.textContent === (state.mode === 'simple' ? 'Simple' : 'Avancé'), ); } } async function renderView(host) { const { segments } = currentRoute(); const route = ROUTES.find((entry) => entry.path === (segments[0] ?? '')); resetSubscriptions(); highlightNav(); refreshTaskCount(); host.scrollIntoView?.({ block: 'start' }); if (!route) { mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' }))); return; } if (state.me.accessLevel < route.level) { mount( host, h( 'div', { class: 'notice notice-error' }, h('p', { text: 'Cette page demande un niveau d’accès supérieur.' }), ), ); return; } mount(host, spinner()); try { const module = await import(route.module); await module.render(host, { params: segments.slice(1), state }); } catch (error) { console.error('[fws] échec de la vue', error); const { errorBox } = await import('./core/ui.js'); mount(host, errorBox(error.message, { retry: () => renderView(host), error })); } } export function render() { const app = qs('#app'); if (!state.me?.authenticated) { import('./views/login.js').then((module) => module.render(app, { state })); return; } // The bootstrap session may only reach the wizard, so it never gets a shell. if (state.me.source === 'setup') { import('./views/setup.js').then((module) => module.render(app, { state, standalone: true })); return; } const main = h('main', { class: 'main' }); const shell = h('div', { class: 'shell' }, sidebar(), main); mount(app, shell); applyModeButtons(shell); highlightNav(shell); refreshTaskCount(); renderView(main); } /** * Open cards assigned to the viewer, shown on the sidebar entry. * * Asked for with `issues=0`: the counter needs a number, not a round trip to * the forge to resolve every linked issue. Throttled, because navigating is not * a reason to ask again. */ const TASK_COUNT_TTL_MS = 60_000; let taskCountAt = 0; async function refreshTaskCount(force = false) { if (!qs('.nav-count')) return; if (!force && Date.now() - taskCountAt < TASK_COUNT_TTL_MS) return; taskCountAt = Date.now(); const data = await api.get('/api/me/tasks', { issues: '0' }).catch(() => null); // The shell may have been rebuilt while the request was in flight. const node = qs('.nav-count'); if (!node || !data) return; const { open, overdue } = data.counts; node.textContent = open > 99 ? '99+' : String(open); node.hidden = open === 0; node.dataset.tone = overdue > 0 ? 'late' : 'normal'; node.title = overdue > 0 ? `${overdue} carte(s) en retard` : `${open} carte(s) à faire`; } document.addEventListener('fws:tasks-changed', () => refreshTaskCount(true)); /** Names the interface actually being served, archive deployments being easy to get wrong. */ async function showBuild() { const health = await api.get('/api/health').catch(() => null); const node = qs('.build'); if (!node || !health) return; const built = health.buildAt ? new Date(health.buildAt).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' }) : 'date inconnue'; node.textContent = `v${health.version} · interface du ${built}`; node.title = "Date du fichier d'interface le plus récent servi par le bot."; } async function boot() { document.body.dataset.mode = state.mode; document.documentElement.dataset.theme = state.theme; const [me, config] = await Promise.all([ api.get('/api/me').catch(() => ({ authenticated: false })), api.get('/api/auth/config').catch(() => ({})), ]); state.me = me; state.config = config; startLive(); showBuild(); bindPalette(visibleRoutes); window.addEventListener('hashchange', () => { const main = qs('.main'); // Without the shell in place there is nothing to swap, so rebuild the page. if (main && state.me?.authenticated && state.me.source !== 'setup') renderView(main); else render(); }); window.addEventListener('unhandledrejection', (event) => { if (event.reason?.status === 401) { state.me = { authenticated: false }; render(); } else if (event.reason instanceof Error) toast(event.reason.message, 'error'); }); render(); } boot();