Open source CapCut alternative.
TypeScript
feat(site): place the blog header and thumbnail by dragging the picture
David Leb3abeee7e747
diff --git a/site/prisma/Blog.prisma b/site/prisma/Blog.prismaindex 804f9b7b..b7516465 100644--- a/site/prisma/Blog.prisma+++ b/site/prisma/Blog.prisma@@ -28,6 +28,8 @@ model BlogPost {// CSS object-position for the header crop, "x% y%".headerFocus String?thumbnailKey String?+ // CSS object-position for the thumbnail crop, "x% y%".+ thumbnailFocus String?// Overrides the <title>; the post title when empty.seoTitle String?// Overrides the canonical URL when the piece was first published elsewhere.diff --git a/site/prisma/migrations/20260911054936/migration.sql b/site/prisma/migrations/20260911054936/migration.sqlnew file mode 100644index 00000000..35654213--- /dev/null+++ b/site/prisma/migrations/20260911054936/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "BlogPost" ADD COLUMN "thumbnailFocus" TEXT;diff --git a/site/src/app/api/su/blog/posts/[id]/generate/route.ts b/site/src/app/api/su/blog/posts/[id]/generate/route.tsindex 8314d32d..b48b873f 100644--- a/site/src/app/api/su/blog/posts/[id]/generate/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/generate/route.ts@@ -85,7 +85,7 @@ export const POST = withSuperUser(async (request, { params }: Params) => {]);const row = await prisma.blogPost.update({where: { id: existing.id },- data: { headerKey: header.key, thumbnailKey: thumbnail.key },+ data: { headerKey: header.key, headerFocus: null, thumbnailKey: thumbnail.key, thumbnailFocus: null },});revalidateBlogLater([row.slug]);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.tsindex 305f01f7..665ba830 100644--- 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@@ -22,7 +22,7 @@ export const POST = withSuperUser(async (request, { params }: Params) => {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 },+ data: parsed.data.kind === "header" ? { headerKey: null, headerAlt: null, headerFocus: null } : { thumbnailKey: null, thumbnailFocus: null },});revalidateBlogLater([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.tsindex 3eedd9bf..274c59a9 100644--- a/site/src/app/api/su/blog/posts/[id]/images/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/images/route.ts@@ -46,7 +46,11 @@ export const POST = withSuperUser(async (request, { params }: Params) => {const row = await prisma.blogPost.update({where: { id: existing.id },- data: kind === "header" ? { headerKey: image.key } : { thumbnailKey: image.key },+ // A new picture starts centred; the old focus named a point in the old one.+ data:+ kind === "header"+ ? { headerKey: image.key, headerFocus: null }+ : { thumbnailKey: image.key, thumbnailFocus: null },});revalidateBlogLater([row.slug]);return NextResponse.json({ image, post: adminPost(row) });diff --git a/site/src/app/api/su/blog/posts/[id]/route.ts b/site/src/app/api/su/blog/posts/[id]/route.tsindex a222931a..e7edc5aa 100644--- a/site/src/app/api/su/blog/posts/[id]/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/route.ts@@ -54,6 +54,7 @@ export const PUT = withSuperUser(async (request, { params }: Params) => {revisedAt: input.revisedAt ? new Date(input.revisedAt) : null,headerAlt: input.headerAlt || null,headerFocus: input.headerFocus,+ thumbnailFocus: input.thumbnailFocus,seoTitle: input.seoTitle || null,canonicalUrl: input.canonicalUrl || null,noIndex: input.noIndex,diff --git a/site/src/app/cut/blog/_components/BlogGrid.tsx b/site/src/app/cut/blog/_components/BlogGrid.tsxindex 7de2335c..6e411002 100644--- a/site/src/app/cut/blog/_components/BlogGrid.tsx+++ b/site/src/app/cut/blog/_components/BlogGrid.tsx@@ -29,10 +29,9 @@ function FeaturedCard({ post }: { post: BlogPostCard }) {<imgsrc={post.thumbnailUrl}alt={post.title}- width={800}- height={500}fetchPriority="high"className="absolute inset-0 h-full w-full object-cover"+ style={{ objectPosition: post.thumbnailFocus ?? "50% 50%" }}/>) : null}</div>@@ -62,10 +61,9 @@ function PostCard({ post }: { post: BlogPostCard }) {<imgsrc={post.thumbnailUrl}alt={post.title}- width={800}- height={500}loading="lazy"className="absolute inset-0 h-full w-full object-cover brightness-90 contrast-125 grayscale transition-all duration-500 group-hover:brightness-100 group-hover:contrast-100 group-hover:grayscale-0"+ style={{ objectPosition: post.thumbnailFocus ?? "50% 50%" }}/>) : null}</div>diff --git a/site/src/app/cut/blog/_components/BlogHeaderImage.tsx b/site/src/app/cut/blog/_components/BlogHeaderImage.tsxindex 882dcbfc..d452a9e7 100644--- a/site/src/app/cut/blog/_components/BlogHeaderImage.tsx+++ b/site/src/app/cut/blog/_components/BlogHeaderImage.tsx@@ -7,8 +7,6 @@ export function BlogHeaderImage({ src, alt, focus }: { src: string; alt: string;<imgsrc={src}alt={alt}- width={1600}- height={900}fetchPriority="high"className="absolute inset-0 h-full w-full object-cover select-none"style={{ objectPosition: focus ?? "50% 50%" }}diff --git a/site/src/app/su/blog/[id]/FocusPicker.tsx b/site/src/app/su/blog/[id]/FocusPicker.tsxnew file mode 100644index 00000000..19c5a57c--- /dev/null+++ b/site/src/app/su/blog/[id]/FocusPicker.tsx@@ -0,0 +1,82 @@+"use client";++import { useRef, useState } from "react";++import { blogFocusSchema } from "@/lib/blog/schema";+import { cn } from "@/lib/utils";++// The picture in the box the page crops it to. Dragging moves the picture+// under the box, so whatever matters in it can be brought into frame; the+// result is kept as an object-position pair and the public page positions+// the same way. The picture only moves along an axis it overflows.+export function FocusPicker({+ src,+ alt,+ focus,+ className,+ onChange,+}: {+ src: string;+ alt: string;+ focus: string | null;+ className?: string;+ onChange: (focus: string) => void;+}) {+ const box = useRef<HTMLDivElement>(null);+ const [natural, setNatural] = useState<{ width: number; height: number } | null>(null);+ const drag = useRef<{ x: number; y: number; fx: number; fy: number } | null>(null);+ const position = focus && blogFocusSchema.safeParse(focus).success ? focus : "50% 50%";++ const moveTo = (event: React.PointerEvent) => {+ const start = drag.current;+ const rect = box.current?.getBoundingClientRect();+ if (!start || !rect || !natural) return;+ // object-fit: cover scales the picture until it fills the box; what hangs+ // over the box is the room there is to move it.+ const scale = Math.max(rect.width / natural.width, rect.height / natural.height);+ const overX = natural.width * scale - rect.width;+ const overY = natural.height * scale - rect.height;+ const fx = overX > 0 ? start.fx - ((event.clientX - start.x) / overX) * 100 : start.fx;+ const fy = overY > 0 ? start.fy - ((event.clientY - start.y) / overY) * 100 : start.fy;+ const clamp = (value: number) => Math.min(100, Math.max(0, value));+ onChange(`${clamp(fx).toFixed(1)}% ${clamp(fy).toFixed(1)}%`);+ };++ return (+ <div+ ref={box}+ className={cn(+ "relative w-full cursor-grab touch-none overflow-hidden rounded-2xl bg-muted select-none active:cursor-grabbing",+ className,+ )}+ onPointerDown={(event) => {+ const [fx, fy] = position.split(" ").map(parseFloat);+ drag.current = { x: event.clientX, y: event.clientY, fx, fy };+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={(event) => {+ if (drag.current) moveTo(event);+ }}+ onPointerUp={(event) => {+ drag.current = null;+ event.currentTarget.releasePointerCapture(event.pointerId);+ }}+ onPointerCancel={() => {+ drag.current = null;+ }}+ >+ {/* 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 }}+ onLoad={(event) => {+ const img = event.currentTarget;+ setNatural({ width: img.naturalWidth, height: img.naturalHeight });+ }}+ />+ </div>+ );+}diff --git a/site/src/app/su/blog/[id]/HeaderFocusPicker.tsx b/site/src/app/su/blog/[id]/HeaderFocusPicker.tsxdeleted file mode 100644index 825ff783..00000000--- a/site/src/app/su/blog/[id]/HeaderFocusPicker.tsx+++ /dev/null@@ -1,63 +0,0 @@-"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.tsxindex 8cd70a66..608b8eeb 100644--- a/site/src/app/su/blog/[id]/ImageUpload.tsx+++ b/site/src/app/su/blog/[id]/ImageUpload.tsx@@ -22,6 +22,7 @@ export function ImageUpload({label,className,children,+ onChanged,}: {postId: string;kind: Exclude<BlogImageKind, "inline">;@@ -29,6 +30,8 @@ export function ImageUpload({label: string;className?: string;children?: ReactNode;+ // Fires once a new picture is on the row, or the old one is gone.+ onChanged?: () => void;}) {const upload = useUploadBlogImage(postId);const remove = useRemoveBlogImage(postId);@@ -37,7 +40,7 @@ export function ImageUpload({const busy = upload.isPending || remove.isPending;const take = (file: File | undefined) => {- if (file && file.type.startsWith("image/")) upload.mutate({ file, kind });+ if (file && file.type.startsWith("image/")) upload.mutate({ file, kind }, { onSuccess: () => onChanged?.() });};return (@@ -73,7 +76,7 @@ export function ImageUpload({<Upload />Replace</Button>- <Button type="button" size="sm" variant="secondary" disabled={busy} onClick={() => remove.mutate(kind)}>+ <Button type="button" size="sm" variant="secondary" disabled={busy} onClick={() => remove.mutate(kind, { onSuccess: () => onChanged?.() })}><Trash2 />Remove</Button>diff --git a/site/src/app/su/blog/[id]/PostEditorPage.tsx b/site/src/app/su/blog/[id]/PostEditorPage.tsxindex 9192b33c..fbd67b20 100644--- a/site/src/app/su/blog/[id]/PostEditorPage.tsx+++ b/site/src/app/su/blog/[id]/PostEditorPage.tsx@@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { BlogEditor } from "@/app/su/blog/[id]/BlogEditor";import { DateTimeField } from "@/app/su/blog/[id]/DateTimeField";-import { HeaderFocusPicker } from "@/app/su/blog/[id]/HeaderFocusPicker";+import { FocusPicker } from "@/app/su/blog/[id]/FocusPicker";import { ImageUpload } from "@/app/su/blog/[id]/ImageUpload";import { TagInput } from "@/app/su/blog/[id]/TagInput";import { Field } from "@/app/su/Field";@@ -80,6 +80,7 @@ const inputOf = (post: BlogPostAdminWithBody): BlogPostInput => ({revisedAt: post.revisedAt,headerAlt: post.headerAlt,headerFocus: post.headerFocus,+ thumbnailFocus: post.thumbnailFocus,seoTitle: post.seoTitle,canonicalUrl: post.canonicalUrl,noIndex: post.noIndex,@@ -340,25 +341,49 @@ function PostEditor({ post }: { post: BlogPostAdminWithBody }) {<h2 className="text-sm font-semibold">Images</h2><div className="space-y-2"><h3 className="text-xs font-medium text-muted-foreground">Header, 1080×240 on the page</h3>- <ImageUpload postId={post.id} kind="header" url={post.headerUrl} label="Header image" className="h-60 w-full">+ <ImageUpload+ postId={post.id}+ kind="header"+ url={post.headerUrl}+ label="Header image"+ className="aspect-[9/2] w-full"+ onChanged={() => patch({ headerFocus: null })}+ >{post.headerUrl ? (- <HeaderFocusPicker+ <FocusPickersrc={post.headerUrl}alt={draft.headerAlt}focus={draft.headerFocus}+ className="aspect-[9/2]"onChange={(focus) => patch({ headerFocus: focus })}/>) : null}</ImageUpload>- {post.headerUrl ? (- <p className="text-xs text-muted-foreground">Click or drag on the image to set what stays in frame.</p>- ) : null}+ {post.headerUrl ? <p className="text-xs text-muted-foreground">Drag the picture to place it.</p> : null}{error("header")}</div><div className="grid gap-6 md:grid-cols-2"><div className="space-y-2"><h3 className="text-xs font-medium text-muted-foreground">Thumbnail, 800×500 on the index</h3>- <ImageUpload postId={post.id} kind="thumbnail" url={post.thumbnailUrl} label="Thumbnail" className="aspect-[8/5] w-full" />+ <ImageUpload+ postId={post.id}+ kind="thumbnail"+ url={post.thumbnailUrl}+ label="Thumbnail"+ className="aspect-[8/5] w-full"+ onChanged={() => patch({ thumbnailFocus: null })}+ >+ {post.thumbnailUrl ? (+ <FocusPicker+ src={post.thumbnailUrl}+ alt=""+ focus={draft.thumbnailFocus}+ className="aspect-[8/5]"+ onChange={(focus) => patch({ thumbnailFocus: focus })}+ />+ ) : null}+ </ImageUpload>+ {post.thumbnailUrl ? <p className="text-xs text-muted-foreground">Drag the picture to place it.</p> : null}{error("thumbnail")}</div>{post.headerUrl ? (diff --git a/site/src/lib/blog/admin.ts b/site/src/lib/blog/admin.tsindex 17111796..ff5d7200 100644--- a/site/src/lib/blog/admin.ts+++ b/site/src/lib/blog/admin.ts@@ -23,6 +23,7 @@ export type BlogPostAdmin = {headerFocus: string | null;thumbnailKey: string | null;thumbnailUrl: string | null;+ thumbnailFocus: string | null;seoTitle: string;canonicalUrl: string;noIndex: boolean;@@ -52,6 +53,7 @@ export function adminPost(row: BlogPost): BlogPostAdmin {headerFocus: row.headerFocus,thumbnailKey: row.thumbnailKey,thumbnailUrl: row.thumbnailKey ? blogImageUrl(row.thumbnailKey) : null,+ thumbnailFocus: row.thumbnailFocus,seoTitle: row.seoTitle ?? "",canonicalUrl: row.canonicalUrl ?? "",noIndex: row.noIndex,diff --git a/site/src/lib/blog/images.ts b/site/src/lib/blog/images.tsindex 18c30b0d..c2ba245f 100644--- a/site/src/lib/blog/images.ts+++ b/site/src/lib/blog/images.ts@@ -1,6 +1,7 @@-// Every image on the blog is encoded here, once, to a fixed size and format,-// and named by its bytes. The header and thumbnail crops match the boxes the-// pages draw them in; an inline image keeps its shape under a width cap.+// Every image on the blog is encoded here, once, to a fixed format under a+// width cap, and named by its bytes. The picture keeps its shape: the pages+// crop the header and the thumbnail to their boxes with the focus the editor+// set, so anything in the picture can be brought into frame later.import { createHash } from "node:crypto";import sharp from "sharp";@@ -9,10 +10,10 @@ import { blogImageKey, blogImageUrl } from "@/lib/blog/keys";export type BlogImageKind = "header" | "thumbnail" | "inline";-export const BLOG_IMAGE_SIZES: Record<BlogImageKind, { width: number; height?: number }> = {- header: { width: 1600, height: 900 },- thumbnail: { width: 800, height: 500 },- inline: { width: 1600 },+export const BLOG_IMAGE_WIDTHS: Record<BlogImageKind, number> = {+ header: 1600,+ thumbnail: 1000,+ inline: 1600,};// AVIF at a quality that keeps a photographic header around 100 KB. The effort@@ -23,12 +24,9 @@ const AVIF_EFFORT = 4;export type EncodedBlogImage = { bytes: Buffer; width: number; height: number; sha256: string };export async function encodeBlogImage(source: Buffer, kind: BlogImageKind): Promise<EncodedBlogImage> {- const size = BLOG_IMAGE_SIZES[kind];- const pipeline = sharp(source, { failOn: "none" }).rotate();- const resized = size.height- ? pipeline.resize(size.width, size.height, { fit: "cover", position: "attention" })- : pipeline.resize({ width: size.width, withoutEnlargement: true });- const { data, info } = await resized+ const { data, info } = await sharp(source, { failOn: "none" })+ .rotate()+ .resize({ width: BLOG_IMAGE_WIDTHS[kind], withoutEnlargement: true }).avif({ quality: AVIF_QUALITY, effort: AVIF_EFFORT }).toBuffer({ resolveWithObject: true });return {diff --git a/site/src/lib/blog/read.ts b/site/src/lib/blog/read.tsindex 9773fa19..f1cb9dc6 100644--- a/site/src/lib/blog/read.ts+++ b/site/src/lib/blog/read.ts@@ -30,6 +30,7 @@ export type BlogPostCard = {headerAlt: string | null;headerFocus: string | null;thumbnailUrl: string | null;+ thumbnailFocus: string | null;};export type BlogPostPage = BlogPostCard & {@@ -58,6 +59,7 @@ export function cardOf(row: BlogPost): BlogPostCard {headerAlt: row.headerAlt,headerFocus: row.headerFocus,thumbnailUrl: row.thumbnailKey ? blogImageUrl(row.thumbnailKey) : null,+ thumbnailFocus: row.thumbnailFocus,};}diff --git a/site/src/lib/blog/schema.ts b/site/src/lib/blog/schema.tsindex 5b9bf1f3..8e686a37 100644--- a/site/src/lib/blog/schema.ts+++ b/site/src/lib/blog/schema.ts@@ -46,6 +46,7 @@ export const blogPostInputSchema = zrevisedAt: isoDate,headerAlt: z.string().trim().max(400),headerFocus: blogFocusSchema.nullable(),+ thumbnailFocus: blogFocusSchema.nullable(),seoTitle: z.string().trim().max(200),canonicalUrl: z.union([z.literal(""), z.string().trim().url()]),noIndex: z.boolean(),