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

ImageAnnotationOverlay.tsx

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