mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
Create short links directly from the link button dialog
The "Add link button" dialog can now either pick an existing short link or create a new one (destination + optional shortcode) in the page's namespace. The block API accepts `newLink` as an alternative to `targetId`; link and button are created in one transaction, so a failed request leaves nothing behind. Field errors such as a taken shortcode are shown inline, and the label is suggested from the destination's hostname. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -81,6 +81,8 @@ curl -X POST https://short.example.com/~/api/pages \
|
|||||||
Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /tokens`.
|
Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /tokens`.
|
||||||
Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`.
|
Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`.
|
||||||
|
|
||||||
|
Link buttons can reference an existing short link (`{"kind":"link","label":"…","targetId":12}`) or create one in the page's namespace in the same request (`{"kind":"link","label":"…","newLink":{"dest":"https://…","code":"optional"}}`).
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+20
-8
@@ -225,14 +225,27 @@ function loadLinkPage(db: Db, actor: Actor, id: number): PageRow {
|
|||||||
|
|
||||||
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
|
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
|
||||||
const page = loadLinkPage(db, actor, pageId);
|
const page = loadLinkPage(db, actor, pageId);
|
||||||
let targetId: number | null = null;
|
// better-sqlite3 uses a single connection, so the calls on `db` below all run inside this transaction:
|
||||||
if (input.kind === "link") {
|
// a new short link is only kept if the button is added too.
|
||||||
const target = db.select().from(pages).where(eq(pages.id, input.targetId)).get();
|
db.transaction(() => {
|
||||||
if (!target || !canLinkTo(actor, page, target)) {
|
let targetId: number | null = null;
|
||||||
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
|
if (input.kind === "link" && input.newLink) {
|
||||||
|
const { code, dest } = input.newLink;
|
||||||
|
// The new link lives next to the page, e.g. /alice/<code> for a page under /alice/.
|
||||||
|
targetId = createPage(db, actor, { kind: "redirect", namespace: page.namespace, code, dest }).id;
|
||||||
|
} else if (input.kind === "link") {
|
||||||
|
const target = input.targetId ? db.select().from(pages).where(eq(pages.id, input.targetId)).get() : undefined;
|
||||||
|
if (!target || !canLinkTo(actor, page, target)) {
|
||||||
|
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
|
||||||
|
}
|
||||||
|
targetId = target.id;
|
||||||
}
|
}
|
||||||
targetId = target.id;
|
insertBlock(db, page.id, input, targetId);
|
||||||
}
|
});
|
||||||
|
return getBlocks(db, pageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertBlock(db: Db, pageId: number, input: CreateBlockInput, targetId: number | null): void {
|
||||||
const max = db
|
const max = db
|
||||||
.select({ max: sql<number | null>`max(${blocks.position})` })
|
.select({ max: sql<number | null>`max(${blocks.position})` })
|
||||||
.from(blocks)
|
.from(blocks)
|
||||||
@@ -248,7 +261,6 @@ export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBloc
|
|||||||
targetId,
|
targetId,
|
||||||
})
|
})
|
||||||
.run();
|
.run();
|
||||||
return getBlocks(db, pageId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
|
function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
|
||||||
|
|||||||
@@ -71,10 +71,21 @@ export const updatePageSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type UpdatePageInput = z.infer<typeof updatePageSchema>;
|
export type UpdatePageInput = z.infer<typeof updatePageSchema>;
|
||||||
|
|
||||||
export const createBlockSchema = z.discriminatedUnion("kind", [
|
// A link button points at an existing short link (targetId) or creates a new one in the page's namespace (newLink).
|
||||||
z.object({ kind: z.literal("link"), targetId: z.number().int().positive(), label: titleSchema }),
|
export const createBlockSchema = z
|
||||||
z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }),
|
.discriminatedUnion("kind", [
|
||||||
]);
|
z.object({
|
||||||
|
kind: z.literal("link"),
|
||||||
|
label: titleSchema,
|
||||||
|
targetId: z.number().int().positive().optional(),
|
||||||
|
newLink: z.object({ dest: destSchema, code: codeSchema.optional() }).optional(),
|
||||||
|
}),
|
||||||
|
z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }),
|
||||||
|
])
|
||||||
|
.refine((b) => b.kind !== "link" || (b.targetId === undefined) !== (b.newLink === undefined), {
|
||||||
|
message: "Pick an existing link or create a new one",
|
||||||
|
path: ["targetId"],
|
||||||
|
});
|
||||||
export type CreateBlockInput = z.infer<typeof createBlockSchema>;
|
export type CreateBlockInput = z.infer<typeof createBlockSchema>;
|
||||||
|
|
||||||
export const updateBlockSchema = z.object({
|
export const updateBlockSchema = z.object({
|
||||||
|
|||||||
@@ -4,18 +4,27 @@ import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, v
|
|||||||
import { CSS } from "@dnd-kit/utilities";
|
import { CSS } from "@dnd-kit/utilities";
|
||||||
import { GripVertical, LayoutList, Link2, Pencil, Plus, Trash2, Type } from "lucide-react";
|
import { GripVertical, LayoutList, Link2, Pencil, Plus, Trash2, Type } from "lucide-react";
|
||||||
import type { Block, Me, PageDetail, PageSummary } from "../../../shared/api-types.js";
|
import type { Block, Me, PageDetail, PageSummary } from "../../../shared/api-types.js";
|
||||||
import { api, useApi } from "../../api.js";
|
import { api, ApiRequestError, errorMessage, useApi } from "../../api.js";
|
||||||
import { Button } from "../../components/ui/button.js";
|
import { Button } from "../../components/ui/button.js";
|
||||||
import { Dialog, useConfirm } from "../../components/ui/dialog.js";
|
import { Dialog, useConfirm } from "../../components/ui/dialog.js";
|
||||||
import { Field, Input, Select, Textarea } from "../../components/ui/form.js";
|
import { Field, Input, PrefixInput, Segmented, Select, Textarea } from "../../components/ui/form.js";
|
||||||
import { Link } from "../../components/ui/misc.js";
|
|
||||||
import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js";
|
import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js";
|
||||||
import { useAction } from "../../components/ui/toast.js";
|
import { useAction, useToast } from "../../components/ui/toast.js";
|
||||||
import { cx } from "../../lib/cx.js";
|
import { cx } from "../../lib/cx.js";
|
||||||
import { stripMarkdown } from "../../lib/markdown.js";
|
import { stripMarkdown } from "../../lib/markdown.js";
|
||||||
import { LivePreview } from "./PhonePreview.js";
|
import { LivePreview } from "./PhonePreview.js";
|
||||||
|
|
||||||
type Editing = { kind: "link"; block?: Block } | { kind: "text"; block?: Block } | null;
|
type Editing = { kind: "link"; block?: Block } | { kind: "text"; block?: Block } | null;
|
||||||
|
type LinkSource = "existing" | "new";
|
||||||
|
|
||||||
|
// Suggests a button label from a URL, e.g. "https://www.github.com/x" → "github.com".
|
||||||
|
function hostnameOf(url: string | null | undefined): string {
|
||||||
|
try {
|
||||||
|
return url ? new URL(url).hostname.replace(/^www\./, "") : "";
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function BlockDialog({
|
function BlockDialog({
|
||||||
editing,
|
editing,
|
||||||
@@ -30,52 +39,98 @@ function BlockDialog({
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onSaved: (blocks: Block[]) => void;
|
onSaved: (blocks: Block[]) => void;
|
||||||
}) {
|
}) {
|
||||||
const pages = useApi<PageSummary[]>(editing?.kind === "link" && !editing.block ? "/pages" : null);
|
const isNewLink = editing?.kind === "link" && !editing.block;
|
||||||
const { busy, run } = useAction();
|
const pages = useApi<PageSummary[]>(isNewLink ? "/pages" : null);
|
||||||
|
const toast = useToast();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
const [source, setSource] = useState<LinkSource>("existing");
|
||||||
const [targetId, setTargetId] = useState("");
|
const [targetId, setTargetId] = useState("");
|
||||||
|
const [dest, setDest] = useState("");
|
||||||
|
const [code, setCode] = useState("");
|
||||||
const [label, setLabel] = useState("");
|
const [label, setLabel] = useState("");
|
||||||
|
const [labelTouched, setLabelTouched] = useState(false);
|
||||||
const [markdown, setMarkdown] = useState("");
|
const [markdown, setMarkdown] = useState("");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
setErrors({});
|
||||||
|
setSource("existing");
|
||||||
setTargetId("");
|
setTargetId("");
|
||||||
|
setDest("");
|
||||||
|
setCode("");
|
||||||
setLabel(editing?.block?.label ?? "");
|
setLabel(editing?.block?.label ?? "");
|
||||||
|
setLabelTouched(!!editing?.block);
|
||||||
setMarkdown(editing?.block?.markdown ?? "");
|
setMarkdown(editing?.block?.markdown ?? "");
|
||||||
}, [editing]);
|
}, [editing]);
|
||||||
|
|
||||||
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
|
|
||||||
|
|
||||||
// Same rule as the server: own namespace only, unless admin.
|
// 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 targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (me.isAdmin || p.namespace === page.namespace));
|
||||||
const isNew = !editing.block;
|
const noTargets = !!pages.data && targets.length === 0;
|
||||||
|
|
||||||
const submit = () =>
|
// Without existing links, creating one is the only option.
|
||||||
run(async () => {
|
useEffect(() => {
|
||||||
let blocks: Block[];
|
if (noTargets) setSource("new");
|
||||||
if (editing.block) {
|
}, [noTargets]);
|
||||||
blocks = await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label });
|
|
||||||
} else if (editing.kind === "link") {
|
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
|
||||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: Number(targetId), label });
|
|
||||||
} else {
|
const isNew = !editing.block;
|
||||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "text", markdown });
|
const suggestLabel = (url: string | null | undefined) => {
|
||||||
}
|
if (!labelTouched) setLabel(hostnameOf(url));
|
||||||
|
};
|
||||||
|
|
||||||
|
const body = (): unknown => {
|
||||||
|
if (editing.kind === "text") return { kind: "text", markdown };
|
||||||
|
if (source === "new") return { kind: "link", label, newLink: { dest: dest.trim(), ...(code.trim() && { code: code.trim() }) } };
|
||||||
|
return { kind: "link", label, targetId: Number(targetId) };
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setErrors({});
|
||||||
|
try {
|
||||||
|
const blocks = editing.block
|
||||||
|
? await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label })
|
||||||
|
: await api<Block[]>("POST", `/pages/${page.id}/blocks`, body());
|
||||||
onSaved(blocks);
|
onSaved(blocks);
|
||||||
onClose();
|
onClose();
|
||||||
}, isNew ? "Block added" : "Block updated");
|
const created = isNewLink && source === "new" ? blocks[blocks.length - 1]?.target?.path : undefined;
|
||||||
|
toast(created ? `Created ${created} and added it` : isNew ? "Block added" : "Block updated");
|
||||||
|
} catch (err) {
|
||||||
|
// Show validation problems next to the field they belong to.
|
||||||
|
const issues = err instanceof ApiRequestError ? err.issues : undefined;
|
||||||
|
if (!issues) {
|
||||||
|
toast(errorMessage(err), true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const field = (key: string) => (key.startsWith("newLink.") ? key.slice(8) : key);
|
||||||
|
setErrors(Object.fromEntries(Object.entries(issues).map(([k, v]) => [field(k), v.join(", ")])));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const canSubmit =
|
||||||
|
editing.kind === "text"
|
||||||
|
? !!markdown.trim()
|
||||||
|
: !!label.trim() && (!isNew || (source === "existing" ? !!targetId : !!dest.trim()));
|
||||||
|
|
||||||
|
const prefix = page.namespace ? `/${page.namespace}/` : "/";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
open
|
open
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onSubmit={submit}
|
onSubmit={() => void submit()}
|
||||||
title={editing.kind === "link" ? (isNew ? "Add link button" : "Edit link button") : isNew ? "Add text" : "Edit text"}
|
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}
|
description={editing.kind === "link" && isNew ? "Buttons point at a short link, so every click is counted." : undefined}
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button variant="secondary" onClick={onClose}>
|
<Button variant="secondary" onClick={onClose}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="submit" loading={busy} disabled={editing.kind === "link" ? !label.trim() || (isNew && !targetId) : !markdown.trim()}>
|
<Button type="submit" loading={busy} disabled={!canSubmit}>
|
||||||
{isNew ? "Add" : "Save"}
|
{isNew ? (source === "new" && editing.kind === "link" ? "Create and add" : "Add") : "Save"}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
@@ -83,22 +138,33 @@ function BlockDialog({
|
|||||||
{editing.kind === "link" ? (
|
{editing.kind === "link" ? (
|
||||||
<>
|
<>
|
||||||
{isNew && (
|
{isNew && (
|
||||||
<Field
|
<Segmented
|
||||||
label="Short link"
|
ariaLabel="Link"
|
||||||
hint={
|
value={source}
|
||||||
pages.data && !targets.length ? (
|
onChange={(v) => {
|
||||||
<>
|
setSource(v);
|
||||||
You don't have any short links yet.{" "}
|
setErrors({});
|
||||||
<Link to="/~/links" className="underline">
|
}}
|
||||||
Create one first
|
options={[
|
||||||
</Link>
|
{ value: "existing", label: "Existing link" },
|
||||||
.
|
{ value: "new", label: "New link" },
|
||||||
</>
|
]}
|
||||||
) : undefined
|
/>
|
||||||
}
|
)}
|
||||||
>
|
|
||||||
|
{isNew && source === "existing" && (
|
||||||
|
<Field label="Short link" error={errors.targetId} hint={noTargets ? "You don't have any short links yet. Create a new one instead." : undefined}>
|
||||||
{(id) => (
|
{(id) => (
|
||||||
<Select id={id} required value={targetId} onChange={(e) => setTargetId(e.target.value)}>
|
<Select
|
||||||
|
id={id}
|
||||||
|
required
|
||||||
|
value={targetId}
|
||||||
|
disabled={noTargets}
|
||||||
|
onChange={(e) => {
|
||||||
|
setTargetId(e.target.value);
|
||||||
|
suggestLabel(targets.find((t) => String(t.id) === e.target.value)?.dest);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<option value="">Choose a short link…</option>
|
<option value="">Choose a short link…</option>
|
||||||
{targets.map((p) => (
|
{targets.map((p) => (
|
||||||
<option key={p.id} value={p.id}>
|
<option key={p.id} value={p.id}>
|
||||||
@@ -109,8 +175,54 @@ function BlockDialog({
|
|||||||
)}
|
)}
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
<Field label="Button label">
|
|
||||||
{(id) => <Input id={id} required autoFocus={!isNew} placeholder="My GitHub" value={label} onChange={(e) => setLabel(e.target.value)} />}
|
{isNew && source === "new" && (
|
||||||
|
<>
|
||||||
|
<Field label="Destination URL" error={errors.dest}>
|
||||||
|
{(id) => (
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
type="url"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
placeholder="https://example.com"
|
||||||
|
value={dest}
|
||||||
|
onChange={(e) => {
|
||||||
|
setDest(e.target.value);
|
||||||
|
suggestLabel(e.target.value);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</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>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Field label="Button label" error={errors.label}>
|
||||||
|
{(id) => (
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
required
|
||||||
|
autoFocus={!isNew}
|
||||||
|
placeholder="My GitHub"
|
||||||
|
value={label}
|
||||||
|
onChange={(e) => {
|
||||||
|
setLabel(e.target.value);
|
||||||
|
setLabelTouched(true);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</Field>
|
</Field>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -195,6 +195,36 @@ describe("link pages", () => {
|
|||||||
expect((await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[0].id] })).status).toBe(400);
|
expect((await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[0].id] })).status).toBe(400);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("creates a new short link while adding a link button", async () => {
|
||||||
|
const { app, user } = setup();
|
||||||
|
const alice = user("alice");
|
||||||
|
const admin = user("root", true);
|
||||||
|
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
|
||||||
|
await alice.api("POST", "/pages", { kind: "redirect", code: "taken", dest: "https://t.test" });
|
||||||
|
|
||||||
|
const blocks = await (
|
||||||
|
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "Blog", newLink: { dest: "https://blog.test", code: "blog" } })
|
||||||
|
).json();
|
||||||
|
expect(blocks[0].target.path).toBe("/alice/blog");
|
||||||
|
expect((await app.request("/alice/blog")).headers.get("location")).toBe("https://blog.test");
|
||||||
|
|
||||||
|
// A taken code fails without leaving a button behind.
|
||||||
|
const clash = await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x", newLink: { dest: "https://x.test", code: "taken" } });
|
||||||
|
expect(clash.status).toBe(409);
|
||||||
|
expect((await (await alice.api("GET", `/pages/${page.id}`)).json()).blocks).toHaveLength(1);
|
||||||
|
|
||||||
|
// Exactly one of targetId and newLink.
|
||||||
|
expect((await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x" })).status).toBe(400);
|
||||||
|
expect(
|
||||||
|
(await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x", targetId: blocks[0].target.id, newLink: { dest: "https://x.test" } }))
|
||||||
|
.status,
|
||||||
|
).toBe(400);
|
||||||
|
|
||||||
|
// An admin editing Alice's page creates the link in Alice's namespace, with a random code.
|
||||||
|
const byAdmin = await (await admin.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "Shop", newLink: { dest: "https://shop.test" } })).json();
|
||||||
|
expect(byAdmin[1].target.path).toMatch(/^\/alice\/[A-Za-z0-9]{5}$/);
|
||||||
|
});
|
||||||
|
|
||||||
it("renders markdown without raw HTML or script links", async () => {
|
it("renders markdown without raw HTML or script links", async () => {
|
||||||
const { app, user } = setup();
|
const { app, user } = setup();
|
||||||
const alice = user("alice");
|
const alice = user("alice");
|
||||||
|
|||||||
Reference in New Issue
Block a user