mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
Redesign the admin UI
Replaces the single-page dashboard with a structured app shell: sidebar on desktop, bottom tab bar on mobile (PWA), and separate screens for overview, short links, link pages, API tokens and administration. - detail view with tabs: content, appearance, analytics, QR code, settings - small component kit (buttons, form controls, cards, dialogs, toasts, tabs) built on semantic color tokens with light and dark mode following the system - native <dialog> modals for creating pages, editing blocks and confirmations instead of window.confirm - theme presets and a live preview of unsaved appearance changes - removed the v1 screenshots for now Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Binary file not shown.
|
Before Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 108 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@@ -11,12 +11,6 @@ A small self-hosted URL shortener and link-page tool for a handful of people, wi
|
||||
|
||||
See [REQUIREMENTS.md](REQUIREMENTS.md) for the full feature list.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## URLs
|
||||
|
||||
| Path | What |
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"concurrently": "^10.0.6",
|
||||
"drizzle-kit": "^0.31.11",
|
||||
"lucide-react": "^1.56.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
|
||||
Generated
+18
@@ -69,6 +69,9 @@ importers:
|
||||
drizzle-kit:
|
||||
specifier: ^0.31.11
|
||||
version: 0.31.11
|
||||
lucide-react:
|
||||
specifier: ^1.56.0
|
||||
version: 1.56.0(@types/react@19.3.0)(react@19.3.0)
|
||||
qrcode:
|
||||
specifier: ^1.5.4
|
||||
version: 1.5.4
|
||||
@@ -1398,6 +1401,15 @@ packages:
|
||||
resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
lucide-react@1.56.0:
|
||||
resolution: {integrity: sha512-b+hqj30/trHBma5r1zlKb6yLewQp6tUtnz9loc3xdrYerPmvLYhlEbyPVCJ8DOg2/blBf6lwPLznftFVACka6A==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
magic-string@0.30.21:
|
||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||
|
||||
@@ -2540,6 +2552,12 @@ snapshots:
|
||||
dependencies:
|
||||
p-locate: 4.1.0
|
||||
|
||||
lucide-react@1.56.0(@types/react@19.3.0)(react@19.3.0):
|
||||
dependencies:
|
||||
react: 19.3.0
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.0
|
||||
|
||||
magic-string@0.30.21:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { ArrowLeft, LogIn } from "lucide-react";
|
||||
import type { Me } from "../../shared/api-types.js";
|
||||
import { useApi } from "../api.js";
|
||||
import { buttonClass } from "../components/ui/button.js";
|
||||
import { Link } from "../components/ui/misc.js";
|
||||
import { EmptyState } from "../components/ui/surface.js";
|
||||
import { parseRoute, usePath } from "../router.js";
|
||||
import { AdminScreen } from "../screens/AdminScreen.js";
|
||||
import { DetailScreen } from "../screens/detail/DetailScreen.js";
|
||||
import { ListScreen } from "../screens/ListScreen.js";
|
||||
import { OverviewScreen } from "../screens/OverviewScreen.js";
|
||||
import { TokensScreen } from "../screens/TokensScreen.js";
|
||||
import { Shell } from "./Shell.js";
|
||||
|
||||
function Login() {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center p-6">
|
||||
<div className="w-full max-w-sm animate-pop-in rounded-2xl border border-border bg-surface p-8 text-center shadow-xl">
|
||||
<img src="/~/short.svg" alt="" className="mx-auto mb-5 size-12 rounded-xl" />
|
||||
<h1 className="text-xl font-semibold tracking-tight">Sign in to short</h1>
|
||||
<p className="mt-1.5 text-sm text-muted">Manage your short links, link pages and stats.</p>
|
||||
<a href="/~/auth/login" className={buttonClass("primary", "md", "mt-6 w-full")}>
|
||||
<LogIn />
|
||||
Continue with single sign-on
|
||||
</a>
|
||||
<a href="/" className="mt-4 inline-block text-sm text-muted hover:text-fg">
|
||||
Back to homepage
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Splash() {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center">
|
||||
<img src="/~/short.svg" alt="" className="size-10 animate-pulse rounded-lg" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const me = useApi<Me>("/me");
|
||||
const path = usePath();
|
||||
|
||||
if (me.error?.status === 401) return <Login />;
|
||||
if (me.error) {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center p-6 text-center">
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold">Can't reach the server</h1>
|
||||
<p className="mt-1 text-sm text-muted">{me.error.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!me.data) return <Splash />;
|
||||
|
||||
const logout = async () => {
|
||||
await fetch("/~/auth/logout", { method: "POST", credentials: "same-origin" });
|
||||
location.href = "/~/";
|
||||
};
|
||||
|
||||
const route = parseRoute(path);
|
||||
let screen;
|
||||
switch (route.name) {
|
||||
case "overview":
|
||||
screen = <OverviewScreen me={me.data} />;
|
||||
break;
|
||||
case "list":
|
||||
screen = <ListScreen key={route.kind} kind={route.kind} me={me.data} />;
|
||||
break;
|
||||
case "detail":
|
||||
screen = <DetailScreen key={route.id} id={route.id} kind={route.kind} tab={route.tab} me={me.data} />;
|
||||
break;
|
||||
case "tokens":
|
||||
screen = <TokensScreen />;
|
||||
break;
|
||||
case "admin":
|
||||
screen = me.data.isAdmin ? <AdminScreen /> : null;
|
||||
break;
|
||||
}
|
||||
|
||||
return (
|
||||
<Shell me={me.data} route={route} onLogout={logout}>
|
||||
{screen ?? (
|
||||
<EmptyState
|
||||
icon={<ArrowLeft />}
|
||||
title="Page not found"
|
||||
description="This part of the dashboard doesn't exist."
|
||||
action={
|
||||
<Link to="/~/" className={buttonClass("secondary")}>
|
||||
Go to overview
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react";
|
||||
import type { Me } from "../../shared/api-types.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Link } from "../components/ui/misc.js";
|
||||
import { cx } from "../lib/cx.js";
|
||||
import type { Route } from "../router.js";
|
||||
|
||||
type Section = "overview" | "links" | "pages" | "tokens" | "admin";
|
||||
|
||||
function sectionOf(route: Route): Section | null {
|
||||
switch (route.name) {
|
||||
case "overview":
|
||||
case "tokens":
|
||||
case "admin":
|
||||
return route.name;
|
||||
case "list":
|
||||
case "detail":
|
||||
return route.kind === "redirect" ? "links" : "pages";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const NAV: { id: Section; label: string; short: string; to: string; icon: ReactNode; adminOnly?: boolean }[] = [
|
||||
{ id: "overview", label: "Overview", short: "Overview", to: "/~/", icon: <LayoutDashboard /> },
|
||||
{ id: "links", label: "Short links", short: "Links", to: "/~/links", icon: <Link2 /> },
|
||||
{ id: "pages", label: "Link pages", short: "Pages", to: "/~/pages", icon: <PanelsTopLeft /> },
|
||||
{ id: "tokens", label: "API tokens", short: "Tokens", to: "/~/tokens", icon: <KeyRound /> },
|
||||
{ id: "admin", label: "Administration", short: "Admin", to: "/~/admin", icon: <ShieldCheck />, adminOnly: true },
|
||||
];
|
||||
|
||||
function Logo() {
|
||||
return (
|
||||
<Link to="/~/" className="flex items-center gap-2.5">
|
||||
<img src="/~/short.svg" alt="" className="size-7 rounded-md" />
|
||||
<span className="text-[15px] font-semibold tracking-tight text-fg">short</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function UserAvatar({ username }: { username: string }) {
|
||||
return (
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
|
||||
{username.charAt(0)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Shell({ me, route, onLogout, children }: { me: Me; route: Route; onLogout: () => void; children: ReactNode }) {
|
||||
const active = sectionOf(route);
|
||||
const items = NAV.filter((n) => !n.adminOnly || me.isAdmin);
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh lg:pl-64">
|
||||
{/* Desktop sidebar */}
|
||||
<aside className="fixed inset-y-0 left-0 hidden w-64 flex-col border-r border-border bg-surface lg:flex">
|
||||
<div className="flex h-16 items-center px-5">
|
||||
<Logo />
|
||||
</div>
|
||||
<nav className="flex flex-1 flex-col gap-0.5 px-3 py-2" aria-label="Main">
|
||||
{items.map((item) => (
|
||||
<Link
|
||||
key={item.id}
|
||||
to={item.to}
|
||||
aria-current={item.id === active ? "page" : undefined}
|
||||
className={cx(
|
||||
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors [&_svg]:size-4",
|
||||
item.id === active ? "bg-accent-soft text-accent-soft-fg" : "text-muted hover:bg-surface-2 hover:text-fg",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<div className="flex items-center gap-3 border-t border-border p-4">
|
||||
<UserAvatar username={me.username} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium text-fg">{me.username}</div>
|
||||
<div className="text-xs text-muted">{me.isAdmin ? "Administrator" : "User"}</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out" title="Sign out">
|
||||
<LogOut />
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Mobile top bar */}
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-border bg-surface/85 px-4 backdrop-blur lg:hidden">
|
||||
<Logo />
|
||||
<div className="flex items-center gap-1">
|
||||
<UserAvatar username={me.username} />
|
||||
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out">
|
||||
<LogOut />
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="mx-auto max-w-6xl px-4 pt-6 pb-28 sm:px-6 lg:px-10 lg:pt-10 lg:pb-12">{children}</main>
|
||||
|
||||
{/* Mobile tab bar */}
|
||||
<nav
|
||||
className="fixed inset-x-0 bottom-0 z-30 flex border-t border-border bg-surface/90 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden"
|
||||
aria-label="Main"
|
||||
>
|
||||
{items.map((item) => (
|
||||
<Link
|
||||
key={item.id}
|
||||
to={item.to}
|
||||
aria-current={item.id === active ? "page" : undefined}
|
||||
className={cx(
|
||||
"flex flex-1 flex-col items-center gap-1 py-2 text-[11px] font-medium [&_svg]:size-5",
|
||||
item.id === active ? "text-accent" : "text-muted",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
{item.short}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
|
||||
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import type { Block, PageSummary } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { useAction } from "./ui.js";
|
||||
|
||||
function SortableBlock({ block, onChange }: { block: Block; onChange: (blocks: Block[]) => void }) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id });
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [text, setText] = useState(block.kind === "text" ? (block.markdown ?? "") : (block.label ?? ""));
|
||||
const { busy, run } = useAction();
|
||||
|
||||
const save = () =>
|
||||
run(async () => {
|
||||
onChange(await api<Block[]>("PATCH", `/blocks/${block.id}`, block.kind === "text" ? { markdown: text } : { label: text }));
|
||||
setEditing(false);
|
||||
});
|
||||
const remove = () => run(async () => onChange(await api<Block[]>("DELETE", `/blocks/${block.id}`)));
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||
className={`flex items-start gap-3 rounded bg-gray-800 p-3 ${isDragging ? "relative z-10 opacity-80 shadow-lg" : ""}`}
|
||||
>
|
||||
<button className="cursor-grab touch-none px-1 text-gray-500" aria-label="Drag to reorder" {...attributes} {...listeners}>
|
||||
⠿
|
||||
</button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs text-gray-500 uppercase">{block.kind === "text" ? "Text" : `Link → ${block.target?.path}`}</div>
|
||||
{editing ? (
|
||||
block.kind === "text" ? (
|
||||
<textarea rows={4} value={text} onChange={(e) => setText(e.target.value)} />
|
||||
) : (
|
||||
<input value={text} onChange={(e) => setText(e.target.value)} />
|
||||
)
|
||||
) : (
|
||||
<div className="truncate whitespace-pre-wrap text-white">{block.kind === "text" ? block.markdown : block.label}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{editing ? (
|
||||
<button className="btn px-2 py-1 text-sm" onClick={save} disabled={busy}>
|
||||
Save
|
||||
</button>
|
||||
) : (
|
||||
<button className="btn btn-secondary px-2 py-1 text-sm" onClick={() => setEditing(true)}>
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
<button className="btn btn-danger px-2 py-1 text-sm" onClick={remove} disabled={busy}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BlockEditor({
|
||||
pageId,
|
||||
namespace,
|
||||
isAdmin,
|
||||
blocks,
|
||||
onChange,
|
||||
}: {
|
||||
pageId: number;
|
||||
namespace: string;
|
||||
isAdmin: boolean;
|
||||
blocks: Block[];
|
||||
onChange: (blocks: Block[]) => void;
|
||||
}) {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const { busy, run } = useAction();
|
||||
const [targetId, setTargetId] = useState("");
|
||||
const [label, setLabel] = useState("");
|
||||
const [markdown, setMarkdown] = useState("");
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
// Same rule as the server: own namespace only, unless admin.
|
||||
const targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (isAdmin || p.namespace === namespace));
|
||||
|
||||
const onDragEnd = ({ active, over }: DragEndEvent) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
const reordered = arrayMove(
|
||||
blocks,
|
||||
blocks.findIndex((b) => b.id === active.id),
|
||||
blocks.findIndex((b) => b.id === over.id),
|
||||
);
|
||||
onChange(reordered);
|
||||
void run(async () => onChange(await api<Block[]>("PUT", `/pages/${pageId}/blocks/order`, { ids: reordered.map((b) => b.id) })));
|
||||
};
|
||||
|
||||
const addLink = () =>
|
||||
run(async () => {
|
||||
onChange(await api<Block[]>("POST", `/pages/${pageId}/blocks`, { kind: "link", targetId: Number(targetId), label }));
|
||||
setTargetId("");
|
||||
setLabel("");
|
||||
});
|
||||
const addText = () =>
|
||||
run(async () => {
|
||||
onChange(await api<Block[]>("POST", `/pages/${pageId}/blocks`, { kind: "text", markdown }));
|
||||
setMarkdown("");
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<h2 className="mb-4">Blocks</h2>
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
|
||||
<SortableContext items={blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{blocks.map((b) => (
|
||||
<SortableBlock key={b.id} block={b} onChange={onChange} />
|
||||
))}
|
||||
{!blocks.length && <p className="text-gray-500">No blocks yet.</p>}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<div className="mt-6 grid gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<h3 className="mb-2 font-semibold text-white">Add link button</h3>
|
||||
<select value={targetId} onChange={(e) => setTargetId(e.target.value)} className="mb-2">
|
||||
<option value="">Choose a short link…</option>
|
||||
{targets.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.path} → {p.dest}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input className="mb-2" placeholder="Button label" value={label} onChange={(e) => setLabel(e.target.value)} />
|
||||
<button className="btn" onClick={addLink} disabled={busy || !targetId || !label.trim()}>
|
||||
Add link
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="mb-2 font-semibold text-white">Add text</h3>
|
||||
<textarea
|
||||
className="mb-2"
|
||||
rows={3}
|
||||
placeholder="**Markdown** is supported: bold, italic, links, lists, headings"
|
||||
value={markdown}
|
||||
onChange={(e) => setMarkdown(e.target.value)}
|
||||
/>
|
||||
<button className="btn" onClick={addText} disabled={busy || !markdown.trim()}>
|
||||
Add text
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState } from "react";
|
||||
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
||||
import { api, ApiRequestError, errorMessage, useApi } from "../api.js";
|
||||
import { Button } from "./ui/button.js";
|
||||
import { Dialog } from "./ui/dialog.js";
|
||||
import { Field, Input, PrefixInput, Select } from "./ui/form.js";
|
||||
|
||||
const COPY: Record<PageKind, { title: string; description: string; submit: string }> = {
|
||||
redirect: {
|
||||
title: "New short link",
|
||||
description: "Redirects visitors to another URL. You can change the destination later.",
|
||||
submit: "Create link",
|
||||
},
|
||||
linkpage: {
|
||||
title: "New link page",
|
||||
description: "A page with your avatar, link buttons and text — like a link in bio.",
|
||||
submit: "Create page",
|
||||
},
|
||||
};
|
||||
|
||||
export function CreatePageDialog({
|
||||
kind,
|
||||
me,
|
||||
open,
|
||||
onClose,
|
||||
onCreated,
|
||||
}: {
|
||||
kind: PageKind;
|
||||
me: Me;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCreated: (page: PageSummary) => void;
|
||||
}) {
|
||||
const users = useApi<string[]>(me.isAdmin && open ? "/users" : null);
|
||||
const [namespace, setNamespace] = useState(me.username);
|
||||
const [code, setCode] = useState("");
|
||||
const [value, setValue] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
const close = () => {
|
||||
setCode("");
|
||||
setValue("");
|
||||
setErrors({});
|
||||
onClose();
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
try {
|
||||
const page = await api<PageSummary>("POST", "/pages", {
|
||||
kind,
|
||||
namespace,
|
||||
...(code.trim() && { code: code.trim() }),
|
||||
...(kind === "redirect" ? { dest: value.trim() } : { title: value.trim() }),
|
||||
});
|
||||
close();
|
||||
onCreated(page);
|
||||
} catch (err) {
|
||||
const issues = err instanceof ApiRequestError ? err.issues : undefined;
|
||||
setErrors(
|
||||
issues
|
||||
? Object.fromEntries(Object.entries(issues).map(([k, v]) => [k, v.join(", ")]))
|
||||
: { form: errorMessage(err) },
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copy = COPY[kind];
|
||||
const prefix = namespace ? `/${namespace}/` : "/";
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
title={copy.title}
|
||||
description={copy.description}
|
||||
onSubmit={submit}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={close}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={busy}>
|
||||
{copy.submit}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{kind === "redirect" ? (
|
||||
<Field label="Destination URL" error={errors.dest}>
|
||||
{(id) => (
|
||||
<Input id={id} type="url" required autoFocus placeholder="https://example.com/very/long/url" value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
)}
|
||||
</Field>
|
||||
) : (
|
||||
<Field label="Title" error={errors.title}>
|
||||
{(id) => <Input id={id} required autoFocus placeholder="Jane Doe" value={value} onChange={(e) => setValue(e.target.value)} />}
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{me.isAdmin && (
|
||||
<Field label="Namespace" hint="Root links are only available to admins." error={errors.namespace}>
|
||||
{(id) => (
|
||||
<Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
|
||||
<option value="">Root (/)</option>
|
||||
{(users.data ?? [me.username]).map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{u === me.username ? `${u} (you)` : u}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
|
||||
<Field label="Shortcode" hint="Optional. Leave empty for a random 5-character code." error={errors.code}>
|
||||
{(id) => (
|
||||
<PrefixInput
|
||||
id={id}
|
||||
prefix={prefix}
|
||||
placeholder="random"
|
||||
pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{errors.form && <p className="text-sm text-danger">{errors.form}</p>}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import QRCode, { type QRCodeErrorCorrectionLevel } from "qrcode";
|
||||
|
||||
const LEVELS: QRCodeErrorCorrectionLevel[] = ["L", "M", "Q", "H"];
|
||||
|
||||
function download(href: string, filename: string) {
|
||||
const a = document.createElement("a");
|
||||
a.href = href;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
}
|
||||
|
||||
export function QrPanel({ url, name }: { url: string; name: string }) {
|
||||
const [level, setLevel] = useState<QRCodeErrorCorrectionLevel>("Q");
|
||||
const [dark, setDark] = useState("#000000");
|
||||
const [light, setLight] = useState("#ffffff");
|
||||
const [svg, setSvg] = useState("");
|
||||
|
||||
const options = { errorCorrectionLevel: level, margin: 2, color: { dark, light } };
|
||||
|
||||
useEffect(() => {
|
||||
QRCode.toString(url, { errorCorrectionLevel: level, margin: 2, color: { dark, light }, type: "svg" }).then(setSvg, () => setSvg(""));
|
||||
}, [url, level, dark, light]);
|
||||
|
||||
const downloadSvg = () => {
|
||||
const blobUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
|
||||
download(blobUrl, `${name}.svg`);
|
||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
|
||||
};
|
||||
const downloadPng = async () => download(await QRCode.toDataURL(url, { ...options, width: 1024 }), `${name}.png`);
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<h2 className="mb-4">QR code</h2>
|
||||
<div className="flex flex-wrap gap-6">
|
||||
<div
|
||||
className="h-40 w-40 overflow-hidden rounded [&>svg]:h-full [&>svg]:w-full"
|
||||
// The SVG markup is generated locally by the qrcode library.
|
||||
dangerouslySetInnerHTML={{ __html: svg }}
|
||||
/>
|
||||
<div className="flex flex-col gap-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
Error correction:
|
||||
{LEVELS.map((l) => (
|
||||
<button
|
||||
key={l}
|
||||
className={`cursor-pointer rounded px-2 ${l === level ? "bg-gray-600 text-white" : "text-gray-400"}`}
|
||||
onClick={() => setLevel(l)}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="flex items-center gap-3 normal-case">
|
||||
Foreground <input type="color" value={dark} onChange={(e) => setDark(e.target.value)} />
|
||||
</label>
|
||||
<label className="flex items-center gap-3 normal-case">
|
||||
Background <input type="color" value={light} onChange={(e) => setLight(e.target.value)} />
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button className="btn btn-secondary py-1" onClick={downloadSvg} disabled={!svg}>
|
||||
SVG
|
||||
</button>
|
||||
<button className="btn btn-secondary py-1" onClick={downloadPng}>
|
||||
PNG
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import uPlot from "uplot";
|
||||
import "uplot/dist/uPlot.min.css";
|
||||
import type { PageStats, StatsDay } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { useAction } from "./ui.js";
|
||||
|
||||
const RANGES = [7, 30, 90] as const;
|
||||
|
||||
function Chart({ series }: { series: StatsDay[] }) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = container.current;
|
||||
if (!el) return;
|
||||
const x = series.map((d) => new Date(`${d.day}T00:00:00`).getTime() / 1000);
|
||||
const axis = { stroke: "#9ca3af", grid: { stroke: "#1f2937" }, ticks: { stroke: "#1f2937" } };
|
||||
const plot = new uPlot(
|
||||
{
|
||||
width: el.clientWidth,
|
||||
height: 220,
|
||||
cursor: { drag: { x: false, y: false } },
|
||||
scales: { y: { range: (_u, _min, max) => [0, Math.max(4, Math.ceil(max * 1.1))] } },
|
||||
axes: [
|
||||
{
|
||||
...axis,
|
||||
// One tick per day (or week), labelled with the date only.
|
||||
incrs: [86400, 7 * 86400],
|
||||
values: (_u, ticks) =>
|
||||
ticks.map((t) => new Date(t * 1000).toLocaleDateString(undefined, { month: "short", day: "numeric" })),
|
||||
},
|
||||
{ ...axis, values: (_u, ticks) => ticks.map((t) => (Number.isInteger(t) ? String(t) : "")) },
|
||||
],
|
||||
series: [
|
||||
{},
|
||||
{ label: "Clicks", stroke: "#22c55e", width: 2, fill: "rgba(34,197,94,0.12)", points: { show: series.length <= 30 } },
|
||||
{ label: "Unique visitors", stroke: "#60a5fa", width: 2, points: { show: series.length <= 30 } },
|
||||
],
|
||||
},
|
||||
[x, series.map((d) => d.clicks), series.map((d) => d.uniques)],
|
||||
el,
|
||||
);
|
||||
const resize = new ResizeObserver(() => plot.setSize({ width: el.clientWidth, height: 220 }));
|
||||
resize.observe(el);
|
||||
return () => {
|
||||
resize.disconnect();
|
||||
plot.destroy();
|
||||
};
|
||||
}, [series]);
|
||||
|
||||
return <div ref={container} className="w-full" />;
|
||||
}
|
||||
|
||||
export function StatsPanel({ pageId }: { pageId: number }) {
|
||||
const [days, setDays] = useState<(typeof RANGES)[number]>(7);
|
||||
const stats = useApi<PageStats>(`/pages/${pageId}/stats?days=${days}`);
|
||||
const { busy, run } = useAction();
|
||||
|
||||
const reset = () => {
|
||||
if (!confirm("Delete all stats for this page?")) return;
|
||||
void run(async () => {
|
||||
await api("DELETE", `/pages/${pageId}/stats`);
|
||||
await stats.reload();
|
||||
}, "Stats reset");
|
||||
};
|
||||
|
||||
const s = stats.data;
|
||||
const tiles = s
|
||||
? [
|
||||
["Total clicks", s.total],
|
||||
["Clicks today", s.today],
|
||||
["Unique visitors today", s.uniquesToday],
|
||||
["Last visit", s.lastVisit ? new Date(s.lastVisit).toLocaleString() : "—"],
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<h2>Stats</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
{RANGES.map((r) => (
|
||||
<button key={r} className={`btn py-1 ${r === days ? "" : "btn-secondary"}`} onClick={() => setDays(r)}>
|
||||
{r}d
|
||||
</button>
|
||||
))}
|
||||
<button className="btn btn-danger py-1" onClick={reset} disabled={busy}>
|
||||
Reset
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{s && (
|
||||
<>
|
||||
<div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
{tiles.map(([label, value]) => (
|
||||
<div key={label} className="rounded bg-gray-900/60 p-3">
|
||||
<div className="text-xs text-gray-400 uppercase">{label}</div>
|
||||
<div className="text-lg font-semibold text-white">{value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Chart series={s.series} />
|
||||
<p className="mt-2 text-xs text-gray-500">
|
||||
Unique visitors are counted per day. Individual clicks are kept for 90 days, daily totals forever.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
import { LoaderCircle } from "lucide-react";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
|
||||
type Variant = "primary" | "secondary" | "ghost" | "danger";
|
||||
type Size = "sm" | "md" | "icon" | "icon-sm";
|
||||
|
||||
const variants: Record<Variant, string> = {
|
||||
primary: "bg-accent text-accent-fg shadow-sm hover:bg-accent-hover",
|
||||
secondary: "border border-border bg-surface text-fg shadow-xs hover:bg-surface-2",
|
||||
ghost: "text-muted hover:bg-surface-2 hover:text-fg",
|
||||
danger: "bg-danger text-white shadow-sm hover:bg-danger/90",
|
||||
};
|
||||
|
||||
const sizes: Record<Size, string> = {
|
||||
sm: "h-8 px-3 text-sm",
|
||||
md: "h-9 px-4 text-sm",
|
||||
icon: "size-9",
|
||||
"icon-sm": "size-8",
|
||||
};
|
||||
|
||||
export function buttonClass(variant: Variant = "primary", size: Size = "md", className?: string) {
|
||||
return cx(
|
||||
"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-lg font-medium whitespace-nowrap transition-colors",
|
||||
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-50",
|
||||
"[&_svg]:size-4 [&_svg]:shrink-0",
|
||||
variants[variant],
|
||||
sizes[size],
|
||||
className,
|
||||
);
|
||||
}
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: Variant;
|
||||
size?: Size;
|
||||
loading?: boolean;
|
||||
icon?: ReactNode;
|
||||
}
|
||||
|
||||
export function Button({ variant, size, loading, icon, className, children, disabled, type = "button", ...props }: ButtonProps) {
|
||||
return (
|
||||
<button type={type} className={buttonClass(variant, size, className)} disabled={disabled || loading} {...props}>
|
||||
{loading ? <LoaderCircle className="animate-spin" /> : icon}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
import { Button } from "./button.js";
|
||||
|
||||
// Modal dialog built on the native <dialog> element (focus trapping, Escape and top layer for free).
|
||||
export function Dialog({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
onSubmit,
|
||||
size = "md",
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
children?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
/** When set, the dialog body is a form and the footer buttons can submit it. */
|
||||
onSubmit?: (e: FormEvent) => void;
|
||||
size?: "sm" | "md";
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = ref.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) dialog.showModal();
|
||||
if (!open && dialog.open) dialog.close();
|
||||
}, [open]);
|
||||
|
||||
const Body = onSubmit ? "form" : "div";
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
onClose={onClose}
|
||||
onClick={(e) => e.target === ref.current && onClose()}
|
||||
className={cx(
|
||||
"m-auto w-[calc(100%-2rem)] rounded-2xl border border-border bg-surface p-0 text-fg shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-[2px] open:animate-pop-in",
|
||||
size === "sm" ? "max-w-md" : "max-w-lg",
|
||||
)}
|
||||
>
|
||||
{open && (
|
||||
<Body
|
||||
onSubmit={
|
||||
onSubmit &&
|
||||
((e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
onSubmit(e);
|
||||
})
|
||||
}
|
||||
>
|
||||
<div className={cx("flex items-start justify-between gap-4 px-6 pt-5", !children && "pb-5")}>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
{description && <p className="mt-1 text-sm text-muted">{description}</p>}
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onClose} aria-label="Close" className="-mr-2">
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
{children && <div className="flex flex-col gap-4 px-6 py-5">{children}</div>}
|
||||
{footer && <div className="flex justify-end gap-2 rounded-b-2xl border-t border-border bg-surface-2/50 px-6 py-3">{footer}</div>}
|
||||
</Body>
|
||||
)}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConfirmOptions {
|
||||
title: string;
|
||||
description?: ReactNode;
|
||||
confirmLabel?: string;
|
||||
danger?: boolean;
|
||||
}
|
||||
|
||||
const ConfirmContext = createContext<(options: ConfirmOptions) => Promise<boolean>>(async () => false);
|
||||
|
||||
// Promise-based replacement for window.confirm: `if (await confirm({...})) …`
|
||||
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<(ConfirmOptions & { resolve: (ok: boolean) => void }) | null>(null);
|
||||
|
||||
const confirm = useCallback((options: ConfirmOptions) => new Promise<boolean>((resolve) => setState({ ...options, resolve })), []);
|
||||
const close = (ok: boolean) => {
|
||||
state?.resolve(ok);
|
||||
setState(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfirmContext.Provider value={confirm}>
|
||||
{children}
|
||||
<Dialog
|
||||
open={!!state}
|
||||
onClose={() => close(false)}
|
||||
title={state?.title}
|
||||
description={state?.description}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => close(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant={state?.danger ? "danger" : "primary"} onClick={() => close(true)} autoFocus>
|
||||
{state?.confirmLabel ?? "Confirm"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</ConfirmContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useConfirm = () => useContext(ConfirmContext);
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useId, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes, type TextareaHTMLAttributes } from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
|
||||
export function Field({
|
||||
label,
|
||||
hint,
|
||||
error,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: ReactNode;
|
||||
error?: string;
|
||||
children: (id: string) => ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={cx("flex flex-col gap-1.5", className)}>
|
||||
<label htmlFor={id} className="text-sm font-medium text-fg">
|
||||
{label}
|
||||
</label>
|
||||
{children(id)}
|
||||
{error ? <p className="text-xs text-danger">{error}</p> : hint && <p className="text-xs text-muted">{hint}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||
return <input className={cx("control h-9", className)} {...props} />;
|
||||
}
|
||||
|
||||
// An input with a fixed, non-editable prefix such as "/alice/".
|
||||
export function PrefixInput({ prefix, className, ...props }: InputHTMLAttributes<HTMLInputElement> & { prefix: string }) {
|
||||
return (
|
||||
<div className="flex rounded-lg shadow-xs focus-within:ring-3 focus-within:ring-accent/20">
|
||||
<span className="flex max-w-[55%] items-center overflow-hidden rounded-l-lg border border-r-0 border-border bg-surface-2 px-3 font-mono text-xs text-muted">
|
||||
{prefix}
|
||||
</span>
|
||||
<input className={cx("control h-9 rounded-l-none font-mono shadow-none focus:ring-0", className)} {...props} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Textarea({ className, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||
return <textarea className={cx("control min-h-24 resize-y py-2", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function Select({ className, children, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<select className={cx("control h-9 cursor-pointer appearance-none pr-9", className)} {...props}>
|
||||
{children}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// A row of mutually exclusive options, e.g. "7d / 30d / 90d".
|
||||
export function Segmented<T extends string | number>({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
}: {
|
||||
value: T;
|
||||
options: { value: T; label: ReactNode }[];
|
||||
onChange: (value: T) => void;
|
||||
ariaLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<div role="radiogroup" aria-label={ariaLabel} className="inline-flex w-fit rounded-lg border border-border bg-surface-2 p-0.5">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={String(o.value)}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={o.value === value}
|
||||
onClick={() => onChange(o.value)}
|
||||
className={cx(
|
||||
"h-7 cursor-pointer rounded-md px-3 text-sm font-medium transition",
|
||||
o.value === value ? "bg-surface text-fg shadow-sm" : "text-muted hover:text-fg",
|
||||
)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorInput({ value, onChange, label }: { value: string; onChange: (value: string) => void; label: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-surface p-1 pr-3 shadow-xs">
|
||||
<label className="relative size-7 shrink-0 cursor-pointer overflow-hidden rounded-md border border-border" style={{ background: value }}>
|
||||
<span className="sr-only">{label}</span>
|
||||
<input type="color" value={value} onChange={(e) => onChange(e.target.value)} className="absolute inset-0 cursor-pointer opacity-0" />
|
||||
</label>
|
||||
<span className="font-mono text-xs text-muted uppercase">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
import { linkHandler } from "../../router.js";
|
||||
import { Button } from "./button.js";
|
||||
import { useToast } from "./toast.js";
|
||||
|
||||
export function Link({ to, className, children, ...rest }: { to: string; className?: string; children: ReactNode; "aria-current"?: "page" }) {
|
||||
return (
|
||||
<a href={to} onClick={linkHandler(to)} className={className} {...rest}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function publicUrl(path: string): string {
|
||||
return `${location.origin}${path}`;
|
||||
}
|
||||
|
||||
export function CopyButton({ value, label, size = "icon-sm" }: { value: string; label?: string; size?: "icon-sm" | "sm" }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const toast = useToast();
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
toast("Couldn't access the clipboard", true);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Button
|
||||
variant={label ? "secondary" : "ghost"}
|
||||
size={label ? "sm" : size}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
void copy();
|
||||
}}
|
||||
aria-label={label ?? "Copy"}
|
||||
title="Copy URL"
|
||||
icon={copied ? <Check className="text-success" /> : <Copy />}
|
||||
>
|
||||
{label && (copied ? "Copied" : label)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
// Website favicon placeholder: the first letter of the destination's hostname.
|
||||
export function DomainIcon({ url, className }: { url: string | null; className?: string }) {
|
||||
let host = "";
|
||||
try {
|
||||
host = url ? new URL(url).hostname.replace(/^www\./, "") : "";
|
||||
} catch {
|
||||
// Keep the placeholder.
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cx(
|
||||
"flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-surface-2 text-xs font-semibold text-muted uppercase",
|
||||
className,
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
{host.charAt(0) || "?"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Tabs({ tabs, active }: { tabs: { id: string; label: string; to: string; icon?: ReactNode }[]; active: string }) {
|
||||
return (
|
||||
<nav className="-mx-4 mb-6 overflow-x-auto border-b border-border px-4 sm:mx-0 sm:px-0" aria-label="Sections">
|
||||
<div className="flex gap-1">
|
||||
{tabs.map((t) => (
|
||||
<Link
|
||||
key={t.id}
|
||||
to={t.to}
|
||||
aria-current={t.id === active ? "page" : undefined}
|
||||
className={cx(
|
||||
"-mb-px flex items-center gap-2 border-b-2 px-3 py-2.5 text-sm font-medium whitespace-nowrap transition-colors [&_svg]:size-4",
|
||||
t.id === active ? "border-accent text-fg" : "border-transparent text-muted hover:border-border-strong hover:text-fg",
|
||||
)}
|
||||
>
|
||||
{t.icon}
|
||||
{t.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
export function Stat({ label, value, icon, hint }: { label: string; value: ReactNode; icon?: ReactNode; hint?: ReactNode }) {
|
||||
return (
|
||||
<div className="min-w-0 rounded-xl border border-border bg-surface p-3 shadow-xs sm:p-4">
|
||||
<div className="flex items-center justify-between gap-2 truncate text-xs text-muted sm:text-sm [&_svg]:hidden [&_svg]:size-4 sm:[&_svg]:block">
|
||||
{label}
|
||||
{icon}
|
||||
</div>
|
||||
<div className="mt-2 text-xl font-semibold tracking-tight text-fg tabular-nums sm:text-2xl">{value}</div>
|
||||
{hint && <div className="mt-1 truncate text-xs text-muted">{hint}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { AlertTriangle, Info } from "lucide-react";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
|
||||
export function Card({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <section className={cx("rounded-xl border border-border bg-surface shadow-xs", className)}>{children}</section>;
|
||||
}
|
||||
|
||||
export function CardHeader({ title, description, actions }: { title: ReactNode; description?: ReactNode; actions?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-start justify-between gap-3 border-border px-5 py-4 not-last:border-b">
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-base font-semibold text-fg">{title}</h2>
|
||||
{description && <p className="mt-0.5 text-sm text-muted">{description}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex items-center gap-2">{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardBody({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cx("p-5", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
export function CardFooter({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cx("flex items-center justify-end gap-2 rounded-b-xl border-t border-border bg-surface-2/50 px-5 py-3", className)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Tone = "neutral" | "accent" | "warning" | "danger" | "success";
|
||||
|
||||
const badgeTones: Record<Tone, string> = {
|
||||
neutral: "bg-surface-2 text-muted",
|
||||
accent: "bg-accent-soft text-accent-soft-fg",
|
||||
warning: "bg-warning-soft text-warning-soft-fg",
|
||||
danger: "bg-danger-soft text-danger-soft-fg",
|
||||
success: "bg-success/10 text-success",
|
||||
};
|
||||
|
||||
export function Badge({ tone = "neutral", children, icon }: { tone?: Tone; children: ReactNode; icon?: ReactNode }) {
|
||||
return (
|
||||
<span
|
||||
className={cx(
|
||||
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap [&_svg]:size-3",
|
||||
badgeTones[tone],
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Alert({ tone = "warning", title, children }: { tone?: "warning" | "info"; title: string; children?: ReactNode }) {
|
||||
const Icon = tone === "warning" ? AlertTriangle : Info;
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
"flex gap-3 rounded-xl border px-4 py-3 text-sm",
|
||||
tone === "warning" ? "border-warning-soft-fg/20 bg-warning-soft text-warning-soft-fg" : "border-accent/20 bg-accent-soft text-accent-soft-fg",
|
||||
)}
|
||||
>
|
||||
<Icon className="mt-0.5 size-4 shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium">{title}</p>
|
||||
{children && <div className="mt-1 opacity-90">{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ icon, title, description, action }: { icon: ReactNode; title: string; description?: string; action?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center px-6 py-14 text-center">
|
||||
<div className="mb-4 flex size-12 items-center justify-center rounded-xl bg-accent-soft text-accent-soft-fg [&_svg]:size-6">{icon}</div>
|
||||
<h3 className="font-semibold text-fg">{title}</h3>
|
||||
{description && <p className="mt-1 max-w-sm text-sm text-muted">{description}</p>}
|
||||
{action && <div className="mt-5">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Skeleton({ className }: { className?: string }) {
|
||||
return <div className={cx("animate-pulse rounded-md bg-surface-2", className)} />;
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
actions,
|
||||
breadcrumb,
|
||||
}: {
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
breadcrumb?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<header className="mb-6 flex flex-wrap items-end justify-between gap-4 lg:mb-8">
|
||||
<div className="min-w-0">
|
||||
{breadcrumb && <div className="mb-2 text-sm text-muted">{breadcrumb}</div>}
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-fg">{title}</h1>
|
||||
{description && <p className="mt-1 text-sm text-muted">{description}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,6 @@
|
||||
import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
|
||||
import { errorMessage } from "../api.js";
|
||||
import { linkHandler } from "../router.js";
|
||||
|
||||
export function Link({ to, className, children }: { to: string; className?: string; children: ReactNode }) {
|
||||
return (
|
||||
<a href={to} onClick={linkHandler(to)} className={className}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) {
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<label>{label}</label>
|
||||
{children}
|
||||
{hint && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { CircleAlert, CircleCheck } from "lucide-react";
|
||||
import { errorMessage } from "../../api.js";
|
||||
|
||||
type Toast = { id: number; message: string; error: boolean };
|
||||
const ToastContext = createContext<(message: string, error?: boolean) => void>(() => {});
|
||||
@@ -28,14 +10,22 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const show = useCallback((message: string, error = false) => {
|
||||
const id = Date.now() + Math.random();
|
||||
setToasts((t) => [...t, { id, message, error }]);
|
||||
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 3500);
|
||||
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), error ? 5000 : 3000);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={show}>
|
||||
{children}
|
||||
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="pointer-events-none fixed inset-x-0 bottom-20 z-50 flex flex-col items-center gap-2 px-4 lg:right-6 lg:bottom-6 lg:left-auto lg:items-end"
|
||||
>
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={`rounded px-4 py-2 text-white shadow-lg ${t.error ? "bg-red-800" : "bg-green-700"}`}>
|
||||
<div
|
||||
key={t.id}
|
||||
className="pointer-events-auto flex max-w-sm animate-pop-in items-center gap-2.5 rounded-xl border border-border bg-surface px-4 py-3 text-sm shadow-lg"
|
||||
>
|
||||
{t.error ? <CircleAlert className="size-4 shrink-0 text-danger" /> : <CircleCheck className="size-4 shrink-0 text-success" />}
|
||||
{t.message}
|
||||
</div>
|
||||
))}
|
||||
@@ -46,7 +36,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
export const useToast = () => useContext(ToastContext);
|
||||
|
||||
// Runs an async action with a busy flag and reports failures as a toast.
|
||||
// Runs an async action with a busy flag and reports the outcome as a toast.
|
||||
export function useAction() {
|
||||
const toast = useToast();
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -68,7 +58,3 @@ export function useAction() {
|
||||
);
|
||||
return { busy, run };
|
||||
}
|
||||
|
||||
export function publicUrl(path: string): string {
|
||||
return `${location.origin}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Joins class names, skipping falsy values.
|
||||
export function cx(...classes: (string | false | null | undefined)[]): string {
|
||||
return classes.filter(Boolean).join(" ");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Rough plain-text version of Markdown for compact previews in the editor.
|
||||
export function stripMarkdown(markdown: string): string {
|
||||
return markdown
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
||||
.replace(/[*_`#>~]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
+5
-69
@@ -1,80 +1,16 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Me } from "../shared/api-types.js";
|
||||
import { useApi } from "./api.js";
|
||||
import { Link, ToastProvider } from "./components/ui.js";
|
||||
import { usePath } from "./router.js";
|
||||
import { Dashboard } from "./screens/Dashboard.js";
|
||||
import { PageScreen } from "./screens/PageScreen.js";
|
||||
import { TokensScreen } from "./screens/TokensScreen.js";
|
||||
import { App } from "./app/App.js";
|
||||
import { ConfirmProvider } from "./components/ui/dialog.js";
|
||||
import { ToastProvider } from "./components/ui/toast.js";
|
||||
import "./styles.css";
|
||||
|
||||
function Login() {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-6 p-6 text-center">
|
||||
<img src="/~/short.svg" alt="" className="h-16 w-16" />
|
||||
<h1>short</h1>
|
||||
<a className="btn" href="/~/auth/login">
|
||||
Sign in
|
||||
</a>
|
||||
<a href="/" className="text-sm hover:underline">
|
||||
back to root
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
const me = useApi<Me>("/me");
|
||||
const path = usePath();
|
||||
|
||||
if (me.error?.status === 401) return <Login />;
|
||||
if (me.error) return <p className="p-10">Could not reach the server: {me.error.message}</p>;
|
||||
if (!me.data) return null;
|
||||
|
||||
const logout = async () => {
|
||||
await fetch("/~/auth/logout", { method: "POST", credentials: "same-origin" });
|
||||
location.href = "/~/";
|
||||
};
|
||||
|
||||
const pageMatch = path.match(/^\/~\/pages\/(\d+)$/);
|
||||
const screen = pageMatch ? (
|
||||
<PageScreen id={Number(pageMatch[1])} me={me.data} />
|
||||
) : path === "/~/tokens" ? (
|
||||
<TokensScreen />
|
||||
) : (
|
||||
<Dashboard me={me.data} />
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-8">
|
||||
<header className="mb-8 flex flex-wrap items-center justify-between gap-4">
|
||||
<Link to="/~/" className="flex items-center gap-3">
|
||||
<img src="/~/short.svg" alt="" className="h-8 w-8" />
|
||||
<h1>short</h1>
|
||||
</Link>
|
||||
<nav className="flex items-center gap-4 text-sm">
|
||||
<Link to="/~/tokens" className="hover:underline">
|
||||
API tokens
|
||||
</Link>
|
||||
<span className="text-gray-500">
|
||||
{me.data.username}
|
||||
{me.data.isAdmin && " (admin)"}
|
||||
</span>
|
||||
<button className="btn btn-secondary py-1" onClick={logout}>
|
||||
Sign out
|
||||
</button>
|
||||
</nav>
|
||||
</header>
|
||||
{screen}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<ToastProvider>
|
||||
<ConfirmProvider>
|
||||
<App />
|
||||
</ConfirmProvider>
|
||||
</ToastProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useSyncExternalStore, type MouseEvent } from "react";
|
||||
import type { PageKind } from "../shared/api-types.js";
|
||||
|
||||
// A tiny history-based router; the app only has a handful of screens under /~/.
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function navigate(to: string) {
|
||||
history.pushState(null, "", to);
|
||||
window.scrollTo({ top: 0 });
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
@@ -27,3 +29,35 @@ export function linkHandler(to: string) {
|
||||
navigate(to);
|
||||
};
|
||||
}
|
||||
|
||||
export type Route =
|
||||
| { name: "overview" }
|
||||
| { name: "list"; kind: PageKind }
|
||||
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined }
|
||||
| { name: "tokens" }
|
||||
| { name: "admin" }
|
||||
| { name: "notFound" };
|
||||
|
||||
const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" };
|
||||
|
||||
export function listPath(kind: PageKind): string {
|
||||
return kind === "redirect" ? "/~/links" : "/~/pages";
|
||||
}
|
||||
|
||||
export function detailPath(page: { id: number; kind: PageKind }, tab?: string): string {
|
||||
return `${listPath(page.kind)}/${page.id}${tab ? `/${tab}` : ""}`;
|
||||
}
|
||||
|
||||
export function parseRoute(path: string): Route {
|
||||
const p = path.replace(/\/+$/, "") || "/~";
|
||||
if (p === "/~") return { name: "overview" };
|
||||
if (p === "/~/tokens") return { name: "tokens" };
|
||||
if (p === "/~/admin") return { name: "admin" };
|
||||
const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/);
|
||||
if (m) {
|
||||
const kind = KIND_SEGMENT[m[1]!]!;
|
||||
if (!m[2]) return { name: "list", kind };
|
||||
return { name: "detail", kind, id: Number(m[2]), tab: m[3] };
|
||||
}
|
||||
return { name: "notFound" };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { PinOff, TriangleAlert, Users } from "lucide-react";
|
||||
import type { Conflict, PageSummary } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Select } from "../components/ui/form.js";
|
||||
import { Link } from "../components/ui/misc.js";
|
||||
import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
|
||||
import { useAction } from "../components/ui/toast.js";
|
||||
import { detailPath } from "../router.js";
|
||||
|
||||
function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) {
|
||||
const pinned = pages.find((p) => p.pinned);
|
||||
const [selected, setSelected] = useState(pinned ? String(pinned.id) : "");
|
||||
const { busy, run } = useAction();
|
||||
|
||||
useEffect(() => setSelected(pinned ? String(pinned.id) : ""), [pinned]);
|
||||
|
||||
const save = () =>
|
||||
run(async () => {
|
||||
if (selected) await api("PUT", "/pin", { pageId: Number(selected) });
|
||||
else await api("DELETE", "/pin");
|
||||
await reload();
|
||||
}, selected ? "Homepage updated" : "Homepage cleared");
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader title="Homepage" description="Where visitors land when they open the bare domain." />
|
||||
<CardBody className="flex flex-col gap-3 sm:flex-row">
|
||||
<div className="flex-1">
|
||||
<Select aria-label="Homepage" value={selected} onChange={(e) => setSelected(e.target.value)}>
|
||||
<option value="">Default landing page</option>
|
||||
{pages.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.path} — {p.kind === "redirect" ? p.dest : p.title}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{pinned && (
|
||||
<Button variant="secondary" icon={<PinOff />} onClick={() => setSelected("")}>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => void save()} loading={busy} disabled={selected === (pinned ? String(pinned.id) : "")}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function AdminScreen() {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const users = useApi<string[]>("/users");
|
||||
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 (
|
||||
<>
|
||||
<PageHeader title="Administration" description="Settings that affect the whole instance." />
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
{pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />}
|
||||
|
||||
<Card>
|
||||
<CardHeader
|
||||
title="Username conflicts"
|
||||
description="Root links whose code matches a username. Users never get /username itself, but it's confusing."
|
||||
/>
|
||||
{!conflicts.data ? (
|
||||
<Skeleton className="m-5 h-10" />
|
||||
) : conflicts.data.length ? (
|
||||
<ul className="divide-y divide-border">
|
||||
{conflicts.data.map((c) => (
|
||||
<li key={c.pageId} className="flex items-center gap-3 px-5 py-3">
|
||||
<TriangleAlert className="size-4 text-warning-soft-fg" />
|
||||
<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">
|
||||
Open root link
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<CardBody className="text-sm text-muted">No conflicts.</CardBody>
|
||||
)}
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import type { Conflict, Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { Field, Link, publicUrl, useAction, useToast } from "../components/ui.js";
|
||||
import { navigate } from "../router.js";
|
||||
|
||||
function CreateForm({ me, onCreated }: { me: Me; onCreated: () => void }) {
|
||||
const users = useApi<string[]>(me.isAdmin ? "/users" : null);
|
||||
const { busy, run } = useAction();
|
||||
const [kind, setKind] = useState<PageKind>("redirect");
|
||||
const [namespace, setNamespace] = useState(me.username);
|
||||
const [code, setCode] = useState("");
|
||||
const [value, setValue] = useState("");
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
void run(async () => {
|
||||
const body = {
|
||||
kind,
|
||||
namespace,
|
||||
...(code.trim() && { code: code.trim() }),
|
||||
...(kind === "redirect" ? { dest: value.trim() } : { title: value.trim() }),
|
||||
};
|
||||
const page = await api<PageSummary>("POST", "/pages", body);
|
||||
setCode("");
|
||||
setValue("");
|
||||
if (page.kind === "linkpage") navigate(`/~/pages/${page.id}`);
|
||||
else {
|
||||
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
|
||||
onCreated();
|
||||
}
|
||||
}, kind === "redirect" ? "Link created and copied" : "Link page created");
|
||||
};
|
||||
|
||||
const prefix = namespace ? `/${namespace}/` : "/";
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="card mb-10">
|
||||
<div className="mb-4 flex gap-2">
|
||||
{(["redirect", "linkpage"] as const).map((k) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
className={`btn py-1 ${kind === k ? "" : "btn-secondary"}`}
|
||||
onClick={() => setKind(k)}
|
||||
>
|
||||
{k === "redirect" ? "Short link" : "Link page"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid gap-x-4 sm:grid-cols-[auto_1fr]">
|
||||
{me.isAdmin && (
|
||||
<Field label="Namespace">
|
||||
<select value={namespace} onChange={(e) => setNamespace(e.target.value)}>
|
||||
<option value="">/ (root)</option>
|
||||
{(users.data ?? [me.username]).map((u) => (
|
||||
<option key={u} value={u}>
|
||||
/{u}/
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Shortcode" hint={`${prefix}${code || "…"} — leave empty for a random code`}>
|
||||
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="random" pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}" />
|
||||
</Field>
|
||||
</div>
|
||||
<Field label={kind === "redirect" ? "Destination URL" : "Title"}>
|
||||
<input
|
||||
required
|
||||
type={kind === "redirect" ? "url" : "text"}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder={kind === "redirect" ? "https://…" : "My links"}
|
||||
/>
|
||||
</Field>
|
||||
<button className="btn mt-2" disabled={busy}>
|
||||
Create
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function PageRow({ page }: { page: PageSummary }) {
|
||||
const toast = useToast();
|
||||
const copy = async () => {
|
||||
await navigator.clipboard.writeText(publicUrl(page.path));
|
||||
toast("Copied");
|
||||
};
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded px-3 py-3 odd:bg-gray-800/60">
|
||||
<Link to={`/~/pages/${page.id}`} className="min-w-0 flex-1">
|
||||
<div className="truncate font-semibold text-white">
|
||||
{page.path}
|
||||
{page.pinned && <span className="ml-2 rounded bg-yellow-700 px-1.5 text-xs">pinned to /</span>}
|
||||
</div>
|
||||
<div className="truncate text-sm text-gray-400">{page.kind === "redirect" ? page.dest : page.title}</div>
|
||||
</Link>
|
||||
<span className="text-sm whitespace-nowrap text-gray-400">{page.totalClicks} clicks</span>
|
||||
<button className="btn btn-secondary px-2 py-1 text-sm" onClick={copy} title="Copy URL">
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Dashboard({ me }: { me: Me }) {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null);
|
||||
const [filter, setFilter] = useState("");
|
||||
|
||||
const visible = (pages.data ?? []).filter(
|
||||
(p) => !filter || p.path.toLowerCase().includes(filter.toLowerCase()) || (p.dest ?? p.title ?? "").toLowerCase().includes(filter.toLowerCase()),
|
||||
);
|
||||
const links = visible.filter((p) => p.kind === "redirect");
|
||||
const linkPages = visible.filter((p) => p.kind === "linkpage");
|
||||
|
||||
return (
|
||||
<>
|
||||
{!!conflicts.data?.length && (
|
||||
<div className="mb-6 rounded border border-yellow-700 bg-yellow-900/30 p-4 text-sm">
|
||||
<strong>Username conflicts:</strong>{" "}
|
||||
{conflicts.data.map((c, i) => (
|
||||
<span key={c.pageId}>
|
||||
{i > 0 && ", "}
|
||||
<Link to={`/~/pages/${c.pageId}`} className="underline">
|
||||
/{c.username}
|
||||
</Link>
|
||||
</span>
|
||||
))}{" "}
|
||||
{conflicts.data.length === 1 ? "is" : "are"} both a root link and a username. Consider renaming the root link.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h2 className="mb-3">Create</h2>
|
||||
<CreateForm me={me} onCreated={() => void pages.reload()} />
|
||||
|
||||
<div className="mb-3 flex items-center justify-between gap-4">
|
||||
<h2>Pages</h2>
|
||||
<input className="max-w-xs" placeholder="Filter…" value={filter} onChange={(e) => setFilter(e.target.value)} />
|
||||
</div>
|
||||
{pages.error && <p className="text-red-400">{pages.error.message}</p>}
|
||||
|
||||
<h3 className="mt-6 mb-2 text-sm font-bold text-gray-400 uppercase">Link pages</h3>
|
||||
{linkPages.length ? linkPages.map((p) => <PageRow key={p.id} page={p} />) : <p className="text-gray-500">None yet.</p>}
|
||||
|
||||
<h3 className="mt-6 mb-2 text-sm font-bold text-gray-400 uppercase">Short links</h3>
|
||||
{links.length ? links.map((p) => <PageRow key={p.id} page={p} />) : <p className="text-gray-500">None yet.</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { ChevronRight, Link2, PanelsTopLeft, Pin, Plus, Search } 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 { Button } from "../components/ui/button.js";
|
||||
import { Input, Select } from "../components/ui/form.js";
|
||||
import { CopyButton, DomainIcon, Link, publicUrl } from "../components/ui/misc.js";
|
||||
import { Badge, Card, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
|
||||
import { useToast } from "../components/ui/toast.js";
|
||||
import { detailPath, navigate } from "../router.js";
|
||||
|
||||
const COPY: Record<PageKind, { title: string; description: string; create: string; empty: string; emptyText: string }> = {
|
||||
redirect: {
|
||||
title: "Short links",
|
||||
description: "Short URLs that redirect to another address.",
|
||||
create: "New short link",
|
||||
empty: "No short links yet",
|
||||
emptyText: "Create your first short link to share long URLs and track clicks.",
|
||||
},
|
||||
linkpage: {
|
||||
title: "Link pages",
|
||||
description: "Pages that collect several links, like a link in bio.",
|
||||
create: "New link page",
|
||||
empty: "No link pages yet",
|
||||
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 }) {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const toast = useToast();
|
||||
const [query, setQuery] = useState("");
|
||||
const [namespace, setNamespace] = useState<string | null>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
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) => {
|
||||
if (page.kind === "linkpage") return navigate(detailPath(page));
|
||||
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
|
||||
toast(`Created ${page.path} — copied to clipboard`);
|
||||
void pages.reload();
|
||||
};
|
||||
|
||||
const createButton = (
|
||||
<Button icon={<Plus />} onClick={() => setCreating(true)}>
|
||||
{copy.create}
|
||||
</Button>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={copy.title} description={copy.description} actions={createButton} />
|
||||
|
||||
<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>
|
||||
{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} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useState } from "react";
|
||||
import { ArrowRight, Link2, MousePointerClick, PanelsTopLeft, Plus, TrendingUp } from "lucide-react";
|
||||
import type { Conflict, Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
||||
import { useApi } from "../api.js";
|
||||
import { CreatePageDialog } from "../components/CreatePageDialog.js";
|
||||
import { Button, buttonClass } from "../components/ui/button.js";
|
||||
import { DomainIcon, Link, Stat } from "../components/ui/misc.js";
|
||||
import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
|
||||
import { detailPath, navigate } from "../router.js";
|
||||
|
||||
function TopPages({ pages }: { pages: PageSummary[] }) {
|
||||
const top = pages.filter((p) => p.totalClicks > 0).sort((a, b) => b.totalClicks - a.totalClicks).slice(0, 6);
|
||||
const max = Math.max(1, ...top.map((p) => p.totalClicks));
|
||||
|
||||
if (!top.length) {
|
||||
return <EmptyState icon={<TrendingUp />} title="No clicks yet" description="Once people open your links, the most visited ones show up here." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-border">
|
||||
{top.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link to={detailPath(p, "analytics")} className="flex items-center gap-3 px-5 py-3 transition-colors hover:bg-surface-2/60">
|
||||
{p.kind === "redirect" ? (
|
||||
<DomainIcon url={p.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 flex-1">
|
||||
<div className="truncate font-mono text-sm font-medium">{p.path}</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full bg-accent" style={{ width: `${(p.totalClicks / max) * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<span className="w-14 text-right text-sm text-muted tabular-nums">{p.totalClicks.toLocaleString()}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export function OverviewScreen({ me }: { me: Me }) {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null);
|
||||
const [creating, setCreating] = useState<PageKind | null>(null);
|
||||
|
||||
const all = pages.data ?? [];
|
||||
const links = all.filter((p) => p.kind === "redirect");
|
||||
const linkPages = all.filter((p) => p.kind === "linkpage");
|
||||
const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0);
|
||||
const scope = me.isAdmin ? "across all namespaces" : `in /${me.username}/`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={`Hi, ${me.username}`}
|
||||
description="Here's how your links are doing."
|
||||
actions={
|
||||
<>
|
||||
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
|
||||
New link page
|
||||
</Button>
|
||||
<Button icon={<Plus />} onClick={() => setCreating("redirect")}>
|
||||
New short link
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
{!!conflicts.data?.length && (
|
||||
<Alert title="Username conflicts">
|
||||
{conflicts.data.map((c, i) => (
|
||||
<span key={c.pageId}>
|
||||
{i > 0 && ", "}
|
||||
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="font-mono underline">
|
||||
/{c.username}
|
||||
</Link>
|
||||
</span>
|
||||
))}{" "}
|
||||
{conflicts.data.length === 1 ? "is" : "are"} both a root link and a username. Consider deleting or recreating the root link under another code.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-3 sm:gap-4">
|
||||
{pages.data ? (
|
||||
<>
|
||||
<Stat label="Short links" value={links.length} icon={<Link2 />} hint={scope} />
|
||||
<Stat label="Link pages" value={linkPages.length} icon={<PanelsTopLeft />} hint={scope} />
|
||||
<Stat label="Total clicks" value={clicks.toLocaleString()} icon={<MousePointerClick />} hint="all time" />
|
||||
</>
|
||||
) : (
|
||||
[0, 1, 2].map((i) => <Skeleton key={i} className="h-28 rounded-xl" />)
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader
|
||||
title="Most visited"
|
||||
description="All-time clicks"
|
||||
actions={
|
||||
<Link to="/~/links" className={buttonClass("ghost", "sm")}>
|
||||
All links <ArrowRight />
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
{pages.data ? <TopPages pages={all} /> : <Skeleton className="m-5 h-40" />}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{creating && (
|
||||
<CreatePageDialog
|
||||
kind={creating}
|
||||
me={me}
|
||||
open
|
||||
onClose={() => setCreating(null)}
|
||||
onCreated={(page) => navigate(detailPath(page))}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import type { Me, PageDetail } from "../../shared/api-types.js";
|
||||
import type { Theme } from "../../shared/validation.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { BlockEditor } from "../components/BlockEditor.js";
|
||||
import { QrPanel } from "../components/QrPanel.js";
|
||||
import { StatsPanel } from "../components/StatsPanel.js";
|
||||
import { Field, Link, publicUrl, useAction, useToast } from "../components/ui.js";
|
||||
import { navigate } from "../router.js";
|
||||
|
||||
const THEME_FIELDS: [keyof Theme, string][] = [
|
||||
["background", "Background"],
|
||||
["text", "Text"],
|
||||
["button", "Button"],
|
||||
["buttonText", "Button text"],
|
||||
];
|
||||
|
||||
function RedirectSettings({ page, onSaved }: { page: PageDetail; onSaved: (p: PageDetail) => void }) {
|
||||
const [dest, setDest] = useState(page.dest ?? "");
|
||||
const { busy, run } = useAction();
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
void run(async () => onSaved(await api<PageDetail>("PATCH", `/pages/${page.id}`, { dest })), "Saved");
|
||||
};
|
||||
return (
|
||||
<form className="card" onSubmit={submit}>
|
||||
<Field label="Destination URL">
|
||||
<input type="url" required value={dest} onChange={(e) => setDest(e.target.value)} />
|
||||
</Field>
|
||||
<button className="btn" disabled={busy || dest === page.dest}>
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function LinkPageSettings({ page, onSaved }: { page: PageDetail; onSaved: (p: PageDetail) => void }) {
|
||||
const [title, setTitle] = useState(page.title ?? "");
|
||||
const [theme, setTheme] = useState(page.theme);
|
||||
const { busy, run } = useAction();
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
void run(async () => onSaved(await api<PageDetail>("PATCH", `/pages/${page.id}`, { title, theme })), "Saved");
|
||||
};
|
||||
|
||||
const upload = (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
void run(async () => {
|
||||
const { avatarUrl } = await api<{ avatarUrl: string }>("PUT", `/pages/${page.id}/avatar`, form);
|
||||
onSaved({ ...page, avatarUrl });
|
||||
}, "Avatar updated");
|
||||
};
|
||||
const removeAvatar = () =>
|
||||
run(async () => {
|
||||
await api("DELETE", `/pages/${page.id}/avatar`);
|
||||
onSaved({ ...page, avatarUrl: null });
|
||||
});
|
||||
|
||||
return (
|
||||
<form className="card" onSubmit={submit}>
|
||||
<div className="mb-4 flex items-center gap-4">
|
||||
{page.avatarUrl ? (
|
||||
<img src={page.avatarUrl} alt="" className="h-16 w-16 rounded-full object-cover" />
|
||||
) : (
|
||||
<div className="h-16 w-16 rounded-full bg-gray-700" />
|
||||
)}
|
||||
<label className="btn btn-secondary mb-0 cursor-pointer py-1 text-base font-medium tracking-normal normal-case">
|
||||
Upload avatar
|
||||
<input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => upload(e.target.files?.[0])} />
|
||||
</label>
|
||||
{page.avatarUrl && (
|
||||
<button type="button" className="btn btn-secondary py-1" onClick={removeAvatar}>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Field label="Title">
|
||||
<input required value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
</Field>
|
||||
<div className="mb-4 flex flex-wrap gap-6">
|
||||
{THEME_FIELDS.map(([key, label]) => (
|
||||
<label key={key} className="flex items-center gap-2 normal-case">
|
||||
<input type="color" value={theme[key]} onChange={(e) => setTheme({ ...theme, [key]: e.target.value })} />
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<button className="btn" disabled={busy}>
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageScreen({ id, me }: { id: number; me: Me }) {
|
||||
const page = useApi<PageDetail>(`/pages/${id}`);
|
||||
const toast = useToast();
|
||||
const { busy, run } = useAction();
|
||||
const [previewKey, setPreviewKey] = useState(0);
|
||||
|
||||
// Reload the preview whenever the page changes.
|
||||
useEffect(() => setPreviewKey((k) => k + 1), [page.data]);
|
||||
|
||||
if (page.error) {
|
||||
return (
|
||||
<p>
|
||||
{page.error.status === 404 ? "Page not found." : page.error.message}{" "}
|
||||
<Link to="/~/" className="underline">
|
||||
Back
|
||||
</Link>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const p = page.data;
|
||||
if (!p) return null;
|
||||
const url = publicUrl(p.path);
|
||||
|
||||
const remove = () => {
|
||||
if (!confirm(`Delete ${p.path}? Its stats and any buttons pointing to it are removed too.`)) return;
|
||||
void run(async () => {
|
||||
await api("DELETE", `/pages/${p.id}`);
|
||||
navigate("/~/");
|
||||
}, "Deleted");
|
||||
};
|
||||
const togglePin = () =>
|
||||
run(async () => {
|
||||
if (p.pinned) await api("DELETE", "/pin");
|
||||
else await api("PUT", "/pin", { pageId: p.id });
|
||||
await page.reload();
|
||||
}, p.pinned ? "Unpinned" : "Pinned to /");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<Link to="/~/" className="text-sm text-gray-400 hover:underline">
|
||||
← All pages
|
||||
</Link>
|
||||
<h1 className="truncate">{p.path}</h1>
|
||||
<p className="text-sm text-gray-400">{p.kind === "redirect" ? "Short link" : "Link page"}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<a className="btn btn-secondary" href={p.path} target="_blank" rel="noreferrer">
|
||||
Open
|
||||
</a>
|
||||
<button className="btn btn-secondary" onClick={() => navigator.clipboard.writeText(url).then(() => toast("Copied"))}>
|
||||
Copy URL
|
||||
</button>
|
||||
{me.isAdmin && (
|
||||
<button className="btn btn-secondary" onClick={togglePin} disabled={busy}>
|
||||
{p.pinned ? "Unpin from /" : "Pin to /"}
|
||||
</button>
|
||||
)}
|
||||
<button className="btn btn-danger" onClick={remove} disabled={busy}>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{p.kind === "redirect" ? (
|
||||
<RedirectSettings page={p} onSaved={page.set} />
|
||||
) : (
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_320px]">
|
||||
<div className="flex flex-col gap-6">
|
||||
<LinkPageSettings key={p.id} page={p} onSaved={page.set} />
|
||||
<BlockEditor
|
||||
pageId={p.id}
|
||||
namespace={p.namespace}
|
||||
isAdmin={me.isAdmin}
|
||||
blocks={p.blocks}
|
||||
onChange={(blocks) => page.set({ ...p, blocks })}
|
||||
/>
|
||||
</div>
|
||||
<div className="hidden lg:block">
|
||||
<h2 className="mb-2">Preview</h2>
|
||||
<iframe key={previewKey} src={`${p.path}?preview`} title="Preview" className="h-[640px] w-full rounded-lg border border-gray-700" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<QrPanel url={url} name={p.code} />
|
||||
<StatsPanel pageId={p.id} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,103 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useState } from "react";
|
||||
import { KeyRound, Plus, Trash2 } from "lucide-react";
|
||||
import type { ApiToken, CreatedToken } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { Field, useAction, useToast } from "../components/ui.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Dialog, useConfirm } from "../components/ui/dialog.js";
|
||||
import { Field, Input } from "../components/ui/form.js";
|
||||
import { CopyButton } from "../components/ui/misc.js";
|
||||
import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
|
||||
import { useAction } from "../components/ui/toast.js";
|
||||
|
||||
function relative(date: string): string {
|
||||
const seconds = (new Date(date).getTime() - Date.now()) / 1000;
|
||||
const units: [Intl.RelativeTimeFormatUnit, number][] = [
|
||||
["year", 31536000],
|
||||
["month", 2592000],
|
||||
["day", 86400],
|
||||
["hour", 3600],
|
||||
["minute", 60],
|
||||
];
|
||||
const fmt = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" });
|
||||
for (const [unit, size] of units) {
|
||||
if (Math.abs(seconds) >= size) return fmt.format(Math.round(seconds / size), unit);
|
||||
}
|
||||
return "just now";
|
||||
}
|
||||
|
||||
function CreateTokenDialog({ open, onClose, onCreated }: { open: boolean; onClose: () => void; onCreated: () => void }) {
|
||||
const [name, setName] = useState("");
|
||||
const [created, setCreated] = useState<CreatedToken | null>(null);
|
||||
const { busy, run } = useAction();
|
||||
|
||||
const close = () => {
|
||||
setName("");
|
||||
setCreated(null);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (created) {
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
title="Token created"
|
||||
description={`"${created.name}" is ready to use.`}
|
||||
footer={<Button onClick={close}>Done</Button>}
|
||||
>
|
||||
<Alert title="Copy it now">You won't be able to see this token again.</Alert>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 overflow-x-auto rounded-lg bg-surface-2 px-3 py-2 font-mono text-sm whitespace-nowrap">{created.token}</code>
|
||||
<CopyButton value={created.token} label="Copy" />
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
title="New API token"
|
||||
description="The token can do everything you can do in this dashboard."
|
||||
onSubmit={() =>
|
||||
void run(async () => {
|
||||
setCreated(await api<CreatedToken>("POST", "/tokens", { name }));
|
||||
onCreated();
|
||||
})
|
||||
}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={close}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={busy} disabled={!name.trim()}>
|
||||
Create token
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Field label="Name" hint="Something to recognize it by, e.g. where it's used.">
|
||||
{(id) => <Input id={id} required autoFocus placeholder="iPhone Shortcut" value={name} onChange={(e) => setName(e.target.value)} />}
|
||||
</Field>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function TokensScreen() {
|
||||
const tokens = useApi<ApiToken[]>("/tokens");
|
||||
const { busy, run } = useAction();
|
||||
const toast = useToast();
|
||||
const [name, setName] = useState("");
|
||||
const [created, setCreated] = useState<CreatedToken | null>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const { run } = useAction();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const create = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
void run(async () => {
|
||||
setCreated(await api<CreatedToken>("POST", "/tokens", { name }));
|
||||
setName("");
|
||||
await tokens.reload();
|
||||
const revoke = async (t: ApiToken) => {
|
||||
const ok = await confirm({
|
||||
title: `Revoke "${t.name}"?`,
|
||||
description: "Scripts using this token stop working immediately.",
|
||||
confirmLabel: "Revoke",
|
||||
danger: true,
|
||||
});
|
||||
};
|
||||
const revoke = (t: ApiToken) => {
|
||||
if (!confirm(`Revoke "${t.name}"? Scripts using it stop working.`)) return;
|
||||
if (ok)
|
||||
void run(async () => {
|
||||
await api("DELETE", `/tokens/${t.id}`);
|
||||
await tokens.reload();
|
||||
@@ -31,61 +109,54 @@ export function TokensScreen() {
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"kind":"redirect","dest":"https://example.com"}'`;
|
||||
|
||||
const createButton = (
|
||||
<Button icon={<Plus />} onClick={() => setCreating(true)}>
|
||||
New token
|
||||
</Button>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title="API tokens" description="Create links from scripts, automations or iOS Shortcuts." actions={createButton} />
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
<h1>API tokens</h1>
|
||||
<p className="text-sm text-gray-400">Tokens act with your permissions. Use them for scripts or iOS Shortcuts.</p>
|
||||
|
||||
<form className="card" onSubmit={create}>
|
||||
<Field label="Name">
|
||||
<input required value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. iPhone Shortcut" />
|
||||
</Field>
|
||||
<button className="btn" disabled={busy}>
|
||||
Create token
|
||||
</button>
|
||||
{created && (
|
||||
<div className="mt-4 rounded border border-green-700 bg-green-900/30 p-3">
|
||||
<p className="mb-2 text-sm">Copy this token now. It won't be shown again.</p>
|
||||
<div className="flex gap-2">
|
||||
<code className="flex-1 overflow-x-auto rounded bg-gray-900 px-2 py-1">{created.token}</code>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary py-1"
|
||||
onClick={() => navigator.clipboard.writeText(created.token).then(() => toast("Copied"))}
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
<Card className="overflow-hidden">
|
||||
{!tokens.data ? (
|
||||
<div className="flex flex-col gap-3 p-5">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : tokens.data.length ? (
|
||||
<ul className="divide-y divide-border">
|
||||
{tokens.data.map((t) => (
|
||||
<li key={t.id} className="flex items-center gap-3 px-5 py-3.5">
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted">
|
||||
<KeyRound className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{t.name}</div>
|
||||
<div className="text-xs text-muted">
|
||||
Created {relative(t.createdAt)} · {t.lastUsedAt ? `last used ${relative(t.lastUsedAt)}` : "never used"}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
|
||||
<section className="card">
|
||||
<h2 className="mb-3">Your tokens</h2>
|
||||
{tokens.data?.length ? (
|
||||
tokens.data.map((t) => (
|
||||
<div key={t.id} className="flex items-center justify-between gap-3 border-b border-gray-700 py-2 last:border-0">
|
||||
<div>
|
||||
<div className="font-semibold text-white">{t.name}</div>
|
||||
<div className="text-xs text-gray-400">
|
||||
created {new Date(t.createdAt).toLocaleDateString()} · last used{" "}
|
||||
{t.lastUsedAt ? new Date(t.lastUsedAt).toLocaleString() : "never"}
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn btn-danger py-1" onClick={() => revoke(t)} disabled={busy}>
|
||||
<Button variant="ghost" size="sm" icon={<Trash2 />} onClick={() => void revoke(t)} className="hover:text-danger">
|
||||
Revoke
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-gray-500">No tokens yet.</p>
|
||||
<EmptyState icon={<KeyRound />} title="No tokens yet" description="Tokens let scripts use the API on your behalf." action={createButton} />
|
||||
)}
|
||||
</section>
|
||||
</Card>
|
||||
|
||||
<section className="card">
|
||||
<h2 className="mb-3">Example</h2>
|
||||
<pre className="overflow-x-auto rounded bg-gray-900 p-3 text-sm">{example}</pre>
|
||||
</section>
|
||||
<Card>
|
||||
<CardHeader title="Example" description="Create a short link with a random code." actions={<CopyButton value={example} />} />
|
||||
<pre className="overflow-x-auto p-5 font-mono text-[13px] leading-relaxed text-muted">{example}</pre>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<CreateTokenDialog open={creating} onClose={() => setCreating(false)} onCreated={() => void tokens.reload()} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import uPlot from "uplot";
|
||||
import "uplot/dist/uPlot.min.css";
|
||||
import { CalendarClock, MousePointerClick, RotateCcw, Sun, Users } from "lucide-react";
|
||||
import type { PageStats, StatsDay } from "../../../shared/api-types.js";
|
||||
import { api, useApi } from "../../api.js";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { useConfirm } from "../../components/ui/dialog.js";
|
||||
import { Segmented } from "../../components/ui/form.js";
|
||||
import { Stat } from "../../components/ui/misc.js";
|
||||
import { Card, CardHeader, Skeleton } from "../../components/ui/surface.js";
|
||||
import { useAction } from "../../components/ui/toast.js";
|
||||
|
||||
type Range = 7 | 30 | 90;
|
||||
|
||||
const cssVar = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
|
||||
// Re-renders when the system switches between light and dark, so the chart picks up the new colors.
|
||||
function useColorScheme() {
|
||||
const [dark, setDark] = useState(() => matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
useEffect(() => {
|
||||
const mq = matchMedia("(prefers-color-scheme: dark)");
|
||||
const update = () => setDark(mq.matches);
|
||||
mq.addEventListener("change", update);
|
||||
return () => mq.removeEventListener("change", update);
|
||||
}, []);
|
||||
return dark;
|
||||
}
|
||||
|
||||
function Chart({ series }: { series: StatsDay[] }) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const dark = useColorScheme();
|
||||
|
||||
useEffect(() => {
|
||||
const el = container.current;
|
||||
if (!el) return;
|
||||
const [c1, c2, muted, border] = ["--color-chart-1", "--color-chart-2", "--color-muted", "--color-border"].map(cssVar);
|
||||
const x = series.map((d) => new Date(`${d.day}T00:00:00`).getTime() / 1000);
|
||||
const axis = { stroke: muted, grid: { stroke: border, width: 1 }, ticks: { show: false }, font: "12px system-ui" };
|
||||
const showPoints = series.length <= 30;
|
||||
|
||||
const plot = new uPlot(
|
||||
{
|
||||
width: el.clientWidth,
|
||||
height: 260,
|
||||
legend: { show: false },
|
||||
cursor: { drag: { x: false, y: false }, points: { size: 8 } },
|
||||
scales: { y: { range: (_u, _min, max) => [0, Math.max(4, Math.ceil(max * 1.15))] } },
|
||||
axes: [
|
||||
{
|
||||
...axis,
|
||||
grid: { show: false },
|
||||
incrs: [86400, 7 * 86400],
|
||||
values: (_u, ticks) => ticks.map((t) => new Date(t * 1000).toLocaleDateString(undefined, { month: "short", day: "numeric" })),
|
||||
},
|
||||
{ ...axis, size: 40, values: (_u, ticks) => ticks.map((t) => (Number.isInteger(t) ? String(t) : "")) },
|
||||
],
|
||||
series: [
|
||||
{},
|
||||
{ label: "Clicks", stroke: c1, width: 2, fill: `${c1}22`, points: { show: showPoints, size: 5, fill: c1 } },
|
||||
{ label: "Unique visitors", stroke: c2, width: 2, points: { show: showPoints, size: 5, fill: c2 } },
|
||||
],
|
||||
},
|
||||
[x, series.map((d) => d.clicks), series.map((d) => d.uniques)],
|
||||
el,
|
||||
);
|
||||
const resize = new ResizeObserver(() => plot.setSize({ width: el.clientWidth, height: 260 }));
|
||||
resize.observe(el);
|
||||
return () => {
|
||||
resize.disconnect();
|
||||
plot.destroy();
|
||||
};
|
||||
}, [series, dark]);
|
||||
|
||||
return <div ref={container} className="w-full" />;
|
||||
}
|
||||
|
||||
function LegendDot({ color, label }: { color: string; label: string }) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted">
|
||||
<span className="size-2.5 rounded-full" style={{ background: `var(${color})` }} />
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function AnalyticsTab({ pageId }: { pageId: number }) {
|
||||
const [days, setDays] = useState<Range>(30);
|
||||
const stats = useApi<PageStats>(`/pages/${pageId}/stats?days=${days}`);
|
||||
const { busy, run } = useAction();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const reset = async () => {
|
||||
const ok = await confirm({
|
||||
title: "Reset all stats?",
|
||||
description: "All clicks and daily totals for this page are deleted. This can't be undone.",
|
||||
confirmLabel: "Reset stats",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
void run(async () => {
|
||||
await api("DELETE", `/pages/${pageId}/stats`);
|
||||
await stats.reload();
|
||||
}, "Stats reset");
|
||||
};
|
||||
|
||||
const s = stats.data;
|
||||
const inRange = s?.series.reduce((sum, d) => sum + d.clicks, 0) ?? 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
|
||||
{s ? (
|
||||
<>
|
||||
<Stat label="Total clicks" value={s.total.toLocaleString()} icon={<MousePointerClick />} hint="all time" />
|
||||
<Stat label="Today" value={s.today.toLocaleString()} icon={<Sun />} hint="clicks" />
|
||||
<Stat label="Unique today" value={s.uniquesToday.toLocaleString()} icon={<Users />} hint="visitors" />
|
||||
<Stat
|
||||
label="Last visit"
|
||||
value={<span className="text-lg">{s.lastVisit ? new Date(s.lastVisit).toLocaleDateString() : "—"}</span>}
|
||||
icon={<CalendarClock />}
|
||||
hint={s.lastVisit ? new Date(s.lastVisit).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "never"}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
[0, 1, 2, 3].map((i) => <Skeleton key={i} className="h-28 rounded-xl" />)
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader
|
||||
title="Clicks per day"
|
||||
description={s ? `${inRange.toLocaleString()} clicks in the last ${days} days` : " "}
|
||||
actions={
|
||||
<Segmented
|
||||
ariaLabel="Time range"
|
||||
value={days}
|
||||
onChange={setDays}
|
||||
options={[
|
||||
{ value: 7, label: "7d" },
|
||||
{ value: 30, label: "30d" },
|
||||
{ value: 90, label: "90d" },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<div className="px-3 pt-4 pb-2">{s ? <Chart series={s.series} /> : <Skeleton className="mx-2 h-[260px]" />}</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-3">
|
||||
<div className="flex gap-4">
|
||||
<LegendDot color="--color-chart-1" label="Clicks" />
|
||||
<LegendDot color="--color-chart-2" label="Unique visitors" />
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon={<RotateCcw />} onClick={() => void reset()} loading={busy} className="hover:text-danger">
|
||||
Reset stats
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<p className="text-xs text-muted">
|
||||
Unique visitors are counted per day, without storing IP addresses. Individual clicks are kept for 90 days, daily totals forever.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Check, ImageUp, Trash2 } from "lucide-react";
|
||||
import type { PageDetail } from "../../../shared/api-types.js";
|
||||
import type { Theme } from "../../../shared/validation.js";
|
||||
import { api } from "../../api.js";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { ColorInput, Field, Input } from "../../components/ui/form.js";
|
||||
import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
|
||||
import { useAction } from "../../components/ui/toast.js";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
import { stripMarkdown } from "../../lib/markdown.js";
|
||||
import { PhoneFrame } from "./PhonePreview.js";
|
||||
|
||||
const PRESETS: { name: string; theme: Theme }[] = [
|
||||
{ name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } },
|
||||
{ name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } },
|
||||
{ name: "Violet", theme: { background: "#2e1065", text: "#ede9fe", button: "#7c3aed", buttonText: "#ffffff" } },
|
||||
{ name: "Forest", theme: { background: "#052e16", text: "#dcfce7", button: "#15803d", buttonText: "#ffffff" } },
|
||||
{ name: "Sunset", theme: { background: "#431407", text: "#ffedd5", button: "#ea580c", buttonText: "#ffffff" } },
|
||||
{ name: "Ocean", theme: { background: "#082f49", text: "#e0f2fe", button: "#0284c7", buttonText: "#ffffff" } },
|
||||
];
|
||||
|
||||
const COLOR_FIELDS: [keyof Theme, string][] = [
|
||||
["background", "Background"],
|
||||
["text", "Text"],
|
||||
["button", "Buttons"],
|
||||
["buttonText", "Button text"],
|
||||
];
|
||||
|
||||
const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase());
|
||||
|
||||
// Renders the page with unsaved settings so changes are visible while editing.
|
||||
function MockPreview({ title, avatarUrl, theme, page }: { title: string; avatarUrl: string | null; theme: Theme; page: PageDetail }) {
|
||||
return (
|
||||
<PhoneFrame caption="Preview of unsaved changes">
|
||||
<div className="absolute inset-0 overflow-y-auto px-5 py-10 text-center" style={{ background: theme.background, color: theme.text }}>
|
||||
{avatarUrl && <img src={avatarUrl} alt="" className="mx-auto size-20 rounded-full object-cover" />}
|
||||
<div className="mt-4 mb-6 text-xl font-bold">{title || "Untitled"}</div>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{page.blocks.map((b) =>
|
||||
b.kind === "link" ? (
|
||||
<div key={b.id} className="rounded-lg px-3 py-2.5 text-sm font-semibold" style={{ background: theme.button, color: theme.buttonText }}>
|
||||
{b.label}
|
||||
</div>
|
||||
) : (
|
||||
<p key={b.id} className="line-clamp-3 text-sm opacity-90">
|
||||
{stripMarkdown(b.markdown ?? "")}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
{!page.blocks.length &&
|
||||
[0, 1, 2].map((i) => <div key={i} className="h-10 rounded-lg opacity-60" style={{ background: theme.button }} />)}
|
||||
</div>
|
||||
</div>
|
||||
</PhoneFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
|
||||
const [title, setTitle] = useState(page.title ?? "");
|
||||
const [theme, setTheme] = useState(page.theme);
|
||||
const { busy, run } = useAction();
|
||||
const upload = useAction();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const dirty = title !== (page.title ?? "") || !sameTheme(theme, page.theme);
|
||||
|
||||
const save = () => run(async () => onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { title, theme })), "Appearance saved");
|
||||
|
||||
const uploadAvatar = (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
void upload.run(async () => {
|
||||
const { avatarUrl } = await api<{ avatarUrl: string }>("PUT", `/pages/${page.id}/avatar`, form);
|
||||
onChange({ ...page, avatarUrl });
|
||||
}, "Avatar updated");
|
||||
};
|
||||
const removeAvatar = () =>
|
||||
upload.run(async () => {
|
||||
await api("DELETE", `/pages/${page.id}/avatar`);
|
||||
onChange({ ...page, avatarUrl: null });
|
||||
}, "Avatar removed");
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[minmax(0,1fr)] items-start gap-8 lg:grid-cols-[minmax(0,1fr)_300px]">
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card>
|
||||
<CardHeader title="Profile" description="Shown at the top of the page." />
|
||||
<CardBody className="flex flex-col gap-5">
|
||||
<div className="flex items-center gap-4">
|
||||
{page.avatarUrl ? (
|
||||
<img src={page.avatarUrl} alt="" className="size-16 rounded-full object-cover ring-1 ring-border" />
|
||||
) : (
|
||||
<span className="flex size-16 items-center justify-center rounded-full border border-dashed border-border-strong text-muted">
|
||||
<ImageUp className="size-5" />
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex gap-2">
|
||||
<Button variant="secondary" size="sm" loading={upload.busy} icon={<ImageUp />} onClick={() => fileInput.current?.click()}>
|
||||
{page.avatarUrl ? "Replace" : "Upload avatar"}
|
||||
</Button>
|
||||
{page.avatarUrl && (
|
||||
<Button variant="ghost" size="sm" icon={<Trash2 />} onClick={() => void removeAvatar()}>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted">PNG, JPEG or WebP, up to 2 MB. Square images work best.</p>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
uploadAvatar(e.target.files?.[0]);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Field label="Title">{(id) => <Input id={id} required value={title} onChange={(e) => setTitle(e.target.value)} />}</Field>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader title="Theme" description="Pick a preset or set your own colors." />
|
||||
<CardBody className="flex flex-col gap-6">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{PRESETS.map((preset) => {
|
||||
const selected = sameTheme(preset.theme, theme);
|
||||
return (
|
||||
<button
|
||||
key={preset.name}
|
||||
type="button"
|
||||
onClick={() => setTheme(preset.theme)}
|
||||
className={cx(
|
||||
"relative cursor-pointer overflow-hidden rounded-xl border text-left transition",
|
||||
selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong",
|
||||
)}
|
||||
>
|
||||
<div className="flex h-16 flex-col items-center justify-center gap-1.5 px-6" style={{ background: preset.theme.background }}>
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} />
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} />
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-3 py-2 text-sm font-medium">
|
||||
{preset.name}
|
||||
{selected && <Check className="size-4 text-accent" />}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{COLOR_FIELDS.map(([key, label]) => (
|
||||
<div key={key} className="flex flex-col gap-1.5">
|
||||
<span className="text-sm font-medium">{label}</span>
|
||||
<ColorInput label={label} value={theme[key]} onChange={(v) => setTheme({ ...theme, [key]: v })} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
{dirty && <span className="mr-auto text-sm text-muted">Unsaved changes</span>}
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={!dirty}
|
||||
onClick={() => {
|
||||
setTitle(page.title ?? "");
|
||||
setTheme(page.theme);
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
</Button>
|
||||
<Button onClick={() => void save()} loading={busy} disabled={!dirty || !title.trim()}>
|
||||
Save changes
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="hidden lg:block">
|
||||
<MockPreview title={title} avatarUrl={page.avatarUrl} theme={theme} page={page} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
|
||||
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { GripVertical, LayoutList, Link2, Pencil, Plus, Trash2, Type } from "lucide-react";
|
||||
import type { Block, Me, PageDetail, PageSummary } from "../../../shared/api-types.js";
|
||||
import { api, useApi } from "../../api.js";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { Dialog, useConfirm } from "../../components/ui/dialog.js";
|
||||
import { Field, Input, Select, Textarea } from "../../components/ui/form.js";
|
||||
import { Link } from "../../components/ui/misc.js";
|
||||
import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js";
|
||||
import { useAction } from "../../components/ui/toast.js";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
import { stripMarkdown } from "../../lib/markdown.js";
|
||||
import { LivePreview } from "./PhonePreview.js";
|
||||
|
||||
type Editing = { kind: "link"; block?: Block } | { kind: "text"; block?: Block } | null;
|
||||
|
||||
function BlockDialog({
|
||||
editing,
|
||||
page,
|
||||
me,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
editing: Editing;
|
||||
page: PageDetail;
|
||||
me: Me;
|
||||
onClose: () => void;
|
||||
onSaved: (blocks: Block[]) => void;
|
||||
}) {
|
||||
const pages = useApi<PageSummary[]>(editing?.kind === "link" && !editing.block ? "/pages" : null);
|
||||
const { busy, run } = useAction();
|
||||
const [targetId, setTargetId] = useState("");
|
||||
const [label, setLabel] = useState("");
|
||||
const [markdown, setMarkdown] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setTargetId("");
|
||||
setLabel(editing?.block?.label ?? "");
|
||||
setMarkdown(editing?.block?.markdown ?? "");
|
||||
}, [editing]);
|
||||
|
||||
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
|
||||
|
||||
// Same rule as the server: own namespace only, unless admin.
|
||||
const targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (me.isAdmin || p.namespace === page.namespace));
|
||||
const isNew = !editing.block;
|
||||
|
||||
const submit = () =>
|
||||
run(async () => {
|
||||
let blocks: Block[];
|
||||
if (editing.block) {
|
||||
blocks = await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label });
|
||||
} else if (editing.kind === "link") {
|
||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: Number(targetId), label });
|
||||
} else {
|
||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "text", markdown });
|
||||
}
|
||||
onSaved(blocks);
|
||||
onClose();
|
||||
}, isNew ? "Block added" : "Block updated");
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={onClose}
|
||||
onSubmit={submit}
|
||||
title={editing.kind === "link" ? (isNew ? "Add link button" : "Edit link button") : isNew ? "Add text" : "Edit text"}
|
||||
description={editing.kind === "link" ? "Buttons point at one of your short links, so every click is counted." : undefined}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={busy} disabled={editing.kind === "link" ? !label.trim() || (isNew && !targetId) : !markdown.trim()}>
|
||||
{isNew ? "Add" : "Save"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{editing.kind === "link" ? (
|
||||
<>
|
||||
{isNew && (
|
||||
<Field
|
||||
label="Short link"
|
||||
hint={
|
||||
pages.data && !targets.length ? (
|
||||
<>
|
||||
You don't have any short links yet.{" "}
|
||||
<Link to="/~/links" className="underline">
|
||||
Create one first
|
||||
</Link>
|
||||
.
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{(id) => (
|
||||
<Select id={id} required value={targetId} onChange={(e) => setTargetId(e.target.value)}>
|
||||
<option value="">Choose a short link…</option>
|
||||
{targets.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.path} → {p.dest}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Button label">
|
||||
{(id) => <Input id={id} required autoFocus={!isNew} placeholder="My GitHub" value={label} onChange={(e) => setLabel(e.target.value)} />}
|
||||
</Field>
|
||||
</>
|
||||
) : (
|
||||
<Field label="Text" hint="Markdown: **bold**, *italic*, [link](https://…), lists and # headings.">
|
||||
{(id) => <Textarea id={id} required autoFocus rows={6} value={markdown} onChange={(e) => setMarkdown(e.target.value)} />}
|
||||
</Field>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SortableBlock({ block, onEdit, onDelete }: { block: Block; onEdit: () => void; onDelete: () => void }) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id });
|
||||
const isLink = block.kind === "link";
|
||||
return (
|
||||
<li
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||
className={cx(
|
||||
"flex items-center gap-2 rounded-xl border border-border bg-surface p-2 pr-3",
|
||||
isDragging ? "relative z-10 shadow-xl ring-2 ring-accent/30" : "shadow-xs",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
className="flex h-9 w-7 cursor-grab touch-none items-center justify-center rounded-md text-muted hover:bg-surface-2 hover:text-fg active:cursor-grabbing"
|
||||
aria-label="Drag to reorder"
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
>
|
||||
<GripVertical className="size-4" />
|
||||
</button>
|
||||
<span
|
||||
className={cx(
|
||||
"flex size-8 shrink-0 items-center justify-center rounded-lg",
|
||||
isLink ? "bg-accent-soft text-accent-soft-fg" : "bg-surface-2 text-muted",
|
||||
)}
|
||||
>
|
||||
{isLink ? <Link2 className="size-4" /> : <Type className="size-4" />}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{isLink ? block.label : stripMarkdown(block.markdown ?? "")}</div>
|
||||
<div className="truncate font-mono text-xs text-muted">{isLink ? block.target?.path : "Text"}</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onEdit} aria-label="Edit">
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label="Delete" className="hover:text-danger">
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContentTab({ page, me, onChange }: { page: PageDetail; me: Me; onChange: (page: PageDetail) => void }) {
|
||||
const [editing, setEditing] = useState<Editing>(null);
|
||||
const [version, setVersion] = useState(0);
|
||||
const { run } = useAction();
|
||||
const confirm = useConfirm();
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
const setBlocks = (blocks: Block[]) => {
|
||||
onChange({ ...page, blocks });
|
||||
setVersion((v) => v + 1);
|
||||
};
|
||||
|
||||
const onDragEnd = ({ active, over }: DragEndEvent) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
const ids = page.blocks.map((b) => b.id);
|
||||
const reordered = arrayMove(page.blocks, ids.indexOf(Number(active.id)), ids.indexOf(Number(over.id)));
|
||||
onChange({ ...page, blocks: reordered });
|
||||
void run(async () => setBlocks(await api<Block[]>("PUT", `/pages/${page.id}/blocks/order`, { ids: reordered.map((b) => b.id) })));
|
||||
};
|
||||
|
||||
const remove = async (block: Block) => {
|
||||
const ok = await confirm({
|
||||
title: "Remove this block?",
|
||||
description: block.kind === "link" ? "The short link itself is kept." : undefined,
|
||||
confirmLabel: "Remove",
|
||||
danger: true,
|
||||
});
|
||||
if (ok) void run(async () => setBlocks(await api<Block[]>("DELETE", `/blocks/${block.id}`)), "Block removed");
|
||||
};
|
||||
|
||||
const addButtons = (
|
||||
<>
|
||||
<Button variant="secondary" size="sm" icon={<Type />} onClick={() => setEditing({ kind: "text" })}>
|
||||
Text
|
||||
</Button>
|
||||
<Button size="sm" icon={<Plus />} onClick={() => setEditing({ kind: "link" })}>
|
||||
Link button
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[minmax(0,1fr)] items-start gap-8 lg:grid-cols-[minmax(0,1fr)_300px]">
|
||||
<Card>
|
||||
<CardHeader title="Blocks" description="Drag to reorder. Changes are saved immediately." actions={addButtons} />
|
||||
{page.blocks.length ? (
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
|
||||
<SortableContext items={page.blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
|
||||
<ul className="flex flex-col gap-2 p-4">
|
||||
{page.blocks.map((b) => (
|
||||
<SortableBlock key={b.id} block={b} onEdit={() => setEditing({ kind: b.kind, block: b })} onDelete={() => void remove(b)} />
|
||||
))}
|
||||
</ul>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon={<LayoutList />}
|
||||
title="This page is empty"
|
||||
description="Add link buttons that point at your short links, or some text."
|
||||
action={<div className="flex gap-2">{addButtons}</div>}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="hidden lg:block">
|
||||
<LivePreview path={page.path} version={version} />
|
||||
</div>
|
||||
|
||||
<BlockDialog editing={editing} page={page} me={me} onClose={() => setEditing(null)} onSaved={setBlocks} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect } from "react";
|
||||
import { ChartNoAxesColumn, ChevronRight, ExternalLink, LayoutList, Palette, Pin, QrCode, Settings } from "lucide-react";
|
||||
import type { Me, PageDetail, PageKind } from "../../../shared/api-types.js";
|
||||
import { useApi } from "../../api.js";
|
||||
import { buttonClass } from "../../components/ui/button.js";
|
||||
import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.js";
|
||||
import { Badge, EmptyState, Skeleton } from "../../components/ui/surface.js";
|
||||
import { detailPath, listPath } from "../../router.js";
|
||||
import { AnalyticsTab } from "./AnalyticsTab.js";
|
||||
import { AppearanceTab } from "./AppearanceTab.js";
|
||||
import { ContentTab } from "./ContentTab.js";
|
||||
import { QrTab } from "./QrTab.js";
|
||||
import { SettingsTab } from "./SettingsTab.js";
|
||||
|
||||
const TABS = {
|
||||
content: { label: "Content", icon: <LayoutList /> },
|
||||
appearance: { label: "Appearance", icon: <Palette /> },
|
||||
analytics: { label: "Analytics", icon: <ChartNoAxesColumn /> },
|
||||
qr: { label: "QR code", icon: <QrCode /> },
|
||||
settings: { label: "Settings", icon: <Settings /> },
|
||||
} as const;
|
||||
type TabId = keyof typeof TABS;
|
||||
|
||||
const TABS_BY_KIND: Record<PageKind, TabId[]> = {
|
||||
redirect: ["analytics", "qr", "settings"],
|
||||
linkpage: ["content", "appearance", "analytics", "qr", "settings"],
|
||||
};
|
||||
|
||||
export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind; tab: string | undefined; me: Me }) {
|
||||
const page = useApi<PageDetail>(`/pages/${id}`);
|
||||
const p = page.data;
|
||||
|
||||
// Links like /~/links/<id of a link page> are corrected to the right section.
|
||||
useEffect(() => {
|
||||
if (p && p.kind !== kind) history.replaceState(null, "", detailPath(p, tab));
|
||||
}, [p, kind, tab]);
|
||||
|
||||
if (page.error) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={<LayoutList />}
|
||||
title={page.error.status === 404 ? "Not found" : "Couldn't load this page"}
|
||||
description={page.error.status === 404 ? "It may have been deleted, or it belongs to someone else." : page.error.message}
|
||||
action={
|
||||
<Link to={listPath(kind)} className={buttonClass("secondary")}>
|
||||
Back to list
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!p) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-10 w-72" />
|
||||
<Skeleton className="mt-6 h-64 rounded-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const tabs = TABS_BY_KIND[p.kind];
|
||||
const active: TabId = tabs.includes(tab as TabId) ? (tab as TabId) : tabs[0]!;
|
||||
const url = publicUrl(p.path);
|
||||
|
||||
return (
|
||||
<>
|
||||
<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">
|
||||
{p.kind === "redirect" ? "Short links" : "Link pages"}
|
||||
</Link>
|
||||
<ChevronRight className="size-3.5" />
|
||||
<span className="truncate text-fg">{p.path}</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-6 flex flex-wrap items-center gap-4">
|
||||
{p.kind === "redirect" ? (
|
||||
<DomainIcon url={p.dest} className="size-12 rounded-xl text-base" />
|
||||
) : p.avatarUrl ? (
|
||||
<img src={p.avatarUrl} alt="" className="size-12 rounded-full object-cover" />
|
||||
) : (
|
||||
<span className="flex size-12 items-center justify-center rounded-xl bg-accent-soft text-lg font-semibold text-accent-soft-fg">
|
||||
{(p.title ?? p.code).charAt(0).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="truncate font-mono text-xl font-semibold tracking-tight sm:text-2xl">{p.path}</h1>
|
||||
{p.pinned && (
|
||||
<Badge tone="accent" icon={<Pin />}>
|
||||
Homepage
|
||||
</Badge>
|
||||
)}
|
||||
{p.namespace === "" && <Badge>Root</Badge>}
|
||||
</div>
|
||||
<p className="mt-0.5 truncate text-sm text-muted">{p.kind === "redirect" ? `→ ${p.dest}` : p.title}</p>
|
||||
</div>
|
||||
<div className="flex basis-full gap-2 sm:basis-auto">
|
||||
<CopyButton value={url} label="Copy" />
|
||||
<a href={p.path} target="_blank" rel="noreferrer" className={buttonClass("secondary", "sm")}>
|
||||
<ExternalLink />
|
||||
Open
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Tabs active={active} tabs={tabs.map((t) => ({ id: t, ...TABS[t], to: detailPath(p, t === tabs[0] ? undefined : t) }))} />
|
||||
|
||||
<div className="animate-fade-in" key={active}>
|
||||
{active === "content" && <ContentTab page={p} me={me} onChange={page.set} />}
|
||||
{active === "appearance" && <AppearanceTab page={p} onChange={page.set} />}
|
||||
{active === "analytics" && <AnalyticsTab pageId={p.id} />}
|
||||
{active === "qr" && <QrTab url={url} name={p.code} />}
|
||||
{active === "settings" && <SettingsTab page={p} me={me} onChange={page.set} reload={page.reload} />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
// A phone-shaped frame for previewing link pages.
|
||||
export function PhoneFrame({ children, caption }: { children: ReactNode; caption?: ReactNode }) {
|
||||
return (
|
||||
<div className="sticky top-6 mx-auto w-full max-w-[300px]">
|
||||
<div className="overflow-hidden rounded-[2.25rem] border-[7px] border-zinc-800 bg-zinc-800 shadow-2xl ring-1 ring-border dark:border-zinc-700">
|
||||
<div className="relative aspect-[9/18.5] overflow-hidden rounded-[1.75rem] bg-black">{children}</div>
|
||||
</div>
|
||||
{caption && <p className="mt-3 text-center text-xs text-muted">{caption}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Shows the real, server-rendered page. `version` forces a reload after edits.
|
||||
export function LivePreview({ path, version }: { path: string; version: number }) {
|
||||
return (
|
||||
<PhoneFrame caption="Live preview">
|
||||
<iframe key={version} src={`${path}?preview`} title="Preview" className="absolute inset-0 h-full w-full border-0" />
|
||||
</PhoneFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import QRCode, { type QRCodeErrorCorrectionLevel } from "qrcode";
|
||||
import { Download } from "lucide-react";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { ColorInput, Segmented } from "../../components/ui/form.js";
|
||||
import { Card, CardFooter, CardHeader } from "../../components/ui/surface.js";
|
||||
|
||||
const LEVELS: { value: QRCodeErrorCorrectionLevel; label: string; detail: string }[] = [
|
||||
{ value: "L", label: "L", detail: "Low (7%): smallest code" },
|
||||
{ value: "M", label: "M", detail: "Medium (15%)" },
|
||||
{ value: "Q", label: "Q", detail: "Quartile (25%): good for print" },
|
||||
{ value: "H", label: "H", detail: "High (30%): survives damage or a logo on top" },
|
||||
];
|
||||
|
||||
function download(href: string, filename: string) {
|
||||
const a = document.createElement("a");
|
||||
a.href = href;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
}
|
||||
|
||||
export function QrTab({ url, name }: { url: string; name: string }) {
|
||||
const [level, setLevel] = useState<QRCodeErrorCorrectionLevel>("Q");
|
||||
const [dark, setDark] = useState("#000000");
|
||||
const [light, setLight] = useState("#ffffff");
|
||||
const [svg, setSvg] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
QRCode.toString(url, { type: "svg", errorCorrectionLevel: level, margin: 2, color: { dark, light } }).then(setSvg, () => setSvg(""));
|
||||
}, [url, level, dark, light]);
|
||||
|
||||
const downloadSvg = () => {
|
||||
const blobUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
|
||||
download(blobUrl, `${name}.svg`);
|
||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
|
||||
};
|
||||
const downloadPng = async () =>
|
||||
download(await QRCode.toDataURL(url, { errorCorrectionLevel: level, margin: 2, color: { dark, light }, width: 1024 }), `${name}.png`);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader title="QR code" description={<span className="font-mono">{url}</span>} />
|
||||
<div className="grid gap-8 p-5 md:grid-cols-[auto_1fr]">
|
||||
<div
|
||||
className="mx-auto size-56 overflow-hidden rounded-xl border border-border shadow-sm [&>svg]:size-full"
|
||||
// The SVG markup is generated locally by the qrcode library.
|
||||
dangerouslySetInnerHTML={{ __html: svg }}
|
||||
/>
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm font-medium">Error correction</span>
|
||||
<Segmented ariaLabel="Error correction" value={level} onChange={setLevel} options={LEVELS} />
|
||||
<p className="text-xs text-muted">{LEVELS.find((l) => l.value === level)?.detail}</p>
|
||||
</div>
|
||||
<div className="grid max-w-md grid-cols-2 gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="text-sm font-medium">Foreground</span>
|
||||
<ColorInput label="Foreground" value={dark} onChange={setDark} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="text-sm font-medium">Background</span>
|
||||
<ColorInput label="Background" value={light} onChange={setLight} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<CardFooter>
|
||||
<span className="mr-auto hidden text-sm text-muted sm:block">SVG scales without quality loss and is best for print.</span>
|
||||
<Button variant="secondary" icon={<Download />} onClick={() => void downloadPng()}>
|
||||
PNG
|
||||
</Button>
|
||||
<Button icon={<Download />} onClick={downloadSvg} disabled={!svg}>
|
||||
SVG
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useState } from "react";
|
||||
import { Pin, PinOff, Trash2 } from "lucide-react";
|
||||
import type { Me, PageDetail } from "../../../shared/api-types.js";
|
||||
import { api } from "../../api.js";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { useConfirm } from "../../components/ui/dialog.js";
|
||||
import { Field, Input } from "../../components/ui/form.js";
|
||||
import { CopyButton, publicUrl } from "../../components/ui/misc.js";
|
||||
import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
|
||||
import { useAction } from "../../components/ui/toast.js";
|
||||
import { listPath, navigate } from "../../router.js";
|
||||
|
||||
function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
|
||||
const [dest, setDest] = useState(page.dest ?? "");
|
||||
const { busy, run } = useAction();
|
||||
return (
|
||||
<Card>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(async () => onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { dest })), "Destination updated");
|
||||
}}
|
||||
>
|
||||
<CardHeader title="Destination" description="Where visitors are sent. Changes apply immediately, existing QR codes keep working." />
|
||||
<CardBody>
|
||||
<Field label="URL">{(id) => <Input id={id} type="url" required value={dest} onChange={(e) => setDest(e.target.value)} />}</Field>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
<Button type="submit" loading={busy} disabled={dest === page.dest}>
|
||||
Save
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsTab({
|
||||
page,
|
||||
me,
|
||||
onChange,
|
||||
reload,
|
||||
}: {
|
||||
page: PageDetail;
|
||||
me: Me;
|
||||
onChange: (page: PageDetail) => void;
|
||||
reload: () => Promise<void>;
|
||||
}) {
|
||||
const { busy, run } = useAction();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const togglePin = () =>
|
||||
run(async () => {
|
||||
if (page.pinned) await api("DELETE", "/pin");
|
||||
else await api("PUT", "/pin", { pageId: page.id });
|
||||
await reload();
|
||||
}, page.pinned ? "Removed from homepage" : "Set as homepage");
|
||||
|
||||
const remove = async () => {
|
||||
const ok = await confirm({
|
||||
title: `Delete ${page.path}?`,
|
||||
description: "Its stats and any link buttons pointing to it are deleted too. The URL stops working immediately.",
|
||||
confirmLabel: "Delete",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
void run(async () => {
|
||||
await api("DELETE", `/pages/${page.id}`);
|
||||
navigate(listPath(page.kind));
|
||||
}, `Deleted ${page.path}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex max-w-3xl flex-col gap-6">
|
||||
{page.kind === "redirect" && <DestinationCard page={page} onChange={onChange} />}
|
||||
|
||||
<Card>
|
||||
<CardHeader title="Address" description="Shortcodes can't be changed. Create a new one if you need a different address." />
|
||||
<CardBody className="flex items-center gap-2">
|
||||
<code className="flex-1 truncate rounded-lg bg-surface-2 px-3 py-2 font-mono text-sm">{publicUrl(page.path)}</code>
|
||||
<CopyButton value={publicUrl(page.path)} label="Copy" />
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{me.isAdmin && (
|
||||
<Card>
|
||||
<CardHeader
|
||||
title="Homepage"
|
||||
description={
|
||||
page.pinned
|
||||
? "Visitors opening the bare domain are sent to this page."
|
||||
: "Send visitors who open the bare domain to this page instead of the default landing page."
|
||||
}
|
||||
actions={
|
||||
<Button variant="secondary" size="sm" icon={page.pinned ? <PinOff /> : <Pin />} onClick={() => void togglePin()} loading={busy}>
|
||||
{page.pinned ? "Unpin" : "Set as homepage"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card className="border-danger/30">
|
||||
<CardHeader
|
||||
title={<span className="text-danger">Delete {page.kind === "redirect" ? "short link" : "link page"}</span>}
|
||||
description="Permanently removes it together with its stats."
|
||||
actions={
|
||||
<Button variant="danger" size="sm" icon={<Trash2 />} onClick={() => void remove()}>
|
||||
Delete
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+70
-22
@@ -1,34 +1,82 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-gray-900 text-gray-300 antialiased;
|
||||
/* Semantic color tokens. Components only use these, so light and dark mode stay in sync. */
|
||||
@theme {
|
||||
--color-canvas: #f6f6f8;
|
||||
--color-surface: #ffffff;
|
||||
--color-surface-2: #f1f1f4;
|
||||
--color-border: #e4e4e9;
|
||||
--color-border-strong: #d1d1d8;
|
||||
--color-fg: #18181b;
|
||||
--color-muted: #6b6b76;
|
||||
--color-accent: #7c3aed;
|
||||
--color-accent-hover: #6d28d9;
|
||||
--color-accent-fg: #ffffff;
|
||||
--color-accent-soft: #f1ebff;
|
||||
--color-accent-soft-fg: #6d28d9;
|
||||
--color-danger: #dc2626;
|
||||
--color-danger-soft: #fdecec;
|
||||
--color-danger-soft-fg: #b91c1c;
|
||||
--color-success: #16a34a;
|
||||
--color-warning-soft: #fdf4e3;
|
||||
--color-warning-soft-fg: #92400e;
|
||||
--color-chart-1: #7c3aed;
|
||||
--color-chart-2: #0ea5e9;
|
||||
|
||||
--font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
|
||||
--animate-fade-in: fade-in 0.15s ease-out;
|
||||
--animate-pop-in: pop-in 0.18s cubic-bezier(0.2, 0.9, 0.3, 1.2);
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
h1 {
|
||||
@apply text-3xl font-bold text-white;
|
||||
}
|
||||
h2 {
|
||||
@apply text-xl font-bold text-white;
|
||||
@keyframes pop-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.98);
|
||||
}
|
||||
label {
|
||||
@apply mb-1 block text-xs font-bold tracking-wide uppercase;
|
||||
}
|
||||
input:not([type="color"]):not([type="file"]),
|
||||
select,
|
||||
textarea {
|
||||
@apply w-full rounded border border-gray-800 bg-gray-800 px-3 py-2 text-gray-200 focus:bg-gray-700 focus:outline-none;
|
||||
}
|
||||
}
|
||||
|
||||
@utility btn {
|
||||
@apply inline-flex cursor-pointer items-center justify-center gap-2 rounded bg-green-600 px-4 py-2 font-medium text-white hover:bg-green-700 disabled:cursor-default disabled:opacity-50;
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-canvas: #0c0c10;
|
||||
--color-surface: #141419;
|
||||
--color-surface-2: #1d1d24;
|
||||
--color-border: #26262e;
|
||||
--color-border-strong: #34343e;
|
||||
--color-fg: #ececf1;
|
||||
--color-muted: #9898a6;
|
||||
--color-accent: #8b5cf6;
|
||||
--color-accent-hover: #7c3aed;
|
||||
--color-accent-soft: #241a3d;
|
||||
--color-accent-soft-fg: #c4b5fd;
|
||||
--color-danger: #ef4444;
|
||||
--color-danger-soft: #2c1517;
|
||||
--color-danger-soft-fg: #fca5a5;
|
||||
--color-warning-soft: #2b2112;
|
||||
--color-warning-soft-fg: #fcd34d;
|
||||
--color-chart-1: #a78bfa;
|
||||
--color-chart-2: #38bdf8;
|
||||
color-scheme: dark;
|
||||
}
|
||||
@utility btn-secondary {
|
||||
@apply bg-gray-700 hover:bg-gray-600;
|
||||
}
|
||||
@utility btn-danger {
|
||||
@apply bg-red-800 hover:bg-red-700;
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
@utility card {
|
||||
@apply rounded-lg bg-gray-800/60 p-4;
|
||||
body {
|
||||
@apply bg-canvas text-fg antialiased;
|
||||
}
|
||||
::selection {
|
||||
@apply bg-accent/25;
|
||||
}
|
||||
}
|
||||
|
||||
/* Shared form control look for input, select and textarea. */
|
||||
@utility control {
|
||||
@apply w-full rounded-lg border border-border bg-surface px-3 text-sm text-fg shadow-xs transition outline-none placeholder:text-muted/70 focus:border-accent focus:ring-3 focus:ring-accent/20 disabled:opacity-60;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user