Files
FWS-DiscordBot/src/web/public/core/ui.js
T
nocodeandClaude Opus 5 a1fb846d51 fix(web): stop the settings page breaking on an unexpected payload
Every list the page walks was read straight off the response, so a single
missing field took the whole view down with `undefined.map` — which reads as
a broken feature rather than as what it is, a page and an API disagreeing on
the shape of the data.

The page now normalises what it receives: absent lists render empty, an enum
without options falls back to a text field, and settings that arrive without
sections are shown under one heading instead of not at all.

Errors of that family also say so, and point at the reload that fixes them.

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

269 lines
8.6 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));
export const errorBox = (message, { retry } = {}) =>
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.',
}),
),
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 };