Skip to content

Open source CapCut alternative.

TypeScript

feat(site): blog CMS in su

David Le34cf53c92d05
diff --git a/site/src/app/api/blog/preview/exit/route.ts b/site/src/app/api/blog/preview/exit/route.ts
new file mode 100644
index 00000000..7e80c23e
--- /dev/null
+++ b/site/src/app/api/blog/preview/exit/route.ts
@@ -0,0 +1,11 @@
+import { draftMode } from "next/headers";
+import { NextResponse } from "next/server";
+
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+
+// Leaves Draft Mode. Reached from the banner on a previewed draft by a plain
+// anchor, since a prefetched link would clear the cookie before the click.
+export const GET = withDonkeyAuth(async (request) => {
+ (await draftMode()).disable();
+ return NextResponse.redirect(new URL("/blog", request.url));
+});
diff --git a/site/src/app/api/blog/preview/route.ts b/site/src/app/api/blog/preview/route.ts
new file mode 100644
index 00000000..8d5ebe3f
--- /dev/null
+++ b/site/src/app/api/blog/preview/route.ts
@@ -0,0 +1,21 @@
+import { draftMode } from "next/headers";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { blogPath } from "@/lib/blog/keys";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+const idSchema = z.string().trim().min(1);
+
+// The su editor's Preview button lands here on the apex host, because the
+// Draft Mode cookie is host-only. Draft Mode makes the blog's cached reads run
+// fresh for this browser and include drafts; everyone else keeps the cache.
+export const GET = withSuperUser(async (request) => {
+ const id = idSchema.safeParse(request.nextUrl.searchParams.get("id"));
+ if (!id.success) return notFoundResponse();
+ const post = await prisma.blogPost.findUnique({ select: { slug: true }, where: { id: id.data } });
+ if (!post) return notFoundResponse();
+ (await draftMode()).enable();
+ return NextResponse.redirect(new URL(blogPath(post.slug), request.url));
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts b/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts
new file mode 100644
index 00000000..5f8f0a04
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { adminPost } from "@/lib/blog/admin";
+import { revalidateBlog } from "@/lib/blog/revalidate";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+const bodySchema = z.object({ kind: z.enum(["header", "thumbnail"]) }).strict();
+
+// Clears the header or thumbnail from the row. The object stays under the
+// post's prefix, content-addressed, and goes when the post does.
+export const POST = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const parsed = bodySchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const existing = await prisma.blogPost.findUnique({ select: { id: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const row = await prisma.blogPost.update({
+ where: { id: existing.id },
+ data: parsed.data.kind === "header" ? { headerKey: null, headerAlt: null, headerFocus: null } : { thumbnailKey: null },
+ });
+ revalidateBlog([row.slug]);
+ return NextResponse.json({ post: adminPost(row) });
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/images/route.ts b/site/src/app/api/su/blog/posts/[id]/images/route.ts
new file mode 100644
index 00000000..21a8e61d
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/images/route.ts
@@ -0,0 +1,56 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { del, getObject, putObject } from "@/cut/server/cloud/r2";
+import { adminPost } from "@/lib/blog/admin";
+import { encodeBlogImage } from "@/lib/blog/images";
+import { blogImageKey, blogImageUrl, blogPrefix } from "@/lib/blog/keys";
+import { revalidateBlog } from "@/lib/blog/revalidate";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+const bodySchema = z
+ .object({
+ uploadKey: z.string().min(1),
+ kind: z.enum(["header", "thumbnail", "inline"]),
+ })
+ .strict();
+
+// Turns an upload into the image the pages serve: read from the scratch key,
+// encoded to the kind's size, written under its own hash, and the scratch
+// deleted. A header or thumbnail is also set on the row.
+export const POST = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const parsed = bodySchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const existing = await prisma.blogPost.findUnique({ select: { id: true, slug: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const { uploadKey, kind } = parsed.data;
+ // A route reads only under its own prefix, so a key from the body cannot
+ // reach into another post or another user's media.
+ if (!uploadKey.startsWith(`${blogPrefix(existing.id)}uploads/`)) {
+ return invalidResponse([{ path: ["uploadKey"], message: "Not an upload for this post." }]);
+ }
+ const upload = await getObject(uploadKey);
+ if (!upload) return invalidResponse([{ path: ["uploadKey"], message: "The upload was not found." }]);
+
+ const encoded = await encodeBlogImage(upload.bytes, kind);
+ const key = blogImageKey(existing.id, encoded.sha256);
+ await putObject(key, encoded.bytes, "image/avif");
+ await del([uploadKey]);
+
+ const image = { key, url: blogImageUrl(key), width: encoded.width, height: encoded.height };
+ if (kind === "inline") return NextResponse.json({ image });
+
+ const row = await prisma.blogPost.update({
+ where: { id: existing.id },
+ data: kind === "header" ? { headerKey: key } : { thumbnailKey: key },
+ });
+ revalidateBlog([row.slug]);
+ return NextResponse.json({ image, post: adminPost(row) });
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/publish/route.ts b/site/src/app/api/su/blog/posts/[id]/publish/route.ts
new file mode 100644
index 00000000..79339cbe
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/publish/route.ts
@@ -0,0 +1,46 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { adminPost } from "@/lib/blog/admin";
+import { readBody } from "@/lib/blog/read";
+import { revalidateBlog } from "@/lib/blog/revalidate";
+import { publishIssues } from "@/lib/blog/schema";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// Publishing holds the post to the full contract, then dates it if the editor
+// left the date empty. One featured post at a time: featuring this one clears
+// the others.
+export const POST = withSuperUser(async (_request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const existing = await prisma.blogPost.findUnique({ where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const body = await readBody(existing.id);
+ const issues = publishIssues({
+ title: existing.title,
+ excerpt: existing.excerpt,
+ summary: existing.summary,
+ headerKey: existing.headerKey,
+ thumbnailKey: existing.thumbnailKey,
+ publishedAt: existing.publishedAt?.toISOString() ?? null,
+ body,
+ });
+ if (issues.length > 0) {
+ return NextResponse.json({ error: "Not ready to publish", issues }, { status: 400 });
+ }
+ const [row] = await prisma.$transaction([
+ prisma.blogPost.update({
+ where: { id: id.data },
+ data: { status: "PUBLISHED", publishedAt: existing.publishedAt ?? new Date() },
+ }),
+ ...(existing.featured
+ ? [prisma.blogPost.updateMany({ where: { featured: true, id: { not: id.data } }, data: { featured: false } })]
+ : []),
+ ]);
+ revalidateBlog([row.slug]);
+ return NextResponse.json({ post: { ...adminPost(row), body } });
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/route.ts b/site/src/app/api/su/blog/posts/[id]/route.ts
new file mode 100644
index 00000000..1aa11a9d
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/route.ts
@@ -0,0 +1,86 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { deletePrefix, putObject } from "@/cut/server/cloud/r2";
+import { Prisma } from "@/generated/prisma/client";
+import { adminPost } from "@/lib/blog/admin";
+import { blogBodyKey, blogPrefix } from "@/lib/blog/keys";
+import { readBody } from "@/lib/blog/read";
+import { revalidateBlog } from "@/lib/blog/revalidate";
+import { blogPostInputSchema } from "@/lib/blog/schema";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+export const GET = withSuperUser(async (_request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const row = await prisma.blogPost.findUnique({ where: { id: id.data } });
+ if (!row) return notFoundResponse();
+ return NextResponse.json({ post: { ...adminPost(row), body: await readBody(row.id) } });
+});
+
+// A save: the fields onto the row, the body into R2 when it changed. Both the
+// old and the new slug are cleared from the cache, so a renamed post stops
+// answering at its old address.
+export const PUT = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const parsed = blogPostInputSchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const existing = await prisma.blogPost.findUnique({ where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const input = parsed.data;
+
+ const bodyChanged = input.body !== (await readBody(existing.id));
+ if (bodyChanged) await putObject(blogBodyKey(existing.id), Buffer.from(input.body, "utf8"), "text/markdown");
+
+ let row;
+ try {
+ row = await prisma.blogPost.update({
+ where: { id: id.data },
+ data: {
+ slug: input.slug,
+ title: input.title,
+ excerpt: input.excerpt,
+ summary: input.summary || null,
+ tags: input.tags,
+ keywords: input.keywords,
+ featured: input.featured,
+ publishedAt: input.publishedAt ? new Date(input.publishedAt) : null,
+ revisedAt: input.revisedAt ? new Date(input.revisedAt) : null,
+ headerAlt: input.headerAlt || null,
+ headerFocus: input.headerFocus,
+ seoTitle: input.seoTitle || null,
+ canonicalUrl: input.canonicalUrl || null,
+ noIndex: input.noIndex,
+ ...(bodyChanged ? { bodyVersion: { increment: 1 } } : {}),
+ },
+ });
+ } catch (error) {
+ if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
+ return NextResponse.json(
+ { error: "Invalid request", issues: [{ path: "slug", message: "Another post has that slug." }] },
+ { status: 409 },
+ );
+ }
+ throw error;
+ }
+ revalidateBlog([existing.slug, row.slug]);
+ return NextResponse.json({ post: { ...adminPost(row), body: input.body } });
+});
+
+// Deleting a post removes its row and sweeps everything it owned in R2.
+export const DELETE = withSuperUser(async (_request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const existing = await prisma.blogPost.findUnique({ where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ await prisma.blogPost.delete({ where: { id: id.data } });
+ await deletePrefix(blogPrefix(existing.id));
+ revalidateBlog([existing.slug]);
+ return NextResponse.json({ ok: true });
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts b/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts
new file mode 100644
index 00000000..8b572f54
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts
@@ -0,0 +1,23 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { adminPost } from "@/lib/blog/admin";
+import { readBody } from "@/lib/blog/read";
+import { revalidateBlog } from "@/lib/blog/revalidate";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// Back to a draft. The page answers 404 from the next request on; the date is
+// kept so republishing lands the post where it was.
+export const POST = withSuperUser(async (_request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const existing = await prisma.blogPost.findUnique({ select: { id: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const row = await prisma.blogPost.update({ where: { id: id.data }, data: { status: "DRAFT" } });
+ revalidateBlog([row.slug]);
+ return NextResponse.json({ post: { ...adminPost(row), body: await readBody(row.id) } });
+});
diff --git a/site/src/app/api/su/blog/posts/[id]/uploads/route.ts b/site/src/app/api/su/blog/posts/[id]/uploads/route.ts
new file mode 100644
index 00000000..2235b461
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/[id]/uploads/route.ts
@@ -0,0 +1,37 @@
+import { randomUUID } from "node:crypto";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { presignPut } from "@/cut/server/cloud/r2";
+import { blogUploadKey } from "@/lib/blog/keys";
+import { invalidResponse } from "@/lib/config/experimentList";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+type Params = { params: Promise<{ id: string }> };
+const idSchema = z.string().trim().min(1);
+
+// What the encoder can read. HEIC needs a decoder the bundled sharp lacks.
+export const BLOG_UPLOAD_MIMES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
+export const BLOG_UPLOAD_MAX_BYTES = 25 * 1024 * 1024;
+
+const bodySchema = z
+ .object({
+ mime: z.string().refine((mime) => BLOG_UPLOAD_MIMES.has(mime), "Not an image the blog can take."),
+ bytes: z.number().int().positive().max(BLOG_UPLOAD_MAX_BYTES, "Keep images under 25 MB."),
+ })
+ .strict();
+
+// Image bytes never ride a request body here (the platform caps it at the
+// edge). The browser gets a one-hour PUT to a scratch key under the post, then
+// names that key to the images route, which encodes and deletes it.
+export const POST = withSuperUser(async (request, { params }: Params) => {
+ const id = idSchema.safeParse((await params).id);
+ if (!id.success) return notFoundResponse();
+ const parsed = bodySchema.safeParse(await request.json());
+ if (!parsed.success) return invalidResponse(parsed.error.issues);
+ const existing = await prisma.blogPost.findUnique({ select: { id: true }, where: { id: id.data } });
+ if (!existing) return notFoundResponse();
+ const key = blogUploadKey(existing.id, randomUUID());
+ return NextResponse.json({ key, putUrl: await presignPut(key, parsed.data.mime, parsed.data.bytes) });
+});
diff --git a/site/src/app/api/su/blog/posts/route.ts b/site/src/app/api/su/blog/posts/route.ts
new file mode 100644
index 00000000..a8f4c0a2
--- /dev/null
+++ b/site/src/app/api/su/blog/posts/route.ts
@@ -0,0 +1,24 @@
+import { randomBytes } from "node:crypto";
+import { NextResponse } from "next/server";
+
+import { adminPost, listAdminPosts } from "@/lib/blog/admin";
+import { withSuperUser } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+// Every post, newest change first.
+export const GET = withSuperUser(async () => {
+ return NextResponse.json({ posts: await listAdminPosts() });
+});
+
+// A new draft. It exists before anything is typed so images can upload under
+// its id; the editor opens on it.
+export const POST = withSuperUser(async (request) => {
+ const row = await prisma.blogPost.create({
+ data: {
+ slug: `untitled-${randomBytes(3).toString("hex")}`,
+ title: "",
+ authorUserId: request.donkey.userId,
+ },
+ });
+ return NextResponse.json({ post: adminPost(row) });
+});
diff --git a/site/src/app/su/SuHeader.tsx b/site/src/app/su/SuHeader.tsx
index dc64f7ec..29359da3 100644
--- a/site/src/app/su/SuHeader.tsx
+++ b/site/src/app/su/SuHeader.tsx
@@ -4,6 +4,7 @@ import { usePathname } from "next/navigation";
import type { ComponentType } from "react";
import { RunAnalyticsButton } from "@/app/su/analytics/RunAnalyticsButton";
+import { NewPostButton } from "@/app/su/blog/NewPostButton";
import { DrainNowButton } from "@/app/su/jobs/email/DrainNowButton";
import { suSurfaceAt, type SuPage } from "@/app/su/nav";
import { ScanOutreachButton } from "@/app/su/outreach/ScanOutreachButton";
@@ -14,6 +15,7 @@ import { SidebarTrigger } from "@/components/ui/sidebar";
// components live here.
const PAGE_ACTIONS: Partial<Record<SuPage["href"], ComponentType>> = {
"/analytics/product": RunAnalyticsButton,
+ "/blog": NewPostButton,
"/jobs/email": DrainNowButton,
"/outreach": ScanOutreachButton,
};
diff --git a/site/src/app/su/SuSidebar.tsx b/site/src/app/su/SuSidebar.tsx
index d70da15f..8ce1d768 100644
--- a/site/src/app/su/SuSidebar.tsx
+++ b/site/src/app/su/SuSidebar.tsx
@@ -11,6 +11,7 @@ import {
ListChecks,
Mail,
Megaphone,
+ Newspaper,
Package,
UserRound,
} from "lucide-react";
@@ -42,6 +43,7 @@ import { SU_APP_ORIGIN } from "@/cut/lib/hosts";
// of React so the proxy can read it, so the icons live here.
const SURFACE_ICONS: Record<SuSurface["href"], typeof UserRound> = {
"/analytics": ChartColumn,
+ "/blog": Newspaper,
"/credits": CreditCard,
"/experiments": FlaskConical,
"/jobs": ListChecks,
diff --git a/site/src/app/su/blog/NewPostButton.tsx b/site/src/app/su/blog/NewPostButton.tsx
new file mode 100644
index 00000000..2cbf2c70
--- /dev/null
+++ b/site/src/app/su/blog/NewPostButton.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+
+import { Button } from "@/components/ui/button";
+import { useCreateBlogPost } from "@/queries/blog";
+
+// Makes a draft and opens it. The draft exists before a word is typed so the
+// editor has a post id to upload images under.
+export function NewPostButton() {
+ const router = useRouter();
+ const create = useCreateBlogPost();
+ return (
+ <div className="flex items-center gap-3">
+ {create.isError ? <span className="text-sm text-destructive">Couldn’t create the post.</span> : null}
+ <Button
+ size="sm"
+ disabled={create.isPending}
+ onClick={() => create.mutate(undefined, { onSuccess: ({ post }) => router.push(`/blog/${post.id}`) })}
+ >
+ {create.isPending ? "Creating…" : "New post"}
+ </Button>
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/[id]/BlogEditor.tsx b/site/src/app/su/blog/[id]/BlogEditor.tsx
new file mode 100644
index 00000000..d4e70c0c
--- /dev/null
+++ b/site/src/app/su/blog/[id]/BlogEditor.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import dynamic from "next/dynamic";
+
+import { Skeleton } from "@/components/ui/skeleton";
+
+export type BlogEditorProps = {
+ markdown: string;
+ // What the post last saved as, shown beside the draft in diff mode.
+ diffMarkdown: string;
+ onChange: (markdown: string) => void;
+ uploadImage: (file: File) => Promise<string>;
+};
+
+// The editor reaches into the DOM (contentEditable, CodeMirror), so it loads
+// in the browser only; the page keeps its shape with a stand-in until then.
+const Inner = dynamic(() => import("./BlogEditorInner"), {
+ ssr: false,
+ loading: () => <Skeleton className="h-[60vh] rounded-xl" />,
+});
+
+export function BlogEditor(props: BlogEditorProps) {
+ return <Inner {...props} />;
+}
diff --git a/site/src/app/su/blog/[id]/BlogEditorInner.tsx b/site/src/app/su/blog/[id]/BlogEditorInner.tsx
new file mode 100644
index 00000000..0e27a2f3
--- /dev/null
+++ b/site/src/app/su/blog/[id]/BlogEditorInner.tsx
@@ -0,0 +1,283 @@
+"use client";
+
+import "@mdxeditor/editor/style.css";
+
+import {
+ BlockTypeSelect,
+ BoldItalicUnderlineToggles,
+ ButtonWithTooltip,
+ CodeToggle,
+ CreateLink,
+ DialogButton,
+ DiffSourceToggleWrapper,
+ GenericJsxEditor,
+ InsertCodeBlock,
+ InsertImage,
+ InsertTable,
+ InsertThematicBreak,
+ ListsToggle,
+ MDXEditor,
+ Separator,
+ UndoRedo,
+ codeBlockPlugin,
+ codeMirrorPlugin,
+ diffSourcePlugin,
+ headingsPlugin,
+ imagePlugin,
+ insertJsx$,
+ jsxPlugin,
+ linkDialogPlugin,
+ linkPlugin,
+ listsPlugin,
+ markdownShortcutPlugin,
+ quotePlugin,
+ rootEditor$,
+ tablePlugin,
+ thematicBreakPlugin,
+ toolbarPlugin,
+ useCellValue,
+ useLexicalNodeRemove,
+ useMdastNodeUpdater,
+ usePublisher,
+ type JsxComponentDescriptor,
+ type JsxEditorProps,
+} from "@mdxeditor/editor";
+import { COMMAND_PRIORITY_HIGH, PASTE_COMMAND } from "lexical";
+import { Megaphone, MessageSquareQuote, Video } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+
+import { BlogVideo } from "@/app/cut/blog/_components/BlogVideo";
+import { BLOG_ARTICLE_CLASS } from "@/app/cut/blog/_components/mdxComponents";
+import type { BlogEditorProps } from "@/app/su/blog/[id]/BlogEditor";
+import { parseVideoUrl } from "@/lib/blog/video";
+
+// The article editor. The body is MDX: markdown with three named blocks the
+// public page knows (Video, BlogCTA, InlineCTA). Images land at the cursor
+// from a drop, a paste, or the toolbar, and each upload comes back as the
+// public address, so the saved markdown is a plain image line.
+
+const CODE_LANGUAGES = {
+ "": "Plain text",
+ bash: "Shell",
+ css: "CSS",
+ html: "HTML",
+ js: "JavaScript",
+ json: "JSON",
+ ts: "TypeScript",
+ tsx: "TSX",
+};
+
+const stringAttr = (node: JsxEditorProps["mdastNode"], name: string): string => {
+ const found = node.attributes.find((attr) => attr.type === "mdxJsxAttribute" && attr.name === name);
+ return found && typeof found.value === "string" ? found.value : "";
+};
+
+// <Video src="…" /> in the editor: the same player the article shows, with
+// the address editable underneath.
+function VideoJsxEditor({ mdastNode }: JsxEditorProps) {
+ const update = useMdastNodeUpdater();
+ const remove = useLexicalNodeRemove();
+ const src = stringAttr(mdastNode, "src");
+ const title = stringAttr(mdastNode, "title");
+ const known = parseVideoUrl(src) !== null;
+ const set = (name: string, value: string) => {
+ const rest = mdastNode.attributes.filter((attr) => !(attr.type === "mdxJsxAttribute" && attr.name === name));
+ update({
+ attributes: value ? [...rest, { type: "mdxJsxAttribute", name, value }] : rest,
+ });
+ };
+ return (
+ <div contentEditable={false} className="my-4 space-y-2">
+ {src ? <BlogVideo src={src} title={title || undefined} /> : null}
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <label className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="shrink-0 text-muted-foreground">Video</span>
+ <input
+ value={src}
+ placeholder="YouTube, Vimeo or .mp4 address"
+ className="min-w-0 flex-1 rounded-md border px-2 py-1"
+ onChange={(event) => set("src", event.target.value.trim())}
+ />
+ </label>
+ <label className="flex items-center gap-2">
+ <span className="text-muted-foreground">Title</span>
+ <input
+ value={title}
+ className="w-40 rounded-md border px-2 py-1"
+ onChange={(event) => set("title", event.target.value)}
+ />
+ </label>
+ <button type="button" className="text-muted-foreground hover:text-destructive" onClick={remove}>
+ Remove
+ </button>
+ </div>
+ {src && !known ? (
+ <p className="text-xs text-destructive">Not a video address the page can play; it renders as a link.</p>
+ ) : null}
+ </div>
+ );
+}
+
+const JSX_DESCRIPTORS: JsxComponentDescriptor[] = [
+ {
+ name: "Video",
+ kind: "flow",
+ props: [
+ { name: "src", type: "string" },
+ { name: "title", type: "string" },
+ ],
+ hasChildren: false,
+ Editor: VideoJsxEditor,
+ },
+ {
+ name: "BlogCTA",
+ kind: "flow",
+ props: [
+ { name: "variant", type: "string" },
+ { name: "title", type: "string" },
+ { name: "description", type: "string" },
+ { name: "buttonText", type: "string" },
+ { name: "buttonHref", type: "string" },
+ ],
+ hasChildren: false,
+ Editor: GenericJsxEditor,
+ },
+ {
+ name: "InlineCTA",
+ kind: "flow",
+ props: [],
+ hasChildren: false,
+ Editor: GenericJsxEditor,
+ },
+];
+
+// A bare video address pasted on its own becomes a Video block where the
+// cursor is. The check is the address's host or file extension, nothing more.
+function VideoPaste() {
+ const editor = useCellValue(rootEditor$);
+ const insertJsx = usePublisher(insertJsx$);
+ useEffect(() => {
+ if (!editor) return;
+ return editor.registerCommand(
+ PASTE_COMMAND,
+ (event) => {
+ if (!(event instanceof ClipboardEvent) || !event.clipboardData) return false;
+ if (event.clipboardData.files.length > 0) return false;
+ const text = event.clipboardData.getData("text/plain").trim();
+ if (!text || /\s/.test(text) || !parseVideoUrl(text)) return false;
+ event.preventDefault();
+ insertJsx({ name: "Video", kind: "flow", props: { src: text } });
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+ }, [editor, insertJsx]);
+ return null;
+}
+
+function InsertVideo() {
+ const insertJsx = usePublisher(insertJsx$);
+ return (
+ <DialogButton
+ tooltipTitle="Insert video"
+ submitButtonTitle="Insert"
+ dialogInputPlaceholder="YouTube, Vimeo or .mp4 address"
+ buttonContent={<Video className="size-5" />}
+ onSubmit={(value) => {
+ const src = value.trim();
+ if (src) insertJsx({ name: "Video", kind: "flow", props: { src } });
+ }}
+ />
+ );
+}
+
+function InsertCtas() {
+ const insertJsx = usePublisher(insertJsx$);
+ return (
+ <>
+ <ButtonWithTooltip
+ title="Insert call to action banner"
+ onClick={() => insertJsx({ name: "BlogCTA", kind: "flow", props: { variant: "banner" } })}
+ >
+ <Megaphone className="size-5" />
+ </ButtonWithTooltip>
+ <ButtonWithTooltip
+ title="Insert inline call to action"
+ onClick={() => insertJsx({ name: "InlineCTA", kind: "flow", props: {} })}
+ >
+ <MessageSquareQuote className="size-5" />
+ </ButtonWithTooltip>
+ </>
+ );
+}
+
+export default function BlogEditorInner({ markdown, diffMarkdown, onChange, uploadImage }: BlogEditorProps) {
+ const [parseError, setParseError] = useState<string | null>(null);
+
+ const plugins = useMemo(
+ () => [
+ headingsPlugin({ allowedHeadingLevels: [2, 3, 4] }),
+ listsPlugin(),
+ quotePlugin(),
+ thematicBreakPlugin(),
+ linkPlugin(),
+ linkDialogPlugin(),
+ tablePlugin(),
+ imagePlugin({ imageUploadHandler: uploadImage }),
+ codeBlockPlugin({ defaultCodeBlockLanguage: "" }),
+ codeMirrorPlugin({ codeBlockLanguages: CODE_LANGUAGES }),
+ jsxPlugin({ jsxComponentDescriptors: JSX_DESCRIPTORS }),
+ markdownShortcutPlugin(),
+ diffSourcePlugin({ viewMode: "rich-text", diffMarkdown }),
+ toolbarPlugin({
+ toolbarContents: () => (
+ <DiffSourceToggleWrapper>
+ <VideoPaste />
+ <UndoRedo />
+ <Separator />
+ <BoldItalicUnderlineToggles />
+ <CodeToggle />
+ <Separator />
+ <BlockTypeSelect />
+ <Separator />
+ <ListsToggle />
+ <Separator />
+ <CreateLink />
+ <InsertImage />
+ <InsertVideo />
+ <Separator />
+ <InsertTable />
+ <InsertThematicBreak />
+ <InsertCodeBlock />
+ <Separator />
+ <InsertCtas />
+ </DiffSourceToggleWrapper>
+ ),
+ }),
+ ],
+ // The diff baseline is read when the plugin mounts; a later save updates
+ // it through the editor's own state.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [uploadImage],
+ );
+
+ return (
+ <div className="overflow-hidden rounded-xl border bg-white">
+ {parseError ? (
+ <p role="alert" className="border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">
+ The body has markup the editor cannot show. Source mode still edits it. {parseError}
+ </p>
+ ) : null}
+ <MDXEditor
+ markdown={markdown}
+ onChange={(next, initialNormalize) => {
+ if (!initialNormalize) onChange(next);
+ }}
+ onError={({ error }) => setParseError(error)}
+ plugins={plugins}
+ contentEditableClassName={`${BLOG_ARTICLE_CLASS} min-h-[60vh] px-6 py-5`}
+ placeholder="Write the article…"
+ />
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/[id]/HeaderFocusPicker.tsx b/site/src/app/su/blog/[id]/HeaderFocusPicker.tsx
new file mode 100644
index 00000000..825ff783
--- /dev/null
+++ b/site/src/app/su/blog/[id]/HeaderFocusPicker.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { useRef } from "react";
+
+import { blogFocusSchema } from "@/lib/blog/schema";
+
+// The header at the crop the article uses (full column width, 240px tall).
+// Clicking or dragging on it names the point that has to stay in frame, kept
+// as an object-position pair so the public page positions the same way.
+export function HeaderFocusPicker({
+ src,
+ alt,
+ focus,
+ onChange,
+}: {
+ src: string;
+ alt: string;
+ focus: string | null;
+ onChange: (focus: string) => void;
+}) {
+ const box = useRef<HTMLDivElement>(null);
+ const dragging = useRef(false);
+ const position = focus && blogFocusSchema.safeParse(focus).success ? focus : "50% 50%";
+ const [x, y] = position.split(" ");
+
+ const setFrom = (event: React.PointerEvent) => {
+ const rect = box.current?.getBoundingClientRect();
+ if (!rect) return;
+ const px = Math.min(100, Math.max(0, ((event.clientX - rect.left) / rect.width) * 100));
+ const py = Math.min(100, Math.max(0, ((event.clientY - rect.top) / rect.height) * 100));
+ onChange(`${px.toFixed(1)}% ${py.toFixed(1)}%`);
+ };
+
+ return (
+ <div
+ ref={box}
+ className="relative h-60 w-full cursor-crosshair touch-none overflow-hidden rounded-2xl border-2 border-ink bg-muted select-none"
+ onPointerDown={(event) => {
+ dragging.current = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ setFrom(event);
+ }}
+ onPointerMove={(event) => {
+ if (dragging.current) setFrom(event);
+ }}
+ onPointerUp={(event) => {
+ dragging.current = false;
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }}
+ onPointerCancel={() => {
+ dragging.current = false;
+ }}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element -- pre-encoded AVIF from the media host, not Next-optimizable */}
+ <img src={src} alt={alt} draggable={false} className="size-full object-cover" style={{ objectPosition: position }} />
+ <div
+ aria-hidden
+ className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-coral shadow"
+ style={{ left: x, top: y }}
+ />
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/[id]/ImageUpload.tsx b/site/src/app/su/blog/[id]/ImageUpload.tsx
new file mode 100644
index 00000000..e928d297
--- /dev/null
+++ b/site/src/app/su/blog/[id]/ImageUpload.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { useRef } from "react";
+
+import { Button } from "@/components/ui/button";
+import type { BlogImageKind } from "@/lib/blog/images";
+import { useRemoveBlogImage, useUploadBlogImage } from "@/queries/blog";
+
+export const BLOG_IMAGE_ACCEPT = "image/png,image/jpeg,image/webp,image/gif,image/avif";
+
+// Upload, replace and remove for the header or the thumbnail. The bytes go
+// straight to storage and come back encoded; the row is updated by the route,
+// so the preview the caller draws follows the query.
+export function ImageUpload({
+ postId,
+ kind,
+ hasImage,
+ onUploaded,
+}: {
+ postId: string;
+ kind: Exclude<BlogImageKind, "inline">;
+ hasImage: boolean;
+ onUploaded?: () => void;
+}) {
+ const upload = useUploadBlogImage(postId);
+ const remove = useRemoveBlogImage(postId);
+ const input = useRef<HTMLInputElement>(null);
+ const busy = upload.isPending || remove.isPending;
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ ref={input}
+ type="file"
+ accept={BLOG_IMAGE_ACCEPT}
+ className="hidden"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (file) upload.mutate({ file, kind }, { onSuccess: () => onUploaded?.() });
+ }}
+ />
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => input.current?.click()}>
+ {upload.isPending ? "Uploading…" : hasImage ? "Replace" : "Upload"}
+ </Button>
+ {hasImage ? (
+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => remove.mutate(kind)}>
+ {remove.isPending ? "Removing…" : "Remove"}
+ </Button>
+ ) : null}
+ {upload.isError ? <span className="text-xs text-destructive">{upload.error.message}</span> : null}
+ {remove.isError ? <span className="text-xs text-destructive">{remove.error.message}</span> : null}
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/[id]/TagInput.tsx b/site/src/app/su/blog/[id]/TagInput.tsx
new file mode 100644
index 00000000..c8971a26
--- /dev/null
+++ b/site/src/app/su/blog/[id]/TagInput.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { X } from "lucide-react";
+import { useId, useState } from "react";
+
+import { Input } from "@/components/ui/input";
+
+// A list of words as chips. Enter or a comma adds what is typed, Backspace on
+// an empty box removes the last chip, and the browser offers the words other
+// posts already use.
+export function TagInput({
+ id,
+ value,
+ onChange,
+ suggestions = [],
+ placeholder,
+ normalize = (word) => word.trim(),
+}: {
+ id: string;
+ value: string[];
+ onChange: (next: string[]) => void;
+ suggestions?: string[];
+ placeholder?: string;
+ normalize?: (word: string) => string;
+}) {
+ const [typed, setTyped] = useState("");
+ const listId = useId();
+
+ const add = (raw: string) => {
+ const words = raw
+ .split(",")
+ .map(normalize)
+ .filter((word) => word.length > 0 && !value.includes(word));
+ if (words.length > 0) onChange([...value, ...words]);
+ setTyped("");
+ };
+
+ return (
+ <div className="space-y-2">
+ {value.length > 0 ? (
+ <div className="flex flex-wrap gap-1.5">
+ {value.map((word) => (
+ <span
+ key={word}
+ className="inline-flex items-center gap-1 rounded-full border bg-muted px-2.5 py-0.5 text-xs font-medium"
+ >
+ {word}
+ <button
+ type="button"
+ aria-label={`Remove ${word}`}
+ className="-mr-1 rounded-full p-0.5 text-muted-foreground hover:text-foreground"
+ onClick={() => onChange(value.filter((other) => other !== word))}
+ >
+ <X className="size-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ ) : null}
+ <Input
+ id={id}
+ list={listId}
+ value={typed}
+ placeholder={placeholder}
+ autoComplete="off"
+ onChange={(event) => setTyped(event.target.value)}
+ onBlur={() => {
+ if (typed.trim()) add(typed);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === ",") {
+ event.preventDefault();
+ add(typed);
+ } else if (event.key === "Backspace" && typed === "" && value.length > 0) {
+ onChange(value.slice(0, -1));
+ }
+ }}
+ />
+ <datalist id={listId}>
+ {suggestions
+ .filter((word) => !value.includes(word))
+ .map((word) => (
+ <option key={word} value={word} />
+ ))}
+ </datalist>
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/[id]/page.tsx b/site/src/app/su/blog/[id]/page.tsx
new file mode 100644
index 00000000..35823ee6
--- /dev/null
+++ b/site/src/app/su/blog/[id]/page.tsx
@@ -0,0 +1,494 @@
+"use client";
+
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+
+import { BlogEditor } from "@/app/su/blog/[id]/BlogEditor";
+import { HeaderFocusPicker } from "@/app/su/blog/[id]/HeaderFocusPicker";
+import { ImageUpload } from "@/app/su/blog/[id]/ImageUpload";
+import { TagInput } from "@/app/su/blog/[id]/TagInput";
+import { Field } from "@/app/su/Field";
+import { SuStandIn } from "@/app/su/SuStandIn";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { SU_APP_ORIGIN } from "@/cut/lib/hosts";
+import {
+ BLOG_DESCRIPTION_MAX,
+ BLOG_DESCRIPTION_MIN,
+ BLOG_SEO_TITLE_MAX,
+ BLOG_TITLE_MAX,
+ publishIssues,
+ slugFromTitle,
+ type BlogPostInput,
+} from "@/lib/blog/schema";
+import { ApiError } from "@/queries/apiClient";
+import {
+ uploadBlogImage,
+ useBlogPost,
+ useBlogPosts,
+ usePublishBlogPost,
+ useSaveBlogPost,
+ useUnpublishBlogPost,
+ type BlogPostAdminWithBody,
+} from "@/queries/blog";
+
+// One post: the body on the left, everything the page and the search result
+// are built from on the right. Save writes the whole draft; Publish holds the
+// saved post to the contract in publishIssues and puts it on the site.
+
+export default function SuBlogPostPage() {
+ const { id } = useParams<{ id: string }>();
+ const post = useBlogPost(id);
+ if (!post.data) {
+ if (post.isPending) return <SuStandIn />;
+ return (
+ <div role="alert" className="space-y-3 rounded-lg border border-destructive/30 p-4">
+ <p className="text-sm text-destructive">Couldn’t load the post. {post.error?.message}</p>
+ <Button variant="outline" nativeButton={false} render={<Link href="/blog" />}>
+ Back to posts
+ </Button>
+ </div>
+ );
+ }
+ return <PostEditor key={post.data.post.id} post={post.data.post} />;
+}
+
+const inputOf = (post: BlogPostAdminWithBody): BlogPostInput => ({
+ slug: post.slug,
+ title: post.title,
+ excerpt: post.excerpt,
+ summary: post.summary,
+ tags: post.tags,
+ keywords: post.keywords,
+ featured: post.featured,
+ publishedAt: post.publishedAt,
+ revisedAt: post.revisedAt,
+ headerAlt: post.headerAlt,
+ headerFocus: post.headerFocus,
+ seoTitle: post.seoTitle,
+ canonicalUrl: post.canonicalUrl,
+ noIndex: post.noIndex,
+ body: post.body,
+});
+
+// datetime-local speaks local wall time without a zone; the row keeps an
+// instant.
+const toLocalInput = (iso: string | null): string => {
+ if (!iso) return "";
+ const date = new Date(iso);
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
+};
+const fromLocalInput = (value: string): string | null => {
+ if (!value) return null;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
+};
+
+const issuesByPath = (error: unknown): Record<string, string> => {
+ const map: Record<string, string> = {};
+ if (error instanceof ApiError) {
+ for (const issue of error.issues) map[issue.path.split(".")[0] || "form"] = issue.message;
+ }
+ return map;
+};
+
+function Count({ value, max, min = 0 }: { value: string; max: number; min?: number }) {
+ const n = value.trim().length;
+ const off = n > max || (min > 0 && n > 0 && n < min);
+ return (
+ <span className={`text-xs tabular-nums ${off ? "text-destructive" : "text-muted-foreground"}`}>
+ {n}/{max}
+ </span>
+ );
+}
+
+function PostEditor({ post }: { post: BlogPostAdminWithBody }) {
+ const posts = useBlogPosts();
+ const save = useSaveBlogPost(post.id);
+ const publish = usePublishBlogPost(post.id);
+ const unpublish = useUnpublishBlogPost(post.id);
+
+ const [draft, setDraft] = useState<BlogPostInput>(() => inputOf(post));
+ const [saved, setSaved] = useState<BlogPostInput>(() => inputOf(post));
+ // The slug follows the title until it is edited by hand, or the post is
+ // live and its address is spoken for.
+ const [slugTouched, setSlugTouched] = useState(
+ () => post.status === "PUBLISHED" || (post.title.trim().length > 0 && post.slug !== slugFromTitle(post.title)),
+ );
+ const [issues, setIssues] = useState<Record<string, string>>({});
+ const [notice, setNotice] = useState<string | null>(null);
+ // The keyboard shortcut and the title handler read the draft at the moment
+ // they fire, outside a render.
+ const draftRef = useRef(draft);
+ useEffect(() => {
+ draftRef.current = draft;
+ }, [draft]);
+
+ const dirty = useMemo(() => JSON.stringify(draft) !== JSON.stringify(saved), [draft, saved]);
+ const busy = save.isPending || publish.isPending || unpublish.isPending;
+ const published = post.status === "PUBLISHED";
+
+ const patch = (next: Partial<BlogPostInput>) => setDraft((current) => ({ ...current, ...next }));
+
+ const doSave = useCallback(() => {
+ const submitted = draftRef.current;
+ if (save.isPending) return;
+ setIssues({});
+ setNotice(null);
+ save.mutate(submitted, {
+ onSuccess: ({ post: row }) => {
+ const next = inputOf(row);
+ setSaved(next);
+ // Keep what was typed during the save; otherwise take the row's
+ // normalized values so the form shows exactly what is stored.
+ setDraft((current) => (current === submitted ? next : current));
+ },
+ onError: (error) => {
+ setIssues(issuesByPath(error));
+ setNotice(error.message);
+ },
+ });
+ }, [save]);
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") {
+ event.preventDefault();
+ doSave();
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [doSave]);
+
+ useEffect(() => {
+ if (!dirty) return;
+ const warn = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ };
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [dirty]);
+
+ const doPublish = () => {
+ setIssues({});
+ setNotice(null);
+ publish.mutate(undefined, {
+ onSuccess: ({ post: row }) => {
+ const next = inputOf(row);
+ setSaved(next);
+ setDraft((current) => ({ ...current, publishedAt: next.publishedAt }));
+ setSlugTouched(true);
+ },
+ onError: (error) => {
+ setIssues(issuesByPath(error));
+ setNotice(error.message);
+ },
+ });
+ };
+
+ const doUnpublish = () => {
+ setNotice(null);
+ unpublish.mutate(undefined, { onError: (error) => setNotice(error.message) });
+ };
+
+ const uploadInline = useCallback(
+ async (file: File) => (await uploadBlogImage(post.id, file, "inline")).image.url,
+ [post.id],
+ );
+
+ const checklist = publishIssues({
+ title: draft.title,
+ excerpt: draft.excerpt,
+ summary: draft.summary,
+ headerKey: post.headerKey,
+ thumbnailKey: post.thumbnailKey,
+ publishedAt: draft.publishedAt,
+ body: draft.body,
+ });
+ const allTags = useMemo(
+ () => Array.from(new Set((posts.data?.posts ?? []).flatMap((row) => row.tags))).sort(),
+ [posts.data],
+ );
+ const allKeywords = useMemo(
+ () => Array.from(new Set((posts.data?.posts ?? []).flatMap((row) => row.keywords))).sort(),
+ [posts.data],
+ );
+ const error = (path: string) =>
+ issues[path] ? (
+ <p role="alert" className="text-xs text-destructive">
+ {issues[path]}
+ </p>
+ ) : null;
+
+ return (
+ <div className="space-y-6 pb-9">
+ <div className="flex flex-wrap items-center gap-2">
+ <Button variant="ghost" size="sm" nativeButton={false} render={<Link href="/blog" />}>
+ ← Posts
+ </Button>
+ <Badge variant={published ? "default" : "outline"}>{published ? "Published" : "Draft"}</Badge>
+ {dirty ? <span className="text-xs text-muted-foreground">Unsaved changes</span> : null}
+ {notice ? (
+ <span role="alert" className="text-xs text-destructive">
+ {notice}
+ </span>
+ ) : null}
+ <div className="ml-auto flex flex-wrap items-center gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={dirty}
+ title={dirty ? "Save to preview" : undefined}
+ onClick={() =>
+ window.open(`${SU_APP_ORIGIN}/api/blog/preview?id=${encodeURIComponent(post.id)}`, "_blank", "noopener")
+ }
+ >
+ Preview
+ </Button>
+ {published ? (
+ <Button
+ size="sm"
+ variant="outline"
+ nativeButton={false}
+ render={<a href={`${SU_APP_ORIGIN}/blog/${post.slug}`} target="_blank" rel="noreferrer" />}
+ >
+ View
+ </Button>
+ ) : null}
+ <Button size="sm" variant={dirty ? "default" : "outline"} disabled={busy || !dirty} onClick={doSave}>
+ {save.isPending ? "Saving…" : "Save"}
+ </Button>
+ {published ? (
+ <Button size="sm" variant="outline" disabled={busy} onClick={doUnpublish}>
+ {unpublish.isPending ? "Unpublishing…" : "Unpublish"}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ disabled={busy || dirty || checklist.length > 0}
+ title={dirty ? "Save to publish" : checklist.length > 0 ? "See the checklist" : undefined}
+ onClick={doPublish}
+ >
+ {publish.isPending ? "Publishing…" : "Publish"}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="min-w-0 space-y-5">
+ <div className="space-y-2">
+ {post.headerUrl ? (
+ <HeaderFocusPicker
+ src={post.headerUrl}
+ alt={draft.headerAlt}
+ focus={draft.headerFocus}
+ onChange={(focus) => patch({ headerFocus: focus })}
+ />
+ ) : (
+ <div className="flex h-60 items-center justify-center rounded-2xl border-2 border-dashed text-sm text-muted-foreground">
+ Header image, shown 1080×240 on the page
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-3">
+ <ImageUpload postId={post.id} kind="header" hasImage={Boolean(post.headerUrl)} />
+ {post.headerUrl ? (
+ <span className="text-xs text-muted-foreground">Click or drag on the image to set what stays in frame.</span>
+ ) : null}
+ </div>
+ {error("header")}
+ {post.headerUrl ? (
+ <Field label="Header alt text" htmlFor="headerAlt">
+ <Input id="headerAlt" value={draft.headerAlt} onChange={(e) => patch({ headerAlt: e.target.value })} />
+ {error("headerAlt")}
+ </Field>
+ ) : null}
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="flex items-baseline justify-between">
+ <Label htmlFor="title" className="text-xs text-muted-foreground">
+ Title
+ </Label>
+ <Count value={draft.title} max={BLOG_TITLE_MAX} />
+ </div>
+ <Input
+ id="title"
+ value={draft.title}
+ placeholder="Post title"
+ className="h-11 text-lg font-semibold"
+ onChange={(e) => {
+ const title = e.target.value;
+ patch(slugTouched ? { title } : { title, slug: slugFromTitle(title) || draftRef.current.slug });
+ }}
+ />
+ {error("title")}
+ </div>
+
+ <Field label="Address" htmlFor="slug">
+ <div className="flex items-center gap-1">
+ <span className="shrink-0 text-sm text-muted-foreground">donkeycut.com/blog/</span>
+ <Input
+ id="slug"
+ value={draft.slug}
+ onChange={(e) => {
+ setSlugTouched(true);
+ patch({ slug: e.target.value.toLowerCase() });
+ }}
+ />
+ </div>
+ {error("slug")}
+ </Field>
+
+ <div className="space-y-1.5">
+ <div className="flex items-baseline justify-between">
+ <Label htmlFor="summary" className="text-xs text-muted-foreground">
+ Summary, the answer-first line under the title
+ </Label>
+ <Count value={draft.summary} max={BLOG_DESCRIPTION_MAX} min={BLOG_DESCRIPTION_MIN} />
+ </div>
+ <Textarea id="summary" rows={2} value={draft.summary} onChange={(e) => patch({ summary: e.target.value })} />
+ {error("summary")}
+ </div>
+
+ <div className="space-y-1.5">
+ <Label className="text-xs text-muted-foreground">Article</Label>
+ <BlogEditor
+ markdown={saved.body}
+ diffMarkdown={saved.body}
+ onChange={(body) => patch({ body })}
+ uploadImage={uploadInline}
+ />
+ {error("body")}
+ </div>
+ </div>
+
+ <aside className="space-y-8">
+ <section className="space-y-4">
+ <h2 className="text-sm font-semibold">Publishing</h2>
+ {checklist.length > 0 ? (
+ <ul className="space-y-1 text-xs text-muted-foreground">
+ {checklist.map((issue) => (
+ <li key={issue.path}>· {issue.message}</li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-muted-foreground">{published ? "Live on the site." : "Ready to publish."}</p>
+ )}
+ <Field label="Publish date" htmlFor="publishedAt">
+ <Input
+ id="publishedAt"
+ type="datetime-local"
+ value={toLocalInput(draft.publishedAt)}
+ onChange={(e) => patch({ publishedAt: fromLocalInput(e.target.value) })}
+ />
+ {error("publishedAt")}
+ </Field>
+ <Field label="Revised date" htmlFor="revisedAt">
+ <Input
+ id="revisedAt"
+ type="datetime-local"
+ value={toLocalInput(draft.revisedAt)}
+ onChange={(e) => patch({ revisedAt: fromLocalInput(e.target.value) })}
+ />
+ {error("revisedAt")}
+ </Field>
+ <div className="flex items-center justify-between gap-3">
+ <Label htmlFor="featured" className="text-xs text-muted-foreground">
+ Featured on the index
+ </Label>
+ <Switch id="featured" checked={draft.featured} onCheckedChange={(featured) => patch({ featured })} />
+ </div>
+ <Field label="Tags" htmlFor="tags">
+ <TagInput
+ id="tags"
+ value={draft.tags}
+ suggestions={allTags}
+ normalize={(word) => word.trim().toLowerCase()}
+ placeholder="Add a tag"
+ onChange={(tags) => patch({ tags })}
+ />
+ {error("tags")}
+ </Field>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-sm font-semibold">Thumbnail</h2>
+ {post.thumbnailUrl ? (
+ // eslint-disable-next-line @next/next/no-img-element -- pre-encoded AVIF from the media host, not Next-optimizable
+ <img src={post.thumbnailUrl} alt="" className="aspect-[8/5] w-full rounded-xl border-2 border-ink object-cover" />
+ ) : (
+ <div className="flex aspect-[8/5] w-full items-center justify-center rounded-xl border-2 border-dashed text-xs text-muted-foreground">
+ 800×500 on the index
+ </div>
+ )}
+ <ImageUpload postId={post.id} kind="thumbnail" hasImage={Boolean(post.thumbnailUrl)} />
+ {error("thumbnail")}
+ </section>
+
+ <section className="space-y-4">
+ <h2 className="text-sm font-semibold">Search</h2>
+ <div className="space-y-1.5">
+ <div className="flex items-baseline justify-between">
+ <Label htmlFor="seoTitle" className="text-xs text-muted-foreground">
+ Meta title
+ </Label>
+ <Count value={draft.seoTitle} max={BLOG_SEO_TITLE_MAX} />
+ </div>
+ <Input
+ id="seoTitle"
+ value={draft.seoTitle}
+ placeholder={draft.title ? `${draft.title} | Donkey Cut` : "Falls back to the title"}
+ onChange={(e) => patch({ seoTitle: e.target.value })}
+ />
+ {error("seoTitle")}
+ </div>
+ <div className="space-y-1.5">
+ <div className="flex items-baseline justify-between">
+ <Label htmlFor="excerpt" className="text-xs text-muted-foreground">
+ Meta description
+ </Label>
+ <Count value={draft.excerpt} max={BLOG_DESCRIPTION_MAX} min={BLOG_DESCRIPTION_MIN} />
+ </div>
+ <Textarea id="excerpt" rows={3} value={draft.excerpt} onChange={(e) => patch({ excerpt: e.target.value })} />
+ {error("excerpt")}
+ </div>
+ <Field label="Keywords" htmlFor="keywords">
+ <TagInput
+ id="keywords"
+ value={draft.keywords}
+ suggestions={allKeywords}
+ placeholder="Add a keyword"
+ onChange={(keywords) => patch({ keywords })}
+ />
+ {error("keywords")}
+ </Field>
+ <Field label="Canonical address" htmlFor="canonicalUrl">
+ <Input
+ id="canonicalUrl"
+ type="url"
+ value={draft.canonicalUrl}
+ placeholder={`https://donkeycut.com/blog/${draft.slug}`}
+ onChange={(e) => patch({ canonicalUrl: e.target.value })}
+ />
+ {error("canonicalUrl")}
+ </Field>
+ <div className="flex items-center justify-between gap-3">
+ <Label htmlFor="noIndex" className="text-xs text-muted-foreground">
+ Keep out of search results
+ </Label>
+ <Switch id="noIndex" checked={draft.noIndex} onCheckedChange={(noIndex) => patch({ noIndex })} />
+ </div>
+ </section>
+ </aside>
+ </div>
+ </div>
+ );
+}
diff --git a/site/src/app/su/blog/page.tsx b/site/src/app/su/blog/page.tsx
new file mode 100644
index 00000000..908692a1
--- /dev/null
+++ b/site/src/app/su/blog/page.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import Link from "next/link";
+import { useState } from "react";
+
+import { SuStandIn } from "@/app/su/SuStandIn";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { useBlogPosts, useDeleteBlogPost, type BlogPostAdmin } from "@/queries/blog";
+
+const when = (iso: string) =>
+ new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
+
+// Every post in one list, the most recently touched first. A row opens the
+// editor; delete sits behind a confirmation because it also sweeps the post's
+// images out of storage.
+export default function SuBlogPage() {
+ const posts = useBlogPosts();
+
+ const loadError = posts.isError ? (
+ <div role="alert" className="space-y-3 rounded-lg border border-destructive/30 p-4">
+ <p className="text-sm text-destructive">Couldn’t load posts. {posts.error.message}</p>
+ <Button variant="outline" disabled={posts.isFetching} onClick={() => void posts.refetch()}>
+ {posts.isFetching ? "Retrying…" : "Retry"}
+ </Button>
+ </div>
+ ) : null;
+
+ if (!posts.data) return posts.isPending ? <SuStandIn /> : loadError;
+ const rows = posts.data.posts;
+
+ return (
+ <div className="space-y-3 pb-9">
+ {loadError}
+ {rows.length === 0 ? <p className="text-sm text-muted-foreground">No posts yet.</p> : null}
+ {rows.map((post) => (
+ <PostRow key={post.id} post={post} />
+ ))}
+ </div>
+ );
+}
+
+function PostRow({ post }: { post: BlogPostAdmin }) {
+ const remove = useDeleteBlogPost();
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const title = post.title.trim() || "Untitled post";
+ return (
+ <div className="flex items-start gap-4 rounded-lg border p-4">
+ {post.thumbnailUrl ? (
+ // eslint-disable-next-line @next/next/no-img-element -- pre-encoded AVIF from the media host, not Next-optimizable
+ <img
+ src={post.thumbnailUrl}
+ alt=""
+ className="hidden h-16 w-[102px] shrink-0 rounded-md border object-cover sm:block"
+ />
+ ) : (
+ <div className="hidden h-16 w-[102px] shrink-0 rounded-md border bg-muted sm:block" />
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <Link href={`/blog/${post.id}`} className="font-medium hover:underline">
+ {title}
+ </Link>
+ <Badge variant={post.status === "PUBLISHED" ? "default" : "outline"}>
+ {post.status === "PUBLISHED" ? "Published" : "Draft"}
+ </Badge>
+ {post.featured ? <Badge variant="secondary">Featured</Badge> : null}
+ {post.noIndex ? <Badge variant="outline">noindex</Badge> : null}
+ </div>
+ <p className="mt-1 truncate text-sm text-muted-foreground">/blog/{post.slug}</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {post.publishedAt ? `Published ${when(post.publishedAt)} · ` : ""}
+ Edited {when(post.updatedAt)}
+ {post.tags.length > 0 ? ` · ${post.tags.join(", ")}` : ""}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button size="sm" variant="outline" nativeButton={false} render={<Link href={`/blog/${post.id}`} />}>
+ Edit
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={remove.isPending}
+ onClick={() => {
+ remove.reset();
+ setConfirmDelete(true);
+ }}
+ >
+ Delete
+ </Button>
+ </div>
+ <AlertDialog
+ open={confirmDelete}
+ onOpenChange={(isOpen) => {
+ if (!remove.isPending) setConfirmDelete(isOpen);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete “{title}”?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {post.status === "PUBLISHED"
+ ? "The page comes down and its images are removed from storage."
+ : "The draft and its images are removed from storage."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {remove.isError ? (
+ <p role="alert" className="text-sm text-destructive">
+ Couldn’t delete the post. {remove.error.message}
+ </p>
+ ) : null}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={remove.isPending}>Keep</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={remove.isPending}
+ onClick={() => remove.mutate(post.id, { onSuccess: () => setConfirmDelete(false) })}
+ >
+ {remove.isPending ? "Deleting…" : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/site/src/app/su/nav.ts b/site/src/app/su/nav.ts
index 9bba28fe..dcfe52ca 100644
--- a/site/src/app/su/nav.ts
+++ b/site/src/app/su/nav.ts
@@ -60,6 +60,12 @@ export const SU_NAV = [
title: "Promotions",
description: "One email to a segment of accounts.",
},
+ {
+ href: "/blog",
+ label: "Blog",
+ title: "Blog",
+ description: "The posts on donkeycut.com/blog.",
+ },
{
href: "/experiments",
label: "Experiments",
diff --git a/site/src/queries/apiClient.ts b/site/src/queries/apiClient.ts
index a9a5a626..ae7ce3c4 100644
--- a/site/src/queries/apiClient.ts
+++ b/site/src/queries/apiClient.ts
@@ -1,19 +1,25 @@
// Thin fetch wrapper shared by every query/mutation hook in this folder. All
// settings UI data access goes through here so it can be audited in one place.
+export type ApiIssue = { path: string; message: string };
+
export class ApiError extends Error {
public readonly status: number;
public readonly code: string | null;
+ // Field-level findings from a validating route, so a form can show each
+ // under its own control.
+ public readonly issues: ApiIssue[];
- public constructor(message: string, status: number, code: string | null) {
+ public constructor(message: string, status: number, code: string | null, issues: ApiIssue[] = []) {
super(message);
this.name = "ApiError";
this.status = status;
this.code = code;
+ this.issues = issues;
}
}
-type ApiErrorBody = { error?: string; message?: string };
+type ApiErrorBody = { error?: string; message?: string; issues?: ApiIssue[] };
export async function apiFetch<T>(
path: string,
@@ -36,9 +42,10 @@ export async function apiFetch<T>(
// Non-JSON error body; fall back to status text.
}
throw new ApiError(
- body.message ?? response.statusText,
+ body.message ?? body.error ?? response.statusText,
response.status,
body.error ?? null,
+ Array.isArray(body.issues) ? body.issues : [],
);
}
diff --git a/site/src/queries/blog.ts b/site/src/queries/blog.ts
new file mode 100644
index 00000000..b7a02dd0
--- /dev/null
+++ b/site/src/queries/blog.ts
@@ -0,0 +1,122 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import type { BlogPostAdmin, BlogPostAdminWithBody } from "@/lib/blog/admin";
+import type { BlogImageKind } from "@/lib/blog/images";
+import type { BlogPostInput } from "@/lib/blog/schema";
+import { apiFetch } from "@/queries/apiClient";
+
+export type { BlogPostAdmin, BlogPostAdminWithBody };
+
+export const blogPostsQueryKey = ["su", "blog", "posts"] as const;
+export const blogPostQueryKey = (id: string) => ["su", "blog", "post", id] as const;
+
+export type BlogImageResult = { key: string; url: string; width: number; height: number };
+
+const base = "/api/su/blog/posts";
+const postUrl = (id: string, tail = "") => `${base}/${encodeURIComponent(id)}${tail}`;
+
+// A write answers with the saved post; it lands in that post's cache and the
+// list refetches.
+function useTakePost() {
+ const queryClient = useQueryClient();
+ return (post: BlogPostAdmin | BlogPostAdminWithBody) => {
+ queryClient.setQueryData<{ post: BlogPostAdminWithBody }>(blogPostQueryKey(post.id), (current) =>
+ current ? { post: { ...current.post, ...post } } : "body" in post ? { post } : current,
+ );
+ void queryClient.invalidateQueries({ queryKey: blogPostsQueryKey });
+ };
+}
+
+export function useBlogPosts() {
+ return useQuery({
+ queryFn: () => apiFetch<{ posts: BlogPostAdmin[] }>(base),
+ queryKey: blogPostsQueryKey,
+ });
+}
+
+export function useBlogPost(id: string) {
+ return useQuery({
+ queryFn: () => apiFetch<{ post: BlogPostAdminWithBody }>(postUrl(id)),
+ queryKey: blogPostQueryKey(id),
+ });
+}
+
+export function useCreateBlogPost() {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: () => apiFetch<{ post: BlogPostAdmin }>(base, { method: "POST" }),
+ onSuccess: ({ post }) => takePost(post),
+ });
+}
+
+export function useSaveBlogPost(id: string) {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: (input: BlogPostInput) =>
+ apiFetch<{ post: BlogPostAdminWithBody }>(postUrl(id), { body: JSON.stringify(input), method: "PUT" }),
+ onSuccess: ({ post }) => takePost(post),
+ });
+}
+
+export function usePublishBlogPost(id: string) {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: () => apiFetch<{ post: BlogPostAdminWithBody }>(postUrl(id, "/publish"), { method: "POST" }),
+ onSuccess: ({ post }) => takePost(post),
+ });
+}
+
+export function useUnpublishBlogPost(id: string) {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: () => apiFetch<{ post: BlogPostAdminWithBody }>(postUrl(id, "/unpublish"), { method: "POST" }),
+ onSuccess: ({ post }) => takePost(post),
+ });
+}
+
+export function useDeleteBlogPost() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => apiFetch<{ ok: true }>(postUrl(id), { method: "DELETE" }),
+ onSuccess: (_result, id) => {
+ queryClient.removeQueries({ queryKey: blogPostQueryKey(id) });
+ void queryClient.invalidateQueries({ queryKey: blogPostsQueryKey });
+ },
+ });
+}
+
+// The whole upload: a presigned scratch key, the bytes PUT straight to
+// storage, then the encode that turns them into the image the pages serve.
+export async function uploadBlogImage(id: string, file: File, kind: BlogImageKind) {
+ const { key, putUrl } = await apiFetch<{ key: string; putUrl: string }>(postUrl(id, "/uploads"), {
+ body: JSON.stringify({ mime: file.type, bytes: file.size }),
+ method: "POST",
+ });
+ const put = await fetch(putUrl, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
+ if (!put.ok) throw new Error(`The upload was refused (${put.status}).`);
+ return apiFetch<{ image: BlogImageResult; post?: BlogPostAdmin }>(postUrl(id, "/images"), {
+ body: JSON.stringify({ uploadKey: key, kind }),
+ method: "POST",
+ });
+}
+
+export function useUploadBlogImage(id: string) {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: ({ file, kind }: { file: File; kind: BlogImageKind }) => uploadBlogImage(id, file, kind),
+ onSuccess: ({ post }) => {
+ if (post) takePost(post);
+ },
+ });
+}
+
+export function useRemoveBlogImage(id: string) {
+ const takePost = useTakePost();
+ return useMutation({
+ mutationFn: (kind: "header" | "thumbnail") =>
+ apiFetch<{ post: BlogPostAdmin }>(postUrl(id, "/images/remove"), { body: JSON.stringify({ kind }), method: "POST" }),
+ onSuccess: ({ post }) => takePost(post),
+ });
+}