diff --git a/AGENTS.md b/AGENTS.md index 81f4fe7..8f9da35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,7 @@ Also verify affected components, multi-monitor/DPI-sensitive geometry, loading, ## Tech stack - Workspace: pnpm 11.14.0, TypeScript, strict mode -- Desktop: Tauri 2.11, Rust 2024, React 19, Vite 8, Tailwind CSS 4, Zod 4, webview2-com 0.38.2 + windows-core 0.61 (camera permission only, pinned to versions already in the tree) +- Desktop: Tauri 2.11, Rust 2024, React 19, Vite 8, Tailwind CSS 4, Zod 4, Rough.js 4.6 (generator only, for sketchy strokes), webview2-com 0.38.2 + windows-core 0.61 (camera permission only, pinned to versions already in the tree) - Landing page: Next.js 16.2 App Router, React 19, TypeScript 5, Tailwind CSS 4, Framer Motion 12 - Tooling: ESLint 9, Vitest 4, Testing Library, Cargo - Targets: Windows 11 supported; macOS, Ubuntu, and Fedora provisional diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index 5d51e14..1382f60 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,6 +2,22 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. +## Unreleased + +### Added + +- Your own keys for toolbar tools: Settings → Toolbar → Tool keys. Smart select now comes first by default for new installs. +- Sketch level (Neat, Loose, Wild) for the Sketchy line style, and hand-drawn fills (hatching, cross-hatch, zigzag, dots) for rectangles and ellipses. Set your defaults in Settings. +- Smart select (W): hover to see an outline around the button, card or image under your pointer, then click to box it. Alt+click draws an ellipse instead; drag to draw a box yourself. +- Line styles: solid, dashed, dotted or sketchy (hand-drawn) for shapes, lines and arrows, in Capture and Screen Draw. Set your default in Settings. +- Rounded corners for rectangles, with a Corners slider and a default in Settings. +- Press any shape with a drawing tool to select and move it, without switching to the cursor. Hold Alt to draw on top of it instead. Escape deselects before it closes the capture. + +### Improved + +- Changing colour, size, line style, fill, corners or font now updates the shape you have selected. Smart select's outline is solid and glides from one element to the next. +- Text appears on the first click, shows a faint "Type something" hint, and clicking away leaves no empty box. Shift+Enter adds a new line, and it matches in the saved image. + ## 0.5.1 — 2026-11-20 ### Fixed diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8941b41..80fadf9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -31,6 +31,7 @@ "react": "^19.2.7", "react-dom": "^19.2.7", "react-konva": "^19.2.5", + "roughjs": "^4.6.6", "zod": "^4.4.3" }, "devDependencies": { diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index 7481513..f36d318 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -59,6 +59,86 @@ pub struct AnnotationScene { pub elements: Vec, } +/// Pre-computed outline of a styled (dashed, dotted, sketchy) or rounded shape. The frontend owns the +/// geometry so the canvas, Screen Draw and this exporter draw identical points. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StrokeGeometry { + /// Polylines to stroke at the annotation's stroke width. + #[serde(default)] + pub strokes: Vec>, + /// Dot centres; each is stamped as a disc as wide as the stroke. + #[serde(default)] + pub dots: Vec, + /// Closed polygon to fill with the annotation's fill colour. + #[serde(default)] + pub fill: Option>, + /// Hand-drawn pattern fill (hatching, zigzag) polylines, drawn under the outline at half weight. + #[serde(default)] + pub fill_strokes: Vec>, + /// Dot-pattern fill centres, drawn under the outline. + #[serde(default)] + pub fill_dots: Vec, +} + +/// Upper bound on geometry points in one scene, so a hostile or buggy request cannot exhaust memory. +pub const MAX_SCENE_GEOMETRY_POINTS: usize = 200_000; + +impl StrokeGeometry { + pub fn point_count(&self) -> usize { + self.strokes.iter().map(Vec::len).sum::() + + self.dots.len() + + self.fill_strokes.iter().map(Vec::len).sum::() + + self.fill_dots.len() + + self.fill.as_ref().map_or(0, Vec::len) + } + + /// Rejects non-finite coordinates and degenerate strokes. + pub fn validate(&self) -> Result<(), String> { + let finite = |point: &Point| point.x.is_finite() && point.y.is_finite(); + if self + .strokes + .iter() + .chain(self.fill_strokes.iter()) + .any(|stroke| stroke.len() < 2) + { + return Err("A stroke needs at least two points".into()); + } + let all_finite = self.strokes.iter().flatten().all(finite) + && self.dots.iter().all(finite) + && self.fill_strokes.iter().flatten().all(finite) + && self.fill_dots.iter().all(finite) + && self.fill.iter().flatten().all(finite); + if !all_finite { + return Err("Stroke geometry contains a non-finite coordinate".into()); + } + Ok(()) + } +} + +impl Annotation { + pub fn stroke_geometry(&self) -> Option<&StrokeGeometry> { + match self { + Self::Line { + stroke_geometry, .. + } + | Self::Arrow { + stroke_geometry, .. + } + | Self::CurvedArrow { + stroke_geometry, .. + } + | Self::Rectangle { + stroke_geometry, .. + } + | Self::Ellipse { + stroke_geometry, .. + } => stroke_geometry.as_ref(), + _ => None, + } + } +} + #[derive(Debug, Clone, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case")] // Scene fields remain explicit for versioned IPC fidelity even when a renderer does not yet use @@ -72,6 +152,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Arrow { id: String, @@ -80,6 +162,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, CurvedArrow { id: String, @@ -88,6 +172,8 @@ pub enum Annotation { color: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Highlighter { id: String, @@ -113,6 +199,8 @@ pub enum Annotation { fill: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Ellipse { id: String, @@ -122,6 +210,8 @@ pub enum Annotation { fill: String, #[serde(rename = "strokeWidth")] stroke_width: f32, + #[serde(default, rename = "strokeGeometry")] + stroke_geometry: Option, }, Spotlight { id: String, diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index 18ec1e2..2ca1f77 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -21,7 +21,7 @@ use image::{Rgba, RgbaImage, imageops}; use imageproc::{ drawing::{ draw_filled_circle_mut, draw_filled_rect_mut, draw_hollow_ellipse_mut, - draw_hollow_rect_mut, draw_line_segment_mut, draw_text_mut, + draw_hollow_rect_mut, draw_line_segment_mut, draw_polygon_mut, draw_text_mut, }, rect::Rect as ImageRect, }; @@ -31,9 +31,9 @@ use crate::{ domain::{ Annotation, AnnotationScene, CaptureSessionDto, ColorFormat, CompletionAction, CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, - PickColorRequest, PickedColorDto, Point, RecognizedTextDto, Rect, SavedCaptureDto, - ScrollingCaptureRequest, ScrollingCaptureResult, TextCopyResult, TextCopyStatus, - TextRecognitionRequest, + MAX_SCENE_GEOMETRY_POINTS, PickColorRequest, PickedColorDto, Point, RecognizedTextDto, + Rect, SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, StrokeGeometry, + TextCopyResult, TextCopyStatus, TextRecognitionRequest, }, error::SnaphubError, platform::{ @@ -1149,9 +1149,31 @@ fn validate_completion_request(request: &CompletionRequest) -> Result<(), Snaphu request.scene.version ))); } + validate_scene_geometry(&request.scene)?; validate_selection(request.selection) } +/// Checks the frontend-computed stroke geometry before any pixel is drawn. +fn validate_scene_geometry(scene: &AnnotationScene) -> Result<(), SnaphubError> { + let mut total = 0_usize; + for geometry in scene + .elements + .iter() + .filter_map(Annotation::stroke_geometry) + { + geometry.validate().map_err(|reason| { + SnaphubError::Export(format!("Invalid annotation geometry: {reason}")) + })?; + total = total.saturating_add(geometry.point_count()); + if total > MAX_SCENE_GEOMETRY_POINTS { + return Err(SnaphubError::Export( + "The annotations are too detailed to export. Simplify or remove some styled shapes.".into(), + )); + } + } + Ok(()) +} + fn validate_selection(selection: Rect) -> Result<(), SnaphubError> { if !selection.x.is_finite() || !selection.y.is_finite() @@ -1217,7 +1239,126 @@ fn render_output( Ok(output) } +/// Draws a styled or rounded shape from the frontend's geometry: fill, then strokes, then dots. +fn render_stroke_geometry( + canvas: &mut RgbaImage, + annotation: &Annotation, + geometry: &StrokeGeometry, + scale: f64, +) { + let (color, fill, stroke_width, opacity) = match annotation { + Annotation::Line { + color, + stroke_width, + opacity, + .. + } + | Annotation::Arrow { + color, + stroke_width, + opacity, + .. + } + | Annotation::CurvedArrow { + color, + stroke_width, + opacity, + .. + } => (color, None, *stroke_width, *opacity), + Annotation::Rectangle { + color, + fill, + stroke_width, + opacity, + .. + } + | Annotation::Ellipse { + color, + fill, + stroke_width, + opacity, + .. + } => (color, Some(fill), *stroke_width, *opacity), + _ => return, + }; + if let (Some(fill), Some(polygon)) = (fill, geometry.fill.as_ref()) + && fill != "transparent" + { + fill_polygon(canvas, polygon, scale, parse_color(fill, opacity)); + } + // Pattern fills sit under the outline: current colour at 35% opacity, half the outline weight. + if !geometry.fill_strokes.is_empty() || !geometry.fill_dots.is_empty() { + let pattern_pixel = parse_color(color, opacity * 0.35); + let pattern_width = (stroke_width / 2.0).max(1.0); + for stroke in &geometry.fill_strokes { + for pair in stroke.windows(2) { + draw_thick_line( + canvas, + pair[0], + pair[1], + pattern_width, + scale, + pattern_pixel, + ); + } + } + let pattern_radius = non_negative_i32(f64::from(pattern_width) * scale / 2.0).max(1); + for dot in &geometry.fill_dots { + draw_filled_circle_mut( + canvas, + ( + non_negative_i32(dot.x * scale), + non_negative_i32(dot.y * scale), + ), + pattern_radius, + pattern_pixel, + ); + } + } + let pixel = parse_color(color, opacity); + for stroke in &geometry.strokes { + for pair in stroke.windows(2) { + draw_thick_line(canvas, pair[0], pair[1], stroke_width, scale, pixel); + } + } + let radius = non_negative_i32(f64::from(stroke_width) * scale / 2.0).max(1); + for dot in &geometry.dots { + draw_filled_circle_mut( + canvas, + ( + non_negative_i32(dot.x * scale), + non_negative_i32(dot.y * scale), + ), + radius, + pixel, + ); + } +} + +fn fill_polygon(canvas: &mut RgbaImage, polygon: &[Point], scale: f64, pixel: Rgba) { + let mut points: Vec> = polygon + .iter() + .map(|point| { + imageproc::point::Point::new( + (point.x * scale).round() as i32, + (point.y * scale).round() as i32, + ) + }) + .collect(); + points.dedup(); + while points.len() > 1 && points.first() == points.last() { + points.pop(); + } + if points.len() >= 3 { + draw_polygon_mut(canvas, &points, pixel); + } +} + fn render_annotation(canvas: &mut RgbaImage, annotation: &Annotation, scale: f64) { + if let Some(geometry) = annotation.stroke_geometry() { + render_stroke_geometry(canvas, annotation, geometry, scale); + return; + } match annotation { Annotation::Line { points, @@ -1367,20 +1508,32 @@ fn render_annotation(canvas: &mut RgbaImage, annotation: &Annotation, scale: f64 .. } => { if let Some(font) = system_font(font_family) { - draw_text_mut( - canvas, - parse_color(color, *opacity), - non_negative_i32(position.x * scale), - non_negative_i32(position.y * scale), - (f64::from(*font_size) * scale) as f32, - &font, - text, - ); + let color = parse_color(color, *opacity); + let pixel_size = (f64::from(*font_size) * scale) as f32; + for (index, line) in text.split('\n').enumerate() { + draw_text_mut( + canvas, + color, + non_negative_i32(position.x * scale), + non_negative_i32(position.y * scale + text_line_offset(pixel_size, index)), + pixel_size, + &font, + line, + ); + } } } } } +/// Line height multiple shared with the TypeScript canvas (`TEXT_LINE_HEIGHT`). +const TEXT_LINE_HEIGHT: f32 = 1.2; + +/// Vertical offset in output pixels of the zero-based text line `index`. +fn text_line_offset(pixel_size: f32, index: usize) -> f64 { + f64::from(pixel_size * TEXT_LINE_HEIGHT) * index as f64 +} + fn draw_thick_line( canvas: &mut RgbaImage, start: Point, @@ -2820,4 +2973,113 @@ mod tests { assert_eq!(png_files(&directory.0).len(), 2); assert!(!has_partial_file(&directory.0)); } + + fn annotation_from_json(raw: &str) -> Annotation { + serde_json::from_str(raw).expect("annotation JSON should parse") + } + + fn scene_with(raw_elements: &[&str]) -> AnnotationScene { + AnnotationScene { + version: 1, + elements: raw_elements + .iter() + .map(|raw| annotation_from_json(raw)) + .collect(), + } + } + + const DASHED_RECT: &str = r##"{"id":"a","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":80,"height":40},"color":"#ff0000","fill":"transparent","strokeWidth":2,"strokeStyle":"dashed","strokeGeometry":{"strokes":[[{"x":10,"y":10},{"x":16,"y":10}],[{"x":20,"y":10},{"x":26,"y":10}]],"dots":[]}}"##; + + #[test] + fn multi_line_text_steps_down_by_the_shared_line_height() { + assert_eq!(text_line_offset(20.0, 0), 0.0); + assert!((text_line_offset(20.0, 1) - 24.0).abs() < 1e-6); + assert!((text_line_offset(20.0, 2) - 48.0).abs() < 1e-6); + assert_eq!("one\ntwo".split('\n').count(), 2); + } + + #[test] + fn dashed_geometry_leaves_gaps_between_dashes() { + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(DASHED_RECT), 1.0); + assert_eq!(canvas.get_pixel(13, 10).0[..3], [255, 0, 0]); + assert_eq!(canvas.get_pixel(23, 10).0[..3], [255, 0, 0]); + assert_eq!(canvas.get_pixel(18, 10).0[..3], [255, 255, 255]); + assert_eq!(canvas.get_pixel(50, 50).0[..3], [255, 255, 255]); + } + + #[test] + fn dotted_geometry_stamps_discs() { + let raw = r##"{"id":"d","kind":"line","opacity":1,"points":[{"x":10,"y":10},{"x":60,"y":10}],"color":"#00ff00","strokeWidth":6,"strokeStyle":"dotted","strokeGeometry":{"strokes":[],"dots":[{"x":20,"y":20},{"x":40,"y":20}]}}"##; + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(raw), 1.0); + assert_eq!(canvas.get_pixel(20, 20).0[..3], [0, 255, 0]); + assert_eq!(canvas.get_pixel(30, 20).0[..3], [255, 255, 255]); + assert_eq!(canvas.get_pixel(20, 10).0[..3], [255, 255, 255]); + } + + #[test] + fn rounded_geometry_cuts_the_corner_and_fills_the_inside() { + let raw = r##"{"id":"r","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":60,"height":40},"color":"#0000ff","fill":"#00ff00","strokeWidth":2,"cornerRadius":16,"strokeGeometry":{"strokes":[[{"x":26,"y":10},{"x":54,"y":10},{"x":70,"y":26},{"x":70,"y":34},{"x":54,"y":50},{"x":26,"y":50},{"x":10,"y":34},{"x":10,"y":26},{"x":26,"y":10}]],"dots":[],"fill":[{"x":26,"y":10},{"x":54,"y":10},{"x":70,"y":26},{"x":70,"y":34},{"x":54,"y":50},{"x":26,"y":50},{"x":10,"y":34},{"x":10,"y":26},{"x":26,"y":10}]}}"##; + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(raw), 1.0); + assert_eq!(canvas.get_pixel(40, 30).0[..3], [0, 255, 0]); + assert_eq!(canvas.get_pixel(11, 11).0[..3], [255, 255, 255]); + } + + #[test] + fn hachure_fill_tints_pixels_under_the_outline_and_leaves_gaps() { + let raw = r##"{"id":"h","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":60,"height":40},"color":"#0000ff","fill":"transparent","strokeWidth":4,"fillStyle":"hachure","strokeGeometry":{"strokes":[[{"x":10,"y":10},{"x":70,"y":10},{"x":70,"y":50},{"x":10,"y":50},{"x":10,"y":10}]],"dots":[],"fillStrokes":[[{"x":20,"y":20},{"x":40,"y":20}]],"fillDots":[{"x":60,"y":40}]}}"##; + let mut canvas = RgbaImage::from_pixel(100, 80, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation_from_json(raw), 1.0); + let tinted = canvas.get_pixel(30, 20).0; + assert!( + tinted[0] < 255 && tinted[2] == 255, + "pattern is a light tint of the colour: {tinted:?}" + ); + assert!(canvas.get_pixel(60, 40).0[0] < 255); + assert_eq!(canvas.get_pixel(30, 35).0[..3], [255, 255, 255]); + assert_eq!(canvas.get_pixel(40, 10).0[..3], [0, 0, 255]); + } + + #[test] + fn scene_without_geometry_still_parses_and_renders_the_old_way() { + let raw = r##"{"id":"o","kind":"rectangle","opacity":1,"bounds":{"x":10,"y":10,"width":30,"height":20},"color":"#ff0000","fill":"transparent","strokeWidth":2}"##; + let annotation = annotation_from_json(raw); + assert!(annotation.stroke_geometry().is_none()); + let mut canvas = RgbaImage::from_pixel(60, 60, Rgba([255, 255, 255, 255])); + render_annotation(&mut canvas, &annotation, 1.0); + assert_eq!(canvas.get_pixel(10, 15).0[..3], [255, 0, 0]); + } + + #[test] + fn geometry_validation_accepts_normal_and_rejects_bad_input() { + assert!(validate_scene_geometry(&scene_with(&[DASHED_RECT])).is_ok()); + + let single_point = r##"{"id":"x","kind":"line","opacity":1,"points":[{"x":0,"y":0},{"x":1,"y":1}],"color":"#ffffff","strokeWidth":2,"strokeGeometry":{"strokes":[[{"x":0,"y":0}]],"dots":[]}}"##; + assert!(validate_scene_geometry(&scene_with(&[single_point])).is_err()); + + let mut scene = scene_with(&[DASHED_RECT]); + if let Annotation::Rectangle { + stroke_geometry: Some(geometry), + .. + } = &mut scene.elements[0] + { + geometry.strokes[0][0].x = f64::NAN; + } + assert!(validate_scene_geometry(&scene).is_err()); + } + + #[test] + fn geometry_validation_caps_total_points() { + let mut scene = scene_with(&[DASHED_RECT]); + if let Annotation::Rectangle { + stroke_geometry: Some(geometry), + .. + } = &mut scene.elements[0] + { + geometry.dots = vec![Point { x: 1.0, y: 1.0 }; MAX_SCENE_GEOMETRY_POINTS + 1]; + } + assert!(validate_scene_geometry(&scene).is_err()); + } } diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 2941fe0..dd92430 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -502,11 +502,11 @@ describe("App", () => { ); expect(screen.getByText("440 × 300 px")).toBeInTheDocument(); - const shapeFamily = screen.getByRole("button", { name: "Rectangle group" }); + const shapeFamily = screen.getByRole("button", { name: "Smart select group" }); fireEvent.pointerDown(shapeFamily, { button: 0, pointerId: 2 }); fireEvent.click(shapeFamily); expect(shapeFamily).toHaveAttribute("aria-pressed", "true"); - expect(screen.getByRole("button", { name: "Rectangle" })).toHaveAttribute( + expect(screen.getByRole("button", { name: "Smart select" })).toHaveAttribute( "aria-pressed", "true", ); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 420036b..6552e51 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -55,6 +55,7 @@ import { captureCursor } from "./lib/cursor"; import { prefersReducedMotion } from "./lib/motion"; import { eyedropperFormat } from "./lib/eyedropper"; import { suggestRedactions, suggestRedactionsFromWeb } from "./lib/redactionPatterns"; +import { useSmartSelect } from "./lib/useSmartSelect"; import { createVisualTargetDetector, type VisualTargetDetector } from "./lib/visualTargets"; import { cancelCapture, @@ -120,6 +121,9 @@ export function App(): React.JSX.Element { const [history, dispatchScene] = useReducer(sceneHistoryReducer, initialSceneHistory); const [notes, dispatchNotes] = useReducer(notesReducer, []); const [editingNoteId, setEditingNoteId] = useState(null); + /** Escape deselects a selected annotation before it exits the capture. */ + const annotationSelectedRef = useRef(false); + const [deselectToken, setDeselectToken] = useState(0); const [pinDrag, setPinDrag] = useState<{ counterId: string; position: Point } | null>(null); const [lookups, setLookups] = useState>>({}); const [developerTools, setDeveloperTools] = useState(false); @@ -139,6 +143,13 @@ export function App(): React.JSX.Element { const [targets, setTargets] = useState([]); const [isDraftingSelection, setIsDraftingSelection] = useState(false); const [message, setMessage] = useState("Hover to preview targets / drag to draw a rectangle / I copies a colour"); + const smartSelect = useSmartSelect({ + session, + selection, + active: activeTool === "smart", + uiRegions: settings.detection.uiRegions, + windows: settings.detection.windows, + }); const [scrollingCapture, setScrollingCapture] = useState(null); // The swatch shows only while its message is still the current one. const [pickedSwatch, setPickedSwatch] = useState<{ hex: string; message: string } | null>(null); @@ -282,6 +293,10 @@ export function App(): React.JSX.Element { ...defaultAnnotationStyle, color: settingsRef.current.annotation.defaultColor, strokeWidth: settingsRef.current.annotation.defaultSize, + strokeStyle: settingsRef.current.annotation.strokeStyle, + cornerRadius: settingsRef.current.annotation.cornerRadius, + sketchLevel: settingsRef.current.annotation.sketchLevel, + fillStyle: settingsRef.current.annotation.fillStyle, }); dispatchScene({ type: "reset" }); dispatchNotes({ type: "reset" }); @@ -1160,8 +1175,14 @@ export function App(): React.JSX.Element { if (event.key === "Escape") { // The note popover owns Esc while it is open. if (editingNoteId !== null) return; + // The canvas text editor owns Esc while it is open: it commits and keeps the tool active. + if (event.target instanceof Element && event.target.closest("[data-text-editor]") !== null) return; event.preventDefault(); event.stopPropagation(); + if (annotationSelectedRef.current) { + setDeselectToken((token) => token + 1); + return; + } if (scrollingCapture !== null) { void closeScrollingCapture(); return; @@ -1316,7 +1337,7 @@ export function App(): React.JSX.Element { id: `tool-${toolId}`, label: tool.label, icon: tool.icon, - ...(tool.shortcut === undefined ? {} : { shortcut: tool.shortcut }), + ...((settings.toolbar.keys[toolId] ?? tool.shortcut) === undefined ? {} : { shortcut: settings.toolbar.keys[toolId] ?? tool.shortcut }), active: tool.annotationTool !== undefined && tool.annotationTool === activeTool, disabled: toolId === "undo" ? history.past.length === 0 : toolId === "redo" ? history.future.length === 0 : false, onSelect: () => runToolbarTool(toolId, { @@ -1386,6 +1407,14 @@ export function App(): React.JSX.Element { onResizeStart={handleResizeStart} > setMessage("Nothing to snap to here. Drag to draw a box instead.")} + onSelectionActiveChange={(active) => { + annotationSelectedRef.current = active; + }} activeTool={activeTool} bounds={selection} cursor={activeCaptureCursor} @@ -1402,6 +1431,7 @@ export function App(): React.JSX.Element { }} onDelete={(annotationId) => dispatchScene({ type: "delete", annotationId })} onUpdate={(annotation) => dispatchScene({ type: "update", annotation })} + onRestyle={(annotation, coalesceKey) => dispatchScene({ type: "update", annotation, coalesceKey })} /> {activeNotes.filter((note) => note.id === editingNoteId).map((note) => ( { expect(onDelete).toHaveBeenCalledWith("text-1"); }); - it("commits the active text before creating a new placeholder", () => { + it("commits the active text on click away without creating another box", () => { const textScene: AnnotationScene = { version: 1, elements: [{ @@ -150,7 +150,74 @@ describe("AnnotationCanvas effect previews", () => { fireEvent.pointerDown(screen.getByRole("application", { name: "Screenshot annotation canvas" }), { button: 0, clientX: 220, clientY: 180, pointerId: 4 }); expect(onUpdate).toHaveBeenCalledWith(expect.objectContaining({ id: "text-1", text: "Keep this edit" })); - expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "text", text: "Type something" })); + expect(onCommit).not.toHaveBeenCalled(); + }); + + describe("text creation", () => { + function renderText(overrides: Partial> = {}): { + onCommit: ReturnType; + onDelete: ReturnType; + canvas: HTMLElement; + } { + const onCommit = vi.fn(); + const onDelete = vi.fn(); + render( + undefined} + {...overrides} + />, + ); + return { onCommit, onDelete, canvas: screen.getByRole("application", { name: "Screenshot annotation canvas" }) }; + } + + it("opens an editor with a placeholder on one click and stores nothing yet", () => { + const { onCommit, canvas } = renderText(); + fireEvent.pointerDown(canvas, { button: 0, clientX: 50, clientY: 60, pointerId: 1 }); + const editor = screen.getByRole("textbox", { name: "Edit annotation text" }); + expect(editor).toHaveAttribute("placeholder", "Type something"); + expect(editor).toHaveValue(""); + expect(onCommit).not.toHaveBeenCalled(); + }); + + it("drops empty or whitespace-only text without an undo entry", () => { + const { onCommit, onDelete, canvas } = renderText(); + fireEvent.pointerDown(canvas, { button: 0, clientX: 50, clientY: 60, pointerId: 1 }); + fireEvent.change(screen.getByRole("textbox", { name: "Edit annotation text" }), { target: { value: " " } }); + fireEvent.pointerDown(canvas, { button: 0, clientX: 200, clientY: 200, pointerId: 2 }); + expect(onCommit).not.toHaveBeenCalled(); + expect(onDelete).not.toHaveBeenCalled(); + expect(screen.queryByRole("textbox", { name: "Edit annotation text" })).toBeNull(); + }); + + it("commits typed text on Enter, and Shift+Enter keeps editing", () => { + const { onCommit, canvas } = renderText(); + fireEvent.pointerDown(canvas, { button: 0, clientX: 50, clientY: 60, pointerId: 1 }); + const editor = screen.getByRole("textbox", { name: "Edit annotation text" }); + fireEvent.change(editor, { target: { value: "one\ntwo" } }); + fireEvent.keyDown(editor, { key: "Enter", shiftKey: true }); + expect(onCommit).not.toHaveBeenCalled(); + fireEvent.keyDown(editor, { key: "Enter" }); + expect(onCommit).toHaveBeenCalledTimes(1); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "text", text: "one\ntwo" })); + }); + + it("commits on Escape and returns focus to the canvas", () => { + const { onCommit, canvas } = renderText(); + fireEvent.pointerDown(canvas, { button: 0, clientX: 50, clientY: 60, pointerId: 1 }); + const editor = screen.getByRole("textbox", { name: "Edit annotation text" }); + fireEvent.change(editor, { target: { value: "hello" } }); + fireEvent.keyDown(editor, { key: "Escape" }); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ text: "hello" })); + expect(canvas).toHaveFocus(); + }); }); it("opens a note pin from Select without moving focus off the comment", () => { @@ -278,4 +345,139 @@ describe("AnnotationCanvas effect previews", () => { fireEvent.keyDown(screen.getByRole("button", { name: "Resize rectangle annotation from the right edge" }), { key: "ArrowRight", shiftKey: true }); expect(onUpdate).toHaveBeenLastCalledWith(expect.objectContaining({ bounds: { x: 20, y: 30, width: 90, height: 50 } })); }); + describe("editing without switching tools", () => { + const frame = { + id: "frame-1", + kind: "rectangle" as const, + bounds: { x: 20, y: 30, width: 200, height: 120 }, + color: "#d9ff43", + fill: "transparent", + strokeWidth: 4, + opacity: 1, + }; + + function renderRectangleTool(): { onCommit: ReturnType; onUpdate: ReturnType; canvas: HTMLElement } { + const onCommit = vi.fn(); + const onUpdate = vi.fn(); + render( + undefined} + onUpdate={onUpdate} + />, + ); + return { onCommit, onUpdate, canvas: screen.getByRole("application", { name: "Screenshot annotation canvas" }) }; + } + + it("moves a rectangle grabbed by its border in one update", () => { + const { onCommit, onUpdate, canvas } = renderRectangleTool(); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 20, clientY: 90, pointerId: 1 }); + fireEvent.pointerMove(canvas, { buttons: 1, clientX: 40, clientY: 90, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 40, clientY: 90, pointerId: 1 }); + expect(onUpdate).toHaveBeenCalledTimes(1); + expect(onUpdate).toHaveBeenCalledWith(expect.objectContaining({ id: "frame-1", bounds: { x: 40, y: 30, width: 200, height: 120 } })); + expect(onCommit).not.toHaveBeenCalled(); + }); + + it("selects without an update when the press never leaves the 3 px slop", () => { + const { onUpdate, canvas } = renderRectangleTool(); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 20, clientY: 90, pointerId: 1 }); + fireEvent.pointerMove(canvas, { buttons: 1, clientX: 22, clientY: 91, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 22, clientY: 91, pointerId: 1 }); + expect(onUpdate).not.toHaveBeenCalled(); + expect(screen.getByLabelText("Selected rectangle annotation")).toBeInTheDocument(); + }); + + it("draws a new rectangle when Alt is held over the border", () => { + const { onCommit, onUpdate, canvas } = renderRectangleTool(); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, altKey: true, clientX: 20, clientY: 90, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, altKey: true, clientX: 80, clientY: 130, pointerId: 1 }); + expect(onUpdate).not.toHaveBeenCalled(); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "rectangle" })); + }); + + it("draws inside an unfilled rectangle instead of selecting it", () => { + const { onCommit, onUpdate, canvas } = renderRectangleTool(); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 100, clientY: 90, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 160, clientY: 130, pointerId: 1 }); + expect(onUpdate).not.toHaveBeenCalled(); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "rectangle" })); + }); + }); + + describe("smart select", () => { + function renderSmart(smartTarget: { x: number; y: number; width: number; height: number } | null): { + onCommit: ReturnType; + onSmartMiss: ReturnType; + onSmartHover: ReturnType; + canvas: HTMLElement; + } { + const onCommit = vi.fn(); + const onSmartMiss = vi.fn(); + const onSmartHover = vi.fn(); + render( + undefined} + onSmartHover={onSmartHover} + onSmartMiss={onSmartMiss} + onUpdate={() => undefined} + />, + ); + return { onCommit, onSmartMiss, onSmartHover, canvas: screen.getByRole("application", { name: "Screenshot annotation canvas" }) }; + } + + const target = { x: 50, y: 60, width: 100, height: 40 }; + + it("shows a ghost outline and reports the hovered point", () => { + const { canvas, onSmartHover } = renderSmart(target); + expect(screen.getByTestId("smart-ghost")).toBeInTheDocument(); + fireEvent.pointerMove(canvas, { buttons: 0, clientX: 70, clientY: 70, pointerId: 1 }); + expect(onSmartHover).toHaveBeenCalledWith({ x: 70, y: 70 }); + }); + + it("a click adds a padded rectangle around the target", () => { + const { canvas, onCommit } = renderSmart(target); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 70, clientY: 70, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 70, clientY: 70, pointerId: 1 }); + expect(onCommit).toHaveBeenCalledTimes(1); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "rectangle", bounds: { x: 46, y: 56, width: 108, height: 48 } })); + }); + + it("Alt+click adds an ellipse that circumscribes the target", () => { + const { canvas, onCommit } = renderSmart(target); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, altKey: true, clientX: 70, clientY: 70, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, altKey: true, clientX: 70, clientY: 70, pointerId: 1 }); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "ellipse" })); + }); + + it("a drag draws a plain rectangle instead of snapping", () => { + const { canvas, onCommit } = renderSmart(target); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 200, clientY: 150, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 260, clientY: 200, pointerId: 1 }); + expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "rectangle", bounds: { x: 200, y: 150, width: 60, height: 50 } })); + }); + + it("reports a miss when there is nothing to snap to", () => { + const { canvas, onCommit, onSmartMiss } = renderSmart(null); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 70, clientY: 70, pointerId: 1 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 70, clientY: 70, pointerId: 1 }); + expect(onCommit).not.toHaveBeenCalled(); + expect(onSmartMiss).toHaveBeenCalledTimes(1); + }); + }); }); diff --git a/apps/desktop/src/components/AnnotationCanvas.tsx b/apps/desktop/src/components/AnnotationCanvas.tsx index 669c45f..640dddb 100644 --- a/apps/desktop/src/components/AnnotationCanvas.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.tsx @@ -1,5 +1,7 @@ +import { changedStyleKeys, restyleAnnotation } from "../domain/restyle"; import { memo, useEffect, useMemo, useRef, useState } from "react"; -import { Arrow, Circle, Ellipse, Group, Layer, Line, Rect, Stage, Text } from "react-konva"; +import { measureTextBlock, TEXT_LINE_HEIGHT } from "../domain/textMetrics"; +import { Arrow, Circle, Ellipse, Group, Layer, Line, Rect, Shape, Stage, Text } from "react-konva"; import type { Annotation, AnnotationScene, @@ -11,11 +13,22 @@ import type { import { annotationBounds, findAnnotationAtPoint, + findEditableAnnotationAt, isResizableAnnotation, resizeAnnotation, translateAnnotation, } from "../domain/annotationGeometry"; +import { smartAnnotationBounds } from "../domain/smartSelect"; import { Cancel } from "./icons"; +import { + FILL_PATTERN_OPACITY, + effectiveFillStyle, + fillPatternWeight, + needsStrokeGeometry, + newSketchSeed, + shapeStrokeGeometry, + type StrokeGeometryInput, +} from "../domain/strokeGeometry"; import type { Point, Rect as CaptureRect } from "../domain/capture"; import { normalizeRect, type ResizeHandle } from "../lib/geometry"; @@ -57,6 +70,8 @@ type AnnotationCanvasProps = { cursor: string; onCommit: (annotation: Annotation) => void; onUpdate: (annotation: Annotation) => void; + /** A strip change restyled the selected annotation; the key lets a slider drag collapse into one undo step. */ + onRestyle?: (annotation: Annotation, coalesceKey: string) => void; onDelete: (annotationId: string) => void; /** Pin colour for the Note tool (the accent colour). */ noteColor?: string; @@ -66,8 +81,39 @@ type AnnotationCanvasProps = { onPinSelect?: (annotationId: string) => void; /** A pin's live position while Select drags it, then null on release, so its comment can follow. */ onPinDrag?: (annotationId: string, position: Point | null) => void; + /** Reports whether an annotation is selected, so Escape can deselect before it exits the capture. */ + onSelectionActiveChange?: (active: boolean) => void; + /** Bump to deselect the current annotation (the app's Escape handler). */ + deselectToken?: number; + /** Smart select: the detected box under the pointer, in canvas coordinates. */ + smartTarget?: CaptureRect | null; + /** Changes only when the Smart select candidate does; restarts the ghost fade-in. */ + smartTargetId?: string | null; + onSmartHover?: (point: Point | null) => void; + /** A Smart select click found nothing to snap to. */ + onSmartMiss?: () => void; }; +/** Drawing tools that still let a press on an existing annotation select and move it. */ +const EDIT_IN_TOOL_TOOLS: readonly ToolId[] = [ + "arrow", + "curved-arrow", + "line", + "rectangle", + "smart", + "ellipse", + "highlighter", + "pencil", + "spotlight", + "counter", + "blur", + "pixelate", + "blackout", +]; + +/** A press must travel further than this (px) before it moves the annotation instead of just selecting it. */ +const DRAG_SLOP = 3; + /** A press that moves less than this (px) places a point note; further drags an area note. */ const noteAreaThreshold = 6; @@ -82,11 +128,18 @@ export function AnnotationCanvas({ cursor, onCommit, onUpdate, + onRestyle, onDelete, noteColor = "#d9ff43", onNotePlace, onPinSelect, onPinDrag, + onSelectionActiveChange, + deselectToken = 0, + smartTarget = null, + smartTargetId = null, + onSmartHover, + onSmartMiss, }: AnnotationCanvasProps): React.JSX.Element { const containerRef = useRef(null); const [draft, setDraft] = useState(null); @@ -95,12 +148,42 @@ export function AnnotationCanvas({ const [movingAnnotation, setMovingAnnotation] = useState<{ initial: Annotation; current: Annotation } | null>(null); const [editingTextId, setEditingTextId] = useState(null); const [editingValue, setEditingValue] = useState(""); + /** A text box created by a click but not yet committed; it enters the scene (and undo) only with content. */ + const [pendingText, setPendingText] = useState(null); const editingTextIdRef = useRef(null); + const finishEditRef = useRef<() => void>(() => undefined); const editingValueRef = useRef(""); const draftRef = useRef(null); const draftFrameRequest = useRef(null); // `handle` is null while moving and names the dragged handle while resizing. - const movingAnnotationRef = useRef<{ initial: Annotation; current: Annotation; start: Point; handle: ResizeHandle | null } | null>(null); + // `slop` is set when a drawing tool picked the annotation up: nothing moves until the press travels past it. + const movingAnnotationRef = useRef<{ initial: Annotation; current: Annotation; start: Point; handle: ResizeHandle | null; slop?: number; engaged?: boolean } | null>(null); + const [hoveredAnnotationId, setHoveredAnnotationId] = useState(null); + const hoverFrameRequest = useRef(null); + const hoverPointRef = useRef(null); + const previousStyleRef = useRef(style); + const sceneRef = useRef(scene); + sceneRef.current = scene; + const selectedAnnotationIdRef = useRef(selectedAnnotationId); + selectedAnnotationIdRef.current = selectedAnnotationId; + const onRestyleRef = useRef(onRestyle ?? ((annotation: Annotation): void => onUpdate(annotation))); + onRestyleRef.current = onRestyle ?? ((annotation: Annotation): void => onUpdate(annotation)); + + // Changing the strip while a drawn annotation is selected restyles it, not just the next one drawn. + useEffect(() => { + const keys = changedStyleKeys(previousStyleRef.current, style); + previousStyleRef.current = style; + const selectedId = selectedAnnotationIdRef.current; + if (keys.length === 0 || selectedId === null) return; + const target = sceneRef.current.elements.find((element) => element.id === selectedId); + if (target === undefined) return; + const restyled = restyleAnnotation(target, style, keys); + if (restyled !== null) onRestyleRef.current(restyled, `${selectedId}:${keys.join(",")}`); + }, [style]); + + const editInTool = EDIT_IN_TOOL_TOOLS.includes(activeTool); + // Smart select draws a plain rectangle when dragged; a click snaps to the detected box instead. + const drawTool: ToolId = activeTool === "smart" ? "rectangle" : activeTool; const displayedElements = useMemo(() => { if (movingAnnotation === null) return scene.elements; @@ -121,8 +204,8 @@ export function AnnotationCanvas({ opacity: 1, }; } - return createAnnotation(activeTool, draft.start, draft.end, style, scene, draft.id, draft.points); - }, [activeTool, draft, noteColor, scene, style]); + return createAnnotation(drawTool, draft.start, draft.end, style, scene, draft.id, draft.points); + }, [drawTool, activeTool, draft, noteColor, scene, style]); function relativePoint(event: React.PointerEvent): Point { const host = containerRef.current?.getBoundingClientRect(); @@ -139,6 +222,18 @@ export function AnnotationCanvas({ }); } + /** Hit-tests at most once per animation frame while the pointer hovers with a drawing tool active. */ + function scheduleHover(point: Point, altHeld: boolean): void { + hoverPointRef.current = altHeld ? null : point; + if (hoverFrameRequest.current !== null) return; + hoverFrameRequest.current = window.requestAnimationFrame((): void => { + hoverFrameRequest.current = null; + const target = hoverPointRef.current; + const hit = target === null ? undefined : findEditableAnnotationAt(scene.elements, target); + setHoveredAnnotationId(hit?.id ?? null); + }); + } + function clearDraftFrame(): void { if (draftFrameRequest.current !== null) { window.cancelAnimationFrame(draftFrameRequest.current); @@ -172,24 +267,42 @@ export function AnnotationCanvas({ if ("setPointerCapture" in event.currentTarget) { event.currentTarget.setPointerCapture(event.pointerId); } + if (editInTool && !event.altKey) { + const hit = findEditableAnnotationAt(scene.elements, point); + if (hit !== undefined) { + finishActiveTextEdit(); + setHoveredAnnotationId(null); + setSelectedAnnotationId(hit.id); + setSelectedTextId(hit.kind === "text" ? hit.id : null); + if (hit.kind === "counter" && onPinSelect !== undefined) { + event.preventDefault(); + onPinSelect(hit.id); + } + movingAnnotationRef.current = { initial: hit, current: hit, start: point, handle: null, slop: DRAG_SLOP, engaged: false }; + setMovingAnnotation({ initial: hit, current: hit }); + return; + } + } + if (activeTool === "text" && editingTextIdRef.current !== null) { + // Clicking away only commits; it never starts a second box. + finishActiveTextEdit(); + return; + } if (activeTool === "counter" || activeTool === "text") { - if (activeTool === "text") finishActiveTextEdit(); const annotation = createAnnotation(activeTool, point, point, style, scene); - if (annotation !== null) { + if (annotation === null) return; + if (annotation.kind === "text") { + setPendingText(annotation); + setSelectedTextId(null); + beginTextEdit(annotation, ""); + } else { onCommit(annotation); - if (annotation.kind === "text") { - setSelectedTextId(annotation.id); - setSelectedAnnotationId(annotation.id); - setEditingTextId(null); - editingTextIdRef.current = null; - } } return; } + finishActiveTextEdit(); setSelectedTextId(null); setSelectedAnnotationId(null); - setEditingTextId(null); - editingTextIdRef.current = null; const nextDraft = { id: crypto.randomUUID(), start: point, end: point, points: [point] }; draftRef.current = nextDraft; setDraft(nextDraft); @@ -220,6 +333,10 @@ export function AnnotationCanvas({ const point = relativePoint(event); const dx = point.x - moving.start.x; const dy = point.y - moving.start.y; + if (moving.slop !== undefined && moving.engaged !== true) { + if (Math.hypot(dx, dy) <= moving.slop) return; + moving.engaged = true; + } const current = moving.handle === null ? translateAnnotation(moving.initial, dx, dy) : resizeAnnotation(moving.initial, moving.handle, dx, dy); @@ -229,7 +346,11 @@ export function AnnotationCanvas({ return; } const current = draftRef.current; - if (current === null) return; + if (current === null) { + if (editInTool && event.buttons === 0) scheduleHover(relativePoint(event), event.altKey); + if (activeTool === "smart" && event.buttons === 0) onSmartHover?.(relativePoint(event)); + return; + } if ((event.buttons & 1) === 0) { handlePointerUp(event); return; @@ -248,7 +369,9 @@ export function AnnotationCanvas({ const moving = movingAnnotationRef.current; if (moving !== null) { event.stopPropagation(); - onUpdate(moving.current); + // A drawing-tool press that never left the slop only selected the annotation. + const wasClick = moving.slop !== undefined && moving.engaged !== true; + if (!wasClick) onUpdate(moving.current); if (moving.current.kind === "counter") onPinDrag?.(moving.current.id, null); movingAnnotationRef.current = null; setMovingAnnotation(null); @@ -283,8 +406,27 @@ export function AnnotationCanvas({ ); return; } + const releasePoint = relativePoint(event); + if (activeTool === "smart" && Math.hypot(releasePoint.x - current.start.x, releasePoint.y - current.start.y) <= DRAG_SLOP) { + draftRef.current = null; + setDraft(null); + if (smartTarget === null) { + onSmartMiss?.(); + return; + } + const box = smartAnnotationBounds(smartTarget, { width: bounds.width, height: bounds.height }, event.altKey); + const snapped = createAnnotation( + event.altKey ? "ellipse" : "rectangle", + { x: box.x, y: box.y }, + { x: box.x + box.width, y: box.y + box.height }, + style, + scene, + ); + if (snapped !== null) onCommit(snapped); + return; + } const annotation = createAnnotation( - activeTool, + drawTool, current.start, relativePoint(event), style, @@ -297,13 +439,32 @@ export function AnnotationCanvas({ if (annotation !== null) onCommit(annotation); } - useEffect(() => (): void => clearDraftFrame(), []); + useEffect( + () => (): void => { + clearDraftFrame(); + if (hoverFrameRequest.current !== null) window.cancelAnimationFrame(hoverFrameRequest.current); + }, + [], + ); + + useEffect(() => { + setHoveredAnnotationId(null); + }, [activeTool]); + + useEffect(() => { + onSelectionActiveChange?.(selectedAnnotationId !== null); + }, [onSelectionActiveChange, selectedAnnotationId]); + + useEffect(() => { + if (deselectToken === 0) return; + setSelectedAnnotationId(null); + setSelectedTextId(null); + }, [deselectToken]); useEffect(() => { if (activeTool !== "text") { + finishEditRef.current(); setSelectedTextId(null); - setEditingTextId(null); - editingTextIdRef.current = null; } }, [activeTool]); @@ -323,46 +484,72 @@ export function AnnotationCanvas({ function selectText(annotation: Extract): void { setSelectedAnnotationId(annotation.id); if (selectedTextId === annotation.id) { - setEditingTextId(annotation.id); - editingTextIdRef.current = annotation.id; - const initialValue = annotation.text === "Type something" ? "" : annotation.text; - editingValueRef.current = initialValue; - setEditingValue(initialValue); + beginTextEdit(annotation, annotation.text); return; } setSelectedTextId(annotation.id); setEditingTextId(null); } - function commitTextEdit(annotation: Extract): void { + function beginTextEdit(annotation: TextAnnotation, initialValue: string): void { + setSelectedAnnotationId(annotation.id); + setEditingTextId(annotation.id); + editingTextIdRef.current = annotation.id; + editingValueRef.current = initialValue; + setEditingValue(initialValue); + } + + /** Commits the open edit: empty text is dropped (no undo entry for a new box), otherwise it is saved. */ + function commitTextEdit(annotation: TextAnnotation): void { if (editingTextIdRef.current !== annotation.id) return; const currentValue = editingValueRef.current; editingTextIdRef.current = null; - const nextText = currentValue.trim() === "" ? "Type something" : currentValue; - if (nextText !== annotation.text) onUpdate({ ...annotation, text: nextText }); setEditingTextId(null); + const isEmpty = currentValue.trim() === ""; + if (pendingText?.id === annotation.id) { + setPendingText(null); + if (isEmpty) { + setSelectedAnnotationId(null); + } else { + onCommit({ ...annotation, text: currentValue }); + setSelectedTextId(annotation.id); + setSelectedAnnotationId(annotation.id); + } + } else if (isEmpty) { + onDelete(annotation.id); + setSelectedTextId(null); + setSelectedAnnotationId(null); + } else if (currentValue !== annotation.text) { + onUpdate({ ...annotation, text: currentValue }); + } + containerRef.current?.focus({ preventScroll: true }); } function finishActiveTextEdit(): void { const activeId = editingTextIdRef.current; if (activeId === null) return; - const annotation = scene.elements.find( - (element): element is Extract => - element.kind === "text" && element.id === activeId, - ); + const annotation = + pendingText?.id === activeId + ? pendingText + : scene.elements.find((element): element is TextAnnotation => element.kind === "text" && element.id === activeId); if (annotation !== undefined) commitTextEdit(annotation); } + finishEditRef.current = finishActiveTextEdit; return (
{ + if (activeTool === "smart") onSmartHover?.(null); + }} onPointerUp={handlePointerUp} > - {displayedElements.filter(isTextAnnotation).map((annotation) => { + {[...displayedElements.filter(isTextAnnotation), ...(pendingText === null ? [] : [pendingText])].map((annotation) => { const selected = selectedTextId === annotation.id; const editing = editingTextId === annotation.id; - const estimatedWidth = Math.max(92, annotation.text.length * annotation.fontSize * 0.54); - const estimatedHeight = annotation.fontSize * 1.35; + const measured = measureTextBlock( + editing ? editingValue || TEXT_PLACEHOLDER : annotation.text, + annotation.fontSize, + annotation.fontFamily, + ); + const estimatedWidth = measured.width + (editing ? 6 : 0); + const estimatedHeight = measured.height; return (
commitTextEdit(annotation)} @@ -416,8 +612,7 @@ export function AnnotationCanvas({ commitTextEdit(annotation); } else if (event.key === "Escape") { event.preventDefault(); - setEditingTextId(null); - editingTextIdRef.current = null; + commitTextEdit(annotation); } }} onPointerDown={(event) => event.stopPropagation()} @@ -428,6 +623,7 @@ export function AnnotationCanvas({ className={`h-full w-full border bg-transparent outline-none ${selected ? "border-dashed border-lime-300/80" : "border border-transparent"}`} type="button" onClick={() => selectText(annotation)} + onDoubleClick={() => beginTextEdit(annotation, annotation.text)} onPointerDown={(event) => { if (activeTool !== "select") event.stopPropagation(); }} @@ -452,6 +648,29 @@ export function AnnotationCanvas({
); })} + {activeTool === "smart" && smartTarget !== null && draft === null && movingAnnotation === null ? ( +