import React, { useCallback, useEffect, useState } from 'react'; import { marked } from 'marked'; import ConsoleShell from './ConsoleShell.jsx'; import { api } from './api.js'; marked.setOptions({ breaks: true }); function DocsWorkspace() { const [docs, setDocs] = useState([]); const [sel, setSel] = useState(null); const [doc, setDoc] = useState(null); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState({ title: '', folder: '', body: '' }); const [err, setErr] = useState(''); const [q, setQ] = useState(''); const loadList = useCallback(async () => { try { const d = await api('/docs'); setDocs(d.docs || []); } catch (e) { setErr(e.message); } }, []); useEffect(() => { loadList(); }, [loadList]); useEffect(() => { if (sel == null) { setDoc(null); return; } api(`/docs/${sel}`).then((d) => { setDoc(d.doc); setDraft({ title: d.doc.title, folder: d.doc.folder, body: d.doc.body }); setEditing(false); }).catch((e) => setErr(e.message)); }, [sel]); const create = async () => { const title = window.prompt('Document title', 'New document'); if (!title) return; try { const r = await api('/docs', { method: 'POST', body: { title, folder: '', body: `# ${title}\n\n` } }); await loadList(); setSel(r.id); setEditing(true); } catch (e) { setErr(e.message); } }; const save = async () => { try { await api(`/docs/${sel}`, { method: 'PATCH', body: draft }); await loadList(); setDoc({ ...doc, ...draft }); setEditing(false); } catch (e) { setErr(e.message); } }; const del = async () => { if (!window.confirm('Delete document?')) return; try { await api(`/docs/${sel}`, { method: 'DELETE' }); setSel(null); loadList(); } catch (e) { setErr(e.message); } }; const filtered = docs.filter((d) => (d.title + ' ' + (d.folder || '')).toLowerCase().includes(q.toLowerCase())); const folders = {}; filtered.forEach((d) => { (folders[d.folder || ''] = folders[d.folder || ''] || []).push(d); }); return (
{err &&

{err}

} {!doc &&
Select or create a document.
} {doc && ( <>
{editing ? setDraft({ ...draft, title: e.target.value })} /> :

{doc.title}

}
{editing && setDraft({ ...draft, folder: e.target.value })} />} {!editing && } {editing && } {editing && }

updated by {doc.updated_by || '—'}

{editing ?