Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ImageAnnotationOverlay.tsx

682 lines23.5 KB

1import {
2 addStrokePoint,
3 openStrokePath,
4 startStroke,
5 strokeBounds,
6 type StrokeGeometry,
7} from "~/lib/annotationStroke";
8import type { PreviewAnnotationPoint, PreviewAnnotationRect } from "@t3tools/contracts";
9import { useGT } from "gt-react";
10import { EraserIcon, MoveUpRightIcon, PencilIcon, TypeIcon, Undo2Icon } from "lucide-react";
11import { use, useEffect, useEffectEvent, useRef, useState, type PointerEvent } from "react";
12​
13import { isContextMenuOpen } from "../../contextMenuFallback";
14import { createCanvas, readImageColorSpace } from "../../lib/imageCanvas";
15import { encodeCanvas } from "../../lib/imageCompression";
16import { cn, isMacPlatform } from "~/lib/utils";
17import { Button } from "../ui/button";
18import { Input } from "../ui/input";
19import { ToggleGroup, ToggleGroupItem } from "../ui/toggle-group";
20import { ZoomableImageNaturalSize } from "./ZoomableImage";
21​
22const TOOL_SHORTCUTS = { d: "draw", e: "erase", a: "arrow", t: "text" } as const;
23type AnnotationTool = (typeof TOOL_SHORTCUTS)[keyof typeof TOOL_SHORTCUTS];
24​
25/** The stored result of an edit: the new bytes and a URL that shows them. */
26export interface EditedImage {
27 readonly src: string;
28 readonly file: File;
30​
31export interface ImageAnnotationTarget {
32 readonly file: File;
33 readonly name: string;
34 readonly mimeType: string;
35 /** Stores the flattened file; `null` when it could not be stored. */
36 readonly save: (file: File) => Promise<EditedImage | null>;
38​
39export interface ImageAnnotationStatus {
40 readonly dirty: boolean;
41 readonly saving: boolean;
43​
44type DrawnStroke = {
45 readonly id: number;
46 readonly color: string;
47 readonly width: number;
48 readonly path: string;
49} & (
50 | { readonly kind: "draw"; readonly bounds: PreviewAnnotationRect }
51 | { readonly kind: "arrow" }
52);
53​
54interface TextLabel extends PreviewAnnotationPoint {
55 readonly kind: "text";
56 readonly id: number;
57 readonly color: string;
58 readonly outline: string;
59 readonly size: number;
60 readonly text: string;
61 readonly bounds: PreviewAnnotationRect;
63​
64type Mark = DrawnStroke | TextLabel;
65​
66interface LabelDraft {
67 readonly anchor: PreviewAnnotationPoint;
68 readonly size: number;
69 readonly color: string;
70 readonly outline: string;
71 readonly input: string;
72 readonly mark: TextLabel | null;
74​
75interface ActiveStroke {
76 readonly kind: "draw" | "arrow";
77 readonly pointerId: number;
78 readonly color: string;
79 readonly width: number;
80 readonly geometry: StrokeGeometry;
81 readonly closedPaths: string[];
82 readonly group: SVGGElement;
83 path: SVGPathElement;
85​
86const SVG_NS = "http://www.w3.org/2000/svg";
87// The browser panel's Draw tool paints 4 CSS pixels wide in its theme's primary color.
88const STROKE_SCREEN_WIDTH = 4;
89const LABEL_SCREEN_SIZE = 20;
90const LABEL_FONT_FAMILY = "system-ui, sans-serif";
91const LABEL_FONT_WEIGHT = 600;
92const PRIMARY_COLOR = "var(--primary)";
93const STROKE_COLORS = [PRIMARY_COLOR, "#ef4444", "#f59e0b", "#22c55e", "#ffffff", "#000000"];
94​
95function resolveColor(color: string): string {
96 if (color !== PRIMARY_COLOR) return color;
97 return (
98 getComputedStyle(document.documentElement).getPropertyValue("--primary").trim() || "#2563eb"
99 );
101​
102function annotatedFileName(name: string, mimeType: string): string {
103 if (mimeType !== "image/png") return name;
104 const dot = name.lastIndexOf(".");
105 return `${dot > 0 ? name.slice(0, dot) : name}.png`;
107​
108function arrowPath(
109 from: PreviewAnnotationPoint,
110 to: PreviewAnnotationPoint,
111 width: number,
112 image: { width: number; height: number },
113) {
114 const dx = to.x - from.x;
115 const dy = to.y - from.y;
116 const fraction = Math.min(
117 1,
118 dx === 0 ? 1 : ((dx > 0 ? image.width : 0) - from.x) / dx,
119 dy === 0 ? 1 : ((dy > 0 ? image.height : 0) - from.y) / dy,
120 );
121 const length = Math.hypot(dx, dy) * fraction;
122 if (length < width) return null;
123 const tip = { x: from.x + dx * fraction, y: from.y + dy * fraction };
124 const angle = Math.atan2(dy, dx);
125 const head = Math.min(width * 4.5, length * 0.65);
126 const headPoint = (angle: number) => ({
127 x: tip.x - head * Math.cos(angle),
128 y: tip.y - head * Math.sin(angle),
129 });
130 const left = headPoint(angle - Math.PI / 7);
131 const right = headPoint(angle + Math.PI / 7);
132 return `M ${from.x} ${from.y} L ${tip.x} ${tip.y} M ${left.x} ${left.y} L ${tip.x} ${tip.y} L ${right.x} ${right.y}`;
134​
135function labelFont(size: number) {
136 return `${LABEL_FONT_WEIGHT} ${size}px ${LABEL_FONT_FAMILY}`;
138​
139function labelOutlineWidth(size: number) {
140 return size / 7;
142​
143function positionLabel(
144 draft: LabelDraft,
145 input: string,
146 image: { width: number; height: number },
147 id: number,
148): TextLabel | null {
149 const text = input.trim();
150 if (!text) return null;
151 const surface = createCanvas(1, 1, "srgb");
152 if (!surface) return null;
153 const { context } = surface;
154 context.font = labelFont(draft.size);
155 context.direction = "ltr";
156 context.textAlign = "left";
157 const unscaled = context.measureText(text);
158 const width = unscaled.actualBoundingBoxLeft + unscaled.actualBoundingBoxRight;
159 const height = unscaled.actualBoundingBoxAscent + unscaled.actualBoundingBoxDescent;
160 const padding = labelOutlineWidth(draft.size) + 2;
161 const scale = Math.min(1, image.width / (width + padding), image.height / (height + padding));
162 const size = draft.size * scale;
163 context.font = labelFont(size);
164 const metrics = context.measureText(text);
165 const pad = labelOutlineWidth(size) / 2;
166 const left = metrics.actualBoundingBoxLeft + pad;
167 const right = metrics.actualBoundingBoxRight + pad;
168 const top = metrics.actualBoundingBoxAscent + pad;
169 const bottom = metrics.actualBoundingBoxDescent + pad;
170 const x = Math.max(left, Math.min(draft.anchor.x, image.width - right));
171 const y = Math.max(top, Math.min(draft.anchor.y + top, image.height - bottom));
172 return {
173 kind: "text",
174 id,
175 x,
176 y,
177 text,
178 size,
179 color: draft.color,
180 outline: draft.outline,
181 bounds: { x: x - left, y: y - top, width: left + right, height: top + bottom },
182 };
184​
185function ImageTextLabel({ label }: { readonly label: TextLabel }) {
186 return (
187 <text
188 x={label.x}
189 y={label.y}
190 fill={label.color}
191 stroke={label.outline}
192 strokeWidth={labelOutlineWidth(label.size)}
193 fontFamily={LABEL_FONT_FAMILY}
194 fontWeight={LABEL_FONT_WEIGHT}
195 fontSize={label.size}
196 direction="ltr"
197 className="whitespace-pre [paint-order:stroke]"
198 >
199 {label.text}
200 </text>
201 );
203​
204/** Paints the marks over the original pixels; `null` when the browser cannot draw or encode it. */
205async function flattenAnnotatedImage(
206 target: ImageAnnotationTarget,
207 marks: ReadonlyArray<Mark>,
208 viewSize: { width: number; height: number },
209): Promise<File | null> {
210 const bitmap = await createImageBitmap(target.file, { imageOrientation: "from-image" }).catch(
211 () => null,
212 );
213 if (!bitmap) return null;
214 try {
215 const colorSpace = await readImageColorSpace(target.file);
216 const surface = createCanvas(bitmap.width, bitmap.height, colorSpace);
217 if (!surface) return null;
218 const { context } = surface;
219 context.drawImage(bitmap, 0, 0);
220 context.scale(bitmap.width / viewSize.width, bitmap.height / viewSize.height);
221 context.lineCap = "round";
222 context.lineJoin = "round";
223 for (const mark of marks) {
224 if (mark.kind === "text") {
225 context.font = labelFont(mark.size);
226 context.direction = "ltr";
227 context.textAlign = "left";
228 context.lineWidth = labelOutlineWidth(mark.size);
229 context.strokeStyle = mark.outline;
230 context.fillStyle = mark.color;
231 context.strokeText(mark.text, mark.x, mark.y);
232 context.fillText(mark.text, mark.x, mark.y);
233 } else {
234 context.strokeStyle = mark.color;
235 context.lineWidth = mark.width;
236 context.stroke(new Path2D(mark.path));
237 }
238 }
239 const mimeType =
240 target.mimeType === "image/jpeg" || target.mimeType === "image/webp"
241 ? target.mimeType
242 : "image/png";
243 const blob = await encodeCanvas(surface.canvas, colorSpace, 0.92, mimeType);
244 if (!blob) return null;
245 return new File([blob], annotatedFileName(target.name, mimeType), {
246 type: mimeType,
247 lastModified: Date.now(),
248 });
249 } finally {
250 bitmap.close();
251 }
253​
254/**
255 * Draws over an image in place: the surface covers the image exactly and the toolbar floats
256 * above it, so nothing around the image moves while editing.
257 */
258export function ImageAnnotationOverlay({
259 target,
260 onStatusChange,
261 onSaved,
262 onExit,
263}: {
264 readonly target: ImageAnnotationTarget;
265 readonly onStatusChange: (status: ImageAnnotationStatus) => void;
266 readonly onSaved: (edited: EditedImage) => void;
267 /** Leaves edit mode without changing the image. */
268 readonly onExit: () => void;
269}) {
270 const gt = useGT();
271 const naturalSize = use(ZoomableImageNaturalSize);
272 const [tool, setTool] = useState<AnnotationTool>("draw");
273 const [color, setColor] = useState(PRIMARY_COLOR);
274 const [marks, setMarks] = useState<ReadonlyArray<Mark>>([]);
275 const [history, setHistory] = useState<ReadonlyArray<ReadonlyArray<Mark>>>([]);
276 const [labelDraft, setLabelDraft] = useState<LabelDraft | null>(null);
277 const [saving, setSaving] = useState(false);
278 const [failed, setFailed] = useState(false);
279 const liveLayerRef = useRef<SVGGElement>(null);
280 const activeStrokeRef = useRef<ActiveStroke | null>(null);
281 const nextMarkIdRef = useRef(0);
282 const labelInputRef = useRef<HTMLInputElement | null>(null);
283 const doneButtonRef = useRef<HTMLButtonElement>(null);
284​
285 const attachLabelInput = (input: HTMLInputElement | null) => {
286 labelInputRef.current = input;
287 input?.focus({ preventScroll: true });
288 };
289​
290 const showMarks = (next: ReadonlyArray<Mark>) => {
291 setMarks(next);
292 onStatusChange({
293 dirty: next.length > 0 || activeStrokeRef.current !== null,
294 saving,
295 });
296 };
297​
298 const commit = (next: ReadonlyArray<Mark>) => {
299 setHistory((current) => [...current, marks]);
300 showMarks(next);
301 };
302​
303 const finishLabel = () => {
304 if (!labelDraft) return marks;
305 setLabelDraft(null);
306 if (!labelDraft.mark) return marks;
307 nextMarkIdRef.current += 1;
308 const next = [...marks, labelDraft.mark];
309 commit(next);
310 return next;
311 };
312​
313 const cancelLabel = () => {
314 setLabelDraft(null);
315 onStatusChange({ dirty: marks.length > 0, saving });
316 };
317​
318 const selectTool = (next: AnnotationTool) => {
319 finishLabel();
320 setTool(next);
321 };
322​
323 const undo = () => {
324 if (labelDraft) {
325 cancelLabel();
326 return;
327 }
328 const previous = history.at(-1);
329 if (!previous || saving) return;
330 setHistory(history.slice(0, -1));
331 showMarks(previous);
332 };
333​
334 const done = async () => {
335 if (saving || activeStrokeRef.current) return;
336 const next = finishLabel();
337 if (next.length === 0) {
338 onExit();
339 return;
340 }
341 setSaving(true);
342 setFailed(false);
343 onStatusChange({ dirty: true, saving: true });
344 const file = await flattenAnnotatedImage(target, next, naturalSize).catch(() => null);
345 const edited = file ? await target.save(file).catch(() => null) : null;
346 if (edited) {
347 onSaved(edited);
348 return;
349 }
350 setSaving(false);
351 setFailed(true);
352 onStatusChange({ dirty: true, saving: false });
353 };
354​
355 const handleKey = useEffectEvent((event: globalThis.KeyboardEvent) => {
356 if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return;
357 if (event.key === "Escape" && labelDraft && !isContextMenuOpen()) {
358 event.preventDefault();
359 event.stopPropagation();
360 cancelLabel();
361 doneButtonRef.current?.focus({ preventScroll: true });
362 return;
363 }
364 if (event.target instanceof HTMLInputElement) return;
365 const mod = isMacPlatform(navigator.platform) ? event.metaKey : event.ctrlKey;
366 if (mod && !event.shiftKey && event.key.toLowerCase() === "z") {
367 event.preventDefault();
368 undo();
369 return;
370 }
371 // Enter on a focused button presses that button instead.
372 if (event.key === "Enter" && !event.shiftKey && !(event.target instanceof HTMLButtonElement)) {
373 event.preventDefault();
374 void done();
375 return;
376 }
377 if (mod || event.altKey) return;
378 if (Object.hasOwn(TOOL_SHORTCUTS, event.key))
379 selectTool(TOOL_SHORTCUTS[event.key as keyof typeof TOOL_SHORTCUTS]);
380 });
381 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for drawing keys anywhere in the preview and moves focus to Done so Enter saves
382 useEffect(() => {
383 doneButtonRef.current?.focus({ preventScroll: true });
384 const onKeyDown = (event: globalThis.KeyboardEvent) => handleKey(event);
385 const onEscape = (event: globalThis.KeyboardEvent) => {
386 if (event.key === "Escape") handleKey(event);
387 };
388 document.addEventListener("keydown", onKeyDown);
389 document.addEventListener("keydown", onEscape, true);
390 return () => {
391 document.removeEventListener("keydown", onKeyDown);
392 document.removeEventListener("keydown", onEscape, true);
393 };
394 }, []);
395​
396 const toViewPoint = (event: PointerEvent<SVGSVGElement>) => {
397 const rect = event.currentTarget.getBoundingClientRect();
398 const scale = naturalSize.width / rect.width;
399 return {
400 x: Math.round((event.clientX - rect.left) * scale * 10) / 10,
401 y: Math.round((event.clientY - rect.top) * scale * 10) / 10,
402 scale,
403 };
404 };
405​
406 const onPointerDown = (event: PointerEvent<SVGSVGElement>) => {
407 if (event.button !== 0 || saving || activeStrokeRef.current) return;
408 doneButtonRef.current?.focus({ preventScroll: true });
409 event.preventDefault();
410 const { x, y, scale } = toViewPoint(event);
411 if (tool === "erase") {
412 const arrowId =
413 event.target instanceof SVGPathElement ? event.target.dataset.arrow : undefined;
414 const index = marks.findLastIndex((mark) => {
415 if (mark.kind === "arrow") return arrowId === String(mark.id);
416 if (arrowId !== undefined) return false;
417 const { bounds } = mark;
418 return (
419 x >= bounds.x &&
420 x <= bounds.x + bounds.width &&
421 y >= bounds.y &&
422 y <= bounds.y + bounds.height
423 );
424 });
425 if (index >= 0) commit(marks.filter((_, candidate) => candidate !== index));
426 return;
427 }
428 if (tool === "text") {
429 finishLabel();
430 setLabelDraft({
431 anchor: { x, y },
432 color: resolveColor(color),
433 outline:
434 color === "#000000" || color === PRIMARY_COLOR
435 ? "rgba(255,255,255,0.85)"
436 : "rgba(0,0,0,0.6)",
437 size: LABEL_SCREEN_SIZE * scale,
438 input: "",
439 mark: null,
440 });
441 labelInputRef.current?.focus({ preventScroll: true });
442 return;
443 }
444 const layer = liveLayerRef.current;
445 if (!layer) return;
446 event.currentTarget.setPointerCapture(event.pointerId);
447 const strokeColor = resolveColor(color);
448 const width = STROKE_SCREEN_WIDTH * scale;
449 const group = document.createElementNS(SVG_NS, "g");
450 group.setAttribute("stroke", strokeColor);
451 group.setAttribute("stroke-width", String(width));
452 const path = group.appendChild(document.createElementNS(SVG_NS, "path"));
453 layer.appendChild(group);
454 activeStrokeRef.current = {
455 kind: tool,
456 pointerId: event.pointerId,
457 color: strokeColor,
458 width,
459 geometry: startStroke({ x, y }),
460 closedPaths: [],
461 group,
462 path,
463 };
464 onStatusChange({ dirty: true, saving });
465 };
466​
467 // Strokes paint straight into the SVG on pointer input, so drawing never re-renders React.
468 const onPointerMove = (event: PointerEvent<SVGSVGElement>) => {
469 const active = activeStrokeRef.current;
470 if (!active || active.pointerId !== event.pointerId) return;
471 const { x, y } = toViewPoint(event);
472 if (active.kind === "arrow") {
473 const path = arrowPath(active.geometry.points[0]!, { x, y }, active.width, naturalSize);
474 active.path.setAttribute("d", path ?? "");
475 return;
476 }
477 const closedPath = addStrokePoint(active.geometry, { x, y });
478 if (closedPath) {
479 active.path.setAttribute("d", closedPath);
480 active.closedPaths.push(closedPath);
481 active.path = active.group.appendChild(document.createElementNS(SVG_NS, "path"));
482 }
483 active.path.setAttribute("d", openStrokePath(active.geometry));
484 };
485​
486 const finishStroke = (event: PointerEvent<SVGSVGElement>) => {
487 const active = activeStrokeRef.current;
488 if (!active || active.pointerId !== event.pointerId) return;
489 activeStrokeRef.current = null;
490 active.group.remove();
491 const path =
492 active.kind === "arrow"
493 ? event.type === "pointerup" &&
494 arrowPath(active.geometry.points[0]!, toViewPoint(event), active.width, naturalSize)
495 : active.geometry.points.length >= 2 &&
496 [...active.closedPaths, openStrokePath(active.geometry)].join(" ");
497 if (!path) {
498 onStatusChange({ dirty: marks.length > 0, saving });
499 return;
500 }
501 nextMarkIdRef.current += 1;
502 commit([
503 ...marks,
504 {
505 ...(active.kind === "arrow"
506 ? { kind: "arrow" }
507 : { kind: "draw", bounds: strokeBounds(active.geometry, active.width) }),
508 id: nextMarkIdRef.current,
509 color: active.color,
510 width: active.width,
511 path,
512 },
513 ]);
514 };
515​
516 const colorLabels: Record<string, string> = {
517 [PRIMARY_COLOR]: gt`Theme color`,
518 "#ef4444": gt({ context: "stroke color" })`Red`,
519 "#f59e0b": gt({ context: "stroke color" })`Orange`,
520 "#22c55e": gt({ context: "stroke color" })`Green`,
521 "#ffffff": gt({ context: "stroke color" })`White`,
522 "#000000": gt({ context: "stroke color" })`Black`,
523 };
524​
525 return (
526 <>
527 <svg
528 viewBox={`0 0 ${naturalSize.width} ${naturalSize.height}`}
529 preserveAspectRatio="none"
530 fill="none"
531 strokeLinecap="round"
532 strokeLinejoin="round"
533 aria-label={gt`Draw on ${{ name: target.name }}`}
534 role="img"
535 className={cn(
536 "absolute inset-0 size-full touch-none rounded-lg",
537 tool === "draw" || tool === "arrow"
538 ? "cursor-crosshair"
539 : tool === "text"
540 ? "cursor-text"
541 : "cursor-pointer",
542 )}
543 onPointerDown={onPointerDown}
544 onPointerMove={onPointerMove}
545 onPointerUp={finishStroke}
546 onPointerCancel={finishStroke}
547 onLostPointerCapture={(event) => {
548 if (event.target === event.currentTarget) finishStroke(event);
549 }}
550 >
551 {marks.map((mark) =>
552 mark.kind === "text" ? (
553 <ImageTextLabel key={mark.id} label={mark} />
554 ) : (
555 <path
556 key={mark.id}
557 data-arrow={mark.kind === "arrow" ? mark.id : undefined}
558 d={mark.path}
559 stroke={mark.color}
560 strokeWidth={mark.width}
561 />
562 ),
563 )}
564 {labelDraft?.mark && <ImageTextLabel label={labelDraft.mark} />}
565 <g ref={liveLayerRef} />
566 </svg>
567 {labelDraft ? (
568 <div
569 className="absolute z-10 w-48 rounded-md bg-popover"
570 style={{
571 left: `clamp(0px, ${(labelDraft.anchor.x / naturalSize.width) * 100}%, calc(100% - 12rem))`,
572 top:
573 labelDraft.anchor.y > naturalSize.height / 2
574 ? `max(0px, calc(${(labelDraft.anchor.y / naturalSize.height) * 100}% - 2.25rem))`
575 : `calc(${(labelDraft.anchor.y / naturalSize.height) * 100}% + 1.75rem)`,
576 }}
577 >
578 <Input
579 ref={attachLabelInput}
580 size="compact"
581 aria-label={gt`Text label`}
582 placeholder={gt`Text label`}
583 value={labelDraft.input}
584 onChange={(event) => {
585 const input = event.target.value;
586 const mark = positionLabel(labelDraft, input, naturalSize, nextMarkIdRef.current + 1);
587 setLabelDraft({ ...labelDraft, input, mark });
588 if (Boolean(mark) !== Boolean(labelDraft.mark))
589 onStatusChange({ dirty: mark !== null || marks.length > 0, saving });
590 }}
591 onKeyDown={(event) => {
592 event.stopPropagation();
593 if (event.nativeEvent.isComposing || event.keyCode === 229 || event.key !== "Enter")
594 return;
595 event.preventDefault();
596 finishLabel();
597 doneButtonRef.current?.focus({ preventScroll: true });
598 }}
599 />
600 </div>
601 ) : null}
602 {/* Floats above the image and takes no layout space, so entering edit mode moves nothing. */}
603 <div className="absolute bottom-full left-1/2 z-10 mb-2 flex w-max max-w-[calc(100vw-7rem)] -translate-x-1/2 flex-col items-center gap-1 rounded-lg border border-border bg-popover/95 p-1 text-popover-foreground shadow-lg backdrop-blur-xl">
604 <div className="flex flex-wrap items-center justify-center gap-1">
605 <ToggleGroup
606 variant="default"
607 size="sm"
608 aria-label={gt`Drawing tool`}
609 value={[tool]}
610 onValueChange={(values) => {
611 const next = values[0];
612 if (next) selectTool(next as AnnotationTool);
613 }}
614 >
615 <ToggleGroupItem value="draw" aria-label={gt`Draw freehand (D)`}>
616 <PencilIcon />
617 <span className="max-sm:sr-only">
618 {gt({ context: "drawing tool, freehand pen" })`Draw`}
619 </span>
620 </ToggleGroupItem>
621 <ToggleGroupItem value="arrow" aria-label={gt`Draw an arrow (A)`}>
622 <MoveUpRightIcon />
623 <span className="max-lg:sr-only">{gt`Arrow`}</span>
624 </ToggleGroupItem>
625 <ToggleGroupItem value="text" aria-label={gt`Add a text label (T)`}>
626 <TypeIcon />
627 <span className="max-lg:sr-only">{gt`Text`}</span>
628 </ToggleGroupItem>
629 <ToggleGroupItem value="erase" aria-label={gt`Erase a stroke (E)`}>
630 <EraserIcon />
631 <span className="max-sm:sr-only">
632 {gt({ context: "drawing tool, removes a stroke" })`Erase`}
633 </span>
634 </ToggleGroupItem>
635 </ToggleGroup>
636 <div role="radiogroup" aria-label={gt`Stroke color`} className="flex items-center px-1">
637 {STROKE_COLORS.map((swatch) => (
638 <button
639 key={swatch}
640 type="button"
641 role="radio"
642 aria-checked={color === swatch}
643 aria-label={colorLabels[swatch]}
644 onClick={() => {
645 setColor(swatch);
646 if (tool === "erase") setTool("draw");
647 }}
648 className={cn(
649 "flex size-7 items-center justify-center rounded-md outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
650 color === swatch && "bg-accent",
651 )}
652 >
653 <span
654 className="size-4 rounded-full ring-1 ring-foreground/20 ring-inset"
655 style={{ background: swatch }}
656 />
657 </button>
658 ))}
659 </div>
660 <Button
661 variant="ghost"
662 size="sm"
663 onClick={undo}
664 disabled={(!labelDraft && history.length === 0) || saving}
665 aria-label={gt`Undo`}
666 >
667 <Undo2Icon />
668 <span className="max-sm:sr-only">{gt`Undo`}</span>
669 </Button>
670 <Button ref={doneButtonRef} size="sm" onClick={() => void done()} disabled={saving}>
671 {gt`Done`}
672 </Button>
673 </div>
674 {failed ? (
675 <p role="alert" className="px-2 pb-1 text-xs text-destructive">
676 {gt`The drawing could not be saved. Try again or cancel.`}
677 </p>
678 ) : null}
679 </div>
680 </>
681 );