From 42d860da446fb067e8f236d6f4d70d2228c36e37 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Fri, 9 Oct 2026 17:56:09 -0400 Subject: [PATCH] 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. --- .../wiki/category/[category]/page.tsx | 108 +++++ src/app/(frontend)/wiki/page.tsx | 35 +- src/components/frontend/wiki/WikiIndex.tsx | 393 +++++++++++------- src/components/frontend/wiki/WikiRow.tsx | 92 ++++ src/lib/tours/registry.ts | 2 +- src/lib/wiki/categories.ts | 17 + src/lib/wiki/indexView.ts | 209 ++++++++++ 7 files changed, 676 insertions(+), 180 deletions(-) create mode 100644 src/app/(frontend)/wiki/category/[category]/page.tsx create mode 100644 src/components/frontend/wiki/WikiRow.tsx create mode 100644 src/lib/wiki/indexView.ts diff --git a/src/app/(frontend)/wiki/category/[category]/page.tsx b/src/app/(frontend)/wiki/category/[category]/page.tsx new file mode 100644 index 00000000..34e4860e --- /dev/null +++ b/src/app/(frontend)/wiki/category/[category]/page.tsx @@ -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 ( +
+
+ + + Wiki + +
+
+ +

{category}

+ + {pages.length} page{pages.length === 1 ? "" : "s"} + +
+

{CATEGORY_META[category]}

+
+
+ + {tagCounts.length > 0 && ( +
+

+ Tags in this category +

+
+ {tagCounts.map(({ tag, count }) => ( + + {tag} + {count} + + ))} +
+
+ )} + + {pages.length === 0 ? ( + + +
+

Nothing filed under {category} yet.

+

+ Be the first to write this part of the field guide. +

+
+ +
+
+ ) : ( +
+ {pages.map((page) => ( + + ))} +
+ )} +
+ ); +} diff --git a/src/app/(frontend)/wiki/page.tsx b/src/app/(frontend)/wiki/page.tsx index f4650df9..e1369675 100644 --- a/src/app/(frontend)/wiki/page.tsx +++ b/src/app/(frontend)/wiki/page.tsx @@ -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 (
@@ -67,7 +44,9 @@ export default async function WikiPage() {

- + + + ); } diff --git a/src/components/frontend/wiki/WikiIndex.tsx b/src/components/frontend/wiki/WikiIndex.tsx index 6dd047c7..ed03f035 100644 --- a/src/components/frontend/wiki/WikiIndex.tsx +++ b/src/components/frontend/wiki/WikiIndex.tsx @@ -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 = { + 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("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(() => { + const value = searchParams.get("category"); + return value !== null && isCategoryFilter(value) ? value : "all"; + }); + const [sort, setSort] = useState(() => { + 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 ( -
-
-
-
- -
- - setSearch(event.target.value)} - /> -
-
-
- -
- - setTagFilter(event.target.value)} - /> -
+
+ {!filtersActive && featuredPages.length > 0 && ( +
+

+ + Start here +

+
+ {featuredPages.map((page) => ( + + + {page.title} + + {page.excerpt && ( + + {page.excerpt} + + )} + + {page.category} + + + ))}
+
+ )} + +
+
+ + setSearch(event.target.value)} + />
-
- { - if (isCategoryFilter(value)) setCategory(value); - }} - > - - All - {WIKI_CATEGORIES.map((option) => ( - - {option} - - ))} - - - -
-

- Field guide -

- - {filteredPages.length} page{filteredPages.length === 1 ? "" : "s"} - - {isModerator && Intel editor} -
- - {filteredPages.length === 0 ? ( + {visiblePages.length === 0 ? ( - -

No pages match those filters.

-

- Try a different title, tag, or category, or start a new field guide entry. -

+ +
+

No pages match those filters.

+

+ Try a different search term, tag, or category, or start a new field guide entry. +

+
+
+ {filtersActive && ( + + )} + +
) : ( -
- {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, + }; +}