Wiki Phase 3: internal links, backlinks, and tags

Connectivity phase of the wiki upgrade (see WIKI_UPGRADE.md).

Schema (additive new tables): wiki_tags, wiki_page_tags, wiki_links.

Internal links & backlinks:
- new wiki.links.js parses a saved body for /wiki/<slug> (and data-wiki-slug)
  targets; wiki_links is rebuilt on every save
- article shows a "Linked from" section (published backlinks) and renders
  links to non-existent pages as red links (server returns missing_links)
- editor gains an internal-link picker listing existing pages

Tags:
- pages accept a tags[] array; tags upsert on save, page tag-set is replaced,
  and orphaned tags are auto-pruned (on save and delete)
- public/admin list filter by ?tag=; /wiki/tags lists tags with published counts
- article shows tag chips; the index has a flat tag-filtered view; editor has a
  comma-separated tags field

Verified end-to-end: A->B backlink appears, red link detected, link index
rebuilds on edit, tag filtering + chips + pruning all work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-27 11:25:15 -05:00
parent 4a7dbf0085
commit 7c081ae749
15 changed files with 516 additions and 70 deletions

View File

@@ -49,8 +49,15 @@ export const api = {
status: () => req('/public/status'),
posts: (category) => req(`/public/posts/${category}`),
post: (category, idOrSlug) => req(`/public/posts/${category}/${idOrSlug}`),
wiki: (category) => req(`/public/wiki${category ? `?category=${encodeURIComponent(category)}` : ''}`),
wiki: (opts = {}) => {
const qs = new URLSearchParams()
if (opts.category) qs.set('category', opts.category)
if (opts.tag) qs.set('tag', opts.tag)
const s = qs.toString()
return req(`/public/wiki${s ? `?${s}` : ''}`)
},
wikiCategories: () => req('/public/wiki/categories'),
wikiTags: () => req('/public/wiki/tags'),
wikiPage: (slug) => req(`/public/wiki/${slug}`),
contact: (payload) => req('/public/contact', { method: 'POST', body: payload }),
@@ -83,6 +90,7 @@ export const api = {
publishWiki: (slug, published) =>
req(`/admin/wiki/${slug}/publish`, { method: 'PATCH', body: { published } }),
deleteWiki: (slug) => req(`/admin/wiki/${slug}`, { method: 'DELETE' }),
listWikiTags: () => req('/admin/wiki/tags'),
listWikiCategories: () => req('/admin/wiki/categories'),
createWikiCategory: (data) => req('/admin/wiki/categories', { method: 'POST', body: data }),
updateWikiCategory: (id, data) =>

View File

@@ -21,9 +21,15 @@ function Btn({ onClick, active, disabled, title, children }) {
)
}
export default function RichTextEditor({ value, onChange }) {
function escapeHtml(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
}
export default function RichTextEditor({ value, onChange, pages = [] }) {
const fileRef = useRef(null)
const [uploading, setUploading] = useState(false)
const [linkMenu, setLinkMenu] = useState(false)
const [linkFilter, setLinkFilter] = useState('')
const editor = useEditor({
extensions: [
@@ -55,6 +61,17 @@ export default function RichTextEditor({ value, onChange }) {
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
}
function insertInternalLink(page) {
const { from, to } = editor.state.selection
if (from === to) {
editor.chain().focus().insertContent(`<a href="/wiki/${page.slug}">${escapeHtml(page.title)}</a> `).run()
} else {
editor.chain().focus().extendMarkRange('link').setLink({ href: `/wiki/${page.slug}` }).run()
}
setLinkMenu(false)
setLinkFilter('')
}
async function onPickImage(e) {
const file = e.target.files?.[0]
e.target.value = '' // allow re-selecting the same file
@@ -109,6 +126,9 @@ export default function RichTextEditor({ value, onChange }) {
<Btn title="Link" active={editor.isActive('link')} onClick={setLink}>
🔗
</Btn>
<Btn title="Link to another wiki page" disabled={pages.length === 0} onClick={() => setLinkMenu((v) => !v)}>
📄
</Btn>
<Btn title="Insert image" disabled={uploading} onClick={() => fileRef.current?.click()}>
{uploading ? '…' : '🖼'}
</Btn>
@@ -121,6 +141,32 @@ export default function RichTextEditor({ value, onChange }) {
</Btn>
</div>
{linkMenu && (
<div className="rte-linkmenu">
<input
autoFocus
className="input"
placeholder="Filter pages…"
value={linkFilter}
onChange={(e) => setLinkFilter(e.target.value)}
/>
<div className="rte-linkmenu-list">
{pages
.filter((p) => {
const q = linkFilter.trim().toLowerCase()
return !q || p.title.toLowerCase().includes(q) || p.slug.includes(q)
})
.slice(0, 30)
.map((p) => (
<button key={p.slug} type="button" className="rte-linkmenu-item" onClick={() => insertInternalLink(p)}>
<span>{p.title}</span>
<span className="rte-linkmenu-slug">/{p.slug}</span>
</button>
))}
</div>
</div>
)}
<EditorContent editor={editor} className="rte-content prose" />
<input ref={fileRef} type="file" accept="image/*" onChange={onPickImage} hidden />
</div>

View File

@@ -15,19 +15,25 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
excerpt: '',
category_id: '',
published: true,
tags: '',
})
const [categories, setCategories] = useState([])
const [pages, setPages] = useState([])
const [loading, setLoading] = useState(isEdit)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
// Categories for the dropdown (both new and edit).
// Categories (dropdown) + pages (internal-link picker), for both new and edit.
useEffect(() => {
let active = true
api.admin
.listWikiCategories()
.then((cats) => active && setCategories(cats))
.catch(() => {})
api.admin
.listWiki()
.then((list) => active && setPages(list.map((p) => ({ slug: p.slug, title: p.title }))))
.catch(() => {})
return () => {
active = false
}
@@ -48,6 +54,7 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
excerpt: p.excerpt || '',
category_id: p.category_id != null ? String(p.category_id) : '',
published: Boolean(p.published),
tags: (p.tags || []).map((t) => t.label).join(', '),
}),
)
.catch(() => active && setError('Could not load this page.'))
@@ -66,6 +73,10 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
excerpt: form.excerpt.trim(),
category_id: form.category_id ? Number(form.category_id) : null,
published: form.published,
tags: form.tags
.split(',')
.map((t) => t.trim())
.filter(Boolean),
}
}
@@ -174,10 +185,24 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
placeholder="One-line summary shown on the wiki home."
/>
</label>
<label>
<span className="field-label">Tags (comma-separated)</span>
<input
type="text"
value={form.tags}
onChange={set('tags')}
className="input"
placeholder="beginner, pvp, towns"
/>
</label>
<div>
<span className="field-label">Body (use Heading 2 for table-of-contents sections)</span>
<Suspense fallback={<span className="spin" />}>
<RichTextEditor value={form.body} onChange={(html) => setForm((f) => ({ ...f, body: html }))} />
<RichTextEditor
value={form.body}
onChange={(html) => setForm((f) => ({ ...f, body: html }))}
pages={pages.filter((p) => p.slug !== form.slug)}
/>
</Suspense>
</div>
</div>

View File

@@ -38,17 +38,22 @@ function PageCard({ page }) {
export default function Wiki() {
const [searchParams] = useSearchParams()
const activeCategory = searchParams.get('category')
const { loading, error, data } = useAsync(() =>
Promise.all([api.wikiCategories(), api.wiki()]).then(([categories, pages]) => ({
categories,
pages,
})),
const activeTag = searchParams.get('tag')
// Tag view fetches a tag-filtered page list; otherwise all pages (grouped here).
const { loading, error, data } = useAsync(
() =>
Promise.all([api.wikiCategories(), api.wiki(activeTag ? { tag: activeTag } : {})]).then(
([categories, pages]) => ({ categories, pages }),
),
[activeTag],
)
const allSections = data ? groupByCategory(data.categories, data.pages) : []
const sections = activeCategory
? allSections.filter((s) => s.slug === activeCategory)
: allSections
const hasPages = data && data.pages.length > 0
const filtered = Boolean(activeCategory || activeTag)
return (
<PublicLayout section="wiki">
@@ -61,39 +66,54 @@ export default function Wiki() {
/>
{loading && <Loading />}
{error && <ErrorState message="Could not load the wiki right now." />}
{!loading && !error && !hasPages && <EmptyState>No wiki pages yet.</EmptyState>}
{!loading && !error && !hasPages && !filtered && <EmptyState>No wiki pages yet.</EmptyState>}
{!loading && !error && activeCategory && (
{!loading && !error && filtered && (
<p className="sans" style={{ margin: '0 0 8px', fontSize: '0.85rem' }}>
<Link to="/wiki" style={{ color: 'var(--accent)', textDecoration: 'none' }}>
All sections
</Link>
{activeTag && <span className="muted"> · Tagged #{activeTag}</span>}
</p>
)}
{!loading && !error && hasPages && activeCategory && sections.length === 0 && (
<EmptyState>No pages in this section yet.</EmptyState>
)}
{sections.map((section) => (
<section key={section.id} style={{ marginTop: 36 }}>
<h2
className="display"
style={{ margin: '0 0 4px', fontSize: '1.5rem', color: 'var(--accent)' }}
>
{section.title}
</h2>
{section.description && (
<p className="muted" style={{ margin: '0 0 16px', fontSize: '0.95rem' }}>
{section.description}
</p>
)}
<div className="grid-4" style={{ marginTop: section.description ? 0 : 12 }}>
{section.pages.map((p) => (
{/* Tag view: a flat list of matching pages (tags cross categories). */}
{!loading && !error && activeTag &&
(data.pages.length === 0 ? (
<EmptyState>No pages with this tag.</EmptyState>
) : (
<div className="grid-4" style={{ marginTop: 12 }}>
{data.pages.map((p) => (
<PageCard key={p.slug} page={p} />
))}
</div>
</section>
))}
))}
{/* Category / full view: grouped sections. */}
{!loading && !error && !activeTag && hasPages && activeCategory && sections.length === 0 && (
<EmptyState>No pages in this section yet.</EmptyState>
)}
{!activeTag &&
sections.map((section) => (
<section key={section.id} style={{ marginTop: 36 }}>
<h2
className="display"
style={{ margin: '0 0 4px', fontSize: '1.5rem', color: 'var(--accent)' }}
>
{section.title}
</h2>
{section.description && (
<p className="muted" style={{ margin: '0 0 16px', fontSize: '0.95rem' }}>
{section.description}
</p>
)}
<div className="grid-4" style={{ marginTop: section.description ? 0 : 12 }}>
{section.pages.map((p) => (
<PageCard key={p.slug} page={p} />
))}
</div>
</section>
))}
</div>
</PublicLayout>
)

View File

@@ -15,8 +15,9 @@ function slugify(text) {
}
// Parse the stored body HTML: sanitize (defense in depth — the server also
// sanitizes on save), then assign ids to <h2> headings and collect a TOC.
function buildArticle(body) {
// sanitizes on save), assign ids to <h2> headings and collect a TOC, and mark
// internal links to pages that don't exist as "red links".
function buildArticle(body, missing) {
if (!body) return { html: '', toc: [] }
if (typeof window === 'undefined' || !window.DOMParser) return { html: '', toc: [] }
const safe = DOMPurify.sanitize(body)
@@ -27,13 +28,22 @@ function buildArticle(body) {
h.id = id
toc.push({ id, label: h.textContent })
})
doc.querySelectorAll('a[href^="/wiki/"]').forEach((a) => {
const target = a.getAttribute('href').replace(/^\/wiki\//, '').replace(/[#?].*$/, '')
a.removeAttribute('target') // internal links stay in-app
if (missing.has(target)) {
a.classList.add('wiki-red-link')
a.setAttribute('title', 'This page does not exist yet')
}
})
return { html: doc.body.innerHTML, toc }
}
export default function WikiArticle() {
const { slug } = useParams()
const { loading, error, data: page } = useAsync(() => api.wikiPage(slug), [slug])
const { html, toc } = useMemo(() => buildArticle(page?.body), [page])
const missing = useMemo(() => new Set(page?.missing_links || []), [page])
const { html, toc } = useMemo(() => buildArticle(page?.body, missing), [page, missing])
return (
<PublicLayout section="wiki">
@@ -100,6 +110,15 @@ export default function WikiArticle() {
<p className="sans" style={{ margin: '18px 0 0', color: 'var(--dim)', fontSize: '0.78rem', letterSpacing: '0.04em' }}>
Last updated {longDate(page.updated_at) || '—'}
</p>
{page.tags && page.tags.length > 0 && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
{page.tags.map((t) => (
<Link key={t.slug} to={`/wiki?tag=${t.slug}`} className="wiki-tag">
#{t.label}
</Link>
))}
</div>
)}
<div style={{ height: 1, background: 'var(--line)', margin: '30px 0' }} />
{html ? (
<div className="prose" dangerouslySetInnerHTML={{ __html: html }} />
@@ -107,6 +126,28 @@ export default function WikiArticle() {
<p className="muted">This page has no content yet.</p>
)}
{page.backlinks && page.backlinks.length > 0 && (
<section
style={{ marginTop: 40, borderTop: '1px solid var(--line)', paddingTop: 22 }}
>
<p
className="sans"
style={{ margin: '0 0 12px', color: 'var(--accent)', fontSize: '0.66rem', fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase' }}
>
Linked from
</p>
<ul style={{ margin: 0, paddingLeft: 18, fontFamily: 'var(--sans)', fontSize: '0.92rem' }}>
{page.backlinks.map((b) => (
<li key={b.slug} style={{ marginBottom: 6 }}>
<Link to={`/wiki/${b.slug}`} style={{ color: 'var(--accent)', textDecoration: 'none' }}>
{b.title}
</Link>
</li>
))}
</ul>
</section>
)}
<nav style={{ display: 'flex', justifyContent: 'flex-start', marginTop: 40 }}>
<Link to="/wiki" className="pill">
All wiki pages

View File

@@ -314,10 +314,10 @@ button[disabled] {
/* ===== Rich text editor (TipTap) ===== */
.rte {
position: relative;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--bg);
overflow: hidden;
}
.rte:focus-within {
border-color: var(--accent);
@@ -380,6 +380,72 @@ button[disabled] {
color: var(--dim);
pointer-events: none;
}
/* Internal-link picker popover */
.rte-linkmenu {
position: absolute;
z-index: 20;
top: 50px;
left: 10px;
width: min(360px, calc(100% - 20px));
padding: 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-a);
box-shadow: var(--shadow-card);
}
.rte-linkmenu-list {
margin-top: 8px;
max-height: 220px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 2px;
}
.rte-linkmenu-item {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
padding: 7px 9px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text);
font-family: var(--sans);
font-size: 0.88rem;
text-align: left;
cursor: pointer;
}
.rte-linkmenu-item:hover {
background: var(--blue);
color: var(--ink);
}
.rte-linkmenu-slug {
color: var(--dim);
font-family: ui-monospace, Menlo, monospace;
font-size: 0.76rem;
}
/* ===== Wiki connectivity (tags + red links) ===== */
.wiki-tag {
display: inline-block;
padding: 3px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(127, 153, 189, 0.1);
color: var(--accent);
font-family: var(--sans);
font-size: 0.78rem;
text-decoration: none;
}
.wiki-tag:hover {
border-color: var(--accent);
background: var(--blue);
}
.prose a.wiki-red-link {
color: #d98b84;
border-bottom: 1px dotted #d98b84;
}
/* ===== Admin tables ===== */
.adm-table {