From ba6512e7472eae89657142c544552eb83a4b4ac1 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 14:55:23 +0530 Subject: [PATCH 01/18] feat(capture): resize annotations and glide the target highlight Selected annotations get eight resize handles (drag, or arrow keys with Shift for 10px). The detection hover outline now glides between targets and stays visible while UI Automation resolves the next one. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG-PUBLIC.md | 2 + apps/desktop/src/App.tsx | 17 +-- .../src/components/AnnotationCanvas.test.tsx | 42 ++++++ .../src/components/AnnotationCanvas.tsx | 112 +++++++++++----- .../desktop/src/components/SelectionFrame.tsx | 3 +- .../src/components/TargetHighlight.test.tsx | 33 +++++ .../src/components/TargetHighlight.tsx | 34 +++++ .../src/domain/annotationGeometry.test.ts | 65 ++++++++++ apps/desktop/src/domain/annotationGeometry.ts | 121 ++++++++++++++++++ apps/desktop/src/lib/geometry.test.ts | 18 ++- apps/desktop/src/lib/geometry.ts | 25 ++++ 11 files changed, 426 insertions(+), 46 deletions(-) create mode 100644 apps/desktop/src/components/TargetHighlight.test.tsx create mode 100644 apps/desktop/src/components/TargetHighlight.tsx create mode 100644 apps/desktop/src/domain/annotationGeometry.test.ts create mode 100644 apps/desktop/src/domain/annotationGeometry.ts diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index b813b51..9fdae69 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -15,6 +15,8 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. - The capture toolbar is a single card, with the colour and size row only for tools that use them. - Only one CapKit runs at a time; opening it again brings the existing window forward. +- Shapes, arrows, pen strokes and highlights can be resized: select one and drag any of its eight handles, or focus a handle and use the arrow keys. +- The highlight that follows your pointer before you select now glides smoothly from one area to the next. It jumps instantly when Windows animation effects are off. - Folder paths in Settings no longer start with `\\?\`. ## Earlier — 2026-10-29 diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index fc2a9aa..1e8a1b0 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -10,6 +10,7 @@ import { type RedactionReview, } from "./components/RedactionReviewPanel"; import { SelectionFrame, type ResizeHandle } from "./components/SelectionFrame"; +import { TargetHighlight } from "./components/TargetHighlight"; import { ScrollingCapturePanel, type ScrollingCaptureState, @@ -404,7 +405,8 @@ export function App(): React.JSX.Element { setMessage("Visual target ready | click to select"); return; } - setHoverTarget((previous) => previous === null ? previous : null); + // Keep the current highlight until UI Automation answers, so it glides to + // the next target instead of blinking off and back on. pendingUiLookup.current = point; if (uiLookupInFlight.current) return; const lookupPoint = pendingUiLookup.current; @@ -423,6 +425,7 @@ export function App(): React.JSX.Element { }) .catch((error: unknown) => { console.error("SH-TARGET-UIA-001", error); + if (sequence === uiLookupSequence.current) setHoverTarget(null); setMessage(`Control detection unavailable · ${describeInvokeError(error, "Windows UI Automation did not return a target")}`); }) .finally(() => { @@ -1128,15 +1131,9 @@ export function App(): React.JSX.Element { /> {selection === null && hoverTarget !== null ? ( -
) : null} diff --git a/apps/desktop/src/components/AnnotationCanvas.test.tsx b/apps/desktop/src/components/AnnotationCanvas.test.tsx index 1940587..4931f86 100644 --- a/apps/desktop/src/components/AnnotationCanvas.test.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.test.tsx @@ -188,4 +188,46 @@ describe("AnnotationCanvas effect previews", () => { fireEvent.keyDown(window, { key: "Delete" }); expect(onDelete).toHaveBeenCalledWith("rectangle-1"); }); + + it("resizes a selected annotation by dragging or nudging a handle", () => { + const rectangle = { + id: "rectangle-1", + kind: "rectangle" as const, + bounds: { x: 20, y: 30, width: 80, height: 50 }, + color: "#d9ff43", + fill: "transparent", + strokeWidth: 4, + opacity: 1, + }; + const onUpdate = vi.fn(); + render( + undefined} + onDelete={() => undefined} + onUpdate={onUpdate} + />, + ); + + const canvas = screen.getByRole("application", { name: "Screenshot annotation canvas" }); + expect(screen.queryByRole("button", { name: /Resize rectangle annotation/ })).toBeNull(); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 30, clientY: 40, pointerId: 5 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 30, clientY: 40, pointerId: 5 }); + onUpdate.mockClear(); + + expect(screen.getAllByRole("button", { name: /Resize rectangle annotation/ })).toHaveLength(8); + const corner = screen.getByRole("button", { name: "Resize rectangle annotation from the bottom-right corner" }); + fireEvent.pointerDown(corner, { button: 0, buttons: 1, clientX: 100, clientY: 80, pointerId: 6 }); + fireEvent.pointerMove(canvas, { buttons: 1, clientX: 130, clientY: 100, pointerId: 6 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 130, clientY: 100, pointerId: 6 }); + expect(onUpdate).toHaveBeenLastCalledWith(expect.objectContaining({ id: "rectangle-1", bounds: { x: 20, y: 30, width: 110, height: 70 } })); + + 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 } })); + }); }); diff --git a/apps/desktop/src/components/AnnotationCanvas.tsx b/apps/desktop/src/components/AnnotationCanvas.tsx index 3838c95..b0effe5 100644 --- a/apps/desktop/src/components/AnnotationCanvas.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.tsx @@ -7,9 +7,45 @@ import type { RegionAnnotation, ToolId, } from "../domain/annotations"; +import { + annotationBounds, + findAnnotationAtPoint, + isResizableAnnotation, + resizeAnnotation, + translateAnnotation, +} from "../domain/annotationGeometry"; import { Cancel } from "./icons"; import type { Point, Rect as CaptureRect } from "../domain/capture"; -import { normalizeRect } from "../lib/geometry"; +import { normalizeRect, type ResizeHandle } from "../lib/geometry"; + +const resizeHandles: readonly ResizeHandle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"]; + +const handleNames: Record = { + nw: "top-left corner", + n: "top edge", + ne: "top-right corner", + e: "right edge", + se: "bottom-right corner", + s: "bottom edge", + sw: "bottom-left corner", + w: "left edge", +}; + +/** Arrow keys on a focused handle nudge that edge: 1px, or 10px with Shift. */ +function keyboardResizeDelta(key: string, step: number): Point | null { + switch (key) { + case "ArrowLeft": + return { x: -step, y: 0 }; + case "ArrowRight": + return { x: step, y: 0 }; + case "ArrowUp": + return { x: 0, y: -step }; + case "ArrowDown": + return { x: 0, y: step }; + default: + return null; + } +} type AnnotationCanvasProps = { bounds: CaptureRect; @@ -47,7 +83,8 @@ export function AnnotationCanvas({ const editingValueRef = useRef(""); const draftRef = useRef(null); const draftFrameRequest = useRef(null); - const movingAnnotationRef = useRef<{ initial: Annotation; current: Annotation; start: Point } | null>(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); const displayedElements = useMemo(() => { if (movingAnnotation === null) return scene.elements; @@ -93,7 +130,7 @@ export function AnnotationCanvas({ setSelectedTextId(hit.kind === "text" ? hit.id : null); finishActiveTextEdit(); if ("setPointerCapture" in event.currentTarget) event.currentTarget.setPointerCapture(event.pointerId); - movingAnnotationRef.current = { initial: hit, current: hit, start: point }; + movingAnnotationRef.current = { initial: hit, current: hit, start: point, handle: null }; setMovingAnnotation({ initial: hit, current: hit }); return; } @@ -124,6 +161,20 @@ export function AnnotationCanvas({ setDraft(nextDraft); } + function startResize(annotation: Annotation, handle: ResizeHandle, event: React.PointerEvent): void { + if (event.button !== 0) return; + // Keep the press away from SelectionFrame, which would move the capture region. + event.stopPropagation(); + event.preventDefault(); + // Capture on the canvas so its move/up handlers keep receiving the drag. + const container = containerRef.current; + if (container !== null && "setPointerCapture" in container) container.setPointerCapture(event.pointerId); + const host = container?.getBoundingClientRect(); + const start = host === undefined ? { x: 0, y: 0 } : { x: event.clientX - host.left, y: event.clientY - host.top }; + movingAnnotationRef.current = { initial: annotation, current: annotation, start, handle }; + setMovingAnnotation({ initial: annotation, current: annotation }); + } + function handlePointerMove(event: React.PointerEvent): void { const moving = movingAnnotationRef.current; if (moving !== null) { @@ -133,7 +184,11 @@ export function AnnotationCanvas({ } event.stopPropagation(); const point = relativePoint(event); - const current = translateAnnotation(moving.initial, point.x - moving.start.x, point.y - moving.start.y); + const dx = point.x - moving.start.x; + const dy = point.y - moving.start.y; + const current = moving.handle === null + ? translateAnnotation(moving.initial, dx, dy) + : resizeAnnotation(moving.initial, moving.handle, dx, dy); moving.current = current; setMovingAnnotation({ initial: moving.initial, current }); return; @@ -342,7 +397,25 @@ export function AnnotationCanvas({ const selectedBounds = annotationBounds(selected); return (
-
@@ -585,35 +658,6 @@ function isTextAnnotation( return annotation.kind === "text"; } -function annotationBounds(annotation: Annotation): CaptureRect { - if ("bounds" in annotation) return annotation.bounds; - if (annotation.kind === "text") { - return { x: annotation.position.x, y: annotation.position.y, width: Math.max(92, annotation.text.length * annotation.fontSize * 0.54), height: annotation.fontSize * 1.35 }; - } - if (annotation.kind === "counter") { - return { x: annotation.position.x - annotation.radius, y: annotation.position.y - annotation.radius, width: annotation.radius * 2, height: annotation.radius * 2 }; - } - const xs = annotation.points.map((point) => point.x); - const ys = annotation.points.map((point) => point.y); - const minX = Math.min(...xs) - annotation.strokeWidth; - const minY = Math.min(...ys) - annotation.strokeWidth; - return { x: minX, y: minY, width: Math.max(1, Math.max(...xs) - minX + annotation.strokeWidth), height: Math.max(1, Math.max(...ys) - minY + annotation.strokeWidth) }; -} - -function findAnnotationAtPoint(elements: readonly Annotation[], point: Point): Annotation | undefined { - const tolerance = 10; - return [...elements].reverse().find((element) => { - const bounds = annotationBounds(element); - return point.x >= bounds.x - tolerance && point.x <= bounds.x + bounds.width + tolerance && point.y >= bounds.y - tolerance && point.y <= bounds.y + bounds.height + tolerance; - }); -} - -function translateAnnotation(annotation: Annotation, dx: number, dy: number): Annotation { - if ("bounds" in annotation) return { ...annotation, bounds: { ...annotation.bounds, x: annotation.bounds.x + dx, y: annotation.bounds.y + dy } }; - if (annotation.kind === "text" || annotation.kind === "counter") return { ...annotation, position: { x: annotation.position.x + dx, y: annotation.position.y + dy } }; - return { ...annotation, points: annotation.points.map((point) => ({ x: point.x + dx, y: point.y + dy })) }; -} - function createAnnotation( tool: ToolId, start: Point, diff --git a/apps/desktop/src/components/SelectionFrame.tsx b/apps/desktop/src/components/SelectionFrame.tsx index 10530d5..bc322aa 100644 --- a/apps/desktop/src/components/SelectionFrame.tsx +++ b/apps/desktop/src/components/SelectionFrame.tsx @@ -1,6 +1,7 @@ import type { Rect } from "../domain/capture"; +import type { ResizeHandle } from "../lib/geometry"; -export type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; +export type { ResizeHandle }; type SelectionFrameProps = { rect: Rect; diff --git a/apps/desktop/src/components/TargetHighlight.test.tsx b/apps/desktop/src/components/TargetHighlight.test.tsx new file mode 100644 index 0000000..bad5c57 --- /dev/null +++ b/apps/desktop/src/components/TargetHighlight.test.tsx @@ -0,0 +1,33 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { TARGET_GLIDE, TargetHighlight } from "./TargetHighlight"; + +function mockReducedMotion(reduce: boolean): void { + vi.stubGlobal("matchMedia", (query: string) => ({ matches: reduce && query.includes("reduce"), media: query })); +} + +describe("TargetHighlight", () => { + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + }); + + it("glides to a new target without remounting", () => { + mockReducedMotion(false); + const { rerender } = render(); + const first = screen.getByTestId("target-highlight"); + expect(first.style.transition).toBe(TARGET_GLIDE); + + rerender(); + const second = screen.getByTestId("target-highlight"); + expect(second).toBe(first); + expect(second).toHaveStyle({ left: "200px", top: "80px", width: "50px", height: "30px" }); + expect(second).toHaveAccessibleName("Detected text: B"); + }); + + it("jumps without a transition under reduced motion", () => { + mockReducedMotion(true); + render(); + expect(screen.getByTestId("target-highlight").style.transition).toBe(""); + }); +}); diff --git a/apps/desktop/src/components/TargetHighlight.tsx b/apps/desktop/src/components/TargetHighlight.tsx new file mode 100644 index 0000000..fa4c7a7 --- /dev/null +++ b/apps/desktop/src/components/TargetHighlight.tsx @@ -0,0 +1,34 @@ +import type { Rect } from "../domain/capture"; +import { prefersReducedMotion } from "../lib/motion"; + +/** Fast enough to stay with the cursor, long enough to read as a glide. */ +export const TARGET_GLIDE = + "left 140ms cubic-bezier(0.22, 1, 0.36, 1), top 140ms cubic-bezier(0.22, 1, 0.36, 1), width 140ms cubic-bezier(0.22, 1, 0.36, 1), height 140ms cubic-bezier(0.22, 1, 0.36, 1)"; + +type TargetHighlightProps = { + bounds: Rect; + label: string; +}; + +/** + * The hover outline in detection mode. It stays mounted while the pointer moves + * between targets, so changing `bounds` glides it to the next target. The first + * appearance is instant because a freshly mounted element has nothing to + * transition from. + */ +export function TargetHighlight({ bounds, label }: TargetHighlightProps): React.JSX.Element { + return ( +
+ ); +} diff --git a/apps/desktop/src/domain/annotationGeometry.test.ts b/apps/desktop/src/domain/annotationGeometry.test.ts new file mode 100644 index 0000000..a00119e --- /dev/null +++ b/apps/desktop/src/domain/annotationGeometry.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import type { Annotation } from "./annotations"; +import { annotationBounds, isResizableAnnotation, resizeAnnotation } from "./annotationGeometry"; + +const rectangle: Annotation = { + id: "rect", + kind: "rectangle", + bounds: { x: 10, y: 20, width: 100, height: 50 }, + color: "#fff", + fill: "transparent", + strokeWidth: 2, + opacity: 1, +}; + +const stroke: Annotation = { + id: "stroke", + kind: "pencil", + points: [{ x: 20, y: 20 }, { x: 60, y: 40 }, { x: 120, y: 80 }], + color: "#fff", + strokeWidth: 4, + opacity: 1, +}; + +describe("resizeAnnotation", () => { + it("moves only the dragged edges of a shape", () => { + expect(resizeAnnotation(rectangle, "se", 30, 10)).toMatchObject({ bounds: { x: 10, y: 20, width: 130, height: 60 } }); + expect(resizeAnnotation(rectangle, "w", -10, 99)).toMatchObject({ bounds: { x: 0, y: 20, width: 110, height: 50 } }); + expect(resizeAnnotation(rectangle, "n", 99, 5)).toMatchObject({ bounds: { x: 10, y: 25, width: 100, height: 45 } }); + }); + + it("stops at the minimum size instead of flipping", () => { + expect(resizeAnnotation(rectangle, "e", -500, 0)).toMatchObject({ bounds: { x: 10, width: 8 } }); + expect(resizeAnnotation(rectangle, "nw", 500, 500)).toMatchObject({ bounds: { x: 102, y: 62, width: 8, height: 8 } }); + }); + + it("scales stroke points into the new frame and keeps the stroke width", () => { + const resized = resizeAnnotation(stroke, "se", 100, 60); + if (!("points" in resized)) throw new Error("expected a stroke"); + // Inner point box was 100 x 60 from (20, 20); now 200 x 120. + expect(resized.points).toEqual([{ x: 20, y: 20 }, { x: 100, y: 60 }, { x: 220, y: 140 }]); + expect(resized.strokeWidth).toBe(4); + expect(annotationBounds(resized)).toEqual({ x: 16, y: 16, width: 208, height: 128 }); + }); + + it("stretches a flat line along its length and keeps it flat", () => { + const line: Annotation = { id: "line", kind: "highlighter", points: [{ x: 10, y: 50 }, { x: 110, y: 50 }], color: "#0f0", strokeWidth: 12, opacity: 0.48 }; + const longer = resizeAnnotation(line, "e", 50, 0); + if (!("points" in longer)) throw new Error("expected a line"); + expect(longer.points).toEqual([{ x: 10, y: 50 }, { x: 160, y: 50 }]); + const taller = resizeAnnotation(line, "s", 0, 40); + if (!("points" in taller)) throw new Error("expected a line"); + expect(taller.points).toEqual([{ x: 10, y: 70 }, { x: 110, y: 70 }]); + }); + + it("resizes a counter around the new frame's centre", () => { + const counter: Annotation = { id: "c", kind: "counter", position: { x: 50, y: 50 }, value: 1, color: "#fff", radius: 10, opacity: 1 }; + expect(resizeAnnotation(counter, "se", 20, 10)).toMatchObject({ position: { x: 60, y: 55 }, radius: 15 }); + }); + + it("leaves text unchanged", () => { + const text: Annotation = { id: "t", kind: "text", position: { x: 0, y: 0 }, text: "Hi", color: "#fff", fontFamily: "Inter", fontSize: 16, opacity: 1 }; + expect(isResizableAnnotation(text)).toBe(false); + expect(resizeAnnotation(text, "se", 40, 40)).toBe(text); + }); +}); diff --git a/apps/desktop/src/domain/annotationGeometry.ts b/apps/desktop/src/domain/annotationGeometry.ts new file mode 100644 index 0000000..80c5952 --- /dev/null +++ b/apps/desktop/src/domain/annotationGeometry.ts @@ -0,0 +1,121 @@ +import type { Annotation } from "./annotations"; +import type { Point, Rect } from "./capture"; +import { resizeRectFromHandle, type ResizeHandle } from "../lib/geometry"; + +/** Smallest frame a resized annotation may shrink to, in logical pixels. */ +export const MIN_ANNOTATION_SIZE = 8; + +/** Text has its own selection control and is moved, not resized. */ +export function isResizableAnnotation(annotation: Annotation): boolean { + return annotation.kind !== "text"; +} + +/** The on-screen frame of an annotation, including stroke padding for lines. */ +export function annotationBounds(annotation: Annotation): Rect { + if ("bounds" in annotation) return annotation.bounds; + if (annotation.kind === "text") { + return { + x: annotation.position.x, + y: annotation.position.y, + width: Math.max(92, annotation.text.length * annotation.fontSize * 0.54), + height: annotation.fontSize * 1.35, + }; + } + if (annotation.kind === "counter") { + return { + x: annotation.position.x - annotation.radius, + y: annotation.position.y - annotation.radius, + width: annotation.radius * 2, + height: annotation.radius * 2, + }; + } + const xs = annotation.points.map((point) => point.x); + const ys = annotation.points.map((point) => point.y); + const minX = Math.min(...xs) - annotation.strokeWidth; + const minY = Math.min(...ys) - annotation.strokeWidth; + return { + x: minX, + y: minY, + width: Math.max(1, Math.max(...xs) - minX + annotation.strokeWidth), + height: Math.max(1, Math.max(...ys) - minY + annotation.strokeWidth), + }; +} + +export function findAnnotationAtPoint( + elements: readonly Annotation[], + point: Point, +): Annotation | undefined { + const tolerance = 10; + return [...elements].reverse().find((element) => { + const bounds = annotationBounds(element); + return ( + point.x >= bounds.x - tolerance && + point.x <= bounds.x + bounds.width + tolerance && + point.y >= bounds.y - tolerance && + point.y <= bounds.y + bounds.height + tolerance + ); + }); +} + +export function translateAnnotation(annotation: Annotation, dx: number, dy: number): Annotation { + if ("bounds" in annotation) { + return { ...annotation, bounds: { ...annotation.bounds, x: annotation.bounds.x + dx, y: annotation.bounds.y + dy } }; + } + if (annotation.kind === "text" || annotation.kind === "counter") { + return { ...annotation, position: { x: annotation.position.x + dx, y: annotation.position.y + dy } }; + } + return { ...annotation, points: annotation.points.map((point) => ({ x: point.x + dx, y: point.y + dy })) }; +} + +/** + * Drags one handle of the annotation's frame by (dx, dy) and refits the + * annotation into the new frame. Lines and strokes scale their points; stroke + * width is kept so a resized pen line keeps its weight. + */ +export function resizeAnnotation( + annotation: Annotation, + handle: ResizeHandle, + dx: number, + dy: number, +): Annotation { + if (!isResizableAnnotation(annotation)) return annotation; + const from = annotationBounds(annotation); + const padding = "points" in annotation ? annotation.strokeWidth : 0; + const minSize = Math.max(MIN_ANNOTATION_SIZE, padding * 2 + 2); + const to = resizeRectFromHandle(from, handle, dx, dy, minSize); + + if ("bounds" in annotation) return { ...annotation, bounds: to }; + if (annotation.kind === "counter") { + return { + ...annotation, + position: { x: to.x + to.width / 2, y: to.y + to.height / 2 }, + radius: Math.min(to.width, to.height) / 2, + }; + } + if (annotation.kind === "text") return annotation; + + const inner = (rect: Rect): Rect => ({ + x: rect.x + padding, + y: rect.y + padding, + width: Math.max(0, rect.width - padding * 2), + height: Math.max(0, rect.height - padding * 2), + }); + const source = inner(from); + const target = inner(to); + return { + ...annotation, + points: annotation.points.map((point) => ({ + x: mapAxis(point.x, source.x, source.width, target.x, target.width), + y: mapAxis(point.y, source.y, source.height, target.y, target.height), + })), + }; +} + +/** + * Maps a coordinate between two spans. A flat span (a horizontal or vertical + * line) can't be stretched, so it follows the target's centre instead. + */ +function mapAxis(value: number, sourceStart: number, sourceSize: number, targetStart: number, targetSize: number): number { + if (sourceSize < 1) return value + targetStart + targetSize / 2 - (sourceStart + sourceSize / 2); + return targetStart + ((value - sourceStart) * targetSize) / sourceSize; +} diff --git a/apps/desktop/src/lib/geometry.test.ts b/apps/desktop/src/lib/geometry.test.ts index 3c90778..d7805c5 100644 --- a/apps/desktop/src/lib/geometry.test.ts +++ b/apps/desktop/src/lib/geometry.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { chooseToolbarPlacement, clampRect, normalizeRect, toolbarPosition } from "./geometry"; +import { chooseToolbarPlacement, clampRect, normalizeRect, resizeRectFromHandle, toolbarPosition } from "./geometry"; describe("normalizeRect", () => { it("normalizes a reverse drag", () => { @@ -66,3 +66,19 @@ describe("toolbarPosition", () => { expect(toolbarPosition(selection, viewport, "top", size)).toEqual({ x: 100, y: 138 }); }); }); + +describe("resizeRectFromHandle", () => { + const initial = { x: 0, y: 0, width: 100, height: 100 }; + + it("moves both edges of a corner handle", () => { + expect(resizeRectFromHandle(initial, "nw", 10, 20, 8)).toEqual({ x: 10, y: 20, width: 90, height: 80 }); + }); + + it("ignores the axis an edge handle does not own", () => { + expect(resizeRectFromHandle(initial, "e", 15, 40, 8)).toEqual({ x: 0, y: 0, width: 115, height: 100 }); + }); + + it("clamps at the minimum size rather than flipping", () => { + expect(resizeRectFromHandle(initial, "s", 0, -400, 8)).toEqual({ x: 0, y: 0, width: 100, height: 8 }); + }); +}); diff --git a/apps/desktop/src/lib/geometry.ts b/apps/desktop/src/lib/geometry.ts index 6d6816e..31bb1ad 100644 --- a/apps/desktop/src/lib/geometry.ts +++ b/apps/desktop/src/lib/geometry.ts @@ -75,3 +75,28 @@ export function toolbarPosition( : Math.max(10, selection.y - size.height - 10); return { x, y: Math.max(0, y) }; } + +export type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; + +/** + * Moves the edges named by `handle` by (dx, dy). Edges stop `minSize` short of + * the opposite edge instead of flipping past it, so a drag never mirrors the + * content it frames. + */ +export function resizeRectFromHandle( + initial: Rect, + handle: ResizeHandle, + dx: number, + dy: number, + minSize: number, +): Rect { + let left = initial.x; + let top = initial.y; + let right = initial.x + initial.width; + let bottom = initial.y + initial.height; + if (handle.includes("w")) left = Math.min(left + dx, right - minSize); + if (handle.includes("e")) right = Math.max(right + dx, left + minSize); + if (handle.includes("n")) top = Math.min(top + dy, bottom - minSize); + if (handle.includes("s")) bottom = Math.max(bottom + dy, top + minSize); + return { x: left, y: top, width: right - left, height: bottom - top }; +} From 50c5bf37508550a8ea5554f79c0d67cfd91ac3f9 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 15:44:44 +0530 Subject: [PATCH 02/18] feat(capture): toolbar placement, pinned drawings, browser detection - Settings > Screenshots: show or hide each finishing action and place each Individual-mode tool and each action in the horizontal or vertical toolbar. - Remove the overlay motion setting; the overlay always fades in and out. - Drawings stay fixed on screen when the selection moves or resizes. - Browser windows: scan the active page's document on its own, clipped to its viewport, and rescan thin browser results on a later hover. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG-PUBLIC.md | 8 +- apps/desktop/src-tauri/src/lib.rs | 22 +- .../src-tauri/src/platform/windows_ui.rs | 261 ++++++++++++++---- .../src-tauri/src/platform/xcap_backend.rs | 66 ++++- apps/desktop/src/App.test.tsx | 86 ++---- apps/desktop/src/App.tsx | 154 ++++------- .../src/components/AnnotationToolbar.test.tsx | 44 +++ .../src/components/AnnotationToolbar.tsx | 50 +++- .../src/components/CompletionToolbar.test.tsx | 122 +++++--- .../src/components/CompletionToolbar.tsx | 119 ++------ .../desktop/src/components/SelectionFrame.tsx | 4 +- .../desktop/src/components/captureActions.tsx | 87 ++++++ .../src/components/dashboard/SettingsView.tsx | 5 - .../dashboard/ToolbarConfiguration.test.tsx | 31 +++ .../dashboard/ToolbarConfiguration.tsx | 122 +++++++- apps/desktop/src/components/toolbarCatalog.ts | 16 ++ apps/desktop/src/domain/annotations.test.ts | 24 ++ apps/desktop/src/domain/annotations.ts | 12 +- apps/desktop/src/domain/settings.test.ts | 44 ++- apps/desktop/src/domain/settings.ts | 53 +++- apps/desktop/src/lib/tauri.ts | 12 +- docs/current-status.md | 4 +- 22 files changed, 921 insertions(+), 425 deletions(-) create mode 100644 apps/desktop/src/components/captureActions.tsx diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index 9fdae69..f1935cf 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -8,8 +8,8 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. - CapKit can update itself. It checks GitHub once when it starts, tells you when a new version is ready, and installs only when you click Install and restart. You can turn the check off in Settings → General. - Copy any capture from the Screenshots page, and drag it straight into another app. -- Choose how the capture overlay appears: Dim and rise, Fade in, or Fade in and out. - Capture toolbar groups open when you click them and remember the last tool you used in each group. +- Settings → Screenshots lets you show or hide each finishing action (Copy, Save, Pin, Showcase and more) and choose whether each tool and action sits in the horizontal or the vertical toolbar. ### Improved @@ -18,6 +18,12 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. - Shapes, arrows, pen strokes and highlights can be resized: select one and drag any of its eight handles, or focus a handle and use the arrow keys. - The highlight that follows your pointer before you select now glides smoothly from one area to the next. It jumps instantly when Windows animation effects are off. - Folder paths in Settings no longer start with `\\?\`. +- The capture overlay fades in and out. The other overlay animations and their setting are gone. +- Drawings stay where they are on screen when you move or resize the capture area. + +### Fixed + +- Detection mode finds parts of web pages in Chrome, Edge and other Chromium browsers again, not just the browser's own buttons. ## Earlier — 2026-10-29 diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 76aea8d..028d0ee 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -50,15 +50,6 @@ use windows::Win32::UI::WindowsAndMessaging::{ const CAPTURE_REVEAL_MS: u32 = 90; const CAPTURE_CONCEAL_MS: u32 = 120; -/// How the capture overlay enters and leaves; chosen in Settings. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] -#[serde(rename_all = "kebab-case")] -enum OverlayMotion { - FadeIn, - DimRise, - FadeBoth, -} - /// Fades the window out through Win32. It hides the window without telling /// tao, so callers must still run `hide_capture_window` afterwards. #[cfg(target_os = "windows")] @@ -194,14 +185,8 @@ async fn begin_capture(app: AppHandle) -> Result Result<(), SnaphubError> { - // Every motion mode keeps the short blend-in: it masks WebView2's first-frame - // flash. `dim-rise` hides the blend by starting its scrim at opacity 0. - let _ = motion; +fn show_capture_surface(app: AppHandle, reduced_motion: bool) -> Result<(), SnaphubError> { + // The overlay fades in and out. The fade-in also masks WebView2's first-frame flash. let window = app .get_webview_window("capture") .ok_or_else(|| SnaphubError::Window("Capture window is unavailable".into()))?; @@ -540,11 +525,10 @@ async fn cancel_capture( window: WebviewWindow, app: AppHandle, session_id: String, - motion: OverlayMotion, reduced_motion: bool, ) -> Result<(), SnaphubError> { ensure_capture_window(&window)?; - if motion == OverlayMotion::FadeBoth && !reduced_motion { + if !reduced_motion { conceal_window_smoothly(&window); } let hide_result = hide_capture_window(&app); diff --git a/apps/desktop/src-tauri/src/platform/windows_ui.rs b/apps/desktop/src-tauri/src/platform/windows_ui.rs index 0c5bdbb..67e9e97 100644 --- a/apps/desktop/src-tauri/src/platform/windows_ui.rs +++ b/apps/desktop/src-tauri/src/platform/windows_ui.rs @@ -8,7 +8,8 @@ use windows::Win32::{ }, UI::{ Accessibility::{ - CUIAutomation, IUIAutomation, TreeScope_Descendants, UIA_BoundingRectanglePropertyId, + CUIAutomation, IUIAutomation, IUIAutomationCacheRequest, IUIAutomationCondition, + IUIAutomationElement, TreeScope_Descendants, UIA_BoundingRectanglePropertyId, UIA_ControlTypePropertyId, UIA_CustomControlTypeId, UIA_DocumentControlTypeId, UIA_GroupControlTypeId, UIA_IsContentElementPropertyId, UIA_IsControlElementPropertyId, UIA_IsOffscreenPropertyId, UIA_NamePropertyId, UIA_PaneControlTypeId, @@ -23,6 +24,8 @@ use crate::{ }; const MAX_CACHED_ELEMENTS: i32 = 4_000; +// Regions smaller than this (in physical pixels) are too small to aim at. +const MIN_REGION_SIZE: f64 = 6.0; // Layout containers (Chromium maps a plain, role-less
to Group/Pane/Document/ // Custom) are only worth surfacing up to this fraction of the window; beyond that // they're indistinguishable from "the whole page", which is already covered by the @@ -33,13 +36,35 @@ const MAX_LAYOUT_CONTAINER_RATIO: f64 = 0.9; const DEDUPE_TOLERANCE: f64 = 2.0; // Chromium/Firefox activate their full accessibility tree lazily, in response to the // first UIA query (WM_GETOBJECT). An immediate scan of a browser window often only -// sees the frame chrome, so we retry briefly if too few candidates come back. +// sees the frame chrome, so we retry briefly if too few candidates come back, and +// the caller rescans later if the result is still thin (see `UiScan::provisional`). const BROWSER_WINDOW_CLASSES: [&str; 2] = ["Chrome_WidgetWin_1", "MozillaWindowClass"]; const BROWSER_SCAN_MIN_REGIONS: usize = 6; -const BROWSER_SCAN_RETRIES: u32 = 2; -const BROWSER_SCAN_RETRY_DELAY: Duration = Duration::from_millis(180); +const BROWSER_SCAN_RETRIES: u32 = 1; +const BROWSER_SCAN_RETRY_DELAY: Duration = Duration::from_millis(150); -pub fn regions_for_window(window_id: u32) -> Result, SnaphubError> { +/// The result of one scan. A browser scan that found almost nothing is +/// provisional: the browser was probably still building its accessibility tree, +/// so the caller should scan again on a later hover instead of keeping it. +pub struct UiScan { + pub regions: Vec, + pub provisional: bool, +} + +pub fn scan_window(window_id: u32) -> Result { + let browser = is_browser_window(window_id); + let regions = regions_for_window(window_id, browser)?; + let provisional = browser && regions.len() < BROWSER_SCAN_MIN_REGIONS; + Ok(UiScan { + regions, + provisional, + }) +} + +fn regions_for_window( + window_id: u32, + browser: bool, +) -> Result, SnaphubError> { // UI Automation objects are apartment-bound. Each bounded scan initializes and releases COM // on the worker thread that performs it; callers cache the resulting plain rectangles. let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; @@ -49,8 +74,8 @@ pub fn regions_for_window(window_id: u32) -> Result, Snap ))); } - let mut result = unsafe { collect_regions(window_id) }; - if is_browser_window(window_id) { + let mut result = unsafe { collect_regions(window_id, browser) }; + if browser { for _ in 0..BROWSER_SCAN_RETRIES { let needs_retry = match &result { Ok(regions) => regions.len() < BROWSER_SCAN_MIN_REGIONS, @@ -60,7 +85,7 @@ pub fn regions_for_window(window_id: u32) -> Result, Snap break; } sleep(BROWSER_SCAN_RETRY_DELAY); - let retry = unsafe { collect_regions(window_id) }; + let retry = unsafe { collect_regions(window_id, browser) }; let retry_is_better = match (&result, &retry) { (Ok(existing), Ok(candidate)) => candidate.len() > existing.len(), (Err(_), Ok(_)) => true, @@ -93,7 +118,10 @@ fn is_browser_window(window_id: u32) -> bool { .any(|candidate| class_name == *candidate) } -unsafe fn collect_regions(window_id: u32) -> Result, SnaphubError> { +unsafe fn collect_regions( + window_id: u32, + browser: bool, +) -> Result, SnaphubError> { let automation: IUIAutomation = unsafe { CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER) .map_err(SnaphubError::capture)? @@ -128,13 +156,6 @@ unsafe fn collect_regions(window_id: u32) -> Result, Snap .map_err(SnaphubError::capture)?; } } - let elements = unsafe { - root.FindAllBuildCache(TreeScope_Descendants, &condition, &cache_request) - .map_err(SnaphubError::capture)? - }; - let count = - unsafe { elements.Length().map_err(SnaphubError::capture)? }.clamp(0, MAX_CACHED_ELEMENTS); - let mut regions = Vec::with_capacity(count as usize); let mut window_rect = RECT::default(); let window_area = if unsafe { GetWindowRect(window_handle, &mut window_rect) }.is_ok() { @@ -144,6 +165,89 @@ unsafe fn collect_regions(window_id: u32) -> Result, Snap 0.0 }; + let mut regions = Vec::new(); + let window_scope = ScanScope { + window_id, + window_area, + viewport: None, + id_prefix: "ui", + }; + let page = unsafe { + scan_subtree( + &root, + &condition, + &cache_request, + &window_scope, + &mut regions, + )? + }; + + // A browser's own tabs, toolbar and side panels can use up the element cap + // before the walk reaches the page. Scan the visible page on its own as well, + // with its own cap, clipped to the page's viewport. + if browser && let Some((document, viewport)) = page { + let page_scope = ScanScope { + window_id, + window_area, + viewport: Some(viewport), + id_prefix: "web", + }; + unsafe { + scan_subtree( + &document, + &condition, + &cache_request, + &page_scope, + &mut regions, + )?; + } + } + + regions.sort_by(|left, right| { + let left_area = left.bounds.width * left.bounds.height; + let right_area = right.bounds.width * right.bounds.height; + left_area.total_cmp(&right_area) + }); + + let mut deduped: Vec = Vec::with_capacity(regions.len()); + for region in regions { + let is_duplicate = deduped + .iter() + .any(|existing| rects_nearly_equal(&existing.bounds, ®ion.bounds)); + if !is_duplicate { + deduped.push(region); + } + } + Ok(deduped) +} + +struct ScanScope { + window_id: u32, + window_area: f64, + /// Inside a web page: the page's visible rectangle. Elements are clipped to + /// it, and the browser's offscreen flag is not trusted on its own (a page + /// behind the capture overlay can report its elements as offscreen). + viewport: Option, + id_prefix: &'static str, +} + +unsafe fn scan_subtree( + root: &IUIAutomationElement, + condition: &IUIAutomationCondition, + cache_request: &IUIAutomationCacheRequest, + scope: &ScanScope, + regions: &mut Vec, +) -> Result, SnaphubError> { + let elements = unsafe { + root.FindAllBuildCache(TreeScope_Descendants, condition, cache_request) + .map_err(SnaphubError::capture)? + }; + let count = + unsafe { elements.Length().map_err(SnaphubError::capture)? }.clamp(0, MAX_CACHED_ELEMENTS); + regions.reserve(count as usize); + // The largest Document seen: in a browser, the active tab's web page. + let mut largest_document: Option<(IUIAutomationElement, Rect)> = None; + for index in 0..count { let Ok(element) = (unsafe { elements.GetElement(index) }) else { continue; @@ -157,72 +261,97 @@ unsafe fn collect_regions(window_id: u32) -> Result, Snap // Web pages made of role-less
s report neither flag: Chromium/Firefox // still expose them as Group/Pane/Document/Custom nodes, so accept those as // a lower-confidence "layout container" match rather than dropping them. + let control_type = unsafe { element.CachedControlType() }; + if scope.viewport.is_none() + && control_type == Ok(UIA_DocumentControlTypeId) + && let Ok(bounds) = unsafe { element.CachedBoundingRectangle() } + { + let rect = rect_from(bounds); + let area = rect.width * rect.height; + if area > 0.0 + && largest_document + .as_ref() + .is_none_or(|(_, current)| area > current.width * current.height) + { + largest_document = Some((element.clone(), rect)); + } + } let is_layout_container = matches!( - unsafe { element.CachedControlType() }, + control_type, Ok(control_type) if control_type == UIA_GroupControlTypeId || control_type == UIA_PaneControlTypeId || control_type == UIA_DocumentControlTypeId || control_type == UIA_CustomControlTypeId ); - if !(is_control || is_content || is_layout_container) - || unsafe { element.CachedIsOffscreen() } - .map(windows::core::BOOL::as_bool) - .unwrap_or(true) - { + if !(is_control || is_content || is_layout_container) { + continue; + } + let offscreen = unsafe { element.CachedIsOffscreen() } + .map(windows::core::BOOL::as_bool) + .unwrap_or(true); + if offscreen && scope.viewport.is_none() { continue; } let Ok(bounds) = (unsafe { element.CachedBoundingRectangle() }) else { continue; }; - let width = bounds.right.saturating_sub(bounds.left); - let height = bounds.bottom.saturating_sub(bounds.top); - if width < 6 || height < 6 { + let raw = rect_from(bounds); + let visible = match scope.viewport { + Some(viewport) => clip_rect(raw, viewport), + None => Some(raw), + }; + let Some(rect) = visible else { + continue; + }; + if rect.width < MIN_REGION_SIZE || rect.height < MIN_REGION_SIZE { continue; } let is_relaxed_only = is_layout_container && !(is_control || is_content); - if is_relaxed_only && window_area > 0.0 { - let area = f64::from(width) * f64::from(height); - if area > window_area * MAX_LAYOUT_CONTAINER_RATIO { - continue; - } + if is_relaxed_only + && scope.window_area > 0.0 + && rect.width * rect.height > scope.window_area * MAX_LAYOUT_CONTAINER_RATIO + { + continue; } let name = unsafe { element.CachedName() } .map(|value| value.to_string()) .unwrap_or_else(|_| "UI region".into()); regions.push(DetectedTargetDto { - id: format!("ui-{window_id}-{index}"), + id: format!("{}-{}-{index}", scope.id_prefix, scope.window_id), title: if name.trim().is_empty() { "UI region".into() } else { name }, kind: "ui-region", - bounds: Rect { - x: f64::from(bounds.left), - y: f64::from(bounds.top), - width: f64::from(width), - height: f64::from(height), - }, + bounds: rect, }); } + Ok(largest_document) +} - regions.sort_by(|left, right| { - let left_area = left.bounds.width * left.bounds.height; - let right_area = right.bounds.width * right.bounds.height; - left_area.total_cmp(&right_area) - }); - - let mut deduped: Vec = Vec::with_capacity(regions.len()); - for region in regions { - let is_duplicate = deduped - .iter() - .any(|existing| rects_nearly_equal(&existing.bounds, ®ion.bounds)); - if !is_duplicate { - deduped.push(region); - } +fn rect_from(bounds: RECT) -> Rect { + Rect { + x: f64::from(bounds.left), + y: f64::from(bounds.top), + width: f64::from(bounds.right.saturating_sub(bounds.left).max(0)), + height: f64::from(bounds.bottom.saturating_sub(bounds.top).max(0)), } - Ok(deduped) +} + +/// The part of `rect` inside `clip`, or `None` when they don't overlap. +fn clip_rect(rect: Rect, clip: Rect) -> Option { + let left = rect.x.max(clip.x); + let top = rect.y.max(clip.y); + let right = (rect.x + rect.width).min(clip.x + clip.width); + let bottom = (rect.y + rect.height).min(clip.y + clip.height); + (right > left && bottom > top).then_some(Rect { + x: left, + y: top, + width: right - left, + height: bottom - top, + }) } fn rects_nearly_equal(left: &Rect, right: &Rect) -> bool { @@ -231,3 +360,31 @@ fn rects_nearly_equal(left: &Rect, right: &Rect) -> bool { && (left.width - right.width).abs() <= DEDUPE_TOLERANCE && (left.height - right.height).abs() <= DEDUPE_TOLERANCE } + +#[cfg(test)] +mod tests { + use super::*; + + fn rect(x: f64, y: f64, width: f64, height: f64) -> Rect { + Rect { + x, + y, + width, + height, + } + } + + #[test] + fn clip_keeps_the_visible_part_of_a_partly_scrolled_element() { + let viewport = rect(0.0, 100.0, 800.0, 600.0); + let clipped = clip_rect(rect(10.0, 60.0, 200.0, 80.0), viewport); + assert_eq!(clipped, Some(rect(10.0, 100.0, 200.0, 40.0))); + } + + #[test] + fn clip_drops_an_element_scrolled_out_of_the_page() { + let viewport = rect(0.0, 100.0, 800.0, 600.0); + assert_eq!(clip_rect(rect(10.0, 0.0, 200.0, 90.0), viewport), None); + assert_eq!(clip_rect(rect(10.0, 700.0, 200.0, 90.0), viewport), None); + } +} diff --git a/apps/desktop/src-tauri/src/platform/xcap_backend.rs b/apps/desktop/src-tauri/src/platform/xcap_backend.rs index 701c787..9d8aa1d 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -14,7 +14,29 @@ use crate::{ #[derive(Default)] pub struct XcapPlatformBackend { - ui_regions: Mutex>>, + ui_regions: Mutex>, +} + +/// After this long, a thin browser scan is worth repeating: the browser has had +/// time to build the accessibility tree our first query asked for. +const PROVISIONAL_RESCAN_AFTER: std::time::Duration = std::time::Duration::from_millis(350); +/// Stop rescanning a window that keeps coming back thin (it may truly be empty). +const MAX_SCAN_ATTEMPTS: u8 = 5; + +/// UI regions found in one window during the current capture session. +struct CachedUiRegions { + regions: Vec, + provisional: bool, + scanned_at: std::time::Instant, + attempts: u8, +} + +impl CachedUiRegions { + fn needs_rescan(&self, now: std::time::Instant) -> bool { + self.provisional + && self.attempts < MAX_SCAN_ATTEMPTS + && now.saturating_duration_since(self.scanned_at) >= PROVISIONAL_RESCAN_AFTER + } } impl CaptureBackend for XcapPlatformBackend { @@ -160,11 +182,26 @@ impl TargetDetectionBackend for XcapPlatformBackend { .ui_regions .lock() .map_err(|_| SnaphubError::Capture("UI-region cache is unavailable".into()))?; - if let std::collections::hash_map::Entry::Vacant(entry) = cache.entry(window_id) { - entry.insert(super::windows_ui::regions_for_window(window_id)?); + let now = std::time::Instant::now(); + let stale = cache + .get(&window_id) + .is_none_or(|cached| cached.needs_rescan(now)); + if stale { + let attempts = cache.get(&window_id).map_or(0, |cached| cached.attempts); + let scan = super::windows_ui::scan_window(window_id)?; + cache.insert( + window_id, + CachedUiRegions { + regions: scan.regions, + provisional: scan.provisional, + scanned_at: now, + attempts: attempts + 1, + }, + ); } - Ok(cache.get(&window_id).and_then(|regions| { - regions + Ok(cache.get(&window_id).and_then(|cached| { + cached + .regions .iter() .find(|target| physical_rect_contains(target.bounds, point)) .cloned() @@ -308,6 +345,25 @@ impl PinnedWindowBackend for XcapPlatformBackend { mod tests { use super::*; + fn cached(provisional: bool, attempts: u8, scanned_at: std::time::Instant) -> CachedUiRegions { + CachedUiRegions { + regions: Vec::new(), + provisional, + scanned_at, + attempts, + } + } + + #[test] + fn rescans_a_thin_browser_scan_only_after_a_pause_and_a_few_times() { + let start = std::time::Instant::now(); + let later = start + PROVISIONAL_RESCAN_AFTER; + assert!(!cached(true, 1, start).needs_rescan(start)); + assert!(cached(true, 1, start).needs_rescan(later)); + assert!(!cached(true, MAX_SCAN_ATTEMPTS, start).needs_rescan(later)); + assert!(!cached(false, 1, start).needs_rescan(later)); + } + #[test] fn locates_points_on_negative_origin_monitors() { let left_monitor = Rect { diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 259d408..784f07f 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libra import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; import type { CaptureSession, CompletionAction } from "./domain/capture"; -import { defaultSnaphubSettings, saveSnaphubSettings, type OverlayMotion } from "./domain/settings"; +import { defaultSnaphubSettings } from "./domain/settings"; import type { CompletionResult } from "./lib/tauri"; const captureMocks = vi.hoisted(() => ({ @@ -691,8 +691,7 @@ describe("App", () => { }); describe("App overlay motion", () => { - function useMotion(motion: OverlayMotion, reduced = false): void { - saveSnaphubSettings({ ...defaultSnaphubSettings, overlay: { ...defaultSnaphubSettings.overlay, motion } }); + function useReducedMotion(reduced: boolean): void { vi.stubGlobal("matchMedia", (media: string) => ({ matches: reduced, media, @@ -715,85 +714,34 @@ describe("App overlay motion", () => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); - vi.useRealTimers(); window.localStorage.clear(); }); - it("dim-rise: scrim and hint start hidden, then transition in after two frames", async () => { - useMotion("dim-rise"); - const frames = createAnimationFrameQueue(); - render(); - await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("dim-rise", false)); - const scrim = screen.getByTestId("capture-scrim"); - const hint = screen.getByTestId("capture-hint"); - expect(scrim).toHaveStyle({ opacity: "0" }); - expect(hint.style.transform).toBe("translateY(6px)"); - frames.flushNext(); - frames.flushNext(); - expect(scrim).toHaveStyle({ opacity: "1" }); - expect(scrim.style.transition).toBe("opacity 160ms cubic-bezier(0.22, 1, 0.36, 1)"); - expect(hint.style.transform).toBe("translateY(0px)"); - }); - - it("dim-rise: Escape fades out and cancels only after 120 ms, once for a double Escape", async () => { - useMotion("dim-rise"); + it("fades the overlay in and out natively, with no scrim animation in the page", async () => { + useReducedMotion(false); render(); - await screen.findByTestId("capture-scrim"); - await waitFor(() => expect(screen.getByTestId("capture-scrim")).toHaveStyle({ opacity: "1" })); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - fireEvent.keyDown(window, { key: "Escape" }); - fireEvent.keyDown(window, { key: "Escape" }); - const scrim = screen.getByTestId("capture-scrim"); - expect(scrim).toHaveStyle({ opacity: "0" }); - expect(scrim.style.transition).toBe("opacity 120ms cubic-bezier(0.4, 0, 1, 1)"); - expect(captureMocks.cancelCapture).not.toHaveBeenCalled(); - await act(async () => { - vi.advanceTimersByTime(120); - await Promise.resolve(); - }); - expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); - }); - - it("fade-both: Escape cancels immediately with the fade-both motion", async () => { - useMotion("fade-both"); - render(); - await screen.findByRole("main"); - fireEvent.keyDown(window, { key: "Escape" }); - await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); - expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), "fade-both", false); - }); - - it("fade-in: reveals without scrim animation and cancels immediately", async () => { - useMotion("fade-in"); - render(); - await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("fade-in", false)); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(false)); expect(screen.getByTestId("capture-scrim").style.transition).toBe(""); fireEvent.keyDown(window, { key: "Escape" }); await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); + expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), false); }); - it("reduced motion: no scrim animation and Escape cancels immediately in every mode", async () => { - useMotion("dim-rise", true); + it("skips both fades under reduced motion", async () => { + useReducedMotion(true); render(); - await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("dim-rise", true)); - expect(screen.getByTestId("capture-scrim").style.transition).toBe(""); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(true)); fireEvent.keyDown(window, { key: "Escape" }); - await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); - expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), "dim-rise", true); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), true)); }); - it("a new capture during the exit fade cancels the old session once and reveals the new one", async () => { - useMotion("dim-rise"); + it("ignores a saved motion choice from an older version", async () => { + window.localStorage.setItem("snaphub.settings.v1", JSON.stringify({ + ...defaultSnaphubSettings, + overlay: { ...defaultSnaphubSettings.overlay, motion: "dim-rise" }, + })); + useReducedMotion(false); render(); - await waitFor(() => expect(screen.getByTestId("capture-scrim")).toHaveStyle({ opacity: "1" })); - fireEvent.keyDown(window, { key: "Escape" }); - act(() => { - captureMocks.listeners.forEach((listener) => listener()); - }); - await waitFor(() => expect(captureMocks.requestCapture).toHaveBeenCalledTimes(2)); - expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); - await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledTimes(2)); - await new Promise((resolve) => window.setTimeout(resolve, 200)); - expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(false)); }); }); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 1e8a1b0..166831f 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,9 +1,11 @@ -import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react"; import { flushSync } from "react-dom"; import { AnnotationCanvas } from "./components/AnnotationCanvas"; import { AnnotationToolbar } from "./components/AnnotationToolbar"; import { CaptureBackdrop } from "./components/CaptureBackdrop"; +import { completionRailItems, type CompletionHandlers, type RailItem } from "./components/captureActions"; import { CompletionToolbar } from "./components/CompletionToolbar"; +import { getToolbarTool, runToolbarTool } from "./components/toolbarCatalog"; import { RedactionPreview, RedactionReviewPanel, @@ -31,7 +33,7 @@ import type { Point, Rect, } from "./domain/capture"; -import { useSnaphubSettings, type CaptureToolbarToolId } from "./domain/settings"; +import { useSnaphubSettings, type CaptureToolbarToolId, type CompletionActionId } from "./domain/settings"; import { chooseToolbarPlacement, clampRect, @@ -102,15 +104,12 @@ export function App(): React.JSX.Element { const [activeTool, setActiveTool] = useState("select"); const [style, setStyle] = useState(defaultAnnotationStyle); const [history, dispatchScene] = useReducer(sceneHistoryReducer, initialSceneHistory); + const drawingOrigin = useRef<{ x: number; y: number } | null>(null); const [busy, setBusy] = useState(false); const [lastToolByGroup, setLastToolByGroup] = useState>>({}); const [openGroupIndex, setOpenGroupIndex] = useState(null); const [toolbarSize, setToolbarSize] = useState({ width: 430, height: 52 }); const toolbarObserver = useRef(null); - const [revealed, setRevealed] = useState(false); - const [exiting, setExiting] = useState(false); - const exitTimer = useRef(null); - const revealFrames = useRef([]); const [completionState, setCompletionState] = useState({ phase: "idle", message: "", @@ -161,6 +160,16 @@ export function App(): React.JSX.Element { pending.resolve(); }, [session]); + // Drawings are stored relative to the capture area. When the area moves or is + // resized from its top or left edge, shift them back so they stay on the same + // screen content. A layout effect applies the shift before the browser paints. + useLayoutEffect(() => { + const previous = drawingOrigin.current; + drawingOrigin.current = selection === null ? null : { x: selection.x, y: selection.y }; + if (previous === null || selection === null) return; + dispatchScene({ type: "shift", dx: previous.x - selection.x, dy: previous.y - selection.y }); + }, [selection]); + useEffect(() => { settingsRef.current = settings; }, [settings]); @@ -197,20 +206,8 @@ export function App(): React.JSX.Element { setLastToolByGroup((current) => current[groupIndex] === toolId ? current : { ...current, [groupIndex]: toolId }); }, []); - function clearPendingMotion(): void { - if (exitTimer.current !== null) window.clearTimeout(exitTimer.current); - exitTimer.current = null; - for (const frame of revealFrames.current) window.cancelAnimationFrame(frame); - revealFrames.current = []; - } - - useEffect(() => clearPendingMotion, []); - function clearCaptureUi(): void { - clearPendingMotion(); setOpenGroupIndex(null); - setExiting(false); - setRevealed(false); activationState.current = "idle"; activeSessionId.current = null; const pendingBackdrop = backdropReadyResolver.current; @@ -229,24 +226,12 @@ export function App(): React.JSX.Element { } const startSession = useCallback(async (): Promise => { - if (exitTimer.current !== null) { - // A new request during the exit fade: finish the old session once, then start fresh. - const oldSessionId = activeSessionId.current; - clearPendingMotion(); - setExiting(false); - activationState.current = "idle"; - sessionGeneration.current += 1; - if (oldSessionId !== null) await cancelCapture(oldSessionId, "fade-in", true).catch(() => undefined); - } if (activationState.current !== "idle") return; const timingStartedAt = import.meta.env.DEV ? performance.now() : null; let timingAfterRequest: number | null = null; let timingAfterReady: number | null = null; activationState.current = "preparing"; sessionGeneration.current += 1; - clearPendingMotion(); - setExiting(false); - setRevealed(false); completionInFlight.current = false; activeSessionId.current = null; let preparedSession: CaptureSession | null = null; @@ -291,19 +276,7 @@ export function App(): React.JSX.Element { if (!isPreparingCaptureSession(activationState, activeSessionId, next.id)) { return; } - const motion = settingsRef.current.overlay.motion; - const reduced = prefersReducedMotion(); - await showCaptureSurface(motion, reduced); - if (motion === "dim-rise" && !reduced) { - // Two frames so the hidden styles paint before the transition target applies. - const first = window.requestAnimationFrame(() => { - const second = window.requestAnimationFrame(() => setRevealed(true)); - revealFrames.current.push(second); - }); - revealFrames.current.push(first); - } else { - setRevealed(true); - } + await showCaptureSurface(prefersReducedMotion()); if ( timingStartedAt !== null && timingAfterRequest !== null && @@ -655,10 +628,9 @@ export function App(): React.JSX.Element { const handleCancel = useCallback(async (): Promise => { sessionGeneration.current += 1; - const exitMotion = settingsRef.current.overlay.motion; try { if (session !== null) { - await cancelCapture(session.id, exitMotion, prefersReducedMotion()).catch(async () => dismissCapture()); + await cancelCapture(session.id, prefersReducedMotion()).catch(async () => dismissCapture()); await cancelManualScrolling(session.id).catch(() => undefined); } else { await dismissCapture(); @@ -672,17 +644,8 @@ export function App(): React.JSX.Element { }, [session]); const requestExit = useCallback((): void => { - if (exitTimer.current !== null) return; - if (settingsRef.current.overlay.motion !== "dim-rise" || prefersReducedMotion() || session === null) { - void handleCancel(); - return; - } - setExiting(true); - exitTimer.current = window.setTimeout(() => { - exitTimer.current = null; - void handleCancel(); - }, 120); - }, [handleCancel, session]); + void handleCancel(); + }, [handleCancel]); const handleComplete = useCallback( async (action: CompletionAction, followUp: "none" | "showcase" = "none"): Promise => { @@ -1099,19 +1062,43 @@ export function App(): React.JSX.Element { ? 10 : Math.max(10, Math.min(selection.y, viewport.height - 190)); const activeCaptureCursor = captureCursor(settings.cursor, settings.accentColor); - const dimRise = settings.overlay.motion === "dim-rise" && !prefersReducedMotion(); - const shown = revealed && !exiting; - const fadeStyle: React.CSSProperties = dimRise - ? { - opacity: shown ? 1 : 0, - transition: exiting - ? "opacity 120ms cubic-bezier(0.4, 0, 1, 1)" - : "opacity 160ms cubic-bezier(0.22, 1, 0.36, 1)", - } - : {}; - const exitOnlyStyle: React.CSSProperties = dimRise - ? { opacity: exiting ? 0 : 1, transition: "opacity 120ms cubic-bezier(0.4, 0, 1, 1)" } - : {}; + + const completionHandlers: CompletionHandlers = { + copyShortcut: settings.shortcuts.captureModeCopy, + copyAndSaveShortcut: settings.shortcuts.captureModeCopyAndSave, + saveShortcut: settings.shortcuts.captureModeSave, + disabled: completionState.phase !== "idle", + canReadText, + onAction: (id: CompletionActionId): void => { + if (id === "showcase") void handleComplete("save", "showcase"); + else if (id === "copy-text") void handleCopyText(); + else if (id === "find-sensitive") void findSensitiveText(); + else void handleComplete(id); + }, + }; + const horizontalActionItems = completionRailItems(settings.toolbar.actions, "horizontal", completionHandlers); + const railToolItems: RailItem[] = settings.toolbar.mode === "individual" + ? settings.toolbar.verticalTools + .filter((toolId) => settings.toolbar.individual[toolId]) + .map((toolId) => { + const tool = getToolbarTool(toolId); + return { + id: `tool-${toolId}`, + label: tool.label, + icon: tool.icon, + ...(tool.shortcut === undefined ? {} : { shortcut: 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, { + onToolChange: setActiveTool, + onScrollCapture: startScrollingCapture, + onUndo: () => dispatchScene({ type: "undo" }), + onRedo: () => dispatchScene({ type: "redo" }), + }), + }; + }) + : []; + const verticalRailItems = [...completionRailItems(settings.toolbar.actions, "vertical", completionHandlers), ...railToolItems]; return (
) : null} - {selection === null ?
: null} + {selection === null ?
: null} {selection === null ? (
{swatchHex === null ? null : } {message} @@ -1173,7 +1151,6 @@ export function App(): React.JSX.Element {
) : ( dispatchScene({ type: "undo" })} + actionItems={horizontalActionItems} />
) : null} @@ -1232,25 +1210,15 @@ export function App(): React.JSX.Element {
void handleComplete(action)} onRetrySave={() => void handleRetrySave()} - onShowcase={() => void handleComplete("save", "showcase")} - {...(canReadText - ? { - onCopyText: () => void handleCopyText(), - onFindSensitive: () => void findSensitiveText(), - } - : {})} /> {redactionReview === null ? null : ( { if (lastTopRow === undefined || firstRow === undefined) throw new Error("buttons missing"); expect(lastTopRow.compareDocumentPosition(firstRow) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); }); + +describe("AnnotationToolbar placement", () => { + afterEach(() => cleanup()); + + it("leaves tools moved to the vertical toolbar out of the horizontal one", () => { + render(); + expect(screen.queryByRole("button", { name: "Pencil" })).toBeNull(); + expect(screen.getByRole("button", { name: "Rectangle" })).toBeTruthy(); + }); + + it("keeps the colour row for an active style tool that lives in the vertical toolbar", () => { + render(); + expect(screen.queryByRole("button", { name: "Pencil" })).toBeNull(); + expect(screen.getByRole("radiogroup", { name: "Annotation color" })).toBeTruthy(); + }); + + it("shows finishing actions moved to the horizontal toolbar after the tools", () => { + const onSelect = vi.fn(); + render( + null, shortcut: "S", onSelect }]} + activeTool="select" + canRedo={false} + canUndo={false} + lastToolByGroup={{}} + openGroupIndex={null} + palette={defaultSnaphubSettings.palette} + style={defaultAnnotationStyle} + toolbar={individual} + onGroupToolUsed={() => undefined} + onOpenGroupChange={() => undefined} + onRedo={() => undefined} + onScrollCapture={() => undefined} + onStyleChange={() => undefined} + onToolChange={() => undefined} + onUndo={() => undefined} + />, + ); + const buttons = screen.getAllByRole("button"); + expect(buttons.at(-1)).toHaveAccessibleName("Save"); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + expect(onSelect).toHaveBeenCalledOnce(); + }); +}); }); diff --git a/apps/desktop/src/components/AnnotationToolbar.tsx b/apps/desktop/src/components/AnnotationToolbar.tsx index 0a0c4cd..95a8e8a 100644 --- a/apps/desktop/src/components/AnnotationToolbar.tsx +++ b/apps/desktop/src/components/AnnotationToolbar.tsx @@ -3,7 +3,8 @@ import type { AnnotationStyle, ToolId } from "../domain/annotations"; import type { CaptureToolbarToolId, SnaphubSettings } from "../domain/settings"; import { SelectPointer, type CapkitIconComponent } from "./icons"; import { ContextControls } from "./ContextControls"; -import { getToolbarTool, toolbarCatalog, type ToolbarToolDefinition } from "./toolbarCatalog"; +import type { RailItem } from "./captureActions"; +import { getToolbarTool, runToolbarTool, toolbarCatalog, type ToolbarToolDefinition } from "./toolbarCatalog"; type AnnotationToolbarProps = { activeTool: ToolId; @@ -16,6 +17,8 @@ type AnnotationToolbarProps = { placement?: "top" | "bottom"; lastToolByGroup: Readonly>>; openGroupIndex: number | null; + /** Finishing actions the user moved into this toolbar; shown after the tools. */ + actionItems?: readonly RailItem[]; onToolChange: (tool: ToolId) => void; onStyleChange: (style: AnnotationStyle) => void; onUndo: () => void; @@ -49,6 +52,7 @@ export function AnnotationToolbar({ placement = "bottom", lastToolByGroup, openGroupIndex, + actionItems = [], onToolChange, onStyleChange, onUndo, @@ -60,14 +64,7 @@ export function AnnotationToolbar({ const [hoveredIndex, setHoveredIndex] = useState(null); function runTool(toolId: CaptureToolbarToolId): void { - const tool = getToolbarTool(toolId); - if (tool.annotationTool !== undefined) { - onToolChange(tool.annotationTool); - return; - } - if (toolId === "scrolling-capture") onScrollCapture(); - else if (toolId === "undo") onUndo(); - else onRedo(); + runToolbarTool(toolId, { onToolChange, onScrollCapture, onUndo, onRedo }); } const groups = toolbar.mode === "group" ? toolbar.groups : []; @@ -97,7 +94,7 @@ export function AnnotationToolbar({ if (toolbar.mode === "individual") { for (const tool of toolbarCatalog) { - if (!toolbar.individual[tool.id]) continue; + if (!toolbar.individual[tool.id] || toolbar.verticalTools.includes(tool.id)) continue; const active = tool.annotationTool === activeTool; items.push({ id: `tool-${tool.id}`, @@ -141,13 +138,27 @@ export function AnnotationToolbar({ }); } + for (const action of actionItems) { + items.push({ + id: action.id, + label: action.label, + icon: action.icon, + ...(action.shortcut === undefined ? {} : { shortcut: action.shortcut }), + active: false, + disabled: action.disabled ?? false, + tools: [], + showStyleControls: false, + onSelect: action.onSelect, + }); + } + const activeIndex = items.findIndex((item) => item.active); const indicatorIndex = hoveredIndex ?? activeIndex; const openGroup = items.find( (item) => item.groupIndex !== undefined && item.groupIndex === openGroupIndex, ); const activeStyleItem = toolbar.mode === "individual" - ? items.find((item) => item.active && item.showStyleControls) + ? items.find((item) => item.active && item.showStyleControls) ?? railStyleItem(toolbar, activeTool) : undefined; const rowTwo = openGroup ?? activeStyleItem; @@ -221,3 +232,20 @@ export function AnnotationToolbar({
); } + +/** A style tool moved to the vertical rail still gets its colour and size row here. */ +function railStyleItem(toolbar: SnaphubSettings["toolbar"], activeTool: ToolId): PrimaryItem | undefined { + const tool = toolbarCatalog.find((candidate) => + candidate.annotationTool === activeTool && toolbar.verticalTools.includes(candidate.id) && toolbar.individual[candidate.id]); + if (!tool?.supportsStyle) return undefined; + return { + id: `rail-${tool.id}`, + label: tool.label, + icon: tool.icon, + active: true, + disabled: false, + tools: [], + showStyleControls: true, + onSelect: () => undefined, + }; +} diff --git a/apps/desktop/src/components/CompletionToolbar.test.tsx b/apps/desktop/src/components/CompletionToolbar.test.tsx index 9673df4..5188eae 100644 --- a/apps/desktop/src/components/CompletionToolbar.test.tsx +++ b/apps/desktop/src/components/CompletionToolbar.test.tsx @@ -1,33 +1,53 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; -import type { CompletionAction } from "../domain/capture"; -import { CompletionToolbar } from "./CompletionToolbar"; +import { + defaultToolbarActions, + type CompletionActionId, + type SnaphubSettings, +} from "../domain/settings"; +import { completionRailItems, type CompletionHandlers } from "./captureActions"; +import { CompletionToolbar, type CompletionToolbarState } from "./CompletionToolbar"; -const actions: readonly { action: CompletionAction; label: string }[] = [ +const actions: readonly { action: CompletionActionId; label: string }[] = [ { action: "copy", label: "Copy" }, { action: "copy-and-save", label: "Copy & Save" }, { action: "save", label: "Save" }, { action: "pin", label: "Pin" }, + { action: "showcase", label: "Save & Showcase" }, ]; +function handlers(onAction: (id: CompletionActionId) => void, canReadText = false): CompletionHandlers { + return { + copyShortcut: "C", + copyAndSaveShortcut: "A", + saveShortcut: "S", + disabled: false, + canReadText, + onAction, + }; +} + function renderToolbar( - onComplete: (action: CompletionAction) => void, - onCopyText?: () => void, - onShowcase: () => void = () => undefined, + onAction: (id: CompletionActionId) => void, + options: { + canReadText?: boolean; + actions?: SnaphubSettings["toolbar"]["actions"]; + state?: CompletionToolbarState; + } = {}, ): void { + const items = completionRailItems( + options.actions ?? defaultToolbarActions, + "vertical", + handlers(onAction, options.canReadText ?? false), + ); render( undefined} - onShowcase={onShowcase} - {...(onCopyText === undefined ? {} : { onCopyText })} />, ); } @@ -36,8 +56,8 @@ describe("CompletionToolbar", () => { afterEach(() => cleanup()); it.each(actions)("activates $label once for mouse and touch pointer sequences", ({ action, label }) => { - const onComplete = vi.fn(); - renderToolbar(onComplete); + const onAction = vi.fn(); + renderToolbar(onAction); const button = screen.getByRole("button", { name: label }); fireEvent.pointerUp(button, { pointerType: "mouse" }); @@ -45,49 +65,79 @@ describe("CompletionToolbar", () => { fireEvent.pointerUp(button, { pointerType: "touch" }); fireEvent.click(button); - expect(onComplete).toHaveBeenCalledTimes(2); - expect(onComplete).toHaveBeenNthCalledWith(1, action); - expect(onComplete).toHaveBeenNthCalledWith(2, action); + expect(onAction).toHaveBeenCalledTimes(2); + expect(onAction).toHaveBeenNthCalledWith(1, action); + expect(onAction).toHaveBeenNthCalledWith(2, action); }); it.each(actions)("keeps $label to one native activation for Enter and Space", ({ action, label }) => { - const onComplete = vi.fn(); - renderToolbar(onComplete); + const onAction = vi.fn(); + renderToolbar(onAction); const button = screen.getByRole("button", { name: label }); button.focus(); - fireEvent.keyDown(button, { key: "Enter" }); fireEvent.keyUp(button, { key: "Enter" }); button.click(); cleanup(); - renderToolbar(onComplete); + renderToolbar(onAction); const spaceButton = screen.getByRole("button", { name: label }); spaceButton.focus(); fireEvent.keyDown(spaceButton, { key: " " }); fireEvent.keyUp(spaceButton, { key: " " }); spaceButton.click(); - expect(onComplete).toHaveBeenCalledTimes(2); - expect(onComplete).toHaveBeenNthCalledWith(1, action); - expect(onComplete).toHaveBeenNthCalledWith(2, action); + expect(onAction).toHaveBeenCalledTimes(2); + expect(onAction).toHaveBeenNthCalledWith(1, action); + expect(onAction).toHaveBeenNthCalledWith(2, action); }); - it("shows Copy text only when the OS can read text", () => { + it("shows the text actions only when the OS can read text", () => { renderToolbar(() => undefined); expect(screen.queryByRole("button", { name: "Copy text" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Find sensitive text" })).toBeNull(); cleanup(); - const onCopyText = vi.fn(); - renderToolbar(() => undefined, onCopyText); + const onAction = vi.fn(); + renderToolbar(onAction, { canReadText: true }); fireEvent.click(screen.getByRole("button", { name: "Copy text" })); - expect(onCopyText).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole("button", { name: "Find sensitive text" })); + expect(onAction).toHaveBeenNthCalledWith(1, "copy-text"); + expect(onAction).toHaveBeenNthCalledWith(2, "find-sensitive"); + }); + + it("hides disabled actions and actions moved to the horizontal toolbar", () => { + renderToolbar(() => undefined, { + actions: { + ...defaultToolbarActions, + pin: { enabled: false, placement: "vertical" }, + save: { enabled: true, placement: "horizontal" }, + }, + }); + expect(screen.queryByRole("button", { name: "Pin" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); + expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy(); }); - it("saves and opens Showcase from its own action, not through onComplete", () => { - const onComplete = vi.fn(); - const onShowcase = vi.fn(); - renderToolbar(onComplete, undefined, onShowcase); - fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); - expect(onShowcase).toHaveBeenCalledOnce(); - expect(onComplete).not.toHaveBeenCalled(); + it("drops the empty rail when every action is hidden", () => { + const hidden = Object.fromEntries( + Object.keys(defaultToolbarActions).map((id) => [id, { enabled: false, placement: "vertical" }]), + ); + renderToolbar(() => undefined, { actions: { ...defaultToolbarActions, ...hidden } }); + expect(screen.queryByRole("toolbar", { name: "Capture actions" })).toBeNull(); + }); + + it("disables every rail button while a capture is finishing", () => { + renderToolbar(() => undefined, { state: "working" }); + expect(screen.getByRole("button", { name: "Copy" })).toHaveProperty("disabled", true); + }); +}); + +describe("completionRailItems", () => { + it("puts moved actions in the horizontal list with their shortcuts", () => { + const items = completionRailItems( + { ...defaultToolbarActions, copy: { enabled: true, placement: "horizontal" } }, + "horizontal", + handlers(() => undefined), + ); + expect(items.map((item) => [item.label, item.shortcut])).toEqual([["Copy", "C"]]); }); }); diff --git a/apps/desktop/src/components/CompletionToolbar.tsx b/apps/desktop/src/components/CompletionToolbar.tsx index 5c14e48..bd3c2fa 100644 --- a/apps/desktop/src/components/CompletionToolbar.tsx +++ b/apps/desktop/src/components/CompletionToolbar.tsx @@ -1,51 +1,27 @@ import { useEffect, useRef } from "react"; -import type { CompletionAction } from "../domain/capture"; -import { - Clipboard, - Copy, - Download, - Pin, - Presentation, - Refresh, - SecurityCheck, - TextSelection, - type CapkitIconProps, -} from "./icons"; +import type { RailItem } from "./captureActions"; +import { Refresh } from "./icons"; import { ToolButton } from "./ToolButton"; export type CompletionToolbarState = "idle" | "working" | "save-pending"; type CompletionToolbarProps = { state: CompletionToolbarState; - copyShortcut: string; - copyAndSaveShortcut: string; - saveShortcut: string; + /** Buttons placed in the vertical rail: finishing actions and any moved tools. */ + items: readonly RailItem[]; statusMessage: string; diagnostic: string | undefined; statusSide: "left" | "right"; - onComplete: (action: CompletionAction) => void; onRetrySave: () => void; - /** Saves, then opens the capture in Showcase with the default style. */ - onShowcase: () => void; - /** Present only when the OS can read text; the button is hidden otherwise. */ - onCopyText?: () => void; - /** Present only when the OS can read text; opens redaction suggestions. */ - onFindSensitive?: () => void; }; export function CompletionToolbar({ state, - copyShortcut, - copyAndSaveShortcut, - saveShortcut, + items, statusMessage, diagnostic, statusSide, - onComplete, onRetrySave, - onShowcase, - onCopyText, - onFindSensitive, }: CompletionToolbarProps): React.JSX.Element { const retryButtonRef = useRef(null); const disabled = state !== "idle"; @@ -60,62 +36,26 @@ export function CompletionToolbar({ return (
-
- onComplete("copy")} - /> - onComplete("copy-and-save")} - /> - onComplete("save")} - /> - onComplete("pin")} - /> - - {onCopyText === undefined ? null : ( - - )} - {onFindSensitive === undefined ? null : ( - - )} -
+ {items.length === 0 ? null : ( +
+ {items.map((item) => ( + + ))} +
+ )} {state === "idle" && statusMessage === "" ? null : (
); } - -function CopyAndSaveIcon({ className }: CapkitIconProps): React.JSX.Element { - return ( - - - ); -} diff --git a/apps/desktop/src/components/SelectionFrame.tsx b/apps/desktop/src/components/SelectionFrame.tsx index bc322aa..5c7dd43 100644 --- a/apps/desktop/src/components/SelectionFrame.tsx +++ b/apps/desktop/src/components/SelectionFrame.tsx @@ -6,7 +6,6 @@ export type { ResizeHandle }; type SelectionFrameProps = { rect: Rect; children: React.ReactNode; - motionStyle?: React.CSSProperties; onMoveStart: (event: React.PointerEvent) => void; onResizeStart: (handle: ResizeHandle, event: React.PointerEvent) => void; }; @@ -16,7 +15,6 @@ const handles: readonly ResizeHandle[] = ["nw", "n", "ne", "e", "se", "s", "sw", export function SelectionFrame({ rect, children, - motionStyle, onMoveStart, onResizeStart, }: SelectionFrameProps): React.JSX.Element { @@ -24,7 +22,7 @@ export function SelectionFrame({
{children} diff --git a/apps/desktop/src/components/captureActions.tsx b/apps/desktop/src/components/captureActions.tsx new file mode 100644 index 0000000..cc7b2f3 --- /dev/null +++ b/apps/desktop/src/components/captureActions.tsx @@ -0,0 +1,87 @@ +import type { CompletionActionId, SnaphubSettings, ToolbarPlacement } from "../domain/settings"; +import { + Clipboard, + Copy, + Download, + Pin, + Presentation, + SecurityCheck, + TextSelection, + type CapkitIconComponent, + type CapkitIconProps, +} from "./icons"; + +/** One button that can live in either capture toolbar. */ +export type RailItem = { + id: string; + label: string; + icon: CapkitIconComponent; + shortcut?: string; + active?: boolean; + disabled?: boolean; + onSelect: () => void; +}; + +export type CompletionActionDefinition = { + id: CompletionActionId; + label: string; + icon: CapkitIconComponent; + /** Only listed when the OS can read text from images. */ + needsTextRecognition: boolean; +}; + +export const completionActionCatalog: readonly CompletionActionDefinition[] = [ + { id: "copy", label: "Copy", icon: Clipboard, needsTextRecognition: false }, + { id: "copy-and-save", label: "Copy & Save", icon: CopyAndSaveIcon, needsTextRecognition: false }, + { id: "save", label: "Save", icon: Download, needsTextRecognition: false }, + { id: "pin", label: "Pin", icon: Pin, needsTextRecognition: false }, + { id: "showcase", label: "Save & Showcase", icon: Presentation, needsTextRecognition: false }, + { id: "copy-text", label: "Copy text", icon: TextSelection, needsTextRecognition: true }, + { id: "find-sensitive", label: "Find sensitive text", icon: SecurityCheck, needsTextRecognition: true }, +]; + +export type CompletionHandlers = { + copyShortcut: string; + copyAndSaveShortcut: string; + saveShortcut: string; + disabled: boolean; + onAction: (id: CompletionActionId) => void; + /** False hides Copy text and Find sensitive text. */ + canReadText: boolean; +}; + +/** The enabled finishing actions that belong to one toolbar, in catalog order. */ +export function completionRailItems( + actions: SnaphubSettings["toolbar"]["actions"], + placement: ToolbarPlacement, + handlers: CompletionHandlers, +): RailItem[] { + const shortcuts: Partial> = { + copy: handlers.copyShortcut, + "copy-and-save": handlers.copyAndSaveShortcut, + save: handlers.saveShortcut, + }; + return completionActionCatalog + .filter((action) => actions[action.id].enabled && actions[action.id].placement === placement) + .filter((action) => handlers.canReadText || !action.needsTextRecognition) + .map((action) => { + const shortcut = shortcuts[action.id]; + return { + id: `action-${action.id}`, + label: action.label, + icon: action.icon, + ...(shortcut === undefined ? {} : { shortcut }), + disabled: handlers.disabled, + onSelect: () => handlers.onAction(action.id), + }; + }); +} + +function CopyAndSaveIcon({ className }: CapkitIconProps): React.JSX.Element { + return ( + + + ); +} diff --git a/apps/desktop/src/components/dashboard/SettingsView.tsx b/apps/desktop/src/components/dashboard/SettingsView.tsx index 3c9a10a..aaf9e3f 100644 --- a/apps/desktop/src/components/dashboard/SettingsView.tsx +++ b/apps/desktop/src/components/dashboard/SettingsView.tsx @@ -631,11 +631,6 @@ export function SettingsView(): React.JSX.Element { update({ ...settings, detection: { ...settings.detection, windows } })} /> update({ ...settings, detection: { ...settings.detection, uiRegions } })} />
Overlay tint
update({ ...settings, overlay: { ...settings.overlay, color: event.currentTarget.value } })} /> update({ ...settings, overlay: { ...settings.overlay, opacity: Number(event.currentTarget.value) / 100 } })} />{Math.round(settings.overlay.opacity * 100)}% update({ ...settings, overlay: defaultSnaphubSettings.overlay })} />
-
Overlay motion
{([ - ["dim-rise", "Dim fades in", "The screen dims gently and the hint rises. Leaving fades out quickly."], - ["fade-in", "Fade in", "The overlay fades in. Escape closes it instantly."], - ["fade-both", "Fade in and out", "The whole overlay fades in and fades out."], - ] as const).map(([value, label, description]) => )}
diff --git a/apps/desktop/src/components/dashboard/ToolbarConfiguration.test.tsx b/apps/desktop/src/components/dashboard/ToolbarConfiguration.test.tsx index ad4e1ea..ac743ca 100644 --- a/apps/desktop/src/components/dashboard/ToolbarConfiguration.test.tsx +++ b/apps/desktop/src/components/dashboard/ToolbarConfiguration.test.tsx @@ -56,4 +56,35 @@ describe("ToolbarConfiguration", () => { Reflect.deleteProperty(document, "elementFromPoint"); } }); + + it("moves an Individual-mode tool to the vertical toolbar and back with the arrow keys", () => { + const changes: SnaphubSettings["toolbar"][] = []; + function Spy(): React.JSX.Element { + const [toolbar, setToolbar] = useState({ ...defaultSnaphubSettings.toolbar, mode: "individual" }); + return { changes.push(next); setToolbar(next); }} />; + } + const view = render(); + const placement = view.getByRole("radiogroup", { name: "Pencil toolbar" }); + fireEvent.click(within(placement).getByRole("radio", { name: "Vertical" })); + expect(changes.at(-1)?.verticalTools).toEqual(["pencil"]); + expect(within(placement).getByRole("radio", { name: "Vertical" })).toHaveAttribute("aria-checked", "true"); + fireEvent.keyDown(within(placement).getByRole("radio", { name: "Vertical" }), { key: "ArrowLeft" }); + expect(changes.at(-1)?.verticalTools).toEqual([]); + expect(within(placement).getByRole("radio", { name: "Horizontal" })).toHaveFocus(); + }); + + it("hides a finishing action and moves another to the horizontal toolbar", () => { + const changes: SnaphubSettings["toolbar"][] = []; + function Spy(): React.JSX.Element { + const [toolbar, setToolbar] = useState(defaultSnaphubSettings.toolbar); + return { changes.push(next); setToolbar(next); }} />; + } + const view = render(); + expect(view.getByText("Finishing actions")).toBeVisible(); + fireEvent.click(view.getByRole("switch", { name: "Show Pin" })); + expect(changes.at(-1)?.actions.pin).toEqual({ enabled: false, placement: "vertical" }); + expect(within(view.getByRole("radiogroup", { name: "Pin toolbar" })).getByRole("radio", { name: "Vertical" })).toBeDisabled(); + fireEvent.click(within(view.getByRole("radiogroup", { name: "Save toolbar" })).getByRole("radio", { name: "Horizontal" })); + expect(changes.at(-1)?.actions.save).toEqual({ enabled: true, placement: "horizontal" }); + }); }); diff --git a/apps/desktop/src/components/dashboard/ToolbarConfiguration.tsx b/apps/desktop/src/components/dashboard/ToolbarConfiguration.tsx index 413ed62..34a8476 100644 --- a/apps/desktop/src/components/dashboard/ToolbarConfiguration.tsx +++ b/apps/desktop/src/components/dashboard/ToolbarConfiguration.tsx @@ -2,8 +2,12 @@ import { Fragment, useState } from "react"; import { captureToolbarToolIds, type CaptureToolbarToolId, + type CompletionActionId, + type CompletionActionSetting, type SnaphubSettings, + type ToolbarPlacement, } from "../../domain/settings"; +import { completionActionCatalog } from "../captureActions"; import { getToolbarTool, toolbarCatalog } from "../toolbarCatalog"; import { Add as Plus, @@ -11,6 +15,7 @@ import { Grip as GripVertical, List, Rows as Rows3, + type CapkitIconComponent, } from "../icons"; type ToolbarConfigurationProps = { @@ -41,6 +46,15 @@ export function ToolbarConfiguration({ onChange({ ...toolbar, mode }); } + function setToolPlacement(toolId: CaptureToolbarToolId, placement: ToolbarPlacement): void { + const others = toolbar.verticalTools.filter((id) => id !== toolId); + onChange({ ...toolbar, verticalTools: placement === "vertical" ? [...others, toolId] : others }); + } + + function setAction(actionId: CompletionActionId, next: CompletionActionSetting): void { + onChange({ ...toolbar, actions: { ...toolbar.actions, [actionId]: next } }); + } + function moveTool(toolId: CaptureToolbarToolId, rowIndex: number, targetIndex: number): void { const sourceRowIndex = toolbar.groups.findIndex((group) => group.includes(toolId)); const sourceToolIndex = sourceRowIndex < 0 ? -1 : toolbar.groups[sourceRowIndex]?.indexOf(toolId) ?? -1; @@ -184,7 +198,7 @@ export function ToolbarConfiguration({

- Select stays fixed as the first recovery tool. Configure everything that follows it. + Select stays fixed as the first recovery tool. Configure everything that follows it. In Group mode, groups always sit in the horizontal toolbar.

setMode("individual")} /> @@ -193,18 +207,18 @@ export function ToolbarConfiguration({
{toolbar.mode === "individual" ? ( -
- {toolbarCatalog.map((tool) => { - const Icon = tool.icon; - const enabled = toolbar.individual[tool.id]; - return ( - - ); - })} +
+ {toolbarCatalog.map((tool) => ( + onChange({ ...toolbar, individual: { ...toolbar.individual, [tool.id]: checked } })} + onPlacementChange={(placement) => setToolPlacement(tool.id, placement)} + /> + ))}
) : (
@@ -283,6 +297,88 @@ export function ToolbarConfiguration({ {dragging?.active === true ? : null}
)} + +
+

Finishing actions

+

+ Choose which actions appear and which toolbar holds them. Copy, Save and Copy & Save keep their keyboard shortcuts even when hidden. +

+
+ {completionActionCatalog.map((action) => { + const setting = toolbar.actions[action.id]; + return ( + setAction(action.id, { ...setting, enabled })} + onPlacementChange={(placement) => setAction(action.id, { ...setting, placement })} + /> + ); + })} +
+
+
+ ); +} + +type ItemRowProps = { + label: string; + icon: CapkitIconComponent; + enabled: boolean; + placement: ToolbarPlacement; + note?: string | undefined; + onEnabledChange: (enabled: boolean) => void; + onPlacementChange: (placement: ToolbarPlacement) => void; +}; +function ItemRow({ label, icon: Icon, enabled, placement, note, onEnabledChange, onPlacementChange }: ItemRowProps): React.JSX.Element { + return ( +
+
+ ); +} + +const placementLabels: Record = { horizontal: "Horizontal", vertical: "Vertical" }; +const placementKeys: ReadonlySet = new Set(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"]); + +type PlacementSwitchProps = { label: string; value: ToolbarPlacement; disabled: boolean; onChange: (placement: ToolbarPlacement) => void }; +/** Two-option radio group; arrow keys switch sides like a native radio group. */ +function PlacementSwitch({ label, value, disabled, onChange }: PlacementSwitchProps): React.JSX.Element { + function onKeyDown(event: React.KeyboardEvent): void { + if (!placementKeys.has(event.key)) return; + event.preventDefault(); + const next: ToolbarPlacement = value === "horizontal" ? "vertical" : "horizontal"; + onChange(next); + event.currentTarget.parentElement?.querySelector(`[data-placement="${next}"]`)?.focus(); + } + return ( +
+ {(["horizontal", "vertical"] as const).map((option) => ( + + ))}
); } diff --git a/apps/desktop/src/components/toolbarCatalog.ts b/apps/desktop/src/components/toolbarCatalog.ts index b207b43..7f2743d 100644 --- a/apps/desktop/src/components/toolbarCatalog.ts +++ b/apps/desktop/src/components/toolbarCatalog.ts @@ -55,3 +55,19 @@ export function getToolbarTool(id: CaptureToolbarToolId): ToolbarToolDefinition if (tool === undefined) throw new Error(`Unknown capture toolbar tool: ${id}`); return tool; } + +export type ToolbarToolHandlers = { + onToolChange: (tool: ToolId) => void; + onScrollCapture: () => void; + onUndo: () => void; + onRedo: () => void; +}; + +/** Runs a toolbar tool the same way from either capture toolbar. */ +export function runToolbarTool(toolId: CaptureToolbarToolId, handlers: ToolbarToolHandlers): void { + const tool = getToolbarTool(toolId); + if (tool.annotationTool !== undefined) handlers.onToolChange(tool.annotationTool); + else if (toolId === "scrolling-capture") handlers.onScrollCapture(); + else if (toolId === "undo") handlers.onUndo(); + else handlers.onRedo(); +} diff --git a/apps/desktop/src/domain/annotations.test.ts b/apps/desktop/src/domain/annotations.test.ts index 47c7ea1..7d03d01 100644 --- a/apps/desktop/src/domain/annotations.test.ts +++ b/apps/desktop/src/domain/annotations.test.ts @@ -44,4 +44,28 @@ describe("sceneHistoryReducer", () => { expect(deleted.present.elements).toHaveLength(0); expect(sceneHistoryReducer(deleted, { type: "undo" }).present.elements).toEqual([updatedAnnotation]); }); + + it("shifts every undo step so drawings stay on screen when the capture area moves", () => { + const line = { + id: "line-1", + kind: "line" as const, + points: [{ x: 10, y: 10 }, { x: 30, y: 20 }], + color: "#fff", + strokeWidth: 2, + opacity: 1, + }; + const added = sceneHistoryReducer(initialSceneHistory, { type: "add", annotation: line }); + const moved = sceneHistoryReducer(added, { type: "update", annotation: { ...line, points: [{ x: 15, y: 10 }, { x: 35, y: 20 }] } }); + // The capture area grew 40 px to the left, so drawings move 40 px right inside it. + const shifted = sceneHistoryReducer(moved, { type: "shift", dx: 40, dy: 0 }); + expect(shifted.present.elements[0]).toMatchObject({ points: [{ x: 55, y: 10 }, { x: 75, y: 20 }] }); + const undone = sceneHistoryReducer(shifted, { type: "undo" }); + expect(undone.present.elements[0]).toMatchObject({ points: [{ x: 50, y: 10 }, { x: 70, y: 20 }] }); + const redone = sceneHistoryReducer(undone, { type: "redo" }); + expect(redone.present.elements[0]).toMatchObject({ points: [{ x: 55, y: 10 }, { x: 75, y: 20 }] }); + }); + + it("keeps the same state for a zero shift", () => { + expect(sceneHistoryReducer(initialSceneHistory, { type: "shift", dx: 0, dy: 0 })).toBe(initialSceneHistory); + }); }); diff --git a/apps/desktop/src/domain/annotations.ts b/apps/desktop/src/domain/annotations.ts index 24ac06f..2cc315a 100644 --- a/apps/desktop/src/domain/annotations.ts +++ b/apps/desktop/src/domain/annotations.ts @@ -1,3 +1,4 @@ +import { translateAnnotation } from "./annotationGeometry"; import type { Point, Rect } from "./capture"; export type ToolId = @@ -107,7 +108,9 @@ export type SceneAction = | { type: "replace"; scene: AnnotationScene } | { type: "undo" } | { type: "redo" } - | { type: "reset" }; + | { type: "reset" } + /** Moves every drawing, in every undo step, so it stays put on screen when the capture area moves. */ + | { type: "shift"; dx: number; dy: number }; export const initialSceneHistory: SceneHistory = { past: [], @@ -175,5 +178,12 @@ export function sceneHistoryReducer(state: SceneHistory, action: SceneAction): S } case "reset": return initialSceneHistory; + case "shift": { + if (action.dx === 0 && action.dy === 0) return state; + const shift = (scene: AnnotationScene): AnnotationScene => scene.elements.length === 0 + ? scene + : { version: 1, elements: scene.elements.map((element) => translateAnnotation(element, action.dx, action.dy)) }; + return { past: state.past.map(shift), present: shift(state.present), future: state.future.map(shift) }; + } } } diff --git a/apps/desktop/src/domain/settings.test.ts b/apps/desktop/src/domain/settings.test.ts index 187681f..83d1d2d 100644 --- a/apps/desktop/src/domain/settings.test.ts +++ b/apps/desktop/src/domain/settings.test.ts @@ -185,20 +185,44 @@ describe("Snaphub settings", () => { }); describe("overlay motion", () => { - it("defaults older saved overlay settings to dim-rise", () => { + it("drops the motion choice saved by older versions", () => { const parsed = snaphubSettingsSchema.parse({ ...defaultSnaphubSettings, - overlay: { color: "#070807", opacity: 0.5 }, + overlay: { color: "#070807", opacity: 0.5, motion: "dim-rise" }, }); - expect(parsed.overlay.motion).toBe("dim-rise"); + expect(parsed.overlay).toEqual({ color: "#070807", opacity: 0.5 }); + }); +}); + +describe("toolbar placement", () => { + it("gives older settings every finishing action, enabled in the vertical toolbar", () => { + const olderToolbar = Object.fromEntries( + Object.entries(defaultSnaphubSettings.toolbar).filter(([key]) => key !== "actions" && key !== "verticalTools"), + ); + const parsed = snaphubSettingsSchema.parse({ ...defaultSnaphubSettings, toolbar: olderToolbar }); + expect(parsed.toolbar.verticalTools).toEqual([]); + expect(Object.values(parsed.toolbar.actions)).toHaveLength(7); + expect(Object.values(parsed.toolbar.actions).every((action) => action.enabled && action.placement === "vertical")).toBe(true); + }); + + it("fills in an action added after the settings were saved", () => { + const withoutPin = Object.fromEntries(Object.entries(defaultSnaphubSettings.toolbar.actions).filter(([key]) => key !== "pin")); + const parsed = snaphubSettingsSchema.parse({ + ...defaultSnaphubSettings, + toolbar: { ...defaultSnaphubSettings.toolbar, actions: { ...withoutPin, save: { enabled: false, placement: "horizontal" } } }, + }); + expect(parsed.toolbar.actions.pin).toEqual({ enabled: true, placement: "vertical" }); + expect(parsed.toolbar.actions.save).toEqual({ enabled: false, placement: "horizontal" }); }); - it("rejects unknown motion values", () => { - expect(() => - snaphubSettingsSchema.parse({ - ...defaultSnaphubSettings, - overlay: { ...defaultSnaphubSettings.overlay, motion: "bounce" }, - }), - ).toThrow(); + it("rejects an unknown placement or tool", () => { + expect(snaphubSettingsSchema.safeParse({ + ...defaultSnaphubSettings, + toolbar: { ...defaultSnaphubSettings.toolbar, actions: { ...defaultSnaphubSettings.toolbar.actions, copy: { enabled: true, placement: "diagonal" } } }, + }).success).toBe(false); + expect(snaphubSettingsSchema.safeParse({ + ...defaultSnaphubSettings, + toolbar: { ...defaultSnaphubSettings.toolbar, verticalTools: ["laser"] }, + }).success).toBe(false); }); }); diff --git a/apps/desktop/src/domain/settings.ts b/apps/desktop/src/domain/settings.ts index 372f9ae..99b69cb 100644 --- a/apps/desktop/src/domain/settings.ts +++ b/apps/desktop/src/domain/settings.ts @@ -134,8 +134,48 @@ const toolbarIndividualSchema = z.object({ redo: z.boolean(), }); -export const overlayMotionValues = ["dim-rise", "fade-in", "fade-both"] as const; -export type OverlayMotion = (typeof overlayMotionValues)[number]; +/** Buttons that finish a capture; by default they sit in the vertical rail. */ +export const completionActionIds = [ + "copy", + "copy-and-save", + "save", + "pin", + "showcase", + "copy-text", + "find-sensitive", +] as const; +export type CompletionActionId = (typeof completionActionIds)[number]; + +export const toolbarPlacementValues = ["horizontal", "vertical"] as const; +export type ToolbarPlacement = (typeof toolbarPlacementValues)[number]; + +const completionActionSettingSchema = z.object({ + enabled: z.boolean(), + placement: z.enum(toolbarPlacementValues), +}); +export type CompletionActionSetting = z.infer; + +const defaultActionSetting: CompletionActionSetting = { enabled: true, placement: "vertical" }; + +export const defaultToolbarActions: Record = { + copy: defaultActionSetting, + "copy-and-save": defaultActionSetting, + save: defaultActionSetting, + pin: defaultActionSetting, + showcase: defaultActionSetting, + "copy-text": defaultActionSetting, + "find-sensitive": defaultActionSetting, +}; + +const toolbarActionsSchema = z.object({ + copy: completionActionSettingSchema.default(defaultActionSetting), + "copy-and-save": completionActionSettingSchema.default(defaultActionSetting), + save: completionActionSettingSchema.default(defaultActionSetting), + pin: completionActionSettingSchema.default(defaultActionSetting), + showcase: completionActionSettingSchema.default(defaultActionSetting), + "copy-text": completionActionSettingSchema.default(defaultActionSetting), + "find-sensitive": completionActionSettingSchema.default(defaultActionSetting), +}); export const snaphubSettingsSchema = z.object({ version: z.literal(1), @@ -158,6 +198,10 @@ export const snaphubSettingsSchema = z.object({ mode: z.enum(["individual", "group"]).default("group"), individual: toolbarIndividualSchema.default(defaultToolbarIndividual), groups: z.array(z.array(captureToolbarToolIdSchema).max(16)).max(8).default(defaultToolbarGroups), + /** Finishing actions: shown or hidden, and which toolbar holds them. */ + actions: toolbarActionsSchema.default(defaultToolbarActions), + /** Individual-mode editing tools moved into the vertical rail. */ + verticalTools: z.array(captureToolbarToolIdSchema).max(16).default([]), }), shortcuts: z.object({ capture: z.string().min(1).max(64), @@ -191,7 +235,6 @@ export const snaphubSettingsSchema = z.object({ overlay: z.object({ color: hexColorSchema, opacity: z.number().min(0.15).max(0.85), - motion: z.enum(overlayMotionValues).default("dim-rise"), }), openAtStartup: z.boolean(), updates: z.object({ autoCheck: z.boolean() }).default({ autoCheck: true }), @@ -256,6 +299,8 @@ export const defaultSnaphubSettings: SnaphubSettings = { mode: "group", individual: defaultToolbarIndividual, groups: defaultToolbarGroups, + actions: defaultToolbarActions, + verticalTools: [], }, shortcuts: { capture: "Alt+Shift+S", @@ -270,7 +315,7 @@ export const defaultSnaphubSettings: SnaphubSettings = { onScreen: defaultOnScreenSettings, detection: { windows: true, uiRegions: false }, scrolling: { defaultMode: "automatic" }, - overlay: { color: "#070807", opacity: 0.64, motion: "dim-rise" }, + overlay: { color: "#070807", opacity: 0.64 }, openAtStartup: false, updates: { autoCheck: true }, cursor: { enabled: true, style: "crosshair", size: "medium" }, diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts index 0c8b00c..13ab8a7 100644 --- a/apps/desktop/src/lib/tauri.ts +++ b/apps/desktop/src/lib/tauri.ts @@ -3,7 +3,7 @@ import { listen } from "@tauri-apps/api/event"; import type { UnlistenFn } from "@tauri-apps/api/event"; import { z } from "zod"; import type { AnnotationScene } from "../domain/annotations"; -import type { OverlayMotion, SnaphubSettings } from "../domain/settings"; +import type { SnaphubSettings } from "../domain/settings"; import { updateStatusSchema, type UpdateStatus } from "../domain/updates"; import { mediaFileSchema, @@ -118,12 +118,9 @@ export async function requestCapture(): Promise { }; } -export async function showCaptureSurface( - motion: OverlayMotion = "fade-in", - reducedMotion = false, -): Promise { +export async function showCaptureSurface(reducedMotion = false): Promise { if (!isTauri()) return; - await invoke("show_capture_surface", { motion, reducedMotion }); + await invoke("show_capture_surface", { reducedMotion }); } export async function requestOnScreenSession(): Promise { @@ -233,11 +230,10 @@ export async function retryCaptureSave(sessionId: string): Promise { if (!isTauri()) return; - await invoke("cancel_capture", { sessionId, motion, reducedMotion }); + await invoke("cancel_capture", { sessionId, reducedMotion }); } type ScrollingMode = "automatic" | "manual-start" | "manual-add"; diff --git a/docs/current-status.md b/docs/current-status.md index 386ceff..5529b3a 100644 --- a/docs/current-status.md +++ b/docs/current-status.md @@ -43,7 +43,9 @@ This document records what exists in the runtime today. The roadmap remains the - **Implemented:** One CapKit process. A second launch focuses the dashboard instead of starting another (release builds; `tauri-plugin-single-instance` pinned to 2.4.5 for the same `webview2-com` reason as the updater). - **Implemented:** Folder paths shown in Settings drop the Windows `\\?\` prefix. - **Implemented:** Screenshots page: a Copy button on every card, Copy in the context menu, Ctrl+C on a focused card, and drag a card out to another app (native file drag after 5 px of movement). -- **Implemented:** Overlay motion setting: Dim and rise (default), Fade in, or Fade in and out. Reduced motion skips every animation. +- **Implemented:** The capture overlay fades in and out; reduced motion skips it. The earlier overlay motion setting was removed. +- **Implemented:** Settings → Screenshots shows or hides each finishing action and places each Individual-mode tool and each action in the horizontal or vertical toolbar. Group mode keeps groups horizontal. +- **Implemented:** Annotations stay fixed on screen when the selection is moved or resized. - **Implemented:** Capture toolbar is one card. Individual mode shows a style row only for tools that have style. Group mode opens on click, remembers the last tool per group, and Escape closes the open row before it cancels the capture. The toolbar is positioned from its measured size. - **Implemented, signing key pending:** In-app updates. Launch check, sidebar notice, tray item, Settings → General → Updates. The release workflow publishes the signed installer, its `.sig` and `latest.json`. Until the updater key pair exists, `tauri.conf.json` holds a placeholder public key and `release.yml` stops early. - **Investigated, not fixed:** The pointer that sometimes does not move over the overlay. See the implementation report in `docs/specs/enhancements-and-fixes.md`. From ca91ad9c1dcdf93bd6caff67db8e412bcffe82d6 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 16:00:13 +0530 Subject: [PATCH 03/18] fix(detection): wake Chromium page accessibility before scanning Chromium leaves web pages out of its accessibility tree until an assistive tool asks for them, so detection only saw the browser's own toolbar. Send the standard accessibility request to each page window (Chrome_RenderWidgetHostHWND) before scanning, which also covers Edge, Electron and WebView2 apps, and rescan on later hovers while the page tree is still filling in. Co-Authored-By: Claude Opus 5.5 --- .../src-tauri/src/platform/windows_ui.rs | 73 ++++++++++++++++--- .../src-tauri/src/platform/xcap_backend.rs | 22 +++++- 2 files changed, 84 insertions(+), 11 deletions(-) diff --git a/apps/desktop/src-tauri/src/platform/windows_ui.rs b/apps/desktop/src-tauri/src/platform/windows_ui.rs index 67e9e97..c28f8f8 100644 --- a/apps/desktop/src-tauri/src/platform/windows_ui.rs +++ b/apps/desktop/src-tauri/src/platform/windows_ui.rs @@ -34,27 +34,31 @@ const MAX_LAYOUT_CONTAINER_RATIO: f64 = 0.9; // Nested elements (a wrapper
around a single child) frequently share an // identical bounding rect; keep only one of each near-duplicate. const DEDUPE_TOLERANCE: f64 = 2.0; -// Chromium/Firefox activate their full accessibility tree lazily, in response to the -// first UIA query (WM_GETOBJECT). An immediate scan of a browser window often only -// sees the frame chrome, so we retry briefly if too few candidates come back, and -// the caller rescans later if the result is still thin (see `UiScan::provisional`). +// Chromium (Chrome, Edge, Electron, WebView2) leaves a web page out of its +// accessibility tree until an assistive tool asks for it (see `wake_web_content`). +// The tree then fills in asynchronously, so we retry briefly if too few candidates +// come back, and the caller rescans on later hovers while the result keeps growing +// (see `UiScan::provisional`). const BROWSER_WINDOW_CLASSES: [&str; 2] = ["Chrome_WidgetWin_1", "MozillaWindowClass"]; +// The child window that hosts a Chromium web page. +const WEB_CONTENT_CLASS: &str = "Chrome_RenderWidgetHostHWND"; const BROWSER_SCAN_MIN_REGIONS: usize = 6; const BROWSER_SCAN_RETRIES: u32 = 1; const BROWSER_SCAN_RETRY_DELAY: Duration = Duration::from_millis(150); -/// The result of one scan. A browser scan that found almost nothing is -/// provisional: the browser was probably still building its accessibility tree, -/// so the caller should scan again on a later hover instead of keeping it. +/// The result of one scan. A scan of a window that shows web content is +/// provisional: the page may still be building its accessibility tree after we +/// asked for it, so the caller should scan again on a later hover. pub struct UiScan { pub regions: Vec, pub provisional: bool, } pub fn scan_window(window_id: u32) -> Result { - let browser = is_browser_window(window_id); + let pages = wake_web_content(window_id); + let browser = pages > 0 || is_browser_window(window_id); let regions = regions_for_window(window_id, browser)?; - let provisional = browser && regions.len() < BROWSER_SCAN_MIN_REGIONS; + let provisional = browser; Ok(UiScan { regions, provisional, @@ -354,6 +358,57 @@ fn clip_rect(rect: Rect, clip: Rect) -> Option { }) } +/// Chromium (Chrome, Edge, Electron, WebView2) only builds a web page's +/// accessibility tree after an assistive tool asks for it. A UI Automation +/// query on the top-level window isn't enough; the standard request +/// (WM_GETOBJECT for the client object) sent to the page's own child window +/// is. The tree then fills in asynchronously. Returns how many page windows +/// were asked. +fn wake_web_content(window_id: u32) -> usize { + use windows::Win32::{ + Foundation::{LPARAM, WPARAM}, + UI::WindowsAndMessaging::{ + EnumChildWindows, OBJID_CLIENT, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_GETOBJECT, + }, + }; + + unsafe extern "system" fn collect(child: HWND, found: LPARAM) -> windows::core::BOOL { + // SAFETY: `found` is the address of the Vec passed below, alive for the whole enumeration. + let found = unsafe { &mut *(found.0 as *mut Vec) }; + let mut buffer = [0u16; 64]; + let length = unsafe { GetClassNameW(child, &mut buffer) }; + if length > 0 && String::from_utf16_lossy(&buffer[..length as usize]) == WEB_CONTENT_CLASS { + found.push(child); + } + true.into() + } + + let parent = HWND(window_id as usize as *mut c_void); + let mut pages: Vec = Vec::new(); + unsafe { + let _ = EnumChildWindows( + Some(parent), + Some(collect), + LPARAM(&mut pages as *mut Vec as isize), + ); + } + for page in &pages { + let mut result = 0usize; + unsafe { + SendMessageTimeoutW( + *page, + WM_GETOBJECT, + WPARAM(0), + LPARAM(OBJID_CLIENT.0 as isize), + SMTO_ABORTIFHUNG, + 200, + Some(&mut result), + ); + } + } + pages.len() +} + fn rects_nearly_equal(left: &Rect, right: &Rect) -> bool { (left.x - right.x).abs() <= DEDUPE_TOLERANCE && (left.y - right.y).abs() <= DEDUPE_TOLERANCE diff --git a/apps/desktop/src-tauri/src/platform/xcap_backend.rs b/apps/desktop/src-tauri/src/platform/xcap_backend.rs index 9d8aa1d..44ce317 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -31,6 +31,12 @@ struct CachedUiRegions { attempts: u8, } +/// A web page's accessibility tree fills in after we ask for it. Keep +/// rescanning while each scan finds more than the last; stop once it settles. +fn still_filling(provisional: bool, previous_count: Option, count: usize) -> bool { + provisional && previous_count.is_none_or(|previous| count > previous) +} + impl CachedUiRegions { fn needs_rescan(&self, now: std::time::Instant) -> bool { self.provisional @@ -187,13 +193,17 @@ impl TargetDetectionBackend for XcapPlatformBackend { .get(&window_id) .is_none_or(|cached| cached.needs_rescan(now)); if stale { - let attempts = cache.get(&window_id).map_or(0, |cached| cached.attempts); + let previous = cache.get(&window_id); + let attempts = previous.map_or(0, |cached| cached.attempts); + let previous_count = previous.map(|cached| cached.regions.len()); let scan = super::windows_ui::scan_window(window_id)?; + let provisional = + still_filling(scan.provisional, previous_count, scan.regions.len()); cache.insert( window_id, CachedUiRegions { regions: scan.regions, - provisional: scan.provisional, + provisional, scanned_at: now, attempts: attempts + 1, }, @@ -354,6 +364,14 @@ mod tests { } } + #[test] + fn keeps_rescanning_a_web_page_only_while_it_grows() { + assert!(still_filling(true, None, 66)); + assert!(still_filling(true, Some(66), 250)); + assert!(!still_filling(true, Some(250), 250)); + assert!(!still_filling(false, None, 300)); + } + #[test] fn rescans_a_thin_browser_scan_only_after_a_pause_and_a_few_times() { let start = std::time::Instant::now(); From 9492953049cc8435fe702d77d6e6b7c3347d388a Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 17:13:50 +0530 Subject: [PATCH 04/18] feat(extension): CapKit Inspector with spacing, styles and source location Adds the shared @snaphub/devtools-protocol package (protocol schemas, Markdown builders, moved sensitive-text matcher) and the MV3 CapKit Inspector extension: hover/lock overlay, measure, styles, accessibility and React source location, plus the background link and popup. Co-Authored-By: Claude Sonnet 5.5 --- apps/browser-extension/eslint.config.js | 22 ++ apps/browser-extension/package.json | 42 +++ apps/browser-extension/public/icons/128.png | Bin 0 -> 571 bytes apps/browser-extension/public/icons/16.png | Bin 0 -> 119 bytes apps/browser-extension/public/icons/48.png | Bin 0 -> 198 bytes apps/browser-extension/public/manifest.json | 20 ++ apps/browser-extension/src/background.ts | 163 +++++++++ apps/browser-extension/src/content/bridge.ts | 46 +++ .../src/content/component.test.ts | 70 ++++ .../src/content/component.ts | 91 +++++ .../src/content/contrast.test.ts | 27 ++ .../browser-extension/src/content/contrast.ts | 48 +++ apps/browser-extension/src/content/dom.ts | 184 ++++++++++ .../src/content/findSensitive.test.ts | 50 +++ .../src/content/findSensitive.ts | 66 ++++ .../browser-extension/src/content/handlers.ts | 100 ++++++ .../src/content/hitTest.test.ts | 39 ++ apps/browser-extension/src/content/hitTest.ts | 59 ++++ .../src/content/inspector/controller.ts | 332 ++++++++++++++++++ .../src/content/inspector/dom.ts | 24 ++ .../src/content/inspector/overlay.ts | 137 ++++++++ .../src/content/inspector/panel.ts | 214 +++++++++++ .../src/content/inspector/styles.ts | 49 +++ .../browser-extension/src/content/isolated.ts | 32 ++ .../src/content/main-world.ts | 83 +++++ .../src/content/mainClient.ts | 88 +++++ .../src/content/measure.test.ts | 19 + apps/browser-extension/src/content/measure.ts | 57 +++ .../src/content/source.test.ts | 87 +++++ apps/browser-extension/src/content/source.ts | 145 ++++++++ apps/browser-extension/src/geometry.test.ts | 39 ++ apps/browser-extension/src/geometry.ts | 41 +++ apps/browser-extension/src/link.test.ts | 180 ++++++++++ apps/browser-extension/src/link.ts | 216 ++++++++++++ apps/browser-extension/src/messages.ts | 68 ++++ .../src/popup/Popup.test.tsx | 103 ++++++ apps/browser-extension/src/popup/Popup.tsx | 200 +++++++++++ apps/browser-extension/src/popup/index.html | 12 + apps/browser-extension/src/popup/main.tsx | 27 ++ apps/browser-extension/src/popup/popup.css | 27 ++ apps/browser-extension/src/tabs.test.ts | 33 ++ apps/browser-extension/src/tabs.ts | 94 +++++ apps/browser-extension/src/test-setup.ts | 1 + apps/browser-extension/src/vite-env.d.ts | 1 + apps/browser-extension/tsconfig.json | 22 ++ apps/browser-extension/vitest.config.ts | 10 + apps/desktop/package.json | 1 + apps/desktop/src/lib/redactionPatterns.ts | 120 +------ package.json | 12 +- packages/devtools-protocol/eslint.config.js | 22 ++ packages/devtools-protocol/package.json | 29 ++ packages/devtools-protocol/src/index.ts | 3 + .../devtools-protocol/src/markdown.test.ts | 75 ++++ packages/devtools-protocol/src/markdown.ts | 209 +++++++++++ .../devtools-protocol/src/protocol.test.ts | 30 ++ packages/devtools-protocol/src/protocol.ts | 237 +++++++++++++ .../devtools-protocol/src/sensitive.test.ts | 26 ++ packages/devtools-protocol/src/sensitive.ts | 130 +++++++ packages/devtools-protocol/tsconfig.json | 22 ++ packages/devtools-protocol/vitest.config.ts | 5 + pnpm-lock.yaml | 139 ++++++++ pnpm-workspace.yaml | 1 + 62 files changed, 4316 insertions(+), 113 deletions(-) create mode 100644 apps/browser-extension/eslint.config.js create mode 100644 apps/browser-extension/package.json create mode 100644 apps/browser-extension/public/icons/128.png create mode 100644 apps/browser-extension/public/icons/16.png create mode 100644 apps/browser-extension/public/icons/48.png create mode 100644 apps/browser-extension/public/manifest.json create mode 100644 apps/browser-extension/src/background.ts create mode 100644 apps/browser-extension/src/content/bridge.ts create mode 100644 apps/browser-extension/src/content/component.test.ts create mode 100644 apps/browser-extension/src/content/component.ts create mode 100644 apps/browser-extension/src/content/contrast.test.ts create mode 100644 apps/browser-extension/src/content/contrast.ts create mode 100644 apps/browser-extension/src/content/dom.ts create mode 100644 apps/browser-extension/src/content/findSensitive.test.ts create mode 100644 apps/browser-extension/src/content/findSensitive.ts create mode 100644 apps/browser-extension/src/content/handlers.ts create mode 100644 apps/browser-extension/src/content/hitTest.test.ts create mode 100644 apps/browser-extension/src/content/hitTest.ts create mode 100644 apps/browser-extension/src/content/inspector/controller.ts create mode 100644 apps/browser-extension/src/content/inspector/dom.ts create mode 100644 apps/browser-extension/src/content/inspector/overlay.ts create mode 100644 apps/browser-extension/src/content/inspector/panel.ts create mode 100644 apps/browser-extension/src/content/inspector/styles.ts create mode 100644 apps/browser-extension/src/content/isolated.ts create mode 100644 apps/browser-extension/src/content/main-world.ts create mode 100644 apps/browser-extension/src/content/mainClient.ts create mode 100644 apps/browser-extension/src/content/measure.test.ts create mode 100644 apps/browser-extension/src/content/measure.ts create mode 100644 apps/browser-extension/src/content/source.test.ts create mode 100644 apps/browser-extension/src/content/source.ts create mode 100644 apps/browser-extension/src/geometry.test.ts create mode 100644 apps/browser-extension/src/geometry.ts create mode 100644 apps/browser-extension/src/link.test.ts create mode 100644 apps/browser-extension/src/link.ts create mode 100644 apps/browser-extension/src/messages.ts create mode 100644 apps/browser-extension/src/popup/Popup.test.tsx create mode 100644 apps/browser-extension/src/popup/Popup.tsx create mode 100644 apps/browser-extension/src/popup/index.html create mode 100644 apps/browser-extension/src/popup/main.tsx create mode 100644 apps/browser-extension/src/popup/popup.css create mode 100644 apps/browser-extension/src/tabs.test.ts create mode 100644 apps/browser-extension/src/tabs.ts create mode 100644 apps/browser-extension/src/test-setup.ts create mode 100644 apps/browser-extension/src/vite-env.d.ts create mode 100644 apps/browser-extension/tsconfig.json create mode 100644 apps/browser-extension/vitest.config.ts create mode 100644 packages/devtools-protocol/eslint.config.js create mode 100644 packages/devtools-protocol/package.json create mode 100644 packages/devtools-protocol/src/index.ts create mode 100644 packages/devtools-protocol/src/markdown.test.ts create mode 100644 packages/devtools-protocol/src/markdown.ts create mode 100644 packages/devtools-protocol/src/protocol.test.ts create mode 100644 packages/devtools-protocol/src/protocol.ts create mode 100644 packages/devtools-protocol/src/sensitive.test.ts create mode 100644 packages/devtools-protocol/src/sensitive.ts create mode 100644 packages/devtools-protocol/tsconfig.json create mode 100644 packages/devtools-protocol/vitest.config.ts diff --git a/apps/browser-extension/eslint.config.js b/apps/browser-extension/eslint.config.js new file mode 100644 index 0000000..bfc6e4c --- /dev/null +++ b/apps/browser-extension/eslint.config.js @@ -0,0 +1,22 @@ +import eslint from "@eslint/js"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { ignores: ["dist", "eslint.config.js", "scripts"] }, + eslint.configs.recommended, + ...tseslint.configs.strictTypeChecked, + ...tseslint.configs.stylisticTypeChecked, + { + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + "@typescript-eslint/consistent-type-definitions": ["error", "type"], + "@typescript-eslint/explicit-function-return-type": "error", + "@typescript-eslint/no-confusing-void-expression": "off", + }, + }, +); diff --git a/apps/browser-extension/package.json b/apps/browser-extension/package.json new file mode 100644 index 0000000..83c405e --- /dev/null +++ b/apps/browser-extension/package.json @@ -0,0 +1,42 @@ +{ + "name": "@snaphub/browser-extension", + "version": "0.3.0", + "private": true, + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "dev": "node scripts/build.mjs --watch", + "typecheck": "tsc -p tsconfig.json --pretty false", + "lint": "eslint . --max-warnings 0", + "lint:fix": "eslint . --fix --max-warnings 0", + "test": "vitest run" + }, + "dependencies": { + "@fontsource-variable/jetbrains-mono": "5.2.8", + "@fontsource-variable/plus-jakarta-sans": "5.2.8", + "@jridgewell/trace-mapping": "^0.3.31", + "@snaphub/devtools-protocol": "workspace:*", + "react": "^19.2.7", + "react-dom": "^19.2.7", + "zod": "^4.4.3" + }, + "devDependencies": { + "@eslint/js": "^9.39.5", + "@tailwindcss/vite": "^4.3.3", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.2", + "@testing-library/user-event": "^14.6.1", + "@types/chrome": "^0.1.40", + "@types/node": "^26.1.1", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.3", + "eslint": "^9.39.5", + "jsdom": "^29.1.1", + "tailwindcss": "^4.3.3", + "typescript": "^6.0.3", + "typescript-eslint": "^8.64.0", + "vite": "^8.1.5", + "vitest": "^4.1.10" + } +} diff --git a/apps/browser-extension/public/icons/128.png b/apps/browser-extension/public/icons/128.png new file mode 100644 index 0000000000000000000000000000000000000000..549fbd93bd6d624bcbf23305fe7437008a2e0187 GIT binary patch literal 571 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrU}ExgaSW-L^Y+roKo&y*m%y8h z70v(I63!MVH_ceOd-?Q9Q{I1guX#0le!TqJ1+(SKe(K6ptl7mD@Ygc4lzG7~;9z99$tWPl@DM?m9_Qz8_`tw{ zN$g_#Q2cw|vRC_AfS$qx4Zj4d8Ed-qpk27xoz4_h-&xSR%LUA`=>&)AUgC+=Q3F9XN1 z+>hI`866DbR=?ZD%E0n?%dch8j13pcXXpRaW8nDpdad<4Mg}MOx4Z5OGB`+l_>j)f kkT_v+JR`#dKfXOz^v{Mz&6He~3`!;pp00i_>zopr02ZUeX#fBK literal 0 HcmV?d00001 diff --git a/apps/browser-extension/public/icons/16.png b/apps/browser-extension/public/icons/16.png new file mode 100644 index 0000000000000000000000000000000000000000..2551d35e4ef8c1a08de8f479aeaaa80523e5b52b GIT binary patch literal 119 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`cAhSdAr*6yCrq1|uXM)Jr zB^gJu1a{7P*cNbJ ztspI)u6{1-oD!M"], + "commands": { + "toggle-inspector": { + "suggested_key": { "default": "Alt+Shift+I" }, + "description": "Inspect the page" + } + }, + "web_accessible_resources": [{ "resources": ["fonts/*"], "matches": [""] }] +} diff --git a/apps/browser-extension/src/background.ts b/apps/browser-extension/src/background.ts new file mode 100644 index 0000000..60c9dac --- /dev/null +++ b/apps/browser-extension/src/background.ts @@ -0,0 +1,163 @@ +import { PROTOCOL_VERSION, type AppMessage, type ExtensionMessage } from "@snaphub/devtools-protocol/protocol"; +import { Link, type SocketLike, type TokenStore } from "./link"; +import { backgroundRequestSchema, type LinkStatus, type PageRequest } from "./messages"; +import { activeTabs, askTab, injectMainWorld, matchTab, originPattern, siteAccessFor, type TabRef } from "./tabs"; + +const TOKEN_KEY = "capkitToken"; +const MAX_HIT_ELEMENTS = 12; +const MAX_INSPECT_ELEMENTS = 20; + +const store: TokenStore = { + get: async () => { + const value: unknown = (await chrome.storage.local.get(TOKEN_KEY))[TOKEN_KEY]; + return typeof value === "string" ? value : null; + }, + set: async (token) => { + await chrome.storage.local.set({ [TOKEN_KEY]: token }); + }, + clear: async () => { + await chrome.storage.local.remove(TOKEN_KEY); + }, +}; + +function browserInfo(): { name: string; version: string } { + const brands = (navigator as Navigator & { userAgentData?: { brands: { brand: string; version: string }[] } }).userAgentData?.brands; // userAgentData is not in the DOM lib + const named = brands?.find((b) => !/not.?a.?brand|chromium/i.test(b.brand)); + const chromium = brands?.find((b) => /chromium/i.test(b.brand)); + const pick = named ?? chromium; + return { name: pick?.brand ?? "Chromium", version: pick?.version ?? "" }; +} + +async function answer(message: AppMessage): Promise { + if (message.type !== "hitTest" && message.type !== "inspect" && message.type !== "findSensitive") return null; + const base = { v: PROTOCOL_VERSION, id: message.id } as const; + const fail = (status: "no-tab" | "no-access" | "mismatch" | "error"): ExtensionMessage => { + switch (message.type) { + case "hitTest": + return { ...base, type: "hitTestResult", status, elements: [] }; + case "inspect": + return { ...base, type: "inspectResult", status, elements: [] }; + case "findSensitive": + return { ...base, type: "findSensitiveResult", status, matches: [] }; + } + }; + + const tab = matchTab(message.windowTitle, await activeTabs()); + if (tab === null) return fail("no-tab"); + const info = { url: tab.url, title: tab.title }; + + let request: PageRequest; + switch (message.type) { + case "hitTest": + request = { kind: "hitTest", viewport: message.viewport, point: message.point }; + break; + case "inspect": + request = { + kind: "inspect", + viewport: message.viewport, + ...(message.point === undefined ? {} : { point: message.point }), + ...(message.area === undefined ? {} : { area: message.area }), + }; + break; + case "findSensitive": + request = { kind: "findSensitive", viewport: message.viewport, area: message.area }; + break; + } + + const result = await askTab(tab, request); + if (result.response === null) return fail(result.status === "ok" ? "error" : result.status); + const response = result.response; + if (response.kind === "hitTest" && message.type === "hitTest") { + return { ...base, type: "hitTestResult", status: response.status, tab: info, elements: response.elements.slice(0, MAX_HIT_ELEMENTS) }; + } + if (response.kind === "inspect" && message.type === "inspect") { + return { + ...base, + type: "inspectResult", + status: response.status, + tab: info, + ...(response.cssViewport === undefined ? {} : { cssViewport: response.cssViewport }), + elements: response.elements.slice(0, MAX_INSPECT_ELEMENTS), + }; + } + if (response.kind === "findSensitive" && message.type === "findSensitive") { + return { ...base, type: "findSensitiveResult", status: response.status, matches: response.matches }; + } + return fail("error"); +} + +const link = new Link({ + createSocket: (url): SocketLike => new WebSocket(url), + store, + browser: browserInfo(), + extensionVersion: chrome.runtime.getManifest().version, + handleRequest: answer, +}); + +async function currentTab(): Promise { + const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); + const tab = tabs[0]; + return tab?.id === undefined ? null : { id: tab.id, url: tab.url ?? "", title: tab.title ?? "" }; +} + +async function inspectActiveTab(): Promise { + const tab = await currentTab(); + if (tab === null) return false; + const result = await askTab(tab, { kind: "toggle" }); + return result.response !== null; +} + +async function dispatch(raw: unknown, sender: chrome.runtime.MessageSender): Promise { + const parsed = backgroundRequestSchema.safeParse(raw); + if (!parsed.success) return { ok: false }; + const request = parsed.data; + switch (request.kind) { + case "injectMain": { + const tabId = sender.tab?.id; + return { ok: tabId !== undefined && (await injectMainWorld(tabId)) }; + } + case "captureVisible": { + const windowId = sender.tab?.windowId; + if (windowId === undefined) return { ok: false }; + return { ok: true, dataUrl: await chrome.tabs.captureVisibleTab(windowId, { format: "png" }) }; + } + case "status": + return link.status satisfies LinkStatus; + case "pair": + link.pair(request.code); + return link.status; + case "retry": + link.retry(); + return link.status; + case "forget": + await link.forget(); + return link.status; + case "inspectActiveTab": + return { ok: await inspectActiveTab() }; + case "siteAccess": + return siteAccessFor(await currentTab()); + case "requestAccess": { + const tab = await currentTab(); + const origins = request.all ? [""] : [tab === null ? "" : (originPattern(tab.url) ?? "")]; + if (origins[0] === "") return { ok: false }; + return { ok: await chrome.permissions.request({ origins }) }; + } + } +} + +chrome.runtime.onMessage.addListener((message: unknown, sender, sendResponse) => { + void dispatch(message, sender).then(sendResponse); + return true; +}); + +chrome.commands.onCommand.addListener((command) => { + if (command === "toggle-inspector") void inspectActiveTab(); +}); + +chrome.runtime.onStartup.addListener(() => { + void link.connect(); +}); +chrome.runtime.onInstalled.addListener(() => { + void link.connect(); +}); +void link.connect(); diff --git a/apps/browser-extension/src/content/bridge.ts b/apps/browser-extension/src/content/bridge.ts new file mode 100644 index 0000000..7bc47d0 --- /dev/null +++ b/apps/browser-extension/src/content/bridge.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; +import { sourceUnavailableReasonSchema } from "@snaphub/devtools-protocol/protocol"; + +/** Attribute on the inspector host element carrying the per-injection channel name. */ +export const CHANNEL_ATTRIBUTE = "data-capkit-channel"; +/** Attribute placed on an element while the main world resolves it. */ +export const TARGET_ATTRIBUTE = "data-capkit-target"; +export const HOST_TAG = "capkit-inspector-host"; + +export const mainRequestSchema = z.strictObject({ id: z.string().min(1).max(40), target: z.string().min(1).max(40) }); +export type MainRequest = z.infer; + +export const mainReplySchema = z.strictObject({ + id: z.string().min(1).max(40), + component: z + .strictObject({ name: z.string().max(80), ownerPath: z.array(z.string().max(80)).max(6) }) + .nullable(), + source: z + .strictObject({ file: z.string().max(400), line: z.number().int(), column: z.number().int() }) + .nullable(), + reason: sourceUnavailableReasonSchema.optional(), +}); +export type MainReply = z.infer; + +export const replyEventName = (channel: string): string => `${channel}:reply`; + +/** Parses a JSON string from the other world. The page can observe or spoof it, so it is validated. */ +export function parseMainReply(raw: unknown): MainReply | null { + if (typeof raw !== "string" || raw.length > 20_000) return null; + try { + const parsed = mainReplySchema.safeParse(JSON.parse(raw)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +export function parseMainRequest(raw: unknown): MainRequest | null { + if (typeof raw !== "string" || raw.length > 2_000) return null; + try { + const parsed = mainRequestSchema.safeParse(JSON.parse(raw)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} diff --git a/apps/browser-extension/src/content/component.test.ts b/apps/browser-extension/src/content/component.test.ts new file mode 100644 index 0000000..2897d46 --- /dev/null +++ b/apps/browser-extension/src/content/component.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { componentName, debugSource, debugStack, describeComponent, findFiber, isMinifiedName } from "./component"; + +function Button(): null { + return null; +} +function Form(): null { + return null; +} + +describe("component names", () => { + it("reads displayName, name, render and memo types", () => { + expect(componentName(Button)).toBe("Button"); + expect(componentName({ displayName: "Styled" })).toBe("Styled"); + expect(componentName({ render: { name: "Forwarded" } })).toBe("Forwarded"); + expect(componentName({ type: { name: "Memoed" } })).toBe("Memoed"); + expect(componentName("div")).toBeNull(); + }); + + it("flags minified names", () => { + expect(isMinifiedName("a")).toBe(true); + expect(isMinifiedName("Zx")).toBe(true); + expect(isMinifiedName("Card")).toBe(false); + }); +}); + +describe("describeComponent", () => { + it("builds the owner path with the nearest component last", () => { + const app = { type: function App(): null { return null; } }; + const form = { type: Form, _debugOwner: app }; + const host = { type: "button", _debugOwner: { type: Button, _debugOwner: form } }; + expect(describeComponent(host)).toEqual({ name: "Button", ownerPath: ["App", "Form", "Button"] }); + }); + + it("falls back to walking .return when there is no debug owner", () => { + const host = { type: "div", return: { type: "span", return: { type: Form } } }; + expect(describeComponent(host)).toEqual({ name: "Form", ownerPath: ["Form"] }); + }); + + it("reports minified production builds", () => { + const host = { type: "div", _debugOwner: { type: function a(): null { return null; } } }; + expect(describeComponent(host)).toBe("minified"); + }); + + it("returns null without any owner", () => { + expect(describeComponent({ type: "div" })).toBeNull(); + }); +}); + +describe("fiber access", () => { + it("finds a fiber on the nearest ancestor", () => { + const parent = document.createElement("div"); + const child = document.createElement("span"); + parent.append(child); + Object.assign(parent, { __reactFiber$abc: { type: "div" } }); + expect(findFiber(child)).toEqual({ type: "div" }); + expect(findFiber(document.createElement("p"))).toBeNull(); + }); + + it("reads React 18 debug source and React 19 debug stack", () => { + expect(debugSource({ _debugSource: { fileName: "src/a.tsx", lineNumber: 4, columnNumber: 2 } })).toEqual({ + file: "src/a.tsx", + line: 4, + column: 2, + }); + expect(debugSource({})).toBeNull(); + expect(debugStack({ _debugStack: { stack: "Error\n at x" } })).toBe("Error\n at x"); + expect(debugStack({})).toBeNull(); + }); +}); diff --git a/apps/browser-extension/src/content/component.ts b/apps/browser-extension/src/content/component.ts new file mode 100644 index 0000000..dcba2f9 --- /dev/null +++ b/apps/browser-extension/src/content/component.ts @@ -0,0 +1,91 @@ +/** A minimal view of a React fiber; every field is read defensively because the page owns the object. */ +export type FiberLike = { + type?: unknown; + return?: FiberLike | null; + _debugOwner?: FiberLike | null; + _debugSource?: { fileName?: unknown; lineNumber?: unknown; columnNumber?: unknown } | null; + _debugStack?: { stack?: unknown } | null; +}; + +const MINIFIED_NAME = /^[a-zA-Z$_]{1,2}$/; + +function str(value: unknown): string | null { + return typeof value === "string" && value !== "" ? value : null; +} + +/** displayName ?? name for a function or object component type (including memo and forwardRef). */ +export function componentName(type: unknown): string | null { + if (typeof type !== "function" && (typeof type !== "object" || type === null)) return null; + const record = type as Record; // React component types are functions or plain objects; fields are probed with typeof. + const render = record.render as Record | undefined; + const inner = record.type as Record | undefined; + return ( + str(record.displayName) ?? + str(record.name) ?? + str(render?.displayName) ?? + str(render?.name) ?? + str(inner?.name) + ); +} + +export function isMinifiedName(name: string): boolean { + return MINIFIED_NAME.test(name); +} + +export function fiberKey(element: object): string | undefined { + return Object.keys(element).find((key) => key.startsWith("__reactFiber$")); +} + +/** Nearest fiber on the element or its ancestors. */ +export function findFiber(element: Element | null): FiberLike | null { + for (let node: Element | null = element; node !== null; node = node.parentElement) { + const key = fiberKey(node); + if (key !== undefined) return (node as unknown as Record)[key] ?? null; // key came from Object.keys of this node + } + return null; +} + +function ownerOf(fiber: FiberLike): FiberLike | null { + if (fiber._debugOwner) return fiber._debugOwner; + for (let next = fiber.return; next; next = next.return) { + if (typeof next.type === "function" || (typeof next.type === "object" && next.type !== null)) return next; + } + return null; +} + +export type ComponentInfo = { name: string; ownerPath: string[] }; + +/** The component that rendered the element, plus up to six named owners (nearest last). */ +export function describeComponent(hostFiber: FiberLike): ComponentInfo | "minified" | null { + const first = ownerOf(hostFiber); + if (first === null) return null; + const names: string[] = []; + let sawMinified = false; + for (let owner: FiberLike | null = first; owner !== null && names.length < 6; owner = ownerOf(owner)) { + const name = componentName(owner.type); + if (name === null) continue; + if (isMinifiedName(name)) { + sawMinified = true; + break; + } + names.push(name); + } + if (names.length === 0) return sawMinified ? "minified" : null; + const nearest = names[0] ?? ""; + const path = names.slice(0, 6).reverse(); + return { name: nearest, ownerPath: path }; +} + +/** The stack string where this host element's JSX was written (React 19), if present. */ +export function debugStack(fiber: FiberLike): string | null { + return str(fiber._debugStack?.stack); +} + +/** The React 18 _debugSource, if present. */ +export function debugSource(fiber: FiberLike): { file: string; line: number; column: number } | null { + const source = fiber._debugSource; + if (source === null || source === undefined) return null; + const file = str(source.fileName); + if (file === null || typeof source.lineNumber !== "number") return null; + return { file, line: source.lineNumber, column: typeof source.columnNumber === "number" ? source.columnNumber : 1 }; +} diff --git a/apps/browser-extension/src/content/contrast.test.ts b/apps/browser-extension/src/content/contrast.test.ts new file mode 100644 index 0000000..7c22d6a --- /dev/null +++ b/apps/browser-extension/src/content/contrast.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { contrastRatio, gradeContrast, over, parseColor } from "./contrast"; + +describe("contrast", () => { + it("computes black on white as 21", () => { + const black = parseColor("rgb(0, 0, 0)"); + const white = parseColor("rgb(255, 255, 255)"); + if (black === null || white === null) throw new Error("parse failed"); + expect(contrastRatio(black, white)).toBeCloseTo(21, 1); + }); + + it("composites translucent colours", () => { + const result = over({ r: 0, g: 0, b: 0, a: 0.5 }, { r: 255, g: 255, b: 255, a: 1 }); + expect(Math.round(result.r)).toBe(128); + }); + + it("grades by text size", () => { + expect(gradeContrast(7.5, false)).toBe("AAA"); + expect(gradeContrast(4.6, false)).toBe("AA"); + expect(gradeContrast(3.2, false)).toBe("Fail"); + expect(gradeContrast(3.2, true)).toBe("AA"); + }); + + it("returns null for non-rgb values", () => { + expect(parseColor("transparent")).toBeNull(); + }); +}); diff --git a/apps/browser-extension/src/content/contrast.ts b/apps/browser-extension/src/content/contrast.ts new file mode 100644 index 0000000..2e8f92d --- /dev/null +++ b/apps/browser-extension/src/content/contrast.ts @@ -0,0 +1,48 @@ +export type Rgba = { r: number; g: number; b: number; a: number }; + +/** Parses rgb()/rgba() computed colours. Returns null for anything else. */ +export function parseColor(value: string): Rgba | null { + const match = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(value.trim()); + if (match === null) return null; + const [, r = "0", g = "0", b = "0", alphaRaw] = match; + let a = 1; + if (alphaRaw !== undefined) { + a = alphaRaw.endsWith("%") ? Number.parseFloat(alphaRaw) / 100 : Number.parseFloat(alphaRaw); + } + return { r: Number(r), g: Number(g), b: Number(b), a }; +} + +function channel(value: number): number { + const s = value / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; +} + +export function luminance({ r, g, b }: Rgba): number { + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); +} + +/** WCAG contrast ratio between two opaque colours. */ +export function contrastRatio(foreground: Rgba, background: Rgba): number { + const a = luminance(foreground); + const b = luminance(background); + return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); +} + +/** Composites a translucent colour over an opaque background. */ +export function over(top: Rgba, bottom: Rgba): Rgba { + const a = top.a; + return { + r: top.r * a + bottom.r * (1 - a), + g: top.g * a + bottom.g * (1 - a), + b: top.b * a + bottom.b * (1 - a), + a: 1, + }; +} + +export type ContrastGrade = "AAA" | "AA" | "Fail"; + +export function gradeContrast(ratio: number, largeText: boolean): ContrastGrade { + if (ratio >= (largeText ? 4.5 : 7)) return "AAA"; + if (ratio >= (largeText ? 3 : 4.5)) return "AA"; + return "Fail"; +} diff --git a/apps/browser-extension/src/content/dom.ts b/apps/browser-extension/src/content/dom.ts new file mode 100644 index 0000000..5471048 --- /dev/null +++ b/apps/browser-extension/src/content/dom.ts @@ -0,0 +1,184 @@ +import type { ElementDetails } from "@snaphub/devtools-protocol/protocol"; +import type { CssRect } from "../geometry"; + +export function clip(value: string, max: number): string { + const collapsed = value.replace(/\s+/g, " ").trim(); + return collapsed.length > max ? collapsed.slice(0, max) : collapsed; +} + +function escapeIdent(value: string): string { + return value.replace(/[^a-zA-Z0-9_-]/g, (char) => `\\${char}`); +} + +const IMPLICIT_ROLES: Record = { + a: "link", + button: "button", + nav: "navigation", + main: "main", + header: "banner", + footer: "contentinfo", + aside: "complementary", + form: "form", + img: "img", + ul: "list", + ol: "list", + li: "listitem", + table: "table", + select: "combobox", + textarea: "textbox", + dialog: "dialog", + h1: "heading", + h2: "heading", + h3: "heading", + h4: "heading", + h5: "heading", + h6: "heading", +}; + +const INPUT_ROLES: Record = { + checkbox: "checkbox", + radio: "radio", + button: "button", + submit: "button", + reset: "button", + range: "slider", + search: "searchbox", + number: "spinbutton", +}; + +export function roleOf(element: Element): string | null { + const explicit = element.getAttribute("role"); + if (explicit !== null && explicit !== "") return clip(explicit, 60); + const tag = element.tagName.toLowerCase(); + if (tag === "input") return INPUT_ROLES[(element.getAttribute("type") ?? "text").toLowerCase()] ?? "textbox"; + if (tag === "a" && !element.hasAttribute("href")) return null; + return IMPLICIT_ROLES[tag] ?? null; +} + +export function accessibleName(element: Element): string { + const label = element.getAttribute("aria-label"); + if (label !== null && label.trim() !== "") return clip(label, 120); + const labelledBy = element.getAttribute("aria-labelledby"); + if (labelledBy !== null) { + const text = labelledBy + .split(/\s+/) + .map((id) => element.ownerDocument.getElementById(id)?.textContent ?? "") + .join(" "); + if (text.trim() !== "") return clip(text, 120); + } + const alt = element.getAttribute("alt"); + if (alt !== null && alt.trim() !== "") return clip(alt, 120); + if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) { + const labels = element.labels; + const first = labels?.[0]; + if (first !== undefined && first.textContent.trim() !== "") return clip(first.textContent, 120); + const placeholder = element.getAttribute("placeholder"); + if (placeholder !== null) return clip(placeholder, 120); + } + const role = roleOf(element); + if (role === "button" || role === "link" || role === "heading") return clip(element.textContent, 120); + const title = element.getAttribute("title"); + return title === null ? "" : clip(title, 120); +} + +/** A readable CSS selector, up to four levels, stopping at the nearest id. */ +export function selectorFor(element: Element): string { + const parts: string[] = []; + let node: Element | null = element; + while (node !== null && node.tagName.toLowerCase() !== "html" && parts.length < 4) { + const tag = node.tagName.toLowerCase(); + if (node.id !== "") { + parts.unshift(`${tag}#${escapeIdent(node.id)}`); + break; + } + const firstClass = [...node.classList].find((name) => /^[a-zA-Z_-][\w-]*$/.test(name) && name.length < 30); + let part = firstClass === undefined ? tag : `${tag}.${escapeIdent(firstClass)}`; + const parent: Element | null = node.parentElement; + if (parent !== null && firstClass === undefined) { + const same = [...parent.children].filter((child) => child.tagName === node?.tagName); + if (same.length > 1) part += `:nth-of-type(${String(same.indexOf(node) + 1)})`; + } + parts.unshift(part); + node = parent; + } + return parts.join(" > "); +} + +/** A stable short hash of a selector, used as the hit-test key. */ +export function hashKey(selector: string): string { + let hash = 2166136261; + for (let index = 0; index < selector.length; index += 1) { + hash ^= selector.charCodeAt(index); + hash = Math.imul(hash, 16777619); + } + return (hash >>> 0).toString(36); +} + +export function shortLabel(element: Element): string { + const tag = element.tagName.toLowerCase(); + const id = element.id === "" ? "" : `#${element.id}`; + const firstClass = [...element.classList][0]; + const cls = firstClass === undefined ? "" : `.${firstClass}`; + const role = roleOf(element); + const name = accessibleName(element); + if (id !== "" || cls !== "") return clip(`${tag}${id}${cls}`, 80); + if (role !== null && name !== "") return clip(`${role} "${name}"`, 80); + return tag; +} + +export function rectOf(element: Element): CssRect { + const { x, y, width, height } = element.getBoundingClientRect(); + return { x, y, width, height }; +} + +export function readStyles(element: Element): ElementDetails["styles"] { + const style = getComputedStyle(element); + const gap = style.getPropertyValue("gap"); + return { + color: clip(style.color, 120), + backgroundColor: clip(style.backgroundColor, 120), + fontFamily: clip(style.fontFamily, 120), + fontSize: clip(style.fontSize, 120), + fontWeight: clip(style.fontWeight, 120), + lineHeight: clip(style.lineHeight, 120), + padding: clip(style.padding, 120), + margin: clip(style.margin, 120), + borderRadius: clip(style.borderRadius, 120), + boxShadow: clip(style.boxShadow, 120), + display: clip(style.display, 120), + gap: clip(gap, 120), + }; +} + +export type ComponentData = { + component: ElementDetails["component"]; + source: ElementDetails["source"]; + sourceUnavailableReason?: ElementDetails["sourceUnavailableReason"]; +}; + +/** Everything about an element except its viewport rect, which depends on the request's scale. */ +export function describeElement( + element: Element, + rect: ElementDetails["rect"], + componentData: ComponentData, +): ElementDetails { + const css = rectOf(element); + const label = componentData.component?.name ?? shortLabel(element); + return { + label: clip(label, 80), + tag: element.tagName.toLowerCase(), + role: roleOf(element), + accessibleName: accessibleName(element), + text: clip(element.textContent, 200), + selector: clip(selectorFor(element), 300), + component: componentData.component, + source: componentData.source, + ...(componentData.sourceUnavailableReason === undefined + ? {} + : { sourceUnavailableReason: componentData.sourceUnavailableReason }), + classes: clip(element.getAttribute("class") ?? "", 400), + styles: readStyles(element), + cssRect: { x: css.x, y: css.y, width: css.width, height: css.height }, + rect, + }; +} diff --git a/apps/browser-extension/src/content/findSensitive.test.ts b/apps/browser-extension/src/content/findSensitive.test.ts new file mode 100644 index 0000000..be975d7 --- /dev/null +++ b/apps/browser-extension/src/content/findSensitive.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { findSensitiveInArea } from "./findSensitive"; + +const area = { x: 0, y: 0, width: 800, height: 600 }; + +function stubRects(target: Element, rect: { x: number; y: number; width: number; height: number }): void { + const dom = { ...rect, top: rect.y, left: rect.x, right: rect.x + rect.width, bottom: rect.y + rect.height, toJSON: (): object => ({}) }; + target.getBoundingClientRect = (): DOMRect => dom; +} + +afterEach(() => { + document.body.replaceChildren(); +}); + +describe("findSensitiveInArea", () => { + it("finds an email in a paragraph using range rects", () => { + const p = document.createElement("p"); + p.textContent = "Contact test@example.com today"; + document.body.append(p); + const rect = { x: 50, y: 20, width: 120, height: 16, top: 20, left: 50, right: 170, bottom: 36, toJSON: (): object => ({}) }; + Range.prototype.getClientRects = (): DOMRectList => Object.assign([rect], { item: (i: number) => (i === 0 ? rect : null) }); // jsdom lacks layout; DOMRectList is array-like + const matches = findSensitiveInArea(document, area, { scale: 2 }); + expect(matches).toHaveLength(1); + expect(matches[0]).toMatchObject({ kind: "email", rects: [{ x: 100, y: 40, width: 240, height: 32 }] }); + expect(matches[0]?.preview).not.toContain("example"); + }); + + it("reports a filled password field and ignores an empty one", () => { + const filled = document.createElement("input"); + filled.type = "password"; + filled.value = "hunter2hunter2"; + const empty = document.createElement("input"); + empty.type = "password"; + document.body.append(filled, empty); + stubRects(filled, { x: 10, y: 10, width: 200, height: 30 }); + stubRects(empty, { x: 10, y: 60, width: 200, height: 30 }); + Range.prototype.getClientRects = (): DOMRectList => Object.assign([], { item: () => null }); // no text rects needed here + const matches = findSensitiveInArea(document, area, { scale: 1 }); + expect(matches).toEqual([{ kind: "password", preview: "••••••••", rects: [{ x: 10, y: 10, width: 200, height: 30 }] }]); + }); + + it("skips fields outside the area", () => { + const field = document.createElement("input"); + field.type = "password"; + field.value = "secret-password"; + document.body.append(field); + stubRects(field, { x: 1000, y: 1000, width: 100, height: 30 }); + expect(findSensitiveInArea(document, area, { scale: 1 })).toEqual([]); + }); +}); diff --git a/apps/browser-extension/src/content/findSensitive.ts b/apps/browser-extension/src/content/findSensitive.ts new file mode 100644 index 0000000..05dd309 --- /dev/null +++ b/apps/browser-extension/src/content/findSensitive.ts @@ -0,0 +1,66 @@ +import type { SensitiveMatch } from "@snaphub/devtools-protocol/protocol"; +import { findSensitiveSpans, maskPreview } from "@snaphub/devtools-protocol/sensitive"; +import { rectsIntersect, toViewportRect, type CssRect, type Scale } from "../geometry"; + +const MAX_MATCHES = 200; +const MAX_RECTS = 40; +const SKIPPED_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"]); +const PASSWORD_MASK = "••••••••"; + +function visible(element: Element): boolean { + const check = Reflect.get(element, "checkVisibility") as ((options?: object) => boolean) | undefined; // not in every DOM lib; absent in jsdom + return typeof check === "function" ? check.call(element, { visibilityProperty: true }) : true; +} + +function toRect(rect: DOMRect): CssRect { + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; +} + +function rangeRects(node: Text, start: number, end: number, area: CssRect, scale: Scale): SensitiveMatch["rects"] { + const range = node.ownerDocument.createRange(); + range.setStart(node, start); + range.setEnd(node, end); + const rects: SensitiveMatch["rects"] = []; + for (const rect of range.getClientRects()) { + const css = toRect(rect); + if (css.width > 0 && css.height > 0 && rectsIntersect(css, area)) rects.push(toViewportRect(css, scale)); + if (rects.length >= MAX_RECTS) break; + } + return rects; +} + +/** Finds sensitive text and filled password fields inside a CSS-px area; rects are in physical viewport px. */ +export function findSensitiveInArea(doc: Document, area: CssRect, scale: Scale): SensitiveMatch[] { + const matches: SensitiveMatch[] = []; + + const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT); + for (let node = walker.nextNode(); node !== null && matches.length < MAX_MATCHES; node = walker.nextNode()) { + if (!(node instanceof Text)) continue; + const parent = node.parentElement; + if (parent === null || SKIPPED_TAGS.has(parent.tagName) || !visible(parent)) continue; + const text = node.data; + if (text.trim().length < 5) continue; + for (const span of findSensitiveSpans(text)) { + const rects = rangeRects(node, span.start, span.end, area, scale); + if (rects.length === 0) continue; + matches.push({ kind: span.kind, preview: maskPreview(text.slice(span.start, span.end)), rects }); + } + } + + for (const field of doc.querySelectorAll("input, textarea")) { + if (matches.length >= MAX_MATCHES) break; + if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue; + if (field.value === "" || !visible(field)) continue; + const css = toRect(field.getBoundingClientRect()); + if (!rectsIntersect(css, area)) continue; + const rect = toViewportRect(css, scale); + if (field instanceof HTMLInputElement && field.type === "password") { + matches.push({ kind: "password", preview: PASSWORD_MASK, rects: [rect] }); + continue; + } + for (const span of findSensitiveSpans(field.value)) { + matches.push({ kind: span.kind, preview: maskPreview(field.value.slice(span.start, span.end)), rects: [rect] }); + } + } + return matches.slice(0, MAX_MATCHES); +} diff --git a/apps/browser-extension/src/content/handlers.ts b/apps/browser-extension/src/content/handlers.ts new file mode 100644 index 0000000..d8f72a8 --- /dev/null +++ b/apps/browser-extension/src/content/handlers.ts @@ -0,0 +1,100 @@ +import type { ElementDetails, HitElement } from "@snaphub/devtools-protocol/protocol"; +import { computeScale, rectsIntersect, toCssPoint, toCssRect, toViewportRect, type CssRect, type Scale } from "../geometry"; +import type { PageRequest, PageResponse } from "../messages"; +import { describeElement, rectOf, type ComponentData } from "./dom"; +import { hitElements } from "./hitTest"; +import type { ComponentResolver } from "./mainClient"; +import { findSensitiveInArea } from "./findSensitive"; + +const MAX_AREA_ELEMENTS = 20; +const MIN_AREA_ELEMENT_CSS_PX = 6; +const CONTAINMENT_SLOP_CSS_PX = 4; + +type Env = { window: Window; document: Document; resolve: ComponentResolver }; + +const NO_DATA: ComponentData = { component: null, source: null }; + +function guard(env: Env, viewport: { x: number; y: number; width: number; height: number }): Scale | null { + return computeScale(viewport, env.window.innerWidth, env.window.innerHeight); +} + +/** Elements fully inside the area, largest first, without same-rect duplicates. */ +export function elementsInArea(doc: Document, area: CssRect): Element[] { + const picked: { element: Element; rect: CssRect }[] = []; + for (const element of doc.body.querySelectorAll("*")) { + const rect = rectOf(element); + if (rect.width < MIN_AREA_ELEMENT_CSS_PX || rect.height < MIN_AREA_ELEMENT_CSS_PX) continue; + if (!rectsIntersect(rect, area)) continue; + const inside = + rect.x >= area.x - CONTAINMENT_SLOP_CSS_PX && + rect.y >= area.y - CONTAINMENT_SLOP_CSS_PX && + rect.x + rect.width <= area.x + area.width + CONTAINMENT_SLOP_CSS_PX && + rect.y + rect.height <= area.y + area.height + CONTAINMENT_SLOP_CSS_PX; + if (!inside) continue; + const parent = picked[picked.length - 1]; + if ( + parent !== undefined && + Math.abs(parent.rect.width - rect.width) <= 1 && + Math.abs(parent.rect.height - rect.height) <= 1 && + parent.element.contains(element) + ) { + picked.pop(); + } + picked.push({ element, rect }); + } + return picked + .sort((a, b) => b.rect.width * b.rect.height - a.rect.width * a.rect.height) + .slice(0, MAX_AREA_ELEMENTS) + .map((entry) => entry.element); +} + +async function details(env: Env, element: Element, scale: Scale): Promise { + const data = await env.resolve(element).catch(() => NO_DATA); + return describeElement(element, toViewportRect(rectOf(element), scale), data); +} + +export function handlePageRequest(env: Env, request: PageRequest): Promise { + switch (request.kind) { + case "hitTest": { + const scale = guard(env, request.viewport); + if (scale === null) return Promise.resolve({ kind: "hitTest", status: "mismatch", elements: [] }); + const css = toCssPoint(request.point, scale); + const elements: HitElement[] = hitElements(env.document, css, scale, () => null); + return Promise.resolve({ kind: "hitTest", status: "ok", elements }); + } + case "inspect": { + const scale = guard(env, request.viewport); + if (scale === null) return Promise.resolve({ kind: "inspect", status: "mismatch", elements: [] }); + return (async (): Promise => { + const targets: Element[] = []; + if (request.point !== undefined) { + const css = toCssPoint(request.point, scale); + const first = env.document.elementFromPoint(css.x, css.y); + if (first !== null) targets.push(first); + } else if (request.area !== undefined) { + targets.push(...elementsInArea(env.document, toCssRect(request.area, scale))); + } + const elements = await Promise.all(targets.map((element) => details(env, element, scale))); + return { + kind: "inspect", + status: "ok", + cssViewport: { + width: env.window.innerWidth, + height: env.window.innerHeight, + devicePixelRatio: env.window.devicePixelRatio, + }, + elements, + }; + })(); + } + case "findSensitive": { + const scale = guard(env, request.viewport); + if (scale === null) return Promise.resolve({ kind: "findSensitive", status: "mismatch", matches: [] }); + const matches = findSensitiveInArea(env.document, toCssRect(request.area, scale), scale); + return Promise.resolve({ kind: "findSensitive", status: "ok", matches }); + } + case "toggle": + case "ping": + return Promise.resolve({ kind: "ok" }); + } +} diff --git a/apps/browser-extension/src/content/hitTest.test.ts b/apps/browser-extension/src/content/hitTest.test.ts new file mode 100644 index 0000000..de44d88 --- /dev/null +++ b/apps/browser-extension/src/content/hitTest.test.ts @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hitCandidates, hitElements } from "./hitTest"; + +function box(parent: Element, x: number, y: number, width: number, height: number, style = ""): HTMLElement { + const element = document.createElement("div"); + element.setAttribute("style", style); + element.getBoundingClientRect = (): DOMRect => ({ x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON: () => ({}) }); + parent.append(element); + return element; +} + +afterEach(() => { + document.body.replaceChildren(); +}); + +describe("hit test filtering", () => { + it("drops tiny elements, display:contents and same-rect parents", () => { + const card = box(document.body, 0, 0, 300, 200); + const wrapper = box(card, 10, 10, 100, 40); + const button = box(wrapper, 10, 10, 100, 40); + const tiny = box(button, 12, 12, 4, 4); + const contents = box(card, 0, 0, 300, 200, "display: contents"); + // smallest first, as elementFromPoint returns the deepest element + const kept = hitCandidates([tiny, button, wrapper, contents, card]); + expect(kept).toEqual([button, card]); + }); + + it("converts rects to viewport pixels", () => { + const card = box(document.body, 10.4, 20.6, 100, 40); + Object.defineProperty(document, "elementFromPoint", { value: () => card, configurable: true }); + const result = hitElements(document, { x: 12, y: 22 }, { scale: 2 }, () => "Card"); + expect(result).toEqual([{ key: expect.any(String) as string, label: "Card", rect: { x: 21, y: 41, width: 200, height: 80 } }]); + }); + + it("returns an empty list when nothing is under the point", () => { + Object.defineProperty(document, "elementFromPoint", { value: vi.fn(() => null), configurable: true }); + expect(hitElements(document, { x: 0, y: 0 }, { scale: 1 }, () => null)).toEqual([]); + }); +}); diff --git a/apps/browser-extension/src/content/hitTest.ts b/apps/browser-extension/src/content/hitTest.ts new file mode 100644 index 0000000..b455ed0 --- /dev/null +++ b/apps/browser-extension/src/content/hitTest.ts @@ -0,0 +1,59 @@ +import type { HitElement } from "@snaphub/devtools-protocol/protocol"; +import { toViewportRect, type CssRect, type Scale } from "../geometry"; +import { hashKey, rectOf, selectorFor, shortLabel } from "./dom"; + +const MIN_SIZE_CSS_PX = 6; +const MAX_ELEMENTS = 12; + +function sameRect(a: CssRect, b: CssRect): boolean { + return ( + Math.abs(a.x - b.x) <= 1 && + Math.abs(a.y - b.y) <= 1 && + Math.abs(a.width - b.width) <= 1 && + Math.abs(a.height - b.height) <= 1 + ); +} + +/** The element at a CSS point and its ancestors up to (excluding) body, smallest first. */ +export function elementsAtPoint(doc: Document, x: number, y: number): Element[] { + const start = doc.elementFromPoint(x, y); + const chain: Element[] = []; + for (let node: Element | null = start; node !== null; node = node.parentElement) { + if (node === doc.body || node === doc.documentElement) break; + chain.push(node); + } + return chain; +} + +/** + * Filters the chain to hover candidates: drops tiny elements, display:contents, + * and any element whose rect equals its child's within 1px (the child is kept). + */ +export function hitCandidates(chain: readonly Element[]): Element[] { + const kept: Element[] = []; + let previousRect: CssRect | null = null; + for (const element of chain) { + const rect = rectOf(element); + const hidden = + rect.width < MIN_SIZE_CSS_PX || rect.height < MIN_SIZE_CSS_PX || getComputedStyle(element).display === "contents"; + if (hidden) continue; + if (previousRect !== null && sameRect(previousRect, rect)) continue; + kept.push(element); + previousRect = rect; + if (kept.length >= MAX_ELEMENTS) break; + } + return kept; +} + +export function hitElements( + doc: Document, + cssPoint: { x: number; y: number }, + scale: Scale, + labelFor: (element: Element) => string | null, +): HitElement[] { + return hitCandidates(elementsAtPoint(doc, cssPoint.x, cssPoint.y)).map((element) => ({ + key: hashKey(selectorFor(element)), + label: (labelFor(element) ?? shortLabel(element)).slice(0, 80), + rect: toViewportRect(rectOf(element), scale), + })); +} diff --git a/apps/browser-extension/src/content/inspector/controller.ts b/apps/browser-extension/src/content/inspector/controller.ts new file mode 100644 index 0000000..e11da52 --- /dev/null +++ b/apps/browser-extension/src/content/inspector/controller.ts @@ -0,0 +1,332 @@ +import { buildElementMarkdown } from "@snaphub/devtools-protocol/markdown"; +import { toViewportRect } from "../../geometry"; +import { describeElement, rectOf, shortLabel } from "../dom"; +import { ensureHost, resolveComponentData } from "../mainClient"; +import { measureBetween } from "../measure"; +import { h } from "./dom"; +import { Overlay } from "./overlay"; +import { Panel, defaultPosition, type PanelPosition } from "./panel"; +import { INSPECTOR_CSS } from "./styles"; + +const TOAST_MS = 1400; +const PAUSE_CSS = + "*,*::before,*::after{animation-play-state:paused!important;transition:none!important;caret-color:transparent!important}"; +const EXIT_MS = 120; +const FONT_FACES = ["Plus Jakarta Sans", "JetBrains Mono"]; + +let savedPosition: PanelPosition | null = null; + +function fontCss(): string { + const url = (file: string): string => chrome.runtime.getURL(`fonts/${file}`); + return [ + `@font-face{font-family:"CapKit Sans";src:url("${url("plus-jakarta-sans-latin-wght-normal.woff2")}") format("woff2");font-weight:200 800}`, + `@font-face{font-family:"CapKit Mono";src:url("${url("jetbrains-mono-latin-wght-normal.woff2")}") format("woff2");font-weight:100 800}`, + ].join(""); +} + +function label(element: Element, name: string | null): string { + const rect = element.getBoundingClientRect(); + return `${name ?? shortLabel(element)} · ${element.tagName.toLowerCase()} · ${String(Math.round(rect.width))}×${String(Math.round(rect.height))}`; +} + +/** Page-side inspector: hover outline, lock, side panel, measure, keyboard shortcuts. */ +export class InspectorController { + private active = false; + private shadow: ShadowRoot | null = null; + private root: HTMLElement | null = null; + private overlay: Overlay | null = null; + private panel: Panel | null = null; + private hovered: Element | null = null; + private locked: Element | null = null; + private altHeld = false; + private paused = false; + private pauseStyle: HTMLStyleElement | null = null; + private pausedAnimations: Animation[] = []; + private toastTimer: ReturnType | null = null; + + constructor(private readonly doc: Document = document) {} + + get isActive(): boolean { + return this.active; + } + + toggle(): void { + if (this.active) this.stop(); + else this.start(); + } + + start(): void { + if (this.active) return; + this.active = true; + const { host } = ensureHost(this.doc); + this.shadow ??= host.attachShadow({ mode: "closed" }); + const style = h(this.doc, "style", {}, fontCss(), INSPECTOR_CSS); + this.root = h(this.doc, "div", { class: "root" }); + this.shadow.replaceChildren(style, this.root); + this.overlay = new Overlay(this.doc, this.root); + this.panel = new Panel(this.doc, this.root, savedPosition ?? defaultPosition(), { + close: (): void => { + this.stop(); + }, + copy: (): void => { + void this.copyMarkdown(); + }, + onCopy: (text, name): void => { + void this.copyText(text, name); + }, + onMove: (position): void => { + savedPosition = position; + }, + }); + this.panel.showHint("Hover an element, click to lock it. Esc exits."); + const win = this.doc.defaultView; + win?.addEventListener("pointermove", this.onMove, true); + win?.addEventListener("pointerdown", this.swallow, true); + win?.addEventListener("mousedown", this.swallow, true); + win?.addEventListener("click", this.onClick, true); + win?.addEventListener("keydown", this.onKey, true); + win?.addEventListener("keyup", this.onKeyUp, true); + } + + stop(): void { + if (!this.active) return; + this.active = false; + const win = this.doc.defaultView; + win?.removeEventListener("pointermove", this.onMove, true); + win?.removeEventListener("pointerdown", this.swallow, true); + win?.removeEventListener("mousedown", this.swallow, true); + win?.removeEventListener("click", this.onClick, true); + win?.removeEventListener("keydown", this.onKey, true); + win?.removeEventListener("keyup", this.onKeyUp, true); + const panel = this.panel; + panel?.node.classList.remove("open"); + panel?.node.classList.add("closing"); + setTimeout(() => { + if (!this.active) this.shadow?.replaceChildren(); + }, EXIT_MS); + this.hovered = null; + this.locked = null; + this.overlay = null; + this.panel = null; + this.resumeAnimations(); + } + + private isOwn(target: EventTarget | null): boolean { + return target instanceof Element && target.localName === "capkit-inspector-host"; + } + + private readonly swallow = (event: Event): void => { + if (this.isOwn(event.target)) return; + event.preventDefault(); + event.stopPropagation(); + }; + + private readonly onMove = (event: PointerEvent): void => { + const element = this.doc.elementFromPoint(event.clientX, event.clientY); + if (element === null || this.isOwn(element) || element === this.hovered) return; + if (this.locked !== null) { + this.hovered = element; + this.drawMeasure(); + return; + } + this.hovered = element; + this.overlay?.show(element, label(element, null), false); + }; + + private readonly onClick = (event: MouseEvent): void => { + if (this.isOwn(event.target)) return; + event.preventDefault(); + event.stopPropagation(); + const element = this.doc.elementFromPoint(event.clientX, event.clientY); + if (element === null || this.isOwn(element)) return; + void this.lock(element); + }; + + private async lock(element: Element): Promise { + this.locked = element; + this.hovered = null; + this.overlay?.show(element, label(element, null), true); + const data = await resolveComponentData(element).catch(() => ({ component: null, source: null })); + if (this.locked !== element || this.panel === null) return; + const css = rectOf(element); + const details = describeElement(element, toViewportRect(css, { scale: 1 }), data); + this.panel.render(element, details); + this.overlay?.show(element, label(element, data.component?.name ?? null), true); + this.currentDetails = details; + this.drawMeasure(); + } + + private currentDetails: ReturnType | null = null; + + private drawMeasure(): void { + const locked = this.locked; + const hovered = this.hovered; + if (locked === null || this.overlay === null) return; + if (hovered === null || hovered === locked) { + this.overlay.clearMeasure(); + return; + } + const hoveredRect = rectOf(hovered); + let other: ReturnType | null = null; + if (this.altHeld && hovered.parentElement !== null) { + const parent = hovered.parentElement; + const pr = rectOf(parent); + const style = getComputedStyle(parent); + const px = (v: string): number => Number.parseFloat(v) || 0; + other = { + x: pr.x + px(style.borderLeftWidth) + px(style.paddingLeft), + y: pr.y + px(style.borderTopWidth) + px(style.paddingTop), + width: pr.width - px(style.borderLeftWidth) - px(style.borderRightWidth) - px(style.paddingLeft) - px(style.paddingRight), + height: pr.height - px(style.borderTopWidth) - px(style.borderBottomWidth) - px(style.paddingTop) - px(style.paddingBottom), + }; + } + this.overlay.drawMeasurements(measureBetween(other ?? rectOf(locked), hoveredRect)); + } + + private readonly onKeyUp = (event: KeyboardEvent): void => { + if (event.key === "Alt" && this.altHeld) { + this.altHeld = false; + this.drawMeasure(); + } + }; + + private readonly onKey = (event: KeyboardEvent): void => { + if (event.ctrlKey || event.metaKey) return; + if (event.key === "Alt") { + event.preventDefault(); + if (!this.altHeld) { + this.altHeld = true; + this.drawMeasure(); + } + return; + } + const handled = this.handleKey(event.key.length === 1 ? event.key.toLowerCase() : event.key); + if (handled) { + event.preventDefault(); + event.stopPropagation(); + } + }; + + private handleKey(key: string): boolean { + switch (key) { + case "Escape": + if (this.locked !== null) { + this.locked = null; + this.hovered = null; + this.overlay?.hide(); + this.panel?.showHint("Hover an element, click to lock it. Esc exits."); + } else { + this.stop(); + } + return true; + case "ArrowUp": + return this.move(this.locked?.parentElement ?? null); + case "ArrowDown": + return this.move(this.locked?.firstElementChild ?? null); + case "ArrowLeft": + return this.move(this.locked?.previousElementSibling ?? null); + case "ArrowRight": + return this.move(this.locked?.nextElementSibling ?? null); + case "c": + void this.copyMarkdown(); + return true; + case "p": + this.togglePause(); + return true; + case "s": + void this.copyImage(); + return true; + default: + return false; + } + } + + private move(target: Element | null): boolean { + if (this.locked === null) return false; + if (target !== null && target !== this.doc.documentElement && !this.isOwn(target)) void this.lock(target); + return true; + } + + private async copyText(text: string, name: string): Promise { + try { + await navigator.clipboard.writeText(text); + this.toast(`Copied ${name}`); + } catch { + this.toast("Couldn't copy"); + } + } + + private async copyMarkdown(): Promise { + const details = this.currentDetails; + if (details === null || this.locked === null) { + this.toast("Lock an element first"); + return; + } + try { + await navigator.clipboard.writeText(buildElementMarkdown(details)); + this.toast("Copied element"); + } catch { + this.toast("Couldn't copy"); + } + } + + private togglePause(): void { + if (this.paused) { + this.resumeAnimations(); + this.toast("Animations resumed"); + return; + } + this.pausedAnimations = this.doc.getAnimations().filter((a) => a.playState === "running"); + for (const animation of this.pausedAnimations) animation.pause(); + this.pauseStyle = h(this.doc, "style", {}, PAUSE_CSS); + this.doc.head.append(this.pauseStyle); + this.paused = true; + this.toast("Animations paused"); + } + + private resumeAnimations(): void { + this.pauseStyle?.remove(); + this.pauseStyle = null; + for (const animation of this.pausedAnimations) animation.play(); + this.pausedAnimations = []; + this.paused = false; + } + + private async copyImage(): Promise { + const element = this.locked; + if (element === null) { + this.toast("Lock an element first"); + return; + } + try { + const rect = element.getBoundingClientRect(); + const response: unknown = await chrome.runtime.sendMessage({ kind: "captureVisible" }); + const dataUrl: unknown = typeof response === "object" && response !== null ? Reflect.get(response, "dataUrl") : null; + if (typeof dataUrl !== "string") throw new Error("no capture"); + const bitmap = await createImageBitmap(await (await fetch(dataUrl)).blob()); + const scale = bitmap.width / window.innerWidth; + const canvas = new OffscreenCanvas(Math.max(1, Math.round(rect.width * scale)), Math.max(1, Math.round(rect.height * scale))); + const context = canvas.getContext("2d"); + if (context === null) throw new Error("no canvas"); + context.drawImage(bitmap, rect.x * scale, rect.y * scale, rect.width * scale, rect.height * scale, 0, 0, canvas.width, canvas.height); + const blob = await canvas.convertToBlob({ type: "image/png" }); + await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]); + this.toast("Copied element image"); + } catch { + this.toast("Couldn't copy image"); + } + } + + private toast(text: string): void { + if (this.root === null) return; + const node = h(this.doc, "div", { class: "toast", role: "status" }, text); + this.root.querySelector(".toast")?.remove(); + this.root.append(node); + if (this.toastTimer !== null) clearTimeout(this.toastTimer); + this.toastTimer = setTimeout(() => { + node.remove(); + }, TOAST_MS); + } +} + +export { FONT_FACES }; diff --git a/apps/browser-extension/src/content/inspector/dom.ts b/apps/browser-extension/src/content/inspector/dom.ts new file mode 100644 index 0000000..258b975 --- /dev/null +++ b/apps/browser-extension/src/content/inspector/dom.ts @@ -0,0 +1,24 @@ +type Child = Node | string | null | undefined | false; + +/** Builds an element with text children only; page data is never parsed as HTML. */ +export function h( + doc: Document, + tag: K, + attributes: Record = {}, + ...children: Child[] +): HTMLElementTagNameMap[K] { + const element = doc.createElement(tag); + for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value); + for (const child of children) { + if (child === null || child === undefined || child === false) continue; + element.append(typeof child === "string" ? doc.createTextNode(child) : child); + } + return element; +} + +export function place(element: HTMLElement, x: number, y: number, width?: number, height?: number): void { + element.style.left = `${String(x)}px`; + element.style.top = `${String(y)}px`; + if (width !== undefined) element.style.width = `${String(width)}px`; + if (height !== undefined) element.style.height = `${String(height)}px`; +} diff --git a/apps/browser-extension/src/content/inspector/overlay.ts b/apps/browser-extension/src/content/inspector/overlay.ts new file mode 100644 index 0000000..57fd95b --- /dev/null +++ b/apps/browser-extension/src/content/inspector/overlay.ts @@ -0,0 +1,137 @@ +import type { CssRect } from "../../geometry"; +import type { Measurement } from "../measure"; +import { h, place } from "./dom"; + +type Edges = { top: number; right: number; bottom: number; left: number }; + +function edges(style: CSSStyleDeclaration, property: "margin" | "padding" | "border"): Edges { + const side = (name: string): number => { + const key = property === "border" ? `border${name}Width` : `${property}${name}`; + return Number.parseFloat(style.getPropertyValue(key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`))) || 0; + }; + return { top: side("Top"), right: side("Right"), bottom: side("Bottom"), left: side("Left") }; +} + +export type BoxModel = { margin: Edges; border: Edges; padding: Edges; content: { width: number; height: number } }; + +export function readBoxModel(element: Element): BoxModel { + const style = getComputedStyle(element); + const margin = edges(style, "margin"); + const border = edges(style, "border"); + const padding = edges(style, "padding"); + const rect = element.getBoundingClientRect(); + return { + margin, + border, + padding, + content: { + width: Math.max(0, rect.width - border.left - border.right - padding.left - padding.right), + height: Math.max(0, rect.height - border.top - border.bottom - padding.top - padding.bottom), + }, + }; +} + +function frame(outer: CssRect, inner: CssRect): string { + const o = (r: CssRect): string => `M${String(r.x - outer.x)} ${String(r.y - outer.y)}h${String(r.width)}v${String(r.height)}h${String(-r.width)}Z`; + return `path(evenodd, "${o(outer)}${o(inner)}")`; +} + +/** Draws hover and lock outlines, padding/margin bands, the label chip and measurement lines. */ +export class Overlay { + private readonly outline: HTMLElement; + private readonly margin: HTMLElement; + private readonly padding: HTMLElement; + private readonly chip: HTMLElement; + private readonly measure: HTMLElement; + + constructor( + private readonly doc: Document, + root: HTMLElement, + ) { + this.margin = h(doc, "div", { class: "band margin" }); + this.padding = h(doc, "div", { class: "band padding" }); + this.outline = h(doc, "div", { class: "outline" }); + this.chip = h(doc, "div", { class: "chip mono" }); + this.measure = h(doc, "div"); + for (const part of [this.margin, this.padding, this.outline, this.chip, this.measure]) { + part.hidden = true; + root.append(part); + } + } + + show(element: Element, label: string, locked: boolean): void { + const rect = element.getBoundingClientRect(); + const box = readBoxModel(element); + place(this.outline, rect.x, rect.y, rect.width, rect.height); + this.outline.classList.toggle("locked", locked); + this.outline.hidden = false; + + const marginRect: CssRect = { + x: rect.x - box.margin.left, + y: rect.y - box.margin.top, + width: rect.width + box.margin.left + box.margin.right, + height: rect.height + box.margin.top + box.margin.bottom, + }; + place(this.margin, marginRect.x, marginRect.y, marginRect.width, marginRect.height); + this.margin.style.clipPath = frame(marginRect, { x: rect.x, y: rect.y, width: rect.width, height: rect.height }); + this.margin.hidden = false; + + const inner: CssRect = { + x: rect.x + box.border.left + box.padding.left, + y: rect.y + box.border.top + box.padding.top, + width: box.content.width, + height: box.content.height, + }; + const paddingBox: CssRect = { + x: rect.x + box.border.left, + y: rect.y + box.border.top, + width: rect.width - box.border.left - box.border.right, + height: rect.height - box.border.top - box.border.bottom, + }; + place(this.padding, paddingBox.x, paddingBox.y, paddingBox.width, paddingBox.height); + this.padding.style.clipPath = frame(paddingBox, inner); + this.padding.hidden = false; + + this.chip.textContent = label; + this.chip.hidden = false; + const chipHeight = 20; + const above = rect.y - chipHeight - 4; + place(this.chip, Math.max(4, Math.min(rect.x, window.innerWidth - 220)), above < 4 ? rect.y + rect.height + 4 : above); + } + + hide(): void { + for (const part of [this.margin, this.padding, this.outline, this.chip]) part.hidden = true; + this.clearMeasure(); + } + + clearMeasure(): void { + this.measure.replaceChildren(); + this.measure.hidden = true; + } + + drawMeasurements(measurements: readonly Measurement[]): void { + this.measure.replaceChildren(); + for (const m of measurements) { + const horizontal = m.orientation === "horizontal"; + const line = h(this.doc, "div", { class: `line ${horizontal ? "h" : "v"}` }); + place( + line, + Math.min(m.from.x, m.to.x), + Math.min(m.from.y, m.to.y), + horizontal ? Math.abs(m.to.x - m.from.x) : undefined, + horizontal ? undefined : Math.abs(m.to.y - m.from.y), + ); + this.measure.append(line); + for (const end of [m.from, m.to]) { + const cap = h(this.doc, "div", { class: "cap" }); + if (horizontal) place(cap, end.x, end.y - 4, 1, 9); + else place(cap, end.x - 4, end.y, 9, 1); + this.measure.append(cap); + } + const pill = h(this.doc, "div", { class: "pill mono" }, `${String(m.distance)}px`); + place(pill, (m.from.x + m.to.x) / 2, (m.from.y + m.to.y) / 2); + this.measure.append(pill); + } + this.measure.hidden = measurements.length === 0; + } +} diff --git a/apps/browser-extension/src/content/inspector/panel.ts b/apps/browser-extension/src/content/inspector/panel.ts new file mode 100644 index 0000000..14a70fa --- /dev/null +++ b/apps/browser-extension/src/content/inspector/panel.ts @@ -0,0 +1,214 @@ +import type { ElementDetails } from "@snaphub/devtools-protocol/protocol"; +import { toHexColor } from "@snaphub/devtools-protocol/markdown"; +import { contrastRatio, gradeContrast, over, parseColor, type Rgba } from "../contrast"; +import { readBoxModel } from "./overlay"; +import { h } from "./dom"; + +const PANEL_WIDTH = 320; +const INSET = 12; + +export type PanelPosition = { x: number; y: number }; + +export function defaultPosition(): PanelPosition { + return { x: Math.max(INSET, window.innerWidth - PANEL_WIDTH - INSET), y: INSET }; +} + +function clampPosition(position: PanelPosition): PanelPosition { + return { + x: Math.min(Math.max(INSET, position.x), Math.max(INSET, window.innerWidth - PANEL_WIDTH - INSET)), + y: Math.min(Math.max(INSET, position.y), Math.max(INSET, window.innerHeight - 60)), + }; +} + +function effectiveBackground(element: Element): Rgba { + const layers: Rgba[] = []; + for (let node: Element | null = element; node !== null; node = node.parentElement) { + const color = parseColor(getComputedStyle(node).backgroundColor); + if (color !== null && color.a > 0) { + layers.push(color); + if (color.a >= 1) break; + } + } + return layers.reduceRight((below, layer) => over(layer, below), { r: 255, g: 255, b: 255, a: 1 }); +} + +export type ContrastInfo = { ratio: number; grade: "AAA" | "AA" | "Fail" }; + +export function contrastOf(element: Element): ContrastInfo | null { + const style = getComputedStyle(element); + const fg = parseColor(style.color); + if (fg === null) return null; + const bg = effectiveBackground(element); + const ratio = contrastRatio(over(fg, bg), bg); + const size = Number.parseFloat(style.fontSize); + const weight = Number.parseInt(style.fontWeight, 10); + const large = size >= 24 || (size >= 18.66 && weight >= 700); + return { ratio, grade: gradeContrast(ratio, large) }; +} + +function row(doc: Document, key: string, value: string | Node, mono = false): HTMLElement { + return h( + doc, + "div", + { class: "row" }, + h(doc, "span", { class: "k" }, key), + h(doc, "span", { class: mono ? "v mono" : "v" }, value), + ); +} + +function copyRow(doc: Document, key: string, shown: string, text: string, name: string, onCopy: PanelActions["onCopy"], swatchColor?: string): HTMLElement { + const button = h(doc, "button", { type: "button", class: "link mono", "aria-label": `Copy ${name}` }); + if (swatchColor !== undefined) { + const swatch = h(doc, "span", { class: "swatch" }); + swatch.style.backgroundColor = swatchColor; + button.append(swatch); + } + button.append(doc.createTextNode(shown)); + button.addEventListener("click", () => { + onCopy(text, name); + }); + return row(doc, key, button); +} + +function boxDiagram(doc: Document, element: Element): HTMLElement { + const box = readBoxModel(element); + const sides = (e: { top: number; right: number; bottom: number; left: number }): string => + `${String(e.top)} ${String(e.right)} ${String(e.bottom)} ${String(e.left)}`; + const inner = h( + doc, + "div", + { class: "inner mono" }, + `padding ${sides(box.padding)}`, + h(doc, "div", {}, `${String(Math.round(box.content.width))} × ${String(Math.round(box.content.height))}`), + ); + return h(doc, "div", { class: "box mono" }, `margin ${sides(box.margin)}`, inner); +} + +export type PanelActions = { + close: () => void; + copy: () => void; + onCopy: (text: string, name: string) => void; + onMove: (position: PanelPosition) => void; +}; + +/** The 320px inspector dialog. Content is rebuilt per element; the dialog node is kept so focus survives. */ +export class Panel { + readonly node: HTMLElement; + private readonly body: HTMLElement; + private position: PanelPosition; + + constructor( + private readonly doc: Document, + root: HTMLElement, + position: PanelPosition, + private readonly actions: PanelActions, + ) { + this.position = clampPosition(position); + this.body = h(doc, "div"); + const close = h(doc, "button", { type: "button", "aria-label": "Close inspector" }, "Esc"); + close.addEventListener("click", actions.close); + const copy = h(doc, "button", { type: "button", "aria-label": "Copy element as Markdown" }, "Copy"); + copy.addEventListener("click", actions.copy); + const header = h(doc, "header", {}, h(doc, "h2", {}, "CapKit Inspector"), copy, close); + this.node = h(doc, "div", { class: "panel", role: "dialog", "aria-label": "CapKit Inspector", tabindex: "-1" }, header, this.body); + this.apply(); + this.enableDrag(header); + root.append(this.node); + requestAnimationFrame(() => { + this.node.classList.add("open"); + }); + } + + private apply(): void { + this.node.style.left = `${String(this.position.x)}px`; + this.node.style.top = `${String(this.position.y)}px`; + } + + private enableDrag(header: HTMLElement): void { + header.addEventListener("pointerdown", (event) => { + if (event.target instanceof HTMLButtonElement) return; + const startX = event.clientX - this.position.x; + const startY = event.clientY - this.position.y; + header.setPointerCapture(event.pointerId); + const move = (e: PointerEvent): void => { + this.position = clampPosition({ x: e.clientX - startX, y: e.clientY - startY }); + this.apply(); + }; + const up = (): void => { + header.removeEventListener("pointermove", move); + header.removeEventListener("pointerup", up); + this.actions.onMove(this.position); + }; + header.addEventListener("pointermove", move); + header.addEventListener("pointerup", up); + }); + } + + showHint(text: string): void { + this.body.replaceChildren(h(this.doc, "p", { class: "hint" }, text)); + } + + render(element: Element, details: ElementDetails): void { + const d = this.doc; + const contrast = contrastOf(element); + const elementSection = h(d, "section", { "aria-label": "Element" }); + elementSection.append( + row(d, "Element", details.label, true), + copyRow(d, "Selector", details.selector, details.selector, "selector", this.actions.onCopy), + row(d, "Component", details.component === null ? "None found" : details.component.name), + details.source === null + ? row(d, "Source", sourceNote(details), true) + : copyRow(d, "Source", `${details.source.file}:${String(details.source.line)}`, `${details.source.file}:${String(details.source.line)}`, "source", this.actions.onCopy), + row(d, "Owners", details.component === null || details.component.ownerPath.length === 0 ? "None" : details.component.ownerPath.join(" › "), true), + row(d, "Text", details.text === "" ? "None" : details.text), + row(d, "Size", `${String(Math.round(details.cssRect.width))} × ${String(Math.round(details.cssRect.height))}`, true), + boxDiagram(d, element), + ); + + const s = details.styles; + const styles = h(d, "details", { open: "" }, h(d, "summary", {}, "Styles")); + styles.append( + copyRow(d, "Color", toHexColor(s.color), toHexColor(s.color), "color", this.actions.onCopy, s.color), + copyRow(d, "Background", toHexColor(s.backgroundColor), toHexColor(s.backgroundColor), "color", this.actions.onCopy, s.backgroundColor), + row(d, "Font", `${s.fontFamily.split(",")[0] ?? ""} ${s.fontSize}/${s.lineHeight} ${s.fontWeight}`, true), + row(d, "Padding", s.padding, true), + row(d, "Margin", s.margin, true), + row(d, "Radius", s.borderRadius, true), + row(d, "Shadow", s.boxShadow, true), + row(d, "Layout", layoutOf(element, s), true), + row(d, "Classes", details.classes === "" ? "None" : details.classes, true), + ); + + const access = h(d, "details", { open: "" }, h(d, "summary", {}, "Accessibility")); + access.append( + row(d, "Role", details.role ?? "none"), + row(d, "Name", details.accessibleName === "" ? "None" : details.accessibleName), + ); + if (contrast !== null) { + const badge = h(d, "span", { class: contrast.grade === "Fail" ? "badge fail" : "badge" }, contrast.grade); + access.append(row(d, "Contrast", h(d, "span", { class: "mono" }, `${contrast.ratio.toFixed(2)}:1 `, badge))); + } + this.body.replaceChildren(elementSection, styles, access); + } +} + +function layoutOf(element: Element, s: ElementDetails["styles"]): string { + const style = getComputedStyle(element); + const direction = s.display.includes("flex") ? ` ${style.flexDirection}` : s.display.includes("grid") ? " grid" : ""; + return `${s.display}${direction}${s.gap === "normal" ? "" : ` · gap ${s.gap}`}`; +} + +function sourceNote(details: ElementDetails): string { + switch (details.sourceUnavailableReason) { + case "no-react": + return "Not a React element"; + case "production-build": + return "Production build"; + case "no-source-map": + return "No source map"; + case "fetch-failed": + return "Source map unavailable"; + case undefined: + return "Unavailable"; + } +} diff --git a/apps/browser-extension/src/content/inspector/styles.ts b/apps/browser-extension/src/content/inspector/styles.ts new file mode 100644 index 0000000..3846e7f --- /dev/null +++ b/apps/browser-extension/src/content/inspector/styles.ts @@ -0,0 +1,49 @@ +/** Stylesheet for the closed shadow root. No gradients, no transition: all, reduced motion keeps opacity only. */ +export const INSPECTOR_CSS = ` +:host { all: initial; } +*, *::before, *::after { box-sizing: border-box; } +.root { position: fixed; inset: 0; pointer-events: none; font: 12px/1.45 "CapKit Sans", "Plus Jakarta Sans", system-ui, sans-serif; color: #f2f1ec; } +.mono { font-family: "CapKit Mono", "JetBrains Mono", ui-monospace, Consolas, monospace; font-variant-numeric: tabular-nums; } +.outline { position: fixed; border: 1px solid #d9ff43; pointer-events: none; } +.outline.locked { box-shadow: 0 0 0 1px rgb(0 0 0 / 55%); } +.band { position: fixed; pointer-events: none; } +.band.margin { background: rgb(217 255 67 / 25%); } +.band.padding { background: repeating-linear-gradient(135deg, rgb(217 255 67 / 35%) 0 2px, transparent 2px 6px); } +.chip { position: fixed; padding: 2px 6px; border-radius: 4px; background: #1b1c1a; color: #d9ff43; border: 1px solid rgb(255 255 255 / 9%); white-space: nowrap; font-size: 11px; pointer-events: none; } +.line { position: fixed; background: #d9ff43; pointer-events: none; } +.line.h { height: 1px; } +.line.v { width: 1px; } +.cap { position: fixed; background: #d9ff43; pointer-events: none; } +.pill { position: fixed; padding: 1px 5px; border-radius: 3px; background: #1b1c1a; color: #d9ff43; font-size: 10px; pointer-events: none; transform: translate(-50%, -50%); } +.panel { position: fixed; width: 320px; max-height: calc(100vh - 24px); overflow: auto; pointer-events: auto; background: #1b1c1a; color: #f2f1ec; border: 1px solid rgb(255 255 255 / 9%); border-radius: 10px; box-shadow: 0 12px 32px rgb(0 0 0 / 45%); opacity: 0; transform: scale(0.97); transition: opacity 160ms cubic-bezier(0.23, 1, 0.32, 1), transform 160ms cubic-bezier(0.23, 1, 0.32, 1); } +.panel.open { opacity: 1; transform: scale(1); } +.panel.closing { opacity: 0; transform: scale(0.97); transition-duration: 120ms; } +.panel header { display: flex; align-items: center; gap: 8px; padding: 10px 12px; cursor: grab; background: #242522; border-bottom: 1px solid rgb(255 255 255 / 9%); user-select: none; } +.panel header:active { cursor: grabbing; } +.panel h2 { margin: 0; font-size: 12px; font-weight: 600; letter-spacing: 0.01em; flex: 1; } +.panel section, .panel details { padding: 8px 12px; border-bottom: 1px solid rgb(255 255 255 / 9%); } +.panel summary { cursor: pointer; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #a9a89f; padding: 2px 0; } +.row { display: flex; align-items: baseline; gap: 8px; padding: 2px 0; } +.row .k { flex: 0 0 76px; color: #a9a89f; } +.row .v { flex: 1; min-width: 0; overflow-wrap: anywhere; } +.swatch { display: inline-block; width: 10px; height: 10px; margin-right: 6px; border-radius: 2px; border: 1px solid rgb(255 255 255 / 25%); vertical-align: -1px; } +button { font: inherit; color: inherit; background: #2d2e2b; border: 1px solid rgb(255 255 255 / 9%); border-radius: 5px; padding: 2px 7px; cursor: pointer; transition: transform 100ms cubic-bezier(0.23, 1, 0.32, 1), background-color 100ms cubic-bezier(0.23, 1, 0.32, 1); } +button:hover { background: #383935; } +button:active { transform: scale(0.97); } +button.link { background: none; border: none; padding: 0; text-align: left; } +button.link:hover { color: #d9ff43; background: none; } +:focus-visible { outline: 2px solid #d9ff43; outline-offset: 1px; } +.box { display: grid; place-items: center; gap: 4px; padding: 6px; border: 1px dashed rgb(255 255 255 / 25%); border-radius: 4px; font-size: 10px; text-align: center; } +.box .inner { width: 100%; padding: 6px; border: 1px solid rgb(255 255 255 / 25%); } +.badge { display: inline-block; padding: 0 5px; border-radius: 3px; background: #d9ff43; color: #1b1c1a; font-weight: 700; font-size: 10px; } +.badge.fail { background: #ff6b5e; } +.toast { position: fixed; left: 50%; bottom: 20px; transform: translate(-50%, 0); padding: 6px 12px; border-radius: 6px; background: #1b1c1a; border: 1px solid rgb(255 255 255 / 9%); color: #f2f1ec; animation: toast-in 180ms cubic-bezier(0.23, 1, 0.32, 1); } +@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } } +.hint { color: #a9a89f; padding: 8px 12px; } +@media (prefers-reduced-motion: reduce) { + .panel, .panel.closing { transform: none; } + .toast { animation-name: toast-fade; } + @keyframes toast-fade { from { opacity: 0; } to { opacity: 1; } } + button:active { transform: none; } +} +`; diff --git a/apps/browser-extension/src/content/isolated.ts b/apps/browser-extension/src/content/isolated.ts new file mode 100644 index 0000000..f805f96 --- /dev/null +++ b/apps/browser-extension/src/content/isolated.ts @@ -0,0 +1,32 @@ +import { PROTOCOL_VERSION } from "@snaphub/devtools-protocol/protocol"; +import { pageRequestSchema, type PageResponse } from "../messages"; +import { handlePageRequest } from "./handlers"; +import { InspectorController } from "./inspector/controller"; +import { resolveComponentData } from "./mainClient"; + +declare global { + var __capkitInspector: number | undefined; +} + +/** A second injection of the same protocol version is a no-op. */ +if (globalThis.__capkitInspector !== PROTOCOL_VERSION) { + globalThis.__capkitInspector = PROTOCOL_VERSION; + const controller = new InspectorController(document); + + chrome.runtime.onMessage.addListener((message: unknown, _sender, sendResponse: (response: PageResponse) => void) => { + const parsed = pageRequestSchema.safeParse(message); + if (!parsed.success) return false; + const request = parsed.data; + if (request.kind === "toggle") { + controller.toggle(); + sendResponse({ kind: "ok" }); + return false; + } + void handlePageRequest({ window, document, resolve: resolveComponentData }, request) + .then(sendResponse) + .catch(() => { + sendResponse({ kind: "ok" }); + }); + return true; + }); +} diff --git a/apps/browser-extension/src/content/main-world.ts b/apps/browser-extension/src/content/main-world.ts new file mode 100644 index 0000000..d59d556 --- /dev/null +++ b/apps/browser-extension/src/content/main-world.ts @@ -0,0 +1,83 @@ +import { + CHANNEL_ATTRIBUTE, + HOST_TAG, + TARGET_ATTRIBUTE, + parseMainRequest, + replyEventName, + type MainReply, +} from "./bridge"; +import { debugSource, debugStack, describeComponent, findFiber } from "./component"; +import { SourceMapCache, normalizeSourcePath, resolveSource } from "./source"; + +const FETCH_TIMEOUT_MS = 1500; +const MAX_SCRIPT_BYTES = 5 * 1024 * 1024; + +async function fetchSameOriginText(url: string): Promise { + try { + if (url.startsWith("data:")) return null; + if (new URL(url, location.href).origin !== location.origin) return null; + const controller = new AbortController(); + const timer = setTimeout(() => { + controller.abort(); + }, FETCH_TIMEOUT_MS); + try { + const response = await fetch(url, { signal: controller.signal, credentials: "omit" }); + if (!response.ok) return null; + const text = await response.text(); + return text.length > MAX_SCRIPT_BYTES ? null : text; + } finally { + clearTimeout(timer); + } + } catch { + return null; + } +} + +const cache = new SourceMapCache(fetchSameOriginText); + +async function describeTarget(id: string, element: Element): Promise { + const fiber = findFiber(element); + if (fiber === null) return { id, component: null, source: null, reason: "no-react" }; + + const info = describeComponent(fiber); + const component = info === null || info === "minified" ? null : info; + + const legacy = debugSource(fiber); + if (legacy !== null) { + const file = normalizeSourcePath(legacy.file, location.origin); + return { id, component, source: { file, line: legacy.line, column: legacy.column } }; + } + const stack = debugStack(fiber); + if (stack === null) { + return { id, component, source: null, reason: "production-build" }; + } + const result = await resolveSource(stack, cache, location.origin); + if (result.ok) return { id, component, source: result.location }; + return { id, component, source: null, reason: result.reason }; +} + +function install(): void { + const host = document.querySelector(HOST_TAG); + const channel = host?.getAttribute(CHANNEL_ATTRIBUTE) ?? null; + if (host === null || channel === null) return; + host.removeAttribute(CHANNEL_ATTRIBUTE); + + document.addEventListener(channel, (event) => { + if (!(event instanceof CustomEvent)) return; + const request = parseMainRequest(event.detail); + if (request === null) return; + const target = document.querySelector(`[${TARGET_ATTRIBUTE}="${CSS.escape(request.target)}"]`); + const reply = (value: MainReply): void => { + document.dispatchEvent(new CustomEvent(replyEventName(channel), { detail: JSON.stringify(value) })); + }; + if (target === null) { + reply({ id: request.id, component: null, source: null, reason: "no-react" }); + return; + } + void describeTarget(request.id, target).then(reply, () => { + reply({ id: request.id, component: null, source: null, reason: "fetch-failed" }); + }); + }); +} + +install(); diff --git a/apps/browser-extension/src/content/mainClient.ts b/apps/browser-extension/src/content/mainClient.ts new file mode 100644 index 0000000..777a7b7 --- /dev/null +++ b/apps/browser-extension/src/content/mainClient.ts @@ -0,0 +1,88 @@ +import { + CHANNEL_ATTRIBUTE, + HOST_TAG, + TARGET_ATTRIBUTE, + parseMainReply, + replyEventName, + type MainReply, +} from "./bridge"; +import type { ComponentData } from "./dom"; + +const REPLY_TIMEOUT_MS = 1800; + +export type ComponentResolver = (element: Element) => Promise; + +function randomId(): string { + return crypto.randomUUID().replaceAll("-", "").slice(0, 24); +} + +/** Creates the host element once per page and returns the channel the main world listens on. */ +export function ensureHost(doc: Document): { host: HTMLElement; channel: string; fresh: boolean } { + const existing = doc.querySelector(HOST_TAG); + const stored = existing === null ? undefined : hostChannels.get(existing); + if (existing !== null && stored !== undefined) return { host: existing, channel: stored, fresh: false }; + const host = doc.createElement(HOST_TAG); + const channel = `capkit-${randomId()}`; + host.setAttribute(CHANNEL_ATTRIBUTE, channel); + host.setAttribute("style", "position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:block"); + doc.documentElement.append(host); + hostChannels.set(host, channel); + return { host, channel, fresh: true }; +} + +const hostChannels = new WeakMap(); + +let mainReady: Promise | null = null; + +/** Injects the main-world script once per page and resolves with the channel name (null on failure). */ +export function ensureMainWorld(doc: Document): Promise { + mainReady ??= (async (): Promise => { + const { channel } = ensureHost(doc); + try { + const response: unknown = await chrome.runtime.sendMessage({ kind: "injectMain" }); + const ok = typeof response === "object" && response !== null && Reflect.get(response, "ok") === true; + return ok ? channel : null; + } catch { + return null; + } + })(); + return mainReady; +} + +/** Asks the main-world script for the component and source of an element. */ +export async function requestMain(doc: Document, element: Element): Promise { + const channel = await ensureMainWorld(doc); + if (channel === null) return null; + const id = randomId(); + const target = randomId(); + return new Promise((resolve) => { + const finish = (value: MainReply | null): void => { + clearTimeout(timer); + doc.removeEventListener(replyEventName(channel), onReply); + element.removeAttribute(TARGET_ATTRIBUTE); + resolve(value); + }; + const onReply = (event: Event): void => { + if (!(event instanceof CustomEvent)) return; + const reply = parseMainReply(event.detail); + if (reply?.id === id) finish(reply); + }; + const timer = setTimeout(() => { + finish(null); + }, REPLY_TIMEOUT_MS); + doc.addEventListener(replyEventName(channel), onReply); + element.setAttribute(TARGET_ATTRIBUTE, target); + doc.dispatchEvent(new CustomEvent(channel, { detail: JSON.stringify({ id, target }) })); + }); +} + +/** Component data for an element; unavailable data comes back as a typed reason, never an exception. */ +export const resolveComponentData: ComponentResolver = async (element) => { + const reply = await requestMain(document, element); + if (reply === null) return { component: null, source: null, sourceUnavailableReason: "fetch-failed" }; + return { + component: reply.component, + source: reply.source, + ...(reply.reason === undefined ? {} : { sourceUnavailableReason: reply.reason }), + }; +}; diff --git a/apps/browser-extension/src/content/measure.test.ts b/apps/browser-extension/src/content/measure.test.ts new file mode 100644 index 0000000..781fb92 --- /dev/null +++ b/apps/browser-extension/src/content/measure.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { measureBetween } from "./measure"; + +describe("measureBetween", () => { + it("measures the horizontal gap between side-by-side boxes", () => { + const [m] = measureBetween({ x: 100, y: 0, width: 50, height: 20 }, { x: 0, y: 0, width: 60, height: 20 }); + expect(m).toMatchObject({ orientation: "horizontal", distance: 40 }); + }); + + it("measures both axes for diagonal boxes", () => { + const result = measureBetween({ x: 100, y: 100, width: 10, height: 10 }, { x: 0, y: 0, width: 10, height: 10 }); + expect(result.map((m) => m.distance)).toEqual([90, 90]); + }); + + it("shows insets for a nested box", () => { + const result = measureBetween({ x: 10, y: 10, width: 20, height: 20 }, { x: 0, y: 0, width: 100, height: 100 }); + expect(result.map((m) => m.distance)).toEqual([10, 70, 10, 70]); + }); +}); diff --git a/apps/browser-extension/src/content/measure.ts b/apps/browser-extension/src/content/measure.ts new file mode 100644 index 0000000..e6e3ebd --- /dev/null +++ b/apps/browser-extension/src/content/measure.ts @@ -0,0 +1,57 @@ +import type { CssRect } from "../geometry"; + +export type Measurement = { + orientation: "horizontal" | "vertical"; + /** Line start and end in CSS px. */ + from: { x: number; y: number }; + to: { x: number; y: number }; + distance: number; +}; + +const round = (value: number): number => Math.round(value * 10) / 10; + +function horizontal(x1: number, x2: number, y: number): Measurement { + return { orientation: "horizontal", from: { x: x1, y }, to: { x: x2, y }, distance: round(x2 - x1) }; +} + +function vertical(y1: number, y2: number, x: number): Measurement { + return { orientation: "vertical", from: { x, y: y1 }, to: { x, y: y2 }, distance: round(y2 - y1) }; +} + +/** + * Distance lines between the nearest edges of two rects: up to one horizontal + * and one vertical line. Nested or overlapping rects show the four insets. + */ +export function measureBetween(a: CssRect, b: CssRect): Measurement[] { + const aRight = a.x + a.width; + const bRight = b.x + b.width; + const aBottom = a.y + a.height; + const bBottom = b.y + b.height; + const result: Measurement[] = []; + + const overlapTop = Math.max(a.y, b.y); + const overlapBottom = Math.min(aBottom, bBottom); + const midY = overlapBottom > overlapTop ? (overlapTop + overlapBottom) / 2 : (a.y + aBottom) / 2; + if (bRight <= a.x) result.push(horizontal(bRight, a.x, midY)); + else if (b.x >= aRight) result.push(horizontal(aRight, b.x, midY)); + + const overlapLeft = Math.max(a.x, b.x); + const overlapRight = Math.min(aRight, bRight); + const midX = overlapRight > overlapLeft ? (overlapLeft + overlapRight) / 2 : (a.x + aRight) / 2; + if (bBottom <= a.y) result.push(vertical(bBottom, a.y, midX)); + else if (b.y >= aBottom) result.push(vertical(aBottom, b.y, midX)); + + if (result.length > 0) return result; + + const aInside = a.width * a.height <= b.width * b.height; + const inner = aInside ? a : b; + const outer = aInside ? b : a; + const cx = inner.x + inner.width / 2; + const cy = inner.y + inner.height / 2; + return [ + horizontal(outer.x, inner.x, cy), + horizontal(inner.x + inner.width, outer.x + outer.width, cy), + vertical(outer.y, inner.y, cx), + vertical(inner.y + inner.height, outer.y + outer.height, cx), + ].filter((m) => m.distance > 0); +} diff --git a/apps/browser-extension/src/content/source.test.ts b/apps/browser-extension/src/content/source.test.ts new file mode 100644 index 0000000..d2db106 --- /dev/null +++ b/apps/browser-extension/src/content/source.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "vitest"; +import { + SourceMapCache, + applicationFrames, + findSourceMappingUrl, + normalizeSourcePath, + parseStack, + resolveSource, +} from "./source"; + +const viteStack = [ + "Error: react-stack-top-frame", + " at exports.jsxDEV (http://localhost:1420/node_modules/.vite/deps/react_jsx-dev-runtime.js?v=abc:250:50)", + " at SaveButton (http://localhost:1420/src/components/SaveButton.tsx?t=17:12:5)", + " at App (http://localhost:1420/src/App.tsx:30:7)", +].join("\n"); + +describe("stack parsing", () => { + it("parses V8 frames and skips React internals", () => { + expect(parseStack(viteStack)).toHaveLength(3); + const frames = applicationFrames(viteStack); + expect(frames[0]).toEqual({ url: "http://localhost:1420/src/components/SaveButton.tsx?t=17", line: 12, column: 5 }); + }); + + it("parses Turbopack style frames", () => { + const stack = "Error\n at Page (turbopack:///[project]/src/app/page.tsx:8:3)"; + expect(applicationFrames(stack)[0]?.line).toBe(8); + }); +}); + +describe("normalizeSourcePath", () => { + it.each([ + ["webpack://_N_E/./src/app/page.tsx", "src/app/page.tsx"], + ["webpack:///./src/index.tsx", "src/index.tsx"], + ["webpack://my-app/./src/a.tsx", "src/a.tsx"], + ["turbopack:///[project]/src/app/page.tsx", "src/app/page.tsx"], + ["file:///C:/work/app/src/a.tsx", "C:/work/app/src/a.tsx"], + ["/@fs/C:/work/app/src/a.tsx", "C:/work/app/src/a.tsx"], + ["http://localhost:1420/src/App.tsx?t=3", "src/App.tsx"], + ])("%s -> %s", (input, expected) => { + expect(normalizeSourcePath(input, "http://localhost:1420")).toBe(expected); + }); +}); + +function inlineMap(sources: string[]): string { + // One segment per generated line mapping column 0 to source 0, line 42 (0-based 41), column 5 (0-based 4). + const map = { version: 3, sources, names: [], mappings: "AAyCI", file: "bundle.js" }; + return `data:application/json;base64,${btoa(JSON.stringify(map))}`; +} + +describe("symbolication", () => { + it("reads the last sourceMappingURL", () => { + expect(findSourceMappingUrl("a\n//# sourceMappingURL=one.map\nb\n//# sourceMappingURL=two.map")).toBe("two.map"); + }); + + it("resolves an inline base64 map", async () => { + const script = `code\n//# sourceMappingURL=${inlineMap(["webpack://_N_E/./src/Card.tsx"])}`; + const cache = new SourceMapCache(() => Promise.resolve(script)); + const stack = "Error\n at Card (http://localhost:3000/_next/static/chunks/app.js:1:1)"; + const result = await resolveSource(stack, cache, "http://localhost:3000"); + expect(result).toEqual({ ok: true, location: { file: "src/Card.tsx", line: 42, column: 5 } }); + }); + + it("reports no-source-map when the script has no map", async () => { + const cache = new SourceMapCache(() => Promise.resolve("console.log(1)")); + const result = await resolveSource("Error\n at A (http://x.test/a.js:1:1)", cache, "http://x.test"); + expect(result).toEqual({ ok: false, reason: "no-source-map" }); + }); + + it("reports fetch-failed when the script cannot be loaded", async () => { + const cache = new SourceMapCache(() => Promise.resolve(null)); + const result = await resolveSource("Error\n at A (http://x.test/a.js:1:1)", cache, "http://x.test"); + expect(result).toEqual({ ok: false, reason: "fetch-failed" }); + }); + + it("caches at most the configured number of maps", async () => { + let fetches = 0; + const cache = new SourceMapCache(() => { + fetches += 1; + return Promise.resolve("no map here"); + }, 2); + for (const name of ["a", "b", "c", "a"]) { + await cache.symbolicate({ url: `http://x.test/${name}.js`, line: 1, column: 1 }, "http://x.test"); + } + expect(fetches).toBe(4); + }); +}); diff --git a/apps/browser-extension/src/content/source.ts b/apps/browser-extension/src/content/source.ts new file mode 100644 index 0000000..3a16a5d --- /dev/null +++ b/apps/browser-extension/src/content/source.ts @@ -0,0 +1,145 @@ +import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping"; + +export type SourceLocation = { file: string; line: number; column: number }; +export type StackFrame = { url: string; line: number; column: number }; + +const SKIPPED_FRAME = /node_modules|\/\.vite\/deps\/|react-dom|react_jsx-dev-runtime|jsx-dev-runtime|react-stack-top-frame/; +const FRAME_PATTERN = /((?:https?|file|webpack-internal|turbopack):[^\s()]*?):(\d+):(\d+)\)?\s*$/; + +/** Frames of a V8 stack string, in order, excluding the message line. */ +export function parseStack(stack: string): StackFrame[] { + const frames: StackFrame[] = []; + for (const raw of stack.split("\n")) { + const match = FRAME_PATTERN.exec(raw.trim()); + if (match === null) continue; + const [, url = "", line = "0", column = "0"] = match; + frames.push({ url, line: Number(line), column: Number(column) }); + } + return frames; +} + +/** Frames that belong to application code, in order. */ +export function applicationFrames(stack: string): StackFrame[] { + return parseStack(stack).filter((frame) => !SKIPPED_FRAME.test(frame.url)); +} + +/** Strips bundler prefixes, the page origin, query strings and a leading "./". */ +export function normalizeSourcePath(source: string, pageOrigin: string): string { + let path = source; + path = path.replace(/^webpack:\/\/_N_E\//, ""); + path = path.replace(/^webpack:\/\/\//, ""); + path = path.replace(/^webpack:\/\/[^/]+\//, ""); + path = path.replace(/^turbopack:\/\/\/\[project\]\//, ""); + path = path.replace(/^file:\/\/\//, ""); + path = path.replace(/^\/@fs\//, ""); + if (pageOrigin !== "" && path.startsWith(pageOrigin)) path = path.slice(pageOrigin.length); + path = path.replace(/[?#].*$/, ""); + path = path.replace(/^\.\//, ""); + return path.replace(/^\//, ""); +} + +export function isDependencyPath(path: string): boolean { + return path.includes("node_modules"); +} + +export type MapFetcher = (url: string) => Promise; + +export type SymbolicationResult = + | { ok: true; location: SourceLocation } + | { ok: false; reason: "no-source-map" | "fetch-failed" }; + +function decodeInlineMap(url: string): string | null { + const match = /^data:[^,]*;base64,(.*)$/.exec(url); + if (match === null) return null; + try { + const binary = atob(match[1] ?? ""); + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); + return new TextDecoder().decode(bytes); + } catch { + return null; + } +} + +/** The last //# sourceMappingURL= comment, or null. */ +export function findSourceMappingUrl(script: string): string | null { + const matches = [...script.matchAll(/\/\/[#@]\s*sourceMappingURL=([^\s]+)\s*$/gm)]; + return matches[matches.length - 1]?.[1] ?? null; +} + +/** Caches parsed maps per script URL, up to `limit` entries. */ +export class SourceMapCache { + private readonly maps = new Map(); + + constructor( + private readonly fetchText: MapFetcher, + private readonly limit = 20, + ) {} + + private remember(url: string, value: TraceMap | "none"): void { + if (this.maps.size >= this.limit) { + const oldest = this.maps.keys().next(); + if (oldest.done !== true) this.maps.delete(oldest.value); + } + this.maps.set(url, value); + } + + private async load(scriptUrl: string): Promise { + const cached = this.maps.get(scriptUrl); + if (cached !== undefined) return cached; + const script = await this.fetchText(scriptUrl); + if (script === null) return "failed"; + const mapUrl = findSourceMappingUrl(script); + if (mapUrl === null) { + this.remember(scriptUrl, "none"); + return "none"; + } + let mapText = decodeInlineMap(mapUrl); + if (mapText === null) { + const resolved = new URL(mapUrl, scriptUrl).href; + mapText = await this.fetchText(resolved); + if (mapText === null) return "failed"; + } + try { + const map = new TraceMap(mapText); + this.remember(scriptUrl, map); + return map; + } catch { + this.remember(scriptUrl, "none"); + return "none"; + } + } + + async symbolicate(frame: StackFrame, pageOrigin: string): Promise { + const map = await this.load(frame.url); + if (map === "failed") return { ok: false, reason: "fetch-failed" }; + if (map === "none") return { ok: false, reason: "no-source-map" }; + const original = originalPositionFor(map, { line: frame.line, column: Math.max(0, frame.column - 1) }); + if (original.source === null) return { ok: false, reason: "no-source-map" }; + return { + ok: true, + location: { + file: normalizeSourcePath(original.source, pageOrigin), + line: original.line, + column: original.column + 1, + }, + }; + } +} + +/** Resolves the first application frame to an original location; falls through node_modules results. */ +export async function resolveSource( + stack: string, + cache: SourceMapCache, + pageOrigin: string, +): Promise { + let failure: SymbolicationResult = { ok: false, reason: "no-source-map" }; + for (const frame of applicationFrames(stack).slice(0, 4)) { + const result = await cache.symbolicate(frame, pageOrigin); + if (result.ok) { + if (isDependencyPath(result.location.file)) continue; + return result; + } + failure = result; + } + return failure; +} diff --git a/apps/browser-extension/src/geometry.test.ts b/apps/browser-extension/src/geometry.test.ts new file mode 100644 index 0000000..8b47a3f --- /dev/null +++ b/apps/browser-extension/src/geometry.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { computeScale, rectsIntersect, toCssPoint, toViewportRect } from "./geometry"; + +const viewport = { x: 0, y: 0, width: 2880, height: 1600 }; + +describe("geometry", () => { + it("derives a 2x scale from a 2880 wide viewport and 1440 innerWidth", () => { + expect(computeScale(viewport, 1440, 800)).toEqual({ scale: 2 }); + }); + + it("handles browser zoom at 125% on a 150% display", () => { + const zoomed = { x: 0, y: 0, width: 1920, height: 1000 }; + expect(computeScale(zoomed, 1024, 533.33)?.scale).toBeCloseTo(1.875, 3); + }); + + it("reports a mismatch when the heights disagree (docked DevTools)", () => { + expect(computeScale(viewport, 1440, 500)).toBeNull(); + }); + + it("rejects degenerate sizes", () => { + expect(computeScale(viewport, 0, 800)).toBeNull(); + }); + + it("converts points and rects with rounding", () => { + expect(toCssPoint({ x: 400, y: 200 }, { scale: 2 })).toEqual({ x: 200, y: 100 }); + expect(toViewportRect({ x: 10.4, y: 20.6, width: 30.2, height: 5 }, { scale: 1.5 })).toEqual({ + x: 16, + y: 31, + width: 45, + height: 8, + }); + }); + + it("intersects rects", () => { + const a = { x: 0, y: 0, width: 10, height: 10 }; + expect(rectsIntersect(a, { x: 5, y: 5, width: 10, height: 10 })).toBe(true); + expect(rectsIntersect(a, { x: 10, y: 0, width: 5, height: 5 })).toBe(false); + }); +}); diff --git a/apps/browser-extension/src/geometry.ts b/apps/browser-extension/src/geometry.ts new file mode 100644 index 0000000..8d00318 --- /dev/null +++ b/apps/browser-extension/src/geometry.ts @@ -0,0 +1,41 @@ +import type { PhysicalRect, ViewportPoint, ViewportRect } from "@snaphub/devtools-protocol/protocol"; + +/** Tolerance, in physical px, between the expected and the reported viewport height. */ +export const MISMATCH_TOLERANCE_PX = 2; + +export type CssRect = { x: number; y: number; width: number; height: number }; + +export type Scale = { scale: number }; + +/** + * Physical px per CSS px, from the render widget's width and innerWidth. + * Returns null when the heights disagree (docked DevTools, side panel, wrong tab). + * Browser zoom is handled here; devicePixelRatio is never used. + */ +export function computeScale(viewport: PhysicalRect, innerWidth: number, innerHeight: number): Scale | null { + if (innerWidth <= 0 || innerHeight <= 0 || viewport.width <= 0) return null; + const scale = viewport.width / innerWidth; + if (Math.abs(innerHeight * scale - viewport.height) > MISMATCH_TOLERANCE_PX) return null; + return { scale }; +} + +export function toCssPoint(point: ViewportPoint, { scale }: Scale): ViewportPoint { + return { x: point.x / scale, y: point.y / scale }; +} + +export function toViewportRect(rect: CssRect, { scale }: Scale): ViewportRect { + return { + x: Math.round(rect.x * scale), + y: Math.round(rect.y * scale), + width: Math.round(rect.width * scale), + height: Math.round(rect.height * scale), + }; +} + +export function toCssRect(rect: ViewportRect, { scale }: Scale): CssRect { + return { x: rect.x / scale, y: rect.y / scale, width: rect.width / scale, height: rect.height / scale }; +} + +export function rectsIntersect(a: CssRect, b: CssRect): boolean { + return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; +} diff --git a/apps/browser-extension/src/link.test.ts b/apps/browser-extension/src/link.test.ts new file mode 100644 index 0000000..d7b96e1 --- /dev/null +++ b/apps/browser-extension/src/link.test.ts @@ -0,0 +1,180 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BACKOFF_MS, Link, PING_INTERVAL_MS, type SocketLike, type TokenStore } from "./link"; + +class FakeSocket implements SocketLike { + static instances: FakeSocket[] = []; + onopen: SocketLike["onopen"] = null; + onmessage: SocketLike["onmessage"] = null; + onclose: SocketLike["onclose"] = null; + onerror: SocketLike["onerror"] = null; + sent: unknown[] = []; + closed = false; + constructor(readonly url: string) { + FakeSocket.instances.push(this); + } + send(data: string): void { + this.sent.push(JSON.parse(data)); + } + close(): void { + this.closed = true; + } + open(): void { + this.onopen?.(new Event("open")); + } + fail(): void { + this.onclose?.(new CloseEvent("close")); + } + receive(message: object): void { + this.onmessage?.(new MessageEvent("message", { data: JSON.stringify({ v: 1, ...message }) })); + } +} + +const TOKEN = "t".repeat(43); + +function memoryStore(initial: string | null): TokenStore & { value: string | null } { + const store = { + value: initial, + get: (): Promise => Promise.resolve(store.value), + set: (token: string): Promise => { + store.value = token; + return Promise.resolve(); + }, + clear: (): Promise => { + store.value = null; + return Promise.resolve(); + }, + }; + return store; +} + +function make(token: string | null): { link: Link; store: ReturnType } { + const store = memoryStore(token); + const link = new Link({ + createSocket: (url): SocketLike => new FakeSocket(url), + store, + browser: { name: "Chrome", version: "130" }, + extensionVersion: "0.3.0", + handleRequest: (): Promise => Promise.resolve(null), + }); + return { link, store }; +} + +const last = (): FakeSocket => { + const socket = FakeSocket.instances[FakeSocket.instances.length - 1]; + if (socket === undefined) throw new Error("no socket"); + return socket; +}; + +beforeEach(() => { + vi.useFakeTimers(); + FakeSocket.instances = []; +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe("Link", () => { + it("reports no-token and opens nothing without a stored token", async () => { + const { link } = make(null); + await link.connect(); + expect(link.status.state).toBe("no-token"); + expect(FakeSocket.instances).toHaveLength(0); + }); + + it("sends hello, becomes connected on ready, then pings every 20 seconds", async () => { + const { link } = make(TOKEN); + await link.connect(); + last().open(); + expect(last().sent[0]).toMatchObject({ type: "hello", token: TOKEN }); + last().receive({ type: "ready" }); + expect(link.status.state).toBe("connected"); + await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS); + expect(last().sent[1]).toEqual({ v: 1, type: "ping" }); + await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS); + expect(last().sent).toHaveLength(3); + }); + + it("tries the next port when the first refuses, then reports unreachable", async () => { + const { link } = make(TOKEN); + await link.connect(); + expect(last().url).toBe("ws://127.0.0.1:47811"); + last().fail(); + expect(last().url).toBe("ws://127.0.0.1:47812"); + last().fail(); + last().fail(); + expect(link.status.state).toBe("unreachable"); + }); + + it("backs off 1s, 2s, 4s between reconnect attempts and resets after ready", async () => { + const { link } = make(TOKEN); + await link.connect(); + const failAll = (): void => { + for (let i = 0; i < 3; i += 1) last().fail(); + }; + failAll(); + const before = FakeSocket.instances.length; + await vi.advanceTimersByTimeAsync(BACKOFF_MS[0] - 1); + expect(FakeSocket.instances).toHaveLength(before); + await vi.advanceTimersByTimeAsync(1); + expect(FakeSocket.instances).toHaveLength(before + 1); + failAll(); + const second = FakeSocket.instances.length; + await vi.advanceTimersByTimeAsync(BACKOFF_MS[1]); + expect(FakeSocket.instances).toHaveLength(second + 1); + }); + + it("reconnects immediately when the popup opens (retry)", async () => { + const { link } = make(TOKEN); + await link.connect(); + for (let i = 0; i < 3; i += 1) last().fail(); + const before = FakeSocket.instances.length; + link.retry(); + await vi.advanceTimersByTimeAsync(0); + expect(FakeSocket.instances).toHaveLength(before + 1); + }); + + it("pairs with a pasted code containing a space, stores the token and says hello", async () => { + const { link, store } = make(null); + link.pair("123 456"); + last().open(); + expect(last().sent[0]).toMatchObject({ type: "pair", code: "123456" }); + last().receive({ type: "paired", token: TOKEN }); + await vi.advanceTimersByTimeAsync(0); + expect(store.value).toBe(TOKEN); + expect(last().sent[1]).toMatchObject({ type: "hello", token: TOKEN }); + }); + + it("rejects a malformed code without opening a socket", () => { + const { link } = make(null); + link.pair("12ab"); + expect(link.status.state).toBe("rejected"); + expect(FakeSocket.instances).toHaveLength(0); + }); + + it("shows a plain reason when pairing is rejected", () => { + const { link } = make(null); + link.pair("123456"); + last().open(); + last().receive({ type: "pairRejected", reason: "wrong-code" }); + expect(link.status).toMatchObject({ state: "rejected" }); + expect(link.status.reason).toMatch(/code/i); + }); + + it("clears the token when CapKit no longer knows it", async () => { + const { link, store } = make(TOKEN); + await link.connect(); + last().open(); + last().receive({ type: "helloRejected", reason: "unknown-token" }); + await vi.advanceTimersByTimeAsync(0); + expect(store.value).toBeNull(); + expect(link.status.state).toBe("rejected"); + }); + + it("ignores frames that fail validation", async () => { + const { link } = make(TOKEN); + await link.connect(); + last().open(); + last().receive({ type: "ready", extra: true }); + expect(link.status.state).toBe("connecting"); + }); +}); diff --git a/apps/browser-extension/src/link.ts b/apps/browser-extension/src/link.ts new file mode 100644 index 0000000..a759deeb --- /dev/null +++ b/apps/browser-extension/src/link.ts @@ -0,0 +1,216 @@ +import { + LINK_PORTS, + PROTOCOL_VERSION, + parseAppMessage, + type AppMessage, + type BrowserInfo, + type ExtensionMessage, +} from "@snaphub/devtools-protocol/protocol"; +import type { LinkStatus } from "./messages"; + +export const PING_INTERVAL_MS = 20_000; +export const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000] as const; + +export type SocketLike = { + onopen: ((event: Event) => void) | null; + onmessage: ((event: MessageEvent) => void) | null; + onclose: ((event: CloseEvent) => void) | null; + onerror: ((event: Event) => void) | null; + send: (data: string) => void; + close: () => void; +}; + +export type TokenStore = { + get: () => Promise; + set: (token: string) => Promise; + clear: () => Promise; +}; + +export type LinkOptions = { + createSocket: (url: string) => SocketLike; + store: TokenStore; + browser: BrowserInfo; + extensionVersion: string; + /** Answers a request from CapKit; null means no reply. */ + handleRequest: (message: AppMessage) => Promise; + onStatus?: (status: LinkStatus) => void; +}; + +const REJECT_TEXT: Record = { + "wrong-code": "That code doesn't match. Check the code in CapKit and try again.", + expired: "That code expired. Open Developer tools in CapKit for a new one.", + "too-many-attempts": "Too many wrong tries. Wait a minute, then pair again.", + "not-pairing": "CapKit isn't waiting for a code. Open Developer tools in CapKit and start pairing.", + "unknown-token": "CapKit no longer knows this browser. Pair again.", +}; + +/** Localhost WebSocket link to CapKit: pairing, hello, ping and request routing. */ +export class Link { + status: LinkStatus = { state: "connecting" }; + private socket: SocketLike | null = null; + private pingTimer: ReturnType | null = null; + private retryTimer: ReturnType | null = null; + private attempt = 0; + private generation = 0; + + constructor(private readonly options: LinkOptions) {} + + private setStatus(status: LinkStatus): void { + this.status = status; + this.options.onStatus?.(status); + } + + private frame(message: ExtensionMessage): string { + return JSON.stringify(message); + } + + /** Connects with the stored token; without one the state is "no-token". */ + async connect(): Promise { + const token = await this.options.store.get(); + if (token === null) { + this.setStatus({ state: "no-token" }); + return; + } + this.setStatus({ state: "connecting" }); + this.open({ kind: "hello", token }); + } + + /** Pairs with a six-digit code, accepting a pasted code with spaces. */ + pair(rawCode: string): void { + const code = rawCode.replaceAll(/\s+/g, ""); + if (!/^\d{6}$/.test(code)) { + this.setStatus({ state: "rejected", reason: "Enter the 6-digit code shown in CapKit." }); + return; + } + this.setStatus({ state: "connecting" }); + this.open({ kind: "pair", code }); + } + + /** Popup opened or Retry pressed: reset backoff and try now. */ + retry(): void { + this.attempt = 0; + if (this.status.state === "connected" || this.status.state === "rejected" || this.status.state === "no-token") return; + this.clearRetry(); + void this.connect(); + } + + async forget(): Promise { + await this.options.store.clear(); + this.teardown(); + this.setStatus({ state: "no-token" }); + } + + private clearRetry(): void { + if (this.retryTimer !== null) clearTimeout(this.retryTimer); + this.retryTimer = null; + } + + private teardown(): void { + this.generation += 1; + this.clearRetry(); + if (this.pingTimer !== null) clearInterval(this.pingTimer); + this.pingTimer = null; + const socket = this.socket; + this.socket = null; + if (socket !== null) { + socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null; + socket.close(); + } + } + + private open(intent: { kind: "hello"; token: string } | { kind: "pair"; code: string }, portIndex = 0): void { + this.teardown(); + const generation = this.generation; + const port = LINK_PORTS[portIndex]; + if (port === undefined) { + this.unreachable(); + return; + } + const socket = this.options.createSocket(`ws://127.0.0.1:${String(port)}`); + this.socket = socket; + let opened = false; + const failed = (): void => { + if (generation !== this.generation) return; + if (!opened) { + this.open(intent, portIndex + 1); + return; + } + this.teardown(); + this.unreachable(); + }; + socket.onopen = (): void => { + if (generation !== this.generation) return; + opened = true; + const common = { v: PROTOCOL_VERSION, browser: this.options.browser, extensionVersion: this.options.extensionVersion } as const; + socket.send( + this.frame( + intent.kind === "hello" + ? { ...common, type: "hello", token: intent.token } + : { ...common, type: "pair", code: intent.code }, + ), + ); + }; + socket.onerror = (): void => { + // The close event that follows drives recovery. + }; + socket.onclose = failed; + socket.onmessage = (event): void => { + if (generation !== this.generation || typeof event.data !== "string") return; + const message = parseAppMessage(event.data); + if (message !== null) void this.onMessage(message, socket); + }; + } + + private unreachable(): void { + this.setStatus({ state: "unreachable" }); + const delay = BACKOFF_MS[Math.min(this.attempt, BACKOFF_MS.length - 1)] ?? 30_000; + this.attempt += 1; + this.clearRetry(); + this.retryTimer = setTimeout(() => { + void this.connect(); + }, delay); + } + + private async onMessage(message: AppMessage, socket: SocketLike): Promise { + switch (message.type) { + case "paired": + await this.options.store.set(message.token); + socket.send( + this.frame({ + v: PROTOCOL_VERSION, + type: "hello", + token: message.token, + browser: this.options.browser, + extensionVersion: this.options.extensionVersion, + }), + ); + return; + case "pairRejected": + this.teardown(); + this.setStatus({ state: "rejected", reason: REJECT_TEXT[message.reason] ?? "Pairing was rejected." }); + return; + case "helloRejected": + await this.options.store.clear(); + this.teardown(); + this.setStatus({ state: "rejected", reason: REJECT_TEXT["unknown-token"] ?? "Pair again." }); + return; + case "ready": + this.attempt = 0; + this.setStatus({ state: "connected" }); + if (this.pingTimer !== null) clearInterval(this.pingTimer); + this.pingTimer = setInterval(() => { + socket.send(this.frame({ v: PROTOCOL_VERSION, type: "ping" })); + }, PING_INTERVAL_MS); + return; + case "pong": + return; + case "hitTest": + case "inspect": + case "findSensitive": { + const reply = await this.options.handleRequest(message); + if (reply !== null && this.socket === socket) socket.send(this.frame(reply)); + return; + } + } + } +} diff --git a/apps/browser-extension/src/messages.ts b/apps/browser-extension/src/messages.ts new file mode 100644 index 0000000..78a1066 --- /dev/null +++ b/apps/browser-extension/src/messages.ts @@ -0,0 +1,68 @@ +import { z } from "zod"; +import { + cssViewportSchema, + elementDetailsSchema, + hitElementSchema, + physicalRectSchema, + resultStatusSchema, + sensitiveMatchSchema, + viewportPointSchema, +} from "@snaphub/devtools-protocol/protocol"; + +/** Messages from the background worker to the content script of a tab. */ +export const pageRequestSchema = z.discriminatedUnion("kind", [ + z.strictObject({ kind: z.literal("hitTest"), viewport: physicalRectSchema, point: viewportPointSchema }), + z.strictObject({ + kind: z.literal("inspect"), + viewport: physicalRectSchema, + point: viewportPointSchema.optional(), + area: physicalRectSchema.optional(), + }), + z.strictObject({ kind: z.literal("findSensitive"), viewport: physicalRectSchema, area: physicalRectSchema }), + z.strictObject({ kind: z.literal("toggle") }), + z.strictObject({ kind: z.literal("ping") }), +]); +export type PageRequest = z.infer; + +export const pageResponseSchema = z.discriminatedUnion("kind", [ + z.strictObject({ kind: z.literal("hitTest"), status: resultStatusSchema, elements: z.array(hitElementSchema) }), + z.strictObject({ + kind: z.literal("inspect"), + status: resultStatusSchema, + cssViewport: cssViewportSchema.optional(), + elements: z.array(elementDetailsSchema), + }), + z.strictObject({ kind: z.literal("findSensitive"), status: resultStatusSchema, matches: z.array(sensitiveMatchSchema) }), + z.strictObject({ kind: z.literal("ok") }), +]); +export type PageResponse = z.infer; + +/** Messages from a content script or the popup to the background worker. */ +export const backgroundRequestSchema = z.discriminatedUnion("kind", [ + z.strictObject({ kind: z.literal("injectMain") }), + z.strictObject({ kind: z.literal("captureVisible") }), + z.strictObject({ kind: z.literal("status") }), + z.strictObject({ kind: z.literal("pair"), code: z.string() }), + z.strictObject({ kind: z.literal("retry") }), + z.strictObject({ kind: z.literal("forget") }), + z.strictObject({ kind: z.literal("inspectActiveTab") }), + z.strictObject({ kind: z.literal("siteAccess"), tabId: z.number().int().optional() }), + z.strictObject({ kind: z.literal("requestAccess"), origin: z.string(), all: z.boolean() }), +]); +export type BackgroundRequest = z.infer; + +export const linkStateSchema = z.enum(["no-token", "connecting", "connected", "unreachable", "rejected"]); +export type LinkState = z.infer; + +export const linkStatusSchema = z.strictObject({ + state: linkStateSchema, + reason: z.string().optional(), +}); +export type LinkStatus = z.infer; + +export const siteAccessSchema = z.strictObject({ + state: z.enum(["allowed", "needs-access", "unavailable"]), + origin: z.string().optional(), +}); +export type SiteAccess = z.infer; + diff --git a/apps/browser-extension/src/popup/Popup.test.tsx b/apps/browser-extension/src/popup/Popup.test.tsx new file mode 100644 index 0000000..a36940e --- /dev/null +++ b/apps/browser-extension/src/popup/Popup.test.tsx @@ -0,0 +1,103 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; +import type { BackgroundRequest } from "../messages"; +import { Popup, type Transport } from "./Popup"; + +type Replies = Partial>; + +function fake(replies: Replies): { send: Transport; calls: BackgroundRequest[] } { + const calls: BackgroundRequest[] = []; + const send: Transport = (request) => { + calls.push(request); + return Promise.resolve(replies[request.kind] ?? { ok: true }); + }; + return { send, calls }; +} + +describe("Popup", () => { + it("asks the background to reconnect when it opens", async () => { + const { send, calls } = fake({ retry: { state: "connected" }, siteAccess: { state: "allowed", origin: "http://localhost/*" } }); + render(); + await screen.findByText("Connected to CapKit"); + expect(calls[0]).toEqual({ kind: "retry" }); + }); + + it("shows the pairing input with numeric one-time-code attributes when there is no token", async () => { + const { send } = fake({ retry: { state: "no-token" } }); + render(); + const input = await screen.findByLabelText(/6-digit code/i); + expect(input).toHaveAttribute("inputmode", "numeric"); + expect(input).toHaveAttribute("autocomplete", "one-time-code"); + expect(input).toHaveAttribute("maxlength", "6"); + }); + + it("accepts a pasted code with a space and submits it", async () => { + const { send, calls } = fake({ retry: { state: "no-token" }, pair: { state: "connected" }, siteAccess: { state: "unavailable" } }); + const user = userEvent.setup(); + render(); + const input = await screen.findByLabelText(/6-digit code/i); + await user.click(input); + await user.paste("123 456"); + expect(input).toHaveValue("123456"); + await user.click(screen.getByRole("button", { name: "Pair" })); + await waitFor(() => { + expect(calls).toContainEqual({ kind: "pair", code: "123456" }); + }); + await screen.findByText("Connected to CapKit"); + }); + + it("keeps Pair disabled until six digits are entered", async () => { + const { send } = fake({ retry: { state: "no-token" } }); + const user = userEvent.setup(); + render(); + const input = await screen.findByLabelText(/6-digit code/i); + await user.type(input, "12ab3"); + expect(input).toHaveValue("123"); + expect(screen.getByRole("button", { name: "Pair" })).toBeDisabled(); + }); + + it("explains an unreachable CapKit and retries", async () => { + const { send, calls } = fake({ retry: { state: "unreachable" } }); + const user = userEvent.setup(); + render(); + await screen.findByText(/isn't running or Developer tools is off/i); + await user.click(screen.getByRole("button", { name: "Retry" })); + expect(calls.filter((c) => c.kind === "retry")).toHaveLength(2); + }); + + it("shows the rejection reason with a Pair again button", async () => { + const { send } = fake({ retry: { state: "rejected", reason: "That code expired. Open Developer tools in CapKit for a new one." } }); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("That code expired"); + expect(screen.getByRole("button", { name: "Pair again" })).toBeInTheDocument(); + }); + + it("offers site access when the page needs it", async () => { + const { send, calls } = fake({ + retry: { state: "connected" }, + siteAccess: { state: "needs-access", origin: "https://example.com/*" }, + }); + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Allow on this site" })); + expect(calls).toContainEqual({ kind: "requestAccess", origin: "https://example.com/*", all: false }); + expect(screen.getByRole("button", { name: "Allow on all sites" })).toBeInTheDocument(); + }); + + it("says when the page can't be inspected", async () => { + const { send } = fake({ retry: { state: "connected" }, siteAccess: { state: "unavailable" } }); + render(); + expect(await screen.findByText("Not available on this page")).toBeInTheDocument(); + }); + + it("starts the inspector from Inspect page", async () => { + const close = vi.spyOn(window, "close").mockImplementation(() => undefined); + const { send, calls } = fake({ retry: { state: "connected" }, siteAccess: { state: "allowed", origin: "http://localhost/*" } }); + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Inspect page" })); + expect(calls).toContainEqual({ kind: "inspectActiveTab" }); + close.mockRestore(); + }); +}); diff --git a/apps/browser-extension/src/popup/Popup.tsx b/apps/browser-extension/src/popup/Popup.tsx new file mode 100644 index 0000000..14623f2 --- /dev/null +++ b/apps/browser-extension/src/popup/Popup.tsx @@ -0,0 +1,200 @@ +import { useCallback, useEffect, useState, type ClipboardEvent, type SyntheticEvent, type ReactElement } from "react"; +import { linkStatusSchema, siteAccessSchema, type BackgroundRequest, type LinkStatus, type SiteAccess } from "../messages"; + +export type Transport = (request: BackgroundRequest) => Promise; + +const SPINNER_DELAY_MS = 300; +const SETTLE_POLL_MS = 400; +const SETTLE_ATTEMPTS = 8; + +const button = + "rounded-md border border-hairline bg-graphite-raised px-3 py-1.5 text-sm font-medium text-ink transition-[transform,background-color] duration-100 ease-out-strong hover:bg-white/10 active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent motion-reduce:active:scale-100"; +const primary = + "rounded-md bg-accent px-3 py-1.5 text-sm font-semibold text-graphite transition-[transform,opacity] duration-100 ease-out-strong hover:opacity-90 active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:opacity-40 motion-reduce:active:scale-100"; + +function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function Spinner(): ReactElement { + return ( + + ); +} + +export function Popup({ send }: { send: Transport }): ReactElement { + const [status, setStatus] = useState({ state: "connecting" }); + const [access, setAccess] = useState(null); + const [code, setCode] = useState(""); + const [showSpinner, setShowSpinner] = useState(false); + + const read = useCallback( + async (request: BackgroundRequest): Promise => { + const parsed = linkStatusSchema.safeParse(await send(request)); + return parsed.success ? parsed.data : { state: "unreachable" }; + }, + [send], + ); + + const settle = useCallback( + async (first: BackgroundRequest): Promise => { + let next = await read(first); + setStatus(next); + for (let i = 0; i < SETTLE_ATTEMPTS && next.state === "connecting"; i += 1) { + await wait(SETTLE_POLL_MS); + next = await read({ kind: "status" }); + setStatus(next); + } + }, + [read], + ); + + useEffect(() => { + void settle({ kind: "retry" }); + }, [settle]); + + useEffect(() => { + if (status.state !== "connected") return; + void send({ kind: "siteAccess" }).then((raw) => { + const parsed = siteAccessSchema.safeParse(raw); + setAccess(parsed.success ? parsed.data : { state: "unavailable" }); + }); + }, [status.state, send]); + + useEffect(() => { + if (status.state !== "connecting") { + setShowSpinner(false); + return; + } + const timer = setTimeout(() => { + setShowSpinner(true); + }, SPINNER_DELAY_MS); + return (): void => { + clearTimeout(timer); + }; + }, [status.state]); + + const onPaste = (event: ClipboardEvent): void => { + event.preventDefault(); + setCode(event.clipboardData.getData("text").replaceAll(/\D/g, "").slice(0, 6)); + }; + + const submit = (event: SyntheticEvent): void => { + event.preventDefault(); + void settle({ kind: "pair", code }); + }; + + const requestAccess = (all: boolean): void => { + void send({ kind: "requestAccess", origin: access?.origin ?? "", all }).then(() => send({ kind: "siteAccess" })).then((raw) => { + const parsed = siteAccessSchema.safeParse(raw); + if (parsed.success) setAccess(parsed.data); + }); + }; + + return ( +
+

CapKit Inspector

+ + {status.state === "no-token" || status.state === "rejected" ? ( +
+ + { + setCode(event.target.value.replaceAll(/\D/g, "")); + }} + className="rounded-md border border-hairline bg-graphite-raised px-3 py-2 font-mono text-lg tracking-[0.3em] tabular-nums text-ink focus-visible:outline-2 focus-visible:outline-accent" + /> + {status.state === "rejected" && status.reason !== undefined ? ( +

+ {status.reason} +

+ ) : null} + +
+ ) : null} + + {status.state === "connecting" ? ( +

+ {showSpinner ? : null} + Connecting to CapKit… +

+ ) : null} + + {status.state === "unreachable" ? ( +
+

CapKit isn't running or Developer tools is off.

+ +
+ ) : null} + + {status.state === "connected" ? ( +
+

+

+ +
+ Site access + {access?.state === "allowed" ? Allowed : null} + {access?.state === "unavailable" ? Not available on this page : null} + {access?.state === "needs-access" ? ( + + ) : null} +
+ {access?.state === "needs-access" ? ( + + ) : null} +
+ ) : null} +
+ ); +} diff --git a/apps/browser-extension/src/popup/index.html b/apps/browser-extension/src/popup/index.html new file mode 100644 index 0000000..78d861a --- /dev/null +++ b/apps/browser-extension/src/popup/index.html @@ -0,0 +1,12 @@ + + + + + + CapKit Inspector + + +
+ + + diff --git a/apps/browser-extension/src/popup/main.tsx b/apps/browser-extension/src/popup/main.tsx new file mode 100644 index 0000000..bc8f036 --- /dev/null +++ b/apps/browser-extension/src/popup/main.tsx @@ -0,0 +1,27 @@ +import { StrictMode, type ReactElement } from "react"; +import { createRoot } from "react-dom/client"; +import { Popup, type Transport } from "./Popup"; +import "./popup.css"; + +const transport: Transport = (request) => chrome.runtime.sendMessage(request); + +function registerFonts(): void { + const url = (file: string): string => chrome.runtime.getURL(`fonts/${file}`); + const style = document.createElement("style"); + style.textContent = [ + `@font-face{font-family:"CapKit Sans";src:url("${url("plus-jakarta-sans-latin-wght-normal.woff2")}") format("woff2");font-weight:200 800}`, + `@font-face{font-family:"CapKit Mono";src:url("${url("jetbrains-mono-latin-wght-normal.woff2")}") format("woff2");font-weight:100 800}`, + ].join(""); + document.head.append(style); +} + +registerFonts(); +const container = document.getElementById("root"); +if (container !== null) { + const app: ReactElement = ( + + + + ); + createRoot(container).render(app); +} diff --git a/apps/browser-extension/src/popup/popup.css b/apps/browser-extension/src/popup/popup.css new file mode 100644 index 0000000..8a6cb0a --- /dev/null +++ b/apps/browser-extension/src/popup/popup.css @@ -0,0 +1,27 @@ +@import "tailwindcss"; + +@theme { + --color-graphite: #1b1c1a; + --color-graphite-raised: #242522; + --color-ink: #f2f1ec; + --color-ink-muted: #a9a89f; + --color-accent: #d9ff43; + --color-danger: #ff6b5e; + --color-hairline: rgb(255 255 255 / 9%); + --font-sans: "CapKit Sans", "Plus Jakarta Sans", system-ui, sans-serif; + --font-mono: "CapKit Mono", "JetBrains Mono", ui-monospace, Consolas, monospace; + --ease-out-strong: cubic-bezier(0.23, 1, 0.32, 1); +} + +html, +body { + margin: 0; + background: var(--color-graphite); + color: var(--color-ink); + font-family: var(--font-sans); + -webkit-font-smoothing: antialiased; +} + +body { + width: 320px; +} diff --git a/apps/browser-extension/src/tabs.test.ts b/apps/browser-extension/src/tabs.test.ts new file mode 100644 index 0000000..d65dc64 --- /dev/null +++ b/apps/browser-extension/src/tabs.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { matchTab, originPattern } from "./tabs"; + +const tabs = [ + { id: 1, url: "http://localhost:5173/", title: "Vite + React" }, + { id: 2, url: "https://example.com/", title: "Example Domain" }, +]; + +describe("matchTab", () => { + it("matches the tab whose title starts the window title", () => { + expect(matchTab("Example Domain - Google Chrome", tabs)?.id).toBe(2); + }); + it("returns null when no title matches", () => { + expect(matchTab("Something else - Google Chrome", tabs)).toBeNull(); + }); + it("prefers the longest matching title", () => { + const extra = [...tabs, { id: 3, url: "https://a.test/", title: "Vite" }]; + expect(matchTab("Vite + React - Microsoft Edge", extra)?.id).toBe(1); + }); + it("ignores tabs with empty titles", () => { + expect(matchTab("Anything", [{ id: 4, url: "https://b.test/", title: "" }])).toBeNull(); + }); +}); + +describe("originPattern", () => { + it("drops the port because match patterns cover every port", () => { + expect(originPattern("http://localhost:5173/a?b")).toBe("http://localhost/*"); + }); + it("rejects non-web pages", () => { + expect(originPattern("chrome://extensions")).toBeNull(); + expect(originPattern("not a url")).toBeNull(); + }); +}); diff --git a/apps/browser-extension/src/tabs.ts b/apps/browser-extension/src/tabs.ts new file mode 100644 index 0000000..eebaa35 --- /dev/null +++ b/apps/browser-extension/src/tabs.ts @@ -0,0 +1,94 @@ +import type { ResultStatus } from "@snaphub/devtools-protocol/protocol"; +import { pageResponseSchema, type PageRequest, type PageResponse, type SiteAccess } from "./messages"; + +const ISOLATED_FILE = "content/isolated.js"; +const MAIN_FILE = "content/main-world.js"; + +export type TabRef = { id: number; url: string; title: string }; + +/** Origin match pattern for a page URL. Match patterns carry no port, so one pattern covers every port. */ +export function originPattern(url: string): string | null { + try { + const parsed = new URL(url); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + return `${parsed.protocol}//${parsed.hostname}/*`; + } catch { + return null; + } +} + +/** The window title is " - "; pick the active tab whose title the window title starts with. */ +export function matchTab(windowTitle: string, tabs: readonly TabRef[]): TabRef | null { + let best: TabRef | null = null; + for (const tab of tabs) { + if (tab.title === "" || !windowTitle.startsWith(tab.title)) continue; + if (best === null || tab.title.length > best.title.length) best = tab; + } + return best; +} + +export async function activeTabs(): Promise { + const tabs = await chrome.tabs.query({ active: true }); + const result: TabRef[] = []; + for (const tab of tabs) { + if (tab.id !== undefined) result.push({ id: tab.id, url: tab.url ?? "", title: tab.title ?? "" }); + } + return result; +} + +export async function hasAccess(url: string): Promise { + const pattern = originPattern(url); + if (pattern === null) return false; + return chrome.permissions.contains({ origins: [pattern] }); +} + +export async function siteAccessFor(tab: TabRef | null): Promise { + if (tab === null) return { state: "unavailable" }; + const pattern = originPattern(tab.url); + if (pattern === null) return { state: "unavailable" }; + return (await hasAccess(tab.url)) ? { state: "allowed", origin: pattern } : { state: "needs-access", origin: pattern }; +} + +async function ping(tabId: number): Promise { + try { + const response: unknown = await chrome.tabs.sendMessage(tabId, { kind: "ping" }); + return pageResponseSchema.safeParse(response).success; + } catch { + return false; + } +} + +/** Injects the isolated content script once; a second injection is a no-op because the script guards itself. */ +export async function ensureInjected(tabId: number): Promise { + if (await ping(tabId)) return true; + try { + await chrome.scripting.executeScript({ target: { tabId }, files: [ISOLATED_FILE] }); + } catch { + return false; + } + return ping(tabId); +} + +export async function injectMainWorld(tabId: number): Promise { + try { + await chrome.scripting.executeScript({ target: { tabId }, world: "MAIN", files: [MAIN_FILE] }); + return true; + } catch { + return false; + } +} + +export type PageResult = { status: ResultStatus; response: PageResponse | null }; + +/** Sends a request to a tab's content script, injecting it first. Never throws. */ +export async function askTab(tab: TabRef, request: PageRequest): Promise { + if (!(await hasAccess(tab.url))) return { status: "no-access", response: null }; + if (!(await ensureInjected(tab.id))) return { status: "error", response: null }; + try { + const raw: unknown = await chrome.tabs.sendMessage(tab.id, request); + const parsed = pageResponseSchema.safeParse(raw); + return parsed.success ? { status: "ok", response: parsed.data } : { status: "error", response: null }; + } catch { + return { status: "error", response: null }; + } +} diff --git a/apps/browser-extension/src/test-setup.ts b/apps/browser-extension/src/test-setup.ts new file mode 100644 index 0000000..f149f27 --- /dev/null +++ b/apps/browser-extension/src/test-setup.ts @@ -0,0 +1 @@ +import "@testing-library/jest-dom/vitest"; diff --git a/apps/browser-extension/src/vite-env.d.ts b/apps/browser-extension/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/apps/browser-extension/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/apps/browser-extension/tsconfig.json b/apps/browser-extension/tsconfig.json new file mode 100644 index 0000000..2bdf245 --- /dev/null +++ b/apps/browser-extension/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "isolatedModules": true, + "noEmit": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": ["chrome", "vitest/globals", "@testing-library/jest-dom"] + }, + "include": ["src", "vitest.config.ts"] +} diff --git a/apps/browser-extension/vitest.config.ts b/apps/browser-extension/vitest.config.ts new file mode 100644 index 0000000..c3613bd --- /dev/null +++ b/apps/browser-extension/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "jsdom", + globals: true, + clearMocks: true, + setupFiles: ["./src/test-setup.ts"], + }, +}); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 7c09392..ca8f000 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -21,6 +21,7 @@ "@fontsource-variable/plus-jakarta-sans": "5.2.8", "@hugeicons/core-free-icons": "4.2.3", "@hugeicons/react": "1.1.9", + "@snaphub/devtools-protocol": "workspace:*", "@tauri-apps/api": "^2.11.1", "@tauri-apps/plugin-dialog": "^2.7.1", "@tauri-apps/plugin-global-shortcut": "^2.3.2", diff --git a/apps/desktop/src/lib/redactionPatterns.ts b/apps/desktop/src/lib/redactionPatterns.ts index e06af06..c093476 100644 --- a/apps/desktop/src/lib/redactionPatterns.ts +++ b/apps/desktop/src/lib/redactionPatterns.ts @@ -1,123 +1,27 @@ import type { Rect, RecognizedLine, RecognizedText } from "../domain/capture"; - -export type SensitiveKind = "token" | "card" | "email" | "phone" | "secret"; - -export type SensitiveSpan = { - kind: SensitiveKind; - start: number; - end: number; -}; +import { findSensitiveSpans, maskPreview, type SensitiveKind } from "@snaphub/devtools-protocol/sensitive"; + +export { + SENSITIVE_KIND_LABELS, + findSensitiveSpans, + maskPreview, + maskSensitiveText, + passesLuhn, + shannonEntropy, +} from "@snaphub/devtools-protocol/sensitive"; +export type { SensitiveKind, SensitiveSpan, WebSensitiveKind } from "@snaphub/devtools-protocol/sensitive"; export type RedactionSuggestion = { id: string; - kind: SensitiveKind; + kind: SensitiveKind | "password"; /** A masked preview, so the list never repeats a full secret. */ preview: string; /** Selection-local logical pixels, padded and clamped to the selection. */ bounds: Rect; }; -export const SENSITIVE_KIND_LABELS: Readonly> = { - token: "API key or token", - card: "Card number", - email: "Email address", - phone: "Phone number", - secret: "Possible secret", -}; - -const TOKEN_PATTERN = - /\b(?:sk-(?:proj-|ant-)?[A-Za-z0-9_-]{16,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[abprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})/g; -const CARD_PATTERN = /\b\d(?:[ -]?\d){12,18}\b/g; -const EMAIL_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g; -const PHONE_PATTERN = /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?)?\d{2,5}(?:[\s.-]?\d{2,5}){1,4}/g; -const SECRET_CANDIDATE_PATTERN = /[A-Za-z0-9+/=_-]{24,}/g; - -/** Below this, long identifiers such as `getElementByIdOrThrow` stop qualifying. */ -const SECRET_MIN_ENTROPY_BITS = 3.5; const BOUNDS_PADDING = 3; -/** Card-number checksum; it removes most random 13–19 digit runs. */ -export function passesLuhn(digits: string): boolean { - if (!/^\d{13,19}$/.test(digits)) return false; - let sum = 0; - for (let index = 0; index < digits.length; index += 1) { - let digit = Number(digits[digits.length - 1 - index]); - if (index % 2 === 1) { - digit *= 2; - if (digit > 9) digit -= 9; - } - sum += digit; - } - return sum % 10 === 0; -} - -/** Shannon entropy in bits per character. */ -export function shannonEntropy(value: string): number { - if (value.length === 0) return 0; - const counts = new Map(); - for (const character of value) counts.set(character, (counts.get(character) ?? 0) + 1); - let entropy = 0; - for (const count of counts.values()) { - const probability = count / value.length; - entropy -= probability * Math.log2(probability); - } - return entropy; -} - -function digitCount(value: string): number { - return value.replace(/\D/g, "").length; -} - -function looksLikeSecret(value: string): boolean { - return /[A-Za-z]/.test(value) - && /\d/.test(value) - && shannonEntropy(value) >= SECRET_MIN_ENTROPY_BITS; -} - -type Matcher = { - kind: SensitiveKind; - pattern: RegExp; - accepts: (match: string) => boolean; -}; - -// Ordered by confidence: an earlier matcher claims overlapping text first. -const MATCHERS: readonly Matcher[] = [ - { kind: "token", pattern: TOKEN_PATTERN, accepts: () => true }, - { kind: "card", pattern: CARD_PATTERN, accepts: (match) => passesLuhn(match.replace(/\D/g, "")) }, - { kind: "email", pattern: EMAIL_PATTERN, accepts: () => true }, - { - kind: "phone", - pattern: PHONE_PATTERN, - accepts: (match): boolean => { - const digits = digitCount(match); - return digits >= 10 && digits <= 15; - }, - }, - { kind: "secret", pattern: SECRET_CANDIDATE_PATTERN, accepts: looksLikeSecret }, -]; - -/** Finds sensitive spans in one line of text. Spans never overlap. */ -export function findSensitiveSpans(text: string): SensitiveSpan[] { - const spans: SensitiveSpan[] = []; - for (const matcher of MATCHERS) { - for (const match of text.matchAll(matcher.pattern)) { - const value = match[0].trim(); - if (value.length === 0 || !matcher.accepts(value)) continue; - const start = match.index + match[0].indexOf(value); - const end = start + value.length; - if (spans.some((span) => start < span.end && end > span.start)) continue; - spans.push({ kind: matcher.kind, start, end }); - } - } - return spans.sort((left, right) => left.start - right.start); -} - -/** Masks all but the first and last two characters. */ -export function maskPreview(value: string): string { - if (value.length <= 6) return "•".repeat(value.length); - return `${value.slice(0, 2)}${"•".repeat(Math.min(8, value.length - 4))}${value.slice(-2)}`; -} - type PositionedWord = { start: number; end: number; diff --git a/package.json b/package.json index 159249c..006a7eb 100644 --- a/package.json +++ b/package.json @@ -6,10 +6,10 @@ "scripts": { "dev": "pnpm --filter @snaphub/desktop dev", "build": "pnpm --filter @snaphub/desktop build", - "typecheck": "pnpm --filter @snaphub/desktop typecheck", - "lint": "pnpm --filter @snaphub/desktop lint", - "lint:fix": "pnpm --filter @snaphub/desktop lint:fix", - "test": "pnpm --filter @snaphub/desktop test", + "typecheck": "pnpm --filter @snaphub/desktop --filter @snaphub/devtools-protocol --filter @snaphub/browser-extension typecheck", + "lint": "pnpm --filter @snaphub/desktop --filter @snaphub/devtools-protocol --filter @snaphub/browser-extension lint", + "lint:fix": "pnpm --filter @snaphub/desktop --filter @snaphub/devtools-protocol --filter @snaphub/browser-extension lint:fix", + "test": "pnpm --filter @snaphub/desktop --filter @snaphub/devtools-protocol --filter @snaphub/browser-extension test", "tauri": "pnpm --filter @snaphub/desktop tauri", "bundle": "pnpm --filter @snaphub/desktop bundle", "bundle:windows": "pnpm --filter @snaphub/desktop bundle:windows", @@ -17,6 +17,8 @@ "test:store": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/test-msix.ps1", "version:bump": "node scripts/bump-version.ts", "version:check": "node scripts/check-version.ts", - "notices": "node scripts/third-party-notices.ts" + "notices": "node scripts/third-party-notices.ts", + "ext:build": "pnpm --filter @snaphub/browser-extension build", + "ext:dev": "pnpm --filter @snaphub/browser-extension dev" } } diff --git a/packages/devtools-protocol/eslint.config.js b/packages/devtools-protocol/eslint.config.js new file mode 100644 index 0000000..65bc204 --- /dev/null +++ b/packages/devtools-protocol/eslint.config.js @@ -0,0 +1,22 @@ +import eslint from "@eslint/js"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { ignores: ["dist", "eslint.config.js"] }, + eslint.configs.recommended, + ...tseslint.configs.strictTypeChecked, + ...tseslint.configs.stylisticTypeChecked, + { + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + "@typescript-eslint/consistent-type-definitions": ["error", "type"], + "@typescript-eslint/explicit-function-return-type": "error", + "@typescript-eslint/no-confusing-void-expression": "off", + }, + }, +); diff --git a/packages/devtools-protocol/package.json b/packages/devtools-protocol/package.json new file mode 100644 index 0000000..c9b99de --- /dev/null +++ b/packages/devtools-protocol/package.json @@ -0,0 +1,29 @@ +{ + "name": "@snaphub/devtools-protocol", + "version": "0.3.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./protocol": "./src/protocol.ts", + "./markdown": "./src/markdown.ts", + "./sensitive": "./src/sensitive.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --pretty false", + "lint": "eslint . --max-warnings 0", + "lint:fix": "eslint . --fix --max-warnings 0", + "test": "vitest run" + }, + "dependencies": { + "zod": "^4.4.3" + }, + "devDependencies": { + "@eslint/js": "^9.39.5", + "@types/node": "^26.1.1", + "eslint": "^9.39.5", + "typescript": "^6.0.3", + "typescript-eslint": "^8.64.0", + "vitest": "^4.1.10" + } +} diff --git a/packages/devtools-protocol/src/index.ts b/packages/devtools-protocol/src/index.ts new file mode 100644 index 0000000..32a8f9b --- /dev/null +++ b/packages/devtools-protocol/src/index.ts @@ -0,0 +1,3 @@ +export * from "./protocol"; +export * from "./markdown"; +export * from "./sensitive"; diff --git a/packages/devtools-protocol/src/markdown.test.ts b/packages/devtools-protocol/src/markdown.test.ts new file mode 100644 index 0000000..4f35770 --- /dev/null +++ b/packages/devtools-protocol/src/markdown.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { buildElementMarkdown, buildNoteMarkdown, toHexColor } from "./markdown"; +import type { ElementDetails } from "./protocol"; + +const rect = { x: 10, y: 20, width: 100, height: 40 }; +const styles = { + color: "rgb(17, 24, 39)", + backgroundColor: "rgba(0, 0, 0, 0)", + fontFamily: '"Inter", sans-serif', + fontSize: "14px", + fontWeight: "600", + lineHeight: "20px", + padding: "8px 12px", + margin: "0px", + borderRadius: "6px", + boxShadow: "none", + display: "flex", + gap: "0px", +}; +const element: ElementDetails = { + label: "button", + tag: "button", + role: "button", + accessibleName: "Save", + text: "Save", + selector: "form > button.primary", + component: { name: "SaveButton", ownerPath: ["App", "Form"] }, + source: { file: "src/SaveButton.tsx", line: 12, column: 5 }, + classes: "primary", + styles, + cssRect: rect, + rect, +}; + +describe("markdown", () => { + it("converts rgb to hex", () => { + expect(toHexColor("rgb(17, 24, 39)")).toBe("#111827"); + expect(toHexColor("rgba(0, 0, 0, 0.5)")).toBe("#00000080"); + }); + + it("builds element markdown", () => { + expect(buildElementMarkdown(element)).toBe( + [ + "## SaveButton", + "", + "- Source: `src/SaveButton.tsx:12:5`", + "- Component: App › Form › SaveButton", + "- Selector: `form > button.primary`", + '- Text: "Save"', + '- Role: button "Save"', + "- Box: 100×40 at 10, 20 (CSS px)", + '- Styles: color #111827 · font 600 14px/20px "Inter" · padding 8px 12px · radius 6px', + "- Classes: `primary`", + "", + ].join("\n"), + ); + }); + + it("builds a note document with a fixed offset", () => { + const markdown = buildNoteMarkdown({ + pageTitle: "Home", + pageUrl: "https://example.com", + capturedAt: new Date("2026-11-19T10:30:00Z"), + utcOffsetMinutes: 330, + screenshotPath: "C:/shots/a.png", + cssViewport: { width: 1280, height: 720, devicePixelRatio: 1.5 }, + detail: "extension", + notes: [{ number: 1, comment: "Too tight", details: [element], isArea: false, fallback: null }], + }); + expect(markdown).toContain("# CapKit note: Home"); + expect(markdown).toContain("- Captured: 2026-11-19 16:00 (2026-11-19T10:30:00Z)"); + expect(markdown).toContain("- Viewport: 1280×720 CSS px at 1.5×"); + expect(markdown).toContain("## 1. SaveButton\n\nToo tight\n\n- Source:"); + }); +}); diff --git a/packages/devtools-protocol/src/markdown.ts b/packages/devtools-protocol/src/markdown.ts new file mode 100644 index 0000000..595ed60 --- /dev/null +++ b/packages/devtools-protocol/src/markdown.ts @@ -0,0 +1,209 @@ +import type { CssViewport, ElementDetails, PhysicalRect } from "./protocol"; + +export type NoteDetailSource = "extension" | "accessibility" | "none"; + +export type NoteMarkdownNote = { + number: number; + comment: string; + /** One element for a point note, up to 20 for an area note, null without extension data. */ + details: readonly ElementDetails[] | null; + isArea: boolean; + /** Accessibility data, used only when `details` is null. */ + fallback: { role: string; name: string; box: PhysicalRect | null } | null; +}; + +export type NoteMarkdownInput = { + pageTitle: string | null; + pageUrl: string | null; + capturedAt: Date; + /** Local offset east of UTC, in minutes (the negative of `Date.getTimezoneOffset()`). */ + utcOffsetMinutes: number; + screenshotPath: string; + cssViewport: CssViewport | null; + detail: NoteDetailSource; + notes: readonly NoteMarkdownNote[]; +}; + +const DETAIL_LABELS: Record = { + extension: "CapKit Inspector", + accessibility: "Windows accessibility", + none: "none", +}; + +const UNAVAILABLE_REASONS: Record, string> = { + "no-react": "no React found", + "production-build": "production build", + "no-source-map": "no source map", + "fetch-failed": "source map could not be loaded", +}; + +const pad = (value: number): string => String(value).padStart(2, "0"); + +function formatLocal(date: Date, offsetMinutes: number): string { + const shifted = new Date(date.getTime() + offsetMinutes * 60_000); + return `${String(shifted.getUTCFullYear())}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())} ${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}`; +} + +function formatUtc(date: Date): string { + return date.toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +function hex(channel: number): string { + return Math.round(Math.min(255, Math.max(0, channel))).toString(16).padStart(2, "0"); +} + +/** Converts `rgb()`/`rgba()` to `#rrggbb` (or `#rrggbbaa` below full opacity). Other values pass through. */ +export function toHexColor(value: string): string { + const match = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(value.trim()); + if (match === null) return value.trim(); + const [, red = "0", green = "0", blue = "0", alphaRaw] = match; + let alpha = 1; + if (alphaRaw !== undefined) { + alpha = alphaRaw.endsWith("%") ? Number.parseFloat(alphaRaw) / 100 : Number.parseFloat(alphaRaw); + } + const base = `#${hex(Number(red))}${hex(Number(green))}${hex(Number(blue))}`; + return alpha < 1 ? `${base}${hex(alpha * 255)}` : base; +} + +function isTransparent(value: string): boolean { + const color = toHexColor(value); + return color === "" || color === "transparent" || /^#[0-9a-f]{6}00$/.test(color); +} + +function firstFamily(value: string): string { + const first = value.split(",")[0]?.trim() ?? ""; + return first.replace(/^["']|["']$/g, ""); +} + +function fontSummary(styles: ElementDetails["styles"]): string { + if (styles.fontSize === "") return ""; + const lineHeight = styles.lineHeight === "" || styles.lineHeight === "normal" ? "" : `/${styles.lineHeight}`; + const family = firstFamily(styles.fontFamily); + const weight = styles.fontWeight === "" ? "" : `${styles.fontWeight} `; + return `${weight}${styles.fontSize}${lineHeight}${family === "" ? "" : ` "${family}"`}`; +} + +function isZeroBox(value: string): boolean { + return value.split(/\s+/).every((part) => part === "0px" || part === "0"); +} + +function stylesLine(details: ElementDetails): string { + const { styles } = details; + const parts: string[] = []; + if (styles.color !== "") parts.push(`color ${toHexColor(styles.color)}`); + if (!isTransparent(styles.backgroundColor)) parts.push(`background ${toHexColor(styles.backgroundColor)}`); + const font = fontSummary(styles); + if (font !== "") parts.push(`font ${font}`); + if (styles.padding !== "" && !isZeroBox(styles.padding)) parts.push(`padding ${styles.padding}`); + if (styles.borderRadius !== "" && !isZeroBox(styles.borderRadius)) parts.push(`radius ${styles.borderRadius}`); + return parts.join(" · "); +} + +function componentPath(details: ElementDetails): string { + if (details.component === null) return ""; + const path = [...details.component.ownerPath]; + if (path[path.length - 1] !== details.component.name) path.push(details.component.name); + return path.join(" › "); +} + +function sourceText(details: ElementDetails): string { + if (details.source !== null) { + return `\`${details.source.file}:${String(details.source.line)}:${String(details.source.column)}\``; + } + return details.sourceUnavailableReason === undefined + ? "" + : `unavailable (${UNAVAILABLE_REASONS[details.sourceUnavailableReason]})`; +} + +function roleText(role: string | null, name: string): string { + const parts = [role ?? "", name === "" ? "" : `"${name}"`].filter((part) => part !== ""); + return parts.join(" "); +} + +function bullets(entries: readonly (readonly [string, string])[]): string[] { + return entries.filter(([, value]) => value !== "").map(([label, value]) => `- ${label}: ${value}`); +} + +function elementName(details: ElementDetails): string { + return details.component?.name ?? (details.label === "" ? "Area" : details.label); +} + +function elementBullets(details: ElementDetails): string[] { + const { cssRect } = details; + const box = `${String(Math.round(cssRect.width))}×${String(Math.round(cssRect.height))} at ${String(Math.round(cssRect.x))}, ${String(Math.round(cssRect.y))} (CSS px)`; + return bullets([ + ["Source", sourceText(details)], + ["Component", componentPath(details)], + ["Selector", details.selector === "" ? "" : `\`${details.selector}\``], + ["Text", details.text === "" ? "" : `"${details.text}"`], + ["Role", roleText(details.role, details.accessibleName)], + ["Box", box], + ["Styles", stylesLine(details)], + ["Classes", details.classes === "" ? "" : `\`${details.classes}\``], + ]); +} + +/** Markdown for one inspected element, as copied by the extension's C shortcut. */ +export function buildElementMarkdown(details: ElementDetails, index?: number): string { + const heading = `## ${index === undefined ? "" : `${String(index)}. `}${elementName(details)}`; + return [heading, "", ...elementBullets(details)].join("\n") + "\n"; +} + +function areaListLine(details: ElementDetails): string { + const parts = [`\`${elementName(details)}\``]; + if (details.source !== null) parts.push(`\`${details.source.file}:${String(details.source.line)}\``); + const role = roleText(details.role, details.accessibleName); + if (role !== "") parts.push(role); + return `- ${parts.join(" · ")}`; +} + +function noteSection(note: NoteMarkdownNote): string[] { + const comment = note.comment.trim() === "" ? "_No comment_" : note.comment.trim(); + const first = note.details?.[0]; + const title = note.isArea || first === undefined ? (note.fallback?.name ?? "Area") : elementName(first); + const lines = [`## ${String(note.number)}. ${title === "" ? "Area" : title}`, "", comment, ""]; + if (note.details !== null && first !== undefined) { + if (note.isArea) { + lines.push("### Elements in this area", ...note.details.slice(0, 20).map(areaListLine)); + } else { + lines.push(...elementBullets(first)); + } + } else if (note.fallback !== null) { + const { role, name, box } = note.fallback; + lines.push( + ...bullets([ + ["Role", roleText(role, name)], + [ + "Box", + box === null + ? "" + : `${String(Math.round(box.width))}×${String(Math.round(box.height))} at ${String(Math.round(box.x))}, ${String(Math.round(box.y))} (screen px)`, + ], + ]), + ); + } + while (lines[lines.length - 1] === "") lines.pop(); + return lines; +} + +/** The Markdown handed to Claude: page, screenshot path, and one section per note pin. */ +export function buildNoteMarkdown(input: NoteMarkdownInput): string { + const title = input.pageTitle === null || input.pageTitle === "" ? "Screen capture" : input.pageTitle; + const viewport = + input.cssViewport === null + ? "" + : `${String(Math.round(input.cssViewport.width))}×${String(Math.round(input.cssViewport.height))} CSS px at ${String(input.cssViewport.devicePixelRatio)}×`; + const header = [ + `# CapKit note: ${title}`, + "", + ...bullets([ + ["URL", input.pageUrl ?? ""], + ["Captured", `${formatLocal(input.capturedAt, input.utcOffsetMinutes)} (${formatUtc(input.capturedAt)})`], + ["Screenshot", input.screenshotPath], + ["Viewport", viewport], + ["Element details", DETAIL_LABELS[input.detail]], + ]), + ]; + const sections = input.notes.map((note) => noteSection(note).join("\n")); + return [header.join("\n"), ...sections].join("\n\n") + "\n"; +} diff --git a/packages/devtools-protocol/src/protocol.test.ts b/packages/devtools-protocol/src/protocol.test.ts new file mode 100644 index 0000000..322112d --- /dev/null +++ b/packages/devtools-protocol/src/protocol.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { MAX_MESSAGE_BYTES, parseAppMessage, parseExtensionMessage } from "./protocol"; + +const rect = { x: 0, y: 0, width: 10, height: 10 }; + +describe("protocol", () => { + it("accepts a valid pair message", () => { + const raw = JSON.stringify({ v: 1, type: "pair", code: "123456", browser: { name: "Chrome", version: "130" }, extensionVersion: "0.1.0" }); + expect(parseExtensionMessage(raw)?.type).toBe("pair"); + }); + + it("rejects unknown fields, bad codes and wrong versions", () => { + const base = { v: 1, type: "pair", code: "123456", browser: { name: "Chrome", version: "1" }, extensionVersion: "1" }; + expect(parseExtensionMessage(JSON.stringify({ ...base, extra: 1 }))).toBeNull(); + expect(parseExtensionMessage(JSON.stringify({ ...base, code: "12345" }))).toBeNull(); + expect(parseExtensionMessage(JSON.stringify({ ...base, v: 2 }))).toBeNull(); + }); + + it("rejects non-JSON and oversize frames", () => { + expect(parseAppMessage("nope")).toBeNull(); + expect(parseAppMessage(" ".repeat(MAX_MESSAGE_BYTES + 1))).toBeNull(); + }); + + it("inspect needs exactly one of point or area", () => { + const base = { v: 1, type: "inspect", id: "a", windowTitle: "t", viewport: rect }; + expect(parseAppMessage(JSON.stringify({ ...base, point: { x: 1, y: 2 } }))?.type).toBe("inspect"); + expect(parseAppMessage(JSON.stringify({ ...base }))).toBeNull(); + expect(parseAppMessage(JSON.stringify({ ...base, point: { x: 1, y: 2 }, area: rect }))).toBeNull(); + }); +}); diff --git a/packages/devtools-protocol/src/protocol.ts b/packages/devtools-protocol/src/protocol.ts new file mode 100644 index 0000000..fe54e49 --- /dev/null +++ b/packages/devtools-protocol/src/protocol.ts @@ -0,0 +1,237 @@ +import { z } from "zod"; + +export const PROTOCOL_VERSION = 1; +export const LINK_PORTS = [47811, 47812, 47813] as const; +export const MAX_MESSAGE_BYTES = 256 * 1024; + +const envelope = { v: z.literal(PROTOCOL_VERSION) }; + +/** Physical screen pixels. */ +export const physicalRectSchema = z.strictObject({ + x: z.number(), + y: z.number(), + width: z.number(), + height: z.number(), +}); +export type PhysicalRect = z.infer; + +/** Physical pixels relative to the page viewport's top-left. */ +export const viewportRectSchema = physicalRectSchema; +export type ViewportRect = PhysicalRect; + +export const viewportPointSchema = z.strictObject({ x: z.number(), y: z.number() }); +export type ViewportPoint = z.infer; + +export const browserInfoSchema = z.strictObject({ + name: z.string().min(1).max(60), + version: z.string().max(40), +}); +export type BrowserInfo = z.infer; + +export const sensitiveKindSchema = z.enum(["token", "card", "email", "phone", "secret", "password"]); + +const tabSchema = z.strictObject({ url: z.string().max(4096), title: z.string().max(500) }); +export type TabInfo = z.infer; + +export const resultStatusSchema = z.enum(["ok", "no-tab", "no-access", "mismatch", "error"]); +export type ResultStatus = z.infer; + +export const hitElementSchema = z.strictObject({ + key: z.string().max(120), + label: z.string().max(80), + rect: viewportRectSchema, +}); +export type HitElement = z.infer; + +export const sourceUnavailableReasonSchema = z.enum([ + "no-react", + "production-build", + "no-source-map", + "fetch-failed", +]); + +export const elementDetailsSchema = z.strictObject({ + label: z.string().max(80), + tag: z.string().max(40), + role: z.string().max(60).nullable(), + accessibleName: z.string().max(120), + text: z.string().max(200), + selector: z.string().max(300), + component: z + .strictObject({ name: z.string().max(80), ownerPath: z.array(z.string().max(80)).max(6) }) + .nullable(), + source: z + .strictObject({ file: z.string().max(400), line: z.number().int(), column: z.number().int() }) + .nullable(), + sourceUnavailableReason: sourceUnavailableReasonSchema.optional(), + classes: z.string().max(400), + styles: z.strictObject({ + color: z.string().max(120), + backgroundColor: z.string().max(120), + fontFamily: z.string().max(120), + fontSize: z.string().max(120), + fontWeight: z.string().max(120), + lineHeight: z.string().max(120), + padding: z.string().max(120), + margin: z.string().max(120), + borderRadius: z.string().max(120), + boxShadow: z.string().max(120), + display: z.string().max(120), + gap: z.string().max(120), + }), + cssRect: physicalRectSchema, + rect: viewportRectSchema, +}); +export type ElementDetails = z.infer; + +export const cssViewportSchema = z.strictObject({ + width: z.number(), + height: z.number(), + devicePixelRatio: z.number(), +}); +export type CssViewport = z.infer; + +const requestBase = { + ...envelope, + id: z.string().min(1).max(80), + windowTitle: z.string().max(500), + viewport: physicalRectSchema, +}; + +// Extension → CapKit. +export const pairMessageSchema = z.strictObject({ + ...envelope, + type: z.literal("pair"), + code: z.string().regex(/^\d{6}$/), + browser: browserInfoSchema, + extensionVersion: z.string().max(40), +}); +export const helloMessageSchema = z.strictObject({ + ...envelope, + type: z.literal("hello"), + token: z.string().min(43).max(64), + browser: browserInfoSchema, + extensionVersion: z.string().max(40), +}); +export const pingMessageSchema = z.strictObject({ ...envelope, type: z.literal("ping") }); +export const hitTestResultSchema = z.strictObject({ + ...envelope, + type: z.literal("hitTestResult"), + id: z.string().min(1).max(80), + status: resultStatusSchema, + tab: tabSchema.optional(), + elements: z.array(hitElementSchema).max(12), +}); +export const inspectResultSchema = z.strictObject({ + ...envelope, + type: z.literal("inspectResult"), + id: z.string().min(1).max(80), + status: resultStatusSchema, + tab: tabSchema.optional(), + cssViewport: cssViewportSchema.optional(), + elements: z.array(elementDetailsSchema).max(20), +}); +export const sensitiveMatchSchema = z.strictObject({ + kind: sensitiveKindSchema, + preview: z.string().max(80), + rects: z.array(viewportRectSchema).max(40), +}); +export type SensitiveMatch = z.infer; +export const findSensitiveResultSchema = z.strictObject({ + ...envelope, + type: z.literal("findSensitiveResult"), + id: z.string().min(1).max(80), + status: resultStatusSchema, + matches: z.array(sensitiveMatchSchema).max(200), +}); + +export const extensionMessageSchema = z.discriminatedUnion("type", [ + pairMessageSchema, + helloMessageSchema, + pingMessageSchema, + hitTestResultSchema, + inspectResultSchema, + findSensitiveResultSchema, +]); +export type ExtensionMessage = z.infer; + +// CapKit → extension. +export const pairRejectReasonSchema = z.enum([ + "wrong-code", + "expired", + "too-many-attempts", + "not-pairing", +]); +export type PairRejectReason = z.infer; + +export const pairedMessageSchema = z.strictObject({ + ...envelope, + type: z.literal("paired"), + token: z.string().min(43).max(64), +}); +export const pairRejectedMessageSchema = z.strictObject({ + ...envelope, + type: z.literal("pairRejected"), + reason: pairRejectReasonSchema, +}); +export const readyMessageSchema = z.strictObject({ ...envelope, type: z.literal("ready") }); +export const helloRejectedMessageSchema = z.strictObject({ + ...envelope, + type: z.literal("helloRejected"), + reason: z.literal("unknown-token"), +}); +export const pongMessageSchema = z.strictObject({ ...envelope, type: z.literal("pong") }); +export const hitTestMessageSchema = z.strictObject({ + ...requestBase, + type: z.literal("hitTest"), + point: viewportPointSchema, +}); +export const inspectMessageSchema = z + .strictObject({ + ...requestBase, + type: z.literal("inspect"), + point: viewportPointSchema.optional(), + area: viewportRectSchema.optional(), + }) + .refine((message) => (message.point === undefined) !== (message.area === undefined), { + message: "inspect needs exactly one of point or area", + }); +export const findSensitiveMessageSchema = z.strictObject({ + ...requestBase, + type: z.literal("findSensitive"), + area: viewportRectSchema, +}); + +export const appMessageSchema = z.union([ + pairedMessageSchema, + pairRejectedMessageSchema, + readyMessageSchema, + helloRejectedMessageSchema, + pongMessageSchema, + hitTestMessageSchema, + inspectMessageSchema, + findSensitiveMessageSchema, +]); +export type AppMessage = z.infer; + +/** Parses one text frame from CapKit. Returns null for oversize, non-JSON or invalid frames. */ +export function parseAppMessage(raw: string): AppMessage | null { + if (raw.length > MAX_MESSAGE_BYTES) return null; + try { + const parsed = appMessageSchema.safeParse(JSON.parse(raw)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +/** Parses one text frame from the extension (used by tests and fake clients). */ +export function parseExtensionMessage(raw: string): ExtensionMessage | null { + if (raw.length > MAX_MESSAGE_BYTES) return null; + try { + const parsed = extensionMessageSchema.safeParse(JSON.parse(raw)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} diff --git a/packages/devtools-protocol/src/sensitive.test.ts b/packages/devtools-protocol/src/sensitive.test.ts new file mode 100644 index 0000000..26e676b --- /dev/null +++ b/packages/devtools-protocol/src/sensitive.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import { findSensitiveSpans, maskPreview, maskSensitiveText, passesLuhn } from "./sensitive"; + +describe("sensitive text", () => { + it("finds an email and masks it", () => { + const spans = findSensitiveSpans("write to jane.doe@example.com now"); + expect(spans.map((s) => s.kind)).toEqual(["email"]); + }); + + it("validates card numbers with Luhn", () => { + expect(passesLuhn("4242424242424242")).toBe(true); + expect(passesLuhn("4242424242424241")).toBe(false); + }); + + it("maskSensitiveText replaces secrets and counts them", () => { + const result = maskSensitiveText("mail jane.doe@example.com\nclean line"); + expect(result.masked).toBe(1); + expect(result.text).not.toContain("jane.doe@example.com"); + expect(result.text.split("\n")[1]).toBe("clean line"); + }); + + it("leaves clean text untouched", () => { + expect(maskSensitiveText("hello world")).toEqual({ text: "hello world", masked: 0 }); + expect(maskPreview("abc")).toBeTypeOf("string"); + }); +}); diff --git a/packages/devtools-protocol/src/sensitive.ts b/packages/devtools-protocol/src/sensitive.ts new file mode 100644 index 0000000..bb4e93e --- /dev/null +++ b/packages/devtools-protocol/src/sensitive.ts @@ -0,0 +1,130 @@ +export type SensitiveKind = "token" | "card" | "email" | "phone" | "secret"; + +/** Kinds the extension can report: the text kinds plus a filled password field. */ +export type WebSensitiveKind = SensitiveKind | "password"; + +export type SensitiveSpan = { + kind: SensitiveKind; + start: number; + end: number; +}; + +export const SENSITIVE_KIND_LABELS: Readonly> = { + password: "Password", + token: "API key or token", + card: "Card number", + email: "Email address", + phone: "Phone number", + secret: "Possible secret", +}; + +const TOKEN_PATTERN = + /\b(?:sk-(?:proj-|ant-)?[A-Za-z0-9_-]{16,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[abprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})/g; +const CARD_PATTERN = /\b\d(?:[ -]?\d){12,18}\b/g; +const EMAIL_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g; +const PHONE_PATTERN = /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?)?\d{2,5}(?:[\s.-]?\d{2,5}){1,4}/g; +const SECRET_CANDIDATE_PATTERN = /[A-Za-z0-9+/=_-]{24,}/g; + +/** Below this, long identifiers such as `getElementByIdOrThrow` stop qualifying. */ +const SECRET_MIN_ENTROPY_BITS = 3.5; + +/** Card-number checksum; it removes most random 13–19 digit runs. */ +export function passesLuhn(digits: string): boolean { + if (!/^\d{13,19}$/.test(digits)) return false; + let sum = 0; + for (let index = 0; index < digits.length; index += 1) { + let digit = Number(digits[digits.length - 1 - index]); + if (index % 2 === 1) { + digit *= 2; + if (digit > 9) digit -= 9; + } + sum += digit; + } + return sum % 10 === 0; +} + +/** Shannon entropy in bits per character. */ +export function shannonEntropy(value: string): number { + if (value.length === 0) return 0; + const counts = new Map(); + for (const character of value) counts.set(character, (counts.get(character) ?? 0) + 1); + let entropy = 0; + for (const count of counts.values()) { + const probability = count / value.length; + entropy -= probability * Math.log2(probability); + } + return entropy; +} + +function digitCount(value: string): number { + return value.replace(/\D/g, "").length; +} + +function looksLikeSecret(value: string): boolean { + return /[A-Za-z]/.test(value) + && /\d/.test(value) + && shannonEntropy(value) >= SECRET_MIN_ENTROPY_BITS; +} + +type Matcher = { + kind: SensitiveKind; + pattern: RegExp; + accepts: (match: string) => boolean; +}; + +// Ordered by confidence: an earlier matcher claims overlapping text first. +const MATCHERS: readonly Matcher[] = [ + { kind: "token", pattern: TOKEN_PATTERN, accepts: () => true }, + { kind: "card", pattern: CARD_PATTERN, accepts: (match) => passesLuhn(match.replace(/\D/g, "")) }, + { kind: "email", pattern: EMAIL_PATTERN, accepts: () => true }, + { + kind: "phone", + pattern: PHONE_PATTERN, + accepts: (match): boolean => { + const digits = digitCount(match); + return digits >= 10 && digits <= 15; + }, + }, + { kind: "secret", pattern: SECRET_CANDIDATE_PATTERN, accepts: looksLikeSecret }, +]; + +/** Finds sensitive spans in one line of text. Spans never overlap. */ +export function findSensitiveSpans(text: string): SensitiveSpan[] { + const spans: SensitiveSpan[] = []; + for (const matcher of MATCHERS) { + for (const match of text.matchAll(matcher.pattern)) { + const value = match[0].trim(); + if (value.length === 0 || !matcher.accepts(value)) continue; + const start = match.index + match[0].indexOf(value); + const end = start + value.length; + if (spans.some((span) => start < span.end && end > span.start)) continue; + spans.push({ kind: matcher.kind, start, end }); + } + } + return spans.sort((left, right) => left.start - right.start); +} + +/** Masks all but the first and last two characters. */ +export function maskPreview(value: string): string { + if (value.length <= 6) return "•".repeat(value.length); + return `${value.slice(0, 2)}${"•".repeat(Math.min(8, value.length - 4))}${value.slice(-2)}`; +} + +/** Replaces every sensitive span with a bullet mask, so exported text never carries a secret. */ +export function maskSensitiveText(text: string): { text: string; masked: number } { + const spans = text + .split("\n") + .map((line) => ({ line, spans: findSensitiveSpans(line) })); + let masked = 0; + const lines = spans.map(({ line, spans: lineSpans }) => { + let result = ""; + let cursor = 0; + for (const span of lineSpans) { + result += line.slice(cursor, span.start) + maskPreview(line.slice(span.start, span.end)); + cursor = span.end; + masked += 1; + } + return result + line.slice(cursor); + }); + return { text: lines.join("\n"), masked }; +} diff --git a/packages/devtools-protocol/tsconfig.json b/packages/devtools-protocol/tsconfig.json new file mode 100644 index 0000000..df3d9b4 --- /dev/null +++ b/packages/devtools-protocol/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023"], + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": ["vitest/globals"] + }, + "include": ["src", "vitest.config.ts"] +} diff --git a/packages/devtools-protocol/vitest.config.ts b/packages/devtools-protocol/vitest.config.ts new file mode 100644 index 0000000..e1b88b8 --- /dev/null +++ b/packages/devtools-protocol/vitest.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { environment: "node", clearMocks: true }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5cfba48..a879d1a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,82 @@ importers: .: {} + apps/browser-extension: + dependencies: + '@fontsource-variable/jetbrains-mono': + specifier: 5.2.8 + version: 5.2.8 + '@fontsource-variable/plus-jakarta-sans': + specifier: 5.2.8 + version: 5.2.8 + '@jridgewell/trace-mapping': + specifier: ^0.3.31 + version: 0.3.31 + '@snaphub/devtools-protocol': + specifier: workspace:* + version: link:../../packages/devtools-protocol + react: + specifier: ^19.2.7 + version: 19.2.7 + react-dom: + specifier: ^19.2.7 + version: 19.2.7(react@19.2.7) + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@eslint/js': + specifier: ^9.39.5 + version: 9.39.5 + '@tailwindcss/vite': + specifier: ^4.3.3 + version: 4.3.3(vite@8.1.5(@types/node@26.1.1)(jiti@2.7.0)) + '@testing-library/jest-dom': + specifier: ^6.9.1 + version: 6.9.1 + '@testing-library/react': + specifier: ^16.3.2 + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@testing-library/user-event': + specifier: ^14.6.1 + version: 14.6.12(@testing-library/dom@10.4.1) + '@types/chrome': + specifier: ^0.1.40 + version: 0.1.43 + '@types/node': + specifier: ^26.1.1 + version: 26.1.1 + '@types/react': + specifier: ^19.2.14 + version: 19.2.17 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.17) + '@vitejs/plugin-react': + specifier: ^6.0.3 + version: 6.0.3(vite@8.1.5(@types/node@26.1.1)(jiti@2.7.0)) + eslint: + specifier: ^9.39.5 + version: 9.39.5(jiti@2.7.0) + jsdom: + specifier: ^29.1.1 + version: 29.1.1 + tailwindcss: + specifier: ^4.3.3 + version: 4.3.3 + typescript: + specifier: ^6.0.3 + version: 6.0.3 + typescript-eslint: + specifier: ^8.64.0 + version: 8.64.0(eslint@9.39.5(jiti@2.7.0))(typescript@6.0.3) + vite: + specifier: ^8.1.5 + version: 8.1.5(@types/node@26.1.1)(jiti@2.7.0) + vitest: + specifier: ^4.1.10 + version: 4.1.10(@types/node@26.1.1)(jsdom@29.1.1)(vite@8.1.5(@types/node@26.1.1)(jiti@2.7.0)) + apps/desktop: dependencies: '@fontsource-variable/caveat': @@ -25,6 +101,9 @@ importers: '@hugeicons/react': specifier: 1.1.9 version: 1.1.9(react@19.2.7) + '@snaphub/devtools-protocol': + specifier: workspace:* + version: link:../../packages/devtools-protocol '@tauri-apps/api': specifier: ^2.11.1 version: 2.11.1 @@ -145,6 +224,31 @@ importers: specifier: ^5 version: 5.9.3 + packages/devtools-protocol: + dependencies: + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@eslint/js': + specifier: ^9.39.5 + version: 9.39.5 + '@types/node': + specifier: ^26.1.1 + version: 26.1.1 + eslint: + specifier: ^9.39.5 + version: 9.39.5(jiti@2.7.0) + typescript: + specifier: ^6.0.3 + version: 6.0.3 + typescript-eslint: + specifier: ^8.64.0 + version: 8.64.0(eslint@9.39.5(jiti@2.7.0))(typescript@6.0.3) + vitest: + specifier: ^4.1.10 + version: 4.1.10(@types/node@26.1.1)(jsdom@29.1.1)(vite@8.1.5(@types/node@26.1.1)(jiti@2.7.0)) + packages: '@adobe/css-tools@4.5.0': @@ -946,6 +1050,12 @@ packages: '@types/react-dom': optional: true + '@testing-library/user-event@14.6.12': + resolution: {integrity: sha512-8yQV8v+eToBhsUO4oYrZY7fzhpTEMZx4IDx0/iuER/x0Xuy0NdqQOhsaaUNlvXE03N7vQ+4RCXUieKC0NJty9w==} + engines: {node: '>=12', npm: '>=6'} + peerDependencies: + '@testing-library/dom': '>=7.21.4' + '@tybys/wasm-util@0.10.3': resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} @@ -955,6 +1065,9 @@ packages: '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + '@types/chrome@0.1.43': + resolution: {integrity: sha512-ukH/HhmR6ht+UTX3PLUWJxgJ/RQcK2Foj4lBzsF24SIWsXgqhGuXqjd8FFuwioPP7d/JUKLM4g8GZxw3F4HTcA==} + '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -964,6 +1077,15 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/filesystem@0.0.36': + resolution: {integrity: sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==} + + '@types/filewriter@0.0.33': + resolution: {integrity: sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==} + + '@types/har-format@1.2.16': + resolution: {integrity: sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -3489,6 +3611,10 @@ snapshots: '@types/react': 19.2.17 '@types/react-dom': 19.2.3(@types/react@19.2.17) + '@testing-library/user-event@14.6.12(@testing-library/dom@10.4.1)': + dependencies: + '@testing-library/dom': 10.4.1 + '@tybys/wasm-util@0.10.3': dependencies: tslib: 2.8.1 @@ -3501,12 +3627,25 @@ snapshots: '@types/deep-eql': 4.0.2 assertion-error: 2.0.1 + '@types/chrome@0.1.43': + dependencies: + '@types/filesystem': 0.0.36 + '@types/har-format': 1.2.16 + '@types/deep-eql@4.0.2': {} '@types/dom-webcodecs@0.1.18': {} '@types/estree@1.0.9': {} + '@types/filesystem@0.0.36': + dependencies: + '@types/filewriter': 0.0.33 + + '@types/filewriter@0.0.33': {} + + '@types/har-format@1.2.16': {} + '@types/json-schema@7.0.15': {} '@types/json5@0.0.29': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index c9cba01..4e12124 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,6 @@ packages: - apps/* + - packages/* allowBuilds: sharp: true unrs-resolver: true From 7fe040b5556c664a6fd878639e29e068856b3e4f Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 17:29:46 +0530 Subject: [PATCH 05/18] feat(capture): browser link and extension-based detection and redaction Add the localhost WebSocket browser link (off by default, paired by one-time code, origin-bound token), extension-first hover detection with fallback to UI Automation, exact redaction from page text rectangles with OCR fallback, and a Developer settings tab to switch it on and pair browsers. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 3 + apps/desktop/src-tauri/Cargo.lock | 261 ++- apps/desktop/src-tauri/Cargo.toml | 7 + apps/desktop/src-tauri/src/error.rs | 2 + apps/desktop/src-tauri/src/lib.rs | 87 + apps/desktop/src-tauri/src/platform/mod.rs | 12 +- .../src-tauri/src/platform/windows_ui.rs | 63 +- .../src-tauri/src/platform/xcap_backend.rs | 36 +- .../src-tauri/src/services/browser_link.rs | 1827 +++++++++++++++++ .../desktop/src-tauri/src/services/capture.rs | 217 +- apps/desktop/src-tauri/src/services/mod.rs | 1 + apps/desktop/src/App.tsx | 15 +- .../BrowserExtensionSettings.test.tsx | 109 + .../dashboard/BrowserExtensionSettings.tsx | 195 ++ .../dashboard/DashboardPanel.test.tsx | 10 +- .../src/components/dashboard/SettingsTabs.tsx | 2 +- .../src/components/dashboard/SettingsView.tsx | 11 +- .../desktop/src/lib/redactionPatterns.test.ts | 42 + apps/desktop/src/lib/redactionPatterns.ts | 36 + apps/desktop/src/lib/tauri.ts | 107 + 20 files changed, 2975 insertions(+), 68 deletions(-) create mode 100644 apps/desktop/src-tauri/src/services/browser_link.rs create mode 100644 apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx create mode 100644 apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30e16a2..928e68b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,9 @@ jobs: - name: Test run: pnpm test + - name: Build browser extension + run: pnpm ext:build + - name: Verify native application run: | cargo fmt --manifest-path apps/desktop/src-tauri/Cargo.toml --check diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index ff87fb4..f5be704 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -353,7 +353,7 @@ dependencies = [ "num-traits", "pastey", "rayon", - "thiserror 2.0.18", + "thiserror 2.0.21", "v_frame", "y4m", ] @@ -466,6 +466,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -615,8 +624,10 @@ dependencies = [ "dirs 6.0.0", "drag", "dunce", + "futures-util", "image", "imageproc", + "rusqlite", "serde", "serde_json", "tauri", @@ -626,7 +637,9 @@ dependencies = [ "tauri-plugin-global-shortcut", "tauri-plugin-single-instance", "tauri-plugin-updater", - "thiserror 2.0.18", + "thiserror 2.0.21", + "tokio", + "tokio-tungstenite", "uuid", "webview2-com", "windows 0.62.2", @@ -654,7 +667,7 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -807,6 +820,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "convert_case" version = "0.8.0" @@ -962,6 +981,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cssparser" version = "0.36.0" @@ -1035,6 +1063,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "dbus" version = "0.9.12" @@ -1093,8 +1127,19 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -1239,7 +1284,7 @@ dependencies = [ "objc2-app-kit", "objc2-foundation", "raw-window-handle", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows 0.52.0", "windows-core 0.58.0", ] @@ -1470,6 +1515,18 @@ dependencies = [ "zune-inflate", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" @@ -1990,7 +2047,7 @@ dependencies = [ "objc2-app-kit", "once_cell", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows-sys 0.59.0", "x11rb", "xkeysym", @@ -2081,6 +2138,18 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "heck" @@ -2161,6 +2230,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.10.1" @@ -2543,7 +2621,7 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link 0.2.1", ] @@ -2777,6 +2855,17 @@ dependencies = [ "system-deps 7.0.8", ] +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "libwayshot-xcap" version = "0.3.2" @@ -2790,7 +2879,7 @@ dependencies = [ "khronos-egl", "memmap2", "rustix 1.1.4", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "wayland-backend", "wayland-client", @@ -2967,7 +3056,7 @@ dependencies = [ "once_cell", "png 0.18.1", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -3558,7 +3647,7 @@ dependencies = [ "objc2-osa-kit", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -3726,7 +3815,7 @@ dependencies = [ "nix", "once_cell", "pipewire-sys", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4088,7 +4177,7 @@ dependencies = [ "rand 0.9.5", "rand_chacha", "simd_helpers", - "thiserror 2.0.18", + "thiserror 2.0.21", "v_frame", "wasm-bindgen", ] @@ -4183,7 +4272,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4318,6 +4407,30 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" +dependencies = [ + "bitflags 2.13.1", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -4738,6 +4851,17 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha2" version = "0.10.9" @@ -4746,7 +4870,7 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -4890,6 +5014,16 @@ dependencies = [ "system-deps 6.2.2", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4964,6 +5098,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -5126,7 +5271,7 @@ dependencies = [ "tauri-runtime", "tauri-runtime-wry", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tray-icon", "url", @@ -5177,7 +5322,7 @@ dependencies = [ "sha2", "syn 2.0.119", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "url", "uuid", @@ -5225,7 +5370,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5242,7 +5387,7 @@ dependencies = [ "tauri", "tauri-plugin", "tauri-plugin-fs", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", ] @@ -5265,7 +5410,7 @@ dependencies = [ "tauri", "tauri-plugin", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml 1.1.3+spec-1.1.0", "url", ] @@ -5282,7 +5427,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5294,7 +5439,7 @@ dependencies = [ "serde", "serde_json", "tauri", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "windows-sys 0.60.2", @@ -5326,7 +5471,7 @@ dependencies = [ "tauri", "tauri-plugin", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tokio", "url", @@ -5352,7 +5497,7 @@ dependencies = [ "serde", "serde_json", "tauri-utils", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "webkit2gtk", "webview2-com", @@ -5415,7 +5560,7 @@ dependencies = [ "serde_json", "serde_with", "swift-rs", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml 1.1.3+spec-1.1.0", "url", "urlpattern", @@ -5467,11 +5612,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -5487,13 +5632,13 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -5576,9 +5721,21 @@ dependencies = [ "mio", "pin-project-lite", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "tokio-rustls" version = "0.26.6" @@ -5589,6 +5746,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.18" @@ -5816,7 +5985,7 @@ dependencies = [ "once_cell", "png 0.18.1", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -5832,6 +6001,22 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.2", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "typeid" version = "1.0.3" @@ -5974,6 +6159,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version-compare" version = "0.2.1" @@ -6302,7 +6493,7 @@ version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" dependencies = [ - "thiserror 2.0.18", + "thiserror 2.0.21", "windows 0.61.3", "windows-core 0.61.2", ] @@ -6999,7 +7190,7 @@ dependencies = [ "sha2", "soup3", "tao-macros", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "webkit2gtk", "webkit2gtk-sys", @@ -7081,7 +7272,7 @@ dependencies = [ "rand 0.9.5", "scopeguard", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "url", "widestring", "windows 0.62.2", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 9d303d1..bb28a49 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -34,6 +34,13 @@ tauri-plugin-global-shortcut = "2.3.2" thiserror = "2.0.18" uuid = { version = "1.24.0", features = ["v4", "serde"] } xcap = { version = "0.9.6", features = ["image", "wgc"] } +# Browser link (localhost WebSocket for the CapKit Inspector extension). tokio is +# already in the tree through tauri and reqwest; only its features are widened. +tokio = { version = "1", features = ["net", "sync", "time", "macros"] } +tokio-tungstenite = "0.30" +futures-util = "0.3" +# Notes library. SQLite is compiled in, so there is no system dependency. +rusqlite = { version = "0.43", features = ["bundled"] } [target.'cfg(target_os = "windows")'.dependencies] drag = "=2.1.1" diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index 9d848a9..8d5dd1b 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -26,6 +26,8 @@ pub enum SnaphubError { Startup(String), #[error("SH-UPDATE-001: {0}")] Update(String), + #[error("SH-LINK-001: {0}")] + Link(String), } impl SnaphubError { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 028d0ee..520dc07 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -23,6 +23,10 @@ use error::SnaphubError; use platform::StartupBackend; use platform::plugin_startup::PluginStartup; use platform::xcap_backend::{XcapPlatformBackend, display_bounds}; +use services::browser_link::{ + BrowserLinkService, BrowserLinkStatusDto, InspectResultDto, InspectTarget, PairingCodeDto, + SensitiveMatchDto, +}; use services::capture::CaptureService; use services::recording::RecordingService; use services::scrolling::stitch_vertical; @@ -620,6 +624,73 @@ async fn detect_targets( .map_err(|error| SnaphubError::Capture(format!("Target detection worker failed: {error}")))? } +#[tauri::command] +fn browser_link_status(link: tauri::State<'_, BrowserLinkService>) -> BrowserLinkStatusDto { + link.status() +} + +#[tauri::command] +fn browser_link_set_enabled( + link: tauri::State<'_, BrowserLinkService>, + enabled: bool, +) -> Result { + link.set_enabled(enabled) +} + +#[tauri::command] +fn browser_link_start_pairing( + link: tauri::State<'_, BrowserLinkService>, +) -> Result { + link.start_pairing() +} + +#[tauri::command] +fn browser_link_cancel_pairing(link: tauri::State<'_, BrowserLinkService>) { + link.cancel_pairing(); +} + +#[tauri::command] +fn browser_link_forget( + link: tauri::State<'_, BrowserLinkService>, + origin: String, +) -> Result { + link.forget(&origin) +} + +/// Element details for a point or area over a browser page; `None` when the extension can't answer. +#[tauri::command] +async fn inspect_web_target( + app: AppHandle, + point: Option, + area: Option, +) -> Result, SnaphubError> { + let target = match (point, area) { + (Some(point), None) => InspectTarget::Point(point), + (None, Some(area)) => InspectTarget::Area(area), + _ => { + return Err(SnaphubError::Link("Pass either a point or an area".into())); + } + }; + tauri::async_runtime::spawn_blocking(move || { + app.state::().inspect_web_target(target) + }) + .await + .map_err(|error| SnaphubError::Link(format!("Inspect worker failed: {error}")))? +} + +/// Sensitive text in the browser page behind `area`; `None` when the extension can't answer. +#[tauri::command] +async fn find_sensitive_web( + app: AppHandle, + area: Rect, +) -> Result>, SnaphubError> { + tauri::async_runtime::spawn_blocking(move || { + app.state::().find_sensitive_web(area) + }) + .await + .map_err(|error| SnaphubError::Link(format!("Redaction worker failed: {error}")))? +} + #[tauri::command] fn get_save_directory(service: tauri::State<'_, CaptureService>) -> Result { service @@ -2670,6 +2741,13 @@ pub fn run() { copy_pinned_capture, save_pinned_capture, detect_targets, + browser_link_status, + browser_link_set_enabled, + browser_link_start_pairing, + browser_link_cancel_pairing, + browser_link_forget, + inspect_web_target, + find_sensitive_web, list_targets, get_save_directory, set_save_directory, @@ -2726,6 +2804,15 @@ pub fn run() { open_startup_settings ]) .setup(move |app| { + // Developer tools: the browser link reads its settings now and listens only when on. + let link = BrowserLinkService::new( + app.handle().clone(), + app.path().app_config_dir()?.join("browser-link.json"), + ); + app.state::() + .set_browser_source(std::sync::Arc::new(link.clone())); + app.manage(link); + if launched_in_background() && let Some(window) = app.get_webview_window("dashboard") { diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs index ce67d81..f390792 100644 --- a/apps/desktop/src-tauri/src/platform/mod.rs +++ b/apps/desktop/src-tauri/src/platform/mod.rs @@ -3,7 +3,7 @@ use image::RgbaImage; use crate::{ domain::{ AudioDeviceDto, DetectedTargetDto, DisplayDto, Point, RecognizedTextDto, - RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, + RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, Rect, StartupStateDto, }, error::SnaphubError, @@ -36,10 +36,20 @@ pub trait CaptureBackend: Send + Sync { fn capture_display_at_point(&self, point: Point) -> Result; } +/// A browser window's page area, in physical screen pixels. +#[derive(Debug, Clone, PartialEq)] +pub struct WebViewport { + pub window_id: u32, + pub window_title: String, + pub viewport: Rect, +} + pub trait TargetDetectionBackend: Send + Sync { fn begin_session(&self) -> Result<(), SnaphubError>; fn targets(&self) -> Result, SnaphubError>; fn ui_region_at(&self, point: Point) -> Result, SnaphubError>; + /// The page area of the browser window under `point`, or `None` when it isn't a browser page. + fn web_viewport_at(&self, point: Point) -> Result, SnaphubError>; } pub trait ClipboardBackend: Send + Sync { diff --git a/apps/desktop/src-tauri/src/platform/windows_ui.rs b/apps/desktop/src-tauri/src/platform/windows_ui.rs index c28f8f8..5a20272 100644 --- a/apps/desktop/src-tauri/src/platform/windows_ui.rs +++ b/apps/desktop/src-tauri/src/platform/windows_ui.rs @@ -19,7 +19,7 @@ use windows::Win32::{ }; use crate::{ - domain::{DetectedTargetDto, Rect}, + domain::{DetectedTargetDto, Point, Rect}, error::SnaphubError, }; @@ -368,10 +368,32 @@ fn wake_web_content(window_id: u32) -> usize { use windows::Win32::{ Foundation::{LPARAM, WPARAM}, UI::WindowsAndMessaging::{ - EnumChildWindows, OBJID_CLIENT, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_GETOBJECT, + OBJID_CLIENT, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_GETOBJECT, }, }; + let pages = web_content_windows(window_id); + for page in &pages { + let mut result = 0usize; + unsafe { + SendMessageTimeoutW( + *page, + WM_GETOBJECT, + WPARAM(0), + LPARAM(OBJID_CLIENT.0 as isize), + SMTO_ABORTIFHUNG, + 200, + Some(&mut result), + ); + } + } + pages.len() +} + +/// The child windows of `window_id` that host Chromium web pages. +fn web_content_windows(window_id: u32) -> Vec { + use windows::Win32::{Foundation::LPARAM, UI::WindowsAndMessaging::EnumChildWindows}; + unsafe extern "system" fn collect(child: HWND, found: LPARAM) -> windows::core::BOOL { // SAFETY: `found` is the address of the Vec passed below, alive for the whole enumeration. let found = unsafe { &mut *(found.0 as *mut Vec) }; @@ -392,21 +414,28 @@ fn wake_web_content(window_id: u32) -> usize { LPARAM(&mut pages as *mut Vec as isize), ); } - for page in &pages { - let mut result = 0usize; - unsafe { - SendMessageTimeoutW( - *page, - WM_GETOBJECT, - WPARAM(0), - LPARAM(OBJID_CLIENT.0 as isize), - SMTO_ABORTIFHUNG, - 200, - Some(&mut result), - ); - } - } - pages.len() + pages +} + +/// Where the web page is on screen (physical pixels): the largest Chromium page window inside +/// `window_id` that contains `point`. `None` when the window shows no web page there. +pub fn web_viewport_rect(window_id: u32, point: Point) -> Option { + web_content_windows(window_id) + .into_iter() + .filter_map(|page| { + let mut bounds = RECT::default(); + unsafe { GetWindowRect(page, &mut bounds) }.ok()?; + Some(rect_from(bounds)) + }) + .filter(|rect| { + rect.width > 0.0 + && rect.height > 0.0 + && point.x >= rect.x + && point.x < rect.x + rect.width + && point.y >= rect.y + && point.y < rect.y + rect.height + }) + .max_by(|left, right| (left.width * left.height).total_cmp(&(right.width * right.height))) } fn rects_nearly_equal(left: &Rect, right: &Rect) -> bool { diff --git a/apps/desktop/src-tauri/src/platform/xcap_backend.rs b/apps/desktop/src-tauri/src/platform/xcap_backend.rs index 44ce317..449f4f6 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -8,7 +8,7 @@ use crate::{ error::SnaphubError, platform::{ CaptureBackend, CapturedDisplay, ClipboardBackend, PermissionBackend, PinnedWindowBackend, - ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, + ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, WebViewport, }, }; @@ -224,10 +224,39 @@ impl TargetDetectionBackend for XcapPlatformBackend { Ok(None) } } + + fn web_viewport_at(&self, point: Point) -> Result, SnaphubError> { + #[cfg(target_os = "windows")] + { + let Some((window_id, window_title)) = underlying_window_with_title_at(point)? else { + return Ok(None); + }; + Ok( + super::windows_ui::web_viewport_rect(window_id, point).map(|viewport| { + WebViewport { + window_id, + window_title, + viewport, + } + }), + ) + } + + #[cfg(not(target_os = "windows"))] + { + let _ = point; + Ok(None) + } + } } #[cfg(target_os = "windows")] fn underlying_window_at(point: Point) -> Result, SnaphubError> { + Ok(underlying_window_with_title_at(point)?.map(|(id, _)| id)) +} + +#[cfg(target_os = "windows")] +fn underlying_window_with_title_at(point: Point) -> Result, SnaphubError> { // Xcap returns windows in z-order. The first visible match is the actual surface beneath // Snaphub; ranking by area could incorrectly select a smaller window hidden behind it. for window in Window::all().map_err(SnaphubError::capture)? { @@ -247,7 +276,10 @@ fn underlying_window_at(point: Point) -> Result, SnaphubError> { if !physical_rect_contains(bounds, point) { continue; } - return window.id().map(Some).map_err(SnaphubError::capture); + return window + .id() + .map(|id| Some((id, title))) + .map_err(SnaphubError::capture); } Ok(None) } diff --git a/apps/desktop/src-tauri/src/services/browser_link.rs b/apps/desktop/src-tauri/src/services/browser_link.rs new file mode 100644 index 0000000..ac013a3 --- /dev/null +++ b/apps/desktop/src-tauri/src/services/browser_link.rs @@ -0,0 +1,1827 @@ +//! Localhost WebSocket link to the CapKit Inspector browser extension. +//! +//! Invariants (see `docs/specs/browser-devtools.md`): the listener binds `127.0.0.1` only and +//! only while Developer tools is on; an upgrade needs an extension `Origin` and a local `Host`; +//! a socket can only pair or say hello until a token tied to its `Origin` authenticates it; +//! every frame is validated and at most 256 KiB; tokens never leave this module except to the +//! extension that earned them. + +use std::{ + collections::HashMap, + net::{SocketAddr, TcpListener as StdListener}, + path::{Path, PathBuf}, + sync::{Arc, Mutex, MutexGuard, mpsc}, + time::Duration, +}; + +use chrono::{DateTime, Utc}; +use futures_util::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use tauri::{AppHandle, Emitter}; +use tokio::{ + net::{TcpListener, TcpStream}, + sync::{mpsc as tokio_mpsc, oneshot}, + time::{Instant, timeout, timeout_at}, +}; +use tokio_tungstenite::{ + accept_hdr_async_with_config, + tungstenite::{ + Message, + handshake::server::{ErrorResponse, Request, Response}, + http::{HeaderMap, StatusCode}, + protocol::{CloseFrame, WebSocketConfig, frame::coding::CloseCode}, + }, +}; +use uuid::Uuid; + +use crate::{ + domain::{DetectedTargetDto, Point, Rect}, + error::SnaphubError, + platform::WebViewport, +}; + +pub const LINK_PORTS: [u16; 3] = [47811, 47812, 47813]; +pub const STATUS_EVENT: &str = "browser-link://status"; +pub const MAX_FRAME_BYTES: usize = 256 * 1024; +const PROTOCOL_VERSION: u8 = 1; +const PAIRING_SECONDS: i64 = 120; +const MAX_PAIRING_ATTEMPTS: u8 = 5; +const FIRST_MESSAGE_DEADLINE: Duration = Duration::from_secs(5); +const HIT_TEST_TIMEOUT: Duration = Duration::from_millis(250); +const INSPECT_TIMEOUT: Duration = Duration::from_millis(2000); +const FIND_SENSITIVE_TIMEOUT: Duration = Duration::from_millis(1500); +const MAX_TITLE_CHARS: usize = 500; + +// --------------------------------------------------------------------------------------------- +// Wire messages +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserDto { + pub name: String, + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TabInfo { + pub url: String, + pub title: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ResultStatus { + Ok, + NoTab, + NoAccess, + Mismatch, + Error, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HitElement { + pub key: String, + pub label: String, + pub rect: Rect, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CssViewport { + pub width: f64, + pub height: f64, + pub device_pixel_ratio: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ComponentInfo { + pub name: String, + #[serde(rename = "ownerPath")] + pub owner_path: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SourceLocation { + pub file: String, + pub line: i64, + pub column: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ElementStyles { + pub color: String, + pub background_color: String, + pub font_family: String, + pub font_size: String, + pub font_weight: String, + pub line_height: String, + pub padding: String, + pub margin: String, + pub border_radius: String, + pub box_shadow: String, + pub display: String, + pub gap: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ElementDetails { + pub label: String, + pub tag: String, + pub role: Option, + pub accessible_name: String, + pub text: String, + pub selector: String, + pub component: Option, + pub source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_unavailable_reason: Option, + pub classes: String, + pub styles: ElementStyles, + pub css_rect: Rect, + pub rect: Rect, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SensitiveKind { + Token, + Card, + Email, + Phone, + Secret, + Password, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SensitiveMatchDto { + pub kind: SensitiveKind, + pub preview: String, + pub rects: Vec, +} + +/// Extension → CapKit. Unknown fields are rejected. +#[allow( + dead_code, + reason = "extensionVersion and tab are validated by the schema but not used yet" +)] +#[derive(Debug, Deserialize)] +#[serde( + tag = "type", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum Incoming { + Pair { + v: u8, + code: String, + browser: BrowserDto, + extension_version: String, + }, + Hello { + v: u8, + token: String, + browser: BrowserDto, + extension_version: String, + }, + Ping { + v: u8, + }, + HitTestResult { + v: u8, + id: String, + status: ResultStatus, + tab: Option, + elements: Vec, + }, + InspectResult { + v: u8, + id: String, + status: ResultStatus, + tab: Option, + css_viewport: Option, + elements: Vec, + }, + FindSensitiveResult { + v: u8, + id: String, + status: ResultStatus, + matches: Vec, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum PairReject { + WrongCode, + Expired, + TooManyAttempts, + NotPairing, +} + +/// CapKit → extension. +#[derive(Debug, Serialize)] +#[serde( + tag = "type", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +enum Outgoing<'a> { + Paired { + v: u8, + token: &'a str, + }, + PairRejected { + v: u8, + reason: PairReject, + }, + Ready { + v: u8, + }, + HelloRejected { + v: u8, + reason: &'static str, + }, + Pong { + v: u8, + }, + HitTest { + v: u8, + id: &'a str, + window_title: String, + viewport: Rect, + point: Point, + }, + Inspect { + v: u8, + id: &'a str, + window_title: String, + viewport: Rect, + #[serde(skip_serializing_if = "Option::is_none")] + point: Option, + #[serde(skip_serializing_if = "Option::is_none")] + area: Option, + }, + FindSensitive { + v: u8, + id: &'a str, + window_title: String, + viewport: Rect, + area: Rect, + }, +} + +fn frame(message: &Outgoing<'_>) -> String { + // Serializing these plain structs cannot fail; an empty frame would be rejected by the peer. + serde_json::to_string(message).unwrap_or_default() +} + +/// Parses one text frame from the extension. `None` for oversize, malformed or wrong-version. +pub fn parse_incoming(raw: &str) -> Option { + if raw.len() > MAX_FRAME_BYTES { + return None; + } + let message: Incoming = serde_json::from_str(raw).ok()?; + let version = match &message { + Incoming::Pair { v, .. } + | Incoming::Hello { v, .. } + | Incoming::Ping { v } + | Incoming::HitTestResult { v, .. } + | Incoming::InspectResult { v, .. } + | Incoming::FindSensitiveResult { v, .. } => *v, + }; + (version == PROTOCOL_VERSION).then_some(message) +} + +// --------------------------------------------------------------------------------------------- +// Pure helpers: upgrade validation, pairing, constant-time compare, base64url +// --------------------------------------------------------------------------------------------- + +/// `chrome-extension://` followed by exactly 32 characters in `a..=p`. +fn is_extension_origin(origin: &str) -> bool { + origin + .strip_prefix("chrome-extension://") + .is_some_and(|id| id.len() == 32 && id.bytes().all(|byte| (b'a'..=b'p').contains(&byte))) +} + +/// Accepts an upgrade only from an extension `Origin` addressed to a local `Host`. +pub fn validate_upgrade(headers: &HeaderMap, port: u16) -> bool { + let origin = headers.get("origin").and_then(|value| value.to_str().ok()); + let host = headers.get("host").and_then(|value| value.to_str().ok()); + let (Some(origin), Some(host)) = (origin, host) else { + return false; + }; + is_extension_origin(origin) + && (host == format!("127.0.0.1:{port}") || host == format!("localhost:{port}")) +} + +/// Compares secrets without an early exit on the first differing byte. +pub fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + left.iter() + .zip(right) + .fold(0u8, |difference, (a, b)| difference | (a ^ b)) + == 0 +} + +fn base64url(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let block = (u32::from(chunk[0]) << 16) + | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) + | u32::from(*chunk.get(2).unwrap_or(&0)); + out.push(char::from(ALPHABET[(block >> 18) as usize & 63])); + out.push(char::from(ALPHABET[(block >> 12) as usize & 63])); + if chunk.len() > 1 { + out.push(char::from(ALPHABET[(block >> 6) as usize & 63])); + } + if chunk.len() > 2 { + out.push(char::from(ALPHABET[block as usize & 63])); + } + } + out +} + +/// 32 random bytes from two v4 UUIDs, base64url (43 characters). +fn new_token() -> String { + let mut bytes = Vec::with_capacity(32); + bytes.extend_from_slice(Uuid::new_v4().as_bytes()); + bytes.extend_from_slice(Uuid::new_v4().as_bytes()); + base64url(&bytes) +} + +fn new_code() -> String { + let bytes = Uuid::new_v4().into_bytes(); + let mut eight = [0u8; 8]; + eight.copy_from_slice(&bytes[..8]); + format!("{:06}", u64::from_be_bytes(eight) % 1_000_000) +} + +/// The pairing code state machine. Expiry is checked lazily on use; no timer runs. +#[derive(Debug, Default)] +pub struct PairingState { + code: Option, + expires_at: Option>, + attempts: u8, +} + +impl PairingState { + /// Replaces any previous code. Returns the expiry. + pub fn start(&mut self, code: String, now: DateTime) -> DateTime { + let expires_at = now + chrono::Duration::seconds(PAIRING_SECONDS); + self.code = Some(code); + self.expires_at = Some(expires_at); + self.attempts = 0; + expires_at + } + + pub fn cancel(&mut self) { + self.code = None; + self.expires_at = None; + self.attempts = 0; + } + + /// Checks a candidate in the spec's order. A correct code is consumed. + pub fn verify(&mut self, candidate: &str, now: DateTime) -> Result<(), PairReject> { + let Some(code) = self.code.as_deref() else { + return Err(PairReject::NotPairing); + }; + if self.expires_at.is_none_or(|expires_at| now >= expires_at) { + self.cancel(); + return Err(PairReject::Expired); + } + if self.attempts >= MAX_PAIRING_ATTEMPTS { + self.cancel(); + return Err(PairReject::TooManyAttempts); + } + if constant_time_eq(code.as_bytes(), candidate.as_bytes()) { + self.cancel(); + Ok(()) + } else { + self.attempts += 1; + Err(PairReject::WrongCode) + } + } +} + +// --------------------------------------------------------------------------------------------- +// Persistence +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PairedRecord { + origin: String, + token: String, + browser: BrowserDto, + paired_at: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct LinkConfig { + version: u8, + enabled: bool, + paired: Vec, +} + +impl Default for LinkConfig { + fn default() -> Self { + Self { + version: 1, + enabled: false, + paired: Vec::new(), + } + } +} + +fn load_config(path: &Path) -> LinkConfig { + let Ok(text) = std::fs::read_to_string(path) else { + return LinkConfig::default(); + }; + match serde_json::from_str::(&text) { + Ok(config) if config.version == 1 => config, + _ => { + eprintln!("SH-LINK-001: browser-link.json is unreadable; starting with it disabled"); + let _ = std::fs::rename(path, path.with_extension("json.bad")); + LinkConfig::default() + } + } +} + +/// Writes to a temporary file, then renames over the target. +fn save_config(path: &Path, config: &LinkConfig) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let temporary = path.with_extension("json.tmp"); + std::fs::write( + &temporary, + serde_json::to_vec_pretty(config).map_err(std::io::Error::other)?, + )?; + std::fs::rename(temporary, path) +} + +// --------------------------------------------------------------------------------------------- +// DTOs shown to the webview. They contain no secrets. +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PairedBrowserDto { + pub origin: String, + pub browser: BrowserDto, + pub paired_at: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BrowserLinkStatusDto { + pub enabled: bool, + pub state: &'static str, + pub port: Option, + pub error: Option, + pub connected: Vec, + pub paired: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PairingCodeDto { + pub code: String, + pub expires_at: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InspectResultDto { + pub tab: Option, + pub css_viewport: Option, + pub elements: Vec, +} + +pub enum InspectTarget { + Point(Point), + Area(Rect), +} + +/// What the capture path asks of a connected browser. Implemented by `BrowserLinkService`; +/// tests substitute a fake. +pub trait BrowserElementSource: Send + Sync { + fn is_connected(&self) -> bool; + fn element_at(&self, viewport: &WebViewport, point: Point) -> Option>; + fn inspect(&self, viewport: &WebViewport, target: InspectTarget) -> Option; + fn find_sensitive(&self, viewport: &WebViewport, area: Rect) -> Option>; +} + +// --------------------------------------------------------------------------------------------- +// Service +// --------------------------------------------------------------------------------------------- + +enum Outbound { + Text(String), + Close(u16, &'static str), +} + +struct Connection { + origin: String, + authed: bool, + browser: Option, + tx: tokio_mpsc::UnboundedSender, +} + +enum Reply { + HitTest { + status: ResultStatus, + elements: Vec, + }, + Inspect { + status: ResultStatus, + tab: Option, + css_viewport: Option, + elements: Vec, + }, + FindSensitive { + status: ResultStatus, + matches: Vec, + }, +} + +impl Reply { + fn is_ok(&self) -> bool { + let status = match self { + Self::HitTest { status, .. } + | Self::Inspect { status, .. } + | Self::FindSensitive { status, .. } => status, + }; + *status == ResultStatus::Ok + } +} + +struct Pending { + sender: mpsc::Sender, + /// Only these connections may answer; anything else is dropped. + from: Vec, + kind: PendingKind, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PendingKind { + HitTest, + Inspect, + FindSensitive, +} + +struct Listener { + port: u16, + handle: tauri::async_runtime::JoinHandle<()>, +} + +struct Shared { + config: LinkConfig, + config_path: PathBuf, + pairing: PairingState, + listener: Option, + bind_error: Option, + connections: HashMap, + next_connection: u64, + pending: HashMap, +} + +type StatusEmitter = dyn Fn(&BrowserLinkStatusDto) + Send + Sync; + +struct Inner { + state: Mutex, + ports: Vec, + emit: Arc, +} + +#[derive(Clone)] +pub struct BrowserLinkService { + inner: Arc, +} + +fn lock(state: &Mutex) -> MutexGuard<'_, Shared> { + state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn status_of(shared: &Shared) -> BrowserLinkStatusDto { + let state = if !shared.config.enabled { + "off" + } else if shared.bind_error.is_some() { + "error" + } else { + "listening" + }; + let mut connected: Vec = shared + .connections + .values() + .filter(|connection| connection.authed) + .filter_map(|connection| connection.browser.clone()) + .collect(); + connected.sort_by(|left, right| left.name.cmp(&right.name)); + BrowserLinkStatusDto { + enabled: shared.config.enabled, + state, + port: shared.listener.as_ref().map(|listener| listener.port), + error: shared.bind_error.clone(), + connected, + paired: shared + .config + .paired + .iter() + .map(|record| PairedBrowserDto { + origin: record.origin.clone(), + browser: record.browser.clone(), + paired_at: record.paired_at.clone(), + }) + .collect(), + } +} + +impl Inner { + fn emit_status(&self) { + let status = status_of(&lock(&self.state)); + (self.emit)(&status); + } +} + +fn truncate_title(title: &str) -> String { + title.chars().take(MAX_TITLE_CHARS).collect() +} + +fn forbidden() -> ErrorResponse { + let mut response = ErrorResponse::new(Some("Forbidden".into())); + *response.status_mut() = StatusCode::FORBIDDEN; + response +} + +impl BrowserLinkService { + /// Reads `browser-link.json` and starts listening when it says enabled. + pub fn new(app: AppHandle, config_path: PathBuf) -> Self { + let emit: Arc = Arc::new(move |status| { + let _ = app.emit_to("dashboard", STATUS_EVENT, status); + }); + Self::with_parts(config_path, LINK_PORTS.to_vec(), emit) + } + + fn with_parts(config_path: PathBuf, ports: Vec, emit: Arc) -> Self { + let config = load_config(&config_path); + let enabled = config.enabled; + let service = Self { + inner: Arc::new(Inner { + state: Mutex::new(Shared { + config, + config_path, + pairing: PairingState::default(), + listener: None, + bind_error: None, + connections: HashMap::new(), + next_connection: 1, + pending: HashMap::new(), + }), + ports, + emit, + }), + }; + if enabled { + service.start_listener(); + } + service + } + + pub fn status(&self) -> BrowserLinkStatusDto { + status_of(&lock(&self.inner.state)) + } + + pub fn set_enabled(&self, enabled: bool) -> Result { + { + let mut shared = lock(&self.inner.state); + shared.config.enabled = enabled; + save_config(&shared.config_path, &shared.config) + .map_err(|error| SnaphubError::Link(error.to_string()))?; + } + if enabled { + self.start_listener(); + } else { + self.stop_listener(); + } + let status = self.status(); + (self.inner.emit)(&status); + Ok(status) + } + + pub fn start_pairing(&self) -> Result { + let mut shared = lock(&self.inner.state); + if !shared.config.enabled { + return Err(SnaphubError::Link("Developer tools is off".into())); + } + let code = new_code(); + let expires_at = shared.pairing.start(code.clone(), Utc::now()); + Ok(PairingCodeDto { + code, + expires_at: expires_at.to_rfc3339(), + }) + } + + pub fn cancel_pairing(&self) { + lock(&self.inner.state).pairing.cancel(); + } + + /// Removes a pairing and closes that origin's sockets. + pub fn forget(&self, origin: &str) -> Result { + { + let mut shared = lock(&self.inner.state); + shared + .config + .paired + .retain(|record| record.origin != origin); + save_config(&shared.config_path, &shared.config) + .map_err(|error| SnaphubError::Link(error.to_string()))?; + for connection in shared.connections.values() { + if connection.origin == origin { + let _ = connection.tx.send(Outbound::Close(1008, "forgotten")); + } + } + } + let status = self.status(); + (self.inner.emit)(&status); + Ok(status) + } + + fn start_listener(&self) { + let mut shared = lock(&self.inner.state); + if shared.listener.is_some() { + return; + } + let bound = self.inner.ports.iter().find_map(|port| { + let listener = StdListener::bind(SocketAddr::from(([127, 0, 0, 1], *port))).ok()?; + listener.set_nonblocking(true).ok()?; + let bound_port = listener.local_addr().ok()?.port(); + Some((listener, bound_port)) + }); + let Some((listener, port)) = bound else { + let first = self.inner.ports.first().copied().unwrap_or(0); + let last = self.inner.ports.last().copied().unwrap_or(0); + shared.bind_error = Some(format!("Ports {first}\u{2013}{last} are in use")); + return; + }; + shared.bind_error = None; + let handle = tauri::async_runtime::spawn(accept_loop(self.inner.clone(), listener, port)); + shared.listener = Some(Listener { port, handle }); + } + + fn stop_listener(&self) { + let mut shared = lock(&self.inner.state); + shared.bind_error = None; + if let Some(listener) = shared.listener.take() { + listener.handle.abort(); + } + for connection in shared.connections.values() { + let _ = connection.tx.send(Outbound::Close(1001, "going away")); + } + // Dropping the senders wakes every waiting caller with no answer. + shared.pending.clear(); + shared.pairing.cancel(); + } + + /// Sends one request to every authenticated connection and returns the first `ok` reply, + /// or `None` when all replies are not ok or the timeout passes. + fn request( + &self, + kind: PendingKind, + wait: Duration, + build: impl Fn(&str) -> String, + ) -> Option { + let id = Uuid::new_v4().to_string(); + let (sender, receiver) = mpsc::channel(); + let frame = build(&id); + let sent = { + let mut shared = lock(&self.inner.state); + let targets: Vec = shared + .connections + .iter() + .filter(|(_, connection)| connection.authed) + .map(|(connection_id, _)| *connection_id) + .collect(); + if targets.is_empty() { + return None; + } + let mut from = Vec::new(); + for connection_id in targets { + if let Some(connection) = shared.connections.get(&connection_id) + && connection.tx.send(Outbound::Text(frame.clone())).is_ok() + { + from.push(connection_id); + } + } + let count = from.len(); + if count == 0 { + return None; + } + shared + .pending + .insert(id.clone(), Pending { sender, from, kind }); + count + }; + let deadline = std::time::Instant::now() + wait; + let mut answered = 0; + let mut result = None; + while answered < sent { + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + match receiver.recv_timeout(remaining) { + Ok(reply) => { + answered += 1; + if reply.is_ok() { + result = Some(reply); + break; + } + } + Err(_) => break, + } + } + lock(&self.inner.state).pending.remove(&id); + result + } +} + +fn to_screen(viewport: &Rect, rect: &Rect) -> Rect { + Rect { + x: viewport.x + rect.x, + y: viewport.y + rect.y, + width: rect.width, + height: rect.height, + } +} + +impl BrowserElementSource for BrowserLinkService { + fn is_connected(&self) -> bool { + lock(&self.inner.state) + .connections + .values() + .any(|connection| connection.authed) + } + + fn element_at(&self, viewport: &WebViewport, point: Point) -> Option> { + let local = Point { + x: point.x - viewport.viewport.x, + y: point.y - viewport.viewport.y, + }; + let reply = self.request(PendingKind::HitTest, HIT_TEST_TIMEOUT, |id| { + frame(&Outgoing::HitTest { + v: PROTOCOL_VERSION, + id, + window_title: truncate_title(&viewport.window_title), + viewport: viewport.viewport, + point: local, + }) + })?; + let Reply::HitTest { elements, .. } = reply else { + return None; + }; + if elements.is_empty() { + return None; + } + Some( + elements + .into_iter() + .map(|element| DetectedTargetDto { + id: format!("ext-{}", element.key), + title: element.label, + kind: "ui-region", + bounds: to_screen(&viewport.viewport, &element.rect), + }) + .collect(), + ) + } + + fn inspect(&self, viewport: &WebViewport, target: InspectTarget) -> Option { + let (point, area) = match target { + InspectTarget::Point(point) => ( + Some(Point { + x: point.x - viewport.viewport.x, + y: point.y - viewport.viewport.y, + }), + None, + ), + InspectTarget::Area(area) => ( + None, + Some(Rect { + x: area.x - viewport.viewport.x, + y: area.y - viewport.viewport.y, + ..area + }), + ), + }; + let reply = self.request(PendingKind::Inspect, INSPECT_TIMEOUT, |id| { + frame(&Outgoing::Inspect { + v: PROTOCOL_VERSION, + id, + window_title: truncate_title(&viewport.window_title), + viewport: viewport.viewport, + point, + area, + }) + })?; + let Reply::Inspect { + tab, + css_viewport, + mut elements, + .. + } = reply + else { + return None; + }; + for element in &mut elements { + element.rect = to_screen(&viewport.viewport, &element.rect); + } + Some(InspectResultDto { + tab, + css_viewport, + elements, + }) + } + + fn find_sensitive(&self, viewport: &WebViewport, area: Rect) -> Option> { + let local = Rect { + x: area.x - viewport.viewport.x, + y: area.y - viewport.viewport.y, + ..area + }; + let reply = self.request(PendingKind::FindSensitive, FIND_SENSITIVE_TIMEOUT, |id| { + frame(&Outgoing::FindSensitive { + v: PROTOCOL_VERSION, + id, + window_title: truncate_title(&viewport.window_title), + viewport: viewport.viewport, + area: local, + }) + })?; + let Reply::FindSensitive { mut matches, .. } = reply else { + return None; + }; + for found in &mut matches { + for rect in &mut found.rects { + *rect = to_screen(&viewport.viewport, rect); + } + } + Some(matches) + } +} + +// --------------------------------------------------------------------------------------------- +// Network tasks +// --------------------------------------------------------------------------------------------- + +async fn accept_loop(inner: Arc, std_listener: StdListener, port: u16) { + let Ok(listener) = TcpListener::from_std(std_listener) else { + return; + }; + loop { + match listener.accept().await { + Ok((stream, peer)) => { + if peer.ip().is_loopback() { + tauri::async_runtime::spawn(handle_connection(inner.clone(), stream, port)); + } + } + // A failed accept (for example out of handles) must not spin the CPU. + Err(_) => tokio::time::sleep(Duration::from_millis(250)).await, + } + } +} + +fn socket_config() -> WebSocketConfig { + WebSocketConfig::default() + .max_message_size(Some(MAX_FRAME_BYTES)) + .max_frame_size(Some(MAX_FRAME_BYTES)) +} + +async fn handle_connection(inner: Arc, stream: TcpStream, port: u16) { + let origin_slot: Arc>> = Arc::new(Mutex::new(None)); + let slot = origin_slot.clone(); + // The error type is fixed by tungstenite's handshake callback. + #[allow(clippy::result_large_err)] + let callback = + move |request: &Request, response: Response| -> Result { + if !validate_upgrade(request.headers(), port) { + return Err(forbidden()); + } + if let Some(origin) = request + .headers() + .get("origin") + .and_then(|value| value.to_str().ok()) + { + *slot + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(origin.to_owned()); + } + Ok(response) + }; + let handshake = accept_hdr_async_with_config(stream, callback, Some(socket_config())); + let Ok(Ok(socket)) = timeout(FIRST_MESSAGE_DEADLINE, handshake).await else { + return; + }; + let origin = origin_slot + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + .unwrap_or_default(); + + let (mut sink, mut source) = socket.split(); + let (tx, mut rx) = tokio_mpsc::unbounded_channel::(); + let (done_tx, mut done_rx) = oneshot::channel::<()>(); + tauri::async_runtime::spawn(async move { + while let Some(outbound) = rx.recv().await { + match outbound { + Outbound::Text(text) => { + if sink.send(Message::text(text)).await.is_err() { + break; + } + } + Outbound::Close(code, reason) => { + let _ = sink + .send(Message::Close(Some(CloseFrame { + code: CloseCode::from(code), + reason: reason.into(), + }))) + .await; + break; + } + } + } + let _ = sink.close().await; + let _ = done_tx.send(()); + }); + + let id = { + let mut shared = lock(&inner.state); + let id = shared.next_connection; + shared.next_connection += 1; + shared.connections.insert( + id, + Connection { + origin, + authed: false, + browser: None, + tx: tx.clone(), + }, + ); + id + }; + + let deadline = Instant::now() + FIRST_MESSAGE_DEADLINE; + loop { + let authed = lock(&inner.state) + .connections + .get(&id) + .is_some_and(|connection| connection.authed); + let next = async { + if authed { + Some(source.next().await) + } else { + timeout_at(deadline, source.next()).await.ok() + } + }; + let message = tokio::select! { + message = next => message, + _ = &mut done_rx => break, + }; + let Some(message) = message else { + let _ = tx.send(Outbound::Close(1008, "no authentication")); + break; + }; + match message { + Some(Ok(Message::Text(text))) => { + if text.len() > MAX_FRAME_BYTES { + let _ = tx.send(Outbound::Close(1009, "too large")); + } else if let Some((code, reason)) = handle_text(&inner, id, &tx, text.as_str()) { + let _ = tx.send(Outbound::Close(code, reason)); + } + } + Some(Ok(Message::Binary(_))) => { + let _ = tx.send(Outbound::Close(1003, "text only")); + } + Some(Ok(Message::Close(_))) | None => break, + Some(Ok(_)) => {} + Some(Err(tokio_tungstenite::tungstenite::Error::Capacity(_))) => { + let _ = tx.send(Outbound::Close(1009, "too large")); + } + Some(Err(_)) => break, + } + } + + { + let mut shared = lock(&inner.state); + shared.connections.remove(&id); + } + inner.emit_status(); +} + +/// Handles one validated-size text frame. Returns a close code when the socket must close. +fn handle_text( + inner: &Arc, + id: u64, + tx: &tokio_mpsc::UnboundedSender, + raw: &str, +) -> Option<(u16, &'static str)> { + let Some(message) = parse_incoming(raw) else { + return Some((1008, "invalid message")); + }; + let (authed, origin) = { + let shared = lock(&inner.state); + let connection = shared.connections.get(&id)?; + (connection.authed, connection.origin.clone()) + }; + let send = |outgoing: &Outgoing<'_>| { + let _ = tx.send(Outbound::Text(frame(outgoing))); + }; + + match message { + Incoming::Pair { code, browser, .. } if !authed => { + let result = lock(&inner.state).pairing.verify(&code, Utc::now()); + match result { + Ok(()) => { + let token = new_token(); + let saved = { + let mut shared = lock(&inner.state); + shared + .config + .paired + .retain(|record| record.origin != origin); + shared.config.paired.push(PairedRecord { + origin: origin.clone(), + token: token.clone(), + browser: browser.clone(), + paired_at: Utc::now().to_rfc3339(), + }); + let saved = save_config(&shared.config_path, &shared.config); + if let Some(connection) = shared.connections.get_mut(&id) { + connection.authed = saved.is_ok(); + connection.browser = Some(browser); + } + saved + }; + if saved.is_err() { + return Some((1011, "could not save pairing")); + } + send(&Outgoing::Paired { + v: PROTOCOL_VERSION, + token: &token, + }); + inner.emit_status(); + None + } + Err(reason) => { + send(&Outgoing::PairRejected { + v: PROTOCOL_VERSION, + reason, + }); + Some((1008, "pairing rejected")) + } + } + } + Incoming::Hello { token, browser, .. } if !authed => { + let known = { + let shared = lock(&inner.state); + shared.config.paired.iter().any(|record| { + record.origin == origin + && constant_time_eq(record.token.as_bytes(), token.as_bytes()) + }) + }; + if known { + { + let mut shared = lock(&inner.state); + if let Some(connection) = shared.connections.get_mut(&id) { + connection.authed = true; + connection.browser = Some(browser); + } + } + send(&Outgoing::Ready { + v: PROTOCOL_VERSION, + }); + inner.emit_status(); + None + } else { + send(&Outgoing::HelloRejected { + v: PROTOCOL_VERSION, + reason: "unknown-token", + }); + Some((1008, "unknown token")) + } + } + // Anything but pair or hello before authentication, and pair or hello after it. + Incoming::Pair { .. } | Incoming::Hello { .. } => Some((1008, "unexpected message")), + _ if !authed => Some((1008, "not authenticated")), + Incoming::Ping { .. } => { + send(&Outgoing::Pong { + v: PROTOCOL_VERSION, + }); + None + } + Incoming::HitTestResult { + id: request_id, + status, + elements, + .. + } => { + route( + inner, + id, + &request_id, + PendingKind::HitTest, + Reply::HitTest { status, elements }, + ); + None + } + Incoming::InspectResult { + id: request_id, + status, + tab, + css_viewport, + elements, + .. + } => { + route( + inner, + id, + &request_id, + PendingKind::Inspect, + Reply::Inspect { + status, + tab, + css_viewport, + elements, + }, + ); + None + } + Incoming::FindSensitiveResult { + id: request_id, + status, + matches, + .. + } => { + route( + inner, + id, + &request_id, + PendingKind::FindSensitive, + Reply::FindSensitive { status, matches }, + ); + None + } + } +} + +/// Delivers a reply to its waiting caller. A reply for an unknown or finished request, from a +/// connection that was not asked, or of the wrong kind is dropped. +fn route(inner: &Arc, connection: u64, request_id: &str, kind: PendingKind, reply: Reply) { + let shared = lock(&inner.state); + if let Some(pending) = shared.pending.get(request_id) + && pending.kind == kind + && pending.from.contains(&connection) + { + let _ = pending.sender.send(reply); + } +} + +// --------------------------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use tokio_tungstenite::tungstenite::{client::IntoClientRequest, http::HeaderValue}; + + const EXTENSION_ORIGIN: &str = "chrome-extension://abcdefghijklmnopabcdefghijklmnop"; + + fn headers(origin: Option<&str>, host: Option<&str>) -> HeaderMap { + let mut map = HeaderMap::new(); + if let Some(origin) = origin { + map.insert("origin", HeaderValue::from_str(origin).unwrap()); + } + if let Some(host) = host { + map.insert("host", HeaderValue::from_str(host).unwrap()); + } + map + } + + #[test] + fn upgrade_accepts_an_extension_origin_on_a_local_host() { + assert!(validate_upgrade( + &headers(Some(EXTENSION_ORIGIN), Some("127.0.0.1:47811")), + 47811 + )); + assert!(validate_upgrade( + &headers(Some(EXTENSION_ORIGIN), Some("localhost:47811")), + 47811 + )); + } + + #[test] + fn upgrade_rejects_web_origins_bad_ids_and_foreign_hosts() { + let good_host = Some("127.0.0.1:47811"); + for origin in [ + Some("https://example.com"), + Some("http://localhost:3000"), + Some("chrome-extension://abcdefghijklmnopabcdefghijklmnoq"), + Some("chrome-extension://abcdefghijklmnopabcdefghijklmno"), + Some("chrome-extension://ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"), + Some("chrome-extension://abcdefghijklmnopabcdefghijklmnop/x"), + None, + ] { + assert!( + !validate_upgrade(&headers(origin, good_host), 47811), + "{origin:?}" + ); + } + for host in [ + Some("evil.example:47811"), + Some("127.0.0.1:9999"), + Some("127.0.0.1"), + Some("localhost.evil.example:47811"), + None, + ] { + assert!( + !validate_upgrade(&headers(Some(EXTENSION_ORIGIN), host), 47811), + "{host:?}" + ); + } + } + + #[test] + fn constant_time_compare_matches_equality() { + assert!(constant_time_eq(b"123456", b"123456")); + assert!(!constant_time_eq(b"123456", b"123457")); + assert!(!constant_time_eq(b"123456", b"12345")); + assert!(constant_time_eq(b"", b"")); + } + + #[test] + fn tokens_are_43_url_safe_characters_and_unique() { + let first = new_token(); + assert_eq!(first.len(), 43); + assert!( + first + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') + ); + assert_ne!(first, new_token()); + assert_eq!(base64url(b"foobar"), "Zm9vYmFy"); + assert_eq!(base64url(b"fo"), "Zm8"); + } + + #[test] + fn codes_are_six_digits() { + for _ in 0..50 { + let code = new_code(); + assert_eq!(code.len(), 6); + assert!(code.bytes().all(|byte| byte.is_ascii_digit())); + } + } + + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_800_000_000 + seconds, 0).unwrap() + } + + #[test] + fn pairing_code_is_single_use() { + let mut state = PairingState::default(); + state.start("123456".into(), at(0)); + assert_eq!(state.verify("123456", at(10)), Ok(())); + assert_eq!(state.verify("123456", at(11)), Err(PairReject::NotPairing)); + } + + #[test] + fn pairing_without_a_code_is_rejected() { + let mut state = PairingState::default(); + assert_eq!(state.verify("123456", at(0)), Err(PairReject::NotPairing)); + } + + #[test] + fn pairing_code_expires_after_120_seconds() { + let mut state = PairingState::default(); + let expires = state.start("123456".into(), at(0)); + assert_eq!(expires, at(120)); + assert_eq!(state.verify("123456", at(119)), Ok(())); + state.start("123456".into(), at(0)); + assert_eq!(state.verify("123456", at(120)), Err(PairReject::Expired)); + assert_eq!(state.verify("123456", at(121)), Err(PairReject::NotPairing)); + } + + #[test] + fn five_wrong_codes_are_allowed_then_the_code_is_burned() { + let mut state = PairingState::default(); + state.start("123456".into(), at(0)); + for _ in 0..5 { + assert_eq!(state.verify("000000", at(1)), Err(PairReject::WrongCode)); + } + assert_eq!( + state.verify("123456", at(2)), + Err(PairReject::TooManyAttempts) + ); + assert_eq!(state.verify("123456", at(3)), Err(PairReject::NotPairing)); + } + + #[test] + fn a_new_code_replaces_the_old_one_and_resets_attempts() { + let mut state = PairingState::default(); + state.start("111111".into(), at(0)); + assert_eq!(state.verify("000000", at(1)), Err(PairReject::WrongCode)); + state.start("222222".into(), at(2)); + assert_eq!(state.verify("111111", at(3)), Err(PairReject::WrongCode)); + assert_eq!(state.verify("222222", at(4)), Ok(())); + } + + #[test] + fn every_extension_message_round_trips_and_rejects_unknown_fields() { + let browser = r#"{"name":"Chrome","version":"130"}"#; + let frames = [ + format!(r#"{{"v":1,"type":"pair","code":"123456","browser":{browser},"extensionVersion":"0.1.0"}}"#), + format!(r#"{{"v":1,"type":"hello","token":"t","browser":{browser},"extensionVersion":"0.1.0"}}"#), + r#"{"v":1,"type":"ping"}"#.to_owned(), + r#"{"v":1,"type":"hitTestResult","id":"a","status":"ok","tab":{"url":"http://x","title":"X"},"elements":[{"key":"k","label":"button","rect":{"x":1,"y":2,"width":3,"height":4}}]}"#.to_owned(), + r#"{"v":1,"type":"hitTestResult","id":"a","status":"no-tab","elements":[]}"#.to_owned(), + r#"{"v":1,"type":"inspectResult","id":"a","status":"mismatch","elements":[]}"#.to_owned(), + r#"{"v":1,"type":"findSensitiveResult","id":"a","status":"ok","matches":[{"kind":"password","preview":"****","rects":[{"x":1,"y":2,"width":3,"height":4}]}]}"#.to_owned(), + ]; + for raw in &frames { + assert!(parse_incoming(raw).is_some(), "{raw}"); + let polluted = raw.replacen('{', r#"{"extra":1,"#, 1); + assert!(parse_incoming(&polluted).is_none(), "{polluted}"); + } + } + + #[test] + fn inspect_result_round_trips_element_details() { + let raw = r##"{"v":1,"type":"inspectResult","id":"a","status":"ok","cssViewport":{"width":1440,"height":900,"devicePixelRatio":2},"elements":[{"label":"Button","tag":"button","role":"button","accessibleName":"Go","text":"Go","selector":"button","component":{"name":"Cta","ownerPath":["App"]},"source":{"file":"src/a.tsx","line":4,"column":7},"classes":"x","styles":{"color":"#fff","backgroundColor":"#000","fontFamily":"Inter","fontSize":"16px","fontWeight":"600","lineHeight":"24px","padding":"1px","margin":"0","borderRadius":"8px","boxShadow":"none","display":"block","gap":"normal"},"cssRect":{"x":1,"y":2,"width":3,"height":4},"rect":{"x":2,"y":4,"width":6,"height":8}}]}"##; + let Some(Incoming::InspectResult { + elements, + css_viewport, + .. + }) = parse_incoming(raw) + else { + panic!("did not parse"); + }; + assert_eq!(elements.len(), 1); + assert_eq!(elements[0].source.as_ref().unwrap().line, 4); + assert_eq!(css_viewport.unwrap().device_pixel_ratio, 2.0); + let again = serde_json::to_string(&elements[0]).unwrap(); + assert!(again.contains("\"accessibleName\":\"Go\"")); + assert!(!again.contains("sourceUnavailableReason")); + } + + #[test] + fn wrong_versions_and_oversize_frames_are_rejected() { + assert!(parse_incoming(r#"{"v":2,"type":"ping"}"#).is_none()); + assert!(parse_incoming("not json").is_none()); + let padding = " ".repeat(MAX_FRAME_BYTES); + assert!(parse_incoming(&format!(r#"{{"v":1,"type":"ping"}}{padding}"#)).is_none()); + } + + #[test] + fn outgoing_messages_use_the_wire_names() { + let request = frame(&Outgoing::HitTest { + v: 1, + id: "id", + window_title: "T".into(), + viewport: Rect { + x: 1.0, + y: 2.0, + width: 3.0, + height: 4.0, + }, + point: Point { x: 5.0, y: 6.0 }, + }); + assert_eq!( + request, + r#"{"type":"hitTest","v":1,"id":"id","windowTitle":"T","viewport":{"x":1.0,"y":2.0,"width":3.0,"height":4.0},"point":{"x":5.0,"y":6.0}}"# + ); + let rejected = frame(&Outgoing::PairRejected { + v: 1, + reason: PairReject::TooManyAttempts, + }); + assert_eq!( + rejected, + r#"{"type":"pairRejected","v":1,"reason":"too-many-attempts"}"# + ); + } + + // ---- service tests over a real localhost socket ------------------------------------------ + + type Client = tokio_tungstenite::WebSocketStream>; + + fn temp_config(name: &str) -> PathBuf { + let directory = std::env::temp_dir().join(format!("capkit-link-{name}-{}", Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + directory.join("browser-link.json") + } + + fn service(path: PathBuf) -> BrowserLinkService { + // Port 0 binds an ephemeral port so tests never collide with a running CapKit. + BrowserLinkService::with_parts(path, vec![0], Arc::new(|_| {})) + } + + async fn connect( + port: u16, + origin: &str, + ) -> Result { + let mut request = format!("ws://127.0.0.1:{port}") + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", HeaderValue::from_str(origin).unwrap()); + tokio_tungstenite::connect_async(request) + .await + .map(|(socket, _)| socket) + } + + async fn next_text(socket: &mut Client) -> String { + loop { + match timeout(Duration::from_secs(5), socket.next()) + .await + .unwrap() + { + Some(Ok(Message::Text(text))) => return text.to_string(), + Some(Ok(Message::Close(_))) | None => return "closed".into(), + Some(Ok(_)) => {} + Some(Err(_)) => return "error".into(), + } + } + } + + const PAIR_BROWSER: &str = r#"{"name":"Chrome","version":"130"}"#; + + fn pair_frame(code: &str) -> String { + format!( + r#"{{"v":1,"type":"pair","code":"{code}","browser":{PAIR_BROWSER},"extensionVersion":"0.1.0"}}"# + ) + } + + fn hello_frame(token: &str) -> String { + format!( + r#"{{"v":1,"type":"hello","token":"{token}","browser":{PAIR_BROWSER},"extensionVersion":"0.1.0"}}"# + ) + } + + fn token_from(text: &str) -> String { + serde_json::from_str::(text).unwrap()["token"] + .as_str() + .unwrap() + .to_owned() + } + + #[test] + fn no_socket_is_bound_while_developer_tools_is_off() { + let service = service(temp_config("off")); + let status = service.status(); + assert!(!status.enabled); + assert_eq!(status.state, "off"); + assert_eq!(status.port, None); + assert!(service.start_pairing().is_err()); + } + + #[test] + fn pairing_a_browser_persists_a_token_and_hello_reuses_it() { + let path = temp_config("pair"); + let link = service(path.clone()); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + let code = link.start_pairing().unwrap().code; + + let token = tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket.send(Message::text(pair_frame(&code))).await.unwrap(); + let reply = next_text(&mut socket).await; + assert!(reply.contains(r#""type":"paired""#), "{reply}"); + token_from(&reply) + }); + assert_eq!(token.len(), 43); + + let saved = std::fs::read_to_string(&path).unwrap(); + assert!(saved.contains(&token)); + // Status shown in Settings carries no secrets. + let status = serde_json::to_string(&link.status()).unwrap(); + assert!(!status.contains(&token)); + assert_eq!(link.status().paired.len(), 1); + + tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket + .send(Message::text(hello_frame(&token))) + .await + .unwrap(); + assert!(next_text(&mut socket).await.contains(r#""type":"ready""#)); + socket + .send(Message::text(r#"{"v":1,"type":"ping"}"#)) + .await + .unwrap(); + assert!(next_text(&mut socket).await.contains(r#""type":"pong""#)); + assert!(link.is_connected()); + + let mut other = connect(port, "chrome-extension://ponmlkjihgfedcbaponmlkjihgfedcba") + .await + .unwrap(); + other + .send(Message::text(hello_frame(&token))) + .await + .unwrap(); + assert!(next_text(&mut other).await.contains("helloRejected")); + }); + } + + #[test] + fn a_web_origin_never_upgrades() { + let link = service(temp_config("web")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + tauri::async_runtime::block_on(async { + assert!(connect(port, "https://evil.example").await.is_err()); + }); + } + + #[test] + fn an_unauthenticated_socket_cannot_send_requests_or_pings() { + let link = service(temp_config("unauth")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket + .send(Message::text(r#"{"v":1,"type":"ping"}"#)) + .await + .unwrap(); + assert_eq!(next_text(&mut socket).await, "closed"); + }); + } + + #[test] + fn an_oversize_frame_closes_the_socket() { + let link = service(temp_config("big")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + let big = format!( + r#"{{"v":1,"type":"ping","pad":"{}"}}"#, + "x".repeat(MAX_FRAME_BYTES) + ); + let _ = socket.send(Message::text(big)).await; + assert_ne!(next_text(&mut socket).await, "pong"); + }); + } + + #[test] + fn forgetting_a_browser_closes_its_sockets_and_removes_the_pairing() { + let link = service(temp_config("forget")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + let code = link.start_pairing().unwrap().code; + tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket.send(Message::text(pair_frame(&code))).await.unwrap(); + assert!(next_text(&mut socket).await.contains("paired")); + link.forget(EXTENSION_ORIGIN).unwrap(); + assert_eq!(next_text(&mut socket).await, "closed"); + }); + assert!(link.status().paired.is_empty()); + } + + #[test] + fn turning_the_switch_off_closes_sockets_and_unbinds_the_port() { + let link = service(temp_config("disable")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + tauri::async_runtime::block_on(async { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + link.set_enabled(false).unwrap(); + assert_eq!(next_text(&mut socket).await, "closed"); + }); + assert_eq!(link.status().state, "off"); + assert_eq!(link.status().port, None); + assert!(!link.is_connected()); + } + + #[test] + fn requests_reach_the_extension_and_the_first_ok_reply_wins() { + let link = service(temp_config("request")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + let code = link.start_pairing().unwrap().code; + let viewport = WebViewport { + window_id: 1, + window_title: "Page - Chrome".into(), + viewport: Rect { + x: 100.0, + y: 200.0, + width: 800.0, + height: 600.0, + }, + }; + + let answers = tauri::async_runtime::spawn(async move { + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket.send(Message::text(pair_frame(&code))).await.unwrap(); + let _ = next_text(&mut socket).await; + let request = next_text(&mut socket).await; + let value: serde_json::Value = serde_json::from_str(&request).unwrap(); + assert_eq!(value["type"], "hitTest"); + assert_eq!(value["point"]["x"], 20.0); + assert_eq!(value["point"]["y"], 30.0); + let id = value["id"].as_str().unwrap(); + // A reply with a wrong id is dropped; the right one is delivered. + socket + .send(Message::text( + r#"{"v":1,"type":"hitTestResult","id":"stale","status":"ok","elements":[]}"#, + )) + .await + .unwrap(); + socket + .send(Message::text(format!( + r#"{{"v":1,"type":"hitTestResult","id":"{id}","status":"ok","elements":[{{"key":"k1","label":"button","rect":{{"x":10,"y":20,"width":30,"height":40}}}}]}}"# + ))) + .await + .unwrap(); + socket + }); + + while !link.is_connected() { + std::thread::sleep(Duration::from_millis(10)); + } + let targets = link + .element_at(&viewport, Point { x: 120.0, y: 230.0 }) + .expect("targets"); + assert_eq!(targets.len(), 1); + assert_eq!(targets[0].id, "ext-k1"); + assert_eq!(targets[0].kind, "ui-region"); + assert_eq!( + targets[0].bounds, + Rect { + x: 110.0, + y: 220.0, + width: 30.0, + height: 40.0 + } + ); + let _keep_alive = tauri::async_runtime::block_on(answers).unwrap(); + } + + #[test] + fn a_request_with_no_browser_returns_none_without_waiting() { + let link = service(temp_config("none")); + link.set_enabled(true).unwrap(); + let viewport = WebViewport { + window_id: 1, + window_title: "x".into(), + viewport: Rect { + x: 0.0, + y: 0.0, + width: 10.0, + height: 10.0, + }, + }; + let started = std::time::Instant::now(); + assert!( + link.element_at(&viewport, Point { x: 1.0, y: 1.0 }) + .is_none() + ); + assert!(started.elapsed() < Duration::from_millis(100)); + } + + #[test] + fn a_corrupt_config_is_quarantined_and_starts_disabled() { + let path = temp_config("corrupt"); + std::fs::write(&path, "{ not json").unwrap(); + let link = service(path.clone()); + assert!(!link.status().enabled); + assert!(link.status().paired.is_empty()); + assert!(!path.exists()); + assert!(path.with_extension("json.bad").exists()); + } + + #[test] + fn busy_ports_surface_an_error_state() { + let blocker = StdListener::bind("127.0.0.1:0").unwrap(); + let busy = blocker.local_addr().unwrap().port(); + let link = + BrowserLinkService::with_parts(temp_config("busy"), vec![busy], Arc::new(|_| {})); + link.set_enabled(true).unwrap(); + let status = link.status(); + assert_eq!(status.state, "error"); + assert!(status.error.unwrap().contains("are in use")); + } +} diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index 924eaf7..548f504 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -38,7 +38,10 @@ use crate::{ error::SnaphubError, platform::{ CaptureBackend, ClipboardBackend, PermissionBackend, PinnedWindowBackend, - ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, + ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, WebViewport, + }, + services::browser_link::{ + BrowserElementSource, InspectResultDto, InspectTarget, SensitiveMatchDto, }, }; @@ -86,6 +89,9 @@ struct CompletionWork { pending_image: bool, } +/// A connected browser source and the page area it should answer for. +type WebPage<'a> = (&'a Arc, WebViewport); + pub struct CaptureService { capture: Arc, clipboard: Arc, @@ -94,6 +100,7 @@ pub struct CaptureService { scrolling: Arc, pinning: Arc, text_recognition: Arc, + browser: OnceLock>, sessions: Mutex>, manual_scrolling: Mutex>, save_directory: Mutex, @@ -139,6 +146,7 @@ impl CaptureService { scrolling: backend.clone(), text_recognition: backend.clone(), pinning: backend, + browser: OnceLock::new(), sessions: Mutex::new(HashMap::new()), manual_scrolling: Mutex::new(HashMap::new()), save_directory: Mutex::new(save_directory), @@ -150,6 +158,55 @@ impl CaptureService { } } + /// Lets detection, inspection and redaction ask a connected browser extension. + /// Set once, after the app handle exists. Later calls are ignored. + pub fn set_browser_source(&self, source: Arc) { + let _ = self.browser.set(source); + } + + /// The browser page under `point` and the connected source, when both exist. + fn web_page_at(&self, point: Point) -> Result>, SnaphubError> { + let Some(source) = self.browser.get().filter(|source| source.is_connected()) else { + return Ok(None); + }; + Ok(self + .targets + .web_viewport_at(point)? + .map(|viewport| (source, viewport))) + } + + /// Element details for a point or area over a browser page, or `None` when the extension + /// is not connected, the pointer is not over a page, or the page cannot answer. + pub fn inspect_web_target( + &self, + target: InspectTarget, + ) -> Result, SnaphubError> { + let anchor = match &target { + InspectTarget::Point(point) => *point, + InspectTarget::Area(area) => Point { + x: area.x + area.width / 2.0, + y: area.y + area.height / 2.0, + }, + }; + Ok(self + .web_page_at(anchor)? + .and_then(|(source, viewport)| source.inspect(&viewport, target))) + } + + /// Sensitive text found in the page behind `area`, with screen-pixel rectangles. + pub fn find_sensitive_web( + &self, + area: Rect, + ) -> Result>, SnaphubError> { + let anchor = Point { + x: area.x + area.width / 2.0, + y: area.y + area.height / 2.0, + }; + Ok(self + .web_page_at(anchor)? + .and_then(|(source, viewport)| source.find_sensitive(&viewport, area))) + } + pub fn begin(&self, cursor: Point) -> Result { #[cfg(debug_assertions)] let begin_started = Instant::now(); @@ -526,8 +583,21 @@ impl CaptureService { && point.y <= target.bounds.y + target.bounds.height }) .collect(); - if include_ui_regions && let Some(region) = self.targets.ui_region_at(point)? { - targets.push(region); + if include_ui_regions { + // Over a browser page the extension knows the real elements; otherwise (or when it + // has nothing for this point) fall back to UI Automation. + let from_page = match self.web_page_at(point)? { + Some((source, viewport)) => source.element_at(&viewport, point), + None => None, + }; + match from_page { + Some(elements) if !elements.is_empty() => targets.extend(elements), + _ => { + if let Some(region) = self.targets.ui_region_at(point)? { + targets.push(region); + } + } + } } targets.sort_by(|left, right| target_area(left).total_cmp(&target_area(right))); Ok(targets) @@ -1681,6 +1751,7 @@ mod tests { fail_clipboard: AtomicBool, clipboard_entered: Mutex>>, clipboard_release: Mutex>>, + web_viewport: Mutex>, } impl FakeBackend { @@ -1695,6 +1766,7 @@ mod tests { fail_clipboard: AtomicBool::new(false), clipboard_entered: Mutex::new(None), clipboard_release: Mutex::new(None), + web_viewport: Mutex::new(None), } } @@ -1762,6 +1834,10 @@ mod tests { fn ui_region_at(&self, _point: Point) -> Result, SnaphubError> { Ok(None) } + + fn web_viewport_at(&self, _point: Point) -> Result, SnaphubError> { + Ok(self.web_viewport.lock().unwrap().clone()) + } } impl TextRecognitionBackend for FakeBackend { @@ -1944,6 +2020,141 @@ mod tests { assert!(result.is_err()); } + struct FakeBrowser { + connected: bool, + elements: Option>, + } + + impl BrowserElementSource for FakeBrowser { + fn is_connected(&self) -> bool { + self.connected + } + + fn element_at( + &self, + _viewport: &WebViewport, + _point: Point, + ) -> Option> { + self.elements.clone() + } + + fn inspect( + &self, + _viewport: &WebViewport, + _target: InspectTarget, + ) -> Option { + None + } + + fn find_sensitive( + &self, + _viewport: &WebViewport, + _area: Rect, + ) -> Option> { + Some(Vec::new()) + } + } + + fn page_element() -> DetectedTargetDto { + DetectedTargetDto { + id: "ext-k1".into(), + title: "button".into(), + kind: "ui-region", + bounds: Rect { + x: 10.0, + y: 10.0, + width: 40.0, + height: 20.0, + }, + } + } + + fn browser_service( + name: &str, + connected: bool, + elements: Option>, + over_page: bool, + ) -> (CaptureService, TestDirectory) { + let directory = TestDirectory::new(name); + let backend = FakeBackend::new(); + if over_page { + *backend.web_viewport.lock().unwrap() = Some(WebViewport { + window_id: 1, + window_title: "Page".into(), + viewport: Rect { + x: 0.0, + y: 0.0, + width: 100.0, + height: 100.0, + }, + }); + } + let service = CaptureService::with_save_directory(Arc::new(backend), directory.0.clone()); + service.set_browser_source(Arc::new(FakeBrowser { + connected, + elements, + })); + (service, directory) + } + + #[test] + fn hover_over_a_browser_page_uses_the_extension_elements() { + let (service, _directory) = + browser_service("web-hover", true, Some(vec![page_element()]), true); + let targets = service + .detect_targets(Point { x: 20.0, y: 20.0 }, true) + .expect("targets"); + assert_eq!(targets.len(), 1); + assert_eq!(targets[0].id, "ext-k1"); + } + + #[test] + fn hover_falls_back_when_the_extension_has_nothing_or_is_not_connected_or_not_a_page() { + for (name, connected, elements, over_page) in [ + ("web-none", true, None, true), + ("web-empty", true, Some(Vec::new()), true), + ("web-off", false, Some(vec![page_element()]), true), + ("web-not-page", true, Some(vec![page_element()]), false), + ] { + let (service, _directory) = browser_service(name, connected, elements, over_page); + let targets = service + .detect_targets(Point { x: 20.0, y: 20.0 }, true) + .expect("targets"); + assert!(targets.is_empty(), "{name}"); + } + } + + #[test] + fn hover_ignores_the_extension_when_ui_regions_are_not_requested() { + let (service, _directory) = + browser_service("web-skip", true, Some(vec![page_element()]), true); + assert!( + service + .detect_targets(Point { x: 20.0, y: 20.0 }, false) + .expect("targets") + .is_empty() + ); + } + + #[test] + fn web_inspection_and_redaction_need_a_connected_page() { + let (service, _directory) = browser_service("web-redact", true, None, true); + let area = Rect { + x: 0.0, + y: 0.0, + width: 50.0, + height: 50.0, + }; + assert_eq!( + service.find_sensitive_web(area).expect("ok"), + Some(Vec::new()) + ); + let (offline, _directory) = browser_service("web-redact-off", false, None, true); + assert_eq!(offline.find_sensitive_web(area).expect("ok"), None); + let (no_page, _directory) = browser_service("web-redact-nopage", true, None, false); + assert_eq!(no_page.find_sensitive_web(area).expect("ok"), None); + } + #[test] fn pick_color_reads_the_physical_pixel_and_copies_text() { let directory = TestDirectory::new("pick-color"); diff --git a/apps/desktop/src-tauri/src/services/mod.rs b/apps/desktop/src-tauri/src/services/mod.rs index 16ce1d9..434b5fb 100644 --- a/apps/desktop/src-tauri/src/services/mod.rs +++ b/apps/desktop/src-tauri/src/services/mod.rs @@ -1,3 +1,4 @@ +pub mod browser_link; pub mod capture; pub mod media; pub mod paths; diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 166831f..89ab715 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -45,7 +45,7 @@ import { import { captureCursor } from "./lib/cursor"; import { prefersReducedMotion } from "./lib/motion"; import { eyedropperFormat } from "./lib/eyedropper"; -import { suggestRedactions } from "./lib/redactionPatterns"; +import { suggestRedactions, suggestRedactionsFromWeb } from "./lib/redactionPatterns"; import { createVisualTargetDetector, type VisualTargetDetector } from "./lib/visualTargets"; import { cancelCapture, @@ -63,6 +63,7 @@ import { listTargets, listenForCaptureRequest, pickCaptureColor, + findSensitiveWeb, recognizeCaptureText, requestCapture, retryCaptureSave, @@ -792,9 +793,17 @@ export function App(): React.JSX.Element { setCompletionState({ phase: "idle", message: "" }); setRedactionReview({ phase: "reading" }); try { - const recognized = await recognizeCaptureText(session.id, reviewedSelection); + // A paired browser extension knows the exact rectangles of page text; OCR + // is the fallback for everything else, and for any extension failure. + const web = await findSensitiveWeb(reviewedSelection, session.display).catch(() => null); if (redactionSequence.current !== sequence) return; - const suggestions = suggestRedactions(recognized, reviewedSelection); + const recognized = web === null ? await recognizeCaptureText(session.id, reviewedSelection) : null; + if (redactionSequence.current !== sequence) return; + const suggestions = web !== null + ? suggestRedactionsFromWeb(web, reviewedSelection) + : recognized === null + ? [] + : suggestRedactions(recognized, reviewedSelection); setRedactionReview({ phase: "ready", suggestions, diff --git a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx new file mode 100644 index 0000000..e8d1dc8 --- /dev/null +++ b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx @@ -0,0 +1,109 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { BrowserLinkStatus } from "../../lib/tauri"; +import { BrowserExtensionSettings, secondsUntil } from "./BrowserExtensionSettings"; + +const tauri = vi.hoisted(() => ({ + getBrowserLinkStatus: vi.fn(), + setBrowserLinkEnabled: vi.fn(), + startBrowserPairing: vi.fn(), + cancelBrowserPairing: vi.fn(), + forgetBrowser: vi.fn(), + listenForBrowserLinkStatus: vi.fn(), +})); + +vi.mock("../../lib/tauri", async (importOriginal) => ({ + ...(await importOriginal()), + ...tauri, +})); + +const off: BrowserLinkStatus = { enabled: false, state: "off", port: null, error: null, connected: [], paired: [] }; +const listening: BrowserLinkStatus = { ...off, enabled: true, state: "listening", port: 47811 }; +const origin = "chrome-extension://abcdefghijklmnopabcdefghijklmnop"; + +describe("BrowserExtensionSettings", () => { + beforeEach(() => { + tauri.getBrowserLinkStatus.mockResolvedValue(off); + tauri.listenForBrowserLinkStatus.mockResolvedValue(() => undefined); + tauri.cancelBrowserPairing.mockResolvedValue(undefined); + }); + afterEach(() => { + cleanup(); + vi.clearAllMocks(); + }); + + it("starts off and turns the link on", async () => { + tauri.setBrowserLinkEnabled.mockResolvedValue(listening); + render(); + + const toggle = await screen.findByRole("switch", { name: "Developer tools" }); + await waitFor(() => expect(toggle).toBeEnabled()); + expect(toggle).not.toBeChecked(); + expect(screen.queryByRole("button", { name: "Pair a browser" })).toBeNull(); + + fireEvent.click(toggle); + + expect(tauri.setBrowserLinkEnabled).toHaveBeenCalledWith(true); + expect(await screen.findByRole("button", { name: "Pair a browser" })).toBeVisible(); + }); + + it("shows the pairing code with a countdown and cancels it", async () => { + tauri.getBrowserLinkStatus.mockResolvedValue(listening); + tauri.startBrowserPairing.mockResolvedValue({ code: "123456", expiresAt: new Date(Date.now() + 120_000).toISOString() }); + render(); + + fireEvent.click(await screen.findByRole("button", { name: "Pair a browser" })); + expect(await screen.findByText("123456")).toBeVisible(); + expect(screen.getByText(/Expires in 1[12]\d s/)).toBeVisible(); + + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(tauri.cancelBrowserPairing).toHaveBeenCalled(); + expect(screen.queryByText("123456")).toBeNull(); + }); + + it("offers a new code once the old one has expired", async () => { + tauri.getBrowserLinkStatus.mockResolvedValue(listening); + tauri.startBrowserPairing.mockResolvedValue({ code: "654321", expiresAt: new Date(Date.now() - 1000).toISOString() }); + render(); + + fireEvent.click(await screen.findByRole("button", { name: "Pair a browser" })); + + expect(await screen.findByText("That code expired.")).toBeVisible(); + expect(screen.getByRole("button", { name: "New pairing code" })).toBeVisible(); + }); + + it("lists paired browsers and forgets one", async () => { + const paired: BrowserLinkStatus = { + ...listening, + connected: [{ name: "Chrome", version: "130" }], + paired: [{ origin, browser: { name: "Chrome", version: "130" }, pairedAt: "2026-11-19T00:00:00Z" }], + }; + tauri.getBrowserLinkStatus.mockResolvedValue(paired); + tauri.forgetBrowser.mockResolvedValue(listening); + render(); + + expect(await screen.findByText(/Connected · chrome-extension/)).toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "Forget Chrome" })); + + expect(tauri.forgetBrowser).toHaveBeenCalledWith(origin); + await waitFor(() => expect(screen.queryByRole("list", { name: "Paired browsers" })).toBeNull()); + }); + + it("reports a failure to switch on", async () => { + tauri.setBrowserLinkEnabled.mockRejectedValue("SH-LINK-001: ports busy"); + render(); + + const toggle = await screen.findByRole("switch", { name: "Developer tools" }); + await waitFor(() => expect(toggle).toBeEnabled()); + fireEvent.click(toggle); + + expect(await screen.findByRole("alert")).toHaveTextContent("ports busy"); + }); + + it("counts whole seconds and never goes negative", () => { + expect(secondsUntil(new Date(10_500).toISOString(), 0)).toBe(11); + expect(secondsUntil(new Date(0).toISOString(), 5000)).toBe(0); + expect(secondsUntil("not a date", 0)).toBe(0); + }); +}); diff --git a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx new file mode 100644 index 0000000..ef0f016 --- /dev/null +++ b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx @@ -0,0 +1,195 @@ +import { useCallback, useEffect, useState } from "react"; +import { + cancelBrowserPairing, + describeInvokeError, + forgetBrowser, + getBrowserLinkStatus, + listenForBrowserLinkStatus, + setBrowserLinkEnabled, + startBrowserPairing, + type BrowserLinkStatus, + type PairingCode, +} from "../../lib/tauri"; + +const buttonClass = + "shrink-0 rounded-md border border-stone-300 bg-stone-50 px-3 py-1.5 text-[12px] font-semibold text-stone-700 outline-none transition hover:border-stone-500 focus-visible:ring-2 focus-visible:ring-[var(--snaphub-accent)] disabled:cursor-not-allowed disabled:opacity-60 dark:border-white/10 dark:bg-[#333431] dark:text-stone-300 dark:hover:border-white/20"; + +/** Whole seconds left until `expiresAt`, never below zero. */ +export function secondsUntil(expiresAt: string, now: number): number { + const target = Date.parse(expiresAt); + if (Number.isNaN(target)) return 0; + return Math.max(0, Math.ceil((target - now) / 1000)); +} + +function describeState(status: BrowserLinkStatus): string { + if (!status.enabled) return "Off. Nothing is listening."; + if (status.state === "error") return status.error ?? "Could not start the browser link."; + if (status.connected.length > 0) { + return `Connected to ${status.connected.map((browser) => browser.name).join(", ")}.`; + } + return status.port === null ? "Starting…" : "Listening. Open the CapKit Inspector extension."; +} + +/** + * The Developer tools switch, the one-time pairing code and the paired browsers. + * Rust owns every secret; this panel only ever sees a short code and origins. + */ +export function BrowserExtensionSettings(): React.JSX.Element { + const [status, setStatus] = useState(null); + const [pairing, setPairing] = useState(null); + const [now, setNow] = useState(() => Date.now()); + const [message, setMessage] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let active = true; + let unlisten: (() => void) | undefined; + void getBrowserLinkStatus().then( + (next) => { + if (active) setStatus(next); + }, + () => undefined, + ); + void listenForBrowserLinkStatus((next) => { + if (active) setStatus(next); + }).then( + (stop) => { + if (active) unlisten = stop; + else stop(); + }, + () => undefined, + ); + return (): void => { + active = false; + unlisten?.(); + }; + }, []); + + const remaining = pairing === null ? 0 : secondsUntil(pairing.expiresAt, now); + const codeExpired = pairing !== null && remaining === 0; + + useEffect(() => { + if (pairing === null || codeExpired) return; + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return (): void => window.clearInterval(timer); + }, [codeExpired, pairing]); + + // A paired browser appearing means the code did its job. + const pairedCount = status?.paired.length ?? 0; + useEffect(() => { + setPairing(null); + }, [pairedCount]); + + const toggle = useCallback(async (enabled: boolean): Promise => { + setBusy(true); + setMessage(null); + try { + setStatus(await setBrowserLinkEnabled(enabled)); + if (!enabled) setPairing(null); + } catch (error: unknown) { + setMessage(describeInvokeError(error, "The browser link did not change")); + } finally { + setBusy(false); + } + }, []); + + const pair = useCallback(async (): Promise => { + setMessage(null); + try { + const code = await startBrowserPairing(); + setNow(Date.now()); + setPairing(code); + } catch (error: unknown) { + setMessage(describeInvokeError(error, "Could not create a pairing code")); + } + }, []); + + const cancel = useCallback(async (): Promise => { + setPairing(null); + await cancelBrowserPairing().catch(() => undefined); + }, []); + + const forget = useCallback(async (origin: string): Promise => { + setMessage(null); + try { + setStatus(await forgetBrowser(origin)); + } catch (error: unknown) { + setMessage(describeInvokeError(error, "Could not forget that browser")); + } + }, []); + + const enabled = status?.enabled ?? false; + + return ( +
+ + + {status === null ? null : ( +

{describeState(status)}

+ )} + + {enabled && status?.state === "listening" ? ( +
+ {pairing === null || codeExpired ? ( +
+

+ {codeExpired ? "That code expired." : "Pair a browser by entering a one-time code in the extension."} +

+ +
+ ) : ( +
+
+

Enter this code in the extension popup

+

{pairing.code}

+

Expires in {String(remaining)} s

+
+ +
+ )} +
+ ) : null} + + {status !== null && status.paired.length > 0 ? ( +
    + {status.paired.map((entry) => { + const isConnected = status.connected.some((browser) => browser.name === entry.browser.name); + return ( +
  • +
    +

    {entry.browser.name} {entry.browser.version}

    +

    {isConnected ? "Connected" : "Not connected"} · {entry.origin}

    +
    + +
  • + ); + })} +
+ ) : null} + + {message === null ? null :

{message}

} +
+ ); +} diff --git a/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx b/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx index 0d9a3ad..6907ccd 100644 --- a/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx +++ b/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx @@ -298,13 +298,13 @@ describe("DashboardPanel", () => { within(tablist) .getAllByRole("tab") .map((tab) => tab.textContent), - ).toEqual(["General", "Screenshots", "Screen Draw", "Shortcuts"]); + ).toEqual(["General", "Screenshots", "Screen Draw", "Shortcuts", "Developer"]); const general = screen.getByRole("tab", { name: "General" }); expect(general).toHaveAttribute("aria-selected", "true"); expect(general).toHaveAttribute("aria-controls", "settings-panel-general"); expect(general).toHaveAttribute("tabindex", "0"); - for (const tab of ["Screenshots", "Screen Draw", "Shortcuts"]) { + for (const tab of ["Screenshots", "Screen Draw", "Shortcuts", "Developer"]) { expect(screen.getByRole("tab", { name: tab })).toHaveAttribute("tabindex", "-1"); } @@ -313,8 +313,8 @@ describe("DashboardPanel", () => { expect(panel).toHaveAttribute("aria-labelledby", "settings-tab-general"); fireEvent.keyDown(tablist, { key: "End" }); - expect(screen.getByRole("tab", { name: "Shortcuts" })).toHaveAttribute("aria-selected", "true"); - expect(screen.getByRole("tabpanel")).toHaveAttribute("id", "settings-panel-shortcuts"); + expect(screen.getByRole("tab", { name: "Developer" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByRole("tabpanel")).toHaveAttribute("id", "settings-panel-developer"); // ArrowRight past the last tab returns to the first. fireEvent.keyDown(tablist, { key: "ArrowRight" }); @@ -323,7 +323,7 @@ describe("DashboardPanel", () => { // ArrowLeft past the first tab wraps to the last. fireEvent.keyDown(tablist, { key: "ArrowLeft" }); - expect(screen.getByRole("tab", { name: "Shortcuts" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByRole("tab", { name: "Developer" })).toHaveAttribute("aria-selected", "true"); fireEvent.keyDown(tablist, { key: "Home" }); expect(screen.getByRole("tab", { name: "General" })).toHaveAttribute("aria-selected", "true"); diff --git a/apps/desktop/src/components/dashboard/SettingsTabs.tsx b/apps/desktop/src/components/dashboard/SettingsTabs.tsx index 7deb19a..696b070 100644 --- a/apps/desktop/src/components/dashboard/SettingsTabs.tsx +++ b/apps/desktop/src/components/dashboard/SettingsTabs.tsx @@ -1,7 +1,7 @@ import { useCallback, useLayoutEffect, useRef, useState } from "react"; /** The four groups Settings is split into, by the task someone is doing. */ -export type SettingsTabId = "general" | "screenshots" | "screen-draw" | "shortcuts"; +export type SettingsTabId = "general" | "screenshots" | "screen-draw" | "shortcuts" | "developer"; export type SettingsTabDefinition = { id: SettingsTabId; diff --git a/apps/desktop/src/components/dashboard/SettingsView.tsx b/apps/desktop/src/components/dashboard/SettingsView.tsx index aaf9e3f..f02092d 100644 --- a/apps/desktop/src/components/dashboard/SettingsView.tsx +++ b/apps/desktop/src/components/dashboard/SettingsView.tsx @@ -47,6 +47,7 @@ import { setStartupEnabled, type StartupState, } from "../../lib/startup"; +import { BrowserExtensionSettings } from "./BrowserExtensionSettings"; import { SettingsTabs, type SettingsTabId } from "./SettingsTabs"; import { ToolbarConfiguration } from "./ToolbarConfiguration"; import { useUpdateStatus } from "./useUpdateStatus"; @@ -84,6 +85,7 @@ const settingsTabs = [ { id: "screenshots", label: "Screenshots" }, { id: "screen-draw", label: "Screen Draw" }, { id: "shortcuts", label: "Shortcuts" }, + { id: "developer", label: "Developer" }, ] as const satisfies readonly { id: SettingsTabId; label: string }[]; type SettingsSectionId = @@ -98,13 +100,15 @@ type SettingsSectionId = | "capture-cursor" | "scrolling" | "on-screen-toolbar" - | "shortcuts"; + | "shortcuts" + | "browser-extension"; const settingsSections: Record = { general: ["startup", "updates", "save-location", "save-recordings", "theme-accent"], screenshots: ["capture-toolbar", "colors", "detection", "capture-cursor", "scrolling"], "screen-draw": ["on-screen-toolbar"], shortcuts: ["shortcuts"], + developer: ["browser-extension"], }; /** Sections whose body holds a shortcut row that can be mid-recording. */ @@ -128,6 +132,7 @@ function defaultOpenSections(): Record { scrolling: false, "on-screen-toolbar": false, shortcuts: false, + "browser-extension": false, }; for (const sections of Object.values(settingsSections)) { const first = sections[0]; @@ -653,6 +658,10 @@ export function SettingsView(): React.JSX.Element { update({ ...settings, scrolling: defaultSnaphubSettings.scrolling })} /> + ) : activeTab === "developer" ? ( + + + ) : activeTab === "screen-draw" ? (
diff --git a/apps/desktop/src/lib/redactionPatterns.test.ts b/apps/desktop/src/lib/redactionPatterns.test.ts index 0ad12e8..2e49c14 100644 --- a/apps/desktop/src/lib/redactionPatterns.test.ts +++ b/apps/desktop/src/lib/redactionPatterns.test.ts @@ -6,6 +6,7 @@ import { passesLuhn, shannonEntropy, suggestRedactions, + suggestRedactionsFromWeb, } from "./redactionPatterns"; function kinds(text: string): string[] { @@ -107,3 +108,44 @@ describe("suggestRedactions", () => { ).toEqual([]); }); }); + +describe("suggestRedactionsFromWeb", () => { + const selection = { x: 100, y: 50, width: 200, height: 100 }; + + it("maps display-local rects into the selection and pads them", () => { + const [first] = suggestRedactionsFromWeb( + [{ kind: "email", preview: "ada@example.com", rects: [{ x: 120, y: 70, width: 60, height: 12 }] }], + selection, + ); + expect(first?.bounds).toEqual({ x: 17, y: 17, width: 66, height: 18 }); + expect(first?.kind).toBe("email"); + expect(first?.preview).not.toContain("ada@example.com"); + }); + + it("clamps to the selection and drops rects outside it", () => { + const suggestions = suggestRedactionsFromWeb( + [ + { + kind: "token", + preview: "ghp_abcdefghijklmnopqrstuvwxyz0123456789", + rects: [ + { x: 280, y: 140, width: 80, height: 30 }, + { x: 400, y: 70, width: 20, height: 10 }, + { x: 100, y: 10, width: 20, height: 10 }, + ], + }, + ], + selection, + ); + expect(suggestions).toHaveLength(1); + expect(suggestions[0]?.bounds).toEqual({ x: 177, y: 87, width: 23, height: 13 }); + }); + + it("gives every rectangle of a wrapped match its own id", () => { + const suggestions = suggestRedactionsFromWeb( + [{ kind: "card", preview: "4111111111111111", rects: [{ x: 110, y: 60, width: 40, height: 10 }, { x: 110, y: 80, width: 40, height: 10 }] }], + selection, + ); + expect(new Set(suggestions.map((s) => s.id)).size).toBe(2); + }); +}); diff --git a/apps/desktop/src/lib/redactionPatterns.ts b/apps/desktop/src/lib/redactionPatterns.ts index c093476..a152476 100644 --- a/apps/desktop/src/lib/redactionPatterns.ts +++ b/apps/desktop/src/lib/redactionPatterns.ts @@ -85,3 +85,39 @@ export function suggestRedactions( }); return suggestions; } + +/** What the browser extension reports for one piece of sensitive page text. */ +export type WebSensitiveReport = { + kind: SensitiveKind | "password"; + /** Already masked by the extension; masked again here so it never leaks. */ + preview: string; + /** Display-local logical pixels, one rectangle per line the text spans. */ + rects: readonly Rect[]; +}; + +/** + * Turns the extension's exact rectangles into redaction suggestions in + * selection-local pixels. Rectangles outside the selection are dropped and the + * rest are padded and clamped, so a blackout never spills past the capture. + */ +export function suggestRedactionsFromWeb( + reports: readonly WebSensitiveReport[], + selection: Rect, +): RedactionSuggestion[] { + const suggestions: RedactionSuggestion[] = []; + reports.forEach((report, reportIndex) => { + report.rects.forEach((rect, rectIndex) => { + const local = { x: rect.x - selection.x, y: rect.y - selection.y, width: rect.width, height: rect.height }; + if (local.x >= selection.width || local.y >= selection.height || local.x + local.width <= 0 || local.y + local.height <= 0) return; + const bounds = padAndClamp(local, selection); + if (bounds.width <= 0 || bounds.height <= 0) return; + suggestions.push({ + id: `web:${String(reportIndex)}:${String(rectIndex)}`, + kind: report.kind, + preview: maskPreview(report.preview), + bounds, + }); + }); + }); + return suggestions; +} diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts index 13ab8a7..b0e6aa8 100644 --- a/apps/desktop/src/lib/tauri.ts +++ b/apps/desktop/src/lib/tauri.ts @@ -584,3 +584,110 @@ export async function listenForUpdateStatus(handler: (status: UpdateStatus) => v export function validateSelection(value: unknown): Rect { return rectSchema.parse(value); } + +// --------------------------------------------------------------------------- +// Browser link (CapKit Inspector extension) +// --------------------------------------------------------------------------- + +const browserNameSchema = z.object({ name: z.string(), version: z.string() }); + +export const browserLinkStatusSchema = z.object({ + enabled: z.boolean(), + state: z.enum(["off", "listening", "error"]), + port: z.number().int().nullable(), + error: z.string().nullable(), + connected: z.array(browserNameSchema), + paired: z.array( + z.object({ origin: z.string(), browser: browserNameSchema, pairedAt: z.string() }), + ), +}); +export type BrowserLinkStatus = z.infer; + +const pairingCodeSchema = z.object({ code: z.string().regex(/^\d{6}$/), expiresAt: z.string() }); +export type PairingCode = z.infer; + +const webSensitiveMatchSchema = z.object({ + kind: z.enum(["token", "card", "email", "phone", "secret", "password"]), + preview: z.string(), + rects: z.array(rectSchema), +}); + +/** Sensitive text the extension found in the page, in display-local logical pixels. */ +export type WebSensitiveMatch = z.infer; + +const offlineLinkStatus: BrowserLinkStatus = { + enabled: false, + state: "off", + port: null, + error: null, + connected: [], + paired: [], +}; + +export async function getBrowserLinkStatus(): Promise { + if (!isTauri()) return offlineLinkStatus; + return browserLinkStatusSchema.parse(await invoke("browser_link_status")); +} + +export async function setBrowserLinkEnabled(enabled: boolean): Promise { + if (!isTauri()) return { ...offlineLinkStatus, enabled }; + return browserLinkStatusSchema.parse(await invoke("browser_link_set_enabled", { enabled })); +} + +export async function startBrowserPairing(): Promise { + const raw: unknown = await invoke("browser_link_start_pairing"); + return pairingCodeSchema.parse(raw); +} + +export async function cancelBrowserPairing(): Promise { + if (!isTauri()) return; + await invoke("browser_link_cancel_pairing"); +} + +export async function forgetBrowser(origin: string): Promise { + if (!isTauri()) return offlineLinkStatus; + return browserLinkStatusSchema.parse(await invoke("browser_link_forget", { origin })); +} + +export async function listenForBrowserLinkStatus( + callback: (status: BrowserLinkStatus) => void, +): Promise { + if (!isTauri()) return () => undefined; + return listen("browser-link://status", (event) => { + const parsed = browserLinkStatusSchema.safeParse(event.payload); + if (parsed.success) callback(parsed.data); + }); +} + +/** + * Sensitive text in the browser page behind `area` (display-local logical + * pixels), or null when no connected extension can answer. + */ +export async function findSensitiveWeb( + area: Rect, + display: Display, +): Promise { + if (!isTauri()) return null; + const scale = display.scaleFactor; + const raw: unknown = await invoke("find_sensitive_web", { + area: { + x: (display.bounds.x + area.x) * scale, + y: (display.bounds.y + area.y) * scale, + width: area.width * scale, + height: area.height * scale, + }, + }); + if (raw === null) return null; + return z + .array(webSensitiveMatchSchema) + .parse(raw) + .map((match) => ({ + ...match, + rects: match.rects.map((rect) => ({ + x: rect.x / scale - display.bounds.x, + y: rect.y / scale - display.bounds.y, + width: rect.width / scale, + height: rect.height / scale, + })), + })); +} From 7006641b5cac21d40c1522c5dc441a6368cc8f0a Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 19 Nov 2026 21:14:49 +0530 Subject: [PATCH 06/18] feat(notes): note pins, Markdown handoff and Notes library Adds the Note tool (point pins and dashed areas with comments), element lookup through the browser link, Markdown handoff (copy/save) with masking, and a Notes tab in the dashboard. Aligns extension reconnect backoff with the spec (1, 2, 5, 10, then 30 s). Co-Authored-By: Claude Sonnet 5.5 --- apps/browser-extension/src/link.ts | 2 +- apps/desktop/src-tauri/src/domain.rs | 5 + apps/desktop/src-tauri/src/error.rs | 2 + apps/desktop/src-tauri/src/lib.rs | 153 +++- .../desktop/src-tauri/src/services/capture.rs | 123 ++- apps/desktop/src-tauri/src/services/mod.rs | 1 + apps/desktop/src-tauri/src/services/notes.rs | 790 ++++++++++++++++++ apps/desktop/src/App.test.tsx | 122 ++- apps/desktop/src/App.tsx | 229 ++++- .../src/components/AnnotationCanvas.tsx | 54 +- .../src/components/CompletionToolbar.test.tsx | 1 + .../src/components/NotePopover.test.tsx | 88 ++ apps/desktop/src/components/NotePopover.tsx | 119 +++ .../desktop/src/components/captureActions.tsx | 8 + .../components/dashboard/DashboardPanel.tsx | 29 +- .../components/dashboard/NotesView.test.tsx | 211 +++++ .../src/components/dashboard/NotesView.tsx | 371 ++++++++ apps/desktop/src/components/icons.tsx | 16 + apps/desktop/src/components/toolbarCatalog.ts | 2 + apps/desktop/src/domain/annotations.ts | 1 + apps/desktop/src/domain/capture.ts | 1 + apps/desktop/src/domain/notes.test.ts | 95 +++ apps/desktop/src/domain/notes.ts | 133 +++ apps/desktop/src/domain/settings.test.ts | 4 +- apps/desktop/src/domain/settings.ts | 16 +- apps/desktop/src/lib/tauri.ts | 128 ++- 26 files changed, 2684 insertions(+), 20 deletions(-) create mode 100644 apps/desktop/src-tauri/src/services/notes.rs create mode 100644 apps/desktop/src/components/NotePopover.test.tsx create mode 100644 apps/desktop/src/components/NotePopover.tsx create mode 100644 apps/desktop/src/components/dashboard/NotesView.test.tsx create mode 100644 apps/desktop/src/components/dashboard/NotesView.tsx create mode 100644 apps/desktop/src/domain/notes.test.ts create mode 100644 apps/desktop/src/domain/notes.ts diff --git a/apps/browser-extension/src/link.ts b/apps/browser-extension/src/link.ts index a759deeb..5fbb398 100644 --- a/apps/browser-extension/src/link.ts +++ b/apps/browser-extension/src/link.ts @@ -9,7 +9,7 @@ import { import type { LinkStatus } from "./messages"; export const PING_INTERVAL_MS = 20_000; -export const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000] as const; +export const BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000] as const; export type SocketLike = { onopen: ((event: Event) => void) | null; diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index be53781..7481513 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -176,6 +176,9 @@ pub struct CompletionRequest { pub session_id: String, pub selection: Rect, pub scene: AnnotationScene, + /// Required (a uuid) for `note-image`, where it names the screenshot file. + #[serde(default)] + pub note_id: Option, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] @@ -186,6 +189,8 @@ pub enum CompletionAction { Save, SaveAs, Pin, + /// Renders the capture into the Notes library and leaves the session open. + NoteImage, } #[derive(Debug, Clone, Copy, Serialize)] diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index 8d5dd1b..c65be73 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -28,6 +28,8 @@ pub enum SnaphubError { Update(String), #[error("SH-LINK-001: {0}")] Link(String), + #[error("SH-NOTES-001: {0}")] + Notes(String), } impl SnaphubError { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 520dc07..8aca790 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -28,6 +28,7 @@ use services::browser_link::{ SensitiveMatchDto, }; use services::capture::CaptureService; +use services::notes::{DeliverNoteRequest, DeliveryDto, NoteSummaryDto, NotesStore}; use services::recording::RecordingService; use services::scrolling::stitch_vertical; use services::updates::{ @@ -403,7 +404,11 @@ async fn complete_capture( .map_err(|error| { SnaphubError::Capture(format!("Capture completion worker failed: {error}")) })??; - if matches!(result.status, CompletionStatus::SavePending) { + // A note image only stores the screenshot. The overlay closes after the + // note itself is delivered, so the window and session stay as they are. + if matches!(result.status, CompletionStatus::SavePending) + || matches!(action, CompletionAction::NoteImage) + { return Ok(result); } if matches!( @@ -809,6 +814,134 @@ fn start_saved_capture_drag( } } +/// Copies and/or saves a note's Markdown. Called from the capture overlay after +/// the note's screenshot was written with the `note-image` completion. +#[tauri::command] +async fn deliver_note( + window: WebviewWindow, + app: AppHandle, + request: DeliverNoteRequest, +) -> Result { + ensure_capture_window(&window)?; + tauri::async_runtime::spawn_blocking(move || { + let outcome = services::notes::deliver( + &app.state::(), + |text| app.state::().copy_plain_text(text), + &request, + ); + // Closing the overlay is the frontend's call, once it has seen the outcome. + Ok(outcome) + }) + .await + .map_err(|error| SnaphubError::Notes(format!("Note worker failed: {error}")))? +} + +#[tauri::command] +async fn notes_list( + app: AppHandle, + query: Option, + limit: u32, + offset: u32, +) -> Result, SnaphubError> { + tauri::async_runtime::spawn_blocking(move || { + app.state::() + .list(query.as_deref(), limit, offset) + }) + .await + .map_err(|error| SnaphubError::Notes(error.to_string()))? +} + +#[tauri::command] +async fn notes_copy(app: AppHandle, id: String) -> Result<(), SnaphubError> { + tauri::async_runtime::spawn_blocking(move || { + let markdown = app.state::().markdown(&id)?; + app.state::().copy_plain_text(&markdown) + }) + .await + .map_err(|error| SnaphubError::Notes(error.to_string()))? +} + +#[tauri::command] +async fn notes_delete(app: AppHandle, id: String) -> Result<(), SnaphubError> { + tauri::async_runtime::spawn_blocking(move || app.state::().delete(&id)) + .await + .map_err(|error| SnaphubError::Notes(error.to_string()))? +} + +#[tauri::command] +async fn notes_cleanup_unsaved(app: AppHandle) -> Result { + tauri::async_runtime::spawn_blocking(move || { + app.state::() + .cleanup_unsaved_images(std::time::Duration::from_secs(7 * 24 * 60 * 60)) + }) + .await + .map_err(|error| SnaphubError::Notes(error.to_string()))? +} + +/// Opens the note's page in the default browser. Only http and https links open. +#[tauri::command] +fn notes_open_url(store: tauri::State<'_, NotesStore>, id: String) -> Result<(), SnaphubError> { + let url = store + .page_url(&id)? + .filter(|url| url.starts_with("http://") || url.starts_with("https://")) + .ok_or_else(|| SnaphubError::Notes("This note has no page address".into()))?; + #[cfg(target_os = "windows")] + return platform::windows_shell::open_path(Path::new(&url), false); + #[cfg(not(target_os = "windows"))] + { + let _ = url; + Err(SnaphubError::Window( + "Opening links is not implemented on this platform".into(), + )) + } +} + +/// Starts a native file drag of the note as a Markdown file, previewed by its screenshot. +#[tauri::command] +fn notes_start_drag( + window: WebviewWindow, + store: tauri::State<'_, NotesStore>, + service: tauri::State<'_, CaptureService>, + id: String, +) -> Result<(), SnaphubError> { + let exported = store.export_for_drag(&id)?; + let image = store.image_path(&id); + if !image.is_file() { + return Err(SnaphubError::Notes( + "This note has no screenshot to drag".into(), + )); + } + #[cfg(target_os = "windows")] + { + let preview = service.drag_preview_path(&image); + let dragged = window.clone(); + window + .run_on_main_thread(move || { + let result = drag::start_drag( + &dragged, + drag::DragItem::Files(vec![exported]), + drag::Image::File(preview), + |_result, _position| {}, + drag::Options { + skip_animatation_on_cancel_or_failure: false, + mode: drag::DragMode::Copy, + }, + ); + if let Err(error) = result { + eprintln!("SH-DRAG-001: {error}"); + } + }) + .map_err(|error| SnaphubError::Window(error.to_string())) + } + #[cfg(not(target_os = "windows"))] + { + let _ = (window, service, exported); + Err(SnaphubError::Window( + "Dragging notes is not implemented on this platform".into(), + )) + } +} + /// Grants the webview read access to images the user explicitly picked from disk. /// /// The asset protocol scope is otherwise locked to the CapKit save and temp @@ -983,6 +1116,11 @@ async fn complete_scrolling_capture( "Copy & Save is available only for a selected region".into(), )); } + CompletionAction::NoteImage => { + return Err(SnaphubError::Capture( + "Notes are available only for a selected region".into(), + )); + } CompletionAction::Pin => { let image = image::open(&source) .map_err(SnaphubError::export)? @@ -2758,6 +2896,13 @@ pub fn run() { delete_saved_capture, copy_saved_capture, start_saved_capture_drag, + deliver_note, + notes_list, + notes_copy, + notes_delete, + notes_cleanup_unsaved, + notes_open_url, + notes_start_drag, import_media_files, list_folder_images, scrolling_capture_supported, @@ -2813,6 +2958,12 @@ pub fn run() { .set_browser_source(std::sync::Arc::new(link.clone())); app.manage(link); + // Notes live in local app data. Nothing is created until a note is used. + let notes = NotesStore::new(app.path().app_local_data_dir()?.join("notes")); + app.state::() + .set_notes_images_directory(notes.images_directory()); + app.manage(notes); + if launched_in_background() && let Some(window) = app.get_webview_window("dashboard") { diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index 548f504..d36c192 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -101,6 +101,7 @@ pub struct CaptureService { pinning: Arc, text_recognition: Arc, browser: OnceLock>, + notes_images: OnceLock, sessions: Mutex>, manual_scrolling: Mutex>, save_directory: Mutex, @@ -147,6 +148,7 @@ impl CaptureService { text_recognition: backend.clone(), pinning: backend, browser: OnceLock::new(), + notes_images: OnceLock::new(), sessions: Mutex::new(HashMap::new()), manual_scrolling: Mutex::new(HashMap::new()), save_directory: Mutex::new(save_directory), @@ -164,6 +166,12 @@ impl CaptureService { let _ = self.browser.set(source); } + /// Where `note-image` completions write their screenshots (`/images`). + /// Set once; later calls are ignored. + pub fn set_notes_images_directory(&self, directory: PathBuf) { + let _ = self.notes_images.set(directory); + } + /// The browser page under `point` and the connected source, when both exist. fn web_page_at(&self, point: Point) -> Result>, SnaphubError> { let Some(source) = self.browser.get().filter(|source| source.is_connected()) else { @@ -288,11 +296,12 @@ impl CaptureService { Ok(None) } CompletionAction::Save => Ok(Some(self.save_new_image(&captured.image)?)), - CompletionAction::CopyAndSave | CompletionAction::SaveAs | CompletionAction::Pin => { - Err(SnaphubError::Capture( - "This completion action requires the capture surface".into(), - )) - } + CompletionAction::CopyAndSave + | CompletionAction::SaveAs + | CompletionAction::Pin + | CompletionAction::NoteImage => Err(SnaphubError::Capture( + "This completion action requires the capture surface".into(), + )), } } @@ -361,6 +370,19 @@ impl CaptureService { } } } + CompletionAction::NoteImage => { + // The session stays open so the note can still be retried or + // the capture finished another way. + let result = self.write_note_image(request, &output); + self.finish_operation(&work.output, SessionOutputState::Idle); + return result.map(|path| CompletionResult { + action: request.action, + output_path: Some(path.to_string_lossy().into_owned()), + status: CompletionStatus::Completed, + diagnostic: None, + cleanup_warning: None, + }); + } CompletionAction::Pin => { if !self.pinning.is_supported() { self.finish_operation(&work.output, SessionOutputState::Idle); @@ -392,6 +414,37 @@ impl CaptureService { }) } + /// Writes `/images/.png` via a temporary file so a crash never + /// leaves a half-written screenshot under a note's name. + fn write_note_image( + &self, + request: &CompletionRequest, + output: &RgbaImage, + ) -> Result { + let note_id = request + .note_id + .as_deref() + .filter(|id| { + Uuid::parse_str(id).is_ok_and(|parsed| parsed.hyphenated().to_string() == *id) + }) + .ok_or_else(|| SnaphubError::Notes("A note needs a valid id".into()))?; + let directory = self + .notes_images + .get() + .ok_or_else(|| SnaphubError::Notes("The notes folder is not ready".into()))?; + fs::create_dir_all(directory).map_err(SnaphubError::export)?; + let path = directory.join(format!("{note_id}.png")); + let temporary = directory.join(format!("{note_id}.png.tmp")); + output + .save_with_format(&temporary, image::ImageFormat::Png) + .map_err(SnaphubError::export)?; + fs::rename(&temporary, &path).map_err(|error| { + let _ = fs::remove_file(&temporary); + SnaphubError::export(error) + })?; + Ok(path) + } + pub fn retry_save(&self, session_id: &str) -> Result { let id = parse_session_id(session_id)?; let work = self.begin_completion(id, true)?; @@ -705,6 +758,11 @@ impl CaptureService { Ok(()) } + /// Puts plain text on the clipboard (a note's Markdown). + pub fn copy_plain_text(&self, text: &str) -> Result<(), SnaphubError> { + self.clipboard.copy_text(text) + } + pub fn copy_image_path(&self, path: &Path) -> Result<(), SnaphubError> { let image = image::open(path) .map_err(SnaphubError::export)? @@ -1918,6 +1976,7 @@ mod tests { intensity: 1.0, }], }, + note_id: None, } } @@ -2364,6 +2423,60 @@ mod tests { service.finalize_committed(&session_id).unwrap(); } + #[test] + fn note_image_renders_into_the_notes_folder_and_keeps_the_session_open() { + let directory = TestDirectory::new("note-image"); + let images = directory.0.join("notes").join("images"); + let backend = Arc::new(FakeBackend::new()); + let service = + CaptureService::with_save_directory(backend.clone(), directory.0.join("saves")); + service.set_notes_images_directory(images.clone()); + let session_id = begin_session(&service); + let note_id = Uuid::new_v4().to_string(); + let mut request = request_for(&session_id); + request.action = CompletionAction::NoteImage; + request.note_id = Some(note_id.clone()); + + let result = service + .complete(&request) + .expect("note image should render"); + + assert!(matches!(result.action, CompletionAction::NoteImage)); + assert!(matches!(result.status, CompletionStatus::Completed)); + let path = images.join(format!("{note_id}.png")); + assert_eq!(result.output_path.as_deref(), path.to_str()); + let saved = image::open(&path).expect("PNG should decode").into_rgba8(); + assert_eq!(saved.dimensions(), (10, 10)); + assert_eq!(saved.get_pixel(4, 4), &Rgba([8, 9, 8, 255])); + assert_eq!(backend.clipboard_calls.load(Ordering::SeqCst), 0); + assert!(!images.join(format!("{note_id}.png.tmp")).exists()); + assert!(png_files(&directory.0.join("saves")).is_empty()); + + // The session is still open, so the same capture can be completed again. + request.action = CompletionAction::Copy; + service + .complete(&request) + .expect("session stays open after a note image"); + service.finalize_committed(&session_id).unwrap(); + } + + #[test] + fn note_image_rejects_a_missing_or_malformed_note_id() { + let directory = TestDirectory::new("note-image-bad"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend, directory.0.join("saves")); + service.set_notes_images_directory(directory.0.join("images")); + let session_id = begin_session(&service); + let mut request = request_for(&session_id); + request.action = CompletionAction::NoteImage; + + assert!(service.complete(&request).is_err()); + request.note_id = Some("../escape".into()); + assert!(service.complete(&request).is_err()); + assert!(!directory.0.join("images").exists()); + service.cancel(&session_id).unwrap(); + } + #[test] fn save_failure_retries_only_the_retained_raster() { let directory = TestDirectory::new("save-retry"); diff --git a/apps/desktop/src-tauri/src/services/mod.rs b/apps/desktop/src-tauri/src/services/mod.rs index 434b5fb..6e146af 100644 --- a/apps/desktop/src-tauri/src/services/mod.rs +++ b/apps/desktop/src-tauri/src/services/mod.rs @@ -1,6 +1,7 @@ pub mod browser_link; pub mod capture; pub mod media; +pub mod notes; pub mod paths; pub mod recording; pub mod scrolling; diff --git a/apps/desktop/src-tauri/src/services/notes.rs b/apps/desktop/src-tauri/src/services/notes.rs new file mode 100644 index 0000000..5b86b06 --- /dev/null +++ b/apps/desktop/src-tauri/src/services/notes.rs @@ -0,0 +1,790 @@ +//! The Notes library: a small SQLite database of saved capture notes. +//! +//! Nothing is opened until the first call, so with Developer tools off no file +//! is created and no connection exists. Each note is one row of Markdown plus, +//! when it exists, the path of its screenshot under `images/`. + +use std::fs; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{Duration, SystemTime}; + +use chrono::{DateTime, SecondsFormat, Utc}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::error::SnaphubError; + +const SCHEMA_VERSION: i64 = 1; +const MAX_MARKDOWN_BYTES: usize = 1024 * 1024; +const MAX_URL_CHARS: usize = 4096; +const MAX_QUERY_CHARS: usize = 200; +const MAX_PAGE_SIZE: u32 = 200; + +fn notes_error(error: impl std::fmt::Display) -> SnaphubError { + SnaphubError::Notes(error.to_string()) +} + +/// What the capture surface hands over to be stored. +#[derive(Debug, Clone)] +pub struct NewNote { + pub id: String, + pub page_url: Option, + pub page_title: Option, + pub markdown: String, + pub pin_count: u32, + pub detail: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NoteSummaryDto { + pub id: String, + pub created_at: String, + pub page_url: Option, + pub page_title: Option, + pub image_path: Option, + pub pin_count: u32, + pub detail: String, + /// The first comment line, so a card says something without opening the note. + pub first_comment: Option, +} + +pub struct NotesStore { + root: PathBuf, + connection: Mutex>, +} + +impl NotesStore { + /// Does no I/O: the database opens on first use. + pub fn new(root: PathBuf) -> Self { + Self { + root, + connection: Mutex::new(None), + } + } + + pub fn images_directory(&self) -> PathBuf { + self.root.join("images") + } + + pub fn image_path(&self, id: &str) -> PathBuf { + self.images_directory().join(format!("{id}.png")) + } + + fn with_connection( + &self, + run: impl FnOnce(&Connection) -> Result, + ) -> Result { + let mut guard = self + .connection + .lock() + .map_err(|_| SnaphubError::Notes("The notes database is unavailable".into()))?; + if guard.is_none() { + *guard = Some(self.open()?); + } + match guard.as_ref() { + Some(connection) => run(connection), + None => Err(SnaphubError::Notes( + "The notes database is unavailable".into(), + )), + } + } + + fn open(&self) -> Result { + fs::create_dir_all(self.images_directory()).map_err(notes_error)?; + let connection = Connection::open(self.root.join("notes.sqlite")).map_err(notes_error)?; + // `journal_mode` returns a row, so it is read rather than executed. + connection + .query_row("PRAGMA journal_mode = WAL", [], |row| { + row.get::<_, String>(0) + }) + .map_err(notes_error)?; + let version: i64 = connection + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .map_err(notes_error)?; + if version > SCHEMA_VERSION { + return Err(SnaphubError::Notes( + "These notes were saved by a newer CapKit".into(), + )); + } + if version < 1 { + connection + .execute_batch( + "BEGIN; + CREATE TABLE IF NOT EXISTS notes ( + id TEXT PRIMARY KEY, + created_at TEXT NOT NULL, + page_url TEXT, + page_title TEXT, + markdown TEXT NOT NULL, + image_path TEXT, + pin_count INTEGER NOT NULL, + detail TEXT NOT NULL CHECK (detail IN ('extension','accessibility','none')) + ); + CREATE INDEX IF NOT EXISTS notes_created_at ON notes(created_at DESC); + PRAGMA user_version = 1; + COMMIT;", + ) + .map_err(notes_error)?; + } + Ok(connection) + } + + /// Inserts or replaces by id, so retrying a save never makes a second row. + pub fn insert(&self, note: &NewNote) -> Result { + validate_note(note)?; + let image = self.image_path(¬e.id); + let image_path = image + .is_file() + .then(|| image.to_string_lossy().into_owned()); + let created_at = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true); + self.with_connection(|connection| { + connection + .execute( + "INSERT OR REPLACE INTO notes + (id, created_at, page_url, page_title, markdown, image_path, pin_count, detail) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![ + note.id, + created_at, + note.page_url, + note.page_title, + note.markdown, + image_path, + note.pin_count, + note.detail + ], + ) + .map_err(notes_error)?; + Ok(()) + })?; + Ok(NoteSummaryDto { + id: note.id.clone(), + created_at, + page_url: note.page_url.clone(), + page_title: note.page_title.clone(), + image_path, + pin_count: note.pin_count, + detail: note.detail.clone(), + first_comment: first_comment(¬e.markdown), + }) + } + + pub fn list( + &self, + query: Option<&str>, + limit: u32, + offset: u32, + ) -> Result, SnaphubError> { + let pattern = query + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(|text| { + let clipped: String = text.chars().take(MAX_QUERY_CHARS).collect(); + format!("%{}%", escape_like(&clipped)) + }); + let limit = limit.clamp(1, MAX_PAGE_SIZE); + self.with_connection(|connection| { + let mut statement = connection + .prepare( + "SELECT id, created_at, page_url, page_title, markdown, image_path, pin_count, detail + FROM notes + WHERE ?1 IS NULL + OR page_title LIKE ?1 ESCAPE '\\' + OR page_url LIKE ?1 ESCAPE '\\' + OR markdown LIKE ?1 ESCAPE '\\' + ORDER BY created_at DESC, rowid DESC + LIMIT ?2 OFFSET ?3", + ) + .map_err(notes_error)?; + let rows = statement + .query_map(params![pattern, limit, offset], |row| { + let markdown: String = row.get(4)?; + Ok(NoteSummaryDto { + id: row.get(0)?, + created_at: row.get(1)?, + page_url: row.get(2)?, + page_title: row.get(3)?, + image_path: row.get(5)?, + pin_count: row.get(6)?, + detail: row.get(7)?, + first_comment: first_comment(&markdown), + }) + }) + .map_err(notes_error)?; + rows.collect::, _>>().map_err(notes_error) + }) + } + + pub fn markdown(&self, id: &str) -> Result { + validate_id(id)?; + self.with_connection(|connection| { + connection + .query_row("SELECT markdown FROM notes WHERE id = ?1", [id], |row| { + row.get::<_, String>(0) + }) + .optional() + .map_err(notes_error)? + .ok_or_else(|| SnaphubError::Notes("That note no longer exists".into())) + }) + } + + pub fn page_url(&self, id: &str) -> Result, SnaphubError> { + validate_id(id)?; + self.with_connection(|connection| { + connection + .query_row("SELECT page_url FROM notes WHERE id = ?1", [id], |row| { + row.get::<_, Option>(0) + }) + .optional() + .map_err(notes_error)? + .ok_or_else(|| SnaphubError::Notes("That note no longer exists".into())) + }) + } + + /// Removes the row and its screenshot. + pub fn delete(&self, id: &str) -> Result<(), SnaphubError> { + validate_id(id)?; + self.with_connection(|connection| { + connection + .execute("DELETE FROM notes WHERE id = ?1", [id]) + .map_err(notes_error)?; + Ok(()) + })?; + match fs::remove_file(self.image_path(id)) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(notes_error(error)), + } + } + + /// Writes the note's Markdown to a file a drag can carry, overwriting any + /// earlier export of the same note. + pub fn export_for_drag(&self, id: &str) -> Result { + validate_id(id)?; + let (created_at, page_url, markdown) = self.with_connection(|connection| { + connection + .query_row( + "SELECT created_at, page_url, markdown FROM notes WHERE id = ?1", + [id], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, String>(2)?, + )) + }, + ) + .optional() + .map_err(notes_error)? + .ok_or_else(|| SnaphubError::Notes("That note no longer exists".into())) + })?; + let directory = self.root.join("export"); + fs::create_dir_all(&directory).map_err(notes_error)?; + let stamp = DateTime::parse_from_rfc3339(&created_at) + .map(|time| { + time.with_timezone(&chrono::Local) + .format("%Y-%m-%d-%H%M") + .to_string() + }) + .unwrap_or_else(|_| "note".into()); + let host = page_url + .as_deref() + .and_then(host_of) + .map(|host| slug(&host)) + .filter(|host| !host.is_empty()) + .unwrap_or_else(|| "capture".into()); + let path = directory.join(format!("{stamp}-{host}.md")); + fs::write(&path, markdown).map_err(notes_error)?; + Ok(path) + } + + /// Removes screenshots older than `older_than` that no note references. + pub fn cleanup_unsaved_images(&self, older_than: Duration) -> Result { + let directory = self.images_directory(); + let Ok(entries) = fs::read_dir(&directory) else { + return Ok(0); + }; + let now = SystemTime::now(); + let mut removed = 0; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|extension| extension.to_str()) != Some("png") { + continue; + } + let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else { + continue; + }; + if validate_id(id).is_err() { + continue; + } + let old_enough = entry + .metadata() + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()) + .is_some_and(|age| age >= older_than); + if !old_enough { + continue; + } + let referenced = self.with_connection(|connection| { + connection + .query_row("SELECT 1 FROM notes WHERE id = ?1", [id], |_| Ok(())) + .optional() + .map(|row| row.is_some()) + .map_err(notes_error) + })?; + if !referenced && fs::remove_file(&path).is_ok() { + removed += 1; + } + } + Ok(removed) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DeliveryMode { + Copy, + Save, + CopyAndSave, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeliverNoteRequest { + pub note_id: String, + pub markdown: String, + pub page_url: Option, + pub page_title: Option, + pub pin_count: u32, + pub detail: String, + pub mode: DeliveryMode, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeliveryDto { + pub copied: bool, + pub saved: Option, + pub diagnostic: Option, +} + +/// Copies first, then saves, so a failed copy never leaves a saved note the +/// user believes is on their clipboard. A failure is reported in the result, +/// not as an error, because the caller needs to know how far it got. +pub fn deliver( + store: &NotesStore, + copy_text: impl FnOnce(&str) -> Result<(), SnaphubError>, + request: &DeliverNoteRequest, +) -> DeliveryDto { + let mut copied = false; + if matches!(request.mode, DeliveryMode::Copy | DeliveryMode::CopyAndSave) { + if let Err(error) = copy_text(&request.markdown) { + return DeliveryDto { + copied: false, + saved: None, + diagnostic: Some(error.to_string()), + }; + } + copied = true; + } + if matches!(request.mode, DeliveryMode::Save | DeliveryMode::CopyAndSave) { + let note = NewNote { + id: request.note_id.clone(), + page_url: request.page_url.clone(), + page_title: request.page_title.clone(), + markdown: request.markdown.clone(), + pin_count: request.pin_count, + detail: request.detail.clone(), + }; + return match store.insert(¬e) { + Ok(saved) => DeliveryDto { + copied, + saved: Some(saved), + diagnostic: None, + }, + Err(error) => DeliveryDto { + copied, + saved: None, + diagnostic: Some(error.to_string()), + }, + }; + } + DeliveryDto { + copied, + saved: None, + diagnostic: None, + } +} + +fn validate_id(id: &str) -> Result<(), SnaphubError> { + match Uuid::parse_str(id) { + Ok(parsed) if parsed.hyphenated().to_string() == id => Ok(()), + _ => Err(SnaphubError::Notes("That note id is not valid".into())), + } +} + +fn validate_note(note: &NewNote) -> Result<(), SnaphubError> { + validate_id(¬e.id)?; + if note.markdown.len() > MAX_MARKDOWN_BYTES { + return Err(SnaphubError::Notes("The note is too large to save".into())); + } + if let Some(url) = ¬e.page_url + && (url.chars().count() > MAX_URL_CHARS + || !(url.starts_with("http://") || url.starts_with("https://"))) + { + return Err(SnaphubError::Notes( + "The page address must be an http or https link".into(), + )); + } + if !(1..=99).contains(¬e.pin_count) { + return Err(SnaphubError::Notes( + "A note holds between 1 and 99 pins".into(), + )); + } + if !matches!(note.detail.as_str(), "extension" | "accessibility" | "none") { + return Err(SnaphubError::Notes("Unknown note detail level".into())); + } + Ok(()) +} + +/// `%`, `_` and the escape character itself match literally. +fn escape_like(text: &str) -> String { + let mut escaped = String::with_capacity(text.len()); + for character in text.chars() { + if matches!(character, '\\' | '%' | '_') { + escaped.push('\\'); + } + escaped.push(character); + } + escaped +} + +fn host_of(url: &str) -> Option { + let rest = url.split_once("://")?.1; + let authority = rest.split(['/', '?', '#']).next()?; + let host = authority.rsplit('@').next()?.split(':').next()?; + (!host.is_empty()).then(|| host.to_owned()) +} + +fn slug(text: &str) -> String { + let mapped: String = text + .to_ascii_lowercase() + .chars() + .map(|character| { + if character.is_ascii_lowercase() || character.is_ascii_digit() { + character + } else { + '-' + } + }) + .collect(); + mapped + .split('-') + .filter(|part| !part.is_empty()) + .collect::>() + .join("-") +} + +/// The first line of the first section's comment, skipping the placeholder. +fn first_comment(markdown: &str) -> Option { + let mut lines = markdown.lines(); + lines.find(|line| line.starts_with("## 1."))?; + lines + .map(str::trim) + .find(|line| !line.is_empty()) + .filter(|line| *line != "_No comment_" && !line.starts_with('-') && !line.starts_with('#')) + .map(|line| line.chars().take(160).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TestRoot(PathBuf); + + impl TestRoot { + fn new() -> Self { + let path = std::env::temp_dir().join(format!("capkit-notes-{}", Uuid::new_v4())); + fs::create_dir_all(&path).expect("create root"); + Self(path) + } + } + + impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn note(markdown: &str) -> NewNote { + NewNote { + id: Uuid::new_v4().to_string(), + page_url: Some("https://example.com/pricing?plan=pro".into()), + page_title: Some("Pricing".into()), + markdown: markdown.into(), + pin_count: 2, + detail: "extension".into(), + } + } + + #[test] + fn nothing_is_created_until_first_use() { + let root = TestRoot::new(); + let path = root.0.join("notes"); + let _store = NotesStore::new(path.clone()); + assert!(!path.exists()); + } + + #[test] + fn migrates_a_new_database_to_version_one() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + store.list(None, 10, 0).expect("list"); + let version: i64 = Connection::open(root.0.join("notes").join("notes.sqlite")) + .expect("open") + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .expect("version"); + assert_eq!(version, 1); + } + + #[test] + fn inserts_and_lists_newest_first() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let first = store + .insert(¬e("# One\n\n## 1. Button\n\nMake it bigger\n")) + .expect("first"); + let second = store + .insert(¬e("# Two\n\n## 1. Card\n\n_No comment_\n")) + .expect("second"); + let listed = store.list(None, 10, 0).expect("list"); + assert_eq!( + listed + .iter() + .map(|item| item.id.as_str()) + .collect::>(), + vec![second.id.as_str(), first.id.as_str()] + ); + assert_eq!(listed[1].first_comment.as_deref(), Some("Make it bigger")); + assert_eq!(listed[0].first_comment, None); + assert_eq!(store.list(None, 1, 1).expect("page").len(), 1); + } + + #[test] + fn inserting_the_same_id_twice_keeps_one_row() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let item = note("# Same\n"); + store.insert(&item).expect("first"); + store.insert(&item).expect("retry"); + assert_eq!(store.list(None, 10, 0).expect("list").len(), 1); + } + + #[test] + fn search_treats_percent_and_underscore_literally() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + store.insert(¬e("# 100% sure\n")).expect("percent"); + store.insert(¬e("# snake_case\n")).expect("underscore"); + store.insert(¬e("# plain text\n")).expect("plain"); + assert_eq!(store.list(Some("100%"), 10, 0).expect("percent").len(), 1); + assert_eq!( + store + .list(Some("snake_case"), 10, 0) + .expect("underscore") + .len(), + 1 + ); + assert_eq!(store.list(Some("%"), 10, 0).expect("only percent").len(), 1); + assert_eq!( + store.list(Some("_"), 10, 0).expect("only underscore").len(), + 1 + ); + assert_eq!( + store.list(Some("example.com"), 10, 0).expect("host").len(), + 3 + ); + } + + #[test] + fn search_is_not_injectable() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + store.insert(¬e("# plain\n")).expect("insert"); + assert!( + store + .list(Some("%' OR 1=1 --"), 10, 0) + .expect("search") + .is_empty() + ); + assert_eq!(store.list(Some(" "), 10, 0).expect("blank").len(), 1); + } + + #[test] + fn rejects_invalid_notes() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let mut bad_id = note("x"); + bad_id.id = "../escape".into(); + assert!(store.insert(&bad_id).is_err()); + let mut upper = note("x"); + upper.id = upper.id.to_uppercase(); + assert!(store.insert(&upper).is_err()); + assert!( + store + .insert(¬e(&"a".repeat(MAX_MARKDOWN_BYTES + 1))) + .is_err() + ); + let mut scheme = note("x"); + scheme.page_url = Some("javascript:alert(1)".into()); + assert!(store.insert(&scheme).is_err()); + let mut pins = note("x"); + pins.pin_count = 0; + assert!(store.insert(&pins).is_err()); + pins.pin_count = 100; + assert!(store.insert(&pins).is_err()); + let mut detail = note("x"); + detail.detail = "other".into(); + assert!(store.insert(&detail).is_err()); + let mut no_url = note("x"); + no_url.page_url = None; + assert!(store.insert(&no_url).is_ok()); + } + + #[test] + fn delete_removes_the_row_and_its_image() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let item = note("# Gone\n"); + fs::create_dir_all(store.images_directory()).expect("images"); + fs::write(store.image_path(&item.id), b"png").expect("image"); + let saved = store.insert(&item).expect("insert"); + assert!(saved.image_path.is_some()); + store.delete(&item.id).expect("delete"); + assert!(!store.image_path(&item.id).exists()); + assert!(store.markdown(&item.id).is_err()); + store.delete(&item.id).expect("deleting twice is harmless"); + } + + #[test] + fn cleanup_keeps_referenced_and_recent_images() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let kept = note("# Kept\n"); + let orphan = Uuid::new_v4().to_string(); + fs::create_dir_all(store.images_directory()).expect("images"); + fs::write(store.image_path(&kept.id), b"png").expect("kept image"); + fs::write(store.image_path(&orphan), b"png").expect("orphan image"); + fs::write(store.images_directory().join("not-a-note.png"), b"png").expect("stray"); + store.insert(&kept).expect("insert"); + + assert_eq!( + store + .cleanup_unsaved_images(Duration::from_secs(3600)) + .expect("recent"), + 0 + ); + assert_eq!( + store.cleanup_unsaved_images(Duration::ZERO).expect("all"), + 1 + ); + assert!(store.image_path(&kept.id).exists()); + assert!(!store.image_path(&orphan).exists()); + assert!(store.images_directory().join("not-a-note.png").exists()); + } + + #[test] + fn export_for_drag_writes_a_sanitised_markdown_file() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let item = note("# Export me\n"); + store.insert(&item).expect("insert"); + let path = store.export_for_drag(&item.id).expect("export"); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .expect("name"); + assert!(name.ends_with("-example-com.md"), "{name}"); + assert_eq!(fs::read_to_string(&path).expect("read"), "# Export me\n"); + assert_eq!(store.export_for_drag(&item.id).expect("again"), path); + } + + #[test] + fn an_unusable_root_fails_the_save_without_panicking() { + let root = TestRoot::new(); + let blocker = root.0.join("blocker"); + fs::write(&blocker, b"file").expect("file"); + let store = NotesStore::new(blocker); + assert!(store.insert(¬e("# x\n")).is_err()); + } + + fn delivery(mode: DeliveryMode) -> DeliverNoteRequest { + DeliverNoteRequest { + note_id: Uuid::new_v4().to_string(), + markdown: "# Note\n".into(), + page_url: None, + page_title: None, + pin_count: 1, + detail: "none".into(), + mode, + } + } + + #[test] + fn a_failed_copy_saves_nothing() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let result = deliver( + &store, + |_| Err(SnaphubError::Clipboard("busy".into())), + &delivery(DeliveryMode::CopyAndSave), + ); + assert!(!result.copied); + assert!(result.saved.is_none()); + assert!(result.diagnostic.expect("diagnostic").contains("busy")); + assert!(store.list(None, 10, 0).expect("list").is_empty()); + } + + #[test] + fn copy_succeeds_even_when_the_save_fails() { + let root = TestRoot::new(); + let blocker = root.0.join("blocker"); + fs::write(&blocker, b"file").expect("file"); + let store = NotesStore::new(blocker); + let result = deliver(&store, |_| Ok(()), &delivery(DeliveryMode::CopyAndSave)); + assert!(result.copied); + assert!(result.saved.is_none()); + assert!(result.diagnostic.is_some()); + } + + #[test] + fn modes_copy_and_save_only_what_they_name() { + let root = TestRoot::new(); + let store = NotesStore::new(root.0.join("notes")); + let copy_only = deliver(&store, |_| Ok(()), &delivery(DeliveryMode::Copy)); + assert!(copy_only.copied && copy_only.saved.is_none() && copy_only.diagnostic.is_none()); + let save_only = deliver( + &store, + |_| panic!("save must not touch the clipboard"), + &delivery(DeliveryMode::Save), + ); + assert!(!save_only.copied && save_only.saved.is_some()); + let both = deliver(&store, |_| Ok(()), &delivery(DeliveryMode::CopyAndSave)); + assert!(both.copied && both.saved.is_some()); + assert_eq!(store.list(None, 10, 0).expect("list").len(), 2); + } + + #[test] + fn host_and_slug_helpers() { + assert_eq!( + host_of("https://user:pw@Example.com:8080/a?b#c").as_deref(), + Some("Example.com") + ); + assert_eq!(host_of("no-scheme"), None); + assert_eq!(slug("My Site!.com"), "my-site-com"); + } +} diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 784f07f..159f463 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -19,6 +19,10 @@ const captureMocks = vi.hoisted(() => ({ requestCapture: vi.fn(), retryCaptureSave: vi.fn(), showCaptureSurface: vi.fn(), + deliverNote: vi.fn(), + inspectWebTarget: vi.fn(), + getBrowserLinkStatus: vi.fn(), + canvasProps: { current: null as null | Record void> }, })); vi.mock("./lib/tauri", async (importOriginal) => { @@ -43,6 +47,9 @@ vi.mock("./lib/tauri", async (importOriginal) => { requestCapture: captureMocks.requestCapture, retryCaptureSave: captureMocks.retryCaptureSave, showCaptureSurface: captureMocks.showCaptureSurface, + deliverNote: captureMocks.deliverNote, + inspectWebTarget: captureMocks.inspectWebTarget, + getBrowserLinkStatus: captureMocks.getBrowserLinkStatus, }; }); @@ -164,7 +171,8 @@ async function selectRegion(): Promise { } vi.mock("./components/AnnotationCanvas", () => ({ - AnnotationCanvas: function MockAnnotationCanvas(): React.JSX.Element { + AnnotationCanvas: function MockAnnotationCanvas(props: Record void>): React.JSX.Element { + captureMocks.canvasProps.current = props; return
; }, })); @@ -176,6 +184,7 @@ describe("App", () => { captureMocks.listeners.length = 0; captureMocks.cancelCapture.mockResolvedValue(undefined); captureMocks.cancelManualScrolling.mockResolvedValue(undefined); + captureMocks.getBrowserLinkStatus.mockResolvedValue({ enabled: false, state: "off", port: null, error: null, connected: [], paired: [] }); captureMocks.requestCapture.mockImplementation(() => Promise.resolve(createCaptureSession())); captureMocks.showCaptureSurface.mockResolvedValue(undefined); captureMocks.isTextRecognitionSupported.mockResolvedValue(false); @@ -745,3 +754,114 @@ describe("App overlay motion", () => { await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(false)); }); }); + +describe("App notes", () => { + function pin(id: string, value: number): { id: string; kind: "counter"; opacity: number; position: { x: number; y: number }; value: number; color: string; radius: number } { + return { id, kind: "counter", opacity: 1, position: { x: 20 * value, y: 30 }, value, color: "#d9ff43", radius: 12 }; + } + function place(id: string, value: number, area: { x: number; y: number; width: number; height: number } | null = null): void { + const props = captureMocks.canvasProps.current; + if (props === null) throw new Error("canvas not rendered"); + act(() => (props.onNotePlace as unknown as (p: unknown, a: unknown) => void)(pin(id, value), area)); + } + + beforeEach(() => { + vi.clearAllMocks(); + window.localStorage.clear(); + captureMocks.listeners.length = 0; + captureMocks.cancelCapture.mockResolvedValue(undefined); + captureMocks.requestCapture.mockImplementation(() => Promise.resolve(createCaptureSession())); + captureMocks.showCaptureSurface.mockResolvedValue(undefined); + captureMocks.isTextRecognitionSupported.mockResolvedValue(false); + captureMocks.getBrowserLinkStatus.mockResolvedValue({ enabled: true, state: "listening", port: 47811, error: null, connected: [], paired: [] }); + captureMocks.inspectWebTarget.mockResolvedValue(null); + captureMocks.completeCapture.mockImplementation((action: CompletionAction) => + Promise.resolve({ ...completedResult(action), outputPath: "C:/notes/shot.png" }), + ); + captureMocks.deliverNote.mockResolvedValue({ copied: true, saved: "C:/notes/x", diagnostic: null }); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + }); + + async function openWithNotes(): Promise { + render(); + await selectRegion(); + await waitFor(() => expect(captureMocks.getBrowserLinkStatus).toHaveBeenCalled()); + } + + it("keeps a comment typed on a pin and offers the note actions", async () => { + await openWithNotes(); + place("c1", 1); + const field = await screen.findByRole("textbox", { name: "Comment for this spot" }); + fireEvent.change(field, { target: { value: "Too tight" } }); + fireEvent.keyDown(field, { key: "Enter" }); + await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment for this spot" })).not.toBeInTheDocument()); + place("c2", 2, { x: 10, y: 10, width: 50, height: 50 }); + expect(await screen.findByText("element: Product workspace")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy note" })).toBeInTheDocument(); + }); + + it("renders the note image, then delivers the Markdown", async () => { + await openWithNotes(); + place("c1", 1); + const field = await screen.findByRole("textbox", { name: "Comment for this spot" }); + fireEvent.change(field, { target: { value: "Too tight" } }); + fireEvent.keyDown(field, { key: "Enter" }); + fireEvent.click(await screen.findByRole("button", { name: "Copy note" })); + await waitFor(() => expect(captureMocks.deliverNote).toHaveBeenCalledTimes(1)); + expect(captureMocks.completeCapture.mock.calls.at(-1)?.[0]).toBe("note-image"); + const request = captureMocks.deliverNote.mock.calls[0]?.[0] as { markdown: string; mode: string }; + expect(request.mode).toBe("copy"); + expect(request.markdown).toContain("Too tight"); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalled()); + }); + + it("stays open when the note cannot be copied", async () => { + captureMocks.deliverNote.mockResolvedValue({ copied: false, saved: null, diagnostic: "clipboard busy" }); + await openWithNotes(); + place("c1", 1); + fireEvent.keyDown(await screen.findByRole("textbox", { name: "Comment for this spot" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("button", { name: "Copy note" })); + expect((await screen.findAllByText(/Couldn.t copy the note. clipboard busy/)).length).toBeGreaterThan(0); + expect(captureMocks.cancelCapture).not.toHaveBeenCalled(); + }); + + it("offers Retry save when the note was copied but not saved", async () => { + captureMocks.deliverNote + .mockResolvedValueOnce({ copied: true, saved: null, diagnostic: "disk full" }) + .mockResolvedValueOnce({ copied: true, saved: "C:/notes/x", diagnostic: null }); + await openWithNotes(); + place("c1", 1); + fireEvent.keyDown(await screen.findByRole("textbox", { name: "Comment for this spot" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("button", { name: "Copy & save note" })); + fireEvent.click(await screen.findByRole("button", { name: "Retry save" })); + await waitFor(() => expect(captureMocks.deliverNote).toHaveBeenCalledTimes(2)); + const retry = captureMocks.deliverNote.mock.calls[1]?.[0] as { mode: string; noteId: string }; + const first = captureMocks.deliverNote.mock.calls[0]?.[0] as { noteId: string }; + expect(retry.mode).toBe("save"); + expect(retry.noteId).toBe(first.noteId); + expect(captureMocks.retryCaptureSave).not.toHaveBeenCalled(); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalled()); + }); + + it("applies lookups to the right note when they finish out of order", async () => { + const first = deferred(); + const second = deferred(); + captureMocks.inspectWebTarget.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise); + await openWithNotes(); + place("c1", 1); + fireEvent.keyDown(await screen.findByRole("textbox", { name: "Comment for this spot" }), { key: "Enter" }); + place("c2", 2); + await act(() => { second.resolve(null); first.resolve(null); return Promise.resolve(); }); + expect(await screen.findByText("element: Product workspace")).toBeInTheDocument(); + }); + + it("hides the note actions and tool when Developer tools is off", async () => { + captureMocks.getBrowserLinkStatus.mockResolvedValue({ enabled: false, state: "off", port: null, error: null, connected: [], paired: [] }); + await openWithNotes(); + expect(screen.queryByRole("button", { name: "Copy note" })).not.toBeInTheDocument(); + }); +}); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 89ab715..2846a39 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -11,18 +11,27 @@ import { RedactionReviewPanel, type RedactionReview, } from "./components/RedactionReviewPanel"; +import { NotePopover } from "./components/NotePopover"; import { SelectionFrame, type ResizeHandle } from "./components/SelectionFrame"; import { TargetHighlight } from "./components/TargetHighlight"; import { ScrollingCapturePanel, type ScrollingCaptureState, } from "./components/ScrollingCapturePanel"; +import { + buildCaptureNote, + noteSummary, + notesReducer, + type CaptureNote, + type NoteLookupStatus, +} from "./domain/notes"; import { defaultAnnotationStyle, initialSceneHistory, sceneHistoryReducer, type Annotation, type AnnotationStyle, + type CounterAnnotation, type ToolId, } from "./domain/annotations"; import type { @@ -58,7 +67,10 @@ import { detectTargets, dismissCapture, discardScrollingOutput, + deliverNote, describeInvokeError, + getBrowserLinkStatus, + inspectWebTarget, isTextRecognitionSupported, listTargets, listenForCaptureRequest, @@ -68,6 +80,7 @@ import { requestCapture, retryCaptureSave, showCaptureSurface, + type NoteDeliveryMode, } from "./lib/tauri"; type Interaction = @@ -105,6 +118,12 @@ export function App(): React.JSX.Element { const [activeTool, setActiveTool] = useState("select"); const [style, setStyle] = useState(defaultAnnotationStyle); const [history, dispatchScene] = useReducer(sceneHistoryReducer, initialSceneHistory); + const [notes, dispatchNotes] = useReducer(notesReducer, []); + const [editingNoteId, setEditingNoteId] = useState(null); + const [lookups, setLookups] = useState>>({}); + const [developerTools, setDeveloperTools] = useState(false); + const noteRetry = useRef<{ noteId: string; request: Parameters[0] } | null>(null); + const lastHoverTitle = useRef(null); const drawingOrigin = useRef<{ x: number; y: number } | null>(null); const [busy, setBusy] = useState(false); const [lastToolByGroup, setLastToolByGroup] = useState>>({}); @@ -224,6 +243,10 @@ export function App(): React.JSX.Element { setBusy(false); setCompletionState({ phase: "idle", message: "" }); dispatchScene({ type: "reset" }); + dispatchNotes({ type: "reset" }); + setEditingNoteId(null); + setLookups({}); + noteRetry.current = null; } const startSession = useCallback(async (): Promise => { @@ -260,7 +283,15 @@ export function App(): React.JSX.Element { strokeWidth: settingsRef.current.annotation.defaultSize, }); dispatchScene({ type: "reset" }); + dispatchNotes({ type: "reset" }); + setEditingNoteId(null); + setLookups({}); + noteRetry.current = null; }); + // Read once per session: the Note tool follows the Developer tools switch. + void getBrowserLinkStatus() + .then((status) => setDeveloperTools(status.enabled)) + .catch(() => setDeveloperTools(false)); setMessage("Hover to preview targets / drag to draw a rectangle / I copies a colour"); let readyTimeout: number | undefined; await Promise.race([ @@ -554,6 +585,59 @@ export function App(): React.JSX.Element { dispatchScene({ type: "add", annotation }); } + // A note lives only while its pin is in the scene, so undo removes it and redo restores it. + const activeNotes = useMemo(() => { + const counterIds = new Set( + history.present.elements.filter((element) => element.kind === "counter").map((element) => element.id), + ); + return notes.filter((note) => counterIds.has(note.counterId)); + }, [history.present.elements, notes]); + + useEffect(() => { + if (hoverTarget !== null) lastHoverTitle.current = hoverTarget.title; + }, [hoverTarget]); + + function placeNote(pin: CounterAnnotation, area: Rect | null): void { + if (session === null || selection === null) return; + const id = crypto.randomUUID(); + const sessionId = session.id; + const fallbackName = lastHoverTitle.current; + const fallback = fallbackName === null ? null : { role: "element", name: fallbackName }; + dispatchScene({ type: "add", annotation: pin }); + dispatchNotes({ + type: "add", + note: { id, counterId: pin.id, number: pin.value, anchor: pin.position, area, comment: "", detail: null, fallback }, + }); + setEditingNoteId(id); + setLookups((current) => ({ ...current, [id]: "pending" })); + const target = area === null + ? { point: { x: selection.x + pin.position.x, y: selection.y + pin.position.y } } + : { area: { x: selection.x + area.x, y: selection.y + area.y, width: area.width, height: area.height } }; + inspectWebTarget(target, session.display) + .then((detail) => { + if (activeSessionId.current !== sessionId) return; + dispatchNotes({ type: "lookup", id, detail, fallback: detail === null ? fallback : null }); + setLookups((current) => ({ + ...current, + [id]: detail === null ? { failed: "no browser extension answered" } : "done", + })); + }) + .catch((error: unknown) => { + if (activeSessionId.current !== sessionId) return; + dispatchNotes({ type: "lookup", id, detail: null, fallback }); + setLookups((current) => ({ + ...current, + [id]: { failed: describeInvokeError(error, "the lookup failed") }, + })); + }); + } + + function discardNote(note: CaptureNote): void { + dispatchScene({ type: "delete", annotationId: note.counterId }); + dispatchNotes({ type: "remove", id: note.id }); + setEditingNoteId(null); + } + async function runScrollingCapture( mode: "automatic" | "manual-start" | "manual-add", ): Promise { @@ -728,6 +812,83 @@ export function App(): React.JSX.Element { [busy, completionState.phase, history.present, scrollingCapture, selection, session], ); + const handleNoteComplete = useCallback( + async (mode: NoteDeliveryMode): Promise => { + if ( + session === null + || selection === null + || busy + || scrollingCapture !== null + || completionState.phase !== "idle" + || completionInFlight.current + || activeNotes.length === 0 + ) return; + const sessionId = session.id; + const generation = sessionGeneration.current; + const isStale = (): boolean => + activeSessionId.current !== sessionId || sessionGeneration.current !== generation; + const pendingMessage = mode === "copy" + ? "Copying note…" + : mode === "save" + ? "Saving note…" + : "Copying & saving note…"; + completionInFlight.current = true; + setEditingNoteId(null); + setCompletionState({ phase: "working", message: pendingMessage }); + setMessage(pendingMessage); + try { + const noteId = crypto.randomUUID(); + const image = await completeCapture("note-image", sessionId, selection, history.present, noteId); + if (isStale()) return; + if (image.outputPath === null) throw new Error("The note screenshot was not written"); + const built = buildCaptureNote(activeNotes, image.outputPath, new Date()); + const request = { + noteId, + markdown: built.markdown, + pageUrl: built.pageUrl, + pageTitle: built.pageTitle, + pinCount: built.pinCount, + detail: built.detail, + mode, + }; + const delivery = await deliverNote(request); + if (isStale()) return; + const diagnostic = delivery.diagnostic ?? "The native service did not return a diagnostic"; + const fail = (text: string): void => { + const failure = text + " " + diagnostic; + setCompletionState({ phase: "idle", message: failure }); + setMessage(failure); + }; + if (mode !== "save" && !delivery.copied) { + fail("Couldn't copy the note."); + return; + } + if (mode !== "copy" && delivery.saved === null) { + if (mode === "save") { + fail("Couldn't save the note."); + return; + } + noteRetry.current = { noteId, request }; + setCompletionState({ phase: "save-pending", diagnostic }); + setMessage("Note copied, but not saved. " + diagnostic); + return; + } + setMessage(mode === "copy" ? "Note copied" : mode === "save" ? "Note saved" : "Note copied and saved"); + await cancelCapture(sessionId, prefersReducedMotion()).catch(async () => dismissCapture()); + clearCaptureUi(); + } catch (error: unknown) { + if (!isStale()) { + const failure = "Could not complete the note. " + describeInvokeError(error, "The native service did not return a diagnostic"); + setCompletionState({ phase: "idle", message: failure }); + setMessage(failure); + } + } finally { + if (sessionGeneration.current === generation) completionInFlight.current = false; + } + }, + [activeNotes, busy, completionState.phase, history.present, scrollingCapture, selection, session], + ); + const handleCopyText = useCallback(async (): Promise => { if ( session === null @@ -873,6 +1034,25 @@ export function App(): React.JSX.Element { setCompletionState({ phase: "working", message: "Saving…" }); setMessage("Saving…"); try { + const noteRetryState = noteRetry.current; + if (noteRetryState !== null) { + const delivery = await deliverNote({ ...noteRetryState.request, mode: "save" }); + if ( + activeSessionId.current !== sessionId + || sessionGeneration.current !== generation + ) return; + if (delivery.saved === null) { + const diagnostic = delivery.diagnostic ?? "The native service did not return a diagnostic"; + setCompletionState({ phase: "save-pending", diagnostic }); + setMessage("Note copied, but not saved. " + diagnostic); + return; + } + noteRetry.current = null; + setMessage("Note copied and saved"); + await cancelCapture(sessionId, prefersReducedMotion()).catch(async () => dismissCapture()); + clearCaptureUi(); + return; + } const result = await retryCaptureSave(sessionId); if ( activeSessionId.current !== sessionId @@ -956,6 +1136,8 @@ export function App(): React.JSX.Element { // the capture phase before a focused control or WebView handler can consume // it, including while the user is still hovering before making a selection. if (event.key === "Escape") { + // The note popover owns Esc while it is open. + if (editingNoteId !== null) return; event.preventDefault(); event.stopPropagation(); if (scrollingCapture !== null) { @@ -1015,6 +1197,9 @@ export function App(): React.JSX.Element { ) { event.preventDefault(); void handleComplete("save"); + } else if (selectedCompletionReady && developerTools && hasNoModifiers && key === "N") { + event.preventDefault(); + setActiveTool("note"); } else if (selectedCompletionReady && event.key === "Enter") { event.preventDefault(); void handleComplete("copy"); @@ -1037,6 +1222,8 @@ export function App(): React.JSX.Element { }, [ busy, completionState.phase, + developerTools, + editingNoteId, requestExit, openGroupIndex, handleComplete, @@ -1078,17 +1265,32 @@ export function App(): React.JSX.Element { saveShortcut: settings.shortcuts.captureModeSave, disabled: completionState.phase !== "idle", canReadText, + hasNotes: developerTools && activeNotes.length > 0, onAction: (id: CompletionActionId): void => { - if (id === "showcase") void handleComplete("save", "showcase"); + if (id === "note-copy") void handleNoteComplete("copy"); + else if (id === "note-save") void handleNoteComplete("save"); + else if (id === "note-copy-and-save") void handleNoteComplete("copy-and-save"); + else if (id === "showcase") void handleComplete("save", "showcase"); else if (id === "copy-text") void handleCopyText(); else if (id === "find-sensitive") void findSensitiveText(); else void handleComplete(id); }, }; + // The Note tool needs Developer tools, so it is hidden from every toolbar layout without it. + const toolbar = developerTools + ? settings.toolbar + : { + ...settings.toolbar, + groups: settings.toolbar.groups + .map((group) => group.filter((toolId) => toolId !== "note")) + .filter((group) => group.length > 0), + individual: { ...settings.toolbar.individual, note: false }, + verticalTools: settings.toolbar.verticalTools.filter((toolId) => toolId !== "note"), + }; const horizontalActionItems = completionRailItems(settings.toolbar.actions, "horizontal", completionHandlers); const railToolItems: RailItem[] = settings.toolbar.mode === "individual" - ? settings.toolbar.verticalTools - .filter((toolId) => settings.toolbar.individual[toolId]) + ? toolbar.verticalTools + .filter((toolId) => toolbar.individual[toolId]) .map((toolId) => { const tool = getToolbarTool(toolId); return { @@ -1171,10 +1373,29 @@ export function App(): React.JSX.Element { scene={history.present} snapshotUrl={session.snapshotUrl} style={style} + noteColor={settings.accentColor} onCommit={handleAnnotation} + onNotePlace={placeNote} + onPinSelect={(annotationId) => { + const pinned = activeNotes.find((note) => note.counterId === annotationId); + if (pinned !== undefined) setEditingNoteId(pinned.id); + }} onDelete={(annotationId) => dispatchScene({ type: "delete", annotationId })} onUpdate={(annotation) => dispatchScene({ type: "update", annotation })} /> + {activeNotes.filter((note) => note.id === editingNoteId).map((note) => ( + dispatchNotes({ type: "comment", id: note.id, comment })} + onClose={() => setEditingNoteId(null)} + onDiscard={() => discardNote(note)} + /> + ))} {redactionReview === null ? null : } {completionState.phase === "idle" ? null : (
0} canUndo={history.past.length > 0} palette={settings.palette} - toolbar={settings.toolbar} + toolbar={toolbar} onRedo={() => dispatchScene({ type: "redo" })} onScrollCapture={startScrollingCapture} onStyleChange={setStyle} diff --git a/apps/desktop/src/components/AnnotationCanvas.tsx b/apps/desktop/src/components/AnnotationCanvas.tsx index b0effe5..36ec3fc 100644 --- a/apps/desktop/src/components/AnnotationCanvas.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.tsx @@ -4,6 +4,7 @@ import type { Annotation, AnnotationScene, AnnotationStyle, + CounterAnnotation, RegionAnnotation, ToolId, } from "../domain/annotations"; @@ -57,8 +58,17 @@ type AnnotationCanvasProps = { onCommit: (annotation: Annotation) => void; onUpdate: (annotation: Annotation) => void; onDelete: (annotationId: string) => void; + /** Pin colour for the Note tool (the accent colour). */ + noteColor?: string; + /** A note was placed: its pin, and the dragged area (null for a point note). */ + onNotePlace?: (pin: CounterAnnotation, area: CaptureRect | null) => void; + /** Select picked a counter pin; the app reopens its note when it has one. */ + onPinSelect?: (annotationId: string) => void; }; +/** A press that moves less than this (px) places a point note; further drags an area note. */ +const noteAreaThreshold = 6; + type Draft = { id: string; start: Point; end: Point; points: readonly Point[] }; export function AnnotationCanvas({ @@ -71,6 +81,9 @@ export function AnnotationCanvas({ onCommit, onUpdate, onDelete, + noteColor = "#d9ff43", + onNotePlace, + onPinSelect, }: AnnotationCanvasProps): React.JSX.Element { const containerRef = useRef(null); const [draft, setDraft] = useState(null); @@ -93,8 +106,20 @@ export function AnnotationCanvas({ const preview = useMemo(() => { if (draft === null) return null; + if (activeTool === "note") { + if (Math.hypot(draft.end.x - draft.start.x, draft.end.y - draft.start.y) < noteAreaThreshold) return null; + return { + id: draft.id, + kind: "rectangle", + bounds: normalizeRect(draft.start, draft.end), + color: noteColor, + fill: "transparent", + strokeWidth: 2, + opacity: 1, + }; + } return createAnnotation(activeTool, draft.start, draft.end, style, scene, draft.id, draft.points); - }, [activeTool, draft, scene, style]); + }, [activeTool, draft, noteColor, scene, style]); function relativePoint(event: React.PointerEvent): Point { const host = containerRef.current?.getBoundingClientRect(); @@ -123,6 +148,7 @@ export function AnnotationCanvas({ if (activeTool === "select") { const hit = findAnnotationAtPoint(scene.elements, point); setSelectedAnnotationId(hit?.id ?? null); + if (hit?.kind === "counter") onPinSelect?.(hit.id); // Leave empty-space presses available to SelectionFrame so the capture // region itself can still be moved while Select is active. if (hit === undefined) return; @@ -222,6 +248,31 @@ export function AnnotationCanvas({ const current = draftRef.current; if (current === null) return; clearDraftFrame(); + if (activeTool === "note") { + const end = relativePoint(event); + draftRef.current = null; + setDraft(null); + const isArea = Math.hypot(end.x - current.start.x, end.y - current.start.y) >= noteAreaThreshold; + const area = isArea ? normalizeRect(current.start, end) : null; + const anchor = area === null ? current.start : { x: area.x, y: area.y }; + const highest = scene.elements.reduce( + (value, element) => (element.kind === "counter" ? Math.max(value, element.value) : value), + 0, + ); + onNotePlace?.( + { + id: crypto.randomUUID(), + kind: "counter", + position: anchor, + value: highest + 1, + color: noteColor, + radius: Math.max(12, style.strokeWidth * 3), + opacity: 1, + }, + area, + ); + return; + } const annotation = createAnnotation( activeTool, current.start, @@ -733,6 +784,7 @@ function createAnnotation( radius: Math.max(12, style.strokeWidth * 3), opacity, }; + case "note": case "select": return null; } diff --git a/apps/desktop/src/components/CompletionToolbar.test.tsx b/apps/desktop/src/components/CompletionToolbar.test.tsx index 5188eae..4402403 100644 --- a/apps/desktop/src/components/CompletionToolbar.test.tsx +++ b/apps/desktop/src/components/CompletionToolbar.test.tsx @@ -23,6 +23,7 @@ function handlers(onAction: (id: CompletionActionId) => void, canReadText = fals saveShortcut: "S", disabled: false, canReadText, + hasNotes: false, onAction, }; } diff --git a/apps/desktop/src/components/NotePopover.test.tsx b/apps/desktop/src/components/NotePopover.test.tsx new file mode 100644 index 0000000..4ac68ad --- /dev/null +++ b/apps/desktop/src/components/NotePopover.test.tsx @@ -0,0 +1,88 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { NotePopover, notePopoverWidth, popoverPosition } from "./NotePopover"; + +function renderPopover(overrides: Partial> = {}): React.ComponentProps { + const props = { + number: 1, + anchor: { x: 40, y: 40 }, + container: { width: 800, height: 600 }, + comment: "", + summary: "Reading element…", + onChange: vi.fn(), + onClose: vi.fn(), + onDiscard: vi.fn(), + ...overrides, + }; + render(); + return props; +} + +afterEach(cleanup); + +describe("popoverPosition", () => { + it("sits right of and below the pin when it fits", () => { + expect(popoverPosition({ x: 40, y: 40 }, { width: 800, height: 600 })).toEqual({ left: 56, top: 56 }); + }); + + it("flips left and above near the far edges", () => { + const position = popoverPosition({ x: 780, y: 590 }, { width: 800, height: 600 }); + expect(position.left).toBeLessThan(780 - notePopoverWidth + 1); + expect(position.top).toBeLessThan(590); + }); + + it("never leaves a small selection", () => { + const position = popoverPosition({ x: 5, y: 5 }, { width: 200, height: 100 }); + expect(position).toEqual({ left: 0, top: 0 }); + }); +}); + +describe("NotePopover", () => { + it("focuses the comment field and shows the summary", () => { + renderPopover(); + expect(screen.getByRole("textbox", { name: "Comment for this spot" })).toHaveFocus(); + expect(screen.getByText("Reading element…")).toBeInTheDocument(); + }); + + it("reports typing", () => { + const props = renderPopover(); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "Too tight" } }); + expect(props.onChange).toHaveBeenCalledWith("Too tight"); + }); + + it("closes on Enter but keeps a newline for Shift+Enter", () => { + const props = renderPopover({ comment: "Hi" }); + const field = screen.getByRole("textbox"); + fireEvent.keyDown(field, { key: "Enter", shiftKey: true }); + expect(props.onClose).not.toHaveBeenCalled(); + fireEvent.keyDown(field, { key: "Enter" }); + expect(props.onClose).toHaveBeenCalledTimes(1); + }); + + it("discards an empty note on Esc and keeps a typed one", () => { + const empty = renderPopover({ comment: " " }); + fireEvent.keyDown(screen.getByRole("textbox"), { key: "Escape" }); + expect(empty.onDiscard).toHaveBeenCalledTimes(1); + expect(empty.onClose).not.toHaveBeenCalled(); + }); + + it("keeps a typed comment on Esc", () => { + const typed = renderPopover({ comment: "Keep me" }); + fireEvent.keyDown(screen.getByRole("textbox"), { key: "Escape" }); + expect(typed.onClose).toHaveBeenCalledTimes(1); + expect(typed.onDiscard).not.toHaveBeenCalled(); + }); + + it("closes on a click outside but not inside", () => { + const props = renderPopover(); + fireEvent.pointerDown(screen.getByRole("textbox")); + expect(props.onClose).not.toHaveBeenCalled(); + fireEvent.pointerDown(document.body); + expect(props.onClose).toHaveBeenCalledTimes(1); + }); + + it("limits the comment to 2000 characters", () => { + renderPopover(); + expect(screen.getByRole("textbox")).toHaveAttribute("maxlength", "2000"); + }); +}); diff --git a/apps/desktop/src/components/NotePopover.tsx b/apps/desktop/src/components/NotePopover.tsx new file mode 100644 index 0000000..7e0bf37 --- /dev/null +++ b/apps/desktop/src/components/NotePopover.tsx @@ -0,0 +1,119 @@ +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import type { Point } from "../domain/capture"; + +export const notePopoverWidth = 280; +const popoverHeight = 156; +const pinGap = 16; +const maxCommentLength = 2000; + +type NotePopoverProps = { + number: number; + /** The pin, in selection-local pixels. */ + anchor: Point; + /** The selection size; the popover flips to stay inside it. */ + container: { width: number; height: number }; + comment: string; + /** One line under the textarea, e.g. "Reading element…". */ + summary: string; + onChange: (comment: string) => void; + /** Enter or a click outside: keep the comment, even if empty. */ + onClose: () => void; + /** Esc on an empty comment: the new note is removed. */ + onDiscard: () => void; +}; + +/** Places the popover beside the pin, flipping when it would leave the selection. */ +export function popoverPosition( + anchor: Point, + container: { width: number; height: number }, +): { left: number; top: number } { + const fitsRight = anchor.x + pinGap + notePopoverWidth <= container.width; + const fitsBelow = anchor.y + pinGap + popoverHeight <= container.height; + const left = fitsRight ? anchor.x + pinGap : anchor.x - pinGap - notePopoverWidth; + const top = fitsBelow ? anchor.y + pinGap : anchor.y - pinGap - popoverHeight; + return { + left: Math.max(0, Math.min(left, container.width - notePopoverWidth)), + top: Math.max(0, Math.min(top, container.height - popoverHeight)), + }; +} + +export function NotePopover({ + number, + anchor, + container, + comment, + summary, + onChange, + onClose, + onDiscard, +}: NotePopoverProps): React.JSX.Element { + const rootRef = useRef(null); + const textareaRef = useRef(null); + const [entered, setEntered] = useState(false); + const position = popoverPosition(anchor, container); + + useLayoutEffect(() => { + textareaRef.current?.focus(); + const frame = window.requestAnimationFrame(() => setEntered(true)); + return (): void => window.cancelAnimationFrame(frame); + }, []); + + useEffect(() => { + function onPointerDown(event: PointerEvent): void { + if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return; + onClose(); + } + document.addEventListener("pointerdown", onPointerDown, true); + return (): void => document.removeEventListener("pointerdown", onPointerDown, true); + }, [onClose]); + + function onKeyDown(event: React.KeyboardEvent): void { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + if (comment.trim() === "") onDiscard(); + else onClose(); + return; + } + if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { + event.preventDefault(); + event.stopPropagation(); + onClose(); + } + } + + return ( +
event.stopPropagation()} + > + +