feat(web): serve the dashboard and its interface

The front-end is plain JavaScript served as is: no build step to run before
the bot starts, and no second toolchain to keep alive. A simple/advanced
switch hides the technical panels without ever standing in for a permission.

`npm run setup` starts the wizard alone, because the bot refuses to boot
without a token and the `.env` has to be writable from somewhere. When the
webhook and the dashboard share a port, a single HTTP server is started.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 20:09:14 +02:00
1 parent bf92badb05
commit 06a9be0cba
23 files changed
+5850 -2

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
/** Typed-ish client for the dashboard API (M16-T11). */
export class ApiError extends Error {
constructor(status, message, details) {
super(message);
this.name = 'ApiError';
this.status = status;
this.details = details;
}
}
async function request(method, path, body) {
const response = await fetch(path, {
method,
headers: {
Accept: 'application/json',
...(body !== undefined && { 'Content-Type': 'application/json' }),
// Required by the server for every write: a cross-site form cannot set it.
'X-Requested-With': 'fws-dashboard',
},
body: body === undefined ? undefined : JSON.stringify(body),
credentials: 'same-origin',
});
const payload = await response.json().catch(() => null);
if (!response.ok) {
throw new ApiError(response.status, payload?.error ?? `Erreur ${response.status}`, payload?.details);
}
return payload;
}
const withQuery = (path, params) => {
const search = new URLSearchParams(
Object.entries(params ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== ''),
).toString();
return search ? `${path}?${search}` : path;
};
export const api = {
get: (path, params) => request('GET', withQuery(path, params)),
post: (path, body = {}) => request('POST', path, body),
put: (path, body = {}) => request('PUT', path, body),
patch: (path, body = {}) => request('PATCH', path, body),
delete: (path, body = {}) => request('DELETE', path, body),
};
export const encodeRepo = (fullName) =>
String(fullName)
.split('/')
.map((part) => encodeURIComponent(part))
.join('/');
+122
View File
@@ -0,0 +1,122 @@
/**
* Minimal DOM helpers. No framework, no build step: the dashboard ships the
* files it serves (M16-T11).
*/
/**
* `h('div', { class: 'card' }, h('h2', { text: 'Titre' }))`
* Text always goes through `textContent`, so API values can never inject markup.
*/
export function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props ?? {})) {
if (value === null || value === undefined || value === false) continue;
if (key === 'text') node.textContent = String(value);
else if (key === 'class') node.className = value;
else if (key === 'dataset') Object.assign(node.dataset, value);
else if (key === 'style') Object.assign(node.style, value);
else if (key.startsWith('on') && typeof value === 'function') {
node.addEventListener(key.slice(2).toLowerCase(), value);
} else if (key === 'value' || key === 'checked' || key === 'disabled' || key === 'selected') {
node[key] = value;
} else node.setAttribute(key, value === true ? '' : String(value));
}
for (const child of children.flat(Infinity)) {
if (child === null || child === undefined || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
export const clear = (node) => {
while (node.firstChild) node.firstChild.remove();
return node;
};
export const mount = (node, ...children) => {
clear(node);
node.append(...children.flat(Infinity).filter(Boolean));
return node;
};
export const qs = (selector, scope = document) => scope.querySelector(selector);
/** Escapes then applies the small subset of Markdown used by Gitea bodies. */
export function markdown(text) {
const escaped = String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;');
return escaped
.replace(/```([\s\S]*?)```/g, (_, code) => `<pre><code>${code.trim()}</code></pre>`)
.replace(/`([^`\n]+)`/g, '<code>$1</code>')
.replace(/^### (.+)$/gm, '<h4>$1</h4>')
.replace(/^## (.+)$/gm, '<h3>$1</h3>')
.replace(/^# (.+)$/gm, '<h3>$1</h3>')
.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
.replace(/^[-*] (.+)$/gm, '<li>$1</li>')
.replace(/(<li>[\s\S]*?<\/li>)/g, '<ul>$1</ul>')
.replace(/\n{2,}/g, '<br><br>');
}
/** Renders trusted Markdown built above; never call it with raw HTML. */
export function richText(text, className = 'rich') {
const node = h('div', { class: className });
node.innerHTML = markdown(text);
return node;
}
export const formatDate = (value) => {
if (!value) return '—';
const date = new Date(String(value).includes('T') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return String(value);
return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
};
export function formatRelative(value) {
if (!value) return '—';
const date = new Date(String(value).includes('T') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return String(value);
const seconds = Math.round((date.getTime() - Date.now()) / 1000);
const units = [
['year', 31_536_000],
['month', 2_592_000],
['day', 86_400],
['hour', 3600],
['minute', 60],
];
const formatter = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' });
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size) return formatter.format(Math.round(seconds / size), unit);
}
return formatter.format(seconds, 'second');
}
export const formatBytes = (bytes) => {
const value = Number(bytes) || 0;
const units = ['o', 'Ko', 'Mo', 'Go'];
let index = 0;
let result = value;
while (result >= 1024 && index < units.length - 1) {
result /= 1024;
index += 1;
}
return `${result.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
};
export const formatDuration = (ms) => {
const seconds = Math.floor(Number(ms) / 1000);
const days = Math.floor(seconds / 86_400);
const hours = Math.floor((seconds % 86_400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days} j ${hours} h`;
if (hours > 0) return `${hours} h ${minutes} min`;
if (minutes > 0) return `${minutes} min`;
return `${seconds} s`;
};
+227
View File
@@ -0,0 +1,227 @@
import { clear, h, mount } from './dom.js';
/** Shared widgets: cards, tables, badges, toasts, modals (M16-T11). */
export const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' };
export function card(title, { subtitle, actions, advanced = false } = {}, ...children) {
return h(
'section',
{ class: advanced ? 'card advanced-only' : 'card' },
(title || actions) &&
h(
'header',
{ class: 'card-head' },
h(
'div',
{},
title && h('h2', { text: title }),
subtitle && h('p', { class: 'muted', text: subtitle }),
),
actions && h('div', { class: 'card-actions' }, actions),
),
h('div', { class: 'card-body' }, ...children),
);
}
export const stat = (label, value, { hint, tone = 'neutral' } = {}) =>
h(
'div',
{ class: `stat stat-${tone}` },
h('span', { class: 'stat-label', text: label }),
h('strong', { class: 'stat-value', text: value ?? '—' }),
hint && h('span', { class: 'stat-hint', text: hint }),
);
export const badge = (text, tone = 'neutral') => h('span', { class: `badge badge-${tone}`, text });
export const button = (label, onClick, { tone = 'ghost', disabled = false, title, type = 'button' } = {}) =>
h('button', { class: `btn btn-${tone}`, onClick, disabled, title, type, text: label });
export function field(label, control, { help, error } = {}) {
return h(
'label',
{ class: error ? 'field field-error' : 'field' },
h('span', { class: 'field-label', text: label }),
control,
help && h('span', { class: 'field-help', text: help }),
error && h('span', { class: 'field-error-text', text: error }),
);
}
export const input = (props = {}) => h('input', { class: 'input', ...props });
export const textarea = (props = {}) => h('textarea', { class: 'input textarea', ...props });
export function select(options, props = {}) {
return h(
'select',
{ class: 'input', ...props },
options.map((option) =>
h('option', {
value: option.value,
text: option.label,
selected: option.value === props.value,
}),
),
);
}
export function toggle(checked, onChange, label) {
return h(
'label',
{ class: 'toggle' },
h('input', { type: 'checkbox', checked, onChange: (event) => onChange(event.target.checked) }),
h('span', { class: 'toggle-track' }),
label && h('span', { text: label }),
);
}
/**
* Renders a table. Each column is `{ key, label, render?, className? }`;
* `render` returns a Node or a string.
*/
export function table(columns, rows, { empty = 'Rien à afficher pour le moment.' } = {}) {
if (!rows || rows.length === 0) return h('p', { class: 'empty', text: empty });
return h(
'div',
{ class: 'table-wrap' },
h(
'table',
{ class: 'table' },
h(
'thead',
{},
h(
'tr',
{},
columns.map((column) => h('th', { class: column.className ?? '', text: column.label })),
),
),
h(
'tbody',
{},
rows.map((row) =>
h(
'tr',
{},
columns.map((column) => {
const cell = h('td', { class: column.className ?? '' });
const value = column.render ? column.render(row) : row[column.key];
if (value instanceof Node) cell.append(value);
else cell.textContent = value === null || value === undefined ? '—' : String(value);
return cell;
}),
),
),
),
),
);
}
export const spinner = (label = 'Chargement…') =>
h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label }));
export const errorBox = (message, { retry } = {}) =>
h(
'div',
{ class: 'notice notice-error' },
h('p', { text: message }),
retry && button('Réessayer', retry, { tone: 'ghost' }),
);
export const notice = (message, tone = 'info') =>
h('div', { class: `notice notice-${tone}` }, h('p', { text: message }));
let toastHost;
export function toast(message, tone = 'success') {
toastHost ??= document.body.appendChild(h('div', { class: 'toast-host' }));
const node = h('div', { class: `toast toast-${tone}`, text: message });
toastHost.append(node);
setTimeout(() => node.classList.add('toast-out'), 3600);
setTimeout(() => node.remove(), 4200);
}
/** Promise-based modal. Resolves with the value passed to `close`. */
export function modal(title, buildBody, { confirmLabel = 'Confirmer', tone = 'primary' } = {}) {
return new Promise((resolve) => {
const overlay = h('div', { class: 'overlay' });
const close = (value) => {
overlay.remove();
document.removeEventListener('keydown', onKey);
resolve(value);
};
const onKey = (event) => {
if (event.key === 'Escape') close(null);
};
const body = buildBody(close);
const footer = h(
'footer',
{ class: 'modal-foot' },
button('Annuler', () => close(null), { tone: 'ghost' }),
button(confirmLabel, () => close(body.submit ? body.submit() : true), { tone }),
);
overlay.append(
h(
'div',
{ class: 'modal' },
h('header', { class: 'modal-head' }, h('h2', { text: title })),
h('div', { class: 'modal-body' }, body.node ?? body),
footer,
),
);
overlay.addEventListener('click', (event) => {
if (event.target === overlay) close(null);
});
document.addEventListener('keydown', onKey);
document.body.append(overlay);
const firstInput = overlay.querySelector('input, textarea, select');
firstInput?.focus();
});
}
/** Confirmation that requires typing an exact phrase, for irreversible actions. */
export function confirmDangerous(title, message, phrase) {
return modal(
title,
() => {
const control = input({ placeholder: phrase, autocomplete: 'off' });
const node = h(
'div',
{},
h('p', { text: message }),
h('p', { class: 'muted', text: `Tape « ${phrase} » pour confirmer.` }),
control,
);
return { node, submit: () => control.value.trim() === phrase };
},
{ confirmLabel: 'Supprimer', tone: 'danger' },
);
}
export const confirmAction = (title, message) =>
modal(title, () => ({ node: h('p', { text: message }), submit: () => true }));
/**
* Renders an async view into a host node, showing a loader then the result.
* Any thrown error becomes a retry box instead of a blank page.
*/
export async function renderAsync(host, load, build) {
mount(host, spinner());
try {
const data = await load();
mount(host, await build(data));
} catch (error) {
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build) }));
}
return host;
}
export const section = (...children) => h('div', { class: 'stack' }, ...children);
export const row = (...children) => h('div', { class: 'row' }, ...children);
export const grid = (...children) => h('div', { class: 'grid' }, ...children);
export { clear, mount };