Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Uploads cancel cleanly; sketch editor: note tool, Escape, fast painting, touch-ups keep strokes

Claudeaa5a0adce3fb
diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsx
index 706a8549..954f1529 100644
--- a/src/components/studio/media-slot.tsx
+++ b/src/components/studio/media-slot.tsx
@@ -5,12 +5,13 @@ import { useRef, useState } from "react";
import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { uploadFile, useAssets } from "@/lib/api";
+import { useAssets, type Asset } from "@/lib/api";
import type { MediaKind } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
+import type { SketchMode, Stroke } from "./sketch-editor";
export interface SlotValue {
- /** Client-side identity for list items (references). */
+ /** Client-side identity for list items (references) and in-flight uploads. */
id?: string;
/** What the server receives: an /api/files URL (or any URL). */
ref: string;
@@ -18,9 +19,11 @@ export interface SlotValue {
kind: MediaKind;
name?: string;
uploading?: boolean;
+ /** Drawings and masks: the strokes they were made from, so the editor reopens them (in image pixels). */
+ sketch?: { mode: SketchMode; strokes: Stroke[] };
}
-const ACCEPT: Record<MediaKind, string> = {
+export const ACCEPT: Record<MediaKind, string> = {
image: "image/png,image/jpeg,image/webp,image/gif",
video: "video/mp4,video/webm,video/quicktime",
audio: "audio/mpeg,audio/wav,audio/x-wav,audio/ogg,audio/flac,audio/mp4,audio/webm",
@@ -30,21 +33,42 @@ const ACCEPT: Record<MediaKind, string> = {
const MAX_MB = 200;
-/** Upload a File and stream state changes back (preview first, then server ref). */
-export async function fileToSlot(file: File, onChange: (v: SlotValue | null) => void, kind?: MediaKind): Promise<void> {
- const k: MediaKind = kind ?? (file.type.startsWith("video/") ? "video" : file.type.startsWith("audio/") ? "audio" : "image");
+export const kindOfFile = (f: File): MediaKind => (f.type.startsWith("video/") ? "video" : f.type.startsWith("audio/") ? "audio" : "image");
+
+async function upload(file: File, signal?: AbortSignal): Promise<Asset> {
+ const form = new FormData();
+ form.append("file", file);
+ const res = await fetch("/api/uploads", { method: "POST", body: form, signal });
+ const body = (await res.json().catch(() => ({}))) as Asset & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Upload failed (${res.status})`);
+ return body;
+}
+
+/**
+ * Upload a File and stream state changes back: a local preview first (`uploading: true`), then
+ * the server ref, or null on failure. Pass a signal to cancel (a removed attachment): an aborted
+ * upload calls back nothing more. The preview's object URL is revoked once the upload settles.
+ */
+export async function fileToSlot(file: File, onChange: (v: SlotValue | null) => void, kind?: MediaKind, opts: { signal?: AbortSignal } = {}): Promise<void> {
+ const k: MediaKind = kind ?? kindOfFile(file);
if (file.size > MAX_MB * 1024 * 1024) {
toast.error(`That file's over ${MAX_MB} MB. Try a smaller one.`);
return;
}
const preview = URL.createObjectURL(file);
+ // Give the <img>/<video> a moment to switch to the server URL before the blob goes away.
+ const revoke = () => setTimeout(() => URL.revokeObjectURL(preview), 1500);
onChange({ ref: "", preview, kind: k, name: file.name, uploading: true });
try {
- const asset = await uploadFile(file);
+ const asset = await upload(file, opts.signal);
+ if (opts.signal?.aborted) return;
onChange({ ref: asset.url, preview: asset.url, kind: asset.kind, name: file.name });
} catch (e) {
+ if (opts.signal?.aborted || (e as Error).name === "AbortError") return;
onChange(null);
toast.error((e as Error).message || "Upload failed. Please try again.");
+ } finally {
+ revoke();
}
}
@@ -54,7 +78,7 @@ function KindIcon({ kind, className }: { kind: MediaKind; className?: string })
return <ImagePlus className={className} />;
}
-export function SlotPreview({ value, className }: { value: SlotValue; className?: string }) {
+export function SlotPreview({ value, className }: { value: Pick<SlotValue, "kind" | "preview" | "name">; className?: string }) {
if (value.kind === "video")
return <video src={value.preview} muted playsInline loop autoPlay className={cn("size-full object-cover", className)} />;
if (value.kind === "audio")
@@ -67,9 +91,53 @@ export function SlotPreview({ value, className }: { value: SlotValue; className?
return <img src={value.preview} alt={value.name ?? ""} className={cn("size-full object-cover", className)} />;
}
+/** Grid of your uploads and results of one kind (or several). */
+export function LibraryGrid({ kinds, onPick }: { kinds: MediaKind[]; onPick: (v: SlotValue) => void }) {
+ const [kind, setKind] = useState<MediaKind>(kinds[0] ?? "image");
+ const assets = useAssets(undefined, kind);
+ return (
+ <div className="space-y-2">
+ {kinds.length > 1 && (
+ <div role="tablist" aria-label="Kind" className="inline-flex rounded-full bg-muted p-0.5">
+ {kinds.map((k) => (
+ <button
+ key={k}
+ role="tab"
+ aria-selected={k === kind}
+ onClick={() => setKind(k)}
+ className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground capitalize transition", k === kind && "bg-background text-foreground shadow-soft")}
+ >
+ {k === "image" ? "Images" : k === "video" ? "Videos" : k === "audio" ? "Audio" : k}
+ </button>
+ ))}
+ </div>
+ )}
+ {assets.isLoading ? (
+ <div className="grid h-40 place-items-center">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
+ </div>
+ ) : assets.data?.length ? (
+ <div className="grid max-h-72 grid-cols-4 gap-1.5 overflow-y-auto">
+ {assets.data.map((a) => (
+ <button
+ key={a.id}
+ className="aspect-square overflow-hidden rounded-md bg-muted ring-primary transition outline-none hover:ring-2 focus-visible:ring-2"
+ aria-label={a.name ?? `${a.kind} from your library`}
+ onClick={() => onPick({ ref: a.url, preview: a.url, kind: a.kind, name: a.name ?? undefined })}
+ >
+ <SlotPreview value={{ preview: a.url, kind: a.kind }} />
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="px-1 py-6 text-center text-sm text-muted-foreground">Nothing here yet. Uploads and results show up here.</p>
+ )}
+ </div>
+ );
+}
+
function LibraryPicker({ kind, onPick }: { kind: MediaKind; onPick: (v: SlotValue) => void }) {
const [open, setOpen] = useState(false);
- const assets = useAssets(undefined, kind);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
@@ -81,25 +149,16 @@ function LibraryPicker({ kind, onPick }: { kind: MediaKind; onPick: (v: SlotValu
<Library className="size-3" />
</button>
</PopoverTrigger>
- <PopoverContent className="w-80 p-2" align="start">
+ <PopoverContent className="w-80 p-2" align="start" collisionPadding={12}>
<p className="px-1 pb-2 text-[13px] font-medium">From your library</p>
- {assets.data?.length ? (
- <div className="grid max-h-72 grid-cols-4 gap-1.5 overflow-y-auto">
- {assets.data.map((a) => (
- <button
- key={a.id}
- className="aspect-square overflow-hidden rounded-md bg-muted ring-primary transition hover:ring-2"
- onClick={() => {
- onPick({ ref: a.url, preview: a.url, kind: a.kind, name: a.name ?? undefined });
- setOpen(false);
- }}
- >
- <SlotPreview value={{ ref: a.url, preview: a.url, kind: a.kind }} />
- </button>
- ))}
- </div>
- ) : (
- <p className="px-1 py-6 text-center text-sm text-muted-foreground">Nothing here yet.</p>
+ {open && (
+ <LibraryGrid
+ kinds={[kind]}
+ onPick={(v) => {
+ onPick(v);
+ setOpen(false);
+ }}
+ />
)}
</PopoverContent>
</Popover>
@@ -115,6 +174,7 @@ export function MediaSlot({
required,
size = "md",
onFile,
+ slotKey,
}: {
label: string;
kind: MediaKind;
@@ -124,6 +184,8 @@ export function MediaSlot({
size?: "md" | "lg";
/** Take over file handling (e.g. to append to a list with a stable id). */
onFile?: (f: File) => void;
+ /** Marks the tile so the composer can point at it ("Add a start frame"). */
+ slotKey?: string;
}) {
const handleFile = (f: File) => (onFile ? onFile(f) : void fileToSlot(f, onChange, kind));
const input = useRef<HTMLInputElement>(null);
@@ -134,7 +196,8 @@ export function MediaSlot({
<Tooltip>
<TooltipTrigger asChild>
<div
- className={cn("group/slot relative shrink-0", dim)}
+ data-slot-key={slotKey}
+ className={cn("group/slot relative shrink-0 rounded-xl", dim)}
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -153,7 +216,7 @@ export function MediaSlot({
<div className="size-full overflow-hidden rounded-xl border bg-muted">
<SlotPreview value={value} />
{value.uploading && (
- <div className="absolute inset-0 grid place-items-center rounded-xl bg-background/60">
+ <div className="absolute inset-0 grid place-items-center rounded-xl bg-background/60" role="status" aria-label="Uploading">
<Loader2 className="size-4 animate-spin" />
</div>
)}
@@ -169,6 +232,7 @@ export function MediaSlot({
<button
type="button"
onClick={() => input.current?.click()}
+ aria-label={`${label}${required ? " (required)" : ""}: upload`}
className={cn(
"flex size-full flex-col items-center justify-center gap-0.5 rounded-xl border border-dashed border-border-strong text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text",
over && "border-primary bg-brand-faint text-brand-text",
diff --git a/src/components/studio/sketch-editor.tsx b/src/components/studio/sketch-editor.tsx
index 948a220a..5395549a 100644
--- a/src/components/studio/sketch-editor.tsx
+++ b/src/components/studio/sketch-editor.tsx
@@ -1,7 +1,7 @@
"use client";
import { Brush, Eraser, Loader2, Redo2, RotateCcw, Type, Undo2 } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -20,6 +20,12 @@ import { cn } from "@/lib/utils";
*/
export type SketchMode = "mask" | "draw";
+export type Stroke =
+ | { type: "path"; points: [number, number][]; size: number; color: string; erase: boolean }
+ | { type: "text"; at: [number, number]; text: string; size: number; color: string };
+
+type PathStroke = Extract<Stroke, { type: "path" }>;
+
export interface SketchResult {
/** mask mode: white = change. */
mask?: string;
@@ -29,14 +35,13 @@ export interface SketchResult {
preview: string;
/** draw mode: every brush stroke as a motion path, normalised to the image (Wan-Move draw-to-video). */
motion?: MotionPaths;
+ /** The strokes, in image pixels, so the drawing can be reopened and touched up. */
+ strokes: Stroke[];
}
-type Stroke =
- | { type: "path"; points: [number, number][]; size: number; color: string; erase: boolean }
- | { type: "text"; at: [number, number]; text: string; size: number; color: string };
-
const COLORS = ["#ff3b30", "#ffcc00", "#34c759", "#0a84ff", "#ffffff", "#111111"];
const MASK_TINT = "rgba(255, 59, 48, 0.55)";
+const MASK_RED = "rgba(255,59,48,1)";
function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
@@ -48,6 +53,28 @@ function loadImage(src: string): Promise<HTMLImageElement> {
});
}
+function pathStyle(ctx: CanvasRenderingContext2D, s: PathStroke, mode: SketchMode, scale: number, forMask: boolean) {
+ ctx.globalCompositeOperation = s.erase ? "destination-out" : "source-over";
+ ctx.strokeStyle = forMask ? "#ffffff" : mode === "mask" ? MASK_RED : s.color;
+ ctx.lineWidth = s.size * scale;
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+}
+
+/** Draw points [from, end) of a path (plus the joint before `from`), so a live stroke grows segment by segment. */
+function drawPath(ctx: CanvasRenderingContext2D, s: PathStroke, mode: SketchMode, scale: number, from = 0, forMask = false) {
+ const pts = s.points;
+ if (!pts.length || from >= pts.length) return;
+ pathStyle(ctx, s, mode, scale, forMask);
+ ctx.beginPath();
+ const start = Math.max(0, from - 1);
+ ctx.moveTo(pts[start][0] * scale, pts[start][1] * scale);
+ for (let i = start + 1; i < pts.length; i++) ctx.lineTo(pts[i][0] * scale, pts[i][1] * scale);
+ if (pts.length === 1) ctx.lineTo(pts[0][0] * scale + 0.01, pts[0][1] * scale);
+ ctx.stroke();
+ ctx.globalCompositeOperation = "source-over";
+}
+
function drawStrokes(ctx: CanvasRenderingContext2D, strokes: Stroke[], mode: SketchMode, scale: number, forMask = false) {
for (const s of strokes) {
if (s.type === "text") {
@@ -62,15 +89,7 @@ function drawStrokes(ctx: CanvasRenderingContext2D, strokes: Stroke[], mode: Ske
ctx.fillText(s.text, s.at[0] * scale, s.at[1] * scale);
continue;
}
- ctx.globalCompositeOperation = s.erase ? "destination-out" : "source-over";
- ctx.strokeStyle = forMask ? "#ffffff" : mode === "mask" ? "rgba(255,59,48,1)" : s.color;
- ctx.lineWidth = s.size * scale;
- ctx.lineCap = "round";
- ctx.lineJoin = "round";
- ctx.beginPath();
- s.points.forEach(([x, y], i) => (i ? ctx.lineTo(x * scale, y * scale) : ctx.moveTo(x * scale, y * scale)));
- if (s.points.length === 1) ctx.lineTo(s.points[0][0] * scale + 0.01, s.points[0][1] * scale);
- ctx.stroke();
+ drawPath(ctx, s, mode, scale, 0, forMask);
}
ctx.globalCompositeOperation = "source-over";
}
@@ -87,6 +106,7 @@ function ToolBtn({ active, onClick, icon: Icon, label }: { active: boolean; onCl
<TooltipTrigger asChild>
<button
onClick={onClick}
+ aria-pressed={active}
className={cn(
"grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
active && "bg-brand-faint text-brand-text",
@@ -101,11 +121,26 @@ function ToolBtn({ active, onClick, icon: Icon, label }: { active: boolean; onCl
);
}
-export function SketchEditor(props: { open: boolean; onOpenChange: (o: boolean) => void; image: string; mode: SketchMode; onDone: (r: SketchResult) => void }) {
+export function SketchEditor(props: {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ image: string;
+ mode: SketchMode;
+ /** Strokes of the drawing being touched up (empty for a new one). */
+ initialStrokes?: Stroke[];
+ onDone: (r: SketchResult) => void;
+}) {
+ // The canvas answers Escape first: it closes an open note instead of the whole editor.
+ const escapeRef = useRef<() => boolean>(() => false);
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
- <DialogContent className="flex h-[min(92vh,880px)] w-[min(96vw,1100px)] max-w-none flex-col gap-3 sm:max-w-none">
- {props.open && <SketchCanvas {...props} />}
+ <DialogContent
+ className="flex h-[min(92vh,880px)] w-[min(96vw,1100px)] max-w-none flex-col gap-3 sm:max-w-none"
+ onEscapeKeyDown={(e) => {
+ if (escapeRef.current()) e.preventDefault();
+ }}
+ >
+ {props.open && <SketchCanvas {...props} escapeRef={escapeRef} />}
</DialogContent>
</Dialog>
);
@@ -115,30 +150,36 @@ function SketchCanvas({
onOpenChange,
image,
mode,
+ initialStrokes,
onDone,
+ escapeRef,
}: {
onOpenChange: (o: boolean) => void;
image: string;
mode: SketchMode;
+ initialStrokes?: Stroke[];
onDone: (r: SketchResult) => void;
+ escapeRef: React.RefObject<() => boolean>;
}) {
const wrap = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
+ const ring = useRef<HTMLSpanElement>(null);
+ /** Offscreen paint layer at screen resolution: committed strokes plus the live one, opaque. */
+ const layer = useRef<HTMLCanvasElement | null>(null);
const [img, setImg] = useState<HTMLImageElement | null>(null);
const [view, setView] = useState({ w: 0, h: 0 });
- const [strokes, setStrokes] = useState<Stroke[]>([]);
+ const [strokes, setStrokes] = useState<Stroke[]>(() => initialStrokes ?? []);
const [redo, setRedo] = useState<Stroke[]>([]);
const [tool, setTool] = useState<"brush" | "eraser" | "text">("brush");
const [size, setSize] = useState(mode === "mask" ? 48 : 10);
const [color, setColor] = useState(COLORS[0]);
const [saving, setSaving] = useState(false);
- const [cursor, setCursor] = useState<[number, number] | null>(null);
- const drawing = useRef<Stroke | null>(null);
+ const drawing = useRef<PathStroke | null>(null);
+ /** How many points of the live stroke are already on the layer. */
+ const drawn = useRef(0);
+ const frame = useRef(0);
const [note, setNote] = useState<{ at: [number, number]; text: string } | null>(null);
- const commitNote = () => {
- if (note?.text.trim()) commit({ type: "text", at: note.at, text: note.text.trim().slice(0, 80), size: Math.max(18, size * 2.4) / scale, color });
- setNote(null);
- };
+ const noteOpen = useRef(false);
useEffect(() => {
loadImage(image).then(setImg, (e) => toast.error((e as Error).message));
@@ -160,38 +201,73 @@ function SketchCanvas({
const scale = img && view.w ? view.w / img.naturalWidth : 1;
- const paint = () => {
+ /** Show the paint layer: mask paint is tinted at a constant alpha so overlapping strokes don't stack. */
+ const composite = useCallback(() => {
const c = canvas.current;
- if (!c || !img || !view.w) return;
- const dpr = window.devicePixelRatio || 1;
- c.width = view.w * dpr;
- c.height = view.h * dpr;
+ const l = layer.current;
+ if (!c || !l) return;
const ctx = c.getContext("2d")!;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, c.width, c.height);
+ ctx.globalAlpha = mode === "mask" ? 0.55 : 1;
+ ctx.drawImage(l, 0, 0);
+ ctx.globalAlpha = 1;
+ }, [mode]);
+
+ /** Repaint the layer from scratch (after undo/redo/clear/commit or a resize): once per change, not per pointer move. */
+ const rebuild = useCallback(() => {
+ const l = layer.current;
+ if (!l) return;
+ const dpr = l.width / Math.max(1, view.w);
+ const ctx = l.getContext("2d")!;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, l.width, l.height);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- ctx.clearRect(0, 0, view.w, view.h);
- const all = drawing.current ? [...strokes, drawing.current] : strokes;
- if (mode === "mask") {
- // Paint the mask opaque on its own layer, then tint it so overlapping strokes don't stack.
- const layer = document.createElement("canvas");
- layer.width = c.width;
- layer.height = c.height;
- const lctx = layer.getContext("2d")!;
- lctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- drawStrokes(lctx, all, mode, scale);
- ctx.globalAlpha = 0.55;
- ctx.drawImage(layer, 0, 0, view.w, view.h);
- ctx.globalAlpha = 1;
- } else {
- drawStrokes(ctx, all, mode, scale);
+ drawStrokes(ctx, strokes, mode, scale);
+ if (drawing.current) {
+ drawPath(ctx, drawing.current, mode, scale);
+ drawn.current = drawing.current.points.length;
}
- };
+ composite();
+ }, [strokes, mode, scale, view.w, composite]);
- // Repaint after every render (strokes, size or layout changed); it's a single canvas.
- useEffect(() => {
- paint();
- });
+ // Size the canvases only when the layout changes (resetting width/height reallocates the backing store).
+ useLayoutEffect(() => {
+ const c = canvas.current;
+ if (!c || !view.w) return;
+ const dpr = window.devicePixelRatio || 1;
+ c.width = Math.round(view.w * dpr);
+ c.height = Math.round(view.h * dpr);
+ layer.current ??= document.createElement("canvas");
+ layer.current.width = c.width;
+ layer.current.height = c.height;
+ }, [view.w, view.h, img]);
+
+ useLayoutEffect(() => {
+ rebuild();
+ }, [rebuild]);
+
+ useEffect(() => () => cancelAnimationFrame(frame.current), []);
+
+ /** Draw the live stroke's new points on the layer, at most once per frame. */
+ const flush = useCallback(() => {
+ frame.current = 0;
+ const l = layer.current;
+ const d = drawing.current;
+ if (!l || !d) return;
+ const dpr = l.width / Math.max(1, view.w);
+ const ctx = l.getContext("2d")!;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ drawPath(ctx, d, mode, scale, drawn.current);
+ drawn.current = d.points.length;
+ composite();
+ }, [mode, scale, view.w, composite]);
+
+ const schedule = () => {
+ if (!frame.current) frame.current = requestAnimationFrame(flush);
+ };
- const pos = (e: React.PointerEvent): [number, number] => {
+ const pos = (e: { clientX: number; clientY: number }): [number, number] => {
const r = canvas.current!.getBoundingClientRect();
return [(e.clientX - r.left) / scale, (e.clientY - r.top) / scale];
};
@@ -201,26 +277,63 @@ function SketchCanvas({
setRedo([]);
};
+ const commitNote = () => {
+ if (note?.text.trim()) commit({ type: "text", at: note.at, text: note.text.trim().slice(0, 80), size: Math.max(18, size * 2.4) / scale, color });
+ setNote(null);
+ };
+
+ useEffect(() => {
+ noteOpen.current = !!note;
+ }, [note]);
+
+ // Escape while writing a note cancels the note; the editor stays open with its strokes.
+ useEffect(() => {
+ escapeRef.current = () => {
+ if (!noteOpen.current) return false;
+ setNote(null);
+ return true;
+ };
+ return () => {
+ escapeRef.current = () => false;
+ };
+ }, [escapeRef]);
+
+ const moveRing = (e: React.PointerEvent) => {
+ const el = ring.current;
+ const c = canvas.current;
+ if (!el || !c) return;
+ const r = c.getBoundingClientRect();
+ el.style.opacity = tool === "text" ? "0" : "1";
+ el.style.transform = `translate(${e.clientX - r.left - size / 2}px, ${e.clientY - r.top - size / 2}px)`;
+ };
+
const onDown = (e: React.PointerEvent) => {
if (tool === "text") {
+ // A click elsewhere keeps the note you were writing, then starts a new one there.
+ commitNote();
setNote({ at: pos(e), text: "" });
return;
}
(e.target as HTMLElement).setPointerCapture(e.pointerId);
drawing.current = { type: "path", points: [pos(e)], size: size / scale, color, erase: tool === "eraser" };
- paint();
+ drawn.current = 0;
+ schedule();
};
const onMove = (e: React.PointerEvent) => {
- const p = pos(e);
- setCursor(p);
+ moveRing(e);
const d = drawing.current;
- if (!d || d.type !== "path") return;
- d.points.push(p);
- paint();
+ if (!d) return;
+ const events = e.nativeEvent.getCoalescedEvents?.() ?? [];
+ for (const ev of events.length ? events : [e]) d.points.push(pos(ev));
+ schedule();
};
const onUp = () => {
- if (drawing.current) commit(drawing.current);
+ const d = drawing.current;
+ if (!d) return;
+ cancelAnimationFrame(frame.current);
+ frame.current = 0;
drawing.current = null;
+ commit(d);
};
const undo = () => {
@@ -245,8 +358,10 @@ function SketchCanvas({
e.preventDefault();
if (e.shiftKey) redoOne();
else undo();
- } else if (e.key === "b") setTool("brush");
+ } else if (e.metaKey || e.ctrlKey || e.altKey) return;
+ else if (e.key === "b") setTool("brush");
else if (e.key === "e") setTool("eraser");
+ else if (e.key === "t" && mode === "draw") setTool("text");
else if (e.key === "[") setSize((s) => Math.max(2, s - 4));
else if (e.key === "]") setSize((s) => Math.min(200, s + 4));
};
@@ -288,7 +403,10 @@ function SketchCanvas({
tctx.fillRect(0, 0, W, H);
octx.drawImage(tint, 0, 0);
} else {
- drawStrokes(octx, strokes, mode, 1);
+ // Draw on a transparent layer first so the eraser removes paint, not the photo.
+ const [paintC, pctx] = make();
+ drawStrokes(pctx, strokes, mode, 1);
+ octx.drawImage(paintC, 0, 0);
}
const overlay = await uploadFile(await canvasToFile(ov, mode === "mask" ? "mask-overlay.png" : "sketch.png"));
const motion: MotionPaths | undefined =
@@ -298,7 +416,7 @@ function SketchCanvas({
paths: strokes.flatMap((st) => (st.type === "path" && !st.erase && st.points.length > 1 ? [st.points.map(([x, y]) => [x / W, y / H] as [number, number])] : [])),
}
: undefined;
- onDone({ mask: maskUrl, overlay: overlay.url, preview: overlay.url, motion });
+ onDone({ mask: maskUrl, overlay: overlay.url, preview: overlay.url, motion, strokes });
onOpenChange(false);
} catch (e) {
toast.error((e as Error).message);
@@ -320,10 +438,10 @@ function SketchCanvas({
<div className="flex flex-wrap items-center gap-1.5">
<ToolBtn active={tool === "brush"} onClick={() => setTool("brush")} icon={Brush} label="Brush (B)" />
<ToolBtn active={tool === "eraser"} onClick={() => setTool("eraser")} icon={Eraser} label="Eraser (E)" />
- {mode === "draw" && <ToolBtn active={tool === "text"} onClick={() => setTool("text")} icon={Type} label="Add a note" />}
+ {mode === "draw" && <ToolBtn active={tool === "text"} onClick={() => setTool("text")} icon={Type} label="Add a note (T)" />}
<div className="mx-2 flex w-40 items-center gap-2">
<span className="text-[12px] text-muted-foreground">Size</span>
- <Slider value={[size]} min={2} max={200} step={1} onValueChange={([v]) => setSize(v)} />
+ <Slider value={[size]} min={2} max={200} step={1} onValueChange={([v]) => setSize(v)} aria-label="Brush size" />
</div>
{mode === "draw" && (
<div className="flex items-center gap-1">
@@ -331,6 +449,7 @@ function SketchCanvas({
<button
key={c}
onClick={() => setColor(c)}
+ aria-pressed={color === c}
className={cn("size-6 rounded-full border ring-offset-2 ring-offset-background", color === c && "ring-2 ring-primary")}
style={{ background: c }}
aria-label={`Colour ${c}`}
@@ -359,10 +478,13 @@ function SketchCanvas({
ref={canvas}
className={cn("absolute inset-0 size-full touch-none", tool === "text" ? "cursor-text" : "cursor-none")}
style={{ width: view.w, height: view.h }}
+ // Keep focus in the note that pointerdown just opened (the default would move it to the dialog).
+ onMouseDown={(e) => tool === "text" && e.preventDefault()}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
- onPointerLeave={() => setCursor(null)}
+ onPointerCancel={onUp}
+ onPointerLeave={() => ring.current && (ring.current.style.opacity = "0")}
/>
{note && (
<input
@@ -375,24 +497,25 @@ function SketchCanvas({
if (e.key === "Escape") setNote(null);
}}
onBlur={commitNote}
+ aria-label="Note text"
placeholder="Type a note, ↵"
className="absolute min-w-40 rounded-md border bg-background/95 px-2 py-1 text-sm shadow-normal outline-none"
style={{ left: note.at[0] * scale, top: note.at[1] * scale, color }}
/>
)}
- {cursor && tool !== "text" && (
- <span
- className="pointer-events-none absolute rounded-full border-2 border-white mix-blend-difference"
- style={{ width: size, height: size, left: cursor[0] * scale - size / 2, top: cursor[1] * scale - size / 2 }}
- />
- )}
+ <span
+ ref={ring}
+ aria-hidden
+ className="pointer-events-none absolute top-0 left-0 rounded-full border-2 border-white opacity-0 mix-blend-difference"
+ style={{ width: size, height: size }}
+ />
</div>
) : (
<Loader2 className="size-5 animate-spin text-white/70" />
)}
</div>
<DialogFooter className="items-center">
- <p className="mr-auto hidden text-[12px] text-muted-foreground sm:block">[ ] brush size · ⌘Z undo · ⇧⌘Z redo</p>
+ <p className="mr-auto hidden text-[12px] text-muted-foreground sm:block">[ ] brush size · ⌘Z undo · ⇧⌘Z redo{mode === "draw" ? " · T note" : ""}</p>
<Button variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
diff --git a/src/components/studio/sketch-tools.tsx b/src/components/studio/sketch-tools.tsx
index 5442cf4b..6912b3d8 100644
--- a/src/components/studio/sketch-tools.tsx
+++ b/src/components/studio/sketch-tools.tsx
@@ -32,17 +32,22 @@ export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; i
<>
{current?.ref ? (
<div className="group/slot relative size-14 shrink-0">
- <button
- onClick={() => setEditing(mode)}
- className="size-full overflow-hidden rounded-xl border-2 border-primary bg-muted"
- aria-label={mode === "mask" ? "Edit the painted area" : "Edit the drawing"}
- >
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={current.preview} alt="" className="size-full object-cover" />
- <span className="absolute inset-x-0 bottom-0 bg-primary/90 py-px text-center text-[9px] font-semibold text-primary-foreground">
- {mode === "mask" ? "Area" : "Drawing"}
- </span>
- </button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={() => setEditing(mode)}
+ className="size-full overflow-hidden rounded-xl border-2 border-primary bg-muted"
+ aria-label={mode === "mask" ? "Edit the painted area" : "Edit the drawing"}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={current.preview} alt="" className="size-full object-cover" />
+ <span className="absolute inset-x-0 bottom-0 bg-primary/90 py-px text-center text-[9px] font-semibold text-primary-foreground">
+ {mode === "mask" ? "Area" : "Drawing"}
+ </span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{mode === "mask" ? "Touch up the painted area" : "Touch up the drawing"}</TooltipContent>
+ </Tooltip>
<button
onClick={clear}
className="absolute -top-1.5 -right-1.5 grid size-5 place-items-center rounded-full bg-foreground text-background shadow-soft"
@@ -73,6 +78,8 @@ export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; i
onOpenChange={(o) => !o && setEditing(null)}
image={image}
mode={editing}
+ // Reopen the earlier strokes so a touch-up adds to the drawing instead of replacing it.
+ initialStrokes={current?.sketch?.mode === editing ? current.sketch.strokes : undefined}
onDone={(r) =>
setDraft((d) => {
const extra = { ...d.params.extra };
@@ -82,7 +89,7 @@ export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; i
slots: {
...d.slots,
mask: r.mask ? { ref: r.mask, preview: r.preview, kind: "image" } : null,
- sketch: { ref: r.overlay, preview: r.preview, kind: "image" },
+ sketch: { ref: r.overlay, preview: r.preview, kind: "image", sketch: { mode: editing, strokes: r.strokes } },
},
params: { ...d.params, extra },
};