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, ApiRequestError, errorMessage, useApi } from "../../api.js"; import { Button } from "../../components/ui/button.js"; import { Dialog, useConfirm } from "../../components/ui/dialog.js"; import { Field, Input, PrefixInput, Segmented, Select, Textarea } from "../../components/ui/form.js"; import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js"; import { useAction, useToast } 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; 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({ editing, page, me, onClose, onSaved, }: { editing: Editing; page: PageDetail; me: Me; onClose: () => void; onSaved: (blocks: Block[]) => void; }) { const isNewLink = editing?.kind === "link" && !editing.block; const pages = useApi(isNewLink ? "/pages" : null); const toast = useToast(); const [busy, setBusy] = useState(false); const [errors, setErrors] = useState>({}); const [source, setSource] = useState("existing"); const [targetId, setTargetId] = useState(""); const [dest, setDest] = useState(""); const [code, setCode] = useState(""); const [label, setLabel] = useState(""); const [labelTouched, setLabelTouched] = useState(false); const [markdown, setMarkdown] = useState(""); useEffect(() => { setErrors({}); setSource("existing"); setTargetId(""); setDest(""); setCode(""); setLabel(editing?.block?.label ?? ""); setLabelTouched(!!editing?.block); setMarkdown(editing?.block?.markdown ?? ""); }, [editing]); // 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 noTargets = !!pages.data && targets.length === 0; // Without existing links, creating one is the only option. useEffect(() => { if (noTargets) setSource("new"); }, [noTargets]); if (!editing) return ; const isNew = !editing.block; 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("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label }) : await api("POST", `/pages/${page.id}/blocks`, body()); onSaved(blocks); onClose(); 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 ( void submit()} title={editing.kind === "link" ? (isNew ? "Add link button" : "Edit link button") : isNew ? "Add text" : "Edit text"} description={editing.kind === "link" && isNew ? "Buttons point at a short link, so every click is counted." : undefined} footer={ <> } > {editing.kind === "link" ? ( <> {isNew && ( { setSource(v); setErrors({}); }} options={[ { value: "existing", label: "Existing link" }, { value: "new", label: "New link" }, ]} /> )} {isNew && source === "existing" && ( {(id) => ( )} )} {isNew && source === "new" && ( <> {(id) => ( { setDest(e.target.value); suggestLabel(e.target.value); }} /> )} {(id) => ( setCode(e.target.value)} /> )} )} {(id) => ( { setLabel(e.target.value); setLabelTouched(true); }} /> )} ) : ( {(id) =>