Commit 802f3568 by PLN (Algolia)

desk: coquille synchronisée — éditeur de post (méta/fr/en), état deep-linkable…

desk: coquille synchronisée — éditeur de post (méta/fr/en), état deep-linkable dans l'URL (?tab=, #post/, #idee/), bannière d'erreur distincte du vide, aperçu markdown escape-first et lien vers la page publiée
parent 4d91f98a
...@@ -23,6 +23,15 @@ textarea{min-height:10rem} ...@@ -23,6 +23,15 @@ textarea{min-height:10rem}
#tabs{margin:1rem 0 .5rem;display:flex;gap:.4rem} #tabs{margin:1rem 0 .5rem;display:flex;gap:.4rem}
#editor{margin-top:1rem} #editor{margin-top:1rem}
form p{margin:.5rem 0} form p{margin:.5rem 0}
.err{background:#fdecea;border:1px solid #e5b4ae;border-radius:6px;padding:.6rem}
#files button{margin-right:.3rem}
a{color:#1c1c1c}
.apnote{color:#888;font-size:.8rem;font-style:italic}
.apmeta{color:#666;font-size:.85rem;margin:.3rem 0}
.apbody{font-family:Georgia,'Times New Roman',serif;line-height:1.55;border:1px solid #ddd;border-radius:6px;padding:.8rem 1rem;margin:.4rem 0}
.apbody p{margin:.5rem 0}
.apbody h2,.apbody h3,.apbody h4{margin:.9rem 0 .3rem}
.apbody pre{overflow-x:auto;background:#f5f5f5;padding:.5rem;border-radius:4px}
</style> </style>
<h1>desk</h1><p id="status">…</p><div id="shelf"></div> <h1>desk</h1><p id="status">…</p><div id="shelf"></div>
<script> <script>
...@@ -39,9 +48,12 @@ form p{margin:.5rem 0} ...@@ -39,9 +48,12 @@ form p{margin:.5rem 0}
// (dev local : remplacer par 'http://127.0.0.1:9786', la coquille servant // (dev local : remplacer par 'http://127.0.0.1:9786', la coquille servant
// alors depuis un fichier ou un autre port) // alors depuis un fichier ou un autre port)
const API = 'https://api.nech.pl/desk/v1'; const API = 'https://api.nech.pl/desk/v1';
const SITE = 'https://me.nech.pl';
const shelf = document.getElementById('shelf'); const shelf = document.getElementById('shelf');
const status = document.getElementById('status'); const status = document.getElementById('status');
let popup = null, timer = null, token = null, debounceTimer = null; let popup = null, timer = null, token = null, debounceTimer = null;
// vue courante, reflétée dans l'URL (?tab=…#post/<slug> | #idee/<name>)
let view = { tab: 'posts', target: null };
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => const esc = (s) => String(s).replace(/[&<>"']/g, (c) =>
({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
...@@ -52,6 +64,47 @@ form p{margin:.5rem 0} ...@@ -52,6 +64,47 @@ form p{margin:.5rem 0}
return r; return r;
}; };
// --- URL : l'état vit dans l'URL, l'URL est la source de vérité -----------
function setUrl() {
const q = view.tab === 'idees' ? '?tab=idees' : '?tab=posts';
const hash = view.target ? '#' + view.target.kind + '/' + view.target.name : '';
// replaceState : deep-linkable sans saut de scroll ni empilement d'historique
history.replaceState(null, '', location.pathname + q + hash);
}
function readUrl() {
const tab = new URLSearchParams(location.search).get('tab') === 'idees' ? 'idees' : 'posts';
const m = location.hash.match(/^#(post|idee)\/(.+)$/);
return { tab, target: m ? { kind: m[1], name: m[2] } : null };
}
async function route() {
if (!token) return; // pas connecté : welcome() tranchera au retour
const wanted = readUrl(); // capturé AVANT les re-rendus, qui touchent view
view = wanted;
if (view.tab === 'idees') {
await showIdeas();
if (wanted.target && wanted.target.kind === 'idee') editIdea(wanted.target.name);
} else {
await showPosts();
if (wanted.target && wanted.target.kind === 'post') editPost(wanted.target.name);
}
}
window.addEventListener('popstate', route);
// --- erreurs honnêtes : vide ≠ cassé ----------------------------------------
function renderError(retry) {
// « Aucun post. » doit rester une affirmation vérifiée (200 + liste
// vide) — jamais la forme muette d'un scan cassé ou d'un 502.
shelf.innerHTML = tabsBar(view.tab) +
'<p class="err" role="alert">Erreur : la liste n’a pas pu être lue — ce n’est pas un blog vide.</p>' +
'<p><button id="retry" type="button">réessayer</button></p>';
document.getElementById('retry').onclick = retry;
}
function stop() { function stop() {
window.removeEventListener('message', onMessage); window.removeEventListener('message', onMessage);
clearInterval(timer); clearInterval(timer);
...@@ -110,7 +163,7 @@ form p{margin:.5rem 0} ...@@ -110,7 +163,7 @@ form p{margin:.5rem 0}
sessionStorage.removeItem(KEY); sessionStorage.removeItem(KEY);
welcome(); welcome();
}; };
showPosts(); route(); // l'URL (onglet + cible) commande la vue, même au boot
} }
// --- onglets --------------------------------------------------------------- // --- onglets ---------------------------------------------------------------
...@@ -123,14 +176,30 @@ form p{margin:.5rem 0} ...@@ -123,14 +176,30 @@ form p{margin:.5rem 0}
).join(' ') + '</p>'; ).join(' ') + '</p>';
} }
function wireTabs(active, showTab) { function wireTabs() {
for (const b of shelf.querySelectorAll('#tabs button')) { for (const b of shelf.querySelectorAll('#tabs button')) {
b.onclick = () => { if (b.dataset.tab !== active) showTab(b.dataset.tab); }; b.onclick = () => {
const tab = b.dataset.tab === 'idées' ? 'idees' : 'posts';
if (tab !== view.tab || view.target) {
view = { tab, target: null };
setUrl();
tab === 'idees' ? showIdeas() : showPosts();
}
};
} }
} }
async function showPosts() { async function showPosts() {
const r = await api('/api/posts', { headers: auth() }); view = { tab: 'posts', target: null };
setUrl();
shelf.innerHTML = tabsBar('posts') + '<p><button id="new-post" type="button">nouveau post</button></p><div id="editor"></div><p>chargement…</p>';
wireTabs();
document.getElementById('new-post').onclick = postForm;
let r;
try {
r = await api('/api/posts', { headers: auth() });
} catch (e) { return; } // 401 : api() a déjà rendu welcome()
if (r.status !== 200) return renderError(showPosts);
const posts = (await r.json()).posts; const posts = (await r.json()).posts;
let year = null, html = ''; let year = null, html = '';
for (const p of posts) { for (const p of posts) {
...@@ -140,14 +209,13 @@ form p{margin:.5rem 0} ...@@ -140,14 +209,13 @@ form p{margin:.5rem 0}
} }
const flags = p.languages.map((l) => '<span class="lang">' + esc(l) + '</span>').join(' '); const flags = p.languages.map((l) => '<span class="lang">' + esc(l) + '</span>').join(' ');
const draft = p.draft ? ' <span class="draft">brouillon</span>' : ''; const draft = p.draft ? ' <span class="draft">brouillon</span>' : '';
html += '<li><span class="title">' + esc(p.title || p.name) + '</span>' + draft + ' ' + flags + html += '<li><a href="#post/' + esc(p.slug) + '" class="popen"><span class="title">' + esc(p.title || p.name) + '</span></a>' +
' <code>' + esc(p.slug) + '</code></li>'; draft + ' ' + flags + ' <code>' + esc(p.slug) + '</code></li>';
} }
shelf.innerHTML = tabsBar('posts') + const list = document.createElement('div');
'<p><button id="new-post" type="button">nouveau post</button></p><div id="editor"></div>' + list.innerHTML = year === null ? '<p>Aucun post.</p>' : html + '</ul>'; // vide = constaté, pas subi
(year === null ? '<p>Aucun post.</p>' : html + '</ul>'); shelf.appendChild(list);
wireTabs('posts', showIdeas); for (const a of list.querySelectorAll('a.popen')) a.onclick = (e) => { e.preventDefault(); editPost(a.getAttribute('href').slice(6)); };
document.getElementById('new-post').onclick = postForm;
} }
function postForm() { function postForm() {
...@@ -160,21 +228,158 @@ form p{margin:.5rem 0} ...@@ -160,21 +228,158 @@ form p{margin:.5rem 0}
const slug = document.getElementById('np-slug').value.trim(); const slug = document.getElementById('np-slug').value.trim();
const r = await api('/api/post', { method: 'POST', headers: auth(), body: JSON.stringify({ slug }) }); const r = await api('/api/post', { method: 'POST', headers: auth(), body: JSON.stringify({ slug }) });
const body = await r.json(); const body = await r.json();
if (r.status === 200) showPosts(); if (r.status === 200) editPost(body.slug);
else { else {
document.getElementById('np-err').textContent = body.detail || 'création refusée'; document.getElementById('np-err').textContent = body.detail || 'création refusée';
} }
}; };
} }
// --- éditeur de post ---------------------------------------------------------
function parseFrontmatter(raw) {
// le même minimalisme que app/posts.py côté serveur : assez pour l'affiche
const meta = {};
if (!raw || !raw.startsWith('---')) return meta;
const lines = raw.split('\n');
const end = lines.indexOf('---', 1);
if (end === -1) return meta;
for (const line of lines.slice(1, end)) {
const i = line.indexOf(':');
if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim().replace(/^['"]|['"]$/g, '');
}
return meta;
}
function splitFrontmatter(raw) {
// {meta: objet|nul, body: le reste} — le frontmatter ne part JAMAIS au
// rendu de corps : il revient en petit bloc méta au-dessus de l'aperçu.
if (!raw || !raw.startsWith('---')) return { meta: null, body: raw || '' };
const lines = raw.split('\n');
const end = lines.indexOf('---', 1);
if (end === -1) return { meta: null, body: raw };
return { meta: parseFrontmatter(raw), body: lines.slice(end + 1).join('\n') };
}
function mdToHtml(src) {
// Rendu markdown minimal, escape-first : TOUT est échappé avant la
// moindre balise — aucun HTML inline ne passe (posture Seurat).
// Sous-ensemble assumé : #/##/### titres, listes -, blocs ```,
// `code`, **gras**, *italique*, [texte](https://…) — liens http(s) seuls.
const inline = (s) => s
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
const out = [];
let para = [], list = null, code = null;
const flushPara = () => { if (para.length) { out.push('<p>' + para.map(inline).join('<br>') + '</p>'); para = []; } };
const flushList = () => { if (list) { out.push('<ul>' + list.map((li) => '<li>' + inline(li) + '</li>').join('') + '</ul>'); list = null; } };
// escape-FIRST : la source est échappée d'un bloc, avant toute balise —
// le `<script>` d'une idée reste du texte visible, jamais du HTML.
for (const line of esc(src).split('\n')) {
if (code !== null) {
if (/^```/.test(line)) { out.push('<pre><code>' + code.join('\n') + '</code></pre>'); code = null; }
else code.push(line);
continue;
}
if (/^```/.test(line)) { flushPara(); flushList(); code = []; continue; }
const h = line.match(/^(#{1,3})\s+(.*)$/);
if (h) {
flushPara(); flushList();
out.push('<h' + (h[1].length + 1) + '>' + inline(h[2]) + '</h' + (h[1].length + 1) + '>');
continue;
}
const li = line.match(/^\s*[-*]\s+(.*)$/);
if (li) { flushPara(); (list ??= []).push(li[1]); continue; }
if (!line.trim()) { flushPara(); flushList(); continue; }
para.push(line);
}
flushPara(); flushList();
if (code !== null) out.push('<pre><code>' + code.join('\n') + '</code></pre>');
return out.join('');
}
async function editPost(name) {
view = { tab: 'posts', target: { kind: 'post', name } };
setUrl();
shelf.innerHTML = tabsBar('posts') + '<p>chargement…</p>';
wireTabs();
let r;
try {
r = await api('/api/post/' + name, { headers: auth() });
} catch (e) { return; }
if (r.status !== 200) return renderError(() => editPost(name));
const post = await r.json();
const files = ['meta.md', ...post.languages.map((l) => l + '.md')];
const meta = parseFrontmatter(post.meta || '');
const draft = meta.draft === 'true';
shelf.innerHTML = tabsBar('posts') +
'<p><code>' + esc(name) + '</code>' + (draft ? ' <span class="draft">brouillon</span>' : '') +
' <span id="pe-title"></span>' +
(draft ? '' : ' · <a href="' + SITE + '/' + esc(post.name) + '" target="_blank" rel="noopener">voir la vraie page</a>') + '</p>' +
'<p id="files">' + files.map((f) =>
'<button type="button" data-file="' + f + '">' + f + '</button>').join(' ') + '</p>' +
'<p><textarea id="pe-body"></textarea></p>' +
'<p><label><input type="checkbox" id="pe-apercu"> aperçu</label> ' +
'<span class="apnote">aperçu approximatif — le rendu réel est celui du build</span></p>' +
'<div id="pe-preview"></div>' +
'<p><button id="pe-save" type="button">enregistrer</button> <span id="pe-err"></span></p>' +
'<div id="pe-extra"></div>';
wireTabs();
let current = 'meta.md';
const body = document.getElementById('pe-body');
const apercu = document.getElementById('pe-apercu');
const preview = document.getElementById('pe-preview');
const paintPreview = () => {
if (!apercu.checked || current === 'meta.md') { preview.innerHTML = ''; return; }
const { meta: fm, body: mdBody } = splitFrontmatter(body.value);
let html = '';
if (fm) {
html += '<div class="apmeta">' +
[fm.title, fm.date, fm.draft === 'true' ? 'brouillon' : null].filter(Boolean).map(esc).join(' · ') + '</div>';
}
html += '<div class="apbody">' + mdToHtml(mdBody) + '</div>';
preview.innerHTML = html;
};
apercu.onchange = paintPreview;
const paintFile = () => {
body.value = post[current] || '';
for (const b of document.querySelectorAll('#files button')) b.classList.toggle('on', b.dataset.file === current);
// l'aperçu est un rendu de corps : meta.md n'en a pas
apercu.disabled = current === 'meta.md';
if (apercu.disabled) apercu.checked = false;
paintPreview();
};
for (const b of document.querySelectorAll('#files button')) {
b.onclick = () => { current = b.dataset.file; paintFile(); };
}
paintFile();
document.getElementById('pe-title').textContent =
(meta.title ? meta.title + ' · ' : '') + (meta.date || '');
document.getElementById('pe-save').onclick = async () => {
const err = document.getElementById('pe-err');
err.textContent = 'enregistrement…';
const r2 = await api('/api/post/' + name + '/files', {
method: 'POST', headers: auth(),
body: JSON.stringify({ files: [{ path: current, content: body.value }], message: 'post(' + name + '): maj ' + current }),
});
const b2 = await r2.json();
if (r2.status === 200) { post[current] = body.value; err.textContent = 'enregistré ✓'; }
else err.textContent = b2.detail || 'enregistrement refusé';
};
}
// --- idées ----------------------------------------------------------------- // --- idées -----------------------------------------------------------------
async function showIdeas() { async function showIdeas() {
view = { tab: 'idees', target: null };
setUrl();
shelf.innerHTML = tabsBar('idées') + shelf.innerHTML = tabsBar('idées') +
'<p><input id="q" placeholder="chercher dans les idées…"></p>' + '<p><input id="q" placeholder="chercher dans les idées…"></p>' +
'<p><button id="new-idea" type="button">nouvelle idée</button></p>' + '<p><button id="new-idea" type="button">nouvelle idée</button></p>' +
'<ul id="list"></ul><div id="editor"></div>'; '<ul id="list"></ul><div id="editor"></div>';
wireTabs('idées', showPosts); wireTabs();
document.getElementById('new-idea').onclick = () => ideaForm(); document.getElementById('new-idea').onclick = () => ideaForm();
document.getElementById('q').oninput = () => { document.getElementById('q').oninput = () => {
clearTimeout(debounceTimer); clearTimeout(debounceTimer);
...@@ -185,14 +390,18 @@ form p{margin:.5rem 0} ...@@ -185,14 +390,18 @@ form p{margin:.5rem 0}
async function paintIdeas() { async function paintIdeas() {
const q = (document.getElementById('q') || {}).value || ''; const q = (document.getElementById('q') || {}).value || '';
const r = await api('/api/ideas?q=' + encodeURIComponent(q), { headers: auth() }); let r;
try {
r = await api('/api/ideas?q=' + encodeURIComponent(q), { headers: auth() });
} catch (e) { return; }
const list = document.getElementById('list'); const list = document.getElementById('list');
if (!list) return; // l'onglet a changé pendant la recherche if (!list) return; // l'onglet a changé pendant la recherche
if (r.status !== 200) return renderError(showIdeas);
const ideas = (await r.json()).ideas; const ideas = (await r.json()).ideas;
list.innerHTML = ideas.map((i) => list.innerHTML = ideas.map((i) =>
'<li><a href="#" data-name="' + esc(i.name) + '">' + esc(i.title) + '</a> <code>' + esc(i.name) + '</code></li>' '<li><a href="#idee/' + esc(i.name) + '" class="iopen">' + esc(i.title) + '</a> <code>' + esc(i.name) + '</code></li>'
).join('') || '<li><em>aucune idée</em></li>'; ).join('') || '<li><em>aucune idée</em></li>';
for (const a of list.querySelectorAll('a')) a.onclick = (e) => { e.preventDefault(); editIdea(a.dataset.name); }; for (const a of list.querySelectorAll('a.iopen')) a.onclick = (e) => { e.preventDefault(); editIdea(a.getAttribute('href').slice(6)); };
} }
async function ideaForm() { async function ideaForm() {
...@@ -207,13 +416,19 @@ form p{margin:.5rem 0} ...@@ -207,13 +416,19 @@ form p{margin:.5rem 0}
const content = document.getElementById('ie-body').value; const content = document.getElementById('ie-body').value;
const r = await api('/api/idea/' + encodeURIComponent(name), { method: 'POST', headers: auth(), body: JSON.stringify({ content }) }); const r = await api('/api/idea/' + encodeURIComponent(name), { method: 'POST', headers: auth(), body: JSON.stringify({ content }) });
const body = await r.json(); const body = await r.json();
if (r.status === 200) showIdeas(); if (r.status === 200) { view.target = { kind: 'idee', name }; setUrl(); showIdeas(); }
else document.getElementById('ie-err').textContent = body.detail || 'enregistrement refusé'; else document.getElementById('ie-err').textContent = body.detail || 'enregistrement refusé';
}; };
} }
async function editIdea(name) { async function editIdea(name) {
const r = await api('/api/idea/' + encodeURIComponent(name), { headers: auth() }); view = { tab: 'idees', target: { kind: 'idee', name } };
setUrl();
let r;
try {
r = await api('/api/idea/' + encodeURIComponent(name), { headers: auth() });
} catch (e) { return; }
if (r.status !== 200) return renderError(showIdeas);
const content = (await r.json()).content; const content = (await r.json()).content;
const editor = document.getElementById('editor'); const editor = document.getElementById('editor');
editor.innerHTML = editor.innerHTML =
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment