Files
FWS-DiscordBot/src/web/public/core/ui.js
T
nocodeandClaude Opus 5 c031b4d9e2 fix(web): keep the stack when a view fails
Views caught their errors and showed only the message, so nothing said which
module or which line had failed — neither in the console, which never saw
the error, nor on the page.

The stack is now logged and offered on the page behind a disclosure, because
opening the developer console is not always an option on a self-hosted
panel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00

283 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.', rowHref = null } = {}) {
if (!rows || rows.length === 0) {
// An empty state is where people look for the action that fills it, so it
// accepts a node and not only a sentence.
return empty instanceof Node
? h('div', { class: 'empty' }, empty)
: 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) => {
const target = rowHref?.(row) ?? null;
const line = h(
'tr',
target ? { class: 'row-link', tabindex: '0', role: 'link' } : {},
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;
}),
);
if (target) {
// A control inside the row keeps its own behaviour; only the empty
// space navigates.
const open = (event) => {
if (event.target.closest('a, button, input, select, textarea, label')) return;
window.location.hash = target.replace(/^#/, '');
};
line.addEventListener('click', open);
line.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
open(event);
}
});
}
return line;
}),
),
),
);
}
export const spinner = (label = 'Chargement…') =>
h('div', { class: 'loading' }, h('span', { class: 'spinner' }), h('span', { text: label }));
/**
* A `undefined is not a function` reaching the screen almost always means the
* page and the API disagree on the shape of the data — which reads as a broken
* feature unless the box says otherwise.
*/
const looksLikeVersionMismatch = (message) =>
/Cannot read propert|undefined is not|is not a function|of undefined/i.test(String(message));
/**
* `error` carries the stack; `message` alone leaves nobody able to say where it
* came from. Showing it on the page matters for a self-hosted panel, where
* opening the developer console is not always an option.
*/
export const errorBox = (message, { retry, error = null } = {}) =>
h(
'div',
{ class: 'notice notice-error' },
h(
'div',
{},
h('p', { text: message }),
looksLikeVersionMismatch(message) &&
h('p', {
class: 'muted',
text: 'Cette erreur vient en général d’une interface plus ancienne que l’API : recharge avec Ctrl+Shift+R, et si elle persiste, re-téléverse le dossier src/web/public.',
}),
error?.stack &&
h(
'details',
{},
h('summary', { text: 'Détails techniques' }),
h('pre', {}, h('code', { text: error.stack })),
),
),
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) {
// Swallowing the stack leaves a failure impossible to place.
console.error('[fws] échec du rendu', error);
mount(host, errorBox(error.message, { retry: () => renderAsync(host, load, build), error }));
}
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 };