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:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user