Skip to content

Link editor

Destination, short link and UTM tags in one dialog, with each error marked on its own field.

599 lines · React · Tailwind 4

Install

$ bunx shadcn@latest add @blocco/link-editor

Code

blocks/free/link-editor.tsx599 lines
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
import { Button } from "@/registry/blocco/ui/button";
import { Dialog, DialogClose, DialogTitle } from "@/registry/blocco/ui/dialog";
import { Field, FieldReason, Input, InvalidMark } from "@/registry/blocco/ui/field";
import { Globe, Pencil, Plus } from "@/registry/blocco/ui/icons";
import { MenuSelect } from "@/registry/blocco/ui/menu";
import { BusyContent } from "@/registry/blocco/ui/spinner";
import { Table, Td, Th } from "@/registry/blocco/ui/misc";
import { useToast } from "@/registry/blocco/ui/toast";
import { cn } from "@/registry/blocco/ui/cn";

const SHARED_HOST = "acme.link";
const CUSTOM_HOST = "go.acme.test";
/** Slugs another link already has on the custom domain, so the editor can say so. */
const TAKEN = ["pricing", "docs", "launch"];

interface LinkForm {
  destination: string;
  host: string;
  slug: string;
  title: string;
  utmSource: string;
  utmMedium: string;
  utmCampaign: string;
  utmTerm: string;
  utmContent: string;
}

interface SavedLink extends LinkForm {
  id: string;
  clicks: number;
}

type UtmKey = "utmSource" | "utmMedium" | "utmCampaign" | "utmTerm" | "utmContent";
const UTM: { key: UtmKey; param: string; label: string; placeholder: string }[] = [
  { key: "utmSource", param: "utm_source", label: "Source", placeholder: "newsletter" },
  { key: "utmMedium", param: "utm_medium", label: "Medium", placeholder: "email" },
  { key: "utmCampaign", param: "utm_campaign", label: "Campaign", placeholder: "spring-sale" },
  { key: "utmTerm", param: "utm_term", label: "Term", placeholder: "running-shoes" },
  { key: "utmContent", param: "utm_content", label: "Content", placeholder: "ad-variant-a" },
];

const blank: LinkForm = {
  destination: "",
  host: CUSTOM_HOST,
  slug: "",
  title: "",
  utmSource: "",
  utmMedium: "",
  utmCampaign: "",
  utmTerm: "",
  utmContent: "",
};

const initial: SavedLink[] = [
  {
    ...blank,
    id: "1",
    destination: "https://acme.test/pricing",
    slug: "pricing",
    title: "Pricing page",
    clicks: 1284,
  },
  {
    ...blank,
    id: "2",
    destination: "https://acme.test/blog/spring-launch?ref=home",
    slug: "launch",
    title: "Spring launch",
    utmSource: "newsletter",
    utmMedium: "email",
    clicks: 612,
  },
  {
    ...blank,
    id: "3",
    destination: "https://docs.acme.test/getting-started",
    host: SHARED_HOST,
    slug: "x7Kq2p",
    title: "",
    clicks: 87,
  },
];

interface FieldError {
  field: "destination" | "slug";
  reason: string;
  detail: string;
}

const withScheme = (raw: string) => (/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : `https://${raw}`);

/** A host with a dot, and no spaces: what a person means by a web address. */
function isWebAddress(raw: string): boolean {
  if (!raw || /\s/.test(raw)) return false;
  try {
    const url = new URL(withScheme(raw));
    return /^https?:$/.test(url.protocol) && url.hostname.includes(".");
  } catch {
    return false;
  }
}

/** The address with every utm_* parameter dropped, the way a save stores it. */
function withoutUtm(raw: string): string {
  try {
    const url = new URL(raw);
    for (const { param } of UTM) url.searchParams.delete(param);
    return url.toString();
  } catch {
    return raw;
  }
}

function hostOf(raw: string): string {
  if (!isWebAddress(raw.trim())) return "";
  return new URL(withScheme(raw.trim())).hostname;
}

