feat: add policy pages

This commit is contained in:
gosangam
2026-06-02 01:57:08 +05:30
parent 0352cb2003
commit 91d5d272d2
168 changed files with 1326 additions and 81 deletions
+145
View File
@@ -0,0 +1,145 @@
export const dynamic = "force-dynamic";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getLetter, getAdjacentLetters } from "@/lib/letters";
import { ogForLetter, extractQuoteFromHl, buildOgMeta } from "@/lib/og";
import { PageHeader } from "@/components/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { buttonVariants } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
export async function generateMetadata({
params,
searchParams,
}: {
params: Promise<{ slug: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}): Promise<Metadata> {
const { slug } = await params;
const sp = await searchParams;
const letter = await getLetter(slug);
if (!letter) return {};
const meta = [letter.date, letter.location].filter(Boolean).join(" · ");
const hlQuote = extractQuoteFromHl(sp, letter.paragraphs);
if (hlQuote) {
return buildOgMeta({
title: `Letter to ${letter.recipientDisplay}`,
detail: meta || undefined,
quote: hlQuote,
});
}
return ogForLetter(letter.recipientDisplay, meta || undefined);
}
export default async function LetterPage({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const letter = await getLetter(slug);
if (!letter) notFound();
const { prev, next } = await getAdjacentLetters(slug, letter.year);
const backHref = letter.year ? `/letters/year/${letter.year}` : "/letters";
const backLabel = letter.year ? `Letters from ${letter.year}` : "Letters";
return (
<div className="min-h-screen bg-background">
<PageHeader sticky>
<Link
href={backHref}
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
&larr; {backLabel}
</Link>
<h1 className="mt-3 text-2xl font-bold text-foreground">
Letter to {letter.recipientDisplay}
</h1>
<p className="mt-1 text-sm text-muted-foreground">
{letter.date}
{letter.location ? ` · ${letter.location}` : ""}
</p>
</PageHeader>
<main className="max-w-5xl mx-auto px-6 py-8 space-y-8">
{/* Top nav */}
<LetterNav prev={prev} next={next} />
{/* Letter content */}
<Card>
<CardContent className="py-8 px-6 sm:px-8">
<div className="space-y-4">
{letter.paragraphs.map((paragraph, i) => (
<div
key={i}
className="text-base text-foreground leading-relaxed"
dangerouslySetInnerHTML={{ __html: paragraph }}
/>
))}
</div>
</CardContent>
</Card>
{/* Bottom nav */}
<LetterNav prev={prev} next={next} />
</main>
</div>
);
}
function LetterNav({
prev,
next,
}: {
prev: { slug: string; recipientDisplay: string } | null;
next: { slug: string; recipientDisplay: string } | null;
}) {
return (
<div className="flex items-center justify-between gap-3">
{prev ? (
<Link
href={`/letters/${prev.slug}`}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<ChevronLeft className="size-4" />
<span className="hidden sm:inline truncate max-w-[180px]">
{prev.recipientDisplay}
</span>
<span className="sm:hidden">Previous</span>
</Link>
) : (
<div />
)}
{next ? (
<Link
href={`/letters/${next.slug}`}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<span className="hidden sm:inline truncate max-w-[180px]">
{next.recipientDisplay}
</span>
<span className="sm:hidden">Next</span>
<ChevronRight className="size-4" />
</Link>
) : (
<div />
)}
</div>
);
}
+527
View File
@@ -0,0 +1,527 @@
"use client";
import { useState, useMemo, useRef } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ChevronLeft, ChevronRight, Menu } from "lucide-react";
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type LetterItem = {
slug: string;
recipientDisplay: string;
date: string | null;
year: number | null;
month: number | null;
location: string | null;
};
type YearGroup = {
year: number;
label: string;
count: number;
letters: LetterItem[];
};
type MonthGroup = {
month: number;
label: string;
letters: LetterItem[];
};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MONTH_NAMES = [
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
// ---------------------------------------------------------------------------
// Grouping helpers
// ---------------------------------------------------------------------------
function buildYearGroups(letters: LetterItem[]): YearGroup[] {
const map = new Map<number, LetterItem[]>();
for (const letter of letters) {
const y = letter.year ?? 0;
if (!map.has(y)) map.set(y, []);
map.get(y)!.push(letter);
}
const groups: YearGroup[] = [];
// Sorted years first, then undated (0) at the end
const years = Array.from(map.keys()).sort((a, b) => a - b);
for (const y of years) {
if (y === 0) continue;
const items = map.get(y)!;
groups.push({
year: y,
label: String(y),
count: items.length,
letters: items,
});
}
const undated = map.get(0);
if (undated && undated.length > 0) {
groups.push({
year: 0,
label: "Undated",
count: undated.length,
letters: undated,
});
}
return groups;
}
function buildMonthGroups(letters: LetterItem[]): MonthGroup[] {
const map = new Map<number, LetterItem[]>();
for (const letter of letters) {
const m =
letter.month && letter.month >= 1 && letter.month <= 12
? letter.month
: 0;
if (!map.has(m)) map.set(m, []);
map.get(m)!.push(letter);
}
const groups: MonthGroup[] = [];
for (let m = 1; m <= 12; m++) {
const items = map.get(m);
if (items && items.length > 0) {
groups.push({ month: m, label: MONTH_NAMES[m], letters: items });
}
}
const unknown = map.get(0);
if (unknown && unknown.length > 0) {
groups.push({ month: 0, label: "Unknown Month", letters: unknown });
}
return groups;
}
// ---------------------------------------------------------------------------
// Year Sidebar — matches book chapter sidebar
// ---------------------------------------------------------------------------
function YearSidebar({
groups,
activeYear,
onSelect,
}: {
groups: YearGroup[];
activeYear: number;
onSelect: (year: number) => void;
}) {
return (
<aside className="hidden lg:block w-56 shrink-0 sticky top-[89px] self-start max-h-[calc(100vh-89px)] overflow-y-auto py-8 pr-4">
<h2 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3 px-2">
Years
</h2>
<nav className="flex flex-col gap-0.5">
{groups.map((g) => {
const isActive = g.year === activeYear;
return (
<button
key={g.year}
onClick={() => onSelect(g.year)}
className={cn(
"flex items-center justify-between gap-2 px-2 py-1.5 rounded-md text-sm transition-colors text-left",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<span className="truncate">{g.label}</span>
<span
className={cn(
"text-xs tabular-nums shrink-0",
isActive ? "text-primary/70" : "text-muted-foreground/60",
)}
>
{g.count}
</span>
</button>
);
})}
</nav>
</aside>
);
}
// ---------------------------------------------------------------------------
// Mobile drawer — matches MobileNav
// ---------------------------------------------------------------------------
function YearMobileNav({
groups,
activeYear,
onSelect,
title,
}: {
groups: YearGroup[];
activeYear: number;
onSelect: (year: number) => void;
title: string;
}) {
const [open, setOpen] = useState(false);
return (
<Drawer open={open} onOpenChange={setOpen} direction="left">
<DrawerTrigger
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"lg:hidden gap-1.5",
)}
>
<Menu className="size-4" />
<span className="hidden sm:inline">Years</span>
</DrawerTrigger>
<DrawerContent direction="left" className="h-full">
<DrawerHeader className="text-left border-b border-border pb-4 mb-2">
<DrawerTitle>{title}</DrawerTitle>
</DrawerHeader>
<nav className="overflow-y-auto px-4 pb-6 pt-2">
<div className="flex flex-col gap-0.5">
{groups.map((g) => {
const isActive = g.year === activeYear;
return (
<DrawerClose key={g.year} asChild>
<button
onClick={() => {
onSelect(g.year);
setOpen(false);
}}
className={cn(
"flex items-center justify-between gap-2 px-2 py-2 rounded-md text-sm transition-colors text-left",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<span>{g.label}</span>
<span
className={cn(
"text-xs tabular-nums",
isActive
? "text-primary/70"
: "text-muted-foreground/60",
)}
>
{g.count}
</span>
</button>
</DrawerClose>
);
})}
</div>
</nav>
</DrawerContent>
</Drawer>
);
}
// ---------------------------------------------------------------------------
// Prev / Next nav — matches BbdNav
// ---------------------------------------------------------------------------
function YearNav({
prev,
next,
groups,
activeYear,
onSelect,
drawerTitle,
}: {
prev: YearGroup | null;
next: YearGroup | null;
groups: YearGroup[];
activeYear: number;
onSelect: (year: number) => void;
drawerTitle: string;
}) {
return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<YearMobileNav
groups={groups}
activeYear={activeYear}
onSelect={onSelect}
title={drawerTitle}
/>
{prev ? (
<button
onClick={() => onSelect(prev.year)}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<ChevronLeft className="size-4" />
<span className="hidden sm:inline truncate max-w-[180px]">
{prev.label}
</span>
<span className="sm:hidden">Previous</span>
</button>
) : (
<div className="hidden lg:block" />
)}
</div>
{next ? (
<button
onClick={() => onSelect(next.year)}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<span className="hidden sm:inline truncate max-w-[180px]">
{next.label}
</span>
<span className="sm:hidden">Next</span>
<ChevronRight className="size-4" />
</button>
) : (
<div />
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Month section — collapsible group of letters for a single month
// ---------------------------------------------------------------------------
function MonthSection({
group,
defaultOpen,
}: {
group: MonthGroup;
defaultOpen: boolean;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<div>
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-3 w-full px-5 py-3 text-left hover:bg-muted/50 transition-colors"
>
<ChevronRight
className={cn(
"size-4 text-muted-foreground shrink-0 transition-transform",
open && "rotate-90",
)}
/>
<span className="font-semibold text-foreground text-sm">
{group.label}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{group.letters.length}{" "}
{group.letters.length === 1 ? "letter" : "letters"}
</span>
</button>
{open && (
<ul className="divide-y divide-border">
{group.letters.map((letter) => (
<li key={letter.slug}>
<Link
href={`/letters/${letter.slug}`}
className="flex flex-col sm:flex-row sm:items-center sm:justify-between px-5 pl-12 py-3.5 gap-1 sm:gap-4 hover:bg-muted transition-colors"
>
<div className="min-w-0 flex-1">
<p className="font-medium text-foreground text-sm">
To: {letter.recipientDisplay}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{letter.date || "Undated"}
{letter.location ? ` · ${letter.location}` : ""}
</p>
</div>
</Link>
</li>
))}
</ul>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Main component — header + sidebar (years) + content (month-grouped letters)
//
// Props:
// letters — all letters for this filter (recipient or location)
// filterName — display name for the filter ("Mukunda", "New York", etc.)
// filterType — "recipient" | "location" (used for back link and title)
// totalCount — total letter count
// ---------------------------------------------------------------------------
export function FilterYearBrowser({
letters,
filterName,
filterType,
totalCount,
}: {
letters: LetterItem[];
filterName: string;
filterType: "recipient" | "location";
totalCount: number;
}) {
const yearGroups = useMemo(() => buildYearGroups(letters), [letters]);
const [activeYearRaw, setActiveYear] = useState<number>(
yearGroups.length > 0 ? yearGroups[0].year : 0,
);
// Derive a safe active year — if the raw value is no longer valid, fall back to the first group
const activeYear = useMemo(() => {
if (yearGroups.length === 0) return activeYearRaw;
if (yearGroups.find((g) => g.year === activeYearRaw)) return activeYearRaw;
return yearGroups[0].year;
}, [yearGroups, activeYearRaw]);
const contentRef = useRef<HTMLDivElement>(null);
const handleYearSelect = (year: number) => {
setActiveYear(year);
contentRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
};
// Active group + neighbors
const activeIdx = yearGroups.findIndex((g) => g.year === activeYear);
const activeGroup = activeIdx >= 0 ? yearGroups[activeIdx] : null;
const prev = activeIdx > 0 ? yearGroups[activeIdx - 1] : null;
const next =
activeIdx >= 0 && activeIdx < yearGroups.length - 1
? yearGroups[activeIdx + 1]
: null;
// Month groups within the active year
const monthGroups = useMemo(
() => buildMonthGroups(activeGroup?.letters ?? []),
[activeGroup],
);
// Header text
const backHref =
filterType === "recipient"
? "/letters?view=recipient"
: "/letters?view=location";
const backLabel =
filterType === "recipient" ? "Letters by Recipient" : "Letters by Location";
const titlePrefix =
filterType === "recipient" ? "Letters to" : "Letters from";
const drawerTitle = `${titlePrefix} ${filterName}`;
const activeYearLabel = activeGroup?.label ?? "Unknown";
return (
<>
{/* Header */}
<header className="border-b border-border bg-card px-6 py-4 sticky top-0 z-20">
<div className="max-w-5xl mx-auto">
<Link
href={backHref}
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
&larr; {backLabel}
</Link>
<h1 className="mt-3 text-2xl font-bold text-foreground">
<span className="text-primary">
{titlePrefix} {filterName}:{" "}
</span>
{activeYearLabel}
</h1>
<p className="mt-1 text-muted-foreground">
{activeGroup?.count ?? 0}{" "}
{(activeGroup?.count ?? 0) === 1 ? "letter" : "letters"} in{" "}
{activeYearLabel} · {totalCount} total
</p>
</div>
</header>
{/* Sidebar + Main */}
<div className="max-w-5xl mx-auto flex">
{/* Left sidebar — years */}
<YearSidebar
groups={yearGroups}
activeYear={activeYear}
onSelect={handleYearSelect}
/>
{/* Main content */}
<main ref={contentRef} className="flex-1 min-w-0 px-6 py-8 space-y-8">
{/* Top navigation */}
<YearNav
prev={prev}
next={next}
groups={yearGroups}
activeYear={activeYear}
onSelect={handleYearSelect}
drawerTitle={drawerTitle}
/>
{/* Content — letters grouped by month */}
{monthGroups.length === 0 ? (
<div className="py-12 text-center text-muted-foreground">
<p className="text-lg font-medium">No letters for this year</p>
</div>
) : (
<Card className="overflow-hidden">
<CardContent className="p-0 divide-y divide-border">
{monthGroups.map((mg, i) => (
<MonthSection
key={mg.month}
group={mg}
defaultOpen={i === 0 || monthGroups.length <= 3}
/>
))}
</CardContent>
</Card>
)}
{/* Bottom navigation */}
<YearNav
prev={prev}
next={next}
groups={yearGroups}
activeYear={activeYear}
onSelect={handleYearSelect}
drawerTitle={drawerTitle}
/>
</main>
</div>
</>
);
}
+455
View File
@@ -0,0 +1,455 @@
"use client";
import { useState, useMemo, useRef, useEffect } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import {
Search,
ChevronLeft,
ChevronRight,
ArrowUpDown,
ArrowDownAZ,
ArrowUpAZ,
Hash,
Check,
} from "lucide-react";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type YearGroup = { year: number; count: number };
export type RecipientGroup = { name: string; count: number };
export type LocationGroup = { name: string; count: number };
type SortMode = "count" | "asc" | "desc";
// ---------------------------------------------------------------------------
// Diacritic-aware normalize (matches books-grid pattern)
// ---------------------------------------------------------------------------
function normalize(text: string): string {
return text
.toLowerCase()
.replace(/ṛ/g, "r")
.replace(/ṝ/g, "r")
.replace(/ṣ/g, "s")
.replace(/ś/g, "s")
.replace(/ṭ/g, "t")
.replace(/ḍ/g, "d")
.replace(/ṇ/g, "n")
.replace(/ñ/g, "n")
.replace(/ṅ/g, "n")
.replace(/ḥ/g, "h")
.replace(/ṁ/g, "m")
.replace(/ṃ/g, "m")
.replace(/ḷ/g, "l")
.replace(/ā/g, "a")
.replace(/ī/g, "i")
.replace(/ū/g, "u")
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "");
}
// ---------------------------------------------------------------------------
// Sort Popover
// ---------------------------------------------------------------------------
const SORT_OPTIONS: { key: SortMode; label: string; icon: typeof Hash }[] = [
{ key: "count", label: "Most letters first", icon: Hash },
{ key: "asc", label: "A → Z", icon: ArrowDownAZ },
{ key: "desc", label: "Z → A", icon: ArrowUpAZ },
];
const SORT_OPTIONS_YEAR: { key: SortMode; label: string; icon: typeof Hash }[] =
[
{ key: "count", label: "Most letters first", icon: Hash },
{ key: "asc", label: "Oldest first", icon: ArrowDownAZ },
{ key: "desc", label: "Newest first", icon: ArrowUpAZ },
];
function SortPopover({
sort,
onSortChange,
isYear,
}: {
sort: SortMode;
onSortChange: (s: SortMode) => void;
isYear?: boolean;
}) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
// Close on outside click
useEffect(() => {
if (!open) return;
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [open]);
const options = isYear ? SORT_OPTIONS_YEAR : SORT_OPTIONS;
return (
<div ref={ref} className="relative">
<button
onClick={() => setOpen(!open)}
className={cn(
"flex items-center justify-center size-10 rounded-lg border transition-colors",
open
? "bg-primary/10 border-primary/30 text-primary"
: "border-border text-muted-foreground hover:bg-muted hover:text-foreground",
)}
title="Sort options"
aria-label="Sort options"
>
<ArrowUpDown className="size-4" />
</button>
{open && (
<div className="absolute right-0 top-12 z-50 w-52 rounded-lg border border-border bg-card shadow-lg py-1 animate-in fade-in-0 zoom-in-95">
{options.map((opt) => {
const Icon = opt.icon;
const isActive = sort === opt.key;
return (
<button
key={opt.key}
onClick={() => {
onSortChange(opt.key);
setOpen(false);
}}
className={cn(
"flex items-center gap-3 w-full px-3 py-2.5 text-sm transition-colors text-left",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-foreground hover:bg-muted",
)}
>
<Icon className="size-4 shrink-0" />
<span className="flex-1">{opt.label}</span>
{isActive && <Check className="size-3.5 shrink-0" />}
</button>
);
})}
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Pagination
// ---------------------------------------------------------------------------
const PAGE_SIZE_RECIPIENTS = 50;
const PAGE_SIZE_LOCATIONS = 60;
const PAGE_SIZE_YEARS = 100;
function Pagination({
page,
totalPages,
onPageChange,
}: {
page: number;
totalPages: number;
onPageChange: (p: number) => void;
}) {
if (totalPages <= 1) return null;
return (
<div className="flex items-center justify-center gap-3 pt-4">
<button
onClick={() => onPageChange(page - 1)}
disabled={page <= 1}
className={cn(
"flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium transition-colors",
page <= 1
? "text-muted-foreground/40 cursor-not-allowed"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<ChevronLeft className="size-4" />
Previous
</button>
<span className="text-sm text-muted-foreground">
Page {page} of {totalPages}
</span>
<button
onClick={() => onPageChange(page + 1)}
disabled={page >= totalPages}
className={cn(
"flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium transition-colors",
page >= totalPages
? "text-muted-foreground/40 cursor-not-allowed"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
Next
<ChevronRight className="size-4" />
</button>
</div>
);
}
// ---------------------------------------------------------------------------
// Sorting helpers
// ---------------------------------------------------------------------------
function sortYears(data: YearGroup[], mode: SortMode): YearGroup[] {
const sorted = [...data];
switch (mode) {
case "count":
return sorted.sort((a, b) => b.count - a.count);
case "asc":
return sorted.sort((a, b) => a.year - b.year);
case "desc":
return sorted.sort((a, b) => b.year - a.year);
}
}
function sortRecipients(
data: RecipientGroup[],
mode: SortMode,
): RecipientGroup[] {
const sorted = [...data];
switch (mode) {
case "count":
return sorted.sort((a, b) => b.count - a.count);
case "asc":
return sorted.sort((a, b) => a.name.localeCompare(b.name));
case "desc":
return sorted.sort((a, b) => b.name.localeCompare(a.name));
}
}
function sortLocations(data: LocationGroup[], mode: SortMode): LocationGroup[] {
const sorted = [...data];
switch (mode) {
case "count":
return sorted.sort((a, b) => b.count - a.count);
case "asc":
return sorted.sort((a, b) => a.name.localeCompare(b.name));
case "desc":
return sorted.sort((a, b) => b.name.localeCompare(a.name));
}
}
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export function LettersBrowser({
currentView,
years,
recipients,
locations,
}: {
currentView: string;
years: YearGroup[];
recipients: RecipientGroup[];
locations: LocationGroup[];
}) {
const [query, setQuery] = useState("");
const [page, setPage] = useState(1);
const [sortYear, setSortYear] = useState<SortMode>("asc");
const [sortRecipient, setSortRecipient] = useState<SortMode>("count");
const [sortLocation, setSortLocation] = useState<SortMode>("count");
const handleQueryChange = (q: string) => {
setQuery(q);
setPage(1);
};
const handleSortChange = (mode: SortMode) => {
if (currentView === "year") setSortYear(mode);
else if (currentView === "recipient") setSortRecipient(mode);
else setSortLocation(mode);
setPage(1);
};
const currentSort =
currentView === "year"
? sortYear
: currentView === "recipient"
? sortRecipient
: sortLocation;
// --- Filtered + sorted data ---
const filteredYears = useMemo(() => {
let data = years;
if (query.trim()) {
const q = normalize(query.trim());
data = data.filter((yg) => String(yg.year).includes(q));
}
return sortYears(data, sortYear);
}, [years, query, sortYear]);
const filteredRecipients = useMemo(() => {
let data = recipients;
if (query.trim()) {
const q = normalize(query.trim());
data = data.filter((rg) => normalize(rg.name).includes(q));
}
return sortRecipients(data, sortRecipient);
}, [recipients, query, sortRecipient]);
const filteredLocations = useMemo(() => {
let data = locations;
if (query.trim()) {
const q = normalize(query.trim());
data = data.filter((lg) => normalize(lg.name).includes(q));
}
return sortLocations(data, sortLocation);
}, [locations, query, sortLocation]);
// --- Paginated data ---
const activeData =
currentView === "year"
? filteredYears
: currentView === "recipient"
? filteredRecipients
: filteredLocations;
const pageSize =
currentView === "year"
? PAGE_SIZE_YEARS
: currentView === "recipient"
? PAGE_SIZE_RECIPIENTS
: PAGE_SIZE_LOCATIONS;
const totalPages = Math.max(1, Math.ceil(activeData.length / pageSize));
const safePage = Math.min(page, totalPages);
const startIdx = (safePage - 1) * pageSize;
const endIdx = startIdx + pageSize;
const placeholder =
currentView === "year"
? "Search years..."
: currentView === "recipient"
? "Search recipients..."
: "Search locations...";
const resultCount = activeData.length;
const totalCount =
currentView === "year"
? years.length
: currentView === "recipient"
? recipients.length
: locations.length;
return (
<div className="space-y-4">
{/* Search + Sort */}
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<Input
type="text"
placeholder={placeholder}
value={query}
onChange={(e) => handleQueryChange(e.target.value)}
className="pl-9"
/>
</div>
<SortPopover
sort={currentSort}
onSortChange={handleSortChange}
isYear={currentView === "year"}
/>
</div>
{/* Result count */}
{query.trim() && (
<p className="text-sm text-muted-foreground">
{resultCount === 0
? "No results found"
: `${resultCount} of ${totalCount} ${currentView === "year" ? "years" : currentView === "recipient" ? "recipients" : "locations"}`}
</p>
)}
{/* Year view */}
{currentView === "year" && (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
{(filteredYears.slice(startIdx, endIdx) as YearGroup[]).map((yg) => (
<Link key={yg.year} href={`/letters/year/${yg.year}`}>
<Card className="transition-all hover:shadow-md hover:ring-foreground/20">
<CardContent className="py-4 px-4 text-center">
<p className="text-lg font-bold text-foreground">{yg.year}</p>
<p className="text-xs text-muted-foreground">
{yg.count} {yg.count === 1 ? "letter" : "letters"}
</p>
</CardContent>
</Card>
</Link>
))}
</div>
)}
{/* Recipient view */}
{currentView === "recipient" && (
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
{(filteredRecipients.slice(startIdx, endIdx) as RecipientGroup[]).map(
(rg) => (
<Link
key={rg.name}
href={`/letters/recipient/${encodeURIComponent(rg.name)}`}
>
<Card className="transition-all hover:shadow-md hover:ring-foreground/20">
<CardContent className="py-4 px-4 text-center">
<p className="font-medium text-foreground truncate">
{rg.name}
</p>
<p className="text-xs text-muted-foreground">
{rg.count} {rg.count === 1 ? "letter" : "letters"}
</p>
</CardContent>
</Card>
</Link>
),
)}
</div>
)}
{/* Location view */}
{currentView === "location" && (
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
{(filteredLocations.slice(startIdx, endIdx) as LocationGroup[]).map(
(lg) => (
<Link
key={lg.name}
href={`/letters/location/${encodeURIComponent(lg.name)}`}
>
<Card className="transition-all hover:shadow-md hover:ring-foreground/20">
<CardContent className="py-4 px-4 text-center">
<p className="font-medium text-foreground">{lg.name}</p>
<p className="text-xs text-muted-foreground">
{lg.count} {lg.count === 1 ? "letter" : "letters"}
</p>
</CardContent>
</Card>
</Link>
),
)}
</div>
)}
{/* Pagination */}
<Pagination
page={safePage}
totalPages={totalPages}
onPageChange={setPage}
/>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
"use client";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { Calendar, User, MapPin } from "lucide-react";
const views = [
{ key: "year", label: "Year", icon: Calendar },
{ key: "recipient", label: "Recipient", icon: User },
{ key: "location", label: "Location", icon: MapPin },
];
export function LettersNav({ currentView }: { currentView: string }) {
return (
<div className="flex gap-2 border-b border-border pb-3">
{views.map((v) => {
const Icon = v.icon;
const isActive = currentView === v.key;
return (
<Link
key={v.key}
href={`/letters?view=${v.key}`}
className={cn(
"flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors",
isActive
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Icon className="size-4" />
{v.label}
</Link>
);
})}
</div>
);
}
@@ -0,0 +1,51 @@
export const dynamic = "force-dynamic";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getLettersByLocation } from "@/lib/letters";
import { ogForLettersByLocation } from "@/lib/og";
import { FilterYearBrowser } from "../../filter-year-browser";
export async function generateMetadata({
params,
}: {
params: Promise<{ name: string }>;
}): Promise<Metadata> {
const { name: encodedName } = await params;
const name = decodeURIComponent(encodedName);
const letters = await getLettersByLocation(name);
if (letters.length === 0) return {};
return ogForLettersByLocation(name, letters.length);
}
export default async function LettersByLocationPage({
params,
}: {
params: Promise<{ name: string }>;
}) {
const { name: encodedName } = await params;
const name = decodeURIComponent(encodedName);
const letters = await getLettersByLocation(name);
if (letters.length === 0) notFound();
const serialized = letters.map((l) => ({
slug: l.slug,
recipientDisplay: l.recipientDisplay,
date: l.date,
year: l.year,
month: l.month,
location: l.location,
}));
return (
<div className="min-h-screen bg-background">
<FilterYearBrowser
letters={serialized}
filterName={name}
filterType="location"
totalCount={letters.length}
/>
</div>
);
}
+66
View File
@@ -0,0 +1,66 @@
export const dynamic = "force-dynamic";
import type { Metadata } from "next";
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { buildOgMeta } from "@/lib/og";
import {
getLetterYears,
getLetterRecipients,
getLetterLocations,
getTotalLetterCount,
} from "@/lib/letters";
import { LettersNav } from "./letters-nav";
import { LettersBrowser } from "./letters-browser";
export function generateMetadata(): Metadata {
return buildOgMeta({
title: "Letters",
detail: "6,800+ letters (1947–1977)",
quote:
"Personal correspondence by Śrīla Prabhupāda — guiding disciples, Godbrothers, and well-wishers in the science of Kṛṣṇa consciousness.",
});
}
export default async function LettersPage({
searchParams,
}: {
searchParams: Promise<{ view?: string }>;
}) {
const { view = "year" } = await searchParams;
const [years, recipients, locations, totalCount] = await Promise.all([
getLetterYears(),
getLetterRecipients(),
getLetterLocations(),
getTotalLetterCount(),
]);
return (
<div className="min-h-screen bg-background">
<PageHeader>
<Link
href="/"
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
&larr; Home
</Link>
<h1 className="mt-3 text-3xl font-bold text-foreground">Letters</h1>
<p className="mt-1 text-muted-foreground">
{totalCount.toLocaleString()} letters by Śrīla Prabhupāda (1947–1977)
</p>
</PageHeader>
<main className="max-w-4xl mx-auto px-6 py-8 space-y-6">
<LettersNav currentView={view} />
<LettersBrowser
currentView={view}
years={years}
recipients={recipients}
locations={locations}
/>
</main>
</div>
);
}
@@ -0,0 +1,51 @@
export const dynamic = "force-dynamic";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getLettersByRecipient } from "@/lib/letters";
import { ogForLettersByRecipient } from "@/lib/og";
import { FilterYearBrowser } from "../../filter-year-browser";
export async function generateMetadata({
params,
}: {
params: Promise<{ name: string }>;
}): Promise<Metadata> {
const { name: encodedName } = await params;
const name = decodeURIComponent(encodedName);
const letters = await getLettersByRecipient(name);
if (letters.length === 0) return {};
return ogForLettersByRecipient(name, letters.length);
}
export default async function LettersByRecipientPage({
params,
}: {
params: Promise<{ name: string }>;
}) {
const { name: encodedName } = await params;
const name = decodeURIComponent(encodedName);
const letters = await getLettersByRecipient(name);
if (letters.length === 0) notFound();
const serialized = letters.map((l) => ({
slug: l.slug,
recipientDisplay: l.recipientDisplay,
date: l.date,
year: l.year,
month: l.month,
location: l.location,
}));
return (
<div className="min-h-screen bg-background">
<FilterYearBrowser
letters={serialized}
filterName={name}
filterType="recipient"
totalCount={letters.length}
/>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
export const dynamic = "force-dynamic";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getLettersByYear } from "@/lib/letters";
import { ogForLettersByYear } from "@/lib/og";
import { YearMonthBrowser } from "./year-month-browser";
export async function generateMetadata({
params,
}: {
params: Promise<{ year: string }>;
}): Promise<Metadata> {
const { year: yearStr } = await params;
const year = parseInt(yearStr, 10);
if (isNaN(year)) return {};
const letters = await getLettersByYear(year);
return ogForLettersByYear(year, letters.length);
}
export default async function LettersByYearPage({
params,
}: {
params: Promise<{ year: string }>;
}) {
const { year: yearStr } = await params;
const year = parseInt(yearStr, 10);
if (isNaN(year)) notFound();
const letters = await getLettersByYear(year);
if (letters.length === 0) notFound();
const serialized = letters.map((l) => ({
slug: l.slug,
recipientDisplay: l.recipientDisplay,
date: l.date,
year: l.year,
month: l.month,
location: l.location,
}));
return (
<div className="min-h-screen bg-background">
<YearMonthBrowser
letters={serialized}
year={year}
totalCount={letters.length}
/>
</div>
);
}
@@ -0,0 +1,443 @@
"use client";
import { useState, useMemo, useRef } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ChevronLeft, ChevronRight, Menu } from "lucide-react";
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type LetterItem = {
slug: string;
recipientDisplay: string;
date: string | null;
year: number | null;
month: number | null;
location: string | null;
};
type MonthGroup = {
month: number;
label: string;
shortLabel: string;
count: number;
letters: LetterItem[];
};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MONTH_NAMES = [
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const MONTH_SHORT = [
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
// ---------------------------------------------------------------------------
// Build month groups from flat letter list
// ---------------------------------------------------------------------------
function buildMonthGroups(letters: LetterItem[]): MonthGroup[] {
const map = new Map<number, LetterItem[]>();
for (const letter of letters) {
const m =
letter.month && letter.month >= 1 && letter.month <= 12
? letter.month
: 0;
if (!map.has(m)) map.set(m, []);
map.get(m)!.push(letter);
}
const groups: MonthGroup[] = [];
for (let m = 1; m <= 12; m++) {
const items = map.get(m);
if (items && items.length > 0) {
groups.push({
month: m,
label: MONTH_NAMES[m],
shortLabel: MONTH_SHORT[m],
count: items.length,
letters: items,
});
}
}
const unknown = map.get(0);
if (unknown && unknown.length > 0) {
groups.push({
month: 0,
label: "Unknown Month",
shortLabel: "Unknown",
count: unknown.length,
letters: unknown,
});
}
return groups;
}
// ---------------------------------------------------------------------------
// Sidebar — matches book chapter sidebar
// ---------------------------------------------------------------------------
function MonthSidebar({
groups,
activeMonth,
onSelect,
}: {
groups: MonthGroup[];
activeMonth: number;
onSelect: (month: number) => void;
}) {
return (
<aside className="hidden lg:block w-56 shrink-0 sticky top-[89px] self-start max-h-[calc(100vh-89px)] overflow-y-auto py-8 pr-4">
<h2 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3 px-2">
Months
</h2>
<nav className="flex flex-col gap-0.5">
{groups.map((g) => {
const isActive = g.month === activeMonth;
return (
<button
key={g.month}
onClick={() => onSelect(g.month)}
className={cn(
"flex items-center justify-between gap-2 px-2 py-1.5 rounded-md text-sm transition-colors text-left",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<span className="truncate">{g.label}</span>
<span
className={cn(
"text-xs tabular-nums shrink-0",
isActive ? "text-primary/70" : "text-muted-foreground/60",
)}
>
{g.count}
</span>
</button>
);
})}
</nav>
</aside>
);
}
// ---------------------------------------------------------------------------
// Mobile drawer — matches MobileNav
// ---------------------------------------------------------------------------
function MonthMobileNav({
groups,
activeMonth,
onSelect,
year,
}: {
groups: MonthGroup[];
activeMonth: number;
onSelect: (month: number) => void;
year: number;
}) {
const [open, setOpen] = useState(false);
return (
<Drawer open={open} onOpenChange={setOpen} direction="left">
<DrawerTrigger
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"lg:hidden gap-1.5",
)}
>
<Menu className="size-4" />
<span className="hidden sm:inline">Months</span>
</DrawerTrigger>
<DrawerContent direction="left" className="h-full">
<DrawerHeader className="text-left border-b border-border pb-4 mb-2">
<DrawerTitle>Letters from {year}</DrawerTitle>
</DrawerHeader>
<nav className="overflow-y-auto px-4 pb-6 pt-2">
<div className="flex flex-col gap-0.5">
{groups.map((g) => {
const isActive = g.month === activeMonth;
return (
<DrawerClose key={g.month} asChild>
<button
onClick={() => {
onSelect(g.month);
setOpen(false);
}}
className={cn(
"flex items-center justify-between gap-2 px-2 py-2 rounded-md text-sm transition-colors text-left",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<span>{g.label}</span>
<span
className={cn(
"text-xs tabular-nums",
isActive
? "text-primary/70"
: "text-muted-foreground/60",
)}
>
{g.count}
</span>
</button>
</DrawerClose>
);
})}
</div>
</nav>
</DrawerContent>
</Drawer>
);
}
// ---------------------------------------------------------------------------
// Prev / Next nav — matches BbdNav
// ---------------------------------------------------------------------------
function MonthNav({
prev,
next,
groups,
activeMonth,
onSelect,
year,
}: {
prev: MonthGroup | null;
next: MonthGroup | null;
groups: MonthGroup[];
activeMonth: number;
onSelect: (month: number) => void;
year: number;
}) {
return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<MonthMobileNav
groups={groups}
activeMonth={activeMonth}
onSelect={onSelect}
year={year}
/>
{prev ? (
<button
onClick={() => onSelect(prev.month)}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<ChevronLeft className="size-4" />
<span className="hidden sm:inline truncate max-w-[180px]">
{prev.shortLabel}
</span>
<span className="sm:hidden">Previous</span>
</button>
) : (
<div className="hidden lg:block" />
)}
</div>
{next ? (
<button
onClick={() => onSelect(next.month)}
className={cn(
buttonVariants({ variant: "outline", size: "sm" }),
"gap-1.5",
)}
>
<span className="hidden sm:inline truncate max-w-[180px]">
{next.shortLabel}
</span>
<span className="sm:hidden">Next</span>
<ChevronRight className="size-4" />
</button>
) : (
<div />
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Main component — renders header + sidebar + content (entire page layout)
// ---------------------------------------------------------------------------
export function YearMonthBrowser({
letters,
year,
totalCount,
}: {
letters: LetterItem[];
year: number;
totalCount: number;
}) {
const allGroups = useMemo(() => buildMonthGroups(letters), [letters]);
const [activeMonthRaw, setActiveMonth] = useState<number>(
allGroups.length > 0 ? allGroups[0].month : 1,
);
// Derive a safe active month — if the raw value is no longer valid, fall back to the first group
const activeMonth = useMemo(() => {
if (allGroups.length === 0) return activeMonthRaw;
if (allGroups.find((g) => g.month === activeMonthRaw))
return activeMonthRaw;
return allGroups[0].month;
}, [allGroups, activeMonthRaw]);
const contentRef = useRef<HTMLDivElement>(null);
const handleMonthSelect = (month: number) => {
setActiveMonth(month);
contentRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
};
// Active group + neighbors
const activeIdx = allGroups.findIndex((g) => g.month === activeMonth);
const activeGroup = activeIdx >= 0 ? allGroups[activeIdx] : null;
const prev = activeIdx > 0 ? allGroups[activeIdx - 1] : null;
const next =
activeIdx >= 0 && activeIdx < allGroups.length - 1
? allGroups[activeIdx + 1]
: null;
const activeLetters = activeGroup?.letters ?? [];
const activeLabel = activeGroup?.label ?? "Unknown Month";
return (
<>
{/* Header */}
<header className="border-b border-border bg-card px-6 py-4 sticky top-0 z-20">
<div className="max-w-5xl mx-auto">
<Link
href="/letters?view=year"
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
&larr; Letters by Year
</Link>
<h1 className="mt-3 text-2xl font-bold text-foreground">
<span className="text-primary">Letters: </span>
{activeLabel} {year}
</h1>
<p className="mt-1 text-muted-foreground">
{activeGroup?.count ?? 0}{" "}
{(activeGroup?.count ?? 0) === 1 ? "letter" : "letters"} ·{" "}
{totalCount} total in {year}
</p>
</div>
</header>
{/* Sidebar + Main */}
<div className="max-w-5xl mx-auto flex">
{/* Left sidebar */}
<MonthSidebar
groups={allGroups}
activeMonth={activeMonth}
onSelect={handleMonthSelect}
/>
{/* Main content */}
<main ref={contentRef} className="flex-1 min-w-0 px-6 py-8 space-y-8">
{/* Top navigation */}
<MonthNav
prev={prev}
next={next}
groups={allGroups}
activeMonth={activeMonth}
onSelect={handleMonthSelect}
year={year}
/>
{/* Content */}
{activeLetters.length === 0 ? (
<div className="py-12 text-center text-muted-foreground">
<p className="text-lg font-medium">No letters for this month</p>
</div>
) : (
<Card>
<CardContent className="p-0">
<ul className="divide-y divide-border">
{activeLetters.map((letter) => (
<li key={letter.slug}>
<Link
href={`/letters/${letter.slug}`}
className="flex flex-col sm:flex-row sm:items-center sm:justify-between px-5 py-4 gap-1 sm:gap-4 hover:bg-muted transition-colors"
>
<div className="min-w-0">
<p className="font-medium text-foreground">
To: {letter.recipientDisplay}
</p>
<p className="text-sm text-muted-foreground">
{letter.date || "Undated"}
{letter.location ? ` · ${letter.location}` : ""}
</p>
</div>
</Link>
</li>
))}
</ul>
</CardContent>
</Card>
)}
{/* Bottom navigation */}
<MonthNav
prev={prev}
next={next}
groups={allGroups}
activeMonth={activeMonth}
onSelect={handleMonthSelect}
year={year}
/>
</main>
</div>
</>
);
}