1
0
Fork 0

feat(wiki): redesign index with URL-shared filters, category portals, featured strip

Rewrite the wiki index: filters (query/tag/category/sort) sync to the URL for shareable/bookmarkable views; a moderator-curated 'Start here' featured strip; category grouping with per-category portal pages (/wiki/category/*) and CATEGORY_META blurbs; excerpt previews; case-insensitive, alphabetized tag counts; and a compact WikiRow. Updates the wiki controls tour copy.
This commit is contained in:
Jason Fraley 2026-10-09 17:56:09 -04:00
parent 2bc9e08b6f
commit 42d860da44
7 changed files with 676 additions and 180 deletions

View file

@ -0,0 +1,108 @@
import config from "@payload-config";
import { headers as nextHeaders } from "next/headers";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getPayload } from "payload";
import { ArrowLeftIcon, BookOpenIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { WikiRow } from "@/components/frontend/wiki/WikiRow";
import { CATEGORY_META, WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
import { collectTagCounts, mapWikiPageToEntry } from "@/lib/wiki/indexView";
export const metadata = {
title: "Wiki category: Polaris Task Force",
};
export default async function WikiCategoryPage({
params,
}: {
readonly params: Promise<{ category: string }>;
}) {
const { category: rawCategory } = await params;
if (!WIKI_CATEGORIES.includes(rawCategory as WikiCategory)) {
notFound();
}
const category = rawCategory as WikiCategory;
const headers = await nextHeaders();
const payload = await getPayload({ config });
const pagesResult = await payload.find({
collection: "wiki-pages",
where: { category: { equals: category } },
sort: "-updatedAt",
limit: 200,
depth: 1,
overrideAccess: true,
});
const pages = pagesResult.docs.map(mapWikiPageToEntry);
const tagCounts = collectTagCounts(pages);
// Tag chips deep-link into the URL-synced index with this category pre-applied.
const tagLinkBase = `/wiki?category=${encodeURIComponent(category)}`;
return (
<div className="flex flex-col gap-6 p-5">
<div className="flex flex-col gap-3">
<Link
href="/wiki"
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Wiki
</Link>
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<BookOpenIcon className="size-5 shrink-0 text-muted-foreground" />
<h1 className="text-lg font-semibold">{category}</h1>
<span className="text-sm tabular-nums text-muted-foreground">
{pages.length} page{pages.length === 1 ? "" : "s"}
</span>
</div>
<p className="max-w-prose text-sm text-muted-foreground">{CATEGORY_META[category]}</p>
</div>
</div>
{tagCounts.length > 0 && (
<section className="flex flex-col gap-1.5">
<h2 className="px-1 text-xs font-semibold tracking-wider text-muted-foreground uppercase">
Tags in this category
</h2>
<div className="flex flex-wrap gap-1.5">
{tagCounts.map(({ tag, count }) => (
<Link
key={tag}
href={`${tagLinkBase}&tag=${encodeURIComponent(tag)}`}
className="inline-flex items-center gap-1.5 rounded-sm border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
{tag}
<span className="tabular-nums opacity-60">{count}</span>
</Link>
))}
</div>
</section>
)}
{pages.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-start gap-3 p-6">
<div className="flex flex-col gap-1">
<p className="font-semibold">Nothing filed under {category} yet.</p>
<p className="text-sm text-muted-foreground">
Be the first to write this part of the field guide.
</p>
</div>
<Button asChild size="sm">
<Link href="/wiki/new">New page</Link>
</Button>
</CardContent>
</Card>
) : (
<div className="divide-y overflow-hidden rounded-lg border">
{pages.map((page) => (
<WikiRow key={page.id} page={page} tagLinkBase={tagLinkBase} />
))}
</div>
)}
</div>
);
}

View file

@ -1,25 +1,16 @@
import { Suspense } from "react";
import config from "@payload-config";
import { headers as nextHeaders } from "next/headers";
import { getPayload } from "payload";
import { BookOpenIcon } from "lucide-react";
import type { WikiPage as WikiPageDocument } from "@/payload-types";
import { WikiIndex, type WikiIndexPage } from "@/components/frontend/wiki/WikiIndex";
import { WikiIndex } from "@/components/frontend/wiki/WikiIndex";
import { mapWikiPageToEntry } from "@/lib/wiki/indexView";
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
export const metadata = {
title: "Wiki: Polaris Task Force",
};
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";
}
export default async function WikiPage() {
const headers = await nextHeaders();
const payload = await getPayload({ config });
@ -39,21 +30,7 @@ export default async function WikiPage() {
hasIntelligenceQualification(payload, user),
]);
const pages: WikiIndexPage[] = pagesResult.docs.map((page) => ({
id: page.id,
title: page.title,
slug: page.slug,
category: page.category,
tags: page.tags ?? [],
updatedAt: page.updatedAt,
// Seeded Documentation pages are written by the system, not a user.
lastEditorName:
page.lastEditor != null
? relationName(page.lastEditor)
: page.category === "Documentation"
? "System"
: "Unknown editor",
}));
const pages = pagesResult.docs.map(mapWikiPageToEntry);
return (
<div className="flex flex-col gap-6 p-5">
@ -67,7 +44,9 @@ export default async function WikiPage() {
</p>
</div>
<WikiIndex pages={pages} isModerator={isModerator} />
<Suspense>
<WikiIndex pages={pages} isModerator={isModerator} />
</Suspense>
</div>
);
}

View file

@ -1,107 +1,219 @@
"use client";
import { useMemo, useState } from "react";
import Link from "next/link";
import { ArrowUpRightIcon, PlusIcon, SearchIcon, TagIcon } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { ArrowRightIcon, PlusIcon, SearchIcon, SparklesIcon, XIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Card, CardContent } from "@/components/ui/card";
import { Combobox } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
export interface WikiIndexPage {
readonly id: number;
readonly title: string;
readonly slug: string;
readonly category: WikiCategory;
readonly tags: readonly string[];
readonly updatedAt: string;
readonly lastEditorName: string;
}
type CategoryFilter = "all" | WikiCategory;
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { WIKI_CATEGORIES } from "@/lib/wiki/categories";
import { WikiRow } from "./WikiRow";
import {
collectTagCounts,
filterWikiPages,
groupWikiPagesByCategory,
isCategoryFilter,
isSortKey,
selectFeatured,
sortWikiPages,
type WikiCategoryFilter,
type WikiIndexEntry,
type WikiSortKey,
} from "@/lib/wiki/indexView";
interface WikiIndexProps {
readonly pages: readonly WikiIndexPage[];
readonly pages: readonly WikiIndexEntry[];
readonly isModerator: boolean;
}
function isCategoryFilter(value: string): value is CategoryFilter {
return value === "all" || WIKI_CATEGORIES.some((category) => category === value);
}
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`;
}
const SORT_LABELS: Record<WikiSortKey, string> = {
recent: "Recently edited",
oldest: "Oldest edit first",
title: "Title A-Z",
};
export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
const [search, setSearch] = useState("");
const [tagFilter, setTagFilter] = useState("");
const [category, setCategory] = useState<CategoryFilter>("all");
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const filteredPages = useMemo(() => {
const query = search.trim().toLowerCase();
const tagQuery = tagFilter.trim().toLowerCase();
const [search, setSearch] = useState(() => searchParams.get("q") ?? "");
const [tagFilter, setTagFilter] = useState(() => searchParams.get("tag") ?? "");
const [category, setCategory] = useState<WikiCategoryFilter>(() => {
const value = searchParams.get("category");
return value !== null && isCategoryFilter(value) ? value : "all";
});
const [sort, setSort] = useState<WikiSortKey>(() => {
const value = searchParams.get("sort");
return value !== null && isSortKey(value) ? value : "recent";
});
return [...pages]
.sort(
(left, right) => new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime(),
)
.filter((page) => {
if (category !== "all" && page.category !== category) return false;
if (query && !`${page.title} ${page.slug}`.toLowerCase().includes(query)) return false;
if (tagQuery && !page.tags.some((tag) => tag.toLowerCase().includes(tagQuery)))
return false;
return true;
});
}, [category, pages, search, tagFilter]);
// The URL carries the view so filtered lists can be shared or bookmarked.
// Local state drives rendering; the replace is debounced to keep typing
// snappy and skipped when nothing actually changed. Crucially the effect
// keys ONLY off local filter state: useSearchParams identity churns while a
// client navigation is in flight, and re-running (or replacing) then aborts
// that navigation (e.g. clicking a category header). Latest params are read
// through a ref purely for the no-op comparison.
const searchParamsRef = useRef(searchParams);
searchParamsRef.current = searchParams;
const pathnameRef = useRef(pathname);
pathnameRef.current = pathname;
useEffect(() => {
const timer = setTimeout(() => {
const params = new URLSearchParams();
if (search.trim() !== "") params.set("q", search.trim());
if (tagFilter.trim() !== "") params.set("tag", tagFilter.trim());
if (category !== "all") params.set("category", category);
if (sort !== "recent") params.set("sort", sort);
const query = params.toString();
if (query === searchParamsRef.current.toString()) return;
const currentPath = pathnameRef.current;
router.replace(query ? `${currentPath}?${query}` : currentPath, { scroll: false });
}, 300);
return () => clearTimeout(timer);
}, [category, router, search, sort, tagFilter]);
const visiblePages = useMemo(
() =>
sortWikiPages(filterWikiPages(pages, { query: search, tag: tagFilter, category }), sort),
[category, pages, search, sort, tagFilter],
);
const groups = useMemo(() => groupWikiPagesByCategory(visiblePages), [visiblePages]);
const tagCounts = useMemo(() => collectTagCounts(pages), [pages]);
const featuredPages = useMemo(() => selectFeatured(pages), [pages]);
const filtersActive = search.trim() !== "" || tagFilter.trim() !== "" || category !== "all";
const clearFilters = () => {
setSearch("");
setTagFilter("");
setCategory("all");
};
const toggleTag = (tag: string) => {
setTagFilter((current) =>
current.toLowerCase() === tag.toLowerCase() ? "" : tag,
);
};
return (
<div className="flex flex-col gap-5" data-tour="wiki-controls">
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="flex flex-wrap items-end gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="wiki-search">Search</Label>
<div className="relative">
<SearchIcon className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="wiki-search"
aria-label="Search wiki pages"
className="w-full pl-8 sm:w-64"
placeholder="Search title or slug..."
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="wiki-tag-filter">Tag</Label>
<div className="relative">
<TagIcon className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="wiki-tag-filter"
aria-label="Filter wiki tags"
className="w-full pl-8 sm:w-48"
placeholder="Filter tags..."
value={tagFilter}
onChange={(event) => setTagFilter(event.target.value)}
/>
</div>
<div className="flex flex-col gap-4">
{!filtersActive && featuredPages.length > 0 && (
<section className="flex flex-col gap-1.5" aria-label="Start here">
<h2 className="flex items-baseline gap-2 px-1 text-xs font-semibold tracking-wider text-muted-foreground uppercase">
<SparklesIcon className="size-3 self-center" aria-hidden />
Start here
</h2>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{featuredPages.map((page) => (
<Link
key={page.id}
href={`/wiki/${page.slug}`}
className="group flex flex-col gap-1 rounded-lg border p-3 transition-colors hover:bg-accent/40"
>
<span className="min-w-0 truncate text-sm font-medium group-hover:underline">
{page.title}
</span>
{page.excerpt && (
<span className="line-clamp-2 text-xs text-muted-foreground">
{page.excerpt}
</span>
)}
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">
{page.category}
</span>
</Link>
))}
</div>
</section>
)}
<div className="flex flex-wrap items-center gap-2" data-tour="wiki-controls">
<div className="relative min-w-56 flex-1 lg:max-w-md">
<SearchIcon className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
aria-label="Search wiki pages"
className="pl-8"
placeholder="Search title, tags, or content..."
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
</div>
<Button asChild>
<Select
value={category}
onValueChange={(value) => {
if (isCategoryFilter(value)) setCategory(value);
}}
>
<SelectTrigger aria-label="Filter wiki pages by category" className="w-40 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All categories</SelectItem>
{WIKI_CATEGORIES.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
<Combobox
aria-label="Filter wiki pages by tag"
className="w-44 shrink-0"
value={tagFilter}
onValueChange={setTagFilter}
placeholder="All tags"
searchPlaceholder="Search tags..."
emptyMessage="No tags yet."
options={[
{ value: "", label: "All tags" },
...tagCounts.map(({ tag, count }) => ({
value: tag,
label: tag,
hint: `${count} page${count === 1 ? "" : "s"}`,
})),
]}
/>
<Select
value={sort}
onValueChange={(value) => {
if (isSortKey(value)) setSort(value);
}}
>
<SelectTrigger aria-label="Sort wiki pages" className="w-40 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(SORT_LABELS) as WikiSortKey[]).map((key) => (
<SelectItem key={key} value={key}>
{SORT_LABELS[key]}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-xs tabular-nums text-muted-foreground">
{filtersActive ? `${visiblePages.length} of ${pages.length}` : `${pages.length}`} pages
</span>
{isModerator && <Badge variant="outline">Intel editor</Badge>}
<Button asChild className="ml-auto" size="sm">
<Link href="/wiki/new">
<PlusIcon data-icon="inline-start" />
New page
@ -109,76 +221,55 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
</Button>
</div>
<Tabs
value={category}
onValueChange={(value) => {
if (isCategoryFilter(value)) setCategory(value);
}}
>
<TabsList className="max-w-full justify-start gap-1 overflow-x-auto">
<TabsTrigger value="all">All</TabsTrigger>
{WIKI_CATEGORIES.map((option) => (
<TabsTrigger key={option} value={option}>
{option}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="flex items-center gap-2">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Field guide
</h2>
<span className="text-xs text-muted-foreground">
{filteredPages.length} page{filteredPages.length === 1 ? "" : "s"}
</span>
{isModerator && <Badge variant="outline">Intel editor</Badge>}
</div>
{filteredPages.length === 0 ? (
{visiblePages.length === 0 ? (
<Card>
<CardContent className="flex flex-col gap-1 p-6">
<p className="font-semibold">No pages match those filters.</p>
<p className="text-sm text-muted-foreground">
Try a different title, tag, or category, or start a new field guide entry.
</p>
<CardContent className="flex flex-col items-start gap-3 p-6">
<div className="flex flex-col gap-1">
<p className="font-semibold">No pages match those filters.</p>
<p className="text-sm text-muted-foreground">
Try a different search term, tag, or category, or start a new field guide entry.
</p>
</div>
<div className="flex gap-2">
{filtersActive && (
<Button onClick={clearFilters} size="sm" variant="outline">
<XIcon data-icon="inline-start" />
Clear filters
</Button>
)}
<Button asChild size="sm">
<Link href="/wiki/new">New page</Link>
</Button>
</div>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
{filteredPages.map((page) => (
<Card key={page.id} className="transition-colors hover:bg-accent/50">
<CardHeader className="gap-3">
<div className="flex items-start justify-between gap-3">
<CardTitle className="min-w-0 text-base">
<Link
href={`/wiki/${page.slug}`}
className="inline-flex items-center gap-1 hover:underline"
>
<span className="truncate">{page.title}</span>
<ArrowUpRightIcon className="size-4 shrink-0 text-muted-foreground" />
</Link>
</CardTitle>
<Badge variant="outline" className="shrink-0">
{page.category}
</Badge>
</div>
<div className="flex flex-wrap items-center gap-1.5">
{page.tags.map((tag) => (
<Badge key={tag} variant="secondary" className="font-normal">
{tag}
</Badge>
))}
{page.tags.length === 0 && (
<span className="text-xs italic text-muted-foreground">No tags</span>
)}
</div>
</CardHeader>
<CardContent className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
<span>Edited by {page.lastEditorName}</span>
<time dateTime={page.updatedAt}>{timeAgo(page.updatedAt)}</time>
</CardContent>
</Card>
<div className="flex flex-col gap-5">
{groups.map((group) => (
<section key={group.category} className="flex flex-col gap-1">
{category === "all" && (
<h2 className="group/cat flex items-baseline gap-2 px-1 text-xs font-semibold tracking-wider text-muted-foreground uppercase">
<Link
href={`/wiki/category/${group.category}`}
className="inline-flex items-center gap-1 transition-colors hover:text-foreground"
>
{group.category}
<ArrowRightIcon
className="size-3 opacity-0 transition-opacity group-hover/cat:opacity-70"
aria-hidden
/>
</Link>
<span className="font-normal tabular-nums normal-case">
{group.pages.length}
</span>
</h2>
)}
<div className="divide-y overflow-hidden rounded-lg border">
{group.pages.map((page) => (
<WikiRow key={page.id} page={page} activeTag={tagFilter} onTagClick={toggleTag} />
))}
</div>
</section>
))}
</div>
)}

View file

@ -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 (
<article className="relative flex flex-col gap-1 px-4 py-2.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
<div className="min-w-0">
<Link
href={`/wiki/${page.slug}`}
className="text-sm font-medium after:absolute after:inset-0 after:content-['']"
>
{page.title}
</Link>
{page.excerpt && (
<p className="line-clamp-1 text-xs text-muted-foreground">{page.excerpt}</p>
)}
</div>
<div className="flex shrink-0 flex-wrap items-center gap-x-2 gap-y-1">
{visibleTags.map((tag) =>
tagLinkBase ? (
<Link
key={tag}
href={`${tagLinkBase}&tag=${encodeURIComponent(tag)}`}
className="relative z-10 rounded-sm border px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
{tag}
</Link>
) : (
<button
key={tag}
type="button"
onClick={() => onTagClick?.(tag)}
aria-label={`Filter by tag ${tag}`}
className={cn(
"relative z-10 rounded-sm border px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
activeTag !== "" &&
activeTag.toLowerCase() === tag.toLowerCase() &&
"border-primary/40 bg-primary/10 text-primary",
)}
>
{tag}
</button>
),
)}
{hiddenCount > 0 && (
<span className="text-[11px] text-muted-foreground" title={page.tags.slice(3).join(", ")}>
+{hiddenCount}
</span>
)}
<span className="text-xs whitespace-nowrap text-muted-foreground">
{page.lastEditorName} · {timeAgo(page.updatedAt)}
</span>
</div>
</article>
);
}

View file

@ -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.",
},
],
},

View file

@ -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<WikiCategory, string> = {
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.",
};

209
src/lib/wiki/indexView.ts Normal file
View file

@ -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<string, { tag: string; count: number }>();
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,
};
}