/** Where the link will send people, split so the tags it adds can be told from the address typed. */
function openedUrl(form: LinkForm): { base: string; tags: string } | null {
  const raw = form.destination.trim();
  if (!raw) return null;
  if (!isWebAddress(raw)) return { base: raw, tags: "" };
  const url = new URL(withScheme(raw));
  for (const { param } of UTM) url.searchParams.delete(param);
  const hash = url.hash;
  url.hash = "";
  const tags = new URLSearchParams();
  for (const { param, key } of UTM) {
    const value = form[key].trim();
    if (value) tags.set(param, value);
  }
  const query = tags.toString();
  return {
    base: url.toString().replace(/^https?:\/\//, ""),
    tags: (query ? (url.search ? "&" : "?") + query : "") + hash,
  };
}

/** The site's first letter stands in for its favicon, since a strict CSP allows no remote images. */
function SiteLetter({ host }: { host: string }) {
  return (
    <span
      aria-hidden
      className="grid size-[22px] place-items-center rounded-md bg-accent/15 text-[11px] font-bold text-accent uppercase"
    >
      {host.replace(/^www\./, "")[0]}
    </span>
  );
}

/** The short link as a domain and a slug joined by a slash. Chosen slugs only exist on custom domains. */
function ShortLinkField({
  form,
  onChange,
  editing,
  slugRef,
  error,
}: {
  form: LinkForm;
  onChange: (patch: Partial<LinkForm>) => void;
  editing: boolean;
  slugRef: React.RefObject<HTMLInputElement | null>;
  error?: FieldError;
}) {
  const slugLocked = form.host === SHARED_HOST;
  const reasonId = "link-editor-slug-reason";
  return (
    <div className="min-w-0">
      <span className="mb-1.5 flex min-h-4 items-center gap-1.5 text-xs text-muted">
        Short link
        {error && <FieldReason id={reasonId} reason={error.reason} detail={error.detail} />}
      </span>
      {/* One ring around the three parts, the way one field reads as one. */}
      <div
        className={cn(
          "flex h-10 min-w-0 items-stretch rounded-lg smooth-shadow-ring-xs",
          error && "shadow-[0_0_0_1.5px_var(--danger)]",
        )}
      >
        <span className="flex w-[42%] max-w-[210px] min-w-0 shrink-0">
          <MenuSelect
            label="Domain"
            value={form.host}
            onChange={(host) => onChange({ host, slug: "" })}
            disabled={editing}
            className="h-10 min-w-0 rounded-l-lg rounded-r-none border-0 bg-surface font-mono text-[13px] [@media(hover:hover)]:hover:bg-surface-2"
            options={[
              { value: CUSTOM_HOST, label: CUSTOM_HOST },
              { value: SHARED_HOST, label: SHARED_HOST },
            ]}
          />
        </span>
        <span
          aria-hidden
          className="grid w-[22px] shrink-0 place-items-center bg-surface font-mono text-sm text-placeholder shadow-[inset_1px_0_0_color-mix(in_oklab,var(--text)_8%,transparent),inset_-1px_0_0_color-mix(in_oklab,var(--text)_8%,transparent)]"
        >
          /
        </span>
        <span className="relative flex min-w-0 flex-1">
          <Input
            ref={slugRef}
            aria-label="Slug"
            aria-invalid={error ? true : undefined}
            aria-describedby={error ? reasonId : undefined}
            value={form.slug}
            onChange={(e) => onChange({ slug: e.target.value })}
            placeholder={slugLocked ? "random" : "launch-2026"}
            disabled={slugLocked}
            autoComplete="off"
            autoCapitalize="none"
            spellCheck={false}
            className={cn(
              "h-10 min-w-0 flex-1 rounded-l-none font-mono text-[13px] shadow-none aria-invalid:shadow-none",
              error && "pr-8",
            )}
          />
          {error && <InvalidMark />}
        </span>
      </div>
      <span className="mt-1.5 block text-xs text-muted">
        {slugLocked
          ? "Use a custom domain for custom slugs."
          : editing
            ? "A link’s domain can’t change. Create a new link on the other domain instead."
            : "Leave the slug empty for a random one."}
      </span>
    </div>
  );
}

function LinkSummary({ form, opened }: { form: LinkForm; opened: ReturnType<typeof openedUrl> }) {
  const slug = form.slug.trim();
  return (
    <dl className="flex min-w-0 flex-col gap-3">
      <div className="flex min-w-0 flex-col gap-0.5">
        <dt className="text-xs text-muted">Short link</dt>
        {/* Clamped, and as tall as the clamp from the start (min-h in lh): a long
            slug would otherwise grow the column, and the dialog with it, a line
            per keystroke. The fields show the whole value. */}
        <dd className="line-clamp-2 min-h-[2lh] font-mono text-[13px] font-bold [overflow-wrap:anywhere]">
          {form.host}/{slug || <span className="font-sans font-normal text-muted">(random)</span>}
        </dd>
      </div>
      <div className="flex min-w-0 flex-col gap-0.5">
        <dt className="text-xs text-muted">Opens</dt>
        {/* The address and its tags clamp apart, so a long address never hides the tags just typed. */}
        <dd className="flex min-h-[4lh] flex-col font-mono text-[11.5px] leading-relaxed text-muted [overflow-wrap:anywhere]">
          {opened ? (
            <>
              <span className={opened.tags ? "line-clamp-2" : "line-clamp-4"}>{opened.base}</span>
              {opened.tags && <span className="line-clamp-2 text-text">{opened.tags}</span>}
            </>
          ) : (
            "Nothing yet"
          )}
        </dd>
      </div>
    </dl>
  );
}

// A phone sheet scrolls as one; this keeps its buttons on its bottom edge.
const PHONE_FOOTER =
  "sticky bottom-0 z-10 bg-surface px-5 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))] shadow-[0_-1px_0_color-mix(in_oklab,var(--text)_8%,transparent)] sm:hidden";

// The side column: the paper colour, split from the form by a hairline.
const ASIDE =
  "flex min-w-0 flex-col gap-4 bg-bg px-5 pt-4 pb-6 max-sm:shadow-[inset_0_1px_0_color-mix(in_oklab,var(--text)_8%,transparent)] sm:shadow-[inset_1px_0_0_color-mix(in_oklab,var(--text)_8%,transparent)]";

function Footer({ children, className }: { children: ReactNode; className?: string }) {
  return <div className={cn("flex items-center justify-end gap-1.5", className)}>{children}</div>;
}

function LinkEditorDialog({
  open,
  onOpenChange,
  editingLink,
  onSaved,
  onDelete,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingLink: SavedLink | null;
  onSaved: (form: LinkForm) => void;
  onDelete: () => void;
}) {
  const editing = editingLink != null;
  const toast = useToast();
  const [form, setForm] = useState<LinkForm>(blank);
  const [error, setError] = useState<FieldError | null>(null);
  const [busy, setBusy] = useState(false);
  const [shaking, setShaking] = useState(false);
  const destinationRef = useRef<HTMLInputElement>(null);
  const slugRef = useRef<HTMLInputElement>(null);

  // The dialog stays mounted to animate, so opening it is the reset.
  useEffect(() => {
    if (!open) return;
    setForm(editingLink ?? blank);
    setError(null);
    setBusy(false);
  }, [open, editingLink]);

  const change = (patch: Partial<LinkForm>) => {
    setForm((f) => ({ ...f, ...patch }));
    // A fixed field drops its mark as it is edited.
    if (error && (error.field in patch || "host" in patch)) setError(null);
  };

  /** Marks one field, says why in its label row, and puts focus on it. */
  const mark = (next: FieldError) => {
    setError(next);
    setShaking(true);
    requestAnimationFrame(() =>
      (next.field === "slug" ? slugRef : destinationRef).current?.focus(),
    );
  };

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (busy) return;
    const destination = form.destination.trim();
    if (!destination)
      return mark({
        field: "destination",
        reason: "Required",
        detail: "Enter the address this link opens",
      });
    if (!isWebAddress(destination))
      return mark({
        field: "destination",
        reason: "Not a web address",
        detail: "Enter a full address, like https://example.com/menu",
      });
    const slug = form.slug.trim();
    if (form.host === CUSTOM_HOST && slug && !/^[a-z0-9][a-z0-9-]*$/i.test(slug))
      return mark({
        field: "slug",
        reason: "Letters, numbers, hyphens",
        detail: "A slug uses letters, numbers and hyphens, and starts with a letter or number.",
      });
    if (!editing && form.host === CUSTOM_HOST && TAKEN.includes(slug.toLowerCase()))
      return mark({
        field: "slug",
        reason: "Already taken",
        detail: `${CUSTOM_HOST}/${slug} already opens another link. Choose a different slug.`,
      });
    setBusy(true);
    await new Promise((r) => setTimeout(r, 700));
    setBusy(false);
    onSaved(form);
    onOpenChange(false);
    toast(editing ? "Link saved" : "Link created", "info", {
      code: `${form.host}/${form.slug.trim() || "random"}`,
    });
  };

  const host = hostOf(form.destination);
  const opened = openedUrl(form);
  const title = editing ? "Edit link" : "New link";

  const actions = (
    <>
      {editing && (
        <Button variant="danger" onClick={onDelete} className="mr-auto px-2.5">
          Delete
        </Button>
      )}
      <Button
        variant="ghost"
        onClick={() => onOpenChange(false)}
        className={cn(editing && "px-2.5")}
      >
        Cancel
      </Button>
      <Button
        variant="primary"
        type="submit"
        disabled={busy}
        className={cn("whitespace-nowrap", shaking && "link-editor-shake")}
        onAnimationEnd={() => setShaking(false)}
      >
        <BusyContent busy={busy}>{editing ? "Save changes" : "Create link"}</BusyContent>
      </Button>
    </>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange} title={title} size="xl" bare>
      <form
        onSubmit={(e) => void submit(e)}
        noValidate
        className="grid min-h-full sm:grid-cols-[minmax(0,1fr)_280px]"
      >
        <div className="flex min-w-0 flex-col gap-[18px] px-5 pt-3 pb-6 sm:px-6 sm:pt-5">
          <div className="flex min-h-8 items-center gap-2">
            <DialogTitle className="flex-1">{title}</DialogTitle>
            <DialogClose className="-mr-1.5 sm:hidden" />
          </div>

          <Field
            label="Destination"
            error={error?.field === "destination" ? error.reason : undefined}
            errorDetail={error?.field === "destination" ? error.detail : undefined}
          >
            <span className="relative block">
              <span className="pointer-events-none absolute top-1/2 left-2.5 z-10 -translate-y-1/2">
                {host ? (
                  <SiteLetter host={host} />
                ) : (
                  <span className="grid size-[22px] place-items-center text-placeholder">
                    <Globe size={15} aria-hidden />
                  </span>
                )}
              </span>
              <Input
                ref={destinationRef}
                value={form.destination}
                onChange={(e) => change({ destination: e.target.value })}
                // A URL keyboard on a text field: the form's own check marks the
                // field, where type="url" would have the browser refuse first in
                // a bubble of its own.
                inputMode="url"
                autoComplete="off"
                autoCapitalize="none"
                spellCheck={false}
                placeholder="https://example.com/launch"
                autoFocus={!editing}
                className="h-11 rounded-[10px] pl-10 font-mono text-[13.5px]"
              />
            </span>
          </Field>

          <ShortLinkField
            form={form}
            onChange={change}
            editing={editing}
            slugRef={slugRef}
            error={error?.field === "slug" ? error : undefined}
          />

          <Field label="Title" optional>
            <Input
              value={form.title}
              onChange={(e) => change({ title: e.target.value })}
              placeholder="Spring launch"
              className="h-10"
            />
          </Field>

          <fieldset className="flex min-w-0 flex-col gap-2">
            <legend className="mb-2 text-sm font-semibold">UTM tags</legend>
            <div className="grid grid-cols-1 gap-2 min-[420px]:grid-cols-3">
              {UTM.slice(0, 3).map((f) => (
                <UtmInput key={f.key} field={f} form={form} onChange={change} />
              ))}
            </div>
            <div className="grid grid-cols-1 gap-2 min-[420px]:grid-cols-2">
              {UTM.slice(3).map((f) => (
                <UtmInput key={f.key} field={f} form={form} onChange={change} />
              ))}
            </div>
          </fieldset>
        </div>

        <aside className={ASIDE}>
          <div className="flex justify-end max-sm:hidden">
            <DialogClose className="-mr-1.5" />
          </div>
          <LinkSummary form={form} opened={opened} />
          <Footer className="mt-auto pt-1 max-sm:hidden">{actions}</Footer>
        </aside>
        <Footer className={PHONE_FOOTER}>{actions}</Footer>
      </form>
    </Dialog>
  );
}

