Separate admins' own content from managing other users

- Short links, Link pages and Overview now show only the admin's own
  namespace and root; other users' content moved to Administration
- Administration lists users with their link/page/click counts; each
  opens /~/admin/users/<name> with that user's pages and links and
  lets admins create content in their namespace
- other users' pages open under /~/admin/users/<name>/…, keep the
  Administration section active and link back to the user
- one PageTable component for all lists, so search and the namespace
  filter (All / mine / Root, admins only) behave the same everywhere
- the create dialog offers admins only their own namespace and root;
  the existing-link picker groups links by namespace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 16:52:22 +02:00
co-authored by Claude Opus 5.5
parent e44e56fd2d
commit 35cb7da929
13 changed files with 420 additions and 176 deletions
+7 -2
View File
@@ -4,8 +4,9 @@ import { useApi } from "../api.js";
import { buttonClass } from "../components/ui/button.js"; import { buttonClass } from "../components/ui/button.js";
import { Link } from "../components/ui/misc.js"; import { Link } from "../components/ui/misc.js";
import { EmptyState } from "../components/ui/surface.js"; import { EmptyState } from "../components/ui/surface.js";
import { parseRoute, usePath } from "../router.js"; import { parseRoute, setViewer, usePath } from "../router.js";
import { AdminScreen } from "../screens/AdminScreen.js"; import { AdminScreen } from "../screens/AdminScreen.js";
import { AdminUserScreen } from "../screens/AdminUserScreen.js";
import { DetailScreen } from "../screens/detail/DetailScreen.js"; import { DetailScreen } from "../screens/detail/DetailScreen.js";
import { ListScreen } from "../screens/ListScreen.js"; import { ListScreen } from "../screens/ListScreen.js";
import { OverviewScreen } from "../screens/OverviewScreen.js"; import { OverviewScreen } from "../screens/OverviewScreen.js";
@@ -61,6 +62,7 @@ export function App() {
location.href = "/~/"; location.href = "/~/";
}; };
setViewer(me.data.username);
const route = parseRoute(path); const route = parseRoute(path);
let screen; let screen;
switch (route.name) { switch (route.name) {
@@ -77,7 +79,10 @@ export function App() {
screen = <TokensScreen />; screen = <TokensScreen />;
break; break;
case "admin": case "admin":
screen = me.data.isAdmin ? <AdminScreen /> : null; screen = me.data.isAdmin ? <AdminScreen me={me.data} /> : null;
break;
case "adminUser":
screen = me.data.isAdmin ? <AdminUserScreen key={route.username} username={route.username} me={me.data} /> : null;
break; break;
} }
+4
View File
@@ -15,8 +15,12 @@ function sectionOf(route: Route): Section | null {
case "tokens": case "tokens":
case "admin": case "admin":
return route.name; return route.name;
case "adminUser":
return "admin";
case "list": case "list":
case "detail": case "detail":
// Other users' pages are opened from Administration and stay in that section.
if (route.name === "detail" && route.owner) return "admin";
return route.kind === "redirect" ? "links" : "pages"; return route.kind === "redirect" ? "links" : "pages";
default: default:
return null; return null;
+9 -11
View File
@@ -1,6 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js"; import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { api, ApiRequestError, errorMessage, useApi } from "../api.js"; import { api, ApiRequestError, errorMessage } from "../api.js";
import { Button } from "./ui/button.js"; import { Button } from "./ui/button.js";
import { Dialog } from "./ui/dialog.js"; import { Dialog } from "./ui/dialog.js";
import { Field, Input, PrefixInput, Select } from "./ui/form.js"; import { Field, Input, PrefixInput, Select } from "./ui/form.js";
@@ -24,15 +24,17 @@ export function CreatePageDialog({
open, open,
onClose, onClose,
onCreated, onCreated,
fixedNamespace,
}: { }: {
kind: PageKind; kind: PageKind;
me: Me; me: Me;
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
onCreated: (page: PageSummary) => void; onCreated: (page: PageSummary) => void;
/** Create in this namespace without offering a choice, e.g. when an admin manages another user. */
fixedNamespace?: string;
}) { }) {
const users = useApi<string[]>(me.isAdmin && open ? "/users" : null); const [namespace, setNamespace] = useState(fixedNamespace ?? me.username);
const [namespace, setNamespace] = useState(me.username);
const [code, setCode] = useState(""); const [code, setCode] = useState("");
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@@ -102,16 +104,12 @@ export function CreatePageDialog({
</Field> </Field>
)} )}
{me.isAdmin && ( {me.isAdmin && fixedNamespace === undefined && (
<Field label="Namespace" hint="Root links are only available to admins." error={errors.namespace}> <Field label="Namespace" error={errors.namespace}>
{(id) => ( {(id) => (
<Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}> <Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
<option value="">Root (/)</option> <option value={me.username}>/{me.username}/ (yours)</option>
{(users.data ?? [me.username]).map((u) => ( <option value="">Root /</option>
<option key={u} value={u}>
{u === me.username ? `${u} (you)` : u}
</option>
))}
</Select> </Select>
)} )}
</Field> </Field>
+124
View File
@@ -0,0 +1,124 @@
import { useMemo, useState, type ReactNode } from "react";
import { ChevronRight, Link2, PanelsTopLeft, Pin, Search } from "lucide-react";
import type { PageKind, PageSummary } from "../../shared/api-types.js";
import { detailPath } from "../router.js";
import { Input, Select } from "./ui/form.js";
import { CopyButton, DomainIcon, Link, publicUrl } from "./ui/misc.js";
import { Badge, Card, EmptyState, Skeleton } from "./ui/surface.js";
function Row({ page, showNamespace }: { page: PageSummary; showNamespace: boolean }) {
const isLink = page.kind === "redirect";
return (
<div className="group relative grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-4 py-3 transition-colors hover:bg-surface-2/60 md:grid-cols-[auto_minmax(0,2fr)_minmax(0,3fr)_5rem_auto] md:px-5">
{isLink ? (
<DomainIcon url={page.dest} />
) : (
<span className="flex size-8 items-center justify-center rounded-lg bg-accent-soft text-accent-soft-fg">
<PanelsTopLeft className="size-4" />
</span>
)}
<div className="min-w-0">
<div className="flex items-center gap-2">
{/* The link stretches over the whole row; the copy button sits above it. */}
<Link to={detailPath(page)} className="truncate font-mono text-sm font-medium text-fg after:absolute after:inset-0">
{page.path}
</Link>
{showNamespace && page.namespace === "" && <Badge>Root</Badge>}
{page.pinned && (
<Badge tone="accent" icon={<Pin />}>
Home
</Badge>
)}
</div>
<div className="truncate text-sm text-muted md:hidden">{isLink ? page.dest : page.title}</div>
</div>
<div className="hidden truncate text-sm text-muted md:block">{isLink ? page.dest : page.title}</div>
<div className="hidden text-right text-sm text-muted tabular-nums md:block">{page.totalClicks.toLocaleString()}</div>
<div className="flex items-center gap-1">
<div className="relative z-10">
<CopyButton value={publicUrl(page.path)} />
</div>
<ChevronRight className="hidden size-4 text-muted transition-transform group-hover:translate-x-0.5 md:block" />
</div>
</div>
);
}
export interface NamespaceOption {
label: string;
match: (namespace: string) => boolean;
}
// Searchable list of short links or link pages. The toolbar is the same everywhere it's used;
// `namespaces` adds a namespace filter (e.g. "Mine" / "Root" for admins).
export function PageTable({
kind,
pages,
namespaces,
empty,
}: {
kind: PageKind;
pages: PageSummary[] | undefined;
namespaces?: NamespaceOption[];
empty: { title: string; description: string; action?: ReactNode };
}) {
const [query, setQuery] = useState("");
const [filter, setFilter] = useState(0);
const ofKind = useMemo(() => (pages ?? []).filter((p) => p.kind === kind), [pages, kind]);
const q = query.trim().toLowerCase();
const option = namespaces?.[filter];
const visible = ofKind.filter(
(p) =>
(!option || option.match(p.namespace)) &&
(!q || p.path.toLowerCase().includes(q) || (p.dest ?? p.title ?? "").toLowerCase().includes(q)),
);
return (
<Card className="overflow-hidden">
<div className="flex flex-wrap items-center gap-2 border-b border-border p-3">
<div className="relative min-w-48 flex-1">
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted" />
<Input className="pl-9" placeholder="Search…" value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" />
</div>
{namespaces && (
<div className="w-36">
<Select aria-label="Namespace" value={filter} onChange={(e) => setFilter(Number(e.target.value))}>
{namespaces.map((n, i) => (
<option key={n.label} value={i}>
{n.label}
</option>
))}
</Select>
</div>
)}
</div>
<div className="hidden grid-cols-[2rem_minmax(0,2fr)_minmax(0,3fr)_5rem_4.25rem] gap-x-3 border-b border-border bg-surface-2/40 px-5 py-2 text-xs font-medium text-muted uppercase md:grid">
<span />
<span>{kind === "redirect" ? "Short link" : "Page"}</span>
<span>{kind === "redirect" ? "Destination" : "Title"}</span>
<span className="text-right">Clicks</span>
<span />
</div>
{!pages ? (
<div className="flex flex-col gap-3 p-5">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-10" />
))}
</div>
) : visible.length ? (
<div className="divide-y divide-border">
{visible.map((p) => (
<Row key={p.id} page={p} showNamespace={!!namespaces} />
))}
</div>
) : ofKind.length ? (
<EmptyState icon={<Search />} title="No matches" description={namespaces ? "Try a different search or filter." : "Try a different search."} />
) : (
<EmptyState icon={kind === "redirect" ? <Link2 /> : <PanelsTopLeft />} title={empty.title} description={empty.description} action={empty.action} />
)}
</Card>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Me, PageSummary } from "../../shared/api-types.js";
import type { NamespaceOption } from "../components/PageTable.js";
// "Your" content: your own namespace, plus root for admins. Other users' content is managed under Administration.
export function isMine(page: Pick<PageSummary, "namespace">, me: Me): boolean {
return page.namespace === me.username || (me.isAdmin && page.namespace === "");
}
// Namespace filter for admins, who see both their own and root content.
export function myNamespaceOptions(me: Me): NamespaceOption[] | undefined {
if (!me.isAdmin) return undefined;
return [
{ label: "All", match: () => true },
{ label: `/${me.username}/`, match: (ns) => ns === me.username },
{ label: "Root /", match: (ns) => ns === "" },
];
}
+39 -3
View File
@@ -33,19 +33,47 @@ export function linkHandler(to: string) {
export type Route = export type Route =
| { name: "overview" } | { name: "overview" }
| { name: "list"; kind: PageKind } | { name: "list"; kind: PageKind }
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined } /** `owner` is set when an admin opens another user's page via Administration. */
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined; owner?: string }
| { name: "tokens" } | { name: "tokens" }
| { name: "admin" } | { name: "admin" }
| { name: "adminUser"; username: string }
| { name: "notFound" }; | { name: "notFound" };
const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" }; const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" };
// The signed-in user. Pages of other users are addressed through Administration,
// so the admin's own and root content stays separate from managing everyone else's.
let viewer: string | null = null;
export function setViewer(username: string) {
viewer = username;
}
const isOtherUsers = (namespace: string | undefined) => namespace !== undefined && namespace !== "" && namespace !== viewer;
export function listPath(kind: PageKind): string { export function listPath(kind: PageKind): string {
return kind === "redirect" ? "/~/links" : "/~/pages"; return kind === "redirect" ? "/~/links" : "/~/pages";
} }
export function detailPath(page: { id: number; kind: PageKind }, tab?: string): string { export function adminUserPath(username: string): string {
return `${listPath(page.kind)}/${page.id}${tab ? `/${tab}` : ""}`; return `/~/admin/users/${encodeURIComponent(username)}`;
}
export function detailPath(page: { id: number; kind: PageKind; namespace?: string }, tab?: string): string {
const segment = page.kind === "redirect" ? "links" : "pages";
const base = isOtherUsers(page.namespace) ? `${adminUserPath(page.namespace!)}/${segment}` : `/~/${segment}`;
return `${base}/${page.id}${tab ? `/${tab}` : ""}`;
}
// Where "back" leads from a page: its owner's admin view for other users' pages, otherwise the list.
export function backPath(page: { kind: PageKind; namespace: string }): string {
return isOtherUsers(page.namespace) ? adminUserPath(page.namespace) : listPath(page.kind);
}
// Replaces the current URL (no new history entry), e.g. to correct a link to the canonical address.
export function replacePath(to: string) {
history.replaceState(null, "", to);
listeners.forEach((l) => l());
} }
export function parseRoute(path: string): Route { export function parseRoute(path: string): Route {
@@ -53,6 +81,14 @@ export function parseRoute(path: string): Route {
if (p === "/~") return { name: "overview" }; if (p === "/~") return { name: "overview" };
if (p === "/~/tokens") return { name: "tokens" }; if (p === "/~/tokens") return { name: "tokens" };
if (p === "/~/admin") return { name: "admin" }; if (p === "/~/admin") return { name: "admin" };
const user = p.match(/^\/~\/admin\/users\/([^/]+)(?:\/(links|pages)\/(\d+)(?:\/([a-z]+))?)?$/);
if (user) {
const username = decodeURIComponent(user[1]!);
if (!user[2]) return { name: "adminUser", username };
return { name: "detail", kind: KIND_SEGMENT[user[2]]!, id: Number(user[3]), tab: user[4], owner: username };
}
const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/); const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/);
if (m) { if (m) {
const kind = KIND_SEGMENT[m[1]!]!; const kind = KIND_SEGMENT[m[1]!]!;
+51 -37
View File
@@ -1,13 +1,13 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { PinOff, TriangleAlert, Users } from "lucide-react"; import { ChevronRight, PinOff, TriangleAlert, Users } from "lucide-react";
import type { Conflict, PageSummary } from "../../shared/api-types.js"; import type { Conflict, Me, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js"; import { api, useApi } from "../api.js";
import { Button } from "../components/ui/button.js"; import { Button } from "../components/ui/button.js";
import { Select } from "../components/ui/form.js"; import { Select } from "../components/ui/form.js";
import { Link } from "../components/ui/misc.js"; import { Link } from "../components/ui/misc.js";
import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js"; import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { useAction } from "../components/ui/toast.js"; import { useAction } from "../components/ui/toast.js";
import { detailPath } from "../router.js"; import { adminUserPath, detailPath } from "../router.js";
function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) { function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) {
const pinned = pages.find((p) => p.pinned); const pinned = pages.find((p) => p.pinned);
@@ -52,19 +52,61 @@ function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => P
); );
} }
export function AdminScreen() { function UsersCard({ users, pages, me }: { users: string[] | undefined; pages: PageSummary[] | undefined; me: Me }) {
const others = users?.filter((u) => u !== me.username);
const stats = (u: string) => {
const theirs = (pages ?? []).filter((p) => p.namespace === u);
const links = theirs.filter((p) => p.kind === "redirect").length;
const linkPages = theirs.length - links;
const clicks = theirs.reduce((sum, p) => sum + p.totalClicks, 0);
return `${links} ${links === 1 ? "link" : "links"} · ${linkPages} ${linkPages === 1 ? "page" : "pages"} · ${clicks.toLocaleString()} clicks`;
};
return (
<Card className="overflow-hidden">
<CardHeader
title="Users"
description="Open a user to manage their short links and link pages. Your own and root content is under Short links and Link pages."
actions={others && <Badge>{others.length}</Badge>}
/>
{!others ? (
<Skeleton className="m-5 h-10" />
) : others.length ? (
<ul className="divide-y divide-border">
{others.map((u) => (
<li key={u} className="group relative flex items-center gap-3 px-5 py-3 transition-colors hover:bg-surface-2/60">
<span className="flex size-8 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{u.charAt(0)}
</span>
<div className="min-w-0 flex-1">
<Link to={adminUserPath(u)} className="font-medium after:absolute after:inset-0">
{u}
</Link>
<div className="truncate text-xs text-muted">{pages ? stats(u) : " "}</div>
</div>
<ChevronRight className="size-4 text-muted transition-transform group-hover:translate-x-0.5" />
</li>
))}
</ul>
) : (
<EmptyState icon={<Users />} title="No other users yet" description="Users appear here after their first sign-in." />
)}
</Card>
);
}
export function AdminScreen({ me }: { me: Me }) {
const pages = useApi<PageSummary[]>("/pages"); const pages = useApi<PageSummary[]>("/pages");
const users = useApi<string[]>("/users"); const users = useApi<string[]>("/users");
const conflicts = useApi<Conflict[]>("/conflicts"); const conflicts = useApi<Conflict[]>("/conflicts");
const countByUser = new Map<string, number>();
for (const p of pages.data ?? []) countByUser.set(p.namespace, (countByUser.get(p.namespace) ?? 0) + 1);
return ( return (
<> <>
<PageHeader title="Administration" description="Settings that affect the whole instance." /> <PageHeader title="Administration" description="Other users' content and settings that affect the whole instance." />
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
<UsersCard users={users.data} pages={pages.data} me={me} />
{pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />} {pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />}
<Card> <Card>
@@ -80,7 +122,7 @@ export function AdminScreen() {
<li key={c.pageId} className="flex items-center gap-3 px-5 py-3"> <li key={c.pageId} className="flex items-center gap-3 px-5 py-3">
<TriangleAlert className="size-4 text-warning-soft-fg" /> <TriangleAlert className="size-4 text-warning-soft-fg" />
<span className="flex-1 font-mono text-sm">/{c.username}</span> <span className="flex-1 font-mono text-sm">/{c.username}</span>
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="text-sm text-accent hover:underline"> <Link to={detailPath({ id: c.pageId, kind: "redirect", namespace: "" }, "settings")} className="text-sm text-accent hover:underline">
Open root link Open root link
</Link> </Link>
</li> </li>
@@ -90,34 +132,6 @@ export function AdminScreen() {
<CardBody className="text-sm text-muted">No conflicts.</CardBody> <CardBody className="text-sm text-muted">No conflicts.</CardBody>
)} )}
</Card> </Card>
<Card className="overflow-hidden">
<CardHeader
title="Users"
description="Everyone who has signed in. Admin rights and usernames are managed in Authentik."
actions={users.data && <Badge>{users.data.length}</Badge>}
/>
{!users.data ? (
<Skeleton className="m-5 h-10" />
) : users.data.length ? (
<ul className="divide-y divide-border">
{users.data.map((u) => (
<li key={u} className="flex items-center gap-3 px-5 py-3">
<span className="flex size-8 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{u.charAt(0)}
</span>
<span className="flex-1 font-mono text-sm">/{u}/</span>
<span className="text-sm text-muted">
{countByUser.get(u) ?? 0} {(countByUser.get(u) ?? 0) === 1 ? "page" : "pages"}
</span>
</li>
))}
</ul>
) : (
<EmptyState icon={<Users />} title="No users yet" />
)}
</Card>
</div> </div>
</> </>
); );
+109
View File
@@ -0,0 +1,109 @@
import { useState } from "react";
import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, UserX } from "lucide-react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { useApi } from "../api.js";
import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { PageTable } from "../components/PageTable.js";
import { Button, buttonClass } from "../components/ui/button.js";
import { Link, Stat } from "../components/ui/misc.js";
import { EmptyState, Skeleton } from "../components/ui/surface.js";
import { useToast } from "../components/ui/toast.js";
import { detailPath, navigate } from "../router.js";
// Everything one user owns, for admins. Kept apart from the admin's own and root content.
export function AdminUserScreen({ username, me }: { username: string; me: Me }) {
const users = useApi<string[]>("/users");
const pages = useApi<PageSummary[]>("/pages");
const toast = useToast();
const [creating, setCreating] = useState<PageKind | null>(null);
if (users.data && !users.data.includes(username)) {
return (
<EmptyState
icon={<UserX />}
title="User not found"
description={`Nobody called "${username}" has signed in yet.`}
action={
<Link to="/~/admin" className={buttonClass("secondary")}>
Back to Administration
</Link>
}
/>
);
}
const theirs = pages.data?.filter((p) => p.namespace === username);
const count = (kind: PageKind) => theirs?.filter((p) => p.kind === kind).length ?? 0;
const clicks = theirs?.reduce((sum, p) => sum + p.totalClicks, 0) ?? 0;
return (
<>
<nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb">
<Link to="/~/admin" className="hover:text-fg">
Administration
</Link>
<ChevronRight className="size-3.5" />
<span className="text-fg">{username}</span>
</nav>
<header className="mb-6 flex flex-wrap items-center gap-4 lg:mb-8">
<span className="flex size-12 items-center justify-center rounded-full bg-accent-soft text-lg font-semibold text-accent-soft-fg uppercase">
{username.charAt(0)}
</span>
<div className="min-w-0 flex-1">
<h1 className="truncate text-2xl font-semibold tracking-tight">{username}</h1>
<p className="mt-0.5 text-sm text-muted">
Manage the links and pages under <span className="font-mono">/{username}/</span>.
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
New link page
</Button>
<Button icon={<Plus />} onClick={() => setCreating("redirect")}>
New short link
</Button>
</div>
</header>
<div className="flex flex-col gap-8">
<div className="grid grid-cols-3 gap-3 sm:gap-4">
{theirs ? (
<>
<Stat label="Short links" value={count("redirect")} icon={<Link2 />} />
<Stat label="Link pages" value={count("linkpage")} icon={<PanelsTopLeft />} />
<Stat label="Total clicks" value={clicks.toLocaleString()} icon={<MousePointerClick />} />
</>
) : (
[0, 1, 2].map((i) => <Skeleton key={i} className="h-24 rounded-xl" />)
)}
</div>
<section>
<h2 className="mb-3 text-base font-semibold">Link pages</h2>
<PageTable kind="linkpage" pages={theirs} empty={{ title: "No link pages", description: `${username} hasn't created any link pages.` }} />
</section>
<section>
<h2 className="mb-3 text-base font-semibold">Short links</h2>
<PageTable kind="redirect" pages={theirs} empty={{ title: "No short links", description: `${username} hasn't created any short links.` }} />
</section>
</div>
{creating && (
<CreatePageDialog
kind={creating}
me={me}
open
fixedNamespace={username}
onClose={() => setCreating(null)}
onCreated={(page) => {
if (page.kind === "linkpage") return navigate(detailPath(page));
toast(`Created ${page.path}`);
void pages.reload();
}}
/>
)}
</>
);
}
+16 -107
View File
@@ -1,19 +1,21 @@
import { useMemo, useState } from "react"; import { useState } from "react";
import { ChevronRight, Link2, PanelsTopLeft, Pin, Plus, Search } from "lucide-react"; import { Plus } from "lucide-react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js"; import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { useApi } from "../api.js"; import { useApi } from "../api.js";
import { CreatePageDialog } from "../components/CreatePageDialog.js"; import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { PageTable } from "../components/PageTable.js";
import { Button } from "../components/ui/button.js"; import { Button } from "../components/ui/button.js";
import { Input, Select } from "../components/ui/form.js"; import { publicUrl } from "../components/ui/misc.js";
import { CopyButton, DomainIcon, Link, publicUrl } from "../components/ui/misc.js"; import { PageHeader } from "../components/ui/surface.js";
import { Badge, Card, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { useToast } from "../components/ui/toast.js"; import { useToast } from "../components/ui/toast.js";
import { isMine, myNamespaceOptions } from "../lib/scope.js";
import { detailPath, navigate } from "../router.js"; import { detailPath, navigate } from "../router.js";
const COPY: Record<PageKind, { title: string; description: string; create: string; empty: string; emptyText: string }> = { const COPY: Record<PageKind, { title: string; description: string; adminDescription: string; create: string; empty: string; emptyText: string }> = {
redirect: { redirect: {
title: "Short links", title: "Short links",
description: "Short URLs that redirect to another address.", description: "Short URLs that redirect to another address.",
adminDescription: "Your short links and root links. Other users' links are under Administration.",
create: "New short link", create: "New short link",
empty: "No short links yet", empty: "No short links yet",
emptyText: "Create your first short link to share long URLs and track clicks.", emptyText: "Create your first short link to share long URLs and track clicks.",
@@ -21,66 +23,19 @@ const COPY: Record<PageKind, { title: string; description: string; create: strin
linkpage: { linkpage: {
title: "Link pages", title: "Link pages",
description: "Pages that collect several links, like a link in bio.", description: "Pages that collect several links, like a link in bio.",
adminDescription: "Your link pages and root pages. Other users' pages are under Administration.",
create: "New link page", create: "New link page",
empty: "No link pages yet", empty: "No link pages yet",
emptyText: "Create a page with your avatar, link buttons and some text.", emptyText: "Create a page with your avatar, link buttons and some text.",
}, },
}; };
function Row({ page }: { page: PageSummary }) {
const isLink = page.kind === "redirect";
return (
<div className="group relative grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-4 py-3 transition-colors hover:bg-surface-2/60 md:grid-cols-[auto_minmax(0,2fr)_minmax(0,3fr)_5rem_auto] md:px-5">
{isLink ? (
<DomainIcon url={page.dest} />
) : (
<span className="flex size-8 items-center justify-center rounded-lg bg-accent-soft text-accent-soft-fg">
<PanelsTopLeft className="size-4" />
</span>
)}
<div className="min-w-0">
<div className="flex items-center gap-2">
{/* The link stretches over the whole row; the copy button sits above it. */}
<Link to={detailPath(page)} className="truncate font-mono text-sm font-medium text-fg after:absolute after:inset-0">
{page.path}
</Link>
{page.pinned && (
<Badge tone="accent" icon={<Pin />}>
Home
</Badge>
)}
</div>
<div className="truncate text-sm text-muted md:hidden">{isLink ? page.dest : page.title}</div>
</div>
<div className="hidden truncate text-sm text-muted md:block">{isLink ? page.dest : page.title}</div>
<div className="hidden text-right text-sm text-muted tabular-nums md:block">{page.totalClicks.toLocaleString()}</div>
<div className="flex items-center gap-1">
<div className="relative z-10">
<CopyButton value={publicUrl(page.path)} />
</div>
<ChevronRight className="hidden size-4 text-muted transition-transform group-hover:translate-x-0.5 md:block" />
</div>
</div>
);
}
export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) { export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) {
const pages = useApi<PageSummary[]>("/pages"); const pages = useApi<PageSummary[]>("/pages");
const toast = useToast(); const toast = useToast();
const [query, setQuery] = useState("");
const [namespace, setNamespace] = useState<string | null>(null);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const copy = COPY[kind]; const copy = COPY[kind];
const ofKind = useMemo(() => (pages.data ?? []).filter((p) => p.kind === kind), [pages.data, kind]);
const namespaces = useMemo(() => [...new Set(ofKind.map((p) => p.namespace))].sort(), [ofKind]);
const q = query.trim().toLowerCase();
const visible = ofKind.filter(
(p) =>
(namespace === null || p.namespace === namespace) &&
(!q || p.path.toLowerCase().includes(q) || (p.dest ?? p.title ?? "").toLowerCase().includes(q)),
);
const created = async (page: PageSummary) => { const created = async (page: PageSummary) => {
if (page.kind === "linkpage") return navigate(detailPath(page)); if (page.kind === "linkpage") return navigate(detailPath(page));
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {}); await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
@@ -96,59 +51,13 @@ export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) {
return ( return (
<> <>
<PageHeader title={copy.title} description={copy.description} actions={createButton} /> <PageHeader title={copy.title} description={me.isAdmin ? copy.adminDescription : copy.description} actions={createButton} />
<PageTable
<Card className="overflow-hidden"> kind={kind}
<div className="flex flex-wrap items-center gap-2 border-b border-border p-3"> pages={pages.data?.filter((p) => isMine(p, me))}
<div className="relative min-w-48 flex-1"> namespaces={myNamespaceOptions(me)}
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted" /> empty={{ title: copy.empty, description: copy.emptyText, action: createButton }}
<Input className="pl-9" placeholder="Search…" value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" /> />
</div>
{me.isAdmin && namespaces.length > 1 && (
<div className="w-44">
<Select
aria-label="Namespace"
value={namespace ?? "*"}
onChange={(e) => setNamespace(e.target.value === "*" ? null : e.target.value)}
>
<option value="*">All namespaces</option>
{namespaces.map((ns) => (
<option key={ns} value={ns}>
{ns ? `/${ns}/` : "Root /"}
</option>
))}
</Select>
</div>
)}
</div>
<div className="hidden grid-cols-[2rem_minmax(0,2fr)_minmax(0,3fr)_5rem_4.25rem] gap-x-3 border-b border-border bg-surface-2/40 px-5 py-2 text-xs font-medium text-muted uppercase md:grid">
<span />
<span>{kind === "redirect" ? "Short link" : "Page"}</span>
<span>{kind === "redirect" ? "Destination" : "Title"}</span>
<span className="text-right">Clicks</span>
<span />
</div>
{!pages.data ? (
<div className="flex flex-col gap-3 p-5">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-10" />
))}
</div>
) : visible.length ? (
<div className="divide-y divide-border">
{visible.map((p) => (
<Row key={p.id} page={p} />
))}
</div>
) : ofKind.length ? (
<EmptyState icon={<Search />} title="No matches" description="Try a different search or namespace." />
) : (
<EmptyState icon={kind === "redirect" ? <Link2 /> : <PanelsTopLeft />} title={copy.empty} description={copy.emptyText} action={createButton} />
)}
</Card>
<CreatePageDialog kind={kind} me={me} open={creating} onClose={() => setCreating(false)} onCreated={created} /> <CreatePageDialog kind={kind} me={me} open={creating} onClose={() => setCreating(false)} onCreated={created} />
</> </>
); );
+5 -3
View File
@@ -6,6 +6,7 @@ import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { Button, buttonClass } from "../components/ui/button.js"; import { Button, buttonClass } from "../components/ui/button.js";
import { DomainIcon, Link, Stat } from "../components/ui/misc.js"; import { DomainIcon, Link, Stat } from "../components/ui/misc.js";
import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js"; import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { isMine } from "../lib/scope.js";
import { detailPath, navigate } from "../router.js"; import { detailPath, navigate } from "../router.js";
function TopPages({ pages }: { pages: PageSummary[] }) { function TopPages({ pages }: { pages: PageSummary[] }) {
@@ -47,11 +48,12 @@ export function OverviewScreen({ me }: { me: Me }) {
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null); const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null);
const [creating, setCreating] = useState<PageKind | null>(null); const [creating, setCreating] = useState<PageKind | null>(null);
const all = pages.data ?? []; // Admins see their own and root content here; other users' content is under Administration.
const all = (pages.data ?? []).filter((p) => isMine(p, me));
const links = all.filter((p) => p.kind === "redirect"); const links = all.filter((p) => p.kind === "redirect");
const linkPages = all.filter((p) => p.kind === "linkpage"); const linkPages = all.filter((p) => p.kind === "linkpage");
const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0); const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0);
const scope = me.isAdmin ? "all users" : `in /${me.username}/`; const scope = me.isAdmin ? "yours & root" : `in /${me.username}/`;
return ( return (
<> <>
@@ -76,7 +78,7 @@ export function OverviewScreen({ me }: { me: Me }) {
{conflicts.data.map((c, i) => ( {conflicts.data.map((c, i) => (
<span key={c.pageId}> <span key={c.pageId}>
{i > 0 && ", "} {i > 0 && ", "}
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="font-mono underline"> <Link to={detailPath({ id: c.pageId, kind: "redirect", namespace: "" }, "settings")} className="font-mono underline">
/{c.username} /{c.username}
</Link> </Link>
</span> </span>
+15 -4
View File
@@ -26,6 +26,13 @@ function hostnameOf(url: string | null | undefined): string {
} }
} }
// Groups links by namespace, with the page's own namespace first (admins can link across namespaces).
function groupByNamespace(links: PageSummary[], first: string): [string, PageSummary[]][] {
const groups = new Map<string, PageSummary[]>([[first, []]]);
for (const link of links) groups.set(link.namespace, [...(groups.get(link.namespace) ?? []), link]);
return [...groups].filter(([, l]) => l.length > 0);
}
function BlockDialog({ function BlockDialog({
editing, editing,
page, page,
@@ -166,10 +173,14 @@ function BlockDialog({
}} }}
> >
<option value="">Choose a short link…</option> <option value="">Choose a short link…</option>
{targets.map((p) => ( {groupByNamespace(targets, page.namespace).map(([ns, links]) => (
<option key={p.id} value={p.id}> <optgroup key={ns} label={ns ? `/${ns}/` : "Root /"}>
{p.path} → {p.dest} {links.map((p) => (
</option> <option key={p.id} value={p.id}>
{p.path} → {p.dest}
</option>
))}
</optgroup>
))} ))}
</Select> </Select>
)} )}
+22 -7
View File
@@ -5,7 +5,7 @@ import { useApi } from "../../api.js";
import { buttonClass } from "../../components/ui/button.js"; import { buttonClass } from "../../components/ui/button.js";
import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.js"; import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.js";
import { Badge, EmptyState, Skeleton } from "../../components/ui/surface.js"; import { Badge, EmptyState, Skeleton } from "../../components/ui/surface.js";
import { detailPath, listPath } from "../../router.js"; import { backPath, detailPath, listPath, replacePath } from "../../router.js";
import { AnalyticsTab } from "./AnalyticsTab.js"; import { AnalyticsTab } from "./AnalyticsTab.js";
import { AppearanceTab } from "./AppearanceTab.js"; import { AppearanceTab } from "./AppearanceTab.js";
import { ContentTab } from "./ContentTab.js"; import { ContentTab } from "./ContentTab.js";
@@ -30,10 +30,13 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
const page = useApi<PageDetail>(`/pages/${id}`); const page = useApi<PageDetail>(`/pages/${id}`);
const p = page.data; const p = page.data;
// Links like /~/links/<id of a link page> are corrected to the right section. // Correct the URL to the canonical one, e.g. /~/links/<id of a link page>, or another user's
// page opened outside Administration.
useEffect(() => { useEffect(() => {
if (p && p.kind !== kind) history.replaceState(null, "", detailPath(p, tab)); if (!p) return;
}, [p, kind, tab]); const canonical = detailPath(p, tab);
if (location.pathname.replace(/\/+$/, "") !== canonical) replacePath(canonical);
}, [p, tab]);
if (page.error) { if (page.error) {
return ( return (
@@ -67,9 +70,21 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
return ( return (
<> <>
<nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb"> <nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb">
<Link to={listPath(p.kind)} className="hover:text-fg"> {backPath(p) === listPath(p.kind) ? (
{p.kind === "redirect" ? "Short links" : "Link pages"} <Link to={listPath(p.kind)} className="hover:text-fg">
</Link> {p.kind === "redirect" ? "Short links" : "Link pages"}
</Link>
) : (
<>
<Link to="/~/admin" className="hover:text-fg">
Administration
</Link>
<ChevronRight className="size-3.5" />
<Link to={backPath(p)} className="hover:text-fg">
{p.namespace}
</Link>
</>
)}
<ChevronRight className="size-3.5" /> <ChevronRight className="size-3.5" />
<span className="truncate text-fg">{p.path}</span> <span className="truncate text-fg">{p.path}</span>
</nav> </nav>
+2 -2
View File
@@ -8,7 +8,7 @@ import { Field, Input, PrefixInput } from "../../components/ui/form.js";
import { CopyButton, publicUrl } from "../../components/ui/misc.js"; import { CopyButton, publicUrl } from "../../components/ui/misc.js";
import { Alert, Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js"; import { Alert, Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
import { useAction, useToast } from "../../components/ui/toast.js"; import { useAction, useToast } from "../../components/ui/toast.js";
import { listPath, navigate } from "../../router.js"; import { backPath, navigate } from "../../router.js";
function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) { function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
const [dest, setDest] = useState(page.dest ?? ""); const [dest, setDest] = useState(page.dest ?? "");
@@ -153,7 +153,7 @@ export function SettingsTab({
if (!ok) return; if (!ok) return;
void run(async () => { void run(async () => {
await api("DELETE", `/pages/${page.id}`); await api("DELETE", `/pages/${page.id}`);
navigate(listPath(page.kind)); navigate(backPath(page));
}, `Deleted ${page.path}`); }, `Deleted ${page.path}`);
}; };