Compare commits

..
5 Commits
Author SHA1 Message Date
gosangamandClaude Opus 5.5 770d465fef Quiz times: show hours and days
Participant and response times roll up into hours, then days past
23h 59m (3h 20m, 2d 4h) — a two-day attempt read "2880m 0s" before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:29:05 +05:30
gosangamandClaude Opus 5.5 a63c329850 Feedback categories page; treat 204 responses as success
Feedback → Categories: add, rename, reorder, archive/restore, and delete
unused categories. Feedback rows show the category's current label.

The API helper now accepts 204 No Content, which previously surfaced as a
"No Content" error after archive/delete and quiz attempt resets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:47:09 +05:30
gosangam b194d4aa03 mobile responsive 2026-10-16 15:45:29 +05:30
gosangam 1e551764e1 mobile responsive 2026-10-16 15:23:58 +05:30
gosangam fcbffead8a quiz reset 2026-10-15 20:59:13 +05:30
27 changed files with 1092 additions and 298 deletions
+5 -4
View File
@@ -17,6 +17,7 @@ import { Can } from "@/components/staff-context";
import { toast } from "sonner"; import { toast } from "sonner";
import { broadcasts, type Broadcast } from "@/lib/api"; import { broadcasts, type Broadcast } from "@/lib/api";
import { compressImage } from "@/lib/compress-image"; import { compressImage } from "@/lib/compress-image";
import { Clamp } from "@/components/ui/clamp";
export default function BroadcastsPage() { export default function BroadcastsPage() {
const [items, setItems] = useState<Broadcast[]>([]); const [items, setItems] = useState<Broadcast[]>([]);
@@ -256,12 +257,12 @@ function BroadcastRow({
return ( return (
<li className="flex items-start gap-3 p-3"> <li className="flex items-start gap-3 p-3">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-foreground"> <Clamp className="text-sm font-medium text-foreground">
{item.title} {item.title}
</p> </Clamp>
<p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground"> <Clamp lines={2} className="mt-0.5 text-xs text-muted-foreground">
{item.body} {item.body}
</p> </Clamp>
<p className="mt-1 text-xs text-muted-foreground"> <p className="mt-1 text-xs text-muted-foreground">
{live {live
? `Published · dismissed by ${item.seen_count}` ? `Published · dismissed by ${item.seen_count}`
+11 -8
View File
@@ -6,6 +6,7 @@ import { usePagedList } from "@/lib/use-paged-list";
import { ListShell, EmptyRow } from "@/components/list-shell"; import { ListShell, EmptyRow } from "@/components/list-shell";
import { Table, THead, TR, TH, TD } from "@/components/ui/table"; import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { fmtDate } from "@/lib/utils"; import { fmtDate } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
export default function CollectionsPage() { export default function CollectionsPage() {
const [q, setQ] = useState(""); const [q, setQ] = useState("");
@@ -40,18 +41,20 @@ export default function CollectionsPage() {
list.items.map((c) => ( list.items.map((c) => (
<TR key={c.id}> <TR key={c.id}>
<TD className="max-w-md"> <TD className="max-w-md">
<div className="font-medium">{c.title}</div> <Clamp lines={2} className="font-medium">
{c.title}
</Clamp>
{c.description ? ( {c.description ? (
<div className="mt-0.5 line-clamp-1 text-xs text-muted-foreground"> <Clamp className="mt-0.5 text-xs text-muted-foreground">
{c.description} {c.description}
</div> </Clamp>
) : null} ) : null}
</TD> </TD>
<TD className="whitespace-nowrap"> <TD className="max-w-[14rem]">
<div className="font-medium">{c.owner_name}</div> <Clamp className="font-medium">{c.owner_name}</Clamp>
<div className="text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
@{c.owner_handle} {`@${c.owner_handle}`}
</div> </Clamp>
</TD> </TD>
<TD>{c.item_count}</TD> <TD>{c.item_count}</TD>
<TD> <TD>
@@ -0,0 +1,366 @@
"use client";
/**
* /feedback/categories — the options on the app's /feedback form.
*
* A category's key (what each submission stores) is fixed when it's created,
* so renaming one relabels every past submission too. Archiving takes it off
* the form but keeps its label on existing feedback. Only a category nothing
* has been filed under can be deleted — production feedback is never left
* without a category.
*
* Anyone who can read feedback can see this page; changing it needs
* feedback:categories.
*/
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { ArrowDown, ArrowUp, Plus } from "lucide-react";
import { toast } from "sonner";
import {
AdminError,
feedbackCategories,
type FeedbackCategory,
} from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal";
import { Clamp } from "@/components/ui/clamp";
import { Can, useStaff } from "@/components/staff-context";
import { useConfirm } from "@/components/confirm";
const errMsg = (err: unknown, fallback: string) =>
err instanceof AdminError ? err.message : fallback;
export default function FeedbackCategoriesPage() {
const [list, setList] = useState<FeedbackCategory[] | null>(null);
const [editing, setEditing] = useState<FeedbackCategory | "new" | null>(
null,
);
const [busy, setBusy] = useState(false);
const confirm = useConfirm();
const { can } = useStaff();
const canEdit = can("feedback:categories");
const refresh = useCallback(
() =>
feedbackCategories
.list()
.then(setList)
.catch((err) => {
toast.error(errMsg(err, "Could not load categories"));
setList([]);
}),
[],
);
useEffect(() => {
void refresh();
}, [refresh]);
const active = (list ?? []).filter((c) => !c.archived_at);
const archived = (list ?? []).filter((c) => c.archived_at);
const run = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
try {
await fn();
toast.success(ok);
await refresh();
} catch (err) {
toast.error(errMsg(err, "That didn't work"));
} finally {
setBusy(false);
}
};
const move = (i: number, by: number) => {
const j = i + by;
if (j < 0 || j >= active.length) return;
const keys = active.map((c) => c.key);
[keys[i], keys[j]] = [keys[j], keys[i]];
void run(() => feedbackCategories.reorder(keys), "Order saved");
};
const setArchived = (c: FeedbackCategory, archived: boolean) =>
run(
() =>
feedbackCategories.update(c.key, {
label: c.label,
description: c.description,
archived,
}),
archived ? `“${c.label}” archived` : `“${c.label}” restored`,
);
const remove = async (c: FeedbackCategory) => {
if (
await confirm({
title: `Delete “${c.label}”?`,
message: "Nothing has been filed under it, so nothing else changes.",
confirmLabel: "Delete category",
destructive: true,
})
) {
void run(() => feedbackCategories.remove(c.key), "Category deleted");
}
};
return (
<div className="space-y-6">
<header className="flex flex-wrap items-start justify-between gap-4">
<div className="min-w-0 flex-1 basis-64">
<Link
href="/feedback"
className="text-xs text-muted-foreground hover:text-foreground"
>
← Feedback
</Link>
<h1 className="mt-1 text-xl font-semibold text-foreground">
Feedback categories
</h1>
<p className="mt-1 text-sm text-muted-foreground">
The choices on the app&apos;s feedback form, in this order.
Renaming a category relabels its past feedback too. Archive one to
take it off the form without touching what&apos;s already been sent.
</p>
</div>
<Can perm="feedback:categories">
<Button onClick={() => setEditing("new")}>
<Plus className="size-4" />
New category
</Button>
</Can>
</header>
{list === null ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : (
<>
<section className="space-y-2">
<h2 className="text-sm font-medium text-foreground">
On the form
</h2>
<ul className="divide-y divide-border rounded-xl border border-border bg-card">
{active.map((c, i) => (
<li
key={c.key}
className="flex flex-wrap items-start gap-3 px-4 py-3"
>
<CategoryText c={c} />
{canEdit && (
<div className="flex shrink-0 flex-wrap items-center gap-1">
<Button
size="sm"
variant="ghost"
disabled={busy || i === 0}
onClick={() => move(i, -1)}
aria-label={`Move ${c.label} up`}
>
<ArrowUp className="size-4" />
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy || i === active.length - 1}
onClick={() => move(i, 1)}
aria-label={`Move ${c.label} down`}
>
<ArrowDown className="size-4" />
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => setEditing(c)}
>
Edit
</Button>
<Button
size="sm"
variant="ghost"
// The form must always offer something.
disabled={busy || active.length === 1}
onClick={() => void setArchived(c, true)}
>
Archive
</Button>
</div>
)}
</li>
))}
</ul>
</section>
{archived.length > 0 && (
<section className="space-y-2">
<h2 className="text-sm font-medium text-foreground">Archived</h2>
<p className="text-xs text-muted-foreground">
Not offered on the form. Feedback already filed under them
keeps its category.
</p>
<ul className="divide-y divide-border rounded-xl border border-border bg-card">
{archived.map((c) => (
<li
key={c.key}
className="flex flex-wrap items-start gap-3 px-4 py-3 opacity-80"
>
<CategoryText c={c} />
{canEdit && (
<div className="flex shrink-0 flex-wrap items-center gap-1">
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => setEditing(c)}
>
Edit
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void setArchived(c, false)}
>
Restore
</Button>
{!c.usage_count && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void remove(c)}
className="text-destructive"
>
Delete
</Button>
)}
</div>
)}
</li>
))}
</ul>
</section>
)}
</>
)}
<CategoryModal
target={editing}
onClose={() => setEditing(null)}
onSaved={() => {
setEditing(null);
void refresh();
}}
/>
</div>
);
}
function CategoryText({ c }: { c: FeedbackCategory }) {
const n = c.usage_count ?? 0;
return (
<div className="min-w-0 flex-1 basis-48">
<Clamp className="text-sm font-medium text-foreground">{c.label}</Clamp>
{c.description && (
<Clamp lines={2} className="mt-0.5 text-xs text-muted-foreground">
{c.description}
</Clamp>
)}
<p className="mt-1 text-xs text-muted-foreground">
<span className="font-mono">{c.key}</span> · {n}{" "}
{n === 1 ? "submission" : "submissions"}
</p>
</div>
);
}
function CategoryModal({
target,
onClose,
onSaved,
}: {
target: FeedbackCategory | "new" | null;
onClose: () => void;
onSaved: () => void;
}) {
const editing = target && target !== "new" ? target : null;
// Re-seed the fields whenever a different category (or "new") opens.
const seed = editing ? editing.key : target;
const [lastSeed, setLastSeed] = useState<typeof seed>(null);
const [label, setLabel] = useState("");
const [description, setDescription] = useState("");
const [busy, setBusy] = useState(false);
if (seed !== lastSeed) {
setLastSeed(seed);
setLabel(editing?.label ?? "");
setDescription(editing?.description ?? "");
}
const save = async () => {
if (!label.trim()) return;
setBusy(true);
try {
if (editing) {
await feedbackCategories.update(editing.key, {
label: label.trim(),
description: description.trim(),
archived: !!editing.archived_at,
});
toast.success("Category saved");
} else {
await feedbackCategories.create(label.trim(), description.trim());
toast.success("Category added to the form");
}
onSaved();
} catch (err) {
toast.error(errMsg(err, "Could not save the category"));
} finally {
setBusy(false);
}
};
return (
<Modal
open={target !== null}
onClose={onClose}
title={editing ? "Edit category" : "New category"}
>
<div className="space-y-4">
<label className="block space-y-1.5">
<span className="text-sm font-medium">Name</span>
<Input
value={label}
onChange={(e) => setLabel(e.target.value)}
maxLength={60}
placeholder="e.g. Audio & playback"
/>
</label>
<label className="block space-y-1.5">
<span className="text-sm font-medium">Description</span>
<Input
value={description}
onChange={(e) => setDescription(e.target.value)}
maxLength={200}
placeholder="Shown under the choice on the form (optional)"
/>
</label>
{editing && (editing.usage_count ?? 0) > 0 && (
<p className="text-xs text-muted-foreground">
{editing.usage_count} past{" "}
{editing.usage_count === 1 ? "submission" : "submissions"} will
show the new name.
</p>
)}
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button onClick={() => void save()} disabled={busy || !label.trim()}>
{busy ? "Saving…" : editing ? "Save" : "Add category"}
</Button>
</div>
</div>
</Modal>
);
}
+24 -11
View File
@@ -1,6 +1,8 @@
"use client"; "use client";
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import Link from "next/link";
import { Tags } from "lucide-react";
import { Can } from "@/components/staff-context"; import { Can } from "@/components/staff-context";
import { toast } from "sonner"; import { toast } from "sonner";
import { api, AdminError, type AdminFeedback } from "@/lib/api"; import { api, AdminError, type AdminFeedback } from "@/lib/api";
@@ -13,6 +15,7 @@ import { useConfirm } from "@/components/confirm";
import { RichTextarea } from "@/components/ui/rich-textarea"; import { RichTextarea } from "@/components/ui/rich-textarea";
import { RichText } from "@/lib/rich-text"; import { RichText } from "@/lib/rich-text";
import { cn, fmtDate } from "@/lib/utils"; import { cn, fmtDate } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
const STATUSES = ["all", "open", "resolved"] as const; const STATUSES = ["all", "open", "resolved"] as const;
type Status = (typeof STATUSES)[number]; type Status = (typeof STATUSES)[number];
@@ -69,6 +72,13 @@ export default function FeedbackPage() {
total={list.total} total={list.total}
list={list} list={list}
toolbar={ toolbar={
<div className="flex flex-wrap items-center gap-2">
<Link href="/feedback/categories">
<Button variant="outline" size="sm">
<Tags className="size-4" />
Categories
</Button>
</Link>
<div className="flex gap-1 rounded-lg border border-border bg-card p-1"> <div className="flex gap-1 rounded-lg border border-border bg-card p-1">
{STATUSES.map((s) => ( {STATUSES.map((s) => (
<button <button
@@ -85,9 +95,12 @@ export default function FeedbackPage() {
</button> </button>
))} ))}
</div> </div>
</div>
} }
> >
<Table> {/* Phone: each field stacked, label above value, so a long message
gets the card's full width. Desktop: ordinary table rows. */}
<Table card="stacked">
<THead> <THead>
<TR> <TR>
<TH>From</TH> <TH>From</TH>
@@ -103,23 +116,23 @@ export default function FeedbackPage() {
) : ( ) : (
list.items.map((f) => ( list.items.map((f) => (
<TR key={f.id}> <TR key={f.id}>
<TD className="whitespace-nowrap"> <TD className="max-w-[14rem]">
{f.author_handle ? ( {f.author_handle ? (
<> <>
<div className="font-medium">{f.author_name}</div> <Clamp className="font-medium">{f.author_name}</Clamp>
<div className="text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
@{f.author_handle} {`@${f.author_handle}`}
</div> </Clamp>
</> </>
) : ( ) : (
<div className="text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
{f.contact_email ?? "Anonymous"} {f.contact_email ?? "Anonymous"}
</div> </Clamp>
)} )}
</TD> </TD>
<TD className="max-w-md"> <TD className="max-w-md">
<div className="text-xs uppercase tracking-wide text-muted-foreground"> <div className="text-xs uppercase tracking-wide text-muted-foreground">
{f.category} {f.category_label || f.category}
</div> </div>
<div className="mt-0.5 whitespace-pre-line">{f.message}</div> <div className="mt-0.5 whitespace-pre-line">{f.message}</div>
{f.reply_message ? ( {f.reply_message ? (
@@ -134,7 +147,7 @@ export default function FeedbackPage() {
</TD> </TD>
<TD className="whitespace-nowrap">{fmtDate(f.created_at)}</TD> <TD className="whitespace-nowrap">{fmtDate(f.created_at)}</TD>
<TD className="text-right"> <TD className="text-right">
<div className="flex flex-wrap justify-end gap-2"> <div className="flex flex-wrap justify-start gap-2 md:justify-end">
<Can perm="feedback:resolve"> <Can perm="feedback:resolve">
{!f.resolved_at && !f.acknowledged_at ? ( {!f.resolved_at && !f.acknowledged_at ? (
<Button <Button
@@ -243,7 +256,7 @@ function ReplyModal({
{feedback ? ( {feedback ? (
<div className="rounded-md bg-muted px-3 py-2 text-sm"> <div className="rounded-md bg-muted px-3 py-2 text-sm">
<div className="text-xs uppercase tracking-wide text-muted-foreground"> <div className="text-xs uppercase tracking-wide text-muted-foreground">
{feedback.category} {feedback.category_label || feedback.category}
</div> </div>
<div className="mt-0.5 whitespace-pre-line">{feedback.message}</div> <div className="mt-0.5 whitespace-pre-line">{feedback.message}</div>
</div> </div>
+38 -120
View File
@@ -3,73 +3,12 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { usePathname, useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
import { import { Menu } from "lucide-react";
ClipboardCheck, import { api, staff, type Me, type StaffMe } from "@/lib/api";
Flag,
ShieldCheck,
Gift,
Megaphone,
Quote,
FolderClosed,
LayoutDashboard,
LayoutGrid,
Link2,
LogOut,
MessageSquare,
Users,
} from "lucide-react";
import { api, staff, MANAGE_STAFF, type Me, type StaffMe } from "@/lib/api";
import { RequirePermission, StaffProvider } from "@/components/staff-context"; import { RequirePermission, StaffProvider } from "@/components/staff-context";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ConfirmProvider } from "@/components/confirm"; import { ConfirmProvider } from "@/components/confirm";
import { NAV, Sidebar } from "./sidebar";
// Each entry names the permission that unlocks it, so the sidebar only shows
// what the signed-in role can actually use.
const NAV = [
{ href: "/", label: "Overview", icon: LayoutDashboard, perm: "stats:read" },
{ href: "/users", label: "Users", icon: Users, perm: "users:read" },
{ href: "/posts", label: "Posts", icon: LayoutGrid, perm: "posts:moderate" },
{
href: "/collections",
label: "Collections",
icon: FolderClosed,
perm: "collections:read",
},
{
href: "/short-urls",
label: "Short URLs",
icon: Link2,
perm: "short_urls:read",
},
{
href: "/feedback",
label: "Feedback",
icon: MessageSquare,
perm: "feedback:read",
},
{ href: "/reports", label: "Reports", icon: Flag, perm: "reports:read" },
{
href: "/broadcasts",
label: "Announcements",
icon: Megaphone,
perm: "broadcasts:read",
},
{ href: "/reward-gifts", label: "Gifts", icon: Gift, perm: "rewards:read" },
{ href: "/vani", label: "Vāṇī of the Day", icon: Quote, perm: "vani:read" },
{
href: "/quizzes",
label: "Quizzes",
icon: ClipboardCheck,
perm: "quizzes:read",
},
{
href: "/staff",
label: "Staff & roles",
icon: ShieldCheck,
perm: MANAGE_STAFF,
},
];
export default function DashboardLayout({ export default function DashboardLayout({
children, children,
@@ -81,6 +20,8 @@ export default function DashboardLayout({
const [me, setMe] = useState<Me | null>(null); const [me, setMe] = useState<Me | null>(null);
const [staffMe, setStaffMe] = useState<StaffMe | null>(null); const [staffMe, setStaffMe] = useState<StaffMe | null>(null);
const [checked, setChecked] = useState(false); const [checked, setChecked] = useState(false);
// Navigation drawer, below lg only.
const [navOpen, setNavOpen] = useState(false);
// Staff gate: only an account holding an admin role, and not blocked from // Staff gate: only an account holding an admin role, and not blocked from
// the panel, may see the dashboard. /admin/me answers both at once — it 403s // the panel, may see the dashboard. /admin/me answers both at once — it 403s
@@ -133,84 +74,61 @@ export default function DashboardLayout({
); );
} }
const section =
NAV.find(
(n) =>
n.href !== "/" &&
(pathname === n.href || pathname.startsWith(n.href + "/")),
) ?? (pathname === "/" ? NAV[0] : undefined);
return ( return (
<div className="flex min-h-screen"> <div className="flex min-h-screen">
<aside className="flex w-60 shrink-0 flex-col border-r border-border bg-card"> <Sidebar
<div className="px-5 py-5"> me={me}
<p className="text-xs uppercase tracking-[0.2em] text-primary"> staffMe={staffMe}
Prabhupāda Says pathname={pathname}
</p> open={navOpen}
<p className="mt-0.5 text-sm font-semibold text-foreground">Admin</p> onClose={() => setNavOpen(false)}
</div> onSignOut={signOut}
<nav className="flex-1 space-y-1 px-3"> />
{NAV.filter((n) => staffMe.permissions.includes(n.perm)).map(
({ href, label, icon: Icon }) => { <div className="flex min-w-0 flex-1 flex-col">
const active = {/* Below lg: a top bar with the menu button and where you are. */}
pathname === href || pathname.startsWith(href + "/"); <header className="sticky top-0 z-30 flex items-center gap-2 border-b border-border bg-card/95 px-2 py-2 backdrop-blur lg:hidden">
return (
<Link
key={href}
href={href}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors",
active
? "bg-accent text-accent-foreground font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Icon className="size-4" />
{label}
</Link>
);
},
)}
</nav>
<div className="border-t border-border px-3 py-3">
<div className="px-3 pb-2 text-xs text-muted-foreground">
<p className="truncate font-medium text-foreground">{me.name}</p>
<p className="truncate">@{me.handle}</p>
<p className="mt-1 inline-block rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{staffMe.role_name}
</p>
</div>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={signOut} onClick={() => setNavOpen(true)}
className="w-full justify-start text-muted-foreground" aria-label="Open menu"
className="size-10 px-0"
> >
<LogOut className="size-4" /> <Menu className="size-5" />
Sign out
</Button> </Button>
</div> <p className="min-w-0 truncate text-sm font-semibold text-foreground">
</aside> {section?.label ?? "Admin"}
</p>
</header>
<main className="flex-1 overflow-x-hidden px-6 py-6 lg:px-10"> {/* break-words: a safety net so no unbroken string (a URL, a long
handle) can push a page sideways. Labels use <Clamp> on top. */}
<main className="min-w-0 flex-1 break-words px-4 py-5 sm:px-6 sm:py-6 lg:px-10">
<div className="mx-auto max-w-6xl"> <div className="mx-auto max-w-6xl">
<StaffProvider value={staffMe}> <StaffProvider value={staffMe}>
<ConfirmProvider> <ConfirmProvider>
{/* The section's own permission, so a URL typed straight in {/* The section's own permission, so a URL typed straight in
explains itself instead of failing call by call. */} explains itself instead of failing call by call. */}
{(() => { {section ? (
const section =
NAV.find(
(n) =>
n.href !== "/" &&
(pathname === n.href ||
pathname.startsWith(n.href + "/")),
) ?? (pathname === "/" ? NAV[0] : undefined);
return section ? (
<RequirePermission perm={section.perm}> <RequirePermission perm={section.perm}>
{children} {children}
</RequirePermission> </RequirePermission>
) : ( ) : (
children children
); )}
})()}
</ConfirmProvider> </ConfirmProvider>
</StaffProvider> </StaffProvider>
</div> </div>
</main> </main>
</div> </div>
</div>
); );
} }
+14 -9
View File
@@ -9,6 +9,7 @@ import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useConfirm } from "@/components/confirm"; import { useConfirm } from "@/components/confirm";
import { fmtDate } from "@/lib/utils"; import { fmtDate } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
export default function PostsPage() { export default function PostsPage() {
const [q, setQ] = useState(""); const [q, setQ] = useState("");
@@ -67,25 +68,29 @@ export default function PostsPage() {
list.items.map((p) => ( list.items.map((p) => (
<TR key={p.id} className={p.deleted_at ? "opacity-60" : ""}> <TR key={p.id} className={p.deleted_at ? "opacity-60" : ""}>
<TD className="max-w-md"> <TD className="max-w-md">
<div className="line-clamp-2">{p.caption || "—"}</div> <Clamp lines={2}>{p.caption || "—"}</Clamp>
<div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"> <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{p.source_title ? (
<Clamp lines={2} className="max-w-full">
{p.source_title} {p.source_title}
</Clamp>
) : null}
{p.deleted_at ? ( {p.deleted_at ? (
<span className="rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive"> <span className="rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive whitespace-nowrap">
Deleted Deleted
</span> </span>
) : p.is_hidden ? ( ) : p.is_hidden ? (
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide"> <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide whitespace-nowrap">
Hidden Hidden
</span> </span>
) : null} ) : null}
</div> </div>
</TD> </TD>
<TD className="whitespace-nowrap"> <TD className="max-w-[14rem]">
<div className="font-medium">{p.author_name}</div> <Clamp className="font-medium">{p.author_name}</Clamp>
<div className="text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
@{p.author_handle} {`@${p.author_handle}`}
</div> </Clamp>
</TD> </TD>
<TD className="whitespace-nowrap text-xs text-muted-foreground"> <TD className="whitespace-nowrap text-xs text-muted-foreground">
{p.likes_count} likes · {p.comments_count} comments {p.likes_count} likes · {p.comments_count} comments
+12 -5
View File
@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";
import { QuizEditor } from "../quiz-editor"; import { QuizEditor } from "../quiz-editor";
import { KIND_LABEL } from "../labels"; import { KIND_LABEL } from "../labels";
import { Participants, Responses } from "./results"; import { Participants, Responses } from "./results";
import { Clamp } from "@/components/ui/clamp";
type Tab = "edit" | "participants" | "responses"; type Tab = "edit" | "participants" | "responses";
@@ -105,7 +106,7 @@ export default function QuizDetailPage() {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<header className="flex flex-wrap items-start justify-between gap-4"> <header className="flex flex-wrap items-start justify-between gap-4">
<div> <div className="min-w-0 flex-1 basis-64">
<Link <Link
href="/quizzes" href="/quizzes"
className="text-xs text-muted-foreground hover:text-foreground" className="text-xs text-muted-foreground hover:text-foreground"
@@ -113,9 +114,15 @@ export default function QuizDetailPage() {
← Quizzes ← Quizzes
</Link> </Link>
<h1 className="mt-1 text-xl font-semibold text-foreground"> <h1 className="mt-1 text-xl font-semibold text-foreground">
{quiz.title} <Clamp lines={2}>{quiz.title}</Clamp>
</h1> </h1>
<p className="mt-1 text-sm text-muted-foreground"> <Clamp
lines={2}
className="mt-1 text-sm text-muted-foreground"
title={[quiz.target_title, quiz.target_path]
.filter(Boolean)
.join(" — ")}
>
{KIND_LABEL[quiz.target_kind]} {KIND_LABEL[quiz.target_kind]}
{quiz.target_title && ` · ${quiz.target_title}`} {quiz.target_title && ` · ${quiz.target_title}`}
{quiz.target_path && ( {quiz.target_path && (
@@ -123,9 +130,9 @@ export default function QuizDetailPage() {
({quiz.target_path}) ({quiz.target_path})
</span> </span>
)} )}
</p> </Clamp>
</div> </div>
<div className="flex gap-2"> <div className="flex shrink-0 gap-2">
<Can perm="quizzes:write"> <Can perm="quizzes:write">
<Button <Button
variant={quiz.published_at ? "outline" : "primary"} variant={quiz.published_at ? "outline" : "primary"}
+53 -11
View File
@@ -6,6 +6,9 @@
* Response times are measured by the BFF — from the moment a question was * Response times are measured by the BFF — from the moment a question was
* served to the moment its answer arrived — so they can't be massaged by the * served to the moment its answer arrived — so they can't be massaged by the
* browser. They include any time the person spent away from the screen. * browser. They include any time the person spent away from the screen.
*
* Staff with quizzes:reset can delete one person's attempt, which puts the
* quiz back to pending for them so they can take it again.
*/ */
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
@@ -18,11 +21,15 @@ import {
type QuizResult, type QuizResult,
} from "@/lib/api"; } from "@/lib/api";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useConfirm } from "@/components/confirm";
import { Can, useStaff } from "@/components/staff-context";
import { Modal } from "@/components/ui/modal"; import { Modal } from "@/components/ui/modal";
import { Table, THead, TH, TR, TD } from "@/components/ui/table"; import { Table, THead, TH, TR, TD } from "@/components/ui/table";
import { RichText } from "@/lib/rich-text"; import { RichText } from "@/lib/rich-text";
import { cn, fmtDate } from "@/lib/utils"; import { cn, fmtDate } from "@/lib/utils";
import { fmtMs } from "../labels"; import { fmtMs } from "../labels";
import { Clamp } from "@/components/ui/clamp";
const errMsg = (err: unknown, fallback: string) => const errMsg = (err: unknown, fallback: string) =>
err instanceof AdminError ? err.message : fallback; err instanceof AdminError ? err.message : fallback;
@@ -31,6 +38,30 @@ export function Participants({ quizId }: { quizId: string }) {
const [rows, setRows] = useState<QuizParticipant[] | null>(null); const [rows, setRows] = useState<QuizParticipant[] | null>(null);
const [open, setOpen] = useState<QuizParticipant | null>(null); const [open, setOpen] = useState<QuizParticipant | null>(null);
const [detail, setDetail] = useState<QuizResult | null>(null); const [detail, setDetail] = useState<QuizResult | null>(null);
const [resetting, setResetting] = useState<string | null>(null);
const confirm = useConfirm();
const { can } = useStaff();
const reset = async (p: QuizParticipant) => {
const ok = await confirm({
title: `Reset ${p.name}'s attempt?`,
message:
"Their answers and score are deleted and the quiz becomes pending for them, so they can take it again. This can't be undone.",
confirmLabel: "Reset attempt",
destructive: true,
});
if (!ok) return;
setResetting(p.user_id);
try {
await quizzes.resetParticipant(quizId, p.user_id);
setRows((rs) => rs?.filter((r) => r.user_id !== p.user_id) ?? rs);
toast.success(`${p.name}'s attempt was reset`);
} catch (err) {
toast.error(errMsg(err, "Could not reset the attempt"));
} finally {
setResetting(null);
}
};
useEffect(() => { useEffect(() => {
quizzes quizzes
@@ -70,6 +101,7 @@ export function Participants({ quizId }: { quizId: string }) {
<TH>Progress</TH> <TH>Progress</TH>
<TH>Time</TH> <TH>Time</TH>
<TH>Started</TH> <TH>Started</TH>
{can("quizzes:reset") && <TH className="text-right">Actions</TH>}
</TR> </TR>
</THead> </THead>
<tbody> <tbody>
@@ -79,7 +111,7 @@ export function Participants({ quizId }: { quizId: string }) {
<button <button
type="button" type="button"
onClick={() => view(p)} onClick={() => view(p)}
className="flex items-center gap-3 text-left hover:underline" className="flex min-w-0 max-w-full items-center gap-3 text-left hover:underline"
> >
<Avatar <Avatar
src={p.avatar_url ?? null} src={p.avatar_url ?? null}
@@ -87,12 +119,10 @@ export function Participants({ quizId }: { quizId: string }) {
className="size-8" className="size-8"
/> />
<span className="min-w-0"> <span className="min-w-0">
<span className="block truncate text-sm font-medium"> <Clamp className="text-sm font-medium">{p.name}</Clamp>
{p.name} <Clamp className="text-xs text-muted-foreground">
</span> {`@${p.handle}`}
<span className="block truncate text-xs text-muted-foreground"> </Clamp>
@{p.handle}
</span>
</span> </span>
</button> </button>
</TD> </TD>
@@ -118,6 +148,18 @@ export function Participants({ quizId }: { quizId: string }) {
<TD className="text-xs text-muted-foreground"> <TD className="text-xs text-muted-foreground">
{fmtDate(p.started_at)} {fmtDate(p.started_at)}
</TD> </TD>
<Can perm="quizzes:reset">
<TD className="text-right">
<Button
size="sm"
variant="ghost"
disabled={resetting === p.user_id}
onClick={() => void reset(p)}
>
{resetting === p.user_id ? "Resetting…" : "Reset"}
</Button>
</TD>
</Can>
</TR> </TR>
))} ))}
</tbody> </tbody>
@@ -131,7 +173,7 @@ export function Participants({ quizId }: { quizId: string }) {
{!detail ? ( {!detail ? (
<p className="text-sm text-muted-foreground">Loading…</p> <p className="text-sm text-muted-foreground">Loading…</p>
) : ( ) : (
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-1"> <div className="space-y-4">
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{detail.completed_at {detail.completed_at
? `Scored ${detail.score} of ${detail.total}` ? `Scored ${detail.score} of ${detail.total}`
@@ -141,7 +183,7 @@ export function Participants({ quizId }: { quizId: string }) {
{detail.items.map((it, i) => ( {detail.items.map((it, i) => (
<div key={it.id ?? i} className="space-y-1.5"> <div key={it.id ?? i} className="space-y-1.5">
<div className="flex items-start justify-between gap-3 text-sm"> <div className="flex items-start justify-between gap-3 text-sm">
<p className="font-medium"> <p className="min-w-0 font-medium">
{i + 1}. <RichText text={it.prompt} /> {i + 1}. <RichText text={it.prompt} />
</p> </p>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground"> <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
@@ -208,10 +250,10 @@ export function Responses({ quizId }: { quizId: string }) {
return ( return (
<li key={q.id} className="rounded-xl border border-border p-4"> <li key={q.id} className="rounded-xl border border-border p-4">
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4">
<p className="text-sm font-medium"> <p className="min-w-0 text-sm font-medium">
{i + 1}. <RichText text={q.prompt} /> {i + 1}. <RichText text={q.prompt} />
{q.multi && ( {q.multi && (
<span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground"> <span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground whitespace-nowrap">
Multiple answers Multiple answers
</span> </span>
)} )}
+16 -4
View File
@@ -7,11 +7,23 @@ export const KIND_LABEL: Record<Quiz["target_kind"], string> = {
standalone: "Stand-alone", standalone: "Stand-alone",
}; };
/** "1m 12s" / "8.4s" — response times read better than raw milliseconds. */ /**
* "8.4s" / "1m 12s" / "3h 20m" / "2d 4h" — response times read better than
* raw milliseconds. Hours past 23h 59m roll up into days. Mirrors fmtMs in
* the app's quiz-result-view.tsx.
*/
export function fmtMs(ms: number | null | undefined): string { export function fmtMs(ms: number | null | undefined): string {
if (ms == null) return "—"; if (ms == null) return "—";
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`; // Below 59.95s: one decimal place (anything higher would print "60.0s").
const m = Math.floor(ms / 60_000); if (ms < 59_950) return `${(ms / 1000).toFixed(1)}s`;
const s = Math.round((ms % 60_000) / 1000); // Whole seconds from here, so rounding can't print "1m 60s".
const total = Math.round(ms / 1000);
const d = Math.floor(total / 86_400);
const h = Math.floor((total % 86_400) / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
// The two largest units: 2d 4h · 3h 20m · 12m 5s.
if (d > 0) return `${d}d ${h}h`;
if (h > 0) return `${h}h ${m}m`;
return `${m}m ${s}s`; return `${m}m ${s}s`;
} }
+9 -8
View File
@@ -13,6 +13,7 @@ import { Table, THead, TH, TR, TD } from "@/components/ui/table";
import { Can } from "@/components/staff-context"; import { Can } from "@/components/staff-context";
import { fmtDate } from "@/lib/utils"; import { fmtDate } from "@/lib/utils";
import { KIND_LABEL } from "./labels"; import { KIND_LABEL } from "./labels";
import { Clamp } from "@/components/ui/clamp";
export default function QuizzesPage() { export default function QuizzesPage() {
const [list, setList] = useState<Quiz[] | null>(null); const [list, setList] = useState<Quiz[] | null>(null);
@@ -41,8 +42,8 @@ export default function QuizzesPage() {
</p> </p>
</div> </div>
<Can perm="quizzes:write"> <Can perm="quizzes:write">
<Link href="/quizzes/new"> <Link href="/quizzes/new" className="shrink-0">
<Button>New quiz</Button> <Button className="whitespace-nowrap">New quiz</Button>
</Link> </Link>
</Can> </Can>
</header> </header>
@@ -68,9 +69,9 @@ export default function QuizzesPage() {
<TD> <TD>
<Link <Link
href={`/quizzes/${q.id}`} href={`/quizzes/${q.id}`}
className="font-medium text-foreground hover:underline" className="block font-medium text-foreground hover:underline"
> >
{q.title} <Clamp lines={2}>{q.title}</Clamp>
</Link> </Link>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Updated {fmtDate(q.updated_at)} Updated {fmtDate(q.updated_at)}
@@ -79,13 +80,13 @@ export default function QuizzesPage() {
<TD> <TD>
<p className="text-sm">{KIND_LABEL[q.target_kind]}</p> <p className="text-sm">{KIND_LABEL[q.target_kind]}</p>
{q.target_title && ( {q.target_title && (
<p className="truncate text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
{q.target_title} {q.target_title}
</p> </Clamp>
)} )}
</TD> </TD>
<TD>{q.question_count}</TD> <TD>{q.question_count}</TD>
<TD> <TD className="[overflow-wrap:normal]">
{q.completed_count ?? 0} finished {q.completed_count ?? 0} finished
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{" "} {" "}
@@ -94,7 +95,7 @@ export default function QuizzesPage() {
</TD> </TD>
<TD> <TD>
{q.published_at ? ( {q.published_at ? (
<span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary"> <span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary whitespace-nowrap">
Published Published
</span> </span>
) : ( ) : (
+4 -3
View File
@@ -191,6 +191,7 @@ export function QuizEditor({
<p className="mt-1 text-xs text-muted-foreground"> <p className="mt-1 text-xs text-muted-foreground">
Paste the page&apos;s link, e.g. /books/bg/2 or Paste the page&apos;s link, e.g. /books/bg/2 or
/transcriptions/720720sb-london. Leave empty for a stand-alone /transcriptions/720720sb-london. Leave empty for a stand-alone
quiz. Each chapter, lecture or conversation can have only one
quiz. quiz.
</p> </p>
</div> </div>
@@ -298,7 +299,7 @@ export function QuizEditor({
maxLength={2000} maxLength={2000}
placeholder="Question" placeholder="Question"
/> />
<label className="flex w-fit items-center gap-2 text-sm text-foreground"> <label className="flex w-fit flex-wrap items-center gap-x-2 gap-y-0.5 text-sm text-foreground">
<input <input
type="checkbox" type="checkbox"
checked={q.multi} checked={q.multi}
@@ -306,8 +307,8 @@ export function QuizEditor({
className="accent-primary" className="accent-primary"
/> />
Multiple correct answers Multiple correct answers
<span className="text-xs text-muted-foreground"> <span className="basis-full pl-6 text-xs text-muted-foreground sm:basis-auto sm:pl-0">
— users select all that apply Users select all that apply
</span> </span>
</label> </label>
<fieldset className="space-y-2"> <fieldset className="space-y-2">
+13 -10
View File
@@ -13,6 +13,7 @@ import { RichTextarea } from "@/components/ui/rich-textarea";
import { RichText } from "@/lib/rich-text"; import { RichText } from "@/lib/rich-text";
import { useConfirm } from "@/components/confirm"; import { useConfirm } from "@/components/confirm";
import { cn, fmtDate } from "@/lib/utils"; import { cn, fmtDate } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
const TYPES: { key: ReportType; label: string }[] = [ const TYPES: { key: ReportType; label: string }[] = [
{ key: "post", label: "Posts" }, { key: "post", label: "Posts" },
@@ -195,18 +196,16 @@ export default function ReportsPage() {
<TR key={r.id} className={resolved ? "opacity-70" : ""}> <TR key={r.id} className={resolved ? "opacity-70" : ""}>
<TD className="max-w-xs align-top"> <TD className="max-w-xs align-top">
{type === "user" ? ( {type === "user" ? (
<span className="font-medium"> <Clamp className="font-medium">
{r.target_text ? `@${r.target_text}` : "—"} {r.target_text ? `@${r.target_text}` : "—"}
</span> </Clamp>
) : ( ) : (
<> <>
<div className="line-clamp-2"> <Clamp lines={2}>{r.target_text || "—"}</Clamp>
{r.target_text || "—"}
</div>
{r.target_author_handle ? ( {r.target_author_handle ? (
<div className="mt-0.5 text-xs text-muted-foreground"> <Clamp className="mt-0.5 text-xs text-muted-foreground">
by @{r.target_author_handle} {`by @${r.target_author_handle}`}
</div> </Clamp>
) : null} ) : null}
</> </>
)} )}
@@ -221,11 +220,15 @@ export default function ReportsPage() {
{r.category} {r.category}
</div> </div>
{r.reason ? ( {r.reason ? (
<div className="mt-0.5 line-clamp-2">{r.reason}</div> <Clamp lines={2} className="mt-0.5">
{r.reason}
</Clamp>
) : null} ) : null}
</TD> </TD>
<TD className="whitespace-nowrap align-top text-xs text-muted-foreground"> <TD className="max-w-[12rem] align-top text-xs text-muted-foreground">
<Clamp>
{r.reporter_handle ? `@${r.reporter_handle}` : "—"} {r.reporter_handle ? `@${r.reporter_handle}` : "—"}
</Clamp>
</TD> </TD>
<TD className="whitespace-nowrap align-top"> <TD className="whitespace-nowrap align-top">
{fmtDate(r.created_at)} {fmtDate(r.created_at)}
+3 -2
View File
@@ -17,6 +17,7 @@ import Image from "next/image";
import { toast } from "sonner"; import { toast } from "sonner";
import { rewardGifts, type GiftableReward } from "@/lib/api"; import { rewardGifts, type GiftableReward } from "@/lib/api";
import { compressImage } from "@/lib/compress-image"; import { compressImage } from "@/lib/compress-image";
import { Clamp } from "@/components/ui/clamp";
export default function RewardGiftsPage() { export default function RewardGiftsPage() {
const [catalog, setCatalog] = useState<GiftableReward[] | null>(null); const [catalog, setCatalog] = useState<GiftableReward[] | null>(null);
@@ -123,9 +124,9 @@ export default function RewardGiftsPage() {
unoptimized unoptimized
/> />
</div> </div>
<p className="line-clamp-2 text-sm font-medium text-foreground"> <Clamp lines={2} className="w-full text-sm font-medium text-foreground">
{r.name} {r.name}
</p> </Clamp>
<div className="mt-auto w-full space-y-1.5"> <div className="mt-auto w-full space-y-1.5">
<Can perm="rewards:send"> <Can perm="rewards:send">
<button <button
+3 -3
View File
@@ -6,6 +6,7 @@ import { usePagedList } from "@/lib/use-paged-list";
import { ListShell, EmptyRow } from "@/components/list-shell"; import { ListShell, EmptyRow } from "@/components/list-shell";
import { Table, THead, TR, TH, TD } from "@/components/ui/table"; import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { fmtDate } from "@/lib/utils"; import { fmtDate } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
export default function ShortUrlsPage() { export default function ShortUrlsPage() {
// ── Stats ──────────────────────────────────────────────────────────────── // ── Stats ────────────────────────────────────────────────────────────────
@@ -137,10 +138,9 @@ export default function ShortUrlsPage() {
href={s.long_url} href={s.long_url}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="line-clamp-1 break-all text-primary hover:underline" className="block text-primary hover:underline"
title={s.long_url}
> >
{s.long_url} <Clamp>{s.long_url}</Clamp>
</a> </a>
</TD> </TD>
<TD className="whitespace-nowrap text-muted-foreground"> <TD className="whitespace-nowrap text-muted-foreground">
+194
View File
@@ -0,0 +1,194 @@
"use client";
/**
* The dashboard's navigation.
*
* From lg up it's a fixed column beside the page. Below that it's a drawer
* that slides in from the left, opened from the top bar's menu button, so
* phones get the full width for the page itself.
*/
import { useEffect } from "react";
import Link from "next/link";
import {
ClipboardCheck,
Flag,
ShieldCheck,
Gift,
Megaphone,
Quote,
FolderClosed,
LayoutDashboard,
LayoutGrid,
Link2,
LogOut,
MessageSquare,
Users,
X,
} from "lucide-react";
import { MANAGE_STAFF, type Me, type StaffMe } from "@/lib/api";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
// Each entry names the permission that unlocks it, so the sidebar only shows
// what the signed-in role can actually use.
export const NAV = [
{ href: "/", label: "Overview", icon: LayoutDashboard, perm: "stats:read" },
{ href: "/users", label: "Users", icon: Users, perm: "users:read" },
{ href: "/posts", label: "Posts", icon: LayoutGrid, perm: "posts:moderate" },
{
href: "/collections",
label: "Collections",
icon: FolderClosed,
perm: "collections:read",
},
{
href: "/short-urls",
label: "Short URLs",
icon: Link2,
perm: "short_urls:read",
},
{
href: "/feedback",
label: "Feedback",
icon: MessageSquare,
perm: "feedback:read",
},
{ href: "/reports", label: "Reports", icon: Flag, perm: "reports:read" },
{
href: "/broadcasts",
label: "Announcements",
icon: Megaphone,
perm: "broadcasts:read",
},
{ href: "/reward-gifts", label: "Gifts", icon: Gift, perm: "rewards:read" },
{ href: "/vani", label: "Vāṇī of the Day", icon: Quote, perm: "vani:read" },
{
href: "/quizzes",
label: "Quizzes",
icon: ClipboardCheck,
perm: "quizzes:read",
},
{
href: "/staff",
label: "Staff & roles",
icon: ShieldCheck,
perm: MANAGE_STAFF,
},
];
export function Sidebar({
me,
staffMe,
pathname,
open,
onClose,
onSignOut,
}: {
me: Me;
staffMe: StaffMe;
pathname: string;
/** Drawer state below lg; ignored from lg up, where it's always shown. */
open: boolean;
onClose: () => void;
onSignOut: () => void;
}) {
// While the drawer is open: Escape closes it and the page behind it
// doesn't scroll.
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
document.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [open, onClose]);
return (
<>
{/* Backdrop — drawer only. */}
<div
aria-hidden
onClick={onClose}
className={cn(
"fixed inset-0 z-40 bg-black/40 transition-opacity lg:hidden",
open ? "opacity-100" : "pointer-events-none opacity-0",
)}
/>
<aside
className={cn(
"fixed inset-y-0 left-0 z-50 flex w-72 max-w-[85vw] flex-col border-r border-border bg-card transition-transform duration-200",
open ? "translate-x-0 shadow-xl" : "-translate-x-full",
// lg+: an ordinary column in the page flow.
"lg:sticky lg:top-0 lg:z-auto lg:h-screen lg:w-60 lg:translate-x-0 lg:shadow-none",
)}
>
<div className="flex items-start justify-between px-5 py-5">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-primary">
Prabhupāda Says
</p>
<p className="mt-0.5 text-sm font-semibold text-foreground">
Admin
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={onClose}
aria-label="Close menu"
className="-mr-2 size-9 px-0 lg:hidden"
>
<X className="size-5" />
</Button>
</div>
<nav className="flex-1 space-y-1 overflow-y-auto px-3">
{NAV.filter((n) => staffMe.permissions.includes(n.perm)).map(
({ href, label, icon: Icon }) => {
const active =
pathname === href || pathname.startsWith(href + "/");
return (
<Link
key={href}
href={href}
// Picking a section closes the drawer on small screens.
onClick={onClose}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors lg:py-2",
active
? "bg-accent text-accent-foreground font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Icon className="size-4" />
{label}
</Link>
);
},
)}
</nav>
<div className="border-t border-border px-3 py-3">
<div className="px-3 pb-2 text-xs text-muted-foreground">
<p className="truncate font-medium text-foreground">{me.name}</p>
<p className="truncate">@{me.handle}</p>
<p className="mt-1 inline-block rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground whitespace-nowrap">
{staffMe.role_name}
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={onSignOut}
className="w-full justify-start text-muted-foreground"
>
<LogOut className="size-4" />
Sign out
</Button>
</div>
</aside>
</>
);
}
+9 -6
View File
@@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal"; import { Modal } from "@/components/ui/modal";
import { useConfirm } from "@/components/confirm"; import { useConfirm } from "@/components/confirm";
import { Clamp } from "@/components/ui/clamp";
const errMsg = (err: unknown, fallback: string) => const errMsg = (err: unknown, fallback: string) =>
err instanceof AdminError ? err.message : fallback; err instanceof AdminError ? err.message : fallback;
@@ -129,18 +130,20 @@ export function RolesTab() {
<li key={r.id} className="rounded-xl border border-border p-4"> <li key={r.id} className="rounded-xl border border-border p-4">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
<p className="text-sm font-medium text-foreground"> <div className="flex min-w-0 items-center gap-2">
{r.name}{" "} <Clamp className="text-sm font-medium text-foreground">
{r.name}
</Clamp>
{r.is_system && ( {r.is_system && (
<span className="ml-1 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground"> <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground whitespace-nowrap">
System System
</span> </span>
)} )}
</p> </div>
{r.description && ( {r.description && (
<p className="mt-0.5 text-xs text-muted-foreground"> <Clamp lines={2} className="mt-0.5 text-xs text-muted-foreground">
{r.description} {r.description}
</p> </Clamp>
)} )}
<p className="mt-1 text-xs text-muted-foreground"> <p className="mt-1 text-xs text-muted-foreground">
{r.member_count} {r.member_count === 1 ? "member" : "members"} {r.member_count} {r.member_count === 1 ? "member" : "members"}
+16 -10
View File
@@ -14,6 +14,7 @@ import { Input } from "@/components/ui/input";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Table, THead, TH, TR, TD } from "@/components/ui/table"; import { Table, THead, TH, TR, TD } from "@/components/ui/table";
import { useConfirm } from "@/components/confirm"; import { useConfirm } from "@/components/confirm";
import { Clamp } from "@/components/ui/clamp";
const errMsg = (err: unknown, fallback: string) => const errMsg = (err: unknown, fallback: string) =>
err instanceof AdminError ? err.message : fallback; err instanceof AdminError ? err.message : fallback;
@@ -132,7 +133,9 @@ export function StaffTab() {
<select <select
value={grantRole} value={grantRole}
onChange={(e) => setGrantRole(e.target.value)} onChange={(e) => setGrantRole(e.target.value)}
className="h-10 rounded-lg border border-input bg-card px-3 text-sm" // A <select> sizes itself to its longest option; a long custom
// role name must not widen the form past the screen.
className="h-10 min-w-0 max-w-full flex-1 truncate rounded-lg border border-input bg-card px-3 text-sm sm:max-w-xs sm:flex-none"
> >
{roles.map((r) => ( {roles.map((r) => (
<option key={r.id} value={r.id}> <option key={r.id} value={r.id}>
@@ -164,22 +167,25 @@ export function StaffTab() {
return ( return (
<TR key={m.user_id}> <TR key={m.user_id}>
<TD> <TD>
<div className="flex items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
<Avatar <Avatar
src={m.avatar_url ?? null} src={m.avatar_url ?? null}
name={m.name} name={m.name}
className="size-8" className="size-8"
/> />
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate text-sm font-medium text-foreground"> <Clamp
className="text-sm font-medium text-foreground"
title={m.name}
>
{m.name}{" "} {m.name}{" "}
{self && ( {self && (
<span className="text-muted-foreground">(you)</span> <span className="text-muted-foreground">(you)</span>
)} )}
</p> </Clamp>
<p className="truncate text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
@{m.handle} {`@${m.handle}`}
</p> </Clamp>
</div> </div>
</div> </div>
</TD> </TD>
@@ -188,7 +194,7 @@ export function StaffTab() {
access, so a superadmin can't demote themselves into access, so a superadmin can't demote themselves into
a locked-out panel by accident. */} a locked-out panel by accident. */}
{self ? ( {self ? (
<span className="text-sm">{m.role_name}</span> <Clamp className="text-sm">{m.role_name}</Clamp>
) : ( ) : (
<select <select
value={m.role_id} value={m.role_id}
@@ -200,7 +206,7 @@ export function StaffTab() {
"Role changed", "Role changed",
) )
} }
className="h-8 rounded-md border border-input bg-card px-2 text-xs" className="h-8 w-full max-w-[14rem] truncate rounded-md border border-input bg-card px-2 text-xs"
> >
{roles.map((r) => ( {roles.map((r) => (
<option key={r.id} value={r.id}> <option key={r.id} value={r.id}>
@@ -212,7 +218,7 @@ export function StaffTab() {
</TD> </TD>
<TD> <TD>
{m.blocked_at ? ( {m.blocked_at ? (
<span className="rounded bg-destructive/10 px-2 py-0.5 text-xs text-destructive"> <span className="rounded bg-destructive/10 px-2 py-0.5 text-xs text-destructive whitespace-nowrap">
Blocked Blocked
</span> </span>
) : ( ) : (
+10 -6
View File
@@ -21,6 +21,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal"; import { Modal } from "@/components/ui/modal";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Clamp } from "@/components/ui/clamp";
/** "Vṛndāvana · 1972" — whichever halves we know. */ /** "Vṛndāvana · 1972" — whichever halves we know. */
function placeYear(d: AdminDisciple): string | null { function placeYear(d: AdminDisciple): string | null {
@@ -138,13 +139,13 @@ export function DiscipleLinkModal({
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
Currently linked to Currently linked to
</div> </div>
<div className="truncate text-sm font-medium"> <Clamp className="text-sm font-medium">
{user.disciple_name ?? ( {user.disciple_name ?? (
<span className="text-muted-foreground"> <span className="text-muted-foreground">
unknown disciple ({user.disciple_id.slice(0, 8)}…) unknown disciple ({user.disciple_id.slice(0, 8)}…)
</span> </span>
)} )}
</div> </Clamp>
</div> </div>
<Button <Button
variant="outline" variant="outline"
@@ -200,16 +201,19 @@ export function DiscipleLinkModal({
)} )}
> >
<span className="min-w-0"> <span className="min-w-0">
<span className="block truncate text-sm font-medium"> <Clamp
className="text-sm font-medium"
title={`${d.initiated_name} ${d.suffix ?? ""}`.trim()}
>
{d.initiated_name}{" "} {d.initiated_name}{" "}
<span className="font-normal text-muted-foreground"> <span className="font-normal text-muted-foreground">
{d.suffix} {d.suffix}
</span> </span>
</span> </Clamp>
{sub ? ( {sub ? (
<span className="block truncate text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
{sub} {sub}
</span> </Clamp>
) : null} ) : null}
</span> </span>
<span className="shrink-0 text-xs"> <span className="shrink-0 text-xs">
+12 -13
View File
@@ -23,6 +23,7 @@ import { RichTextarea } from "@/components/ui/rich-textarea";
import { fmtDate } from "@/lib/utils"; import { fmtDate } from "@/lib/utils";
import { DiscipleLinkModal } from "./disciple-link-modal"; import { DiscipleLinkModal } from "./disciple-link-modal";
import { useStaff } from "@/components/staff-context"; import { useStaff } from "@/components/staff-context";
import { Clamp } from "@/components/ui/clamp";
export default function UsersPage() { export default function UsersPage() {
const { can } = useStaff(); const { can } = useStaff();
@@ -138,20 +139,20 @@ export default function UsersPage() {
list.items.map((u) => ( list.items.map((u) => (
<TR key={u.id}> <TR key={u.id}>
<TD> <TD>
<div className="flex items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
<Avatar src={u.avatar_url} name={u.name} /> <Avatar src={u.avatar_url} name={u.name} />
<div className="min-w-0"> <div className="min-w-0">
<div className="flex items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<span className="font-medium">{u.name}</span> <Clamp className="font-medium">{u.name}</Clamp>
{u.banned_at ? ( {u.banned_at ? (
<span className="rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive"> <span className="shrink-0 rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive whitespace-nowrap">
Suspended Suspended
</span> </span>
) : null} ) : null}
</div> </div>
<div className="text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
@{u.handle} {`@${u.handle}`}
</div> </Clamp>
{u.disciple_id ? ( {u.disciple_id ? (
<div <div
className="mt-1 inline-flex max-w-full items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary" className="mt-1 inline-flex max-w-full items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary"
@@ -161,9 +162,7 @@ export default function UsersPage() {
: "Linked to an unknown disciple record" : "Linked to an unknown disciple record"
} }
> >
<span className="truncate"> <Clamp>{u.disciple_name ?? "Direct disciple"}</Clamp>
{u.disciple_name ?? "Direct disciple"}
</span>
</div> </div>
) : null} ) : null}
</div> </div>
@@ -171,11 +170,11 @@ export default function UsersPage() {
</TD> </TD>
<TD> <TD>
<div className="space-y-1.5"> <div className="space-y-1.5">
<div> {u.email ? (
{u.email ?? ( <Clamp>{u.email}</Clamp>
) : (
<span className="text-muted-foreground">—</span> <span className="text-muted-foreground">—</span>
)} )}
</div>
<AuthIcons user={u} /> <AuthIcons user={u} />
</div> </div>
</TD> </TD>
+17 -19
View File
@@ -22,6 +22,7 @@ import {
type VaniCandidate, type VaniCandidate,
type VaniPick, type VaniPick,
} from "@/lib/api"; } from "@/lib/api";
import { Clamp } from "@/components/ui/clamp";
/** Today in UTC — picks are keyed on a UTC calendar day. */ /** Today in UTC — picks are keyed on a UTC calendar day. */
function todayUTC(): string { function todayUTC(): string {
@@ -145,19 +146,19 @@ export default function VaniPage() {
<Can perm="vani:write"> <Can perm="vani:write">
<section className="space-y-3 rounded-xl border border-border p-4"> <section className="space-y-3 rounded-xl border border-border p-4">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<input <input
value={link} value={link}
onChange={(e) => setLink(e.target.value)} onChange={(e) => setLink(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && void pinByLink()} onKeyDown={(e) => e.key === "Enter" && void pinByLink()}
placeholder="Paste a link — /transcriptions/720720sb-london" placeholder="Paste a link — /transcriptions/720720sb-london"
className={`${field} min-w-0 flex-1`} className={`${field} w-full min-w-0 sm:flex-1`}
/> />
<button <button
type="button" type="button"
disabled={busy || !link.trim()} disabled={busy || !link.trim()}
onClick={pinByLink} onClick={pinByLink}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50" className="shrink-0 whitespace-nowrap rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
> >
Use this link Use this link
</button> </button>
@@ -167,22 +168,22 @@ export default function VaniPage() {
link when you know exactly which item you want. link when you know exactly which item you want.
</p> </p>
<div className="flex flex-wrap items-center gap-3 border-t border-border pt-3"> <div className="flex flex-col gap-3 border-t border-border pt-3 sm:flex-row sm:items-center">
<label className="text-sm text-muted-foreground"> <label className="flex items-center text-sm text-muted-foreground">
Date Date
<input <input
type="date" type="date"
value={day} value={day}
min={todayUTC()} min={todayUTC()}
onChange={(e) => setDay(e.target.value)} onChange={(e) => setDay(e.target.value)}
className={`${field} ml-2`} className={`${field} ml-2 min-w-0 flex-1 sm:flex-none`}
/> />
</label> </label>
<input <input
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
placeholder="Search verses, chapters and lectures" placeholder="Search verses, chapters and lectures"
className={`${field} min-w-0 flex-1`} className={`${field} w-full min-w-0 sm:flex-1`}
/> />
</div> </div>
@@ -200,12 +201,10 @@ export default function VaniPage() {
className="flex items-center gap-3 px-3 py-2.5" className="flex items-center gap-3 px-3 py-2.5"
> >
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground"> <Clamp className="text-sm text-foreground">{c.title}</Clamp>
{c.title} <Clamp className="text-xs text-muted-foreground">
</p> {`${vaniKindFor(c.collection)} · ${c.snippet}`}
<p className="truncate text-xs text-muted-foreground"> </Clamp>
{vaniKindFor(c.collection)} · {c.snippet}
</p>
</div> </div>
<button <button
type="button" type="button"
@@ -240,13 +239,12 @@ export default function VaniPage() {
{p.day} {p.day}
</span> </span>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground"> <Clamp className="text-sm text-foreground">
{p.payload.title} {p.payload.title}
</p> </Clamp>
<p className="truncate text-xs text-muted-foreground"> <Clamp className="text-xs text-muted-foreground">
{p.payload.label} {`${p.payload.label}${p.payload.book_title ? ` · ${p.payload.book_title}` : ""}`}
{p.payload.book_title ? ` · ${p.payload.book_title}` : ""} </Clamp>
</p>
</div> </div>
<Can perm="vani:write"> <Can perm="vani:write">
<button <button
+3 -3
View File
@@ -48,7 +48,7 @@ export function ListShell({
return ( return (
<div className="space-y-5"> <div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-2xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground sm:text-2xl">
{title} {title}
<span className="ml-2 text-sm font-normal text-muted-foreground"> <span className="ml-2 text-sm font-normal text-muted-foreground">
{total.toLocaleString()} {total.toLocaleString()}
@@ -58,7 +58,7 @@ export function ListShell({
</div> </div>
{onQueryChange ? ( {onQueryChange ? (
<div className="relative max-w-md"> <div className="relative w-full sm:max-w-md">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" /> <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input <Input
value={raw} value={raw}
@@ -77,7 +77,7 @@ export function ListShell({
{children} {children}
</div> </div>
<div className="flex items-center justify-between text-sm text-muted-foreground"> <div className="flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground">
<span> <span>
Page {list.page} of {list.totalPages} Page {list.page} of {list.totalPages}
{list.loading ? " · loading…" : ""} {list.loading ? " · loading…" : ""}
+1 -1
View File
@@ -27,7 +27,7 @@ export function Button({
return ( return (
<button <button
className={cn( className={cn(
"inline-flex items-center justify-center gap-2 rounded-lg font-medium transition-colors outline-none", "inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-lg font-medium transition-colors outline-none",
"focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 disabled:pointer-events-none", "focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 disabled:pointer-events-none",
variants[variant], variants[variant],
sizes[size], sizes[size],
+50
View File
@@ -0,0 +1,50 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const LINES = {
1: "line-clamp-1",
2: "line-clamp-2",
3: "line-clamp-3",
} as const;
/**
* Clamp — a dynamic label (a quiz title, a name, an email, a link) cut off
* with "…" after a set number of lines, with the full text on hover.
*
* Use this rather than Tailwind's `truncate` for anything user- or content-
* supplied. `truncate` forbids wrapping, and inside a table cell that makes
* the column grow to the text's full width — the table then overflows its
* card instead of truncating. A line clamp wraps first and cuts after N
* lines, and `overflow-wrap: anywhere` lets even an unbroken string (a URL,
* a handle) break, so it can never widen whatever it sits in.
*/
export function Clamp({
children,
lines = 1,
title,
className,
}: {
children: React.ReactNode;
lines?: keyof typeof LINES;
/** Hover text; defaults to the label itself when it's plain text. */
title?: string;
className?: string;
}) {
const hover =
title ??
(typeof children === "string" || typeof children === "number"
? String(children)
: undefined);
return (
<span
title={hover}
className={cn(
"block min-w-0 [overflow-wrap:anywhere]",
LINES[lines],
className,
)}
>
{children}
</span>
);
}
+21 -1
View File
@@ -10,6 +10,12 @@ export type MenuItem = {
destructive?: boolean; destructive?: boolean;
}; };
// Menu geometry, for keeping it on screen: w-44, rows of py-2 text-sm.
const MENU_WIDTH = 176;
const MENU_ROW = 36;
const MENU_GAP = 8;
/** /**
* A kebab (⋯) trigger with a small dropdown of actions — keeps secondary / * A kebab (⋯) trigger with a small dropdown of actions — keeps secondary /
* destructive row actions hidden until opened. The menu is fixed-positioned * destructive row actions hidden until opened. The menu is fixed-positioned
@@ -50,7 +56,21 @@ export function RowMenu({ items }: { items: MenuItem[] }) {
function toggle() { function toggle() {
if (!open && btnRef.current) { if (!open && btnRef.current) {
const r = btnRef.current.getBoundingClientRect(); const r = btnRef.current.getBoundingClientRect();
setPos({ top: r.bottom + 4, right: window.innerWidth - r.right }); const vw = window.innerWidth;
const vh = window.innerHeight;
// Right-aligned to the button, but kept on screen: on a phone the
// button can sit at the left of a card, where a right-aligned menu
// would hang off the edge. Near the bottom it opens upwards instead.
const right = Math.max(
MENU_GAP,
Math.min(vw - r.right, vw - MENU_WIDTH - MENU_GAP),
);
const height = items.length * MENU_ROW + 8;
const top =
r.bottom + 4 + height > vh - MENU_GAP
? Math.max(MENU_GAP, r.top - 4 - height)
: r.bottom + 4;
setPos({ top, right });
} }
setOpen((v) => !v); setOpen((v) => !v);
} }
+17 -6
View File
@@ -4,7 +4,11 @@ import * as React from "react";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
/** A minimal centered modal dialog. Closes on overlay click and Escape. */ /**
* A minimal modal dialog. Closes on overlay click and Escape. Centred from sm
* up; on a phone it rises from the bottom as a full-width sheet. Either way
* it never outgrows the screen — the body scrolls inside it.
*/
export function Modal({ export function Modal({
open, open,
onClose, onClose,
@@ -29,15 +33,20 @@ export function Modal({
return ( return (
<div <div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 sm:items-center sm:p-4"
onClick={onClose} onClick={onClose}
> >
<div <div
className="w-full max-w-lg rounded-2xl border border-border bg-card shadow-xl" className="flex max-h-[92dvh] w-full max-w-lg flex-col rounded-t-2xl border border-border bg-card shadow-xl sm:max-h-[85dvh] sm:rounded-2xl"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
<div className="flex items-center justify-between border-b border-border px-5 py-4"> <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3.5 sm:px-5 sm:py-4">
<h2 className="text-base font-semibold text-foreground">{title}</h2> <h2
title={title}
className="min-w-0 truncate text-base font-semibold text-foreground"
>
{title}
</h2>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -48,7 +57,9 @@ export function Modal({
<X className="size-4" /> <X className="size-4" />
</Button> </Button>
</div> </div>
<div className="px-5 py-4">{children}</div> <div className="min-h-0 overflow-y-auto [overflow-wrap:anywhere] px-4 py-4 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-5">
{children}
</div>
</div> </div>
</div> </div>
); );
+98 -7
View File
@@ -1,17 +1,74 @@
"use client";
import * as React from "react"; import * as React from "react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export function Table({ children }: { children: React.ReactNode }) { /**
* The panel's data table.
*
* From md up it's an ordinary table. Long values (emails, URLs) may wrap
* anywhere so the columns always fit; if they still can't, the table scrolls
* sideways inside its card as a last resort. Labels inside cells should use
* <Clamp>, never `truncate` (see clamp.tsx for why).
*
* On a phone (below md) each row becomes a stacked card: one line per cell, labelled
* with its column heading. The labels are read from the table's own <th>s
* and stamped onto the cells as `data-label`, so pages need no extra markup
* — every table in the panel gets the card layout for free. Cells under an
* empty heading (an actions column) simply go unlabelled.
*
* `card="stacked"` puts each label above its value instead of beside it, so
* long content (a feedback message) gets the card's full width.
*/
type CardLayout = "inline" | "stacked";
const CardLayoutContext = React.createContext<CardLayout>("inline");
export function Table({
children,
card = "inline",
}: {
children: React.ReactNode;
/** Phone card layout: labels beside values (default) or above them. */
card?: CardLayout;
}) {
const ref = React.useRef<HTMLTableElement>(null);
// Runs after every render: rows arrive and change with the data.
React.useLayoutEffect(() => {
const table = ref.current;
if (!table) return;
const heads = Array.from(table.querySelectorAll("thead th")).map(
(th) => th.textContent?.trim() ?? "",
);
table.querySelectorAll("tbody tr").forEach((tr) => {
let col = 0;
Array.from(tr.children).forEach((cell) => {
const td = cell as HTMLTableCellElement;
const label = td.colSpan > 1 ? "" : (heads[col] ?? "");
if (label) td.dataset.label = label;
else delete td.dataset.label;
col += td.colSpan || 1;
});
});
});
return ( return (
<div className="overflow-x-auto rounded-xl border border-border bg-card"> <CardLayoutContext.Provider value={card}>
<table className="w-full border-collapse text-sm">{children}</table> <div className="rounded-xl border border-border bg-card md:overflow-x-auto md:overscroll-x-contain">
<table
ref={ref}
className="w-full border-collapse text-sm max-md:block"
>
{children}
</table>
</div> </div>
</CardLayoutContext.Provider>
); );
} }
export function THead({ children }: { children: React.ReactNode }) { export function THead({ children }: { children: React.ReactNode }) {
return ( return (
<thead className="border-b border-border bg-muted/50 text-left text-xs uppercase tracking-wide text-muted-foreground"> <thead className="border-b border-border bg-muted/50 text-left text-xs uppercase tracking-wide text-muted-foreground max-md:hidden">
{children} {children}
</thead> </thead>
); );
@@ -24,7 +81,11 @@ export function TH({
children?: React.ReactNode; children?: React.ReactNode;
className?: string; className?: string;
}) { }) {
return <th className={cn("px-4 py-3 font-medium", className)}>{children}</th>; return (
<th className={cn("whitespace-nowrap px-4 py-3 font-medium", className)}>
{children}
</th>
);
} }
export function TR({ export function TR({
@@ -35,7 +96,14 @@ export function TR({
className?: string; className?: string;
}) { }) {
return ( return (
<tr className={cn("border-b border-border last:border-0 align-top", className)}> <tr
className={cn(
"border-b border-border last:border-0 align-top",
// Phone: a card per row.
"max-md:block max-md:px-4 max-md:py-3",
className,
)}
>
{children} {children}
</tr> </tr>
); );
@@ -48,5 +116,28 @@ export function TD({
children?: React.ReactNode; children?: React.ReactNode;
className?: string; className?: string;
}) { }) {
return <td className={cn("px-4 py-3 text-foreground", className)}>{children}</td>; const card = React.useContext(CardLayoutContext);
return (
<td
className={cn(
"px-4 py-3 text-foreground",
// Phone: one labelled block per cell — the label pinned on the left,
// the cell's own content flowing beside it exactly as it would in the
// table (stacked lines stay stacked). Alignment classes meant for a
// column (text-right on actions) give way to the card's flow.
"max-md:relative max-md:block max-md:px-0 max-md:py-1.5 max-md:text-left",
card === "inline"
? "max-md:data-label:pl-28 max-md:data-label:before:absolute max-md:data-label:before:left-0 max-md:data-label:before:top-2 max-md:data-label:before:w-24"
: // Stacked: the label is its own line above the value.
"max-md:py-2 max-md:data-label:before:mb-1 max-md:data-label:before:block",
"max-md:data-label:before:text-[11px] max-md:data-label:before:font-medium max-md:data-label:before:uppercase max-md:data-label:before:leading-4 max-md:data-label:before:tracking-wide max-md:data-label:before:text-muted-foreground max-md:data-label:before:content-[attr(data-label)]",
// Long values (emails, URLs) wrap rather than widen the table or
// card — at every width, so no string can push a column off-screen.
"[overflow-wrap:anywhere]",
className,
)}
>
{children}
</td>
);
} }
+45
View File
@@ -36,6 +36,9 @@ async function call<T>(
headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) }, headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
...init, ...init,
}); });
// 204 No Content (archive, delete, reset…) is success with no body —
// there's no JSON to parse.
if (res.status === 204) return { data: undefined as T };
let body: Envelope<T>; let body: Envelope<T>;
try { try {
body = (await res.json()) as Envelope<T>; body = (await res.json()) as Envelope<T>;
@@ -191,6 +194,8 @@ export type AdminCollection = {
export type AdminFeedback = { export type AdminFeedback = {
id: string; id: string;
category: string; category: string;
/** The category's current display name. */
category_label?: string;
message: string; message: string;
contact_email: string | null; contact_email: string | null;
created_at: string; created_at: string;
@@ -744,4 +749,44 @@ export const quizzes = {
call<QuizResult>(`/admin/quizzes/${id}/participants/${userId}`).then((r) => r.data), call<QuizResult>(`/admin/quizzes/${id}/participants/${userId}`).then((r) => r.data),
responses: (id: string) => responses: (id: string) =>
call<QuizQuestionStat[]>(`/admin/quizzes/${id}/responses`).then((r) => r.data), call<QuizQuestionStat[]>(`/admin/quizzes/${id}/responses`).then((r) => r.data),
/** Deletes one person's attempt; the quiz is pending for them again. */
resetParticipant: (id: string, userId: string) =>
call<void>(`/admin/quizzes/${id}/participants/${userId}`, { method: "DELETE" }),
};
// ─── Feedback categories ────────────────────────────────────────────────────
/** One option on the app's /feedback form. `key` is fixed once created. */
export type FeedbackCategory = {
key: string;
label: string;
description: string;
sort_order: number;
archived_at?: string | null;
/** How much feedback is filed under it. */
usage_count?: number;
};
export const feedbackCategories = {
list: () =>
call<FeedbackCategory[]>("/admin/feedback/categories").then((r) => r.data),
create: (label: string, description: string) =>
call<FeedbackCategory>("/admin/feedback/categories", {
method: "POST",
body: JSON.stringify({ label, description }),
}).then((r) => r.data),
update: (key: string, v: { label: string; description: string; archived: boolean }) =>
call<void>(`/admin/feedback/categories/${encodeURIComponent(key)}`, {
method: "PUT",
body: JSON.stringify(v),
}),
remove: (key: string) =>
call<void>(`/admin/feedback/categories/${encodeURIComponent(key)}`, {
method: "DELETE",
}),
reorder: (keys: string[]) =>
call<void>("/admin/feedback/categories/order", {
method: "PUT",
body: JSON.stringify({ keys }),
}),
}; };