Files
FWS-DiscordBot/src/web/public/views/wiki.js
T
nocodeandClaude Opus 5 748a8c19e1 feat(wiki): add the reading site and its editor
The renderer escapes HTML before any transformation and drops
`javascript:` links. Pages are written by the team, but a renderer that
relies on that is one mistake away from being a hole.

The editor previews as you type: legal pages are long, and writing Markdown
blind is how broken tables end up published.

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

241 lines
8.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 { api } from '../core/api.js';
import { formatRelative, h } from '../core/dom.js';
import { autoRefresh } from '../core/live.js';
import { render as renderMarkdown } from '../core/markdown.js';
import {
badge,
button,
card,
confirmAction,
field,
input,
notice,
renderAsync,
table,
textarea,
toast,
toggle,
} from '../core/ui.js';
/** Editing the public documentation from the panel (M17). */
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
const slugify = (text) =>
text
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 80);
/**
* Editor with a live preview: legal pages are long, and writing Markdown blind
* is how broken tables end up published.
*/
async function editPage(existing, reload) {
const title = input({ value: existing?.title ?? '', placeholder: 'Titre de la page' });
const slug = input({ value: existing?.slug ?? '', placeholder: 'adresse-de-la-page' });
const summary = input({ value: existing?.summary ?? '', placeholder: 'Une phrase de résumé' });
const category = input({ value: existing?.category ?? 'Général', placeholder: 'Général' });
const position = input({ type: 'number', value: existing?.position ?? 0 });
const content = textarea({ value: existing?.content ?? '', style: { minHeight: '22rem' } });
let published = existing?.published ?? false;
// A new page gets its address from its title until the address is touched.
let slugTouched = Boolean(existing);
slug.addEventListener('input', () => (slugTouched = true));
title.addEventListener('input', () => {
if (!slugTouched) slug.value = slugify(title.value);
});
const preview = h('div', { class: 'wiki-content' });
const refreshPreview = () => {
preview.innerHTML = renderMarkdown(content.value).html;
};
content.addEventListener('input', refreshPreview);
refreshPreview();
const showPreview = h('div', { class: 'wiki-preview' }, preview);
showPreview.hidden = true;
const { modal } = await import('../core/ui.js');
const confirmed = await modal(
existing ? `Modifier « ${existing.title} »` : 'Nouvelle page',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Titre', title),
field('Adresse', slug, { help: 'Minuscules, chiffres et tirets. Visible dans l’URL : /wiki/…' }),
field('Résumé', summary, { help: 'Affiché sous le titre et dans les résultats de recherche.' }),
field('Catégorie', category, { help: 'Regroupe les pages dans le menu du site public.' }),
field('Position', position, { help: 'Ordre dans la catégorie, du plus petit au plus grand.' }),
field('Contenu (Markdown)', content),
button(
'Afficher / masquer l’aperçu',
() => {
showPreview.hidden = !showPreview.hidden;
refreshPreview();
},
{ tone: 'ghost' },
),
showPreview,
toggle(published, (checked) => (published = checked), 'Publier (visible par tout le monde)'),
existing?.protected &&
notice('Page protégée : son contenu est modifiable, mais elle ne peut pas être supprimée.', 'info'),
),
submit: () => title.value.trim().length >= 2 && slug.value.trim() !== '',
}),
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
);
if (!confirmed) return;
const payload = {
title: title.value.trim(),
slug: slug.value.trim(),
summary: summary.value.trim(),
category: category.value.trim() || 'Général',
position: Number(position.value) || 0,
content: content.value,
published,
};
try {
if (existing) await api.patch(`/api/wiki/admin/${existing.id}`, payload);
else await api.post('/api/wiki/admin', payload);
toast(existing ? 'Page enregistrée.' : 'Page créée.');
reload();
} catch (error) {
toast(error.message, 'error');
}
}
export function render(host, { state }) {
const level = state.me.accessLevel;
const reload = () => render(host, { state });
autoRefresh(reload, { topics: ['mutation'] });
return renderAsync(
host,
() => api.get('/api/wiki/admin'),
(data) => {
const published = data.pages.filter((page) => page.published).length;
return h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('h1', { text: 'Wiki' }),
h('p', {
class: 'muted',
text: 'Documentation publique, écrite ici et lisible sans compte sur /wiki.',
}),
),
h(
'div',
{ class: 'row' },
h('a', {
class: 'btn btn-ghost',
href: '/wiki',
target: '_blank',
rel: 'noreferrer',
text: '↗ Voir le site',
}),
level >= LEVELS.DEV && button('Nouvelle page', () => editPage(null, reload), { tone: 'primary' }),
),
),
published === 0 &&
notice('Aucune page publiée : le site public affichera une documentation vide.', 'warning'),
card(
'Pages',
{ subtitle: `${data.pages.length} page(s), dont ${published} publiée(s)` },
table(
[
{
label: 'Page',
render: (page) =>
h(
'div',
{},
h('strong', { text: page.title }),
h('div', { class: 'muted', text: page.summary || `/wiki/${page.slug}` }),
),
},
{ label: 'Catégorie', render: (page) => badge(page.category, 'info') },
{ label: 'Ordre', className: 'num advanced-only', key: 'position' },
{
label: 'État',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published ? badge('Publiée', 'success') : badge('Brouillon', 'neutral'),
page.protected && badge('Protégée', 'warning'),
),
},
{
label: 'Modifiée',
className: 'nowrap',
render: (page) => formatRelative(page.updatedAt),
},
{
label: '',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published &&
h('a', {
class: 'btn btn-ghost btn-sm',
href: `/wiki/${page.slug}`,
target: '_blank',
rel: 'noreferrer',
text: 'Voir',
}),
level >= LEVELS.DEV &&
button('Modifier', () => editPage(page, reload), { tone: 'ghost' }),
level >= LEVELS.DEV &&
button(
page.published ? 'Dépublier' : 'Publier',
async () => {
await api.patch(`/api/wiki/admin/${page.id}`, { published: !page.published });
toast(page.published ? 'Page dépubliée.' : 'Page publiée.');
reload();
},
{ tone: page.published ? 'ghost' : 'success' },
),
level >= LEVELS.OWNER &&
!page.protected &&
button(
'Supprimer',
async () => {
if (!(await confirmAction('Supprimer la page', `Supprimer « ${page.title} » ?`))) {
return;
}
await api.delete(`/api/wiki/admin/${page.id}`);
toast('Page supprimée.');
reload();
},
{ tone: 'danger' },
),
),
},
],
data.pages,
{ empty: 'Aucune page.' },
),
),
);
},
);
}