Wiki Phase 4: full-text search + revision history

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

Schema (additive): wiki_revisions table (per-save content snapshots).
The FULLTEXT index on wiki_pages(title, body) shipped in Phase 1.

Search:
- MATCH ... AGAINST natural-language search over title + body, ordered by
  relevance
- public: GET /public/wiki?q= (published only); admin: GET /admin/wiki?q=
  (all statuses)
- public wiki index gains a search box; admin list gains a search field

Revision history:
- every create/update snapshots the page into wiki_revisions
- admin endpoints: list revisions, get one, and restore (restore overwrites
  the page, rebuilds links, and appends a new revision — history stays
  append-only); logged as wiki.revision.restore
- editor gains a History modal: revision list + word-level diff (jsdiff) of a
  chosen revision against the current page, with one-click restore

Verified end-to-end: search matches body and title; two edits produce three
revisions; diff renders added/removed words; restore reverts and records a new
revision. No console errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-27 15:49:05 -05:00
parent 7c081ae749
commit 7bb992f58d
15 changed files with 492 additions and 14 deletions

View File

@@ -12,6 +12,7 @@
"@tiptap/extension-link": "^2.27.2",
"@tiptap/react": "^2.27.2",
"@tiptap/starter-kit": "^2.27.2",
"diff": "^5.2.2",
"dompurify": "^3.4.11",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -1794,6 +1795,15 @@
}
}
},
"node_modules/diff": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-5.2.2.tgz",
"integrity": "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/dompurify": {
"version": "3.4.11",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz",

View File

@@ -13,6 +13,7 @@
"@tiptap/extension-link": "^2.27.2",
"@tiptap/react": "^2.27.2",
"@tiptap/starter-kit": "^2.27.2",
"diff": "^5.2.2",
"dompurify": "^3.4.11",
"react": "^18.3.1",
"react-dom": "^18.3.1",

View File

@@ -53,6 +53,7 @@ export const api = {
const qs = new URLSearchParams()
if (opts.category) qs.set('category', opts.category)
if (opts.tag) qs.set('tag', opts.tag)
if (opts.q) qs.set('q', opts.q)
const s = qs.toString()
return req(`/public/wiki${s ? `?${s}` : ''}`)
},
@@ -90,6 +91,10 @@ export const api = {
publishWiki: (slug, published) =>
req(`/admin/wiki/${slug}/publish`, { method: 'PATCH', body: { published } }),
deleteWiki: (slug) => req(`/admin/wiki/${slug}`, { method: 'DELETE' }),
listWikiRevisions: (slug) => req(`/admin/wiki/${slug}/revisions`),
getWikiRevision: (slug, id) => req(`/admin/wiki/${slug}/revisions/${id}`),
restoreWikiRevision: (slug, id) =>
req(`/admin/wiki/${slug}/revisions/${id}/restore`, { method: 'POST' }),
listWikiTags: () => req('/admin/wiki/tags'),
listWikiCategories: () => req('/admin/wiki/categories'),
createWikiCategory: (data) => req('/admin/wiki/categories', { method: 'POST', body: data }),

View File

@@ -9,7 +9,11 @@ import WikiCategories from './WikiCategories.jsx'
export default function WikiAdmin() {
const [tick, setTick] = useState(0)
const reload = useCallback(() => setTick((t) => t + 1), [])
const { loading, error, data } = useAsync(() => api.admin.listWiki(), [tick])
const [q, setQ] = useState('')
const { loading, error, data } = useAsync(
() => api.admin.listWiki(q.trim() ? `?q=${encodeURIComponent(q.trim())}` : ''),
[tick, q],
)
const [editing, setEditing] = useState(null) // null | 'new' | slug
const [managingCats, setManagingCats] = useState(false)
const pages = data || []
@@ -21,6 +25,14 @@ export default function WikiAdmin() {
{pages.length} page{pages.length === 1 ? '' : 's'} · edit content and structure
</p>
<div style={{ display: 'flex', gap: 10 }}>
<input
type="search"
value={q}
onChange={(e) => setQ(e.target.value)}
className="input"
placeholder="Search pages…"
style={{ width: 200 }}
/>
<button onClick={() => setManagingCats(true)} className="pill">
Manage sections
</button>

View File

@@ -1,5 +1,6 @@
import { lazy, Suspense, useEffect, useState } from 'react'
import Modal from '../../../components/Modal.jsx'
import WikiHistory from './WikiHistory.jsx'
import { api } from '../../../api/client.js'
// Admin-only and heavy (TipTap) — load as its own chunk so the public bundle
@@ -22,6 +23,7 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
const [loading, setLoading] = useState(isEdit)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [showHistory, setShowHistory] = useState(false)
// Categories (dropdown) + pages (internal-link picker), for both new and edit.
useEffect(() => {
@@ -110,6 +112,7 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
}
return (
<>
<Modal
title={isEdit ? 'Edit wiki page' : 'New wiki page'}
onClose={onClose}
@@ -121,6 +124,11 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
Delete
</button>
)}
{isEdit && (
<button onClick={() => setShowHistory(true)} disabled={busy} className="pill">
History
</button>
)}
<button onClick={onClose} disabled={busy} className="pill">
Cancel
</button>
@@ -208,6 +216,17 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
</div>
)}
</Modal>
{showHistory && (
<WikiHistory
slug={slug}
onClose={() => setShowHistory(false)}
onRestored={() => {
setShowHistory(false)
onSaved()
}}
/>
)}
</>
)
}

