feat(web): Phase 11 UI/UX — TOC, dark mode toggle, /docs index
- Install rehype-slug (proper heading anchors) + github-slugger (matching TOC) - TOC component: auto-generated from h2/h3 headings, clickable anchors - Dark mode toggle: ThemeToggle (localStorage + system default), class-based - /docs index page (lists all docs by section) - Markdown.tsx uses rehype-slug for stable heading ids - globals.css: @custom-variant dark (.dark class) for class-based dark mode - layout.tsx: nav includes ThemeToggle Note: per user instruction, installed real deps (rehype-slug, github-slugger, @types/hast) instead of hacky inline any-cast hacks.
This commit is contained in:
@@ -8,11 +8,14 @@
|
|||||||
3. **UI/UX**: Polish doc page, edit forms, search UX, dark mode
|
3. **UI/UX**: Polish doc page, edit forms, search UX, dark mode
|
||||||
4. **Agent integration**: MCP tools for CRUD with auth
|
4. **Agent integration**: MCP tools for CRUD with auth
|
||||||
|
|
||||||
### Files to touch:
|
## Requirements:
|
||||||
- `packages/db/` — migrations (users table, if needed)
|
1. **Source of truth is the filesystem** — each doc is a markdown file under `content/{section}/{slug}.md` with YAML frontmatter (parsed/striped by gray-matter).
|
||||||
- `apps/api/src/` — auth routes, CRUD tRPC routers
|
2. **DB mirrors disk** — `documents` table has slug/title/section/body/status/tags/etc; `document_chunks` stores embeddings; `document_revisions` snapshots body+meta.
|
||||||
- `apps/mcp/src/` — add create/update/delete tools
|
3. **Single indexing path** — `indexContentFile` in `@mcpedia/core` writes DB + revisions + chunks; CRUD ops call it (or its pieces) after writing the file.
|
||||||
- `apps/web/app/` — edit/create pages, auth UI
|
4. **Auth** — MCP/API writes require `x-webhook-secret` matching `WEBHOOK_SECRET` (Phase 4 pattern). Web CRUD uses cookie-based auth (Phase 11 addition: `ADMIN_PASSWORD`).
|
||||||
|
5. **Slug rules** — `[a-z0-9][a-z0-9/_-]*`, no `//`, no path traversal (`..`). The slug in the URL is `<section>/<slug-parts>`.
|
||||||
|
6. **No breaking existing features** — read tools/routes unchanged; existing 32 tests still green.
|
||||||
|
7. **UI/UX** — edit button on doc pages (auth-gated), `?edit=1` inline form, `/create` page, login page, table of contents auto-generated from h2, dark mode toggle.
|
||||||
|
|
||||||
### Schema changes:
|
### Schema changes:
|
||||||
- Optional: `users` table if auth is user-based
|
- Optional: `users` table if auth is user-based
|
||||||
|
|||||||
@@ -344,6 +344,85 @@ The VPS services were configured manually (systemd units in `deploy/`). Added a
|
|||||||
`/metrics`, `/trpc/*`, `mcp.asepharyana.my.id/mcp`.
|
`/metrics`, `/trpc/*`, `mcp.asepharyana.my.id/mcp`.
|
||||||
- Doc pages render clean markdown (no frontmatter); History panel + Restore work.
|
- Doc pages render clean markdown (no frontmatter); History panel + Restore work.
|
||||||
|
|
||||||
|
## Phase 11 — CRUD + Auth + Web UI ✅ DONE
|
||||||
|
|
||||||
|
> User requested: "perbagus agar jadi CRUD, pastikan ada autentikasi dan bisa
|
||||||
|
> manual dari web atau lewat agent melalui MCP, dan perbaui UI/UXnya."
|
||||||
|
|
||||||
|
### Backend (Core + API + MCP)
|
||||||
|
|
||||||
|
- [x] **`packages/parser` — `stringifyFile()`** — serialize `DocumentMeta` + body
|
||||||
|
back to a markdown file with YAML frontmatter (gray-matter). Round-trip stable
|
||||||
|
with `parseFile`.
|
||||||
|
- [x] **`@mcpedia/core` — CRUD functions:**
|
||||||
|
- `createDocument({slug, title, section, body, type?, status?, author?, tags?})`
|
||||||
|
— writes file to `content/{section}/{slug}.md`, upserts `documents` row,
|
||||||
|
snapshots revision, indexes chunks.
|
||||||
|
- `updateDocument(slug, {...})` — writes file, updates DB row, snapshots
|
||||||
|
revision (if body changed), reindexes chunks.
|
||||||
|
- `deleteDocument(slug)` — removes file + `documents`/`document_chunks`/
|
||||||
|
`document_revisions` rows.
|
||||||
|
- Slug validation: `[a-z0-9][a-z0-9/_-]*`, no `//`, no `..` traversal.
|
||||||
|
- [x] **`apps/api` — tRPC CRUD routers** — `createDocument`, `updateDocument`,
|
||||||
|
`deleteDocument` (all `.use(requireWriteAuth)`). Fixed `requireWriteAuth` to
|
||||||
|
compare against `ctx.expectedSecret` (injected from deps) instead of the
|
||||||
|
module-level `WEBHOOK_SECRET` env constant — latent bug that made the middleware
|
||||||
|
untestable without env manipulation.
|
||||||
|
- [x] **`apps/mcp` — 3 new write tools** — `create_document`, `update_document`,
|
||||||
|
`delete_document` (all require `x-webhook-secret`). Tools: 10 → 13.
|
||||||
|
- [x] **Auth** — MCP/API writes reuse the existing `WEBHOOK_SECRET` /
|
||||||
|
`x-webhook-secret` pattern. Web CRUD adds cookie-based auth: `ADMIN_PASSWORD`
|
||||||
|
env + `/api/auth/login` (HMAC-signed `mcpedia_admin` cookie, HttpOnly).
|
||||||
|
|
||||||
|
### Web UI
|
||||||
|
|
||||||
|
- [x] **`/create` page** — form (section/type/status/title/slug/tags/author/body),
|
||||||
|
POSTs to `/api/docs` with `x-webhook-secret`.
|
||||||
|
- [x] **`?edit=1` on doc pages** — inline edit form (`DocForm` component),
|
||||||
|
PUTs to `/api/docs/{slug}`.
|
||||||
|
- [x] **`/login` page** — password → `/api/auth/login` → cookie → redirect `/create`.
|
||||||
|
- [x] **Edit buttons** — homepage "+ Create Document" + per-doc "✎" (auth-gated);
|
||||||
|
doc page "Edit" button (auth-gated).
|
||||||
|
- [x] **TOC** — doc page auto-generates a table of contents from `h2` headings.
|
||||||
|
- [x] **Dark mode** — toggle persisted in `localStorage`, defaults to system.
|
||||||
|
- [x] **`/api/docs` REST routes** — POST (create), PUT (update), DELETE (delete),
|
||||||
|
all `x-webhook-secret` gated.
|
||||||
|
|
||||||
|
### Files changed
|
||||||
|
```
|
||||||
|
new: apps/web/app/api/auth/login/route.ts # cookie-based login + verify
|
||||||
|
new: apps/web/app/api/docs/route.ts # REST CRUD
|
||||||
|
new: apps/web/app/components/DocForm.tsx # shared create/edit form
|
||||||
|
new: apps/web/app/create/page.tsx # create UI
|
||||||
|
new: apps/web/app/login/page.tsx # login UI
|
||||||
|
new: apps/web/app/components/TOC.tsx # auto-generated TOC
|
||||||
|
mod: apps/web/app/page.tsx # edit/create buttons (auth-gated)
|
||||||
|
mod: apps/web/app/[section]/[...slug]/page.tsx # ?edit=1 + TOC + dark mode
|
||||||
|
mod: packages/core/src/document.service.ts # createDocument/updateDocument/deleteDocument
|
||||||
|
mod: packages/core/src/index.service.ts # export snapshotRevision
|
||||||
|
mod: packages/core/src/index.ts # re-export CRUD + types
|
||||||
|
mod: packages/parser/src/index.ts # stringifyFile
|
||||||
|
mod: packages/config/src/index.ts # ADMIN_PASSWORD
|
||||||
|
mod: apps/api/src/router.ts # CRUD routers + fix requireWriteAuth
|
||||||
|
mod: apps/api/src/app.ts # createContext passes expectedSecret
|
||||||
|
mod: apps/api/src/trpc.ts # Context.expectedSecret
|
||||||
|
mod: apps/mcp/src/index.ts # 3 new CRUD write tools
|
||||||
|
mod: apps/mcp/src/auth.test.ts # +4 CRUD auth tests
|
||||||
|
mod: apps/api/src/app.test.ts # +5 tRPC CRUD auth tests
|
||||||
|
mod: .env.example # ADMIN_PASSWORD
|
||||||
|
```
|
||||||
|
|
||||||
|
### Gotchas / lessons
|
||||||
|
1. **tRPC fetch adapter** expects input directly as JSON body, NOT JSON-RPC
|
||||||
|
envelope (`{"slug":...}` not `{"jsonrpc":"2.0","method":...,"params":{...}}`).
|
||||||
|
2. **`requireWriteAuth` env-constant bug** — comparing `ctx.webhookSecret !== WEBHOOK_SECRET`
|
||||||
|
(module-level env constant) is untestable. Fix: thread `expectedSecret` through
|
||||||
|
`Context` from `createApp(deps)`.
|
||||||
|
3. **Next.js catch-all routes** — `[...slug]/edit/` is invalid (catch-all must be
|
||||||
|
last). Used `?edit=1` query param instead.
|
||||||
|
4. **`stringifyFile` YAML** — quote string values with `JSON.stringify` for
|
||||||
|
special-char safety; arrays use `[...]` syntax.
|
||||||
|
|
||||||
|
|
||||||
## Decisions locked (from initial planning)
|
## Decisions locked (from initial planning)
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { getDocument, getRelated, listRevisions } from "@mcpedia/core";
|
|||||||
import { WEBHOOK_SECRET } from "@mcpedia/config";
|
import { WEBHOOK_SECRET } from "@mcpedia/config";
|
||||||
import Markdown from "@/components/Markdown";
|
import Markdown from "@/components/Markdown";
|
||||||
import DocForm from "@/components/DocForm";
|
import DocForm from "@/components/DocForm";
|
||||||
|
import TOC from "@/components/TOC";
|
||||||
|
|
||||||
// Render at request time. The content lives in Postgres (populated by the
|
// Render at request time. The content lives in Postgres (populated by the
|
||||||
// indexer/worker), which is not available at build time (CI has no DB), so we
|
// indexer/worker), which is not available at build time (CI has no DB), so we
|
||||||
@@ -76,6 +77,8 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<TOC source={doc.body} />
|
||||||
|
|
||||||
<Markdown source={doc.body} />
|
<Markdown source={doc.body} />
|
||||||
|
|
||||||
{related.length > 0 && (
|
{related.length > 0 && (
|
||||||
@@ -84,10 +87,7 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
|
|||||||
<ul className="text-sm space-y-1">
|
<ul className="text-sm space-y-1">
|
||||||
{related.map((r) => (
|
{related.map((r) => (
|
||||||
<li key={r.slug}>
|
<li key={r.slug}>
|
||||||
<Link
|
<Link href={`/${r.slug}`} className="hover:underline">
|
||||||
href={`/${r.slug}`}
|
|
||||||
className="hover:underline"
|
|
||||||
>
|
|
||||||
{r.title}
|
{r.title}
|
||||||
</Link>
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
|
import rehypeSlug from "rehype-slug";
|
||||||
|
|
||||||
export default function Markdown({ source }: { source: string }) {
|
export default function Markdown({ source }: { source: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="prose prose-zinc dark:prose-invert max-w-none [&_pre]:bg-zinc-100 dark:[&_pre]:bg-zinc-900 [&_pre]:p-3 [&_pre]:rounded [&_code]:font-mono [&_a]:underline">
|
<div className="prose prose-zinc dark:prose-invert max-w-none [&_pre]:bg-zinc-100 dark:[&_pre]:bg-zinc-900 [&_pre]:p-3 [&_pre]:rounded [&_code]:font-mono [&_a]:underline">
|
||||||
<ReactMarkdown>{source}</ReactMarkdown>
|
<ReactMarkdown rehypePlugins={[rehypeSlug]}>
|
||||||
|
{source}
|
||||||
|
</ReactMarkdown>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import GithubSlugger from "github-slugger";
|
||||||
|
|
||||||
|
interface TOCEntry {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
level: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extract h2/h3 headings from markdown and render as a clickable TOC. The
|
||||||
|
* heading `id`s are generated by rehype-slug (via github-slugger) in Markdown.tsx,
|
||||||
|
* so the same slugger is used here to produce matching anchors. */
|
||||||
|
export default function TOC({ source }: { source: string }) {
|
||||||
|
const [toc, setToc] = useState<TOCEntry[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const slugger = new GithubSlugger();
|
||||||
|
const lines = source.split("\n");
|
||||||
|
const entries: TOCEntry[] = [];
|
||||||
|
for (const line of lines) {
|
||||||
|
const m = line.match(/^(#{2,3})\s+(.+?)\s*#*\s*$/);
|
||||||
|
if (m) {
|
||||||
|
const level = m[1].length;
|
||||||
|
const text = m[2].trim();
|
||||||
|
entries.push({ id: slugger.slug(text), text, level });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setToc(entries);
|
||||||
|
}, [source]);
|
||||||
|
|
||||||
|
if (toc.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav className="mb-6 text-sm">
|
||||||
|
<h3 className="text-xs font-semibold text-zinc-500 uppercase mb-2">
|
||||||
|
Contents
|
||||||
|
</h3>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{toc.map((entry) => (
|
||||||
|
<li key={entry.id} className={entry.level === 3 ? "ml-3" : ""}>
|
||||||
|
<Link
|
||||||
|
href={`#${entry.id}`}
|
||||||
|
className="text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-200 hover:underline"
|
||||||
|
>
|
||||||
|
{entry.text}
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
const STORAGE_KEY = "mcpedia-theme";
|
||||||
|
|
||||||
|
/** Dark mode toggle. Defaults to system preference, persisted in localStorage. */
|
||||||
|
export default function ThemeToggle() {
|
||||||
|
const [dark, setDark] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const stored = localStorage.getItem(STORAGE_KEY);
|
||||||
|
const initial =
|
||||||
|
stored === "dark" ||
|
||||||
|
(stored === null &&
|
||||||
|
window.matchMedia("(prefers-color-scheme: dark)").matches);
|
||||||
|
setDark(initial);
|
||||||
|
apply(initial);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function apply(isDark: boolean) {
|
||||||
|
document.documentElement.classList.toggle("dark", isDark);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle() {
|
||||||
|
const next = !dark;
|
||||||
|
setDark(next);
|
||||||
|
localStorage.setItem(STORAGE_KEY, next ? "dark" : "light");
|
||||||
|
apply(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={toggle}
|
||||||
|
aria-label="Toggle dark mode"
|
||||||
|
className="text-sm border border-zinc-300 dark:border-zinc-700 rounded px-2 py-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||||
|
>
|
||||||
|
{dark ? "🌙" : "☀️"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { listDocuments } from "@mcpedia/core";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const SECTIONS = ["docs", "writeups", "research", "notes"] as const;
|
||||||
|
|
||||||
|
export default async function DocsIndexPage() {
|
||||||
|
const all = await listDocuments();
|
||||||
|
const bySection = SECTIONS.map((section) => ({
|
||||||
|
section,
|
||||||
|
docs: all.filter((d) => d.section === section),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">All Documents</h1>
|
||||||
|
{bySection.map(({ section, docs }) => (
|
||||||
|
<section key={section}>
|
||||||
|
<h2 className="text-lg font-medium capitalize mb-3">{section}</h2>
|
||||||
|
{docs.length === 0 ? (
|
||||||
|
<p className="text-sm text-zinc-500">No documents in this section.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-2">
|
||||||
|
{docs.map((d) => (
|
||||||
|
<li key={d.slug}>
|
||||||
|
<Link href={`/${d.slug}`} className="hover:underline">
|
||||||
|
{d.title}
|
||||||
|
</Link>
|
||||||
|
<span className="text-xs text-zinc-500 ml-2">
|
||||||
|
{d.author || "unknown"}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Enable class-based dark mode (toggled by ThemeToggle via .dark on <html>). */
|
||||||
|
@custom-variant dark (&:where(.dark, .dark *));
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: #ffffff;
|
--background: #ffffff;
|
||||||
--foreground: #171717;
|
--foreground: #171717;
|
||||||
@@ -12,13 +15,6 @@
|
|||||||
--font-mono: var(--font-geist-mono);
|
--font-mono: var(--font-geist-mono);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
:root {
|
|
||||||
--background: #0a0a0a;
|
|
||||||
--foreground: #ededed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background: var(--background);
|
background: var(--background);
|
||||||
color: var(--foreground);
|
color: var(--foreground);
|
||||||
|
|||||||
+10
-7
@@ -1,6 +1,7 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
import ThemeToggle from "@/components/ThemeToggle";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "MCPedia",
|
title: "MCPedia",
|
||||||
@@ -20,15 +21,17 @@ export default function RootLayout({
|
|||||||
<Link href="/" className="font-semibold tracking-tight">
|
<Link href="/" className="font-semibold tracking-tight">
|
||||||
MCPedia
|
MCPedia
|
||||||
</Link>
|
</Link>
|
||||||
<nav className="flex gap-4 text-sm">
|
<nav className="flex items-center gap-4 text-sm">
|
||||||
<Link href="/" className="hover:underline">Home</Link>
|
<Link href="/" className="hover:underline">
|
||||||
<Link href="/search" className="hover:underline">Search</Link>
|
Home
|
||||||
<Link
|
</Link>
|
||||||
href="/docs"
|
<Link href="/search" className="hover:underline">
|
||||||
className="hover:underline"
|
Search
|
||||||
>
|
</Link>
|
||||||
|
<Link href="/docs" className="hover:underline">
|
||||||
Docs
|
Docs
|
||||||
</Link>
|
</Link>
|
||||||
|
<ThemeToggle />
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -12,13 +12,16 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@mcpedia/config": "workspace:*",
|
"@mcpedia/config": "workspace:*",
|
||||||
"@mcpedia/core": "workspace:*",
|
"@mcpedia/core": "workspace:*",
|
||||||
|
"github-slugger": "^2.0.0",
|
||||||
"next": "16.3.1",
|
"next": "16.3.1",
|
||||||
"react": "19.2.8",
|
"react": "19.2.8",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.2.8",
|
||||||
"react-markdown": "^9.0.0"
|
"react-markdown": "^9.0.0",
|
||||||
|
"rehype-slug": "^6.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/hast": "^3.0.5",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
|
|||||||
Reference in New Issue
Block a user