Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: visualize wiki frontmatter + render wikilinks as clickable chips

nash_succ1c1a528b7a
diff --git a/package-lock.json b/package-lock.json
index 9dd3c61a..f7755a11 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "llm-wiki",
- "version": "0.4.0",
+ "version": "0.4.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "llm-wiki",
- "version": "0.4.0",
+ "version": "0.4.3",
"dependencies": {
"@base-ui/react": "^1.3.0",
"@fontsource-variable/geist": "^5.2.8",
@@ -21,12 +21,14 @@
"@tauri-apps/plugin-http": "^2.5.8",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-store": "^2.4.2",
+ "@types/js-yaml": "^4.0.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"graphology": "^0.26.0",
"graphology-communities-louvain": "^2.0.2",
"graphology-layout-forceatlas2": "^0.10.1",
"i18next": "^26.0.3",
+ "js-yaml": "^4.1.1",
"katex": "^0.16.45",
"lucide-react": "^1.7.0",
"react": "^19.0.0",
@@ -2987,6 +2989,12 @@
"@types/unist": "*"
}
},
+ "node_modules/@types/js-yaml": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
+ "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
+ "license": "MIT"
+ },
"node_modules/@types/katex": {
"version": "0.16.8",
"resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.8.tgz",
diff --git a/package.json b/package.json
index b87f3b69..9c9696f7 100644
--- a/package.json
+++ b/package.json
@@ -27,12 +27,14 @@
"@tauri-apps/plugin-http": "^2.5.8",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-store": "^2.4.2",
+ "@types/js-yaml": "^4.0.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"graphology": "^0.26.0",
"graphology-communities-louvain": "^2.0.2",
"graphology-layout-forceatlas2": "^0.10.1",
"i18next": "^26.0.3",
+ "js-yaml": "^4.1.1",
"katex": "^0.16.45",
"lucide-react": "^1.7.0",
"react": "^19.0.0",
diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsx
index 550a7764..7261b0a7 100644
--- a/src/components/editor/file-preview.tsx
+++ b/src/components/editor/file-preview.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from "react"
+import { useEffect, useMemo, useRef } from "react"
import { convertFileSrc } from "@tauri-apps/api/core"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
@@ -17,6 +17,8 @@ import { getFileCategory, getCodeLanguage } from "@/lib/file-types"
import type { FileCategory } from "@/lib/file-types"
import { getFileName } from "@/lib/path-utils"
import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"
+import { parseFrontmatter } from "@/lib/frontmatter"
+import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"
import { useWikiStore } from "@/stores/wiki-store"
interface FilePreviewProps {
@@ -119,6 +121,8 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
const setPendingScrollImageSrc = useWikiStore((s) => s.setPendingScrollImageSrc)
const scrollRootRef = useRef<HTMLDivElement | null>(null)
+ const { frontmatter, body } = useMemo(() => parseFrontmatter(content), [content])
+
// Consume `pendingScrollImageSrc` once the file has rendered.
// We re-scan the DOM whenever:
// - file content changes (different page just loaded), OR
@@ -179,6 +183,7 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
<span>{filePath}</span>
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase">{label}</span>
</div>
+ {frontmatter && <FrontmatterPanel data={frontmatter} />}
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath]}
@@ -220,7 +225,7 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
),
}}
>
- {content}
+ {body}
</ReactMarkdown>
</div>
</div>
diff --git a/src/components/editor/frontmatter-panel.tsx b/src/components/editor/frontmatter-panel.tsx
new file mode 100644
index 00000000..52951177
--- /dev/null
+++ b/src/components/editor/frontmatter-panel.tsx
@@ -0,0 +1,354 @@
+import { useMemo } from "react"
+import {
+ FileText as FileTextIcon,
+ FileSpreadsheet,
+ FileJson,
+ FileCode,
+ FileImage,
+ Film,
+ Music,
+ File as FileIcon,
+ ArrowUpRight,
+ AlertTriangle,
+ Layers,
+ Calendar,
+ Tag as TagIcon,
+} from "lucide-react"
+import type { FrontmatterValue } from "@/lib/frontmatter"
+import { getWikiTypeStyle } from "@/lib/wiki-type-style"
+import {
+ resolveRelatedSlug,
+ resolveSourceName,
+ unwrapWikilink,
+} from "@/lib/wiki-page-resolver"
+import { useWikiStore } from "@/stores/wiki-store"
+import { normalizePath } from "@/lib/path-utils"
+
+interface FrontmatterPanelProps {
+ data: Record<string, FrontmatterValue>
+}
+
+const TOP_LEVEL_KEYS = new Set([
+ "title",
+ "type",
+ "tags",
+ "created",
+ "description",
+ "sources",
+ "related",
+ "origin",
+])
+
+export function FrontmatterPanel({ data }: FrontmatterPanelProps) {
+ const project = useWikiStore((s) => s.project)
+ const fileTree = useWikiStore((s) => s.fileTree)
+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+
+ const title = stringValue(data.title)
+ const type = stringValue(data.type)
+ const created = stringValue(data.created)
+ const description = stringValue(data.description)
+ const origin = stringValue(data.origin)
+ const tags = arrayValue(data.tags)
+ const sources = arrayValue(data.sources)
+ const related = arrayValue(data.related)
+
+ const extras = useMemo(
+ () =>
+ Object.entries(data).filter(([k, v]) => {
+ if (TOP_LEVEL_KEYS.has(k)) return false
+ if (Array.isArray(v) && v.length === 0) return false
+ if (v === "") return false
+ return true
+ }),
+ [data],
+ )
+
+ const projectPath = project ? normalizePath(project.path) : null
+ const wikiRoot = projectPath ? `${projectPath}/wiki` : null
+ const sourcesRoot = projectPath ? `${projectPath}/raw/sources` : null
+
+ const typeStyle = getWikiTypeStyle(type)
+ const TypeIcon = typeStyle.icon
+
+ const hasIdentity = title || type || tags.length > 0 || created
+ const hasRelations = sources.length > 0 || related.length > 0
+ const hasContent =
+ hasIdentity || description || origin || hasRelations || extras.length > 0
+ if (!hasContent) return null
+
+ function handleNavigate(path: string | null) {
+ if (!path) return
+ setSelectedFile(path)
+ }
+
+ return (
+ <div className="not-prose mb-5 overflow-hidden rounded-xl border border-border/60 bg-gradient-to-br from-muted/40 to-muted/10 shadow-sm">
+ {/* Identity strip ─────────────────────────────────────────── */}
+ <div className="flex items-start gap-3 px-4 pt-4">
+ <div
+ className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${typeStyle.chipClass}`}
+ title={typeStyle.label}
+ >
+ <TypeIcon className="h-5 w-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ {title && (
+ <div className="truncate text-base font-semibold leading-tight text-foreground">
+ {title}
+ </div>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-1.5 text-xs">
+ {type && (
+ <span
+ className={`rounded px-1.5 py-0.5 font-medium uppercase tracking-wide ${typeStyle.chipClass}`}
+ >
+ {typeStyle.label}
+ </span>
+ )}
+ {created && (
+ <span className="inline-flex items-center gap-1 text-muted-foreground">
+ <Calendar className="h-3 w-3" />
+ {created}
+ </span>
+ )}
+ {tags.map((tag) => (
+ <span
+ key={tag}
+ className="inline-flex items-center gap-0.5 rounded bg-muted px-1.5 py-0.5 text-muted-foreground"
+ >
+ <TagIcon className="h-3 w-3" />
+ {tag}
+ </span>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {description && (
+ <div className="px-4 pt-2 text-sm italic leading-relaxed text-muted-foreground">
+ {description}
+ </div>
+ )}
+
+ {origin && (
+ <div className="mx-4 mt-3 rounded border-l-2 border-primary/40 bg-primary/5 px-3 py-1.5 text-xs text-foreground/80">
+ <span className="font-medium text-muted-foreground">Origin: </span>
+ {origin}
+ </div>
+ )}
+
+ {/* Sources card row ───────────────────────────────────────── */}
+ {sources.length > 0 && (
+ <div className="px-4 pt-4">
+ <div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
+ <Layers className="h-3.5 w-3.5" />
+ Sources
+ <span className="text-muted-foreground/60">({sources.length})</span>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {sources.map((source) => {
+ const { slug, label } = unwrapWikilink(source)
+ const path = sourcesRoot
+ ? resolveSourceName(fileTree, slug, sourcesRoot)
+ : null
+ return (
+ <SourceCard
+ key={source}
+ name={label}
+ resolved={!!path}
+ onClick={() => handleNavigate(path)}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )}
+
+ {/* Related chips ──────────────────────────────────────────── */}
+ {related.length > 0 && (
+ <div className="px-4 pt-4">
+ <div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
+ <ArrowUpRight className="h-3.5 w-3.5" />
+ Related
+ <span className="text-muted-foreground/60">({related.length})</span>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {related.map((entry) => {
+ const { slug, label } = unwrapWikilink(entry)
+ const path = wikiRoot
+ ? resolveRelatedSlug(fileTree, slug, wikiRoot)
+ : null
+ return (
+ <RelatedChip
+ key={entry}
+ slug={label}
+ resolved={!!path}
+ onClick={() => handleNavigate(path)}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )}
+
+ {/* Extras (any other key/values we didn't surface above) ──── */}
+ {extras.length > 0 && (
+ <div className="mx-4 mt-4 rounded border border-border/40 bg-background/50 px-3 py-2 text-xs">
+ <div className="mb-1 font-medium text-muted-foreground/80">More</div>
+ <div className="space-y-0.5">
+ {extras.map(([k, v]) => (
+ <div key={k} className="flex gap-2">
+ <span className="shrink-0 font-mono text-muted-foreground">
+ {k}:
+ </span>
+ <span className="text-foreground/80">
+ {Array.isArray(v) ? v.join(", ") : v}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Bottom padding — done via wrapper not last child to keep
+ per-section spacing consistent regardless of which sections
+ are present. */}
+ <div className="h-4" />
+ </div>
+ )
+}
+
+function SourceCard({
+ name,
+ resolved,
+ onClick,
+}: {
+ name: string
+ resolved: boolean
+ onClick: () => void
+}) {
+ const Icon = iconForSource(name)
+ return (
+ <button
+ type="button"
+ onClick={resolved ? onClick : undefined}
+ title={resolved ? `Open ${name}` : `Source not found in raw/sources/: ${name}`}
+ className={`group flex min-w-0 max-w-[200px] items-center gap-2 rounded-md border px-2.5 py-1.5 text-left text-xs transition-colors ${
+ resolved
+ ? "border-border/60 bg-background hover:border-primary/40 hover:bg-primary/5 cursor-pointer"
+ : "border-dashed border-border/50 bg-muted/20 text-muted-foreground/70 cursor-default"
+ }`}
+ >
+ <Icon className={`h-4 w-4 shrink-0 ${resolved ? "text-foreground/70" : "text-muted-foreground/60"}`} />
+ <span className="truncate">{name}</span>
+ {!resolved && <AlertTriangle className="h-3 w-3 shrink-0 text-amber-500/70" />}
+ </button>
+ )
+}
+
+function RelatedChip({
+ slug,
+ resolved,
+ onClick,
+}: {
+ slug: string
+ resolved: boolean
+ onClick: () => void
+}) {
+ return (
+ <button
+ type="button"
+ onClick={resolved ? onClick : undefined}
+ title={resolved ? `Open ${slug}` : `Related page not found: ${slug}`}
+ className={`group inline-flex max-w-[260px] items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
+ resolved
+ ? "border-border/60 bg-background hover:border-primary/50 hover:bg-primary/10 cursor-pointer"
+ : "border-dashed border-border/50 bg-muted/20 text-muted-foreground/70 cursor-default"
+ }`}
+ >
+ <span className="truncate">{slug}</span>
+ {resolved ? (
+ <ArrowUpRight className="h-3 w-3 shrink-0 opacity-60 group-hover:opacity-100" />
+ ) : (
+ <AlertTriangle className="h-3 w-3 shrink-0 text-amber-500/70" />
+ )}
+ </button>
+ )
+}
+
+function iconForSource(name: string) {
+ const ext = name.split(".").pop()?.toLowerCase() ?? ""
+ switch (ext) {
+ case "pdf":
+ return FileTextIcon
+ case "xlsx":
+ case "xls":
+ case "csv":
+ case "tsv":
+ case "ods":
+ return FileSpreadsheet
+ case "json":
+ case "jsonl":
+ case "yaml":
+ case "yml":
+ case "ndjson":
+ return FileJson
+ case "py":
+ case "js":
+ case "ts":
+ case "tsx":
+ case "jsx":
+ case "rs":
+ case "go":
+ case "java":
+ case "c":
+ case "cpp":
+ case "rb":
+ case "php":
+ return FileCode
+ case "png":
+ case "jpg":
+ case "jpeg":
+ case "gif":
+ case "webp":
+ case "bmp":
+ case "svg":
+ return FileImage
+ case "mp4":
+ case "webm":
+ case "mov":
+ case "avi":
+ case "mkv":
+ return Film
+ case "mp3":
+ case "wav":
+ case "ogg":
+ case "flac":
+ case "m4a":
+ return Music
+ case "md":
+ case "mdx":
+ case "txt":
+ case "rtf":
+ case "html":
+ case "htm":
+ case "xml":
+ case "docx":
+ case "doc":
+ case "pptx":
+ case "ppt":
+ return FileTextIcon
+ default:
+ return FileIcon
+ }
+}
+
+function stringValue(v: FrontmatterValue | undefined): string | null {
+ return typeof v === "string" && v.trim() !== "" ? v : null
+}
+
+function arrayValue(v: FrontmatterValue | undefined): string[] {
+ if (!Array.isArray(v)) return []
+ return v.filter((x): x is string => typeof x === "string" && x.trim() !== "")
+}
diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsx
index 6c804479..390f72ba 100644
--- a/src/components/editor/wiki-editor.tsx
+++ b/src/components/editor/wiki-editor.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useRef } from "react"
+import { useMemo, useRef, useState } from "react"
import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core"
import { commonmark } from "@milkdown/kit/preset/commonmark"
import { gfm } from "@milkdown/kit/preset/gfm"
@@ -9,6 +9,10 @@ import { nord } from "@milkdown/theme-nord"
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react"
import "@milkdown/theme-nord/style.css"
import "katex/dist/katex.min.css"
+import { Pencil, Eye } from "lucide-react"
+import { parseFrontmatter } from "@/lib/frontmatter"
+import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"
+import { WikiReader } from "@/components/editor/wiki-reader"
interface WikiEditorInnerProps {
content: string
@@ -63,13 +67,62 @@ function wrapBareMathBlocks(text: string): string {
}
export function WikiEditor({ content, onSave }: WikiEditorProps) {
- const processedContent = useMemo(() => wrapBareMathBlocks(content), [content])
+ // Default to read mode (ReactMarkdown render). Edit mode swaps
+ // in Milkdown WYSIWYG. We default to read because:
+ // 1. Milkdown's commonmark/gfm preset has no wikilink schema,
+ // so `[[…]]` shows up as raw text — exactly what users
+ // called out as "looking like raw code".
+ // 2. We can pre-process wikilinks for the read view safely
+ // (the rendered output is throwaway). Doing the same in
+ // Milkdown would be a save-corruption hazard because
+ // Milkdown serializes its current state on save — the
+ // transformed `[label](#slug)` would overwrite the
+ // original `[[…]]` source.
+ // 3. Users read wiki pages far more often than they edit
+ // them; the toggle makes editing a deliberate action
+ // rather than the default state.
+ const [mode, setMode] = useState<"read" | "edit">("read")
+
+ // Split frontmatter from body. Both modes consume `body`;
+ // Milkdown additionally rebuilds the full file via `rawBlock`
+ // on save so user-managed YAML survives untouched.
+ const { frontmatter, body, rawBlock } = useMemo(
+ () => parseFrontmatter(content),
+ [content],
+ )
+
+ const processedBody = useMemo(() => wrapBareMathBlocks(body), [body])
+
+ const handleSave = useMemo(
+ () => (markdown: string) => onSave(rawBlock + markdown),
+ [onSave, rawBlock],
+ )
return (
- <MilkdownProvider>
- <div className="prose prose-invert min-w-0 max-w-none overflow-hidden p-6">
- <WikiEditorInner content={processedContent} onSave={onSave} />
- </div>
- </MilkdownProvider>
+ <div className="relative h-full overflow-auto">
+ <button
+ type="button"
+ onClick={() => setMode((m) => (m === "read" ? "edit" : "read"))}
+ title={mode === "read" ? "Edit (raw markdown)" : "Done editing"}
+ className="absolute right-3 top-3 z-10 inline-flex items-center gap-1 rounded-md border border-border/60 bg-background/90 px-2 py-1 text-xs text-muted-foreground shadow-sm hover:bg-accent hover:text-foreground"
+ >
+ {mode === "read" ? <Pencil className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
+ {mode === "read" ? "Edit" : "Done"}
+ </button>
+
+ {mode === "read" ? (
+ <div className="px-6 py-6">
+ {frontmatter && <FrontmatterPanel data={frontmatter} />}
+ <WikiReader body={body} />
+ </div>
+ ) : (
+ <MilkdownProvider>
+ <div className="prose prose-invert min-w-0 max-w-none overflow-hidden p-6">
+ {frontmatter && <FrontmatterPanel data={frontmatter} />}
+ <WikiEditorInner content={processedBody} onSave={handleSave} />
+ </div>
+ </MilkdownProvider>
+ )}
+ </div>
)
}
diff --git a/src/components/editor/wiki-reader.tsx b/src/components/editor/wiki-reader.tsx
new file mode 100644
index 00000000..bf74c675
--- /dev/null
+++ b/src/components/editor/wiki-reader.tsx
@@ -0,0 +1,122 @@
+import { useMemo } from "react"
+import ReactMarkdown from "react-markdown"
+import remarkGfm from "remark-gfm"
+import remarkMath from "remark-math"
+import rehypeKatex from "rehype-katex"
+import "katex/dist/katex.min.css"
+import { transformWikilinks } from "@/lib/wikilink-transform"
+import { resolveRelatedSlug } from "@/lib/wiki-page-resolver"
+import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"
+import { normalizePath } from "@/lib/path-utils"
+import { useWikiStore } from "@/stores/wiki-store"
+
+interface WikiReaderProps {
+ body: string
+}
+
+/**
+ * Read-only render of a wiki page body. Distinct from WikiEditor
+ * (Milkdown WYSIWYG) because Milkdown round-trips the markdown
+ * through prosemirror — applying our wikilink → markdown-link
+ * pre-processing there would mean the user's saves overwrite the
+ * original `[[…]]` source with `[label](#slug)`. Here, since we
+ * never serialize back to disk, transforming for display is safe.
+ *
+ * Wikilink anchor clicks are intercepted: `#slug` is resolved
+ * against the project's wiki tree and routed to setSelectedFile,
+ * giving the user single-click navigation between pages.
+ */
+export function WikiReader({ body }: WikiReaderProps) {
+ const project = useWikiStore((s) => s.project)
+ const fileTree = useWikiStore((s) => s.fileTree)
+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+
+ const transformed = useMemo(() => transformWikilinks(body), [body])
+ const projectPath = project ? normalizePath(project.path) : null
+ const wikiRoot = projectPath ? `${projectPath}/wiki` : null
+
+ function handleAnchorClick(e: React.MouseEvent<HTMLAnchorElement>, href: string) {
+ if (!href.startsWith("#")) return
+ e.preventDefault()
+ if (!wikiRoot) return
+ const slug = (() => {
+ try {
+ return decodeURIComponent(href.slice(1))
+ } catch {
+ return href.slice(1)
+ }
+ })()
+ const path = resolveRelatedSlug(fileTree, slug, wikiRoot)
+ if (path) setSelectedFile(path)
+ }
+
+ return (
+ <div className="prose prose-invert min-w-0 max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ components={{
+ a: ({ href, children, ...props }) => {
+ const h = typeof href === "string" ? href : ""
+ const isWikilink = h.startsWith("#")
+ return (
+ <a
+ href={h || undefined}
+ onClick={(e) => isWikilink && handleAnchorClick(e, h)}
+ className={
+ isWikilink
+ ? "cursor-pointer text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary"
+ : "text-primary underline underline-offset-2"
+ }
+ {...props}
+ >
+ {children}
+ </a>
+ )
+ },
+ img: ({ src, alt, ...props }) => (
+ <img
+ src={
+ typeof src === "string"
+ ? resolveMarkdownImageSrc(src, projectPath)
+ : undefined
+ }
+ data-mdsrc={typeof src === "string" ? src : undefined}
+ alt={alt ?? ""}
+ className="max-w-full rounded border border-border/40"
+ loading="lazy"
+ {...props}
+ />
+ ),
+ table: ({ children, ...props }) => (
+ <div className="my-2 overflow-x-auto rounded border border-border">
+ <table className="w-full border-collapse text-xs" {...props}>
+ {children}
+ </table>
+ </div>
+ ),
+ thead: ({ children, ...props }) => (
+ <thead className="bg-muted" {...props}>
+ {children}
+ </thead>
+ ),
+ th: ({ children, ...props }) => (
+ <th
+ className="border border-border/80 bg-muted px-3 py-1.5 text-left font-semibold"
+ {...props}
+ >
+ {children}
+ </th>
+ ),
+ td: ({ children, ...props }) => (
+ <td className="border border-border/60 px-3 py-1.5" {...props}>
+ {children}
+ </td>
+ ),
+ }}
+ >
+ {transformed}
+ </ReactMarkdown>
+ </div>
+ )
+}
diff --git a/src/lib/frontmatter.test.ts b/src/lib/frontmatter.test.ts
new file mode 100644
index 00000000..7bf78f2c
--- /dev/null
+++ b/src/lib/frontmatter.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect } from "vitest"
+import { parseFrontmatter } from "./frontmatter"
+
+describe("parseFrontmatter", () => {
+ it("returns null + full body when content has no frontmatter", () => {
+ const r = parseFrontmatter("# Hello\nbody text")
+ expect(r.frontmatter).toBeNull()
+ expect(r.body).toBe("# Hello\nbody text")
+ expect(r.rawBlock).toBe("")
+ })
+
+ it("strips a basic frontmatter block and returns the body", () => {
+ const content = `---\ntype: entity\ntitle: "Foo"\n---\n\n# Body`
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter).toEqual({ type: "entity", title: "Foo" })
+ expect(r.body).toBe("# Body")
+ })
+
+ it("rawBlock + body equals the original content for well-formed input", () => {
+ const cases = [
+ `---\ntype: x\n---\nbody`,
+ `---\ntype: x\n---\n\nbody with leading blank line`,
+ `# No frontmatter at all`,
+ `---\ntype: x\ntitle: "Foo"\ntags: [a, b]\n---\n\n# Heading`,
+ ]
+ for (const content of cases) {
+ const r = parseFrontmatter(content)
+ expect(r.rawBlock + r.body).toBe(content)
+ }
+ })
+
+ it("parses inline arrays", () => {
+ const r = parseFrontmatter(`---\ntags: [foo, bar, baz]\n---\nx`)
+ expect(r.frontmatter).toEqual({ tags: ["foo", "bar", "baz"] })
+ })
+
+ it("parses block-style arrays (the YAML `- item` syntax)", () => {
+ const content =
+ `---\nrelated:\n - foo.md\n - bar.md\n - baz.md\n---\nbody`
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter).toEqual({ related: ["foo.md", "bar.md", "baz.md"] })
+ expect(r.body).toBe("body")
+ })
+
+ it("doesn't interpret YYYY-MM-DD scalars as Date objects (JSON_SCHEMA)", () => {
+ const r = parseFrontmatter(`---\ncreated: 2026-04-09\n---\nbody`)
+ expect(r.frontmatter).toEqual({ created: "2026-04-09" })
+ })
+
+ it("handles CJK/Unicode tags without quoting", () => {
+ const r = parseFrontmatter(
+ `---\ntags: [污水处理, 功能微生物, NOB优势菌]\n---\nbody`,
+ )
+ expect(r.frontmatter).toEqual({
+ tags: ["污水处理", "功能微生物", "NOB优势菌"],
+ })
+ })
+
+ it("strips quotes from string scalars", () => {
+ const r = parseFrontmatter(`---\ntitle: "Hello World"\n---\nx`)
+ expect(r.frontmatter).toEqual({ title: "Hello World" })
+ })
+
+ it("handles a frontmatter-only file with no body", () => {
+ const r = parseFrontmatter(`---\ntype: entity\n---\n`)
+ expect(r.frontmatter).toEqual({ type: "entity" })
+ expect(r.body).toBe("")
+ })
+
+ it("handles CRLF line endings", () => {
+ const content = "---\r\ntype: query\r\n---\r\n\r\nbody"
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter).toEqual({ type: "query" })
+ expect(r.body).toBe("body")
+ })
+
+ it("returns null frontmatter when YAML is malformed but still strips the fence block", () => {
+ const content = `---\nthis is not: : valid\n malformed\n---\nbody`
+ const r = parseFrontmatter(content)
+ // YAML parser may or may not error on this; either way we
+ // shouldn't crash. If it errors, we return body without the
+ // fence block. If it parses, we return whatever it produced.
+ expect(typeof r.body).toBe("string")
+ expect(r.body).toBe("body")
+ })
+
+ it("matches the real Accumulibacter frontmatter (block array of paths)", () => {
+ const content =
+ `---\ntype: entity\ntitle: "Accumulibacter"\ncreated: 2026-04-09\nupdated: 2026-04-09\ntags: [microorganism, PAO, DPAO, phosphorus-removal, Betaproteobacteria]\nrelated:\n - wiki/entities/dpao.md\n - wiki/entities/paos.md\n - wiki/concepts/denitrifying-phosphorus-removal.md\nsources: ["research-foo-2026-04-09.md"]\n---\n\n# Body`
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter?.type).toBe("entity")
+ expect(r.frontmatter?.title).toBe("Accumulibacter")
+ expect(r.frontmatter?.related).toEqual([
+ "wiki/entities/dpao.md",
+ "wiki/entities/paos.md",
+ "wiki/concepts/denitrifying-phosphorus-removal.md",
+ ])
+ expect(r.frontmatter?.sources).toEqual(["research-foo-2026-04-09.md"])
+ expect(r.body).toBe("# Body")
+ })
+
+ it("matches the real Nitrospira frontmatter (all inline arrays, CJK tags)", () => {
+ const content =
+ `---\ntype: entity\ntitle: Nitrospira\ncreated: 2026-04-07\nupdated: 2026-04-07\ntags: [污水处理, 功能微生物, 亚硝酸盐氧化细菌, NOB优势菌]\nrelated: [nitrite-oxidizing-bacteria, nitrifying-bacteria, nh3-n]\nsources: ["research--2026-04-07.md"]\n---\n`
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter?.type).toBe("entity")
+ expect(r.frontmatter?.title).toBe("Nitrospira")
+ expect(r.frontmatter?.tags).toEqual([
+ "污水处理", "功能微生物", "亚硝酸盐氧化细菌", "NOB优势菌",
+ ])
+ expect(r.frontmatter?.related).toEqual([
+ "nitrite-oxidizing-bacteria",
+ "nitrifying-bacteria",
+ "nh3-n",
+ ])
+ expect(r.frontmatter?.sources).toEqual(["research--2026-04-07.md"])
+ })
+
+ it("matches the real BOD entity frontmatter (quoted wikilink items in block array)", () => {
+ const content =
+ `---\ntype: entity\ntitle: BOD(生化需氧量)\ncreated: 2026-04-07\nupdated: 2026-04-07\ntags: [水质指标, 环境监测, 污水处理, 核心参数]\nrelated:\n - "[[nh3-n]]"\n - "[[soft-sensor-watertreatment]]"\n - "[[ai-effluent-water-quality-prediction]]"\n - "[[digital-twin-wastewater]]"\nsources: ["research-ai-2026-04-07.md"]\n---\n\n# Body`
+ const r = parseFrontmatter(content)
+ expect(r.frontmatter?.title).toBe("BOD(生化需氧量)")
+ expect(r.frontmatter?.related).toEqual([
+ "[[nh3-n]]",
+ "[[soft-sensor-watertreatment]]",
+ "[[ai-effluent-water-quality-prediction]]",
+ "[[digital-twin-wastewater]]",
+ ])
+ expect(r.body).toBe("# Body")
+ })
+})
diff --git a/src/lib/frontmatter.ts b/src/lib/frontmatter.ts
new file mode 100644
index 00000000..98053d47
--- /dev/null
+++ b/src/lib/frontmatter.ts
@@ -0,0 +1,85 @@
+import yaml from "js-yaml"
+
+export type FrontmatterValue = string | string[]
+
+export interface FrontmatterParseResult {
+ frontmatter: Record<string, FrontmatterValue> | null
+ body: string
+ /**
+ * The literal frontmatter block (opening `---`, YAML payload,
+ * closing `---`, plus the newlines that separate it from the
+ * body) as it appears in the input. Empty string when there is
+ * no frontmatter. Callers that edit only the body — e.g. the
+ * WikiEditor — write back `rawBlock + body` so user-managed YAML
+ * survives untouched.
+ */
+ rawBlock: string
+}
+
+// Single, generic detector. Both fence lines must be on their own
+// line (anchored with `^...$` under the `m` flag); content between
+// is delegated to a real YAML parser. We do NOT try to special-case
+// trailing whitespace, BOMs, alternative fence markers, or LLM
+// corruption patterns here — that path leads to ever-growing regex
+// patches with no real progress. If the file isn't a standard
+// `---\n…\n---` document, we treat it as "no frontmatter" and let
+// the body render in full.
+const FM_BLOCK_RE = /^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/
+
+export function parseFrontmatter(content: string): FrontmatterParseResult {
+ const match = content.match(FM_BLOCK_RE)
+ if (!match) return { frontmatter: null, body: content, rawBlock: "" }
+
+ const yamlPayload = match[1]
+ const rawBlock = match[0]
+ const body = content.slice(rawBlock.length)
+
+ let parsed: unknown
+ try {
+ parsed = yaml.load(yamlPayload, { schema: yaml.JSON_SCHEMA })
+ } catch {
+ // Malformed YAML — degrade gracefully. Treat the file as having
+ // no parseable frontmatter, but keep stripping the fence block
+ // so the user doesn't see a wall of `key: value` text in the
+ // rendered body.
+ return { frontmatter: null, body, rawBlock }
+ }
+
+ return {
+ frontmatter: normalize(parsed),
+ body,
+ rawBlock,
+ }
+}
+
+/**
+ * Coerce js-yaml's output into the shape FrontmatterPanel consumes:
+ * a flat `Record<string, string | string[]>`. Nested objects and
+ * scalars that aren't strings are stringified so unusual YAML
+ * still surfaces in the UI rather than silently disappearing.
+ */
+function normalize(parsed: unknown): Record<string, FrontmatterValue> | null {
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null
+ const out: Record<string, FrontmatterValue> = {}
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
+ if (Array.isArray(value)) {
+ out[key] = value.map((v) => stringifyScalar(v))
+ continue
+ }
+ out[key] = stringifyScalar(value)
+ }
+ return out
+}
+
+function stringifyScalar(v: unknown): string {
+ if (v === null || v === undefined) return ""
+ if (typeof v === "string") return v
+ if (typeof v === "number" || typeof v === "boolean") return String(v)
+ if (v instanceof Date) return v.toISOString().slice(0, 10)
+ // Object / nested array → JSON so the user still sees something.
+ try {
+ return JSON.stringify(v)
+ } catch {
+ return String(v)
+ }
+}
diff --git a/src/lib/wiki-page-resolver.test.ts b/src/lib/wiki-page-resolver.test.ts
new file mode 100644
index 00000000..44767607
--- /dev/null
+++ b/src/lib/wiki-page-resolver.test.ts
@@ -0,0 +1,185 @@
+import { describe, it, expect } from "vitest"
+import type { FileNode } from "@/types/wiki"
+import {
+ findInTreeByName,
+ resolveRelatedSlug,
+ resolveSourceName,
+ unwrapWikilink,
+} from "./wiki-page-resolver"
+
+const PP = "/p"
+const WIKI = `${PP}/wiki`
+const SOURCES = `${PP}/raw/sources`
+
+function file(path: string): FileNode {
+ const name = path.split("/").pop()!
+ return { name, path, is_dir: false }
+}
+function dir(path: string, children: FileNode[]): FileNode {
+ const name = path.split("/").pop()!
+ return { name, path, is_dir: true, children }
+}
+
+const TREE: FileNode[] = [
+ dir(`${PP}/wiki`, [
+ dir(`${WIKI}/entities`, [file(`${WIKI}/entities/foo.md`)]),
+ dir(`${WIKI}/concepts`, [file(`${WIKI}/concepts/bar.md`)]),
+ dir(`${WIKI}/queries`, [file(`${WIKI}/queries/what-is-foo.md`)]),
+ dir(`${WIKI}/sources`, [file(`${WIKI}/sources/paper.md`)]),
+ ]),
+ dir(`${PP}/raw`, [
+ dir(`${SOURCES}`, [
+ file(`${SOURCES}/report.pdf`),
+ dir(`${SOURCES}/year-2025`, [
+ file(`${SOURCES}/year-2025/q1.pdf`),
+ file(`${SOURCES}/year-2025/notes.md`),
+ ]),
+ ]),
+ ]),
+]
+
+describe("unwrapWikilink", () => {
+ it("unwraps a bare [[target]]", () => {
+ expect(unwrapWikilink("[[nh3-n]]")).toEqual({ slug: "nh3-n", label: "nh3-n" })
+ })
+
+ it("unwraps [[target|alias]] and uses alias as label", () => {
+ expect(unwrapWikilink("[[nh3-n|NH3-N (氨氮)]]")).toEqual({
+ slug: "nh3-n",
+ label: "NH3-N (氨氮)",
+ })
+ })
+
+ it("trims whitespace inside the wikilink", () => {
+ expect(unwrapWikilink("[[ nh3-n | 氨氮 ]]")).toEqual({
+ slug: "nh3-n",
+ label: "氨氮",
+ })
+ })
+
+ it("returns input unchanged for non-wikilink strings", () => {
+ expect(unwrapWikilink("nh3-n")).toEqual({ slug: "nh3-n", label: "nh3-n" })
+ expect(unwrapWikilink("wiki/entities/nh3-n.md")).toEqual({
+ slug: "wiki/entities/nh3-n.md",
+ label: "wiki/entities/nh3-n.md",
+ })
+ })
+
+ it("does not match partial brackets", () => {
+ expect(unwrapWikilink("[[broken")).toEqual({ slug: "[[broken", label: "[[broken" })
+ expect(unwrapWikilink("broken]]")).toEqual({ slug: "broken]]", label: "broken]]" })
+ })
+
+ it("returns target when alias is empty pipe", () => {
+ expect(unwrapWikilink("[[nh3-n|]]")).toEqual({ slug: "nh3-n", label: "nh3-n" })
+ })
+})
+
+describe("findInTreeByName", () => {
+ it("returns null on an empty tree", () => {
+ expect(findInTreeByName([], "foo.md", "/wiki/")).toBeNull()
+ })
+
+ it("finds a file at the top of a subtree", () => {
+ expect(findInTreeByName(TREE, "foo.md", `${WIKI}/`)).toBe(`${WIKI}/entities/foo.md`)
+ })
+
+ it("recurses into nested directories", () => {
+ expect(findInTreeByName(TREE, "q1.pdf", `${SOURCES}/`)).toBe(
+ `${SOURCES}/year-2025/q1.pdf`,
+ )
+ })
+
+ it("respects pathContains as a subtree filter", () => {
+ // "notes.md" exists under raw/sources/year-2025 but not under wiki/.
+ expect(findInTreeByName(TREE, "notes.md", `${WIKI}/`)).toBeNull()
+ expect(findInTreeByName(TREE, "notes.md", `${SOURCES}/`)).toBe(
+ `${SOURCES}/year-2025/notes.md`,
+ )
+ })
+
+ it("returns null when nothing matches", () => {
+ expect(findInTreeByName(TREE, "missing.md", `${WIKI}/`)).toBeNull()
+ })
+})
+
+describe("resolveRelatedSlug", () => {
+ it("appends .md and finds entities by bare slug", () => {
+ expect(resolveRelatedSlug(TREE, "foo", WIKI)).toBe(`${WIKI}/entities/foo.md`)
+ })
+
+ it("finds queries with hyphenated slugs", () => {
+ expect(resolveRelatedSlug(TREE, "what-is-foo", WIKI)).toBe(
+ `${WIKI}/queries/what-is-foo.md`,
+ )
+ })
+
+ it("accepts bare filename with .md extension", () => {
+ expect(resolveRelatedSlug(TREE, "foo.md", WIKI)).toBe(`${WIKI}/entities/foo.md`)
+ })
+
+ it("accepts a project-relative wiki path", () => {
+ expect(resolveRelatedSlug(TREE, "wiki/entities/foo.md", WIKI)).toBe(
+ `${WIKI}/entities/foo.md`,
+ )
+ })
+
+ it("accepts a project-relative path under nested wiki subfolder", () => {
+ expect(resolveRelatedSlug(TREE, "wiki/concepts/bar.md", WIKI)).toBe(
+ `${WIKI}/concepts/bar.md`,
+ )
+ })
+
+ it("returns null when slug doesn't exist", () => {
+ expect(resolveRelatedSlug(TREE, "ghost", WIKI)).toBeNull()
+ })
+
+ it("returns null when path-like ref doesn't exist", () => {
+ expect(resolveRelatedSlug(TREE, "wiki/entities/ghost.md", WIKI)).toBeNull()
+ })
+
+ it("never returns a path under raw/sources, even if a matching .md exists there", () => {
+ expect(resolveRelatedSlug(TREE, "notes", WIKI)).toBeNull()
+ })
+
+ it("rejects path-like refs that point outside wiki/", () => {
+ expect(resolveRelatedSlug(TREE, "raw/sources/year-2025/notes.md", WIKI)).toBeNull()
+ })
+})
+
+describe("resolveSourceName", () => {
+ it("finds a top-level source file", () => {
+ expect(resolveSourceName(TREE, "report.pdf", SOURCES)).toBe(
+ `${SOURCES}/report.pdf`,
+ )
+ })
+
+ it("finds a source nested in a subfolder", () => {
+ expect(resolveSourceName(TREE, "q1.pdf", SOURCES)).toBe(
+ `${SOURCES}/year-2025/q1.pdf`,
+ )
+ })
+
+ it("returns null when filename doesn't exist", () => {
+ expect(resolveSourceName(TREE, "ghost.pdf", SOURCES)).toBeNull()
+ })
+
+ it("prefers wiki/sources/<name>.md over raw/sources for bare .md refs", () => {
+ // paper.md only exists under wiki/sources, so it should resolve there.
+ expect(resolveSourceName(TREE, "paper.md", SOURCES)).toBe(
+ `${WIKI}/sources/paper.md`,
+ )
+ })
+
+ it("accepts a project-relative path", () => {
+ expect(resolveSourceName(TREE, "raw/sources/year-2025/q1.pdf", SOURCES)).toBe(
+ `${SOURCES}/year-2025/q1.pdf`,
+ )
+ })
+
+ it("accepts a project-relative wiki/sources path", () => {
+ expect(resolveSourceName(TREE, "wiki/sources/paper.md", SOURCES)).toBe(
+ `${WIKI}/sources/paper.md`,
+ )
+ })
+})
diff --git a/src/lib/wiki-page-resolver.ts b/src/lib/wiki-page-resolver.ts
new file mode 100644
index 00000000..5893b3ab
--- /dev/null
+++ b/src/lib/wiki-page-resolver.ts
@@ -0,0 +1,133 @@
+import type { FileNode } from "@/types/wiki"
+
+/**
+ * Strip Obsidian-style `[[target]]` or `[[target|alias]]` wrapping
+ * from a value, returning `{ slug, label }`. Frontmatter authors
+ * (humans and the LLM) sometimes write related entries as
+ * wikilinks instead of bare slugs; we want to display the alias
+ * (or target) without the bracket noise and look up by target.
+ *
+ * Non-wikilink input is returned with `slug === label === input`.
+ */
+export function unwrapWikilink(s: string): { slug: string; label: string } {
+ const m = s.match(/^\[\[([^\]|]+)(?:\|([^\]]*))?\]\]$/)
+ if (!m) return { slug: s, label: s }
+ const target = m[1].trim()
+ const alias = m[2]?.trim()
+ return { slug: target, label: alias && alias.length > 0 ? alias : target }
+}
+
+/**
+ * Walk a FileNode tree and return the absolute path of the first
+ * file whose name matches `targetName`, restricted to subtrees that
+ * sit underneath any directory whose absolute path contains
+ * `pathContains`. Returns null when nothing matches.
+ *
+ * Used by the frontmatter panel to resolve `related: [slug]` to a
+ * concrete `wiki/.../<slug>.md` path so a chip can navigate, and
+ * `sources: [name.pdf]` to a `raw/sources/.../name.pdf` path so a
+ * card can open the raw file. We intentionally take the first
+ * match — duplicate basenames across subfolders are a wiki-author
+ * collision the user sees in the file tree anyway, and resolving
+ * arbitrarily is no worse than the prior text-only display.
+ */
+export function findInTreeByName(
+ tree: FileNode[],
+ targetName: string,
+ pathContains: string,
+): string | null {
+ function walk(nodes: FileNode[]): string | null {
+ for (const node of nodes) {
+ if (node.is_dir) {
+ if (node.children) {
+ const r = walk(node.children)
+ if (r) return r
+ }
+ continue
+ }
+ if (node.name === targetName && node.path.includes(pathContains)) {
+ return node.path
+ }
+ }
+ return null
+ }
+ return walk(tree)
+}
+
+/**
+ * Resolve a `related:` reference to an absolute wiki page path.
+ * Accepts three shapes the wiki has historically written:
+ * 1. project-relative path: `wiki/entities/dpao.md`
+ * 2. bare filename with .md: `dpao.md`
+ * 3. bare slug: `dpao`
+ * Returns the absolute path of an existing file, or null if none
+ * matches. Always restricts the lookup to `wiki/` to avoid pulling
+ * in a same-named file from `raw/sources/`.
+ */
+export function resolveRelatedSlug(
+ tree: FileNode[],
+ ref: string,
+ wikiRoot: string,
+): string | null {
+ // Path-like → resolve relative to project root (one segment up
+ // from wikiRoot).
+ if (ref.includes("/")) {
+ const projectRoot = wikiRoot.replace(/\/wiki$/, "")
+ const target = `${projectRoot}/${ref}`
+ const found = findInTreeByPath(tree, target)
+ return found && found.includes(`${wikiRoot}/`) ? found : null
+ }
+
+ const filename = ref.endsWith(".md") ? ref : `${ref}.md`
+ return findInTreeByName(tree, filename, `${wikiRoot}/`)
+}
+
+/**
+ * Resolve a `sources:` reference. Accepts:
+ * 1. project-relative path: `wiki/sources/foo.md` or
+ * `raw/sources/year-2025/q1.pdf`
+ * 2. bare filename with ext: `q1.pdf`
+ * 3. wiki source-summary: `foo.md` (in wiki/sources/)
+ * Tries wiki/sources/ first when the ref is a bare .md filename
+ * (the ingest pipeline writes summary pages there), then falls
+ * back to raw/sources/. Returns null if nothing matches.
+ */
+export function resolveSourceName(
+ tree: FileNode[],
+ ref: string,
+ sourcesRoot: string,
+): string | null {
+ // sourcesRoot is `<project>/raw/sources` — derive project root
+ // and wiki/ root from it.
+ const projectRoot = sourcesRoot.replace(/\/raw\/sources$/, "")
+ const wikiSources = `${projectRoot}/wiki/sources`
+
+ if (ref.includes("/")) {
+ const target = `${projectRoot}/${ref}`
+ return findInTreeByPath(tree, target)
+ }
+
+ // Bare .md filename → look in wiki/sources/ first (ingest's
+ // canonical home for source-summary pages).
+ if (ref.endsWith(".md")) {
+ const inWiki = findInTreeByName(tree, ref, `${wikiSources}/`)
+ if (inWiki) return inWiki
+ }
+
+ // Otherwise, search raw/sources/.
+ return findInTreeByName(tree, ref, `${sourcesRoot}/`)
+}
+
+function findInTreeByPath(tree: FileNode[], targetPath: string): string | null {
+ function walk(nodes: FileNode[]): string | null {
+ for (const node of nodes) {
+ if (node.path === targetPath) return node.path
+ if (node.is_dir && node.children) {
+ const r = walk(node.children)
+ if (r) return r
+ }
+ }
+ return null
+ }
+ return walk(tree)
+}
diff --git a/src/lib/wiki-type-style.test.ts b/src/lib/wiki-type-style.test.ts
new file mode 100644
index 00000000..d0215364
--- /dev/null
+++ b/src/lib/wiki-type-style.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect } from "vitest"
+import {
+ getWikiTypeStyle,
+ WIKI_TYPE_STYLES,
+ FALLBACK_TYPE_STYLE,
+} from "./wiki-type-style"
+
+describe("getWikiTypeStyle", () => {
+ it("returns the entity style for 'entity'", () => {
+ expect(getWikiTypeStyle("entity")).toBe(WIKI_TYPE_STYLES.entity)
+ })
+
+ it("is case-insensitive", () => {
+ expect(getWikiTypeStyle("ENTITY")).toBe(WIKI_TYPE_STYLES.entity)
+ expect(getWikiTypeStyle("Concept")).toBe(WIKI_TYPE_STYLES.concept)
+ })
+
+ it("trims surrounding whitespace", () => {
+ expect(getWikiTypeStyle(" query ")).toBe(WIKI_TYPE_STYLES.query)
+ })
+
+ it("returns fallback for null", () => {
+ expect(getWikiTypeStyle(null)).toBe(FALLBACK_TYPE_STYLE)
+ })
+
+ it("returns fallback for undefined", () => {
+ expect(getWikiTypeStyle(undefined)).toBe(FALLBACK_TYPE_STYLE)
+ })
+
+ it("returns fallback for empty string", () => {
+ expect(getWikiTypeStyle("")).toBe(FALLBACK_TYPE_STYLE)
+ })
+
+ it("returns fallback for an unknown type", () => {
+ expect(getWikiTypeStyle("zorbax")).toBe(FALLBACK_TYPE_STYLE)
+ })
+
+ it("covers every documented page type", () => {
+ const expected = [
+ "entity", "concept", "query", "source",
+ "thesis", "finding", "event", "overview",
+ ]
+ for (const t of expected) {
+ const style = getWikiTypeStyle(t)
+ expect(style).not.toBe(FALLBACK_TYPE_STYLE)
+ expect(style.label.length).toBeGreaterThan(0)
+ expect(style.chipClass).toContain("bg-")
+ expect(style.dotClass).toContain("bg-")
+ }
+ })
+})
diff --git a/src/lib/wiki-type-style.ts b/src/lib/wiki-type-style.ts
new file mode 100644
index 00000000..f75e1665
--- /dev/null
+++ b/src/lib/wiki-type-style.ts
@@ -0,0 +1,93 @@
+import type { LucideIcon } from "lucide-react"
+import {
+ User,
+ Lightbulb,
+ HelpCircle,
+ FileText,
+ Target,
+ TrendingUp,
+ BookOpen,
+ Calendar,
+ Hash,
+} from "lucide-react"
+
+export interface WikiTypeStyle {
+ /** Display label for chips and tooltips. Capitalized. */
+ label: string
+ /** Lucide icon component for the type. */
+ icon: LucideIcon
+ /**
+ * Tailwind classes for a colored chip (background + text). Includes
+ * dark-mode variants so the chip stays readable on either theme.
+ */
+ chipClass: string
+ /**
+ * Tailwind class for the type's accent dot or border (without the
+ * 15% opacity used by chips). Useful for connector lines.
+ */
+ dotClass: string
+}
+
+export const WIKI_TYPE_STYLES: Record<string, WikiTypeStyle> = {
+ entity: {
+ label: "Entity",
+ icon: User,
+ chipClass: "bg-blue-500/15 text-blue-700 dark:text-blue-300",
+ dotClass: "bg-blue-500",
+ },
+ concept: {
+ label: "Concept",
+ icon: Lightbulb,
+ chipClass: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
+ dotClass: "bg-emerald-500",
+ },
+ query: {
+ label: "Query",
+ icon: HelpCircle,
+ chipClass: "bg-amber-500/15 text-amber-700 dark:text-amber-300",
+ dotClass: "bg-amber-500",
+ },
+ source: {
+ label: "Source",
+ icon: FileText,
+ chipClass: "bg-slate-500/15 text-slate-700 dark:text-slate-300",
+ dotClass: "bg-slate-500",
+ },
+ thesis: {
+ label: "Thesis",
+ icon: Target,
+ chipClass: "bg-rose-500/15 text-rose-700 dark:text-rose-300",
+ dotClass: "bg-rose-500",
+ },
+ finding: {
+ label: "Finding",
+ icon: TrendingUp,
+ chipClass: "bg-purple-500/15 text-purple-700 dark:text-purple-300",
+ dotClass: "bg-purple-500",
+ },
+ event: {
+ label: "Event",
+ icon: Calendar,
+ chipClass: "bg-cyan-500/15 text-cyan-700 dark:text-cyan-300",
+ dotClass: "bg-cyan-500",
+ },
+ overview: {
+ label: "Overview",
+ icon: BookOpen,
+ chipClass: "bg-indigo-500/15 text-indigo-700 dark:text-indigo-300",
+ dotClass: "bg-indigo-500",
+ },
+}
+
+export const FALLBACK_TYPE_STYLE: WikiTypeStyle = {
+ label: "Page",
+ icon: Hash,
+ chipClass: "bg-muted text-muted-foreground",
+ dotClass: "bg-muted-foreground/60",
+}
+
+export function getWikiTypeStyle(type: string | null | undefined): WikiTypeStyle {
+ if (!type) return FALLBACK_TYPE_STYLE
+ const key = type.trim().toLowerCase()
+ return WIKI_TYPE_STYLES[key] ?? FALLBACK_TYPE_STYLE
+}
diff --git a/src/lib/wikilink-transform.test.ts b/src/lib/wikilink-transform.test.ts
new file mode 100644
index 00000000..078a5ebd
--- /dev/null
+++ b/src/lib/wikilink-transform.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect } from "vitest"
+import { transformWikilinks } from "./wikilink-transform"
+
+describe("transformWikilinks", () => {
+ it("returns input unchanged when there are no wikilinks", () => {
+ expect(transformWikilinks("just plain text")).toBe("just plain text")
+ expect(transformWikilinks("# Heading\n\nparagraph")).toBe("# Heading\n\nparagraph")
+ })
+
+ it("converts a bare [[slug]] to a standard markdown link", () => {
+ expect(transformWikilinks("see [[foo]] for details")).toBe(
+ "see [foo](#foo) for details",
+ )
+ })
+
+ it("uses the alias as label and target as href for [[slug|alias]]", () => {
+ expect(transformWikilinks("see [[foo|the foo page]]")).toBe(
+ "see [the foo page](#foo)",
+ )
+ })
+
+ it("trims whitespace inside the wikilink", () => {
+ expect(transformWikilinks("[[ foo | the alias ]]")).toBe(
+ "[the alias](#foo)",
+ )
+ })
+
+ it("converts multiple wikilinks on the same line", () => {
+ expect(transformWikilinks("[[a]] and [[b|B]] and [[c]]")).toBe(
+ "[a](#a) and [B](#b) and [c](#c)",
+ )
+ })
+
+ it("encodes special characters in the href", () => {
+ expect(transformWikilinks("[[hello world]]")).toBe(
+ "[hello world](#hello%20world)",
+ )
+ })
+
+ it("does not touch wikilinks inside fenced code blocks", () => {
+ const input = "before [[a]]\n```md\ncode [[b]] block\n```\nafter [[c]]"
+ expect(transformWikilinks(input)).toBe(
+ "before [a](#a)\n```md\ncode [[b]] block\n```\nafter [c](#c)",
+ )
+ })
+
+ it("does not touch wikilinks inside inline code spans", () => {
+ expect(transformWikilinks("text `[[skip]]` and [[keep]]")).toBe(
+ "text `[[skip]]` and [keep](#keep)",
+ )
+ })
+
+ it("handles multiple inline-code spans correctly", () => {
+ expect(transformWikilinks("[[a]] `[[b]]` [[c]] `[[d]]` [[e]]")).toBe(
+ "[a](#a) `[[b]]` [c](#c) `[[d]]` [e](#e)",
+ )
+ })
+
+ it("preserves [[empty alias|]] by falling back to target as label", () => {
+ expect(transformWikilinks("[[foo|]]")).toBe("[foo](#foo)")
+ })
+
+ it("matches the real DPAO body wikilink density", () => {
+ const input =
+ "DPAOs differ from [[paos|Polyphosphate-Accumulating Organisms (PAOs)]] " +
+ "and store [[pha|polyhydroxyalkanoates (PHAs)]] from [[vfa|volatile fatty acids (VFAs)]]. " +
+ "[[accumulibacter]] is the most-characterized genus."
+ const out = transformWikilinks(input)
+ expect(out).toContain("[Polyphosphate-Accumulating Organisms (PAOs)](#paos)")
+ expect(out).toContain("[polyhydroxyalkanoates (PHAs)](#pha)")
+ expect(out).toContain("[volatile fatty acids (VFAs)](#vfa)")
+ expect(out).toContain("[accumulibacter](#accumulibacter)")
+ expect(out).not.toContain("[[")
+ })
+
+ it("does not mangle existing standard markdown links", () => {
+ const input = "see [foo](https://example.com) and [[bar]]"
+ expect(transformWikilinks(input)).toBe(
+ "see [foo](https://example.com) and [bar](#bar)",
+ )
+ })
+
+ it("leaves dangling brackets untouched", () => {
+ expect(transformWikilinks("[[broken")).toBe("[[broken")
+ expect(transformWikilinks("broken]]")).toBe("broken]]")
+ })
+})
diff --git a/src/lib/wikilink-transform.ts b/src/lib/wikilink-transform.ts
new file mode 100644
index 00000000..a220660f
--- /dev/null
+++ b/src/lib/wikilink-transform.ts
@@ -0,0 +1,55 @@
+/**
+ * Convert Obsidian-style `[[target]]` and `[[target|alias]]` wiki
+ * links inside a markdown body to standard markdown links so a
+ * commonmark renderer (Milkdown / ReactMarkdown) styles them as
+ * links instead of dumping the bracket syntax as raw text.
+ *
+ * Output format: `[label](#target)` — using a fragment href so
+ * Tauri's webview doesn't try to navigate externally on click.
+ * In-app navigation can be wired up later via a click intercept
+ * on `<a href="#…">` elements; for now the goal is just to stop
+ * the wikilinks from looking like "raw code".
+ *
+ * Skips content inside fenced code blocks (```…```) and inline
+ * code spans (`…`) so wikilinks shown as code examples in
+ * documentation don't get mangled.
+ */
+export function transformWikilinks(body: string): string {
+ if (!body.includes("[[")) return body
+
+ // Split on triple-backtick fences. The capturing group keeps
+ // the fence content in the output. Odd indices are inside a
+ // fence and must pass through untouched.
+ const parts = body.split(/(```[\s\S]*?```)/g)
+ return parts
+ .map((part, idx) => (idx % 2 === 1 ? part : transformOutsideCode(part)))
+ .join("")
+}
+
+const WIKILINK_RE = /\[\[([^\]|\n]+)(?:\|([^\]\n]*))?\]\]/g
+
+function transformOutsideCode(text: string): string {
+ if (!text.includes("[[")) return text
+
+ // Split on inline-code spans so backticked content is preserved.
+ const parts = text.split(/(`[^`\n]+`)/g)
+ return parts
+ .map((part, idx) => (idx % 2 === 1 ? part : replaceWikilinks(part)))
+ .join("")
+}
+
+function replaceWikilinks(text: string): string {
+ return text.replace(WIKILINK_RE, (_match, rawTarget: string, rawAlias?: string) => {
+ const target = rawTarget.trim()
+ const alias = rawAlias?.trim() ?? ""
+ const label = alias.length > 0 ? alias : target
+ // Encode the target so spaces / parens / hashes don't break the
+ // markdown link parser. encodeURIComponent is overkill for a
+ // fragment but it's the safe default.
+ const href = `#${encodeURIComponent(target)}`
+ // Escape any closing brackets in the label that would otherwise
+ // terminate the markdown link text.
+ const escapedLabel = label.replace(/\[/g, "\\[").replace(/\]/g, "\\]")
+ return `[${escapedLabel}](${href})`
+ })
+}