-
- {filteredPages.length === 0 ? (
+ {visiblePages.length === 0 ? (
- {filteredPages.map((page) => (
-
-
-
-
-
- {page.title}
-
-
-
-
- {page.category}
-
-
-
- {page.tags.map((tag) => (
-
- {tag}
-
- ))}
- {page.tags.length === 0 && (
- No tags
- )}
-
-
-
- Edited by {page.lastEditorName}
-
-
-
+
+ {groups.map((group) => (
+
+ {category === "all" && (
+
+
+ {group.category}
+
+
+
+ {group.pages.length}
+
+
+ )}
+
+ {group.pages.map((page) => (
+
+ ))}
+
+
))}
)}
diff --git a/src/components/frontend/wiki/WikiRow.tsx b/src/components/frontend/wiki/WikiRow.tsx
new file mode 100644
index 00000000..6ffb956c
--- /dev/null
+++ b/src/components/frontend/wiki/WikiRow.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import Link from "next/link";
+import { cn } from "@/lib/utils";
+import type { WikiIndexEntry } from "@/lib/wiki/indexView";
+
+export function timeAgo(iso: string): string {
+ const diff = Math.max(0, Date.now() - new Date(iso).getTime());
+ const minutes = Math.floor(diff / 60000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ const months = Math.floor(days / 30);
+ if (months < 12) return `${months}mo ago`;
+ return `${Math.floor(months / 12)}y ago`;
+}
+
+interface WikiRowProps {
+ readonly page: WikiIndexEntry;
+ /**
+ * When set, tags render as links to `${tagLinkBase}&tag=...` (category
+ * portals deep-linking into the filtered index). Otherwise they render as
+ * toggle buttons via onTagClick (the index itself).
+ */
+ readonly tagLinkBase?: string;
+ readonly activeTag?: string;
+ readonly onTagClick?: (tag: string) => void;
+}
+
+/**
+ * One compact list row. The title link stretches over the whole row via an
+ * ::after overlay; tag controls sit above that overlay so they stay clickable.
+ */
+export function WikiRow({ page, tagLinkBase, activeTag = "", onTagClick }: WikiRowProps) {
+ const visibleTags = page.tags.slice(0, 3);
+ const hiddenCount = page.tags.length - visibleTags.length;
+
+ return (
+
+
+
+ {page.title}
+
+ {page.excerpt && (
+
{page.excerpt}
+ )}
+
+
+ {visibleTags.map((tag) =>
+ tagLinkBase ? (
+
+ {tag}
+
+ ) : (
+
+ ),
+ )}
+ {hiddenCount > 0 && (
+
+ +{hiddenCount}
+
+ )}
+
+ {page.lastEditorName} ยท {timeAgo(page.updatedAt)}
+
+
+
+ );
+}
diff --git a/src/lib/tours/registry.ts b/src/lib/tours/registry.ts
index 9ef08956..b25961f5 100644
--- a/src/lib/tours/registry.ts
+++ b/src/lib/tours/registry.ts
@@ -193,7 +193,7 @@ export const TOURS: TourDefinition[] = [
id: "controls",
selector: '[data-tour="wiki-controls"]',
title: "The unit wiki",
- body: "A shared field guide for campaigns, lore, and how the unit's systems work. Search, filter by tag, or browse by category tab.",
+ body: "A shared field guide for campaigns, lore, and how the unit's systems work. Search across titles, tags, and content, narrow with the pickers, or open a category header to browse one shelf at a time.",
},
],
},
diff --git a/src/lib/wiki/categories.ts b/src/lib/wiki/categories.ts
index a3712ea8..f7c8c2f0 100644
--- a/src/lib/wiki/categories.ts
+++ b/src/lib/wiki/categories.ts
@@ -11,3 +11,20 @@ export const WIKI_CATEGORIES = [
] as const;
export type WikiCategory = (typeof WIKI_CATEGORIES)[number];
+
+/**
+ * One-line descriptions for the category portal pages (/wiki/category/*).
+ * Typed as a full Record so a new category cannot ship without a blurb.
+ */
+export const CATEGORY_META: Record
= {
+ Campaign:
+ "Written-up operations: what happened, who was there, and how the story moved afterward.",
+ World: "Places, terrain, and the setting details the campaign takes place on.",
+ Lore: "Unit history, factions, and the fiction that grows around each operation.",
+ Characters: "People of note: NPCs we have met, leadership, and recurring personalities.",
+ Plot: "Story threads, open questions, and narrative devices in play.",
+ Media: "Screenshots, recordings, and other captures worth keeping.",
+ Guides: "How-to write-ups from members: tactics, kit, and conventions that stuck.",
+ Meta: "About the wiki itself: standards, examples, and how to contribute.",
+ Documentation: "Guides to this website's systems: logistics, banking, market, map, and more.",
+};
diff --git a/src/lib/wiki/indexView.ts b/src/lib/wiki/indexView.ts
new file mode 100644
index 00000000..4b275864
--- /dev/null
+++ b/src/lib/wiki/indexView.ts
@@ -0,0 +1,209 @@
+import type { WikiPage as WikiPageDocument } from "@/payload-types";
+import { WIKI_CATEGORIES, type WikiCategory } from "./categories";
+
+/**
+ * Pure view-model helpers for the wiki index page: excerpting, filtering,
+ * sorting, grouping, tag counts, and featured selection. No runtime Payload
+ * imports, client-safe.
+ */
+
+/** One wiki page as the index renders it (the server route maps documents into this shape). */
+export interface WikiIndexEntry {
+ readonly id: number;
+ readonly title: string;
+ readonly slug: string;
+ readonly category: WikiCategory;
+ readonly tags: readonly string[];
+ readonly updatedAt: string;
+ readonly lastEditorName: string;
+ readonly excerpt: string;
+ readonly featured: boolean;
+ readonly featuredOrder: number | null;
+}
+
+export type WikiCategoryFilter = "all" | WikiCategory;
+
+export type WikiSortKey = "recent" | "oldest" | "title";
+
+export interface WikiIndexFilters {
+ readonly query: string;
+ readonly tag: string;
+ readonly category: WikiCategoryFilter;
+}
+
+export function isCategoryFilter(value: string): value is WikiCategoryFilter {
+ return value === "all" || WIKI_CATEGORIES.some((category) => category === value);
+}
+
+export function isSortKey(value: string): value is WikiSortKey {
+ return value === "recent" || value === "oldest" || value === "title";
+}
+
+/**
+ * Plain-text teaser for a markdown body: fenced code dropped, inline syntax
+ * stripped to its readable text, whitespace collapsed, truncated on a word
+ * boundary. Emphasis runs (`*`, `_`, `~`) are removed wholesale, which can
+ * flatten snake_case words in prose; acceptable for a one-line preview.
+ */
+export function buildExcerpt(markdown: string, maxLen = 140): string {
+ const text = markdown
+ .replace(/```[\s\S]*?```/g, " ") // fenced code blocks are noise in a teaser
+ .replace(/~~~[\s\S]*?~~~/g, " ")
+ .replace(/^[ \t]*(?:---+|\*\*\*+|___+)[ \t]*$/gm, " ") // horizontal rules
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1") // images keep their alt text
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") // links keep their label
+ .replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2") // [[target|label]] wikilinks
+ .replace(/\[\[([^\]]+)\]\]/g, "$1")
+ .replace(/\{\{([^}]*)\}\}/g, "$1") // {{templates}} collapse to their name
+ .replace(/`([^`]*)`/g, "$1") // inline code
+ .replace(/<[^>\n]+>/g, " ") // raw html tags
+ .replace(/^[ \t]*(?:#{1,6}|>|[-*+]|\d+\.)[ \t]+/gm, "") // heading/quote/list markers
+ .replace(/[*_~]+/g, "") // emphasis runs
+ .replace(/\|/g, " ") // table pipes
+ .replace(/\s+/g, " ")
+ .trim();
+
+ if (text.length <= maxLen) return text;
+ const window = text.slice(0, maxLen + 1);
+ const boundary = window.lastIndexOf(" ");
+ const head = boundary > 0 ? window.slice(0, boundary) : window.trimEnd();
+ return `${head.trimEnd()}...`;
+}
+
+/** Case-insensitive match over title, slug, tags, and excerpt text. */
+export function filterWikiPages(
+ pages: readonly WikiIndexEntry[],
+ filters: WikiIndexFilters,
+): WikiIndexEntry[] {
+ const query = filters.query.trim().toLowerCase();
+ const tag = filters.tag.trim().toLowerCase();
+
+ return pages.filter((page) => {
+ if (filters.category !== "all" && page.category !== filters.category) return false;
+ if (tag && !page.tags.some((entry) => entry.toLowerCase().includes(tag))) return false;
+ if (query) {
+ const haystack =
+ `${page.title} ${page.slug} ${page.tags.join(" ")} ${page.excerpt}`.toLowerCase();
+ if (!haystack.includes(query)) return false;
+ }
+ return true;
+ });
+}
+
+/** Newest-edited first by default; ids break ties so ordering stays deterministic. */
+export function sortWikiPages(
+ pages: readonly WikiIndexEntry[],
+ sort: WikiSortKey,
+): WikiIndexEntry[] {
+ const sorted = [...pages];
+ if (sort === "title") {
+ sorted.sort((left, right) => left.title.localeCompare(right.title) || left.id - right.id);
+ } else if (sort === "oldest") {
+ sorted.sort(
+ (left, right) =>
+ new Date(left.updatedAt).getTime() - new Date(right.updatedAt).getTime() ||
+ left.id - right.id,
+ );
+ } else {
+ sorted.sort(
+ (left, right) =>
+ new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime() ||
+ right.id - left.id,
+ );
+ }
+ return sorted;
+}
+
+export interface WikiCategoryGroup {
+ readonly category: WikiCategory;
+ readonly pages: readonly WikiIndexEntry[];
+}
+
+/** Groups in WIKI_CATEGORIES order, preserving the incoming (sorted) order within each group. */
+export function groupWikiPagesByCategory(
+ pages: readonly WikiIndexEntry[],
+): WikiCategoryGroup[] {
+ return WIKI_CATEGORIES.map((category) => ({
+ category,
+ pages: pages.filter((page) => page.category === category),
+ })).filter((group) => group.pages.length > 0);
+}
+
+export interface WikiTagCount {
+ readonly tag: string;
+ readonly count: number;
+}
+
+/**
+ * Every tag with a page count, deduplicated case-insensitively (first casing
+ * wins) and sorted alphabetically. Drives the tag dropdown so filtering is
+ * never blind.
+ */
+export function collectTagCounts(pages: readonly WikiIndexEntry[]): WikiTagCount[] {
+ const counts = new Map();
+ for (const page of pages) {
+ for (const rawTag of page.tags) {
+ const tag = rawTag.trim();
+ const key = tag.toLowerCase();
+ if (!key) continue;
+ const existing = counts.get(key);
+ if (existing) existing.count += 1;
+ else counts.set(key, { tag, count: 1 });
+ }
+ }
+ return [...counts.values()].sort((left, right) =>
+ left.tag.localeCompare(right.tag, undefined, { sensitivity: "base" }),
+ );
+}
+
+/** How many featured pages the index strip shows at most. */
+export const FEATURED_CAP = 6;
+
+/** Moderator-picked pages for the "Start here" strip: explicit order first, then newest. */
+export function selectFeatured(
+ pages: readonly WikiIndexEntry[],
+ cap: number = FEATURED_CAP,
+): WikiIndexEntry[] {
+ return pages
+ .filter((page) => page.featured)
+ .sort(
+ (left, right) =>
+ (left.featuredOrder ?? Number.MAX_SAFE_INTEGER) -
+ (right.featuredOrder ?? Number.MAX_SAFE_INTEGER) ||
+ new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime() ||
+ left.id - right.id,
+ )
+ .slice(0, cap);
+}
+
+function relationName(relation: WikiPageDocument["lastEditor"]): string {
+ if (typeof relation === "object" && relation !== null) {
+ return (
+ relation.payloadDisplayName || relation.displayName || relation.username || "Unknown editor"
+ );
+ }
+
+ return typeof relation === "number" ? `User #${relation}` : "Unknown editor";
+}
+
+/** Maps a wiki-pages document into the index view model (shared by /wiki and category portals). */
+export function mapWikiPageToEntry(page: WikiPageDocument): WikiIndexEntry {
+ return {
+ id: page.id,
+ title: page.title,
+ slug: page.slug,
+ category: page.category,
+ tags: page.tags ?? [],
+ updatedAt: page.updatedAt,
+ excerpt: buildExcerpt(page.body),
+ // Seeded Documentation pages are written by the system, not a user.
+ lastEditorName:
+ page.lastEditor != null
+ ? relationName(page.lastEditor)
+ : page.category === "Documentation"
+ ? "System"
+ : "Unknown editor",
+ featured: page.curation?.featured === true,
+ featuredOrder: page.curation?.featuredOrder ?? null,
+ };
+}