function UtmInput({
  field,
  form,
  onChange,
}: {
  field: (typeof UTM)[number];
  form: LinkForm;
  onChange: (patch: Partial<LinkForm>) => void;
}) {
  return (
    <Field label={field.label}>
      <Input
        value={form[field.key]}
        onChange={(e) => onChange({ [field.key]: e.target.value })}
        placeholder={field.placeholder}
        autoComplete="off"
        autoCapitalize="none"
        spellCheck={false}
        className="px-2.5 font-mono text-xs"
      />
    </Field>
  );
}

/** A list of links with the editor behind New link and Edit. Nothing saves anywhere. */
export default function LinkEditor() {
  const toast = useToast();
  const [links, setLinks] = useState(initial);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<SavedLink | null>(null);

  const openEditor = (link: SavedLink | null) => {
    setEditing(link);
    setOpen(true);
  };

  return (
    <section className="mx-auto max-w-4xl px-4 py-10 sm:px-6 sm:py-12">
      <div className="mb-6 flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold tracking-tight text-balance">Links</h1>
          <p className="tnum mt-1 text-sm text-muted">{links.length} links on Acme.</p>
        </div>
        <Button variant="primary" onClick={() => openEditor(null)}>
          <Plus size={14} /> New link
        </Button>
      </div>

      <Table minWidth="min-w-[32rem]">
        <thead>
          <tr>
            <Th>Link</Th>
            <Th className="w-24 text-right">Clicks</Th>
            <Th className="w-14" aria-label="Actions" />
          </tr>
        </thead>
        <tbody>
          {links.map((l) => (
            <tr key={l.id}>
              <Td>
                <div className="min-w-0">
                  <span className="block truncate text-sm font-medium">
                    {l.title || l.destination.replace(/^https?:\/\//, "")}
                  </span>
                  <span className="block truncate font-mono text-xs text-muted">
                    {l.host}/{l.slug}
                  </span>
                </div>
              </Td>
              <Td className="tnum text-right">{l.clicks.toLocaleString("en-US")}</Td>
              <Td>
                <div className="flex justify-end">
                  <button
                    type="button"
                    aria-label={`Edit ${l.host}/${l.slug}`}
                    onClick={() => openEditor(l)}
                    className="grid size-9 cursor-pointer place-items-center rounded-lg text-muted transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-accent [@media(hover:hover)]:hover:bg-surface-2 [@media(hover:hover)]:hover:text-text"
                  >
                    <Pencil size={15} aria-hidden />
                  </button>
                </div>
              </Td>
            </tr>
          ))}
        </tbody>
      </Table>

      <LinkEditorDialog
        open={open}
        onOpenChange={setOpen}
        editingLink={editing}
        onSaved={(saved) => {
          // The tags are saved on their own fields, so the stored address has none.
          const form = { ...saved, destination: withoutUtm(saved.destination) };
          setLinks((all) =>
            editing
              ? all.map((l) => (l.id === editing.id ? { ...l, ...form } : l))
              : [
                  {
                    ...form,
                    id: crypto.randomUUID(),
                    slug: form.slug.trim() || "r4nD0m",
                    clicks: 0,
                  },
                  ...all,
                ],
          );
        }}
        onDelete={() => {
          if (!editing) return;
          setLinks((all) => all.filter((l) => l.id !== editing.id));
          setOpen(false);
          toast("Link deleted", "info", { code: `${editing.host}/${editing.slug}` });
        }}
      />
    </section>
  );
}