View File

@@ -0,0 +1,139 @@
import { useEffect, useMemo, useState } from 'react'
import { diffWords } from 'diff'
import Modal from '../../../components/Modal.jsx'
import { dateTime } from '../../../lib/format.js'
import { api } from '../../../api/client.js'
// Plain-text view of a body, for a readable word-level diff.
function toText(html) {
if (!html) return ''
if (typeof window === 'undefined' || !window.DOMParser) return html
const doc = new DOMParser().parseFromString(html, 'text/html')
return doc.body.textContent || ''
}
export default function WikiHistory({ slug, onClose, onRestored }) {
const [revisions, setRevisions] = useState([])
const [current, setCurrent] = useState(null)
const [selected, setSelected] = useState(null) // full revision snapshot
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
let active = true
Promise.all([api.admin.listWikiRevisions(slug), api.admin.getWiki(slug)])
.then(([revs, page]) => {
if (!active) return
setRevisions(revs)
setCurrent(page)
})
.catch(() => active && setError('Could not load history.'))
.finally(() => active && setLoading(false))
return () => {
active = false
}
}, [slug])
async function selectRevision(id) {
setError('')
try {
const rev = await api.admin.getWikiRevision(slug, id)
setSelected(rev)
} catch (err) {
setError(err.message || 'Could not load revision.')
}
}
async function restore() {
if (!selected) return
if (!confirm(`Restore the page to revision #${selected.id}? This creates a new revision.`)) return
setBusy(true)
try {
await api.admin.restoreWikiRevision(slug, selected.id)
onRestored()
} catch (err) {
setError(err.message || 'Could not restore.')
setBusy(false)
}
}
// Diff the selected revision (old) against the current saved page (new).
const parts = useMemo(
() => (selected ? diffWords(toText(selected.body), toText(current?.body || '')) : []),
[selected, current],
)
return (
<Modal
title={`History — ${slug}`}
onClose={onClose}
width={760}
footer={
<>
<button onClick={onClose} disabled={busy} className="pill">
Close
</button>
<button onClick={restore} disabled={busy || !selected} className="btn btn-primary btn-sq">
{busy ? 'Restoring…' : 'Restore this revision'}
</button>
</>
}
>
{loading ? (
<span className="spin" />
) : error ? (
<p className="sans" style={{ margin: 0, color: '#d98b84', fontSize: '0.85rem' }}>{error}</p>
) : (
<div className="wiki-history">
<ul className="wiki-history-list">
{revisions.map((r, i) => (
<li key={r.id}>
<button
type="button"
className={`wiki-rev${selected?.id === r.id ? ' is-active' : ''}`}
onClick={() => selectRevision(r.id)}
>
<span className="wiki-rev-note">
{r.change_note || 'Edit'}
{i === 0 && <span className="wiki-rev-latest"> · latest</span>}
</span>
<span className="wiki-rev-meta">
{dateTime(r.created_at)}
{r.editor ? ` · ${r.editor}` : ''}
</span>
</button>
</li>
))}
{revisions.length === 0 && <li className="dim sans" style={{ fontSize: '0.85rem' }}>No revisions yet.</li>}
</ul>
<div className="wiki-history-diff">
{!selected ? (
<p className="muted sans" style={{ fontSize: '0.9rem' }}>
Select a revision to see what changed between it and the current page.
</p>
) : (
<>
<p className="sans dim" style={{ margin: '0 0 10px', fontSize: '0.76rem' }}>
Diff: revision #{selected.id} current
</p>
<div className="wiki-diff">
{parts.length === 0 || (parts.length === 1 && !parts[0].added && !parts[0].removed) ? (
<span className="muted">No textual differences.</span>
) : (
parts.map((p, i) => (
<span key={i} className={p.added ? 'diff-add' : p.removed ? 'diff-del' : ''}>
{p.value}
</span>
))
)}
</div>
</>
)}
</div>
</div>
)}
</Modal>
)
}

View File

@@ -1,3 +1,4 @@
import { useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import PublicLayout from '../../components/PublicLayout.jsx'
import PageHeader from '../../components/PageHeader.jsx'
@@ -5,6 +6,30 @@ import { Loading, ErrorState, EmptyState } from '../../components/PageState.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { api } from '../../api/client.js'
function SearchBox({ initial, onSubmit }) {
const [term, setTerm] = useState(initial || '')
return (
<form
onSubmit={(e) => {
e.preventDefault()
onSubmit(term.trim())
}}
style={{ display: 'flex', gap: 8, maxWidth: 460, margin: '0 auto 8px' }}
>
<input
type="search"
value={term}
onChange={(e) => setTerm(e.target.value)}
className="input"
placeholder="Search the wiki…"
/>
<button type="submit" className="btn btn-primary btn-sq">
Search
</button>
</form>
)
}
// Group published pages under their category, preserving category sort order and
// collecting anything uncategorized into a trailing section.
function groupByCategory(categories, pages) {
@@ -36,16 +61,19 @@ function PageCard({ page }) {
}
export default function Wiki() {
const [searchParams] = useSearchParams()
const [searchParams, setSearchParams] = useSearchParams()
const activeCategory = searchParams.get('category')
const activeTag = searchParams.get('tag')
// Tag view fetches a tag-filtered page list; otherwise all pages (grouped here).
const activeQ = searchParams.get('q')
// Search / tag views fetch a filtered page list; otherwise all pages (grouped here).
const pageOpts = activeQ ? { q: activeQ } : activeTag ? { tag: activeTag } : {}
const { loading, error, data } = useAsync(
() =>
Promise.all([api.wikiCategories(), api.wiki(activeTag ? { tag: activeTag } : {})]).then(
([categories, pages]) => ({ categories, pages }),
),
[activeTag],
Promise.all([api.wikiCategories(), api.wiki(pageOpts)]).then(([categories, pages]) => ({
categories,
pages,
})),
[activeTag, activeQ],
)
const allSections = data ? groupByCategory(data.categories, data.pages) : []
@@ -53,7 +81,10 @@ export default function Wiki() {
? allSections.filter((s) => s.slug === activeCategory)
: allSections
const hasPages = data && data.pages.length > 0
const filtered = Boolean(activeCategory || activeTag)
const flat = Boolean(activeTag || activeQ) // flat-list views
const filtered = Boolean(activeCategory || activeTag || activeQ)
const runSearch = (term) => setSearchParams(term ? { q: term } : {})
return (
<PublicLayout section="wiki">
@@ -64,6 +95,8 @@ export default function Wiki() {
title="Mysticmoon Wiki"
lead="A calm starting point for shard guides, the world and its lore, gameplay systems, and community rules."
/>
<SearchBox initial={activeQ || ''} onSubmit={runSearch} />
{loading && <Loading />}
{error && <ErrorState message="Could not load the wiki right now." />}
{!loading && !error && !hasPages && !filtered && <EmptyState>No wiki pages yet.</EmptyState>}
@@ -74,13 +107,14 @@ export default function Wiki() {
All sections
</Link>
{activeTag && <span className="muted"> · Tagged #{activeTag}</span>}
{activeQ && <span className="muted"> · Results for {activeQ}</span>}
</p>
)}
{/* Tag view: a flat list of matching pages (tags cross categories). */}
{!loading && !error && activeTag &&
{/* Flat list: search results or a tag filter (both cross categories). */}
{!loading && !error && flat &&
(data.pages.length === 0 ? (
<EmptyState>No pages with this tag.</EmptyState>
<EmptyState>{activeQ ? 'No pages match that search.' : 'No pages with this tag.'}</EmptyState>
) : (
<div className="grid-4" style={{ marginTop: 12 }}>
{data.pages.map((p) => (
@@ -90,10 +124,10 @@ export default function Wiki() {
))}
{/* Category / full view: grouped sections. */}
{!loading && !error && !activeTag && hasPages && activeCategory && sections.length === 0 && (
{!loading && !error && !flat && hasPages && activeCategory && sections.length === 0 && (
<EmptyState>No pages in this section yet.</EmptyState>
)}
{!activeTag &&
{!flat &&
sections.map((section) => (
<section key={section.id} style={{ marginTop: 36 }}>
<h2

View File

@@ -447,6 +447,86 @@ button[disabled] {
border-bottom: 1px dotted #d98b84;
}
/* ===== Wiki revision history ===== */
.wiki-history {
display: grid;
grid-template-columns: 240px 1fr;
gap: 18px;
align-items: start;
}
@media (max-width: 640px) {
.wiki-history {
grid-template-columns: 1fr;
}
}
.wiki-history-list {
list-style: none;
margin: 0;
padding: 0;
max-height: 360px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 4px;
}
.wiki-rev {
display: flex;
flex-direction: column;
gap: 2px;
width: 100%;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-flat);
color: var(--text);
text-align: left;
cursor: pointer;
}
.wiki-rev:hover {
border-color: var(--accent);
}
.wiki-rev.is-active {
border-color: var(--accent);
background: var(--blue);
}
.wiki-rev-note {
font-family: var(--sans);
font-size: 0.86rem;
color: var(--head);
}
.wiki-rev-latest {
color: var(--accent);
font-size: 0.74rem;
}
.wiki-rev-meta {
font-family: var(--sans);
font-size: 0.72rem;
color: var(--dim);
}
.wiki-diff {
white-space: pre-wrap;
word-break: break-word;
font-family: var(--sans);
font-size: 0.92rem;
line-height: 1.6;
color: var(--text);
max-height: 360px;
overflow-y: auto;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--bg);
}
.diff-add {
background: rgba(95, 185, 138, 0.22);
color: #b9e6cd;
}
.diff-del {
background: rgba(176, 102, 95, 0.24);
color: #e3b0aa;
text-decoration: line-through;
}
/* ===== Admin tables ===== */
.adm-table {
width: 100%;