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/.gitignore b/.gitignore index 2068474..3dc4696 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,7 @@ docs/* !docs/specs/ docs/specs/* !docs/specs/capture-copy-and-save.md -scripts +/scripts .gitignore CHANGELOG.md AGENTS.md diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index b813b51..a1570c4 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,20 +2,39 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. -## Unreleased — 2026-11-19 +## 0.4.0 — 2026-11-20 ### Added -- 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. +- The CapKit Inspector extension now uses the accent colour you chose in CapKit. +- Developer tools (off by default): link the CapKit Inspector browser extension to see exact page elements, find sensitive text precisely, and pin numbered notes on a page. Notes copy as Markdown with a screenshot and are kept in a new Notes tab. +- 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. Install 0.4.0 by hand once; later versions arrive through the app. - 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 +- Press 1–9 and 0 to pick a tool in the capture toolbar, and V for Select. Each button shows its number in the corner, like C, S and A. +- Copy, Save and Copy & Save (C, S, A) now deliver your note when the capture has pins, so the separate note buttons are gone. +- Click a note pin with the Select tool to edit its comment, and drag the pin to move its comment with it. - 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 `\\?\`. +- 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 + +- The CapKit Inspector extension reconnects by itself after CapKit restarts, instead of staying disconnected until you open its popup. +- The show/hide switches in Settings → Screenshots (tools and finishing actions) respond to clicks again. +- Saved notes show their screenshot again in the Notes tab. +- Click a saved note to read all of it: the full screenshot and every pin's comment and details. +- Detection works again when a tiling window manager such as FancyWM is running. Before, it found nothing in tiled windows. +- Screenshots in Aside now highlight exact page elements when the CapKit Inspector extension is linked. +- 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/PRIVACY.md b/PRIVACY.md index 41e76dd..4b17fa8 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -31,6 +31,9 @@ Copy actions write the resulting image to the Windows clipboard. User-initiated Core screenshot capture, editing, drawing, recording and export run locally and do not require a CapKit cloud account. This release does not include a built-in capture-upload service, application analytics, or automatic remote diagnostic uploads in the inspected production application. Microsoft Edge WebView2 and Windows are external components with their own update, diagnostic and privacy settings. Files saved in a folder managed by OneDrive or another synchronization service may be synchronized by that service. Those services operate under their own terms and controls. +## Developer tools and the browser extension +Developer tools is off by default. When you turn it on, CapKit listens on 127.0.0.1 only (your own computer) and accepts connections only from a browser extension you paired with a one-time code. The CapKit Inspector extension reads page content only when CapKit asks for it or when you use its inspector, keeps everything on your device, and opens no network access beyond 127.0.0.1. Notes you create are stored in a local database in CapKit's data folder, and you can delete them from the Notes tab. Turning the switch off closes the listener. + ## Your choices and deletion Choose capture and recording folders in Settings, disable optional recording inputs, and stop capture or recording when you no longer need it. Close CapKit before manually removing its local data. Delete unwanted screenshots, recording folders and temporary CapKit files through File Explorer. Removing a recording from CapKit's library currently removes its library entry, not necessarily the underlying recording files; delete those files separately if required. Clearing local application/WebView storage removes saved preferences and editing metadata but does not by itself delete exported media. Uninstalling should not be relied on to remove every output, temporary file or setting. Editing or redacting an export does not guarantee that original or temporary sources have been securely erased. diff --git a/README.md b/README.md index 92aebf8..3d8af2b 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,12 @@ The selected area becomes the editor. Tools appear right beside it. - Turn a plain screenshot into something worth posting: backgrounds, gradients and wallpapers; padding, rounded corners and shadows; browser and device frames; tilt and perspective; titles and notes. - Save your favourite looks as presets. +### Developer tools (Provisional, off by default) + +- Turn on **Settings → Developer → Developer tools** to link the CapKit Inspector browser extension. Hovering a web page then highlights exact page elements, Find sensitive text marks exact rects, and the Note tool pins numbered comments with element details and a Markdown handoff for AI. +- Load the extension: in Chrome or Aside open chrome://extensions, turn on Developer mode, choose Load unpacked, and select `apps/browser-extension/dist` (build it with `pnpm ext:build`). Then click **Pair a browser** in Settings and enter the 6-digit code in the extension popup. +- Notes are listed in the **Notes** tab, where you can copy or drag them out. + ### Private by design - Everything stays on your device. No account, sign-in, telemetry or network access is needed to capture, edit, record or export. 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 0000000..549fbd9 Binary files /dev/null and b/apps/browser-extension/public/icons/128.png differ diff --git a/apps/browser-extension/public/icons/16.png b/apps/browser-extension/public/icons/16.png new file mode 100644 index 0000000..2551d35 Binary files /dev/null and b/apps/browser-extension/public/icons/16.png differ diff --git a/apps/browser-extension/public/icons/48.png b/apps/browser-extension/public/icons/48.png new file mode 100644 index 0000000..b1d25c7 Binary files /dev/null and b/apps/browser-extension/public/icons/48.png differ diff --git a/apps/browser-extension/public/manifest.json b/apps/browser-extension/public/manifest.json new file mode 100644 index 0000000..9990800 --- /dev/null +++ b/apps/browser-extension/public/manifest.json @@ -0,0 +1,20 @@ +{ + "manifest_version": 3, + "name": "CapKit Inspector", + "version": "0.3.0", + "description": "Inspect spacing, styles and source locations on any page, and give CapKit exact element data.", + "minimum_chrome_version": "116", + "icons": { "16": "icons/16.png", "48": "icons/48.png", "128": "icons/128.png" }, + "action": { "default_popup": "popup/index.html", "default_title": "CapKit Inspector" }, + "background": { "service_worker": "background.js" }, + "permissions": ["activeTab", "alarms", "scripting", "storage", "clipboardWrite"], + "host_permissions": ["http://localhost/*", "http://127.0.0.1/*"], + "optional_host_permissions": [""], + "commands": { + "toggle-inspector": { + "suggested_key": { "default": "Alt+Shift+I" }, + "description": "Inspect the page" + } + }, + "web_accessible_resources": [{ "resources": ["fonts/*"], "matches": [""], "use_dynamic_url": true }] +} diff --git a/apps/browser-extension/scripts/build.mjs b/apps/browser-extension/scripts/build.mjs new file mode 100644 index 0000000..f0a9477 --- /dev/null +++ b/apps/browser-extension/scripts/build.mjs @@ -0,0 +1,62 @@ +// Builds the extension: three single-file IIFE scripts plus the React popup. +import { build } from "vite"; +import react from "@vitejs/plugin-react"; +import tailwind from "@tailwindcss/vite"; +import { cp, mkdir, readFile, writeFile, readdir } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRequire } from "node:module"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = resolve(root, "dist"); +const watch = process.argv.includes("--watch"); +const require = createRequire(import.meta.url); + +const scripts = [ + { name: "background", entry: "src/background.ts", file: "background.js" }, + { name: "capkitIsolated", entry: "src/content/isolated.ts", file: "content/isolated.js" }, + { name: "capkitMainWorld", entry: "src/content/main-world.ts", file: "content/main-world.js" }, +]; + +let first = true; +for (const script of scripts) { + await build({ + root, + configFile: false, + logLevel: "warn", + publicDir: first ? resolve(root, "public") : false, + build: { + outDir: dist, + emptyOutDir: first, + watch: watch ? {} : null, + minify: true, + sourcemap: false, + lib: { entry: resolve(root, script.entry), name: script.name, formats: ["iife"], fileName: () => script.file }, + }, + }); + first = false; +} + +await build({ + root: resolve(root, "src/popup"), + base: "./", + configFile: false, + logLevel: "warn", + plugins: [react(), tailwind()], + build: { outDir: resolve(dist, "popup"), emptyOutDir: true, watch: watch ? {} : null }, +}); + +await mkdir(resolve(dist, "fonts"), { recursive: true }); +for (const pkg of ["plus-jakarta-sans", "jetbrains-mono"]) { + const dir = resolve(dirname(require.resolve(`@fontsource-variable/${pkg}/package.json`)), "files"); + for (const file of await readdir(dir)) { + if (file.endsWith("-latin-wght-normal.woff2")) await cp(resolve(dir, file), resolve(dist, "fonts", file)); + } +} + +const rootVersion = JSON.parse(await readFile(resolve(root, "../../package.json"), "utf8")).version; +const manifestPath = resolve(dist, "manifest.json"); +const manifest = JSON.parse(await readFile(manifestPath, "utf8")); +manifest.version = rootVersion; +await writeFile(manifestPath, JSON.stringify(manifest, null, 2)); +console.log(`CapKit Inspector ${rootVersion} built to ${dist}`); diff --git a/apps/browser-extension/src/accent.ts b/apps/browser-extension/src/accent.ts new file mode 100644 index 0000000..4abcca1 --- /dev/null +++ b/apps/browser-extension/src/accent.ts @@ -0,0 +1,15 @@ +import { accentSchema } from "@snaphub/devtools-protocol/protocol"; + +/** Storage key for CapKit's accent colour; the lime default applies until CapKit sends one. */ +export const ACCENT_KEY = "capkitAccent"; +export const DEFAULT_ACCENT = "#d9ff43"; + +/** The stored accent, or the default when none is stored or the value is invalid. */ +export async function readAccent(): Promise { + try { + const parsed = accentSchema.safeParse((await chrome.storage.local.get(ACCENT_KEY))[ACCENT_KEY]); + return parsed.success ? parsed.data : DEFAULT_ACCENT; + } catch { + return DEFAULT_ACCENT; + } +} diff --git a/apps/browser-extension/src/background.ts b/apps/browser-extension/src/background.ts new file mode 100644 index 0000000..310b539 --- /dev/null +++ b/apps/browser-extension/src/background.ts @@ -0,0 +1,177 @@ +import { PROTOCOL_VERSION, type AppMessage, type ExtensionMessage } from "@snaphub/devtools-protocol/protocol"; +import { ACCENT_KEY } from "./accent"; +import { Link, WAKE_ALARM_MINUTES, wakeAlarmFor, 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 WAKE_ALARM = "capkit-reconnect"; +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; + } + + // Try even without a stored site permission: a tab the user opened the extension on has + // temporary access. If injection fails, CapKit falls back to Windows accessibility. + const result = await askTab(tab, request, { requireSiteAccess: false }); + 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, + onStatus: (status): void => { + const action = wakeAlarmFor(status); + if (action === "schedule") void chrome.alarms.create(WAKE_ALARM, { periodInMinutes: WAKE_ALARM_MINUTES }); + if (action === "cancel") void chrome.alarms.clear(WAKE_ALARM); + }, + onAccent: (accent): void => { + void chrome.storage.local.set({ [ACCENT_KEY]: accent }); + }, +}); + +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 ?? "" }; +} + +/** Opening the popup or pressing the shortcut grants activeTab, so the inspector needs no site access. */ +async function inspectActiveTab(): Promise { + const tab = await currentTab(); + if (tab === null || originPattern(tab.url) === null) return false; + const result = await askTab(tab, { kind: "toggle" }, { requireSiteAccess: false }); + 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()); + } +} + +chrome.runtime.onMessage.addListener((message: unknown, sender, sendResponse) => { + // Always answer, even on failure; otherwise the caller sees "message channel closed". + dispatch(message, sender).then(sendResponse, () => { + sendResponse({ ok: false }); + }); + return true; +}); + +chrome.commands.onCommand.addListener((command) => { + if (command === "toggle-inspector") void inspectActiveTab(); +}); + +// A fresh worker already connects at the bottom of this file; the alarm only nudges a live one. +chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name === WAKE_ALARM && link.status.state === "unreachable") link.retry(); +}); +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..9200b6e --- /dev/null +++ b/apps/browser-extension/src/content/inspector/controller.ts @@ -0,0 +1,337 @@ +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 { readAccent } from "../../accent"; +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" }); + const root = this.root; + void readAccent().then((accent) => { + root.style.setProperty("--accent", accent); + }); + 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..0b17e28 --- /dev/null +++ b/apps/browser-extension/src/content/inspector/styles.ts @@ -0,0 +1,50 @@ +/** Stylesheet for the closed shadow root. No gradients, no transition: all, reduced motion keeps opacity only. */ +export const INSPECTOR_CSS = ` +:host { all: initial; } +.root { --accent: #d9ff43; } +*, *::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 var(--accent); 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: color-mix(in srgb, var(--accent) 25%, transparent); } +.band.padding { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--accent) 35%, transparent) 0 2px, transparent 2px 6px); } +.chip { position: fixed; padding: 2px 6px; border-radius: 4px; background: #1b1c1a; color: var(--accent); border: 1px solid rgb(255 255 255 / 9%); white-space: nowrap; font-size: 11px; pointer-events: none; } +.line { position: fixed; background: var(--accent); pointer-events: none; } +.line.h { height: 1px; } +.line.v { width: 1px; } +.cap { position: fixed; background: var(--accent); pointer-events: none; } +.pill { position: fixed; padding: 1px 5px; border-radius: 3px; background: #1b1c1a; color: var(--accent); 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: var(--accent); background: none; } +:focus-visible { outline: 2px solid var(--accent); 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: var(--accent); 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..b6d8a5d --- /dev/null +++ b/apps/browser-extension/src/content/mainClient.ts @@ -0,0 +1,93 @@ +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; + } + })(); + const pending = mainReady; + // A failed injection is retried on the next request instead of being remembered for the page. + void pending.then((channel) => { + if (channel === null && mainReady === pending) mainReady = null; + }); + return pending; +} + +/** 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..3c81a80 --- /dev/null +++ b/apps/browser-extension/src/link.test.ts @@ -0,0 +1,211 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BACKOFF_MS, Link, PING_INTERVAL_MS, wakeAlarmFor, 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, onAccent?: (accent: string) => void): { link: Link; store: ReturnType } { + const store = memoryStore(token); + const link = new Link({ + ...(onAccent === undefined ? {} : { onAccent }), + 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("passes CapKit's accent on from ready and from later theme messages", async () => { + const accents: string[] = []; + const { link } = make(TOKEN, (accent) => accents.push(accent)); + await link.connect(); + last().open(); + last().receive({ type: "ready", accent: "#39ff88" }); + last().receive({ type: "theme", accent: "#7c5cff" }); + last().receive({ type: "theme", accent: "nope" }); + expect(accents).toEqual(["#39ff88", "#7c5cff"]); + expect(link.status.state).toBe("connected"); + }); + + 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).toBe("That code didn't match"); + }); + + it("asks for a new code after too many wrong ones, with no time lockout", () => { + const { link } = make(null); + link.pair("123456"); + last().open(); + last().receive({ type: "pairRejected", reason: "too-many-attempts" }); + expect(link.status.reason).toBe("Too many wrong codes. Generate a new code in CapKit."); + }); + + 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"); + }); +}); + +describe("wakeAlarmFor", () => { + it("schedules a wake-up only while CapKit is unreachable", () => { + expect(wakeAlarmFor({ state: "unreachable" })).toBe("schedule"); + expect(wakeAlarmFor({ state: "connecting" })).toBe("keep"); + expect(wakeAlarmFor({ state: "connected" })).toBe("cancel"); + expect(wakeAlarmFor({ state: "no-token" })).toBe("cancel"); + expect(wakeAlarmFor({ state: "rejected", reason: "Pair again." })).toBe("cancel"); + }); +}); diff --git a/apps/browser-extension/src/link.ts b/apps/browser-extension/src/link.ts new file mode 100644 index 0000000..004960f --- /dev/null +++ b/apps/browser-extension/src/link.ts @@ -0,0 +1,242 @@ +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, 5_000, 10_000, 30_000] as const; +/** Chrome's minimum alarm period (Chrome 120+; older builds round up to one minute). */ +export const WAKE_ALARM_MINUTES = 0.5; + +/** + * What the background worker's wake-up alarm should do for a link state. + * Chrome suspends an idle MV3 worker after about 30 seconds and drops its timers with it, + * so the backoff `setTimeout` alone can't outlive a CapKit restart. While CapKit is + * unreachable an alarm wakes the worker to try again; once connected, or when only the + * user can move things on (no token, rejected), it is cleared. + */ +export function wakeAlarmFor(status: LinkStatus): "schedule" | "cancel" | "keep" { + switch (status.state) { + case "unreachable": + return "schedule"; + case "connecting": + return "keep"; + default: + return "cancel"; + } +} + +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; + /** CapKit's accent colour, sent on connect and whenever it changes there. */ + onAccent?: (accent: string) => void; +}; + +const REJECT_TEXT: Record = { + "wrong-code": "That code didn't match", + expired: "That code expired. Open Developer tools in CapKit for a new one.", + "too-many-attempts": "Too many wrong codes. Generate a new code in CapKit.", + "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": + if (message.accent !== undefined) this.options.onAccent?.(message.accent); + 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 "theme": + this.options.onAccent?.(message.accent); + 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..22770a0 --- /dev/null +++ b/apps/browser-extension/src/messages.ts @@ -0,0 +1,67 @@ +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() }), +]); +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..05ecc63 --- /dev/null +++ b/apps/browser-extension/src/popup/Popup.test.tsx @@ -0,0 +1,149 @@ +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"; + +const grant = (): Promise => Promise.resolve(true); + +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("shows the wrong-code and too-many-attempts copy", async () => { + const first = fake({ retry: { state: "rejected", reason: "That code didn't match" } }); + const { unmount } = render(); + expect(await screen.findByRole("alert")).toHaveTextContent("That code didn't match"); + unmount(); + const second = fake({ retry: { state: "rejected", reason: "Too many wrong codes. Generate a new code in CapKit." } }); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Too many wrong codes. Generate a new code in CapKit."); + }); + + it("asks Chrome for site access from the popup click, then rereads access", async () => { + const { send, calls } = fake({ + retry: { state: "connected" }, + siteAccess: { state: "needs-access", origin: "https://example.com/*" }, + }); + const requestPermission = vi.fn((): Promise => Promise.resolve(true)); + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Allow on this site" })); + expect(requestPermission).toHaveBeenCalledWith(["https://example.com/*"]); + await waitFor(() => { + expect(calls.filter((call) => call.kind === "siteAccess").length).toBeGreaterThanOrEqual(2); + }); + expect(screen.getByRole("button", { name: "Allow on all sites" })).toBeInTheDocument(); + }); + + it("says when the page can't be inspected and disables Inspect page", async () => { + const { send } = fake({ retry: { state: "connected" }, siteAccess: { state: "unavailable" } }); + render(); + expect(await screen.findByText("Not available on this page")).toBeInTheDocument(); + expect(screen.getByText("Inspect works on web pages (http and https) only.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Inspect page" })).toBeDisabled(); + }); + + it("keeps the popup open with a message when the inspector can't start", async () => { + const close = vi.spyOn(window, "close").mockImplementation(() => undefined); + const { send } = fake({ retry: { state: "connected" }, siteAccess: { state: "allowed" }, inspectActiveTab: { ok: false } }); + const user = userEvent.setup(); + render(); + await screen.findByText("Connected to CapKit"); + await waitFor(() => { + expect(screen.getByRole("button", { name: "Inspect page" })).toBeEnabled(); + }); + await user.click(screen.getByRole("button", { name: "Inspect page" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't start the inspector here."); + expect(close).not.toHaveBeenCalled(); + close.mockRestore(); + }); + + it("offers Inspect page without CapKit (standalone)", async () => { + const { send } = fake({ retry: { state: "unreachable" }, siteAccess: { state: "needs-access", origin: "https://example.com/*" } }); + render(); + expect(await screen.findByRole("button", { name: "Inspect page" })).toBeEnabled(); + }); + + 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 screen.findByText("Connected to CapKit"); + await waitFor(() => { + expect(screen.getByRole("button", { name: "Inspect page" })).toBeEnabled(); + }); + await user.click(screen.getByRole("button", { name: "Inspect page" })); + expect(calls).toContainEqual({ kind: "inspectActiveTab" }); + await waitFor(() => { + expect(close).toHaveBeenCalled(); + }); + 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..888b9fb --- /dev/null +++ b/apps/browser-extension/src/popup/Popup.tsx @@ -0,0 +1,230 @@ +import { useCallback, useEffect, useState, type ClipboardEvent, type SyntheticEvent, type ReactElement } from "react"; +import { z } from "zod"; +import { linkStatusSchema, siteAccessSchema, type BackgroundRequest, type LinkStatus, type SiteAccess } from "../messages"; + +export type Transport = (request: BackgroundRequest) => Promise; +export type RequestPermission = (origins: string[]) => 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 ( + + ); +} + +const inspectResultSchema = z.object({ ok: z.boolean() }); + +export function Popup({ send, requestPermission }: { send: Transport; requestPermission: RequestPermission }): ReactElement { + const [status, setStatus] = useState({ state: "connecting" }); + const [access, setAccess] = useState(null); + const [code, setCode] = useState(""); + const [showSpinner, setShowSpinner] = useState(false); + const [inspectError, setInspectError] = useState(null); + + const refreshAccess = useCallback(async (): Promise => { + const parsed = siteAccessSchema.safeParse(await send({ kind: "siteAccess" })); + setAccess(parsed.success ? parsed.data : { state: "unavailable" }); + }, [send]); + + 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(() => { + void refreshAccess(); + }, [refreshAccess]); + + 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 }); + }; + + // Called synchronously from the click so Chrome sees the user gesture. + const requestAccess = (all: boolean): void => { + const origins = all ? [""] : access?.origin === undefined ? [] : [access.origin]; + if (origins.length === 0) return; + void requestPermission(origins) + .catch(() => false) + .then(refreshAccess); + }; + + const inspect = (): void => { + setInspectError(null); + void send({ kind: "inspectActiveTab" }).then((raw) => { + const parsed = inspectResultSchema.safeParse(raw); + if (parsed.success && parsed.data.ok) { + window.close(); + return; + } + setInspectError("Couldn't start the inspector here. Reload the page and try again."); + }); + }; + + const canInspect = access !== null && access.state !== "unavailable"; + + const inspectBlock = ( +
+ + {access?.state === "unavailable" ? ( +

Inspect works on web pages (http and https) only.

+ ) : null} + {inspectError === null ? null : ( +

+ {inspectError} +

+ )} +
+ ); + + 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 === "connected" ? null : inspectBlock} + + {status.state === "unreachable" ? ( +
+

CapKit isn't running or Developer tools is off.

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

+

+ {inspectBlock} +
+ 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..43bf73c --- /dev/null +++ b/apps/browser-extension/src/popup/main.tsx @@ -0,0 +1,33 @@ +import { StrictMode, type ReactElement } from "react"; +import { createRoot } from "react-dom/client"; +import { Popup, type RequestPermission, type Transport } from "./Popup"; +import "./popup.css"; +import { readAccent } from "../accent"; + +const transport: Transport = (request) => chrome.runtime.sendMessage(request); +// Must run inside the click handler: Chrome only shows the prompt during a user gesture. +const requestPermission: RequestPermission = (origins) => chrome.permissions.request({ origins }); + +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(); +void readAccent().then((accent) => { + document.documentElement.style.setProperty("--color-accent", accent); +}); +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..084761c --- /dev/null +++ b/apps/browser-extension/src/tabs.ts @@ -0,0 +1,98 @@ +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, + options: { requireSiteAccess: boolean } = { requireSiteAccess: true }, +): Promise { + if (options.requireSiteAccess && !(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..38fa9ee 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@snaphub/desktop", - "version": "0.3.0", + "version": "0.4.0", "private": true, "type": "module", "scripts": { @@ -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-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index ff87fb4..4256306 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" @@ -607,7 +616,7 @@ dependencies = [ [[package]] name = "capkit-desktop" -version = "0.3.0" +version = "0.4.0" dependencies = [ "ab_glyph", "arboard", @@ -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..717fa14 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "capkit-desktop" -version = "0.3.0" +version = "0.4.0" description = "CapKit lightweight desktop toolkit to capture, record, and showcase" authors = ["CapKit"] edition = "2024" @@ -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/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 9d848a9..c65be73 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -26,6 +26,10 @@ pub enum SnaphubError { Startup(String), #[error("SH-UPDATE-001: {0}")] 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 76aea8d..eca8cdc 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -23,7 +23,12 @@ 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::notes::{DeliverNoteRequest, DeliveryDto, NoteSummaryDto, NotesStore}; use services::recording::RecordingService; use services::scrolling::stitch_vertical; use services::updates::{ @@ -50,15 +55,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 +190,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()))?; @@ -414,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!( @@ -540,11 +534,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); @@ -636,6 +629,78 @@ 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_set_accent(link: tauri::State<'_, BrowserLinkService>, accent: String) { + link.set_accent(&accent); +} + +#[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 @@ -754,6 +819,155 @@ 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)?; + services::notes::require_developer_tools(app.state::().status().enabled)?; + 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> { + services::notes::require_developer_tools(app.state::().status().enabled)?; + 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> { + services::notes::require_developer_tools(app.state::().status().enabled)?; + 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()))? +} + +/// The note's full Markdown (every pin and its element details), for reading it in the Notes tab. +#[tauri::command] +async fn notes_read(app: AppHandle, id: String) -> Result { + services::notes::require_developer_tools(app.state::().status().enabled)?; + tauri::async_runtime::spawn_blocking(move || app.state::().markdown(&id)) + .await + .map_err(|error| SnaphubError::Notes(error.to_string()))? +} + +#[tauri::command] +async fn notes_delete(app: AppHandle, id: String) -> Result<(), SnaphubError> { + services::notes::require_developer_tools(app.state::().status().enabled)?; + 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 { + services::notes::require_developer_tools(app.state::().status().enabled)?; + 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( + link: tauri::State<'_, BrowserLinkService>, + store: tauri::State<'_, NotesStore>, + id: String, +) -> Result<(), SnaphubError> { + services::notes::require_developer_tools(link.status().enabled)?; + 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, + link: tauri::State<'_, BrowserLinkService>, + store: tauri::State<'_, NotesStore>, + service: tauri::State<'_, CaptureService>, + id: String, +) -> Result<(), SnaphubError> { + services::notes::require_developer_tools(link.status().enabled)?; + 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 @@ -928,6 +1142,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)? @@ -2686,6 +2905,14 @@ 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_set_accent, + browser_link_forget, + inspect_web_target, + find_sensitive_web, list_targets, get_save_directory, set_save_directory, @@ -2696,6 +2923,14 @@ pub fn run() { delete_saved_capture, copy_saved_capture, start_saved_capture_drag, + deliver_note, + notes_list, + notes_copy, + notes_read, + notes_delete, + notes_cleanup_unsaved, + notes_open_url, + notes_start_drag, import_media_files, list_folder_images, scrolling_capture_supported, @@ -2742,6 +2977,21 @@ 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); + + // 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/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 0c5bdbb..ecbcf45 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, @@ -18,11 +19,13 @@ use windows::Win32::{ }; use crate::{ - domain::{DetectedTargetDto, Rect}, + domain::{DetectedTargetDto, Point, Rect}, error::SnaphubError, }; 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 @@ -31,15 +34,45 @@ 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. +// 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 = 2; -const BROWSER_SCAN_RETRY_DELAY: Duration = Duration::from_millis(180); +// Upper bound on browser UI elements visited while looking for the page's Document element. +const MAX_DOCUMENT_SEARCH_ELEMENTS: usize = 400; +// How long the page rectangles found by that search are reused while the window doesn't move. +const DOCUMENT_CACHE_TTL: Duration = Duration::from_secs(2); +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 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 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; + 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 +82,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 +93,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, @@ -86,6 +119,32 @@ fn window_class_name(window_id: u32) -> String { String::from_utf16_lossy(&buffer[..length as usize]) } +/// Whether `window_id` is an invisible overlay the cursor passes through, such as the +/// full-screen overlays a tiling window manager (FancyWM, for example) keeps above the +/// windows it tiles. Such a window is never what the user is pointing at, so target +/// detection must look at the window beneath it. +pub fn is_pass_through_overlay(window_id: u32) -> bool { + use windows::Win32::UI::WindowsAndMessaging::{GWL_EXSTYLE, GetWindowLongPtrW}; + + let hwnd = HWND(window_id as usize as *mut c_void); + // The extended style is a 32-bit flag set stored in a pointer-sized slot; truncating is exact. + let ex_style = unsafe { GetWindowLongPtrW(hwnd, GWL_EXSTYLE) } as u32; + is_pass_through_ex_style(ex_style) +} + +/// See [`is_pass_through_overlay`]. A window is pass-through when mouse input goes to the +/// window below it (`WS_EX_TRANSPARENT`), or when it is a layered tool window that can never +/// be activated: a drawing surface, not something a user works in. +fn is_pass_through_ex_style(ex_style: u32) -> bool { + use windows::Win32::UI::WindowsAndMessaging::{ + WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, + }; + + let has = |flag: u32| ex_style & flag == flag; + has(WS_EX_TRANSPARENT.0) + || (has(WS_EX_LAYERED.0) && has(WS_EX_NOACTIVATE.0) && has(WS_EX_TOOLWINDOW.0)) +} + fn is_browser_window(window_id: u32) -> bool { let class_name = window_class_name(window_id); BROWSER_WINDOW_CLASSES @@ -93,7 +152,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 +190,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 +199,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 +295,290 @@ 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) - }); +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)), + } +} - let mut deduped: Vec = Vec::with_capacity(regions.len()); - for region in regions { - let is_duplicate = 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, + }) +} + +/// 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::{ + 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) }; + 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), + ); + } + pages +} + +/// Where the web page is on screen (physical pixels) inside `window_id` at `point`. +/// +/// Chrome hosts each page in its own child window, so that window's rectangle is the page. +/// Some Chromium browsers (Aside, for example) draw the page into one shared surface with no +/// page window; there the page's UI Automation Document element gives the rectangle instead. +/// `None` when the window shows no web page there. +pub fn web_viewport_rect(window_id: u32, point: Point) -> Option { + page_window_rect(window_id, point).or_else(|| { + if is_browser_window(window_id) { + document_rect(window_id, point) + } else { + None + } + }) +} + +fn contains(rect: &Rect, point: Point) -> bool { + 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 +} + +/// The largest visible Chromium page window inside `window_id` that contains `point`. +fn page_window_rect(window_id: u32, point: Point) -> Option { + use windows::Win32::UI::WindowsAndMessaging::IsWindowVisible; + + web_content_windows(window_id) + .into_iter() + .filter(|page| unsafe { IsWindowVisible(*page) }.as_bool()) + .filter_map(|page| { + let mut bounds = RECT::default(); + unsafe { GetWindowRect(page, &mut bounds) }.ok()?; + Some(rect_from(bounds)) + }) + .filter(|rect| contains(rect, point)) + .max_by(|left, right| (left.width * left.height).total_cmp(&(right.width * right.height))) +} + +/// The largest UI Automation Document element in `window_id` that contains `point`. Runs only +/// when the browser has no page window there. The walk takes tens of milliseconds, so the page +/// rectangles are reused for a short time while the window keeps the same position and size. +fn document_rect(window_id: u32, point: Point) -> Option { + use std::sync::Mutex; + use std::time::Instant; + + struct Cached { + window_id: u32, + window: Rect, + at: Instant, + documents: Vec, + } + static CACHE: Mutex> = Mutex::new(None); + + let mut bounds = RECT::default(); + unsafe { GetWindowRect(HWND(window_id as usize as *mut c_void), &mut bounds) }.ok()?; + let window = rect_from(bounds); + let pick = |documents: &[Rect]| -> Option { + documents .iter() - .any(|existing| rects_nearly_equal(&existing.bounds, ®ion.bounds)); - if !is_duplicate { - deduped.push(region); + .filter(|rect| contains(rect, point)) + .max_by(|left, right| { + (left.width * left.height).total_cmp(&(right.width * right.height)) + }) + .copied() + }; + + let mut cache = CACHE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(cached) = cache.as_ref() + && cached.window_id == window_id + && cached.window == window + && cached.at.elapsed() < DOCUMENT_CACHE_TTL + { + return pick(&cached.documents); + } + let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + if initialized.is_err() { + return None; + } + let documents = unsafe { find_documents(window_id) }; + unsafe { CoUninitialize() }; + let result = pick(&documents); + *cache = Some(Cached { + window_id, + window, + at: Instant::now(), + documents, + }); + result +} + +/// Walks the browser's own UI (toolbars, panels) breadth first without entering pages, so the +/// walk stays small; a page's Document element sits a few levels below the window. +unsafe fn find_documents(window_id: u32) -> Vec { + let mut documents = Vec::new(); + let Ok(automation) = (unsafe { + CoCreateInstance::<_, IUIAutomation>(&CUIAutomation, None, CLSCTX_INPROC_SERVER) + }) else { + return documents; + }; + let Ok(root) = + (unsafe { automation.ElementFromHandle(HWND(window_id as usize as *mut c_void)) }) + else { + return documents; + }; + let Ok(walker) = (unsafe { automation.ControlViewWalker() }) else { + return documents; + }; + let mut queue = std::collections::VecDeque::from([root]); + let mut visited = 0usize; + while let Some(element) = queue.pop_front() { + visited += 1; + if visited > MAX_DOCUMENT_SEARCH_ELEMENTS { + break; + } + if unsafe { element.CurrentControlType() } == Ok(UIA_DocumentControlTypeId) { + if let Ok(bounds) = unsafe { element.CurrentBoundingRectangle() } { + documents.push(rect_from(bounds)); + } + continue; + } + let mut child = unsafe { walker.GetFirstChildElement(&element) }.ok(); + while let Some(current) = child { + child = unsafe { walker.GetNextSiblingElement(¤t) }.ok(); + queue.push_back(current); } } - Ok(deduped) + documents } fn rects_nearly_equal(left: &Rect, right: &Rect) -> bool { @@ -231,3 +587,62 @@ 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::*; + + #[test] + fn window_manager_overlays_are_pass_through() { + // Extended styles read from real windows on Windows 11. + assert!( + is_pass_through_ex_style(0x0808_0080), + "FancyWM interactive overlay" + ); + assert!( + is_pass_through_ex_style(0x0808_00A0), + "FancyWM non-interactive overlay" + ); + assert!( + is_pass_through_ex_style(0x0000_0020), + "any click-through window" + ); + } + + #[test] + fn app_windows_are_not_pass_through() { + assert!(!is_pass_through_ex_style(0x0020_0100), "Aside and Brave"); + assert!(!is_pass_through_ex_style(0x0004_0110), "a Tauri app window"); + assert!( + !is_pass_through_ex_style(0x0020_0108), + "a topmost picture-in-picture window" + ); + assert!( + !is_pass_through_ex_style(0x0008_0080), + "a layered tool window that activates" + ); + } + + 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..1b82282 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -8,13 +8,41 @@ use crate::{ error::SnaphubError, platform::{ CaptureBackend, CapturedDisplay, ClipboardBackend, PermissionBackend, PinnedWindowBackend, - ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, + ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, WebViewport, }, }; #[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, +} + +/// 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 + && self.attempts < MAX_SCAN_ATTEMPTS + && now.saturating_duration_since(self.scanned_at) >= PROVISIONAL_RESCAN_AFTER + } } impl CaptureBackend for XcapPlatformBackend { @@ -126,6 +154,13 @@ impl TargetDetectionBackend for XcapPlatformBackend { if title.starts_with("CapKit Capture") || title.starts_with("CapKit Pin") { continue; } + #[cfg(target_os = "windows")] + if window + .id() + .is_ok_and(super::windows_ui::is_pass_through_overlay) + { + continue; + } let x = f64::from(window.x().map_err(SnaphubError::capture)?); let y = f64::from(window.y().map_err(SnaphubError::capture)?); let width = f64::from(window.width().map_err(SnaphubError::capture)?); @@ -160,11 +195,30 @@ 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 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, + 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() @@ -177,10 +231,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)? { @@ -191,6 +274,12 @@ fn underlying_window_at(point: Point) -> Result, SnaphubError> { if title.starts_with("CapKit Capture") || title.starts_with("CapKit Pin") { continue; } + if window + .id() + .is_ok_and(super::windows_ui::is_pass_through_overlay) + { + continue; + } let bounds = Rect { x: f64::from(window.x().map_err(SnaphubError::capture)?), y: f64::from(window.y().map_err(SnaphubError::capture)?), @@ -200,7 +289,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) } @@ -308,6 +400,33 @@ 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 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(); + 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-tauri/src/services/browser_link.rs b/apps/desktop/src-tauri/src/services/browser_link.rs new file mode 100644 index 0000000..f17871c --- /dev/null +++ b/apps/desktop/src-tauri/src/services/browser_link.rs @@ -0,0 +1,1932 @@ +//! 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, + #[serde(skip_serializing_if = "Option::is_none")] + accent: Option, + }, + Theme { + v: u8, + accent: &'a str, + }, + 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 + } + + /// True while a code is live but its guesses are used up. + pub fn exhausted(&self) -> bool { + self.code.is_some() && self.attempts >= MAX_PAIRING_ATTEMPTS + } + + 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 pairing_locked: bool, + 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, + /// Set once a code ran out of guesses, so Settings can say so. Cleared by a new code. + pairing_locked: bool, + listener: Option, + bind_error: Option, + connections: HashMap, + next_connection: u64, + pending: HashMap, + /// CapKit's theme accent (`#rrggbb`), set by the frontend; sent to the extension. + accent: Option, +} + +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(), + pairing_locked: shared.pairing_locked, + 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 is_hex_color(value: &str) -> bool { + value.len() == 7 && value.starts_with('#') && value[1..].chars().all(|c| c.is_ascii_hexdigit()) +} + +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(), + pairing_locked: false, + listener: None, + bind_error: None, + connections: HashMap::new(), + accent: None, + 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()); + shared.pairing_locked = false; + Ok(PairingCodeDto { + code, + expires_at: expires_at.to_rfc3339(), + }) + } + + /// Remembers CapKit's accent colour and sends it to every connected extension. + /// Ignores anything that isn't `#rrggbb`. + pub fn set_accent(&self, accent: &str) { + if !is_hex_color(accent) { + return; + } + let mut shared = lock(&self.inner.state); + if shared.accent.as_deref() == Some(accent) { + return; + } + shared.accent = Some(accent.to_owned()); + let message = frame(&Outgoing::Theme { + v: PROTOCOL_VERSION, + accent, + }); + for connection in shared.connections.values().filter(|c| c.authed) { + let _ = connection.tx.send(Outbound::Text(message.clone())); + } + } + + pub fn cancel_pairing(&self) { + let mut shared = lock(&self.inner.state); + shared.pairing.cancel(); + shared.pairing_locked = false; + } + + /// 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.pairing_locked = false; + 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) => { + let locked = { + let mut shared = lock(&inner.state); + let locked = + reason == PairReject::TooManyAttempts || shared.pairing.exhausted(); + let changed = locked && !shared.pairing_locked; + shared.pairing_locked |= locked; + changed + }; + send(&Outgoing::PairRejected { + v: PROTOCOL_VERSION, + reason, + }); + if locked { + inner.emit_status(); + } + 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 accent = { + let mut shared = lock(&inner.state); + if let Some(connection) = shared.connections.get_mut(&id) { + connection.authed = true; + connection.browser = Some(browser); + } + shared.accent.clone() + }; + send(&Outgoing::Ready { + v: PROTOCOL_VERSION, + accent, + }); + 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 the_code_reports_when_its_guesses_are_used_up() { + let mut state = PairingState::default(); + assert!(!state.exhausted()); + state.start("123456".into(), at(0)); + for _ in 0..4 { + let _ = state.verify("000000", at(1)); + } + assert!(!state.exhausted()); + let _ = state.verify("000000", at(1)); + assert!(state.exhausted()); + state.start("654321".into(), at(2)); + assert!(!state.exhausted()); + } + + #[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 the_accent_reaches_the_extension_on_connect_and_on_change() { + let link = service(temp_config("accent")); + link.set_enabled(true).unwrap(); + let port = link.status().port.unwrap(); + let code = link.start_pairing().unwrap().code; + link.set_accent("not a colour"); + link.set_accent("#39ff88"); + + 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 token = token_from(&next_text(&mut socket).await); + let mut socket = connect(port, EXTENSION_ORIGIN).await.unwrap(); + socket + .send(Message::text(hello_frame(&token))) + .await + .unwrap(); + let ready = next_text(&mut socket).await; + assert!(ready.contains(r##""accent":"#39ff88""##), "{ready}"); + + link.set_accent("#7c5cff"); + let theme = next_text(&mut socket).await; + assert!( + theme.contains(r##""type":"theme","v":1,"accent":"#7c5cff""##), + "{theme}" + ); + }); + } + + #[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..8ce1863 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,8 @@ pub struct CaptureService { scrolling: Arc, pinning: Arc, text_recognition: Arc, + browser: OnceLock>, + notes_images: OnceLock, sessions: Mutex>, manual_scrolling: Mutex>, save_directory: Mutex, @@ -139,6 +147,8 @@ impl CaptureService { scrolling: backend.clone(), 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), @@ -150,6 +160,61 @@ 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); + } + + /// 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 { + 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(); @@ -231,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(), + )), } } @@ -304,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); @@ -335,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)?; @@ -526,8 +636,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) @@ -635,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)? @@ -1678,9 +1806,11 @@ mod tests { recognized_text: Mutex, recognized_size: Mutex>, clipboard_calls: AtomicUsize, + ui_region_calls: AtomicUsize, fail_clipboard: AtomicBool, clipboard_entered: Mutex>>, clipboard_release: Mutex>>, + web_viewport: Mutex>, } impl FakeBackend { @@ -1692,9 +1822,11 @@ mod tests { recognized_text: Mutex::new(String::new()), recognized_size: Mutex::new(None), clipboard_calls: AtomicUsize::new(0), + ui_region_calls: AtomicUsize::new(0), fail_clipboard: AtomicBool::new(false), clipboard_entered: Mutex::new(None), clipboard_release: Mutex::new(None), + web_viewport: Mutex::new(None), } } @@ -1760,8 +1892,13 @@ mod tests { } fn ui_region_at(&self, _point: Point) -> Result, SnaphubError> { + self.ui_region_calls.fetch_add(1, Ordering::SeqCst); Ok(None) } + + fn web_viewport_at(&self, _point: Point) -> Result, SnaphubError> { + Ok(self.web_viewport.lock().unwrap().clone()) + } } impl TextRecognitionBackend for FakeBackend { @@ -1842,6 +1979,7 @@ mod tests { intensity: 1.0, }], }, + note_id: None, } } @@ -1944,6 +2082,166 @@ 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 (service, directory, _backend) = + counted_browser_service(name, connected, elements, over_page); + (service, directory) + } + + fn counted_browser_service( + name: &str, + connected: bool, + elements: Option>, + over_page: bool, + ) -> (CaptureService, TestDirectory, Arc) { + 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 backend = Arc::new(backend); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + service.set_browser_source(Arc::new(FakeBrowser { + connected, + elements, + })); + (service, directory, backend) + } + + #[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 ui_automation_runs_only_when_the_extension_has_no_elements() { + let point = Point { x: 20.0, y: 20.0 }; + let (service, _directory, backend) = + counted_browser_service("web-calls-hit", true, Some(vec![page_element()]), true); + service.detect_targets(point, true).expect("targets"); + assert_eq!(backend.ui_region_calls.load(Ordering::SeqCst), 0); + let (service, _directory, backend) = + counted_browser_service("web-calls-none", true, None, true); + service.detect_targets(point, true).expect("targets"); + assert_eq!(backend.ui_region_calls.load(Ordering::SeqCst), 1); + } + + #[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"); @@ -2153,6 +2451,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 16ce1d9..6e146af 100644 --- a/apps/desktop/src-tauri/src/services/mod.rs +++ b/apps/desktop/src-tauri/src/services/mod.rs @@ -1,5 +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..b5ec4e3 --- /dev/null +++ b/apps/desktop/src-tauri/src/services/notes.rs @@ -0,0 +1,806 @@ +//! 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. +/// Notes belong to Developer tools: every notes command checks this before touching the store. +pub fn require_developer_tools(enabled: bool) -> Result<(), SnaphubError> { + if enabled { + Ok(()) + } else { + Err(SnaphubError::Notes("Developer tools is off".into())) + } +} + +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 { + #[test] + fn notes_commands_need_developer_tools() { + let error = super::require_developer_tools(false).unwrap_err(); + assert!(error.to_string().contains("Developer tools is off")); + assert!(super::require_developer_tools(true).is_ok()); + } + + 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-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index c402a5a..24a515f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "CapKit", - "version": "0.3.0", + "version": "0.4.0", "identifier": "com.snaphub.desktop", "build": { "beforeDevCommand": "pnpm dev", @@ -47,16 +47,21 @@ "enable": true, "scope": [ "$TEMP/CapKit/**", - "$PICTURE/CapKit/**" + "$PICTURE/CapKit/**", + "$APPLOCALDATA/notes/images/**" ] } } }, "plugins": { "updater": { - "pubkey": "REPLACE_WITH_UPDATER_PUBLIC_KEY", - "endpoints": ["https://github.com/imnakul/Capkit/releases/latest/download/latest.json"], - "windows": { "installMode": "passive" } + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFFRTYwMkQ5OEU2REE4QjIKUldTeXFHMk8yUUxtSG5tRW93Tmxteit5S0JSV1RoT0Z0bjY1NGQ3U3pVQTRjekFEbXZjSUtCaXoK", + "endpoints": [ + "https://github.com/imnakul/Capkit/releases/latest/download/latest.json" + ], + "windows": { + "installMode": "passive" + } } }, "bundle": { diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 259d408..2941fe0 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(() => ({ @@ -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); @@ -691,8 +700,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 +723,191 @@ 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(); + it("fades the overlay in and out natively, with no scrim animation in the page", async () => { + useReducedMotion(false); 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)"); + 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("dim-rise: Escape fades out and cancels only after 120 ms, once for a double Escape", async () => { - useMotion("dim-rise"); + it("skips both fades under reduced motion", async () => { + useReducedMotion(true); render(); - await screen.findByTestId("capture-scrim"); - await waitFor(() => expect(screen.getByTestId("capture-scrim")).toHaveStyle({ opacity: "1" })); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(true)); 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); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), true)); }); - it("fade-both: Escape cancels immediately with the fade-both motion", async () => { - useMotion("fade-both"); + 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 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); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith(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)); - expect(screen.getByTestId("capture-scrim").style.transition).toBe(""); - fireEvent.keyDown(window, { key: "Escape" }); - await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); +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 }); }); - it("reduced motion: no scrim animation and Escape cancels immediately in every mode", async () => { - useMotion("dim-rise", true); - render(); - await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("dim-rise", true)); - 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), "dim-rise", true); + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); }); - it("a new capture during the exit fade cancels the old session once and reveals the new one", async () => { - useMotion("dim-rise"); + async function openWithNotes(): Promise { 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 selectRegion(); + await waitFor(() => expect(captureMocks.getBrowserLinkStatus).toHaveBeenCalled()); + } + + it("keeps a comment typed on a pin, without separate note buttons", 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.queryByRole("button", { name: "Copy note" })).not.toBeInTheDocument(); + }); + + it("reopens a pin's comment for editing when the pin is clicked", 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()); + const props = captureMocks.canvasProps.current; + if (props === null) throw new Error("canvas not rendered"); + act(() => (props.onPinSelect as unknown as (id: string) => void)("c1")); + expect(await screen.findByRole("textbox", { name: "Comment for this spot" })).toHaveValue("Too tight"); + }); + + it("moves a pin's comment with the pin", async () => { + await openWithNotes(); + place("c1", 1); + const before = (await screen.findByRole("dialog", { name: "Note 1" })).style.left; + const props = captureMocks.canvasProps.current; + if (props === null) throw new Error("canvas not rendered"); + act(() => (props.onPinDrag as unknown as (id: string, p: { x: number; y: number } | null) => void)("c1", { x: 120, y: 60 })); + const during = screen.getByRole("dialog", { name: "Note 1" }).style.left; + expect(during).not.toBe(before); + expect(during).toBe("136px"); + }); + + 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" })); + 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" }); + await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment for this spot" })).not.toBeInTheDocument()); + fireEvent.keyDown(window, { key: "c" }); + 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" }); + await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment for this spot" })).not.toBeInTheDocument()); + fireEvent.keyDown(window, { key: "a" }); + await waitFor(() => expect(captureMocks.deliverNote).toHaveBeenCalledTimes(1)); + expect((captureMocks.deliverNote.mock.calls[0]?.[0] as { mode: string }).mode).toBe("copy-and-save"); + 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("saves the note with S", async () => { + await openWithNotes(); + place("c1", 1); + fireEvent.keyDown(await screen.findByRole("textbox", { name: "Comment for this spot" }), { key: "Enter" }); + await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment for this spot" })).not.toBeInTheDocument()); + fireEvent.keyDown(window, { key: "s" }); + await waitFor(() => expect(captureMocks.deliverNote).toHaveBeenCalledTimes(1)); + expect((captureMocks.deliverNote.mock.calls[0]?.[0] as { mode: string }).mode).toBe("save"); + }); + + it("copies the plain image with C while the capture has no notes", async () => { + await openWithNotes(); + fireEvent.keyDown(window, { key: "c" }); + await waitFor(() => expect(captureMocks.completeCapture).toHaveBeenCalledWith("copy", expect.any(String), expect.anything(), expect.anything())); + expect(captureMocks.deliverNote).not.toHaveBeenCalled(); + }); + + it("hides the Note 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: "Note" })).not.toBeInTheDocument(); }); }); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index fc2a9aa..420036b 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,25 +1,37 @@ -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, 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 { @@ -30,7 +42,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, @@ -42,7 +54,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, @@ -55,15 +67,20 @@ import { detectTargets, dismissCapture, discardScrollingOutput, + deliverNote, describeInvokeError, + getBrowserLinkStatus, + inspectWebTarget, isTextRecognitionSupported, listTargets, listenForCaptureRequest, pickCaptureColor, + findSensitiveWeb, recognizeCaptureText, requestCapture, retryCaptureSave, showCaptureSurface, + type NoteDeliveryMode, } from "./lib/tauri"; type Interaction = @@ -101,15 +118,19 @@ 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 [pinDrag, setPinDrag] = useState<{ counterId: string; position: Point } | null>(null); + const [lookups, setLookups] = useState>>({}); + const [developerTools, setDeveloperTools] = useState(false); + const noteRetry = useRef<{ noteId: string; request: Parameters[0] } | null>(null); + const lastHover = useRef(null); + 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: "", @@ -160,6 +181,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]); @@ -196,20 +227,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; @@ -225,27 +244,19 @@ 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 => { - 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; @@ -273,7 +284,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([ @@ -290,19 +309,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 && @@ -404,7 +411,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 +431,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(() => { @@ -577,6 +586,72 @@ 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) lastHover.current = hoverTarget; + }, [hoverTarget]); + + function placeNote(pin: CounterAnnotation, area: Rect | null): void { + if (session === null || selection === null) return; + const id = crypto.randomUUID(); + const sessionId = session.id; + const hovered = lastHover.current; + // Hover bounds are display-local logical px; the note records physical screen px. + const scale = session.display.scaleFactor; + const fallback = hovered === null + ? null + : { + role: "element", + name: hovered.title, + box: { + x: Math.round((session.display.bounds.x + hovered.bounds.x) * scale), + y: Math.round((session.display.bounds.y + hovered.bounds.y) * scale), + width: Math.round(hovered.bounds.width * scale), + height: Math.round(hovered.bounds.height * scale), + }, + }; + 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 { @@ -652,10 +727,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(); @@ -669,17 +743,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 => { @@ -761,6 +826,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 @@ -826,9 +968,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, @@ -898,6 +1048,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 @@ -975,12 +1144,22 @@ export function App(): React.JSX.Element { } }, [session]); + const hasNotes = developerTools && activeNotes.length > 0; + + /** Copy, Save and Copy & Save deliver the note (Markdown plus screenshot) once the capture has a pin. */ + const finishCapture = useCallback((action: "copy" | "save" | "copy-and-save"): void => { + if (hasNotes) void handleNoteComplete(action); + else void handleComplete(action); + }, [handleComplete, handleNoteComplete, hasNotes]); + useEffect(() => { function handleKeyDown(event: KeyboardEvent): void { // Escape is the capture surface's unconditional exit hatch. Handle it in // 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) { @@ -1025,24 +1204,27 @@ export function App(): React.JSX.Element { && key === settingsRef.current.shortcuts.captureModeCopy ) { event.preventDefault(); - void handleComplete("copy"); + finishCapture("copy"); } else if ( selectedCompletionReady && hasNoModifiers && key === settingsRef.current.shortcuts.captureModeCopyAndSave ) { event.preventDefault(); - void handleComplete("copy-and-save"); + finishCapture("copy-and-save"); } else if ( selectedCompletionReady && hasNoModifiers && key === settingsRef.current.shortcuts.captureModeSave ) { event.preventDefault(); - void handleComplete("save"); + finishCapture("save"); + } else if (selectedCompletionReady && developerTools && hasNoModifiers && key === "N") { + event.preventDefault(); + setActiveTool("note"); } else if (selectedCompletionReady && event.key === "Enter") { event.preventDefault(); - void handleComplete("copy"); + finishCapture("copy"); } else if ( event.ctrlKey && !busy @@ -1062,9 +1244,11 @@ export function App(): React.JSX.Element { }, [ busy, completionState.phase, + developerTools, + editingNoteId, requestExit, openGroupIndex, - handleComplete, + finishCapture, isDraftingSelection, pickColor, scrollingCapture, @@ -1096,19 +1280,55 @@ 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 === "copy" || id === "save" || id === "copy-and-save") finishCapture(id); + 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" + ? toolbar.verticalTools + .filter((toolId) => 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 (
{selection === null && hoverTarget !== null ? ( -
) : null} - {selection === null ?
: null} + {selection === null ?
: null} {selection === null ? (
{swatchHex === null ? null : } {message} @@ -1176,7 +1381,6 @@ export function App(): React.JSX.Element {
) : ( setPinDrag(position === null ? null : { counterId: annotationId, position })} + 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} onToolChange={setActiveTool} onUndo={() => dispatchScene({ type: "undo" })} + actionItems={horizontalActionItems} + keyboardEnabled={scrollingCapture === null && !busy} />
) : null} @@ -1235,25 +1461,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 : ( element.id === note.counterId); + return pin?.kind === "counter" ? pin.position : note.anchor; +} diff --git a/apps/desktop/src/components/AnnotationCanvas.test.tsx b/apps/desktop/src/components/AnnotationCanvas.test.tsx index 1940587..0a8d8dc 100644 --- a/apps/desktop/src/components/AnnotationCanvas.test.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.test.tsx @@ -153,6 +153,54 @@ describe("AnnotationCanvas effect previews", () => { expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ kind: "text", text: "Type something" })); }); + it("opens a note pin from Select without moving focus off the comment", () => { + const pin = { id: "pin-1", kind: "counter" as const, position: { x: 40, y: 40 }, value: 1, color: "#d9ff43", radius: 12, opacity: 1 }; + const onPinSelect = vi.fn(); + render( + undefined} + onDelete={() => undefined} + onPinSelect={onPinSelect} + onUpdate={() => undefined} + />, + ); + const canvas = screen.getByRole("application", { name: "Screenshot annotation canvas" }); + const pressed = fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 40, clientY: 40, pointerId: 3 }); + expect(onPinSelect).toHaveBeenCalledWith("pin-1"); + expect(pressed).toBe(false); + }); + + it("reports a pin's live position while it is dragged, then null on release", () => { + const pin = { id: "pin-1", kind: "counter" as const, position: { x: 40, y: 40 }, value: 1, color: "#d9ff43", radius: 12, opacity: 1 }; + const onPinDrag = vi.fn(); + render( + undefined} + onDelete={() => undefined} + onPinDrag={onPinDrag} + onUpdate={() => undefined} + />, + ); + const canvas = screen.getByRole("application", { name: "Screenshot annotation canvas" }); + fireEvent.pointerDown(canvas, { button: 0, buttons: 1, clientX: 40, clientY: 40, pointerId: 4 }); + fireEvent.pointerMove(canvas, { buttons: 1, clientX: 70, clientY: 55, pointerId: 4 }); + expect(onPinDrag).toHaveBeenLastCalledWith("pin-1", { x: 70, y: 55 }); + fireEvent.pointerUp(canvas, { button: 0, buttons: 0, clientX: 70, clientY: 55, pointerId: 4 }); + expect(onPinDrag).toHaveBeenLastCalledWith("pin-1", null); + }); + it("selects, moves, and deletes an existing annotation", () => { const rectangle = { id: "rectangle-1", @@ -188,4 +236,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..669c45f 100644 --- a/apps/desktop/src/components/AnnotationCanvas.tsx +++ b/apps/desktop/src/components/AnnotationCanvas.tsx @@ -4,12 +4,49 @@ import type { Annotation, AnnotationScene, AnnotationStyle, + CounterAnnotation, 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; @@ -21,8 +58,19 @@ 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 pin's live position while Select drags it, then null on release, so its comment can follow. */ + onPinDrag?: (annotationId: string, position: Point | null) => 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({ @@ -35,6 +83,10 @@ export function AnnotationCanvas({ onCommit, onUpdate, onDelete, + noteColor = "#d9ff43", + onNotePlace, + onPinSelect, + onPinDrag, }: AnnotationCanvasProps): React.JSX.Element { const containerRef = useRef(null); const [draft, setDraft] = useState(null); @@ -47,7 +99,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; @@ -56,8 +109,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(); @@ -86,6 +151,12 @@ export function AnnotationCanvas({ if (activeTool === "select") { const hit = findAnnotationAtPoint(scene.elements, point); setSelectedAnnotationId(hit?.id ?? null); + if (hit?.kind === "counter" && onPinSelect !== undefined) { + // The pin's comment popover focuses its textarea; without this the press's + // default mousedown focus change would blur it, so typing would fire capture shortcuts. + event.preventDefault(); + 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; @@ -93,7 +164,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 +195,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,9 +218,14 @@ 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 }); + if (current.kind === "counter") onPinDrag?.(current.id, current.position); return; } const current = draftRef.current; @@ -159,6 +249,7 @@ export function AnnotationCanvas({ if (moving !== null) { event.stopPropagation(); onUpdate(moving.current); + if (moving.current.kind === "counter") onPinDrag?.(moving.current.id, null); movingAnnotationRef.current = null; setMovingAnnotation(null); return; @@ -167,6 +258,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, @@ -342,7 +458,25 @@ export function AnnotationCanvas({ const selectedBounds = annotationBounds(selected); return (
-
@@ -585,35 +719,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, @@ -689,6 +794,7 @@ function createAnnotation( radius: Math.max(12, style.strokeWidth * 3), opacity, }; + case "note": case "select": return null; } diff --git a/apps/desktop/src/components/AnnotationToolbar.test.tsx b/apps/desktop/src/components/AnnotationToolbar.test.tsx index 5429b7a..a3892af 100644 --- a/apps/desktop/src/components/AnnotationToolbar.test.tsx +++ b/apps/desktop/src/components/AnnotationToolbar.test.tsx @@ -9,6 +9,7 @@ type HarnessProps = { toolbar?: typeof defaultSnaphubSettings.toolbar; initialTool?: ToolId; placement?: "top" | "bottom"; + keyboardEnabled?: boolean; onToolChange?: (tool: ToolId) => void; }; @@ -17,6 +18,7 @@ function Harness({ toolbar = defaultSnaphubSettings.toolbar, initialTool = "select", placement = "bottom", + keyboardEnabled = true, onToolChange, }: HarnessProps): React.JSX.Element { const [activeTool, setActiveTool] = useState(initialTool); @@ -27,6 +29,7 @@ function Harness({ activeTool={activeTool} canRedo={false} canUndo={false} + keyboardEnabled={keyboardEnabled} lastToolByGroup={last} openGroupIndex={open} palette={defaultSnaphubSettings.palette} @@ -129,10 +132,43 @@ describe("AnnotationToolbar", () => { it("does not advertise A for the Arrow tool", () => { render(); const arrow = screen.getByRole("button", { name: "Arrow" }); - expect(arrow.querySelector("kbd")).toBeNull(); + expect(arrow).not.toHaveAttribute("aria-keyshortcuts", "A"); expect(arrow).toHaveTextContent("Arrow"); }); + it("numbers the tools 1–9 then 0 and shows each number on its button", () => { + render(); + const tools = screen.getAllByRole("button").filter((button) => button.getAttribute("aria-label") !== "Select"); + expect(screen.getByRole("button", { name: "Select" })).toHaveAttribute("aria-keyshortcuts", "V"); + expect(tools.slice(0, 10).map((button) => button.getAttribute("aria-keyshortcuts"))).toEqual(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]); + expect(tools[0]?.querySelector("kbd")).toHaveTextContent("1"); + expect(tools[10]).not.toHaveAttribute("aria-keyshortcuts"); + }); + + it("picks a tool with its number key and Select with V", () => { + const onToolChange = vi.fn(); + render(); + const second = screen.getAllByRole("button").find((button) => button.getAttribute("aria-keyshortcuts") === "2"); + fireEvent.keyDown(window, { key: "2" }); + expect(second).toHaveAttribute("aria-pressed", "true"); + fireEvent.keyDown(window, { key: "v" }); + expect(onToolChange).toHaveBeenLastCalledWith("select"); + }); + + it("ignores number keys while typing, with modifiers, or when the keyboard is off", () => { + const onToolChange = vi.fn(); + const { rerender } = render(); + const field = document.createElement("textarea"); + document.body.append(field); + fireEvent.keyDown(field, { key: "1" }); + fireEvent.keyDown(window, { key: "1", ctrlKey: true }); + expect(onToolChange).not.toHaveBeenCalled(); + field.remove(); + rerender(); + fireEvent.keyDown(window, { key: "1" }); + expect(onToolChange).not.toHaveBeenCalled(); + }); + it("puts the style row on the far side of the selection when the toolbar sits above it", () => { render(); const card = screen.getByRole("toolbar", { name: "Quick editing tools" }).parentElement; @@ -151,4 +187,48 @@ describe("AnnotationToolbar", () => { 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..4f4356c 100644 --- a/apps/desktop/src/components/AnnotationToolbar.tsx +++ b/apps/desktop/src/components/AnnotationToolbar.tsx @@ -1,9 +1,10 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; 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,10 @@ 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[]; + /** False while the capture is busy (scrolling capture, finishing); V and the number keys do nothing. */ + keyboardEnabled?: boolean; onToolChange: (tool: ToolId) => void; onStyleChange: (style: AnnotationStyle) => void; onUndo: () => void; @@ -49,6 +54,8 @@ export function AnnotationToolbar({ placement = "bottom", lastToolByGroup, openGroupIndex, + actionItems = [], + keyboardEnabled = true, onToolChange, onStyleChange, onUndo, @@ -60,14 +67,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 +97,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 +141,53 @@ export function AnnotationToolbar({ }); } + // Tools and groups (not finishing actions, which have their own letters) take 1–9, then 0. + items.slice(1).forEach((item, index) => { + const key = numberKeys[index]; + if (key !== undefined) item.shortcut = key; + }); + + 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 shortcutItems = useRef(items); + useEffect(() => { + shortcutItems.current = items; + }); + + useEffect(() => { + if (!keyboardEnabled) return undefined; + function onKeyDown(event: KeyboardEvent): void { + if (event.defaultPrevented || event.repeat || event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) return; + if (isTypingTarget(event.target)) return; + const key = event.key.toUpperCase(); + const item = shortcutItems.current.find((candidate) => candidate.shortcut === key && !candidate.id.startsWith("action-")); + if (item === undefined || item.disabled) return; + event.preventDefault(); + item.onSelect(); + } + window.addEventListener("keydown", onKeyDown); + return (): void => window.removeEventListener("keydown", onKeyDown); + }, [keyboardEnabled]); + 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; @@ -176,6 +216,7 @@ export function AnnotationToolbar({ return (
); } + +const numberKeys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] as const; + +function isTypingTarget(target: EventTarget | null): boolean { + return target instanceof HTMLInputElement + || target instanceof HTMLTextAreaElement + || (target instanceof HTMLElement && target.isContentEditable); +} + +/** 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/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()} + > + +