diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index 0a4458d..f66c6ba 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,6 +2,24 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. +## 0.7.0 — 2026-11-27 + +### Added + +- Browser extension: Pick and comment. Click elements on any page, add a comment to each, and copy them all as compact text an AI agent understands without an extra prompt. A note can ask for a change or just point an element out. Start it with Alt+Shift+C, from the extension popup, or by right-clicking the page → CapKit. +- Browser extension: Font tool. Hover any text to see its font, size, weight, line height and colour; click to copy it as CSS. Alt+Shift+F or right-click → CapKit → Font. +- Browser extension: Colour tool. Hover to see an element's text, background and border colours; click to lock it and copy any of them as HEX. Press E to pick any pixel on screen. Alt+Shift+K or right-click → CapKit → Colour. +- Screen record: hover a recording to copy the video file (paste it into a folder, chat or email) or show it in its folder. + +### Improved + +- Screen record: clicking a recording opens it in your default video player. If none is set, Windows asks which app to use. The in-app player and its full-screen button, which could break the dashboard window, are gone. +- Browser extension: the popup and on-page panels now match the CapKit dashboard: Geist font, compact buttons, and light and dark themes. The extension uses the CapKit app logo. + +### Fixed + +- Browser extension: after the extension updates, its tools start on pages that were already open, instead of asking you to reload the page. + ## 0.6.2 — 2026-11-26 ### Fixed diff --git a/apps/browser-extension/package.json b/apps/browser-extension/package.json index 83c405e..6dd8bb8 100644 --- a/apps/browser-extension/package.json +++ b/apps/browser-extension/package.json @@ -12,8 +12,8 @@ "test": "vitest run" }, "dependencies": { - "@fontsource-variable/jetbrains-mono": "5.2.8", - "@fontsource-variable/plus-jakarta-sans": "5.2.8", + "@fontsource-variable/geist": "5.3.0", + "@fontsource-variable/geist-mono": "5.3.0", "@jridgewell/trace-mapping": "^0.3.31", "@snaphub/devtools-protocol": "workspace:*", "react": "^19.2.7", diff --git a/apps/browser-extension/public/icons/128.png b/apps/browser-extension/public/icons/128.png index 549fbd9..fc73266 100644 Binary files a/apps/browser-extension/public/icons/128.png 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 index 2551d35..dc531d3 100644 Binary files a/apps/browser-extension/public/icons/16.png and b/apps/browser-extension/public/icons/16.png differ diff --git a/apps/browser-extension/public/icons/32.png b/apps/browser-extension/public/icons/32.png new file mode 100644 index 0000000..fe6bb32 Binary files /dev/null and b/apps/browser-extension/public/icons/32.png differ diff --git a/apps/browser-extension/public/icons/48.png b/apps/browser-extension/public/icons/48.png index b1d25c7..f5c09c4 100644 Binary files a/apps/browser-extension/public/icons/48.png 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 index 9990800..3e6f001 100644 --- a/apps/browser-extension/public/manifest.json +++ b/apps/browser-extension/public/manifest.json @@ -2,19 +2,35 @@ "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.", + "description": "Inspect spacing, styles and source locations, comment on elements for AI agents, read fonts and pick colours on any page.", "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" }, + "icons": { "16": "icons/16.png", "32": "icons/32.png", "48": "icons/48.png", "128": "icons/128.png" }, + "action": { + "default_popup": "popup/index.html", + "default_title": "CapKit Inspector", + "default_icon": { "16": "icons/16.png", "32": "icons/32.png" } + }, "background": { "service_worker": "background.js" }, - "permissions": ["activeTab", "alarms", "scripting", "storage", "clipboardWrite"], + "permissions": ["activeTab", "alarms", "scripting", "storage", "clipboardWrite", "contextMenus"], "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" + }, + "toggle-picker": { + "suggested_key": { "default": "Alt+Shift+C" }, + "description": "Pick elements and comment" + }, + "toggle-font": { + "suggested_key": { "default": "Alt+Shift+F" }, + "description": "Read fonts" + }, + "toggle-color": { + "suggested_key": { "default": "Alt+Shift+K" }, + "description": "Pick colours" } }, - "web_accessible_resources": [{ "resources": ["fonts/*"], "matches": [""], "use_dynamic_url": true }] + "web_accessible_resources": [{ "resources": ["fonts/*"], "matches": [""], "use_dynamic_url": false }] } diff --git a/apps/browser-extension/scripts/build.mjs b/apps/browser-extension/scripts/build.mjs index f0a9477..66c8416 100644 --- a/apps/browser-extension/scripts/build.mjs +++ b/apps/browser-extension/scripts/build.mjs @@ -47,7 +47,7 @@ await build({ }); await mkdir(resolve(dist, "fonts"), { recursive: true }); -for (const pkg of ["plus-jakarta-sans", "jetbrains-mono"]) { +for (const pkg of ["geist", "geist-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)); diff --git a/apps/browser-extension/src/background.ts b/apps/browser-extension/src/background.ts index 310b539..c47c48c 100644 --- a/apps/browser-extension/src/background.ts +++ b/apps/browser-extension/src/background.ts @@ -1,7 +1,8 @@ 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 { installMenus, toolForCommand, toolForMenu } from "./menus"; +import { backgroundRequestSchema, type LinkStatus, type PageRequest, type Tool } from "./messages"; import { activeTabs, askTab, injectMainWorld, matchTab, originPattern, siteAccessFor, type TabRef } from "./tabs"; const TOKEN_KEY = "capkitToken"; @@ -112,14 +113,19 @@ async function currentTab(): Promise { 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(); +/** The popup, a shortcut or a menu click grants activeTab, so the page tools need no site access. */ +async function runTool(tab: TabRef | null, tool: Tool, action: "toggle" | "start"): Promise { if (tab === null || originPattern(tab.url) === null) return false; - const result = await askTab(tab, { kind: "toggle" }, { requireSiteAccess: false }); + const result = await askTab(tab, { kind: "tool", tool, action }, { requireSiteAccess: false }); return result.response !== null; } +async function refreshMenus(): Promise { + const commands = await chrome.commands.getAll(); + const shortcuts = new Map(commands.flatMap((command) => (command.name === undefined || command.shortcut === undefined ? [] : [[command.name, command.shortcut] as const]))); + await installMenus(chrome.contextMenus, shortcuts); +} + async function dispatch(raw: unknown, sender: chrome.runtime.MessageSender): Promise { const parsed = backgroundRequestSchema.safeParse(raw); if (!parsed.success) return { ok: false }; @@ -145,8 +151,8 @@ async function dispatch(raw: unknown, sender: chrome.runtime.MessageSender): Pro case "forget": await link.forget(); return link.status; - case "inspectActiveTab": - return { ok: await inspectActiveTab() }; + case "startTool": + return { ok: await runTool(await currentTab(), request.tool, "start") }; case "siteAccess": return siteAccessFor(await currentTab()); } @@ -161,7 +167,14 @@ chrome.runtime.onMessage.addListener((message: unknown, sender, sendResponse) => }); chrome.commands.onCommand.addListener((command) => { - if (command === "toggle-inspector") void inspectActiveTab(); + const tool = toolForCommand(command); + if (tool !== null) void currentTab().then((tab) => runTool(tab, tool, "toggle")); +}); + +chrome.contextMenus.onClicked.addListener((info, tab) => { + const tool = toolForMenu(info.menuItemId); + if (tool === null || tab?.id === undefined) return; + void runTool({ id: tab.id, url: tab.url ?? info.pageUrl ?? "", title: tab.title ?? "" }, tool, "start"); }); // A fresh worker already connects at the bottom of this file; the alarm only nudges a live one. @@ -170,8 +183,10 @@ chrome.alarms.onAlarm.addListener((alarm) => { }); chrome.runtime.onStartup.addListener(() => { void link.connect(); + void refreshMenus(); }); chrome.runtime.onInstalled.addListener(() => { void link.connect(); + void refreshMenus(); }); void link.connect(); diff --git a/apps/browser-extension/src/content/contrast.ts b/apps/browser-extension/src/content/contrast.ts index 2e8f92d..6b3f961 100644 --- a/apps/browser-extension/src/content/contrast.ts +++ b/apps/browser-extension/src/content/contrast.ts @@ -46,3 +46,16 @@ export function gradeContrast(ratio: number, largeText: boolean): ContrastGrade if (ratio >= (largeText ? 3 : 4.5)) return "AA"; return "Fail"; } + +/** The opaque colour behind an element: its own and its ancestors' backgrounds composited over white. */ +export 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 }); +} diff --git a/apps/browser-extension/src/content/handlers.ts b/apps/browser-extension/src/content/handlers.ts index d8f72a8..842884e 100644 --- a/apps/browser-extension/src/content/handlers.ts +++ b/apps/browser-extension/src/content/handlers.ts @@ -93,7 +93,7 @@ export function handlePageRequest(env: Env, request: PageRequest): Promise 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))}`; @@ -33,7 +27,7 @@ function label(element: Element, name: string | null): string { /** Page-side inspector: hover outline, lock, side panel, measure, keyboard shortcuts. */ export class InspectorController { private active = false; - private shadow: ShadowRoot | null = null; + private frame: HTMLElement | null = null; private root: HTMLElement | null = null; private overlay: Overlay | null = null; private panel: Panel | null = null; @@ -59,15 +53,17 @@ export class InspectorController { 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); + installFonts(this.doc); + const style = h(this.doc, "style", {}, THEME_CSS, 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); + // Own frame in the shared shadow root, so stopping never removes the picker's UI. + this.frame?.remove(); + this.frame = h(this.doc, "div", { style: "display:contents" }, style, root); + hostShadow(this.doc).append(this.frame); this.overlay = new Overlay(this.doc, this.root); this.panel = new Panel(this.doc, this.root, savedPosition ?? defaultPosition(), { close: (): void => { @@ -106,8 +102,9 @@ export class InspectorController { const panel = this.panel; panel?.node.classList.remove("open"); panel?.node.classList.add("closing"); + const frame = this.frame; setTimeout(() => { - if (!this.active) this.shadow?.replaceChildren(); + frame?.remove(); }, EXIT_MS); this.hovered = null; this.locked = null; diff --git a/apps/browser-extension/src/content/inspector/panel.ts b/apps/browser-extension/src/content/inspector/panel.ts index 14a70fa..3965d6d 100644 --- a/apps/browser-extension/src/content/inspector/panel.ts +++ b/apps/browser-extension/src/content/inspector/panel.ts @@ -1,7 +1,8 @@ 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 { contrastRatio, effectiveBackground, gradeContrast, over, parseColor } from "../contrast"; import { readBoxModel } from "./overlay"; +import { closeIcon } from "../theme"; import { h } from "./dom"; const PANEL_WIDTH = 320; @@ -20,18 +21,6 @@ function clampPosition(position: PanelPosition): PanelPosition { }; } -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 { @@ -105,12 +94,12 @@ export class Panel { ) { this.position = clampPosition(position); this.body = h(doc, "div"); - const close = h(doc, "button", { type: "button", "aria-label": "Close inspector" }, "Esc"); + const close = h(doc, "button", { type: "button", class: "ghost icon", "aria-label": "Close inspector", title: "Close (Esc)" }, closeIcon(doc)); close.addEventListener("click", actions.close); - const copy = h(doc, "button", { type: "button", "aria-label": "Copy element as Markdown" }, "Copy"); + const copy = h(doc, "button", { type: "button", class: "primary", "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); + const header = h(doc, "header", {}, h(doc, "h2", {}, "Inspect"), copy, close); + this.node = h(doc, "div", { class: "panel card", role: "dialog", "aria-label": "CapKit Inspector", tabindex: "-1" }, header, this.body); this.apply(); this.enableDrag(header); root.append(this.node); diff --git a/apps/browser-extension/src/content/inspector/styles.ts b/apps/browser-extension/src/content/inspector/styles.ts index 0b17e28..a634bb3 100644 --- a/apps/browser-extension/src/content/inspector/styles.ts +++ b/apps/browser-extension/src/content/inspector/styles.ts @@ -1,50 +1,39 @@ -/** Stylesheet for the closed shadow root. No gradients, no transition: all, reduced motion keeps opacity only. */ +/** Inspector rules, added after THEME_CSS. No gradients on surfaces, 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; } +.band.margin { background: color-mix(in srgb, var(--accent) 22%, transparent); } +.band.padding { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--accent) 32%, transparent) 0 2px, transparent 2px 6px); } .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); } +.pill { position: fixed; padding: 1px 5px; border-radius: 4px; background: var(--accent); color: var(--accent-ink); font-size: 10px; font-weight: 600; pointer-events: none; transform: translate(-50%, -50%); } +.panel { + position: fixed; width: 320px; max-height: calc(100vh - 24px); overflow: auto; overscroll-behavior: contain; + opacity: 0; transform: scale(0.97); transform-origin: top right; + transition: opacity 180ms var(--ease-arrive), transform 180ms var(--ease-arrive); +} .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 { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 4px; height: 40px; padding: 0 8px 0 12px; cursor: grab; background: var(--surface); border-bottom: 1px solid var(--c8); 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; } +.panel h2 { margin: 0; flex: 1; font-size: 13px; font-weight: 600; } +.panel section, .panel details { padding: 8px 12px; border-bottom: 1px solid var(--c8); } +.panel details:last-child { border-bottom: 0; } +.panel summary { cursor: pointer; padding: 2px 0 4px; font-weight: 500; color: var(--c60); list-style: none; display: flex; align-items: center; gap: 6px; } +.panel summary::-webkit-details-marker { display: none; } +.panel summary::before { content: ""; width: 5px; height: 5px; border-right: 1.5px solid currentColor; border-bottom: 1.5px solid currentColor; transform: rotate(-45deg); transition: transform 160ms var(--ease-settle); } +.panel details[open] > summary::before { transform: rotate(45deg); } +.panel summary:hover { color: var(--fg); } +.row { display: flex; align-items: baseline; gap: 8px; padding: 3px 0; } +.row .k { flex: 0 0 80px; color: var(--c60); } +.row .v { flex: 1; min-width: 0; overflow-wrap: anywhere; color: var(--c80); } +.box { display: grid; place-items: center; gap: 4px; margin-top: 6px; padding: 6px; border: 1px dashed var(--c15); border-radius: 6px; font-size: 10px; color: var(--c60); text-align: center; } +.box .inner { width: 100%; padding: 6px; border: 1px solid var(--c15); border-radius: 4px; } +.box .inner div { color: var(--fg); } +.badge { display: inline-block; padding: 1px 5px; border-radius: 4px; background: color-mix(in oklab, var(--success) 18%, transparent); color: var(--success); font-weight: 600; font-size: 10px; } +.badge.fail { background: color-mix(in oklab, var(--danger) 18%, transparent); color: var(--danger); } @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/instance.test.ts b/apps/browser-extension/src/content/instance.test.ts new file mode 100644 index 0000000..ccc94ca --- /dev/null +++ b/apps/browser-extension/src/content/instance.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; +import { replaceInstance, type Dispose } from "./instance"; + +function scope(): typeof globalThis { + // A fresh object stands in for the isolated world's globals; only __capkitDispose is used. + return Object.create(null) as typeof globalThis; +} + +describe("replaceInstance", () => { + it("installs when nothing was loaded before", () => { + const world = scope(); + let installs = 0; + replaceInstance((): Dispose => { + installs += 1; + return (): void => undefined; + }, world); + expect(installs).toBe(1); + expect(world.__capkitDispose).toBeTypeOf("function"); + }); + + it("tears down the earlier instance before installing again", () => { + const world = scope(); + const events: string[] = []; + replaceInstance((): Dispose => { + events.push("install 1"); + return (): void => { + events.push("dispose 1"); + }; + }, world); + replaceInstance((): Dispose => { + events.push("install 2"); + return (): void => undefined; + }, world); + expect(events).toEqual(["install 1", "dispose 1", "install 2"]); + }); + + it("still installs when the orphaned instance throws on teardown", () => { + const world = scope(); + replaceInstance((): Dispose => (): void => { + throw new Error("Extension context invalidated."); + }, world); + let installed = false; + replaceInstance((): Dispose => { + installed = true; + return (): void => undefined; + }, world); + expect(installed).toBe(true); + }); +}); diff --git a/apps/browser-extension/src/content/instance.ts b/apps/browser-extension/src/content/instance.ts new file mode 100644 index 0000000..9c1c923 --- /dev/null +++ b/apps/browser-extension/src/content/instance.ts @@ -0,0 +1,28 @@ +/** Tears down one content-script instance: its tools and its message listener. */ +export type Dispose = () => void; + +declare global { + var __capkitDispose: Dispose | undefined; +} + +/** + * Runs `install` and records its teardown, first tearing down any earlier instance. + * + * After the extension reloads or updates, the old content script stays in open tabs but + * can no longer receive messages, while its globals survive in the same isolated world. + * A "skip if already loaded" flag would then block the new script forever (until the + * page reloads). The background injects only when its ping gets no answer, so a live + * instance is never replaced. + */ +export function replaceInstance(install: () => Dispose, scope: typeof globalThis = globalThis): void { + const previous = scope.__capkitDispose; + scope.__capkitDispose = undefined; + if (previous !== undefined) { + try { + previous(); + } catch { + // An orphaned instance's chrome.* calls can throw; its DOM cleanup already ran. + } + } + scope.__capkitDispose = install(); +} diff --git a/apps/browser-extension/src/content/isolated.ts b/apps/browser-extension/src/content/isolated.ts index f805f96..66524ea 100644 --- a/apps/browser-extension/src/content/isolated.ts +++ b/apps/browser-extension/src/content/isolated.ts @@ -1,24 +1,26 @@ -import { PROTOCOL_VERSION } from "@snaphub/devtools-protocol/protocol"; import { pageRequestSchema, type PageResponse } from "../messages"; import { handlePageRequest } from "./handlers"; +import { replaceInstance, type Dispose } from "./instance"; import { InspectorController } from "./inspector/controller"; import { resolveComponentData } from "./mainClient"; +import { PickerController } from "./picker/controller"; +import { ProbeController } from "./probe/controller"; +import { runTool } from "./tools"; -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); +function install(): Dispose { + const controllers = { + inspect: new InspectorController(document), + pick: new PickerController(document), + font: new ProbeController("font", document), + color: new ProbeController("color", document), + }; - chrome.runtime.onMessage.addListener((message: unknown, _sender, sendResponse: (response: PageResponse) => void) => { + const listener = (message: unknown, _sender: chrome.runtime.MessageSender, sendResponse: (response: PageResponse) => void): boolean => { const parsed = pageRequestSchema.safeParse(message); if (!parsed.success) return false; const request = parsed.data; - if (request.kind === "toggle") { - controller.toggle(); + if (request.kind === "tool") { + runTool(controllers, request.tool, request.action); sendResponse({ kind: "ok" }); return false; } @@ -28,5 +30,13 @@ if (globalThis.__capkitInspector !== PROTOCOL_VERSION) { sendResponse({ kind: "ok" }); }); return true; - }); + }; + chrome.runtime.onMessage.addListener(listener); + + return (): void => { + for (const controller of Object.values(controllers)) controller.stop(); + chrome.runtime.onMessage.removeListener(listener); + }; } + +replaceInstance(install); diff --git a/apps/browser-extension/src/content/picker/controller.test.ts b/apps/browser-extension/src/content/picker/controller.test.ts new file mode 100644 index 0000000..3bf667e --- /dev/null +++ b/apps/browser-extension/src/content/picker/controller.test.ts @@ -0,0 +1,142 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hostShadow } from "../shadow"; +import { PickerController, type PickerDeps } from "./controller"; + +function setup(writeText: PickerDeps["writeText"] = () => Promise.resolve()): { picker: PickerController; shadow: ShadowRoot; target: Element } { + document.body.innerHTML = '
'; + const deps: PickerDeps = { + resolve: () => Promise.resolve({ component: { name: "SaveButton", ownerPath: ["SaveButton"] }, source: null }), + writeText, + accent: () => Promise.resolve("#d9ff43"), + fonts: () => undefined, + }; + const picker = new PickerController(document, deps); + picker.start(); + const target = document.querySelector("button.save"); + if (target === null) throw new Error("no target"); + return { picker, shadow: hostShadow(document), target }; +} + +function query(shadow: ShadowRoot, selector: string): Element { + const found = shadow.querySelector(selector); + if (found === null) throw new Error(`missing ${selector}`); + return found; +} + +function textarea(shadow: ShadowRoot): HTMLTextAreaElement { + const found = shadow.querySelector("textarea"); + if (found === null) throw new Error("missing textarea"); + return found; +} + +function button(shadow: ShadowRoot, name: string): HTMLButtonElement { + const found = [...shadow.querySelectorAll("button")].find((b) => (b.getAttribute("aria-label") ?? b.textContent) === name); + if (found === undefined) throw new Error(`missing button ${name}`); + return found; +} + +async function addComment(picker: PickerController, shadow: ShadowRoot, target: Element, text: string): Promise { + picker.openCard(target); + const input = textarea(shadow); + input.value = text; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + expect(shadow.querySelector(".pk-card")).toBeNull(); + }); +} + +afterEach(() => { + document.documentElement.querySelector("capkit-inspector-host")?.remove(); +}); + +describe("PickerController", () => { + it("shows the empty hint with Copy and Clear disabled", () => { + const { picker, shadow } = setup(); + expect(shadow.textContent).toContain("Click any element to comment on it."); + expect(button(shadow, "Copy").disabled).toBe(true); + expect(button(shadow, "Clear").disabled).toBe(true); + picker.stop(); + }); + + it("adds a comment with Enter and lists it", async () => { + const { picker, shadow, target } = setup(); + await addComment(picker, shadow, target, "Make it green"); + expect(picker.items).toHaveLength(1); + expect(picker.items[0]).toMatchObject({ name: "SaveButton", text: "Save", comment: "Make it green" }); + expect(query(shadow, ".pk-list ol").textContent).toContain("Make it green"); + expect(shadow.querySelectorAll(".pk-marker")).toHaveLength(1); + picker.stop(); + }); + + it("copies the notes as text and keeps the picks", async () => { + const writeText = vi.fn(() => Promise.resolve()); + const { picker, shadow, target } = setup(writeText); + await addComment(picker, shadow, target, "Make it green"); + button(shadow, "Copy").click(); + await vi.waitFor(() => { + expect(writeText).toHaveBeenCalledOnce(); + }); + const copied: unknown = writeText.mock.calls[0]?.at(0); + expect(copied).toContain("1. SaveButton: Make it green"); + expect(picker.items).toHaveLength(1); + expect(await vi.waitFor(() => query(shadow, ".toast"))).toHaveTextContent("Copied 1 comment"); + picker.stop(); + }); + + it("keeps picks and tells the user when the copy fails", async () => { + const { picker, shadow, target } = setup(() => Promise.reject(new Error("denied"))); + await addComment(picker, shadow, target, "x"); + await picker.copy(); + expect(query(shadow, ".toast")).toHaveTextContent("Couldn't copy"); + expect(picker.items).toHaveLength(1); + picker.stop(); + }); + + it("removes one pick and clears all", async () => { + const { picker, shadow, target } = setup(); + await addComment(picker, shadow, target, "one"); + await addComment(picker, shadow, target, "two"); + button(shadow, "Remove comment 1").click(); + expect(picker.items.map((item) => item.comment)).toEqual(["two"]); + button(shadow, "Clear").click(); + expect(picker.items).toHaveLength(0); + picker.stop(); + }); + + it("keeps an unsaved draft when another element is clicked", () => { + const { picker, shadow, target } = setup(); + picker.openCard(target); + textarea(shadow).value = "draft"; + const other = document.querySelector("input"); + if (other === null) throw new Error("no input"); + picker.openCard(other); + expect(textarea(shadow).value).toBe("draft"); + picker.stop(); + }); + + it("Esc closes the card first, then exits and keeps picks for next time", async () => { + const { picker, shadow, target } = setup(); + await addComment(picker, shadow, target, "keep me"); + picker.openCard(target); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(shadow.querySelector(".pk-card")).toBeNull(); + expect(picker.isActive).toBe(true); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(picker.isActive).toBe(false); + expect(shadow.querySelector(".pk-list")).toBeNull(); + picker.start(); + expect(query(shadow, ".pk-list").textContent).toContain("keep me"); + picker.stop(); + }); + + it("blocks page clicks while picking", () => { + const { picker, target } = setup(); + const pageClick = vi.fn(); + target.addEventListener("mousedown", pageClick); + target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); + expect(pageClick).not.toHaveBeenCalled(); + picker.stop(); + target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); + expect(pageClick).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/browser-extension/src/content/picker/controller.ts b/apps/browser-extension/src/content/picker/controller.ts new file mode 100644 index 0000000..a082419 --- /dev/null +++ b/apps/browser-extension/src/content/picker/controller.ts @@ -0,0 +1,371 @@ +import { readAccent } from "../../accent"; +import { HOST_TAG } from "../bridge"; +import { shortLabel, type ComponentData } from "../dom"; +import { h, place } from "../inspector/dom"; +import { Overlay } from "../inspector/overlay"; +import { INSPECTOR_CSS } from "../inspector/styles"; +import { resolveComponentData, type ComponentResolver } from "../mainClient"; +import { hostShadow, installFonts } from "../shadow"; +import { THEME_CSS, closeIcon } from "../theme"; +import { MAX_COMMENT, MAX_PICKS, buildPicksText, pickItem, type PickItem } from "./format"; +import { PICKER_CSS } from "./styles"; + +const TOAST_MS = 1600; +const CARD_WIDTH = 280; +const CARD_HEIGHT = 150; +const HINT = "Click any element to comment on it. Esc exits."; +const NO_DATA: ComponentData = { component: null, source: null }; +const SWALLOWED = ["pointerdown", "pointerup", "mousedown", "mouseup", "dblclick", "auxclick"] as const; + +export type PickerDeps = { + resolve: ComponentResolver; + writeText: (text: string) => Promise; + accent: () => Promise; + fonts: (doc: Document) => void; +}; + +const defaultDeps: PickerDeps = { + resolve: resolveComponentData, + writeText: (text) => navigator.clipboard.writeText(text), + accent: readAccent, + fonts: installFonts, +}; + +type Entry = { element: Element; item: PickItem }; +type Card = { node: HTMLElement; input: HTMLTextAreaElement; element: Element }; + +function hoverLabel(element: Element): string { + const rect = element.getBoundingClientRect(); + return `${shortLabel(element)} · ${String(Math.round(rect.width))}×${String(Math.round(rect.height))}`; +} + +/** Page-side pick and comment: hover, click to comment, numbered markers, a list with Copy. */ +export class PickerController { + private active = false; + private frame: HTMLElement | null = null; + private root: HTMLElement | null = null; + private overlay: Overlay | null = null; + private marks: HTMLElement | null = null; + private list: HTMLElement | null = null; + private card: Card | null = null; + private entries: Entry[] = []; + private frameRequest: number | null = null; + private toastTimer: ReturnType | null = null; + private readonly deps: PickerDeps; + + constructor( + private readonly doc: Document = document, + deps: Partial = {}, + ) { + this.deps = { ...defaultDeps, ...deps }; + } + + get isActive(): boolean { + return this.active; + } + + /** Picks kept for this page, oldest first. */ + get items(): readonly PickItem[] { + return this.entries.map((entry) => entry.item); + } + + toggle(): void { + if (this.active) this.stop(); + else this.start(); + } + + start(): void { + if (this.active) return; + this.active = true; + this.deps.fonts(this.doc); + const style = h(this.doc, "style", {}, THEME_CSS, INSPECTOR_CSS, PICKER_CSS); + const root = h(this.doc, "div", { class: "root" }); + this.root = root; + void this.deps.accent().then((accent) => { + root.style.setProperty("--accent", accent); + }); + this.marks = h(this.doc, "div"); + root.append(this.marks); + this.overlay = new Overlay(this.doc, root); + this.list = h(this.doc, "section", { class: "pk-list card", "aria-label": "Pick and comment" }); + root.append(this.list); + this.frame = h(this.doc, "div", { style: "display:contents" }, style, root); + hostShadow(this.doc).append(this.frame); + this.renderList(); + this.renderMarks(); + const win = this.doc.defaultView; + win?.addEventListener("pointermove", this.onMove, true); + win?.addEventListener("click", this.onClick, true); + win?.addEventListener("keydown", this.onKey, true); + win?.addEventListener("scroll", this.onViewport, true); + win?.addEventListener("resize", this.onViewport); + for (const type of SWALLOWED) win?.addEventListener(type, this.swallow, true); + } + + /** Hides the tool; picks stay in memory until the page unloads. */ + stop(): void { + if (!this.active) return; + this.active = false; + const win = this.doc.defaultView; + win?.removeEventListener("pointermove", this.onMove, true); + win?.removeEventListener("click", this.onClick, true); + win?.removeEventListener("keydown", this.onKey, true); + win?.removeEventListener("scroll", this.onViewport, true); + win?.removeEventListener("resize", this.onViewport); + for (const type of SWALLOWED) win?.removeEventListener(type, this.swallow, true); + if (this.frameRequest !== null) win?.cancelAnimationFrame(this.frameRequest); + this.frameRequest = null; + if (this.toastTimer !== null) clearTimeout(this.toastTimer); + this.frame?.remove(); + this.frame = null; + this.root = null; + this.overlay = null; + this.marks = null; + this.list = null; + this.card = null; + } + + async copy(): Promise { + if (this.entries.length === 0) return; + const count = this.entries.length; + try { + await this.deps.writeText(buildPicksText(this.doc.location.href, this.items)); + this.toast(count === 1 ? "Copied 1 comment" : `Copied ${String(count)} comments`); + } catch { + this.toast("Couldn't copy"); + } + } + + clear(): void { + this.entries = []; + this.renderList(); + this.renderMarks(); + } + + remove(index: number): void { + this.entries.splice(index, 1); + this.renderList(); + this.renderMarks(); + } + + private isOwn(target: EventTarget | null): boolean { + return target instanceof Element && target.localName === HOST_TAG; + } + + private readonly swallow = (event: Event): void => { + if (this.isOwn(event.target)) return; + event.preventDefault(); + event.stopPropagation(); + }; + + private readonly onMove = (event: PointerEvent): void => { + if (this.card !== null) return; + const element = this.doc.elementFromPoint(event.clientX, event.clientY); + if (element === null || this.isOwn(element)) { + this.overlay?.hide(); + return; + } + this.overlay?.show(element, hoverLabel(element), 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; + this.openCard(element); + }; + + private readonly onKey = (event: KeyboardEvent): void => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + if (this.card !== null) this.closeCard(); + else this.stop(); + }; + + private readonly onViewport = (): void => { + const win = this.doc.defaultView; + if (win === null || this.frameRequest !== null) return; + this.frameRequest = win.requestAnimationFrame(() => { + this.frameRequest = null; + this.renderMarks(); + if (this.card !== null) this.placeCard(this.card); + }); + }; + + /** Opens the comment card; a card with an unsaved draft keeps it and takes focus back instead. */ + openCard(element: Element): void { + if (this.root === null) return; + if (this.card !== null && this.card.input.value.trim() !== "") { + this.card.input.focus(); + return; + } + if (this.entries.length >= MAX_PICKS) { + this.toast(`Limit is ${String(MAX_PICKS)} comments. Copy or clear to add more.`); + return; + } + this.closeCard(); + this.overlay?.show(element, hoverLabel(element), true); + const data = this.deps.resolve(element).catch(() => NO_DATA); + const who = h(this.doc, "div", { class: "pk-who mono" }, shortLabel(element)); + void data.then((resolved) => { + if (resolved.component !== null) who.textContent = `${resolved.component.name} · ${shortLabel(element)}`; + }); + const input = h(this.doc, "textarea", { + "aria-label": "Comment", + placeholder: "What should change here?", + maxlength: String(MAX_COMMENT), + }); + const cancel = h(this.doc, "button", { type: "button", class: "ghost" }, "Cancel"); + const add = h(this.doc, "button", { type: "button", class: "primary" }, "Add"); + const node = h( + this.doc, + "div", + { class: "pk-card card", role: "dialog", "aria-label": "Add a comment" }, + who, + input, + h(this.doc, "div", { class: "pk-actions" }, h(this.doc, "span", { class: "tip" }, "Shift+Enter for a new line"), cancel, add), + ); + const card: Card = { node, input, element }; + const commit = (): void => { + void this.commit(card, data); + }; + cancel.addEventListener("click", () => { + this.closeCard(); + }); + add.addEventListener("click", commit); + input.addEventListener("keydown", (event) => { + // Keep the page's own shortcuts from reacting to typing. + event.stopPropagation(); + if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + commit(); + } + }); + for (const type of ["keyup", "keypress"] as const) { + input.addEventListener(type, (event) => { + event.stopPropagation(); + }); + } + this.card = card; + this.root.append(node); + this.placeCard(card); + setTimeout(() => { + input.focus(); + }, 0); + } + + private async commit(card: Card, data: Promise): Promise { + const resolved = await data; + if (this.card !== card) return; + const win = this.doc.defaultView; + const scroll = { x: win?.scrollX ?? 0, y: win?.scrollY ?? 0 }; + this.entries.push({ + element: card.element, + item: pickItem(card.element, resolved.component, resolved.source, scroll, card.input.value), + }); + this.closeCard(); + this.renderList(); + this.renderMarks(); + } + + private closeCard(): void { + this.card?.node.remove(); + this.card = null; + this.overlay?.hide(); + } + + private placeCard(card: Card): void { + const win = this.doc.defaultView; + const width = win?.innerWidth ?? 1024; + const height = win?.innerHeight ?? 768; + const rect = card.element.getBoundingClientRect(); + const left = Math.min(Math.max(8, rect.left), Math.max(8, width - CARD_WIDTH - 8)); + const below = rect.bottom + 8; + const top = below + CARD_HEIGHT < height ? below : Math.max(8, rect.top - CARD_HEIGHT - 8); + place(card.node, left, top); + } + + private renderMarks(): void { + const marks = this.marks; + if (marks === null) return; + marks.replaceChildren(); + this.entries.forEach((entry, index) => { + if (!entry.element.isConnected) return; + const rect = entry.element.getBoundingClientRect(); + const outline = h(this.doc, "div", { class: "pk-outline" }); + place(outline, rect.x, rect.y, rect.width, rect.height); + const marker = h(this.doc, "div", { class: "pk-marker", "aria-hidden": "true" }, String(index + 1)); + place(marker, Math.max(2, rect.x - 10), Math.max(2, rect.y - 10)); + marks.append(outline, marker); + }); + } + + private renderList(): void { + const list = this.list; + if (list === null) return; + const count = this.entries.length; + const clear = h(this.doc, "button", { type: "button", class: "ghost" }, "Clear"); + const copy = h(this.doc, "button", { type: "button", class: "primary" }, "Copy"); + const close = h(this.doc, "button", { type: "button", class: "ghost icon", "aria-label": "Close Pick and comment", title: "Close (Esc)" }, closeIcon(this.doc)); + clear.disabled = count === 0; + copy.disabled = count === 0; + clear.addEventListener("click", () => { + this.clear(); + }); + copy.addEventListener("click", () => { + void this.copy(); + }); + close.addEventListener("click", () => { + this.stop(); + }); + const header = h( + this.doc, + "header", + {}, + h(this.doc, "h2", {}, "Comments", h(this.doc, "span", { class: "pk-count" }, String(count))), + clear, + copy, + close, + ); + if (count === 0) { + list.replaceChildren(header, h(this.doc, "p", { class: "pk-hint" }, HINT)); + return; + } + const items = this.entries.map(({ item }, index) => { + const remove = h(this.doc, "button", { type: "button", class: "ghost icon", "aria-label": `Remove comment ${String(index + 1)}` }, closeIcon(this.doc)); + remove.addEventListener("click", () => { + this.remove(index); + }); + return h( + this.doc, + "li", + {}, + h(this.doc, "span", { class: "pk-num", "aria-hidden": "true" }, String(index + 1)), + h( + this.doc, + "div", + { class: "pk-body" }, + h(this.doc, "div", { class: "pk-comment" }, item.comment === "" ? "(no comment)" : item.comment), + h(this.doc, "div", { class: "pk-el mono" }, item.text === "" ? item.name : `${item.name} · "${item.text}"`), + ), + remove, + ); + }); + list.replaceChildren(header, h(this.doc, "ol", {}, ...items)); + } + + private toast(text: string): void { + const root = this.root; + if (root === null) return; + const node = h(this.doc, "div", { class: "toast", role: "status" }, text); + root.querySelector(".toast")?.remove(); + root.append(node); + if (this.toastTimer !== null) clearTimeout(this.toastTimer); + this.toastTimer = setTimeout(() => { + node.remove(); + }, TOAST_MS); + } +} diff --git a/apps/browser-extension/src/content/picker/format.test.ts b/apps/browser-extension/src/content/picker/format.test.ts new file mode 100644 index 0000000..5baf4b4 --- /dev/null +++ b/apps/browser-extension/src/content/picker/format.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; +import { buildPicksText, cleanComment, pickItem, pickText, type PickItem } from "./format"; + +function el(html: string): Element { + document.body.innerHTML = html; + const first = document.body.firstElementChild; + if (first === null) throw new Error("no element"); + return first; +} + +describe("pickText", () => { + it("prefers visible text", () => { + expect(pickText(el(""))).toBe("Send message"); + }); + + it("falls back to placeholder, then aria-label", () => { + expect(pickText(el(''))).toBe("Search docs"); + expect(pickText(el(''))).toBe("Close"); + }); + + it("reads button-type input values but never typed input values", () => { + expect(pickText(el(''))).toBe("Sign in"); + expect(pickText(el(''))).toBe(""); + }); +}); + +describe("cleanComment", () => { + it("keeps line breaks, trims, caps length", () => { + expect(cleanComment(" first\r\nsecond ")).toBe("first\nsecond"); + expect(cleanComment("x".repeat(1200))).toHaveLength(1000); + }); +}); + +describe("pickItem", () => { + it("uses the component name and page coordinates", () => { + const button = el('
').querySelector("button"); + if (button === null) throw new Error("no button"); + const item = pickItem( + button, + { name: "SubmitButton", ownerPath: ["ContactForm", "SubmitButton"] }, + { file: "src/Contact.tsx", line: 42, column: 7 }, + { x: 0, y: 500 }, + "Make it bigger", + ); + expect(item).toMatchObject({ + name: "SubmitButton", + tag: "button", + text: "Send", + selector: "form#contact > button.primary", + source: "src/Contact.tsx:42", + comment: "Make it bigger", + }); + expect(item.box.y).toBe(500); + }); + + it("falls back to a short label without a component", () => { + const item = pickItem(el('Docs'), null, null, { x: 0, y: 0 }, ""); + expect(item.name).toBe('link "Docs"'); + expect(item.source).toBeNull(); + }); +}); + +describe("buildPicksText", () => { + const base: PickItem = { + name: "SubmitButton", + tag: "button", + text: "Send", + selector: "form#contact > button.primary", + source: "src/Contact.tsx:42", + box: { x: 120, y: 860, width: 320, height: 40 }, + comment: "Make it bigger", + }; + + it("writes one compact plain-text item per pick, without inspect-only details", () => { + const text = buildPicksText("https://example.com/contact", [base, { ...base, name: "Logo", text: "", source: null, comment: "" }]); + expect(text).toBe( + [ + "Notes on elements of https://example.com/contact", + "Each item names one element, then my note. Under it: source file, tag, selector, text, size and page position (CSS px). An item without a note just points the element out.", + "", + "1. SubmitButton: Make it bigger", + ' src/Contact.tsx:42 · button · form#contact > button.primary · "Send" · 320×40 at 120,860', + "", + "2. Logo", + " button · form#contact > button.primary · 320×40 at 120,860", + "", + ].join("\n"), + ); + expect(text).not.toMatch(/Styles|Classes|Role|^#|\*\*/mu); + }); + + it("keeps a multi-line note inside its item", () => { + const text = buildPicksText("https://example.com", [{ ...base, comment: "Bigger\nAnd blue" }]); + expect(text).toContain("1. SubmitButton: Bigger\n And blue\n src/Contact.tsx:42"); + }); +}); diff --git a/apps/browser-extension/src/content/picker/format.ts b/apps/browser-extension/src/content/picker/format.ts new file mode 100644 index 0000000..6d691b8 --- /dev/null +++ b/apps/browser-extension/src/content/picker/format.ts @@ -0,0 +1,94 @@ +import type { ElementDetails } from "@snaphub/devtools-protocol/protocol"; +import { clip, selectorFor, shortLabel } from "../dom"; + +export const MAX_PICKS = 30; +export const MAX_COMMENT = 1000; + +/** What an agent needs to find one element again: no styles, classes or box model. */ +export type PickItem = { + name: string; + tag: string; + text: string; + selector: string; + source: string | null; + box: { x: number; y: number; width: number; height: number }; + comment: string; +}; + +const TEXT_ATTRIBUTES = ["placeholder", "aria-label", "alt", "title"] as const; + +/** Visible text, or the placeholder/label an empty element shows instead. Input values are never read. */ +export function pickText(element: Element): string { + const text = clip(element.textContent, 120); + if (text !== "") return text; + for (const name of TEXT_ATTRIBUTES) { + const value = element.getAttribute(name); + if (value !== null && value.trim() !== "") return clip(value, 120); + } + const type = element.getAttribute("type")?.toLowerCase(); + if (element.tagName === "INPUT" && (type === "button" || type === "submit" || type === "reset")) { + return clip(element.getAttribute("value") ?? "", 120); + } + return ""; +} + +/** Keeps line breaks the user typed; trims and caps the length. */ +export function cleanComment(value: string): string { + const trimmed = value.replace(/\r\n?/g, "\n").trim(); + return trimmed.length > MAX_COMMENT ? trimmed.slice(0, MAX_COMMENT) : trimmed; +} + +export function pickItem( + element: Element, + component: ElementDetails["component"], + source: ElementDetails["source"], + scroll: { x: number; y: number }, + comment: string, +): PickItem { + const rect = element.getBoundingClientRect(); + return { + name: clip(component?.name ?? shortLabel(element), 80), + tag: element.tagName.toLowerCase(), + text: pickText(element), + selector: clip(selectorFor(element), 300), + source: source === null ? null : `${source.file}:${String(source.line)}`, + box: { + x: Math.round(rect.x + scroll.x), + y: Math.round(rect.y + scroll.y), + width: Math.round(rect.width), + height: Math.round(rect.height), + }, + comment: cleanComment(comment), + }; +} + +/** Continuation lines of a note or detail sit under the item number. */ +const INDENT = " "; + +function itemLines(item: PickItem, index: number): string[] { + const { box } = item; + const [first = "", ...rest] = item.comment.split("\n"); + const head = `${String(index + 1)}. ${item.name}${first === "" ? "" : `: ${first}`}`; + const details = [ + item.source, + item.tag, + item.selector, + item.text === "" ? null : `"${item.text}"`, + `${String(box.width)}×${String(box.height)} at ${String(box.x)},${String(box.y)}`, + ].filter((part): part is string => part !== null); + return [head, ...rest.map((line) => INDENT + line), INDENT + details.join(" · ")]; +} + +/** + * The plain text the Copy button puts on the clipboard. The first two lines + * say what it is, so it can be pasted into an agent without a prompt. A pick + * can be a request or just a pointer to an element, so nothing assumes a change. + */ +export function buildPicksText(url: string, items: readonly PickItem[]): string { + const sections = items.flatMap((item, index) => ["", ...itemLines(item, index)]); + return [ + `Notes on elements of ${url}`, + "Each item names one element, then my note. Under it: source file, tag, selector, text, size and page position (CSS px). An item without a note just points the element out.", + ...sections, + ].join("\n") + "\n"; +} diff --git a/apps/browser-extension/src/content/picker/styles.ts b/apps/browser-extension/src/content/picker/styles.ts new file mode 100644 index 0000000..bcedf0c --- /dev/null +++ b/apps/browser-extension/src/content/picker/styles.ts @@ -0,0 +1,33 @@ +/** Picker rules, added after THEME_CSS and INSPECTOR_CSS. Class names are pk-prefixed. */ +export const PICKER_CSS = ` +.pk-outline { position: fixed; border: 1.5px dashed var(--accent); border-radius: 3px; pointer-events: none; } +.pk-marker { position: fixed; width: 20px; height: 20px; border-radius: 10px; display: grid; place-items: center; background: var(--accent); color: var(--accent-ink); font-weight: 600; font-size: 11px; box-shadow: 0 1px 4px rgb(0 0 0 / 35%); pointer-events: none; } +.pk-card { position: fixed; width: 280px; padding: 10px; display: flex; flex-direction: column; gap: 8px; animation: pk-in 180ms var(--ease-arrive); } +.pk-who { color: var(--c60); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pk-card textarea { font: inherit; width: 100%; min-height: 64px; resize: vertical; padding: 6px 8px; color: var(--fg); background: var(--c4); border: 1px solid var(--c10); border-radius: 6px; } +.pk-card textarea::placeholder { color: var(--c45); } +.pk-card textarea:focus-visible { outline: 2px solid color-mix(in oklab, var(--accent) 70%, transparent); outline-offset: 0; border-color: transparent; } +.pk-actions { display: flex; justify-content: flex-end; align-items: center; gap: 6px; } +.pk-actions .tip { margin-right: auto; color: var(--c45); font-size: 11px; } +.pk-list { position: fixed; right: 16px; bottom: 16px; width: 300px; max-height: min(60vh, 420px); display: flex; flex-direction: column; overflow: hidden; animation: pk-in 180ms var(--ease-arrive); } +.pk-list header { display: flex; align-items: center; gap: 4px; height: 40px; padding: 0 8px 0 12px; border-bottom: 1px solid var(--c8); } +.pk-list h2 { margin: 0; flex: 1; font-size: 13px; font-weight: 600; } +.pk-count { color: var(--c45); font-weight: 500; margin-left: 6px; font-variant-numeric: tabular-nums; } +.pk-list ol { list-style: none; margin: 0; padding: 4px; overflow: auto; overscroll-behavior: contain; } +.pk-list li { display: flex; align-items: flex-start; gap: 8px; padding: 6px 4px 6px 8px; border-radius: 6px; } +.pk-list li:hover { background: var(--c4); } +.pk-list li button { opacity: 0; } +.pk-list li:hover button, .pk-list li button:focus-visible { opacity: 1; } +.pk-num { flex: 0 0 18px; height: 18px; margin-top: 1px; border-radius: 9px; display: grid; place-items: center; background: var(--accent); color: var(--accent-ink); font-weight: 600; font-size: 10px; } +.pk-body { flex: 1; min-width: 0; } +.pk-comment { white-space: pre-wrap; overflow-wrap: anywhere; } +.pk-el { color: var(--c45); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pk-hint { margin: 0; color: var(--c60); padding: 12px; } +@keyframes pk-in { from { opacity: 0; transform: scale(0.97); } to { opacity: 1; transform: scale(1); } } +@media (prefers-reduced-motion: reduce) { + .pk-card, .pk-list { animation-name: pk-fade; } + .pk-list li button { opacity: 1; } + @keyframes pk-fade { from { opacity: 0; } to { opacity: 1; } } +} +@media (hover: none) { .pk-list li button { opacity: 1; } } +`; diff --git a/apps/browser-extension/src/content/probe/controller.test.ts b/apps/browser-extension/src/content/probe/controller.test.ts new file mode 100644 index 0000000..6e6aa64 --- /dev/null +++ b/apps/browser-extension/src/content/probe/controller.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hostShadow } from "../shadow"; +import { ProbeController, type ProbeDeps, type ProbeKind } from "./controller"; + +type Setup = { probe: ProbeController; shadow: ShadowRoot; target: Element; copied: string[] }; + +function setup(kind: ProbeKind, extra: Partial = {}): Setup { + document.body.innerHTML = + '

Hello

'; + const copied: string[] = []; + const deps: Partial = { + writeText: (text) => { + copied.push(text); + return Promise.resolve(); + }, + accent: () => Promise.resolve("#d9ff43"), + fonts: () => undefined, + pickPixel: null, + ...extra, + }; + const probe = new ProbeController(kind, document, deps); + probe.start(); + const target = document.querySelector("p.lead"); + if (target === null) throw new Error("no target"); + return { probe, shadow: hostShadow(document), target, copied }; +} + +function button(shadow: ShadowRoot, name: string): HTMLButtonElement | undefined { + return [...shadow.querySelectorAll("button")].find((b) => (b.getAttribute("aria-label") ?? b.textContent) === name); +} + +function tip(shadow: ShadowRoot): HTMLElement { + const found = shadow.querySelector(".pb-tip"); + if (!(found instanceof HTMLElement)) throw new Error("no tip"); + return found; +} + +afterEach(() => { + document.documentElement.querySelector("capkit-inspector-host")?.remove(); +}); + +describe("Font tool", () => { + it("previews the hovered element's font", () => { + const { probe, shadow, target } = setup("font"); + probe.preview(target, 10, 10); + expect(tip(shadow).hidden).toBe(false); + expect(tip(shadow).textContent).toContain("Georgia"); + expect(tip(shadow).textContent).toContain("18px"); + expect(tip(shadow).textContent).toContain("#ff0000"); + probe.stop(); + }); + + it("copies the font as CSS on click", async () => { + const { probe, shadow, target, copied } = setup("font"); + await probe.choose(target, 10, 10); + expect(copied[0]).toContain("font-family: Georgia, serif;"); + expect(copied[0]).toContain("color: #ff0000;"); + expect(shadow.querySelector(".toast")?.textContent).toBe("Copied font CSS"); + probe.stop(); + }); + + it("closes with Escape and from its close button", () => { + const first = setup("font"); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(first.probe.isActive).toBe(false); + const second = setup("font"); + button(second.shadow, "Close Font")?.click(); + expect(second.probe.isActive).toBe(false); + }); +}); + +describe("Colour tool", () => { + it("locks the element and copies a chosen colour as HEX", async () => { + const { probe, shadow, target, copied } = setup("color"); + await probe.choose(target, 10, 10); + expect(probe.lockedElement).toBe(target); + button(shadow, "Copy Background #0000ff")?.click(); + await vi.waitFor(() => { + expect(copied).toEqual(["#0000ff"]); + }); + expect(shadow.querySelector(".toast")?.textContent).toBe("Copied #0000ff"); + probe.stop(); + }); + + it("ignores hover while locked; Escape unlocks before closing", async () => { + const { probe, shadow, target } = setup("color"); + await probe.choose(target, 10, 10); + const other = document.createElement("div"); + document.body.append(other); + probe.preview(other, 0, 0); + expect(button(shadow, "Copy Background #0000ff")).toBeDefined(); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(probe.lockedElement).toBeNull(); + expect(probe.isActive).toBe(true); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + expect(probe.isActive).toBe(false); + }); + + it("hides the eyedropper button when the browser has none", () => { + const { probe, shadow } = setup("color"); + expect(shadow.querySelector('[aria-keyshortcuts="E"]')).toBeNull(); + probe.stop(); + }); + + it("copies a pixel from the eyedropper with E", async () => { + const pickPixel = vi.fn((): Promise => Promise.resolve("#ABCDEF")); + const { probe, shadow, copied } = setup("color", { pickPixel }); + expect(shadow.querySelector('[aria-keyshortcuts="E"]')).not.toBeNull(); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "e" })); + await vi.waitFor(() => { + expect(copied).toEqual(["#abcdef"]); + }); + probe.stop(); + }); + + it("copies nothing when the eyedropper is cancelled", async () => { + const pickPixel = vi.fn((): Promise => Promise.resolve(null)); + const { probe, copied } = setup("color", { pickPixel }); + await probe.pickPixel(); + expect(pickPixel).toHaveBeenCalledOnce(); + expect(copied).toEqual([]); + probe.stop(); + }); +}); diff --git a/apps/browser-extension/src/content/probe/controller.ts b/apps/browser-extension/src/content/probe/controller.ts new file mode 100644 index 0000000..148d410 --- /dev/null +++ b/apps/browser-extension/src/content/probe/controller.ts @@ -0,0 +1,373 @@ +import { readAccent } from "../../accent"; +import { HOST_TAG } from "../bridge"; +import { shortLabel } from "../dom"; +import { h, place } from "../inspector/dom"; +import { hostShadow, installFonts } from "../shadow"; +import { THEME_CSS, closeIcon } from "../theme"; +import { fontCssText, readColors, readFont, type ColorSwatch } from "./read"; +import { PROBE_CSS } from "./styles"; + +export type ProbeKind = "font" | "color"; + +const TOAST_MS = 1600; +const TIP_WIDTH = 240; +const TIP_GAP = 14; +const SWALLOWED = ["pointerdown", "pointerup", "mousedown", "mouseup", "dblclick", "auxclick"] as const; + +/** Opens Chrome's eyedropper and resolves with the picked sRGB HEX, or null when cancelled. */ +export type PixelPicker = () => Promise; + +export type ProbeDeps = { + writeText: (text: string) => Promise; + accent: () => Promise; + fonts: (doc: Document) => void; + /** Null when the browser has no EyeDropper. */ + pickPixel: PixelPicker | null; +}; + +type EyeDropperLike = { open: () => Promise<{ sRGBHex: string }> }; + +function browserPixelPicker(): PixelPicker | null { + const ctor: unknown = Reflect.get(globalThis, "EyeDropper"); + if (typeof ctor !== "function") return null; + return async (): Promise => { + // EyeDropper is missing from the TypeScript DOM lib; `typeof` above checked it exists. + const dropper = Reflect.construct(ctor, []) as EyeDropperLike; + try { + return (await dropper.open()).sRGBHex; + } catch { + return null; // Esc cancels with AbortError. + } + }; +} + +function defaultDeps(): ProbeDeps { + return { + writeText: (text) => navigator.clipboard.writeText(text), + accent: readAccent, + fonts: installFonts, + pickPixel: browserPixelPicker(), + }; +} + +const TITLES: Record = { font: "Font", color: "Colour" }; + +/** + * Hover tools. Font: hover text to read its font, click copies the CSS. + * Colour: hover to read an element's colours, click locks it so each colour can be copied; + * the eyedropper (E) copies any pixel. Colours are always HEX. + */ +export class ProbeController { + private active = false; + private frame: HTMLElement | null = null; + private root: HTMLElement | null = null; + private outline: HTMLElement | null = null; + private tip: HTMLElement | null = null; + private locked: Element | null = null; + private dropping = false; + private toastTimer: ReturnType | null = null; + private readonly deps: ProbeDeps; + + constructor( + private readonly kind: ProbeKind, + private readonly doc: Document = document, + deps: Partial = {}, + ) { + this.deps = { ...defaultDeps(), ...deps }; + } + + get isActive(): boolean { + return this.active; + } + + get lockedElement(): Element | null { + return this.locked; + } + + toggle(): void { + if (this.active) this.stop(); + else this.start(); + } + + start(): void { + if (this.active) return; + this.active = true; + this.deps.fonts(this.doc); + const style = h(this.doc, "style", {}, THEME_CSS, PROBE_CSS); + const root = h(this.doc, "div", { class: "root" }); + this.root = root; + void this.deps.accent().then((accent) => { + root.style.setProperty("--accent", accent); + }); + this.outline = h(this.doc, "div", { class: "outline" }); + this.outline.hidden = true; + this.tip = h(this.doc, "div", { class: "pb-tip card" }); + this.tip.hidden = true; + root.append(this.outline, this.tip, this.renderBar()); + this.frame = h(this.doc, "div", { style: "display:contents" }, style, root); + hostShadow(this.doc).append(this.frame); + const win = this.doc.defaultView; + win?.addEventListener("pointermove", this.onMove, true); + win?.addEventListener("click", this.onClick, true); + win?.addEventListener("keydown", this.onKey, true); + win?.addEventListener("scroll", this.onScroll, true); + for (const type of SWALLOWED) win?.addEventListener(type, this.swallow, true); + } + + stop(): void { + if (!this.active) return; + this.active = false; + const win = this.doc.defaultView; + win?.removeEventListener("pointermove", this.onMove, true); + win?.removeEventListener("click", this.onClick, true); + win?.removeEventListener("keydown", this.onKey, true); + win?.removeEventListener("scroll", this.onScroll, true); + for (const type of SWALLOWED) win?.removeEventListener(type, this.swallow, true); + if (this.toastTimer !== null) clearTimeout(this.toastTimer); + this.frame?.remove(); + this.frame = null; + this.root = null; + this.outline = null; + this.tip = null; + this.locked = null; + } + + /** Hover preview for an element at a pointer position (CSS px). */ + preview(element: Element, x: number, y: number): void { + if (this.locked !== null) return; + this.showOutline(element); + this.fillTip(element, false); + this.placeTip(x, y); + } + + /** Font: copies the element's font CSS. Colour: locks the element so each colour can be copied. */ + async choose(element: Element, x: number, y: number): Promise { + if (this.kind === "font") { + this.showOutline(element); + await this.copy(fontCssText(readFont(element)), "Copied font CSS"); + return; + } + this.locked = element; + this.showOutline(element, true); + this.fillTip(element, true); + this.placeTip(x, y); + this.tip?.querySelector("button")?.focus(); + } + + unlock(): void { + this.locked = null; + if (this.outline !== null) { + this.outline.classList.remove("locked"); + this.outline.hidden = true; + } + if (this.tip !== null) { + this.tip.hidden = true; + this.tip.classList.remove("locked"); + } + } + + async pickPixel(): Promise { + const pick = this.deps.pickPixel; + if (pick === null || this.dropping) return; + this.dropping = true; + const tipWasShown = this.tip !== null && !this.tip.hidden; + if (this.tip !== null) this.tip.hidden = true; + const hex = await pick(); + this.dropping = false; + if (!this.active) return; + if (this.tip !== null && this.locked !== null && tipWasShown) this.tip.hidden = false; + if (hex === null) return; + const value = hex.toLowerCase(); + await this.copy(value, `Copied ${value}`, value); + } + + private isOwn(target: EventTarget | null): boolean { + return target instanceof Element && target.localName === HOST_TAG; + } + + private target(event: MouseEvent): Element | null { + const element = this.doc.elementFromPoint(event.clientX, event.clientY); + return element === null || this.isOwn(element) ? null : element; + } + + private readonly swallow = (event: Event): void => { + if (this.isOwn(event.target)) return; + event.preventDefault(); + event.stopPropagation(); + }; + + private readonly onMove = (event: PointerEvent): void => { + if (this.dropping || this.locked !== null) return; + const element = this.target(event); + if (element === null) { + this.unlock(); + return; + } + this.preview(element, event.clientX, event.clientY); + }; + + private readonly onClick = (event: MouseEvent): void => { + if (this.isOwn(event.target)) return; + event.preventDefault(); + event.stopPropagation(); + const element = this.target(event); + if (element === null) return; + this.locked = null; + void this.choose(element, event.clientX, event.clientY); + }; + + private readonly onKey = (event: KeyboardEvent): void => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + if (this.locked !== null) this.unlock(); + else this.stop(); + return; + } + const plain = !event.ctrlKey && !event.metaKey && !event.altKey; + if (this.kind === "color" && plain && event.key.toLowerCase() === "e" && !isTyping(event)) { + event.preventDefault(); + event.stopPropagation(); + void this.pickPixel(); + } + }; + + private readonly onScroll = (): void => { + if (this.locked?.isConnected === true) this.showOutline(this.locked, true); + else this.unlock(); + }; + + private renderBar(): HTMLElement { + const d = this.doc; + const close = h(d, "button", { type: "button", class: "ghost icon", "aria-label": `Close ${TITLES[this.kind]}`, title: "Close (Esc)" }, closeIcon(d)); + close.addEventListener("click", () => { + this.stop(); + }); + const tip = h(d, "span", { class: "tip" }, this.kind === "font" ? "Hover text, click to copy CSS" : "Hover to read, click to lock"); + const parts: Node[] = [h(d, "span", { class: "title" }, TITLES[this.kind]), h(d, "span", { class: "sep" }), tip]; + if (this.kind === "color" && this.deps.pickPixel !== null) { + const dropper = h(d, "button", { type: "button", "aria-keyshortcuts": "E" }, "Pick any pixel", h(d, "kbd", { "aria-hidden": "true" }, "E")); + dropper.addEventListener("click", () => { + void this.pickPixel(); + }); + parts.push(dropper); + } + parts.push(close); + return h(d, "div", { class: "bar card", role: "toolbar", "aria-label": `${TITLES[this.kind]} tool` }, ...parts); + } + + private showOutline(element: Element, locked = false): void { + const outline = this.outline; + if (outline === null) return; + const rect = element.getBoundingClientRect(); + place(outline, rect.x, rect.y, rect.width, rect.height); + outline.classList.toggle("locked", locked); + outline.hidden = false; + } + + private fillTip(element: Element, interactive: boolean): void { + const tip = this.tip; + if (tip === null) return; + tip.classList.toggle("locked", interactive); + tip.hidden = false; + tip.replaceChildren(...(this.kind === "font" ? this.fontTip(element) : this.colorTip(element, interactive))); + } + + private fontTip(element: Element): Node[] { + const d = this.doc; + const font = readFont(element); + const family = h(d, "div", { class: "pb-family" }, font.family); + // Page fonts are document-wide, so the name previews in its own face. + family.style.fontFamily = font.stack; + const swatch = h(d, "span", { class: "swatch" }); + swatch.style.backgroundColor = font.color; + const rows: [string, Node | string][] = [ + ["Size", font.size], + ["Weight", font.weight], + ["Line height", font.lineHeight], + ]; + if (font.letterSpacing !== "normal" && font.letterSpacing !== "0px") rows.push(["Letter spacing", font.letterSpacing]); + if (font.style !== "normal") rows.push(["Style", font.style]); + rows.push(["Colour", h(d, "span", {}, swatch, font.color)]); + const grid = h(d, "dl", { class: "pb-grid" }); + for (const [key, value] of rows) grid.append(h(d, "dt", {}, key), h(d, "dd", { class: "mono" }, value)); + return [family, h(d, "div", { class: "pb-el mono" }, shortLabel(element)), grid, h(d, "div", { class: "pb-foot" }, "Click to copy as CSS")]; + } + + private colorTip(element: Element, interactive: boolean): Node[] { + const d = this.doc; + const list = h(d, "ul", { class: "pb-swatches" }); + for (const swatch of readColors(element)) list.append(this.swatchRow(swatch, interactive)); + const head = h(d, "div", { class: "pb-head" }, h(d, "div", { class: "pb-el mono" }, shortLabel(element))); + if (interactive) { + const close = h(d, "button", { type: "button", class: "ghost icon", "aria-label": "Unlock element", title: "Unlock (Esc)" }, closeIcon(d)); + close.addEventListener("click", () => { + this.unlock(); + }); + head.append(close); + } + const foot = h(d, "div", { class: "pb-foot" }, interactive ? "Click a colour to copy it" : "Click to lock and copy"); + return [head, list, foot]; + } + + private swatchRow(swatch: ColorSwatch, interactive: boolean): HTMLElement { + const d = this.doc; + const chip = h(d, "span", { class: "swatch" }); + chip.style.backgroundColor = swatch.hex; + let value: HTMLElement; + if (interactive) { + const button = h(d, "button", { type: "button", class: "mono", "aria-label": `Copy ${swatch.name} ${swatch.hex}` }, swatch.hex); + button.addEventListener("click", () => { + void this.copy(swatch.hex, `Copied ${swatch.hex}`, swatch.hex); + }); + value = button; + } else { + value = h(d, "span", { class: "mono" }, swatch.hex); + } + return h(d, "li", {}, chip, h(d, "span", { class: "name" }, swatch.name), value); + } + + private placeTip(x: number, y: number): void { + const tip = this.tip; + const win = this.doc.defaultView; + if (tip === null) return; + const width = win?.innerWidth ?? 1024; + const height = win?.innerHeight ?? 768; + const tipHeight = tip.offsetHeight || 160; + const left = x + TIP_GAP + TIP_WIDTH < width ? x + TIP_GAP : Math.max(8, x - TIP_GAP - TIP_WIDTH); + const top = Math.min(Math.max(8, y + TIP_GAP), Math.max(8, height - tipHeight - 8)); + place(tip, left, top); + } + + private async copy(text: string, message: string, color?: string): Promise { + try { + await this.deps.writeText(text); + this.toast(message, color); + } catch { + this.toast("Couldn't copy"); + } + } + + private toast(text: string, color?: string): void { + const root = this.root; + if (root === null) return; + const node = h(this.doc, "div", { class: "toast card", role: "status" }); + if (color !== undefined) { + const swatch = h(this.doc, "span", { class: "swatch" }); + swatch.style.backgroundColor = color; + node.append(swatch); + } + node.append(this.doc.createTextNode(text)); + root.querySelector(".toast")?.remove(); + root.append(node); + if (this.toastTimer !== null) clearTimeout(this.toastTimer); + this.toastTimer = setTimeout(() => { + node.remove(); + }, TOAST_MS); + } +} + +function isTyping(event: KeyboardEvent): boolean { + const target = event.composedPath()[0]; + return target instanceof HTMLElement && (target.isContentEditable || target.localName === "input" || target.localName === "textarea"); +} diff --git a/apps/browser-extension/src/content/probe/read.test.ts b/apps/browser-extension/src/content/probe/read.test.ts new file mode 100644 index 0000000..92f5756 --- /dev/null +++ b/apps/browser-extension/src/content/probe/read.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { firstFamily, fontCssText, readColors, readFont, rgbaToHex, toHex, type FontInfo } from "./read"; + +const base: FontInfo = { + family: "Inter", + stack: '"Inter", sans-serif', + size: "14px", + weight: "500", + lineHeight: "20px", + letterSpacing: "normal", + style: "normal", + color: "#111111", +}; + +function only(selector: string, type: new () => T): T { + const found = document.querySelector(selector); + if (!(found instanceof type)) throw new Error(`missing ${selector}`); + return found; +} + +describe("colour to HEX", () => { + it("writes opaque colours as 6 digits and translucent ones as 8", () => { + expect(rgbaToHex({ r: 217, g: 255, b: 67, a: 1 })).toBe("#d9ff43"); + expect(rgbaToHex({ r: 0, g: 0, b: 0, a: 0.5 })).toBe("#00000080"); + }); + + it("converts rgb() and rgba()", () => { + expect(toHex("rgb(255, 0, 0)", document)).toBe("#ff0000"); + expect(toHex("rgba(0, 0, 255, 0.25)", document)).toBe("#0000ff40"); + }); +}); + +describe("font", () => { + it("takes the first family without quotes", () => { + expect(firstFamily('"Geist Variable", system-ui')).toBe("Geist Variable"); + expect(firstFamily("Arial")).toBe("Arial"); + }); + + it("copies family, size, weight, line height and colour", () => { + expect(fontCssText(base)).toBe('font-family: "Inter", sans-serif;\nfont-size: 14px;\nfont-weight: 500;\nline-height: 20px;\ncolor: #111111;'); + }); + + it("adds letter spacing and style only when set", () => { + const text = fontCssText({ ...base, letterSpacing: "0.5px", style: "italic" }); + expect(text).toContain("letter-spacing: 0.5px;"); + expect(text).toContain("font-style: italic;"); + }); + + it("reads an element's computed font", () => { + document.body.innerHTML = '

Hi

'; + const font = readFont(only("p", HTMLParagraphElement)); + expect(font.family).toBe("Georgia"); + expect(font.size).toBe("18px"); + expect(font.color).toBe("#0a141e"); + }); +}); + +describe("readColors", () => { + it("lists text, background and a visible border", () => { + document.body.innerHTML = '
x
'; + expect(readColors(only("div", HTMLDivElement))).toEqual([ + { name: "Text", hex: "#ffffff" }, + { name: "Background", hex: "#000000" }, + { name: "Border", hex: "#ff0000" }, + ]); + }); + + it("uses the background behind a transparent element", () => { + document.body.innerHTML = '
x
'; + expect(readColors(only("span", HTMLSpanElement))).toContainEqual({ name: "Background (behind)", hex: "#008000" }); + }); +}); diff --git a/apps/browser-extension/src/content/probe/read.ts b/apps/browser-extension/src/content/probe/read.ts new file mode 100644 index 0000000..db8d13e --- /dev/null +++ b/apps/browser-extension/src/content/probe/read.ts @@ -0,0 +1,96 @@ +import { effectiveBackground, parseColor, type Rgba } from "../contrast"; + +export type FontInfo = { + family: string; + stack: string; + size: string; + weight: string; + lineHeight: string; + letterSpacing: string; + style: string; + color: string; +}; + +export type ColorSwatch = { name: string; hex: string }; + +function hex2(value: number): string { + return Math.round(Math.min(255, Math.max(0, value))).toString(16).padStart(2, "0"); +} + +export function rgbaToHex({ r, g, b, a }: Rgba): string { + const base = `#${hex2(r)}${hex2(g)}${hex2(b)}`; + return a < 1 ? `${base}${hex2(a * 255)}` : base; +} + +/** + * Any computed CSS colour as HEX. Chrome reports oklch()/color() values as written, so + * those are painted on a 1px canvas and read back (sRGB, gamut-clipped). + */ +export function toHex(value: string, doc: Document): string { + const parsed = parseColor(value); + if (parsed !== null) return rgbaToHex(parsed); + const context = doc.createElement("canvas").getContext("2d", { willReadFrequently: true }); + if (context === null) return value.trim(); + context.clearRect(0, 0, 1, 1); + context.fillStyle = value; + context.fillRect(0, 0, 1, 1); + const [r = 0, g = 0, b = 0, a = 255] = context.getImageData(0, 0, 1, 1).data; + return rgbaToHex({ r, g, b, a: a / 255 }); +} + +/** First family in a font-family list, without quotes. */ +export function firstFamily(stack: string): string { + const first = stack.split(",")[0] ?? ""; + return first.trim().replace(/^["']|["']$/g, ""); +} + +export function readFont(element: Element): FontInfo { + const style = getComputedStyle(element); + return { + family: firstFamily(style.fontFamily), + stack: style.fontFamily, + size: style.fontSize, + weight: style.fontWeight, + lineHeight: style.lineHeight, + letterSpacing: style.letterSpacing, + style: style.fontStyle, + color: toHex(style.color, element.ownerDocument), + }; +} + +/** The CSS a click copies; default-valued letter spacing and style are left out. */ +export function fontCssText(font: FontInfo): string { + const lines = [ + `font-family: ${font.stack};`, + `font-size: ${font.size};`, + `font-weight: ${font.weight};`, + `line-height: ${font.lineHeight};`, + ]; + if (font.letterSpacing !== "normal" && font.letterSpacing !== "0px") lines.push(`letter-spacing: ${font.letterSpacing};`); + if (font.style !== "normal") lines.push(`font-style: ${font.style};`); + lines.push(`color: ${font.color};`); + return lines.join("\n"); +} + +function visible(value: string): boolean { + const parsed = parseColor(value); + return parsed === null ? value !== "transparent" && value !== "none" && value !== "" : parsed.a > 0; +} + +/** Text, background, border and SVG paint colours of one element, as HEX, duplicates kept apart by name. */ +export function readColors(element: Element): ColorSwatch[] { + const doc = element.ownerDocument; + const style = getComputedStyle(element); + const swatches: ColorSwatch[] = [{ name: "Text", hex: toHex(style.color, doc) }]; + if (visible(style.backgroundColor)) swatches.push({ name: "Background", hex: toHex(style.backgroundColor, doc) }); + else swatches.push({ name: "Background (behind)", hex: rgbaToHex(effectiveBackground(element)) }); + const border = Number.parseFloat(style.borderTopWidth) > 0 && style.borderTopStyle !== "none"; + if (border && visible(style.borderTopColor)) swatches.push({ name: "Border", hex: toHex(style.borderTopColor, doc) }); + if (element instanceof SVGElement) { + const fill = style.getPropertyValue("fill"); + const stroke = style.getPropertyValue("stroke"); + if (visible(fill)) swatches.push({ name: "Fill", hex: toHex(fill, doc) }); + if (visible(stroke)) swatches.push({ name: "Stroke", hex: toHex(stroke, doc) }); + } + return swatches; +} diff --git a/apps/browser-extension/src/content/probe/styles.ts b/apps/browser-extension/src/content/probe/styles.ts new file mode 100644 index 0000000..637dd5a --- /dev/null +++ b/apps/browser-extension/src/content/probe/styles.ts @@ -0,0 +1,22 @@ +/** Font and Colour tool rules, added after THEME_CSS. Class names are pb-prefixed. */ +export const PROBE_CSS = ` +.pb-tip { position: fixed; width: 240px; padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; pointer-events: none; } +.pb-tip.locked { pointer-events: auto; animation: pb-in 160ms var(--ease-arrive); } +.pb-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; } +.pb-family { font-size: 15px; font-weight: 500; line-height: 1.3; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pb-el { color: var(--c45); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pb-grid { display: grid; grid-template-columns: auto 1fr; gap: 2px 12px; margin: 0; } +.pb-grid dt { color: var(--c60); } +.pb-grid dd { margin: 0; color: var(--fg); display: flex; align-items: center; min-width: 0; overflow-wrap: anywhere; } +.pb-foot { color: var(--c45); font-size: 11px; padding-top: 6px; border-top: 1px solid var(--c8); } +.pb-swatches { display: flex; flex-direction: column; gap: 2px; margin: 0; padding: 0; list-style: none; } +.pb-swatches li { display: flex; align-items: center; gap: 8px; height: 24px; } +.pb-swatches .swatch { width: 14px; height: 14px; margin: 0; border-radius: 4px; } +.pb-swatches .name { flex: 1; color: var(--c60); } +.pb-swatches button { height: 22px; padding: 0 6px; } +@keyframes pb-in { from { opacity: 0; transform: scale(0.97); } to { opacity: 1; transform: scale(1); } } +@media (prefers-reduced-motion: reduce) { + .pb-tip.locked { animation-name: pb-fade; } + @keyframes pb-fade { from { opacity: 0; } to { opacity: 1; } } +} +`; diff --git a/apps/browser-extension/src/content/shadow.ts b/apps/browser-extension/src/content/shadow.ts new file mode 100644 index 0000000..294d4b5 --- /dev/null +++ b/apps/browser-extension/src/content/shadow.ts @@ -0,0 +1,29 @@ +import { fontFaceCss } from "../fonts"; +import { ensureHost } from "./mainClient"; + +const FONT_STYLE_ID = "capkit-fonts"; +const shadows = new WeakMap(); + +/** The one closed shadow root on the host; every page tool mounts its own frame in it. */ +export function hostShadow(doc: Document): ShadowRoot { + const { host } = ensureHost(doc); + let shadow = shadows.get(host); + if (shadow === undefined) { + shadow = host.attachShadow({ mode: "closed" }); + shadows.set(host, shadow); + } + return shadow; +} + +/** + * Chrome ignores @font-face inside shadow roots, so the faces go in the page head once. + * The family names are CapKit-only, so page text never changes. + */ +export function installFonts(doc: Document, url: (path: string) => string = (path) => chrome.runtime.getURL(path)): void { + if (doc.getElementById(FONT_STYLE_ID) !== null) return; + const style = doc.createElement("style"); + style.id = FONT_STYLE_ID; + style.textContent = fontFaceCss(url); + // `doc.head` is typed non-null but is missing on XML and SVG documents. + (doc.querySelector("head") ?? doc.documentElement).append(style); +} diff --git a/apps/browser-extension/src/content/theme.ts b/apps/browser-extension/src/content/theme.ts new file mode 100644 index 0000000..15089e8 --- /dev/null +++ b/apps/browser-extension/src/content/theme.ts @@ -0,0 +1,114 @@ +import { MONO_STACK, SANS_STACK } from "../fonts"; + +/** + * Dashboard tokens for page tools: one hue, content/N over background-base, accent for + * selection, focus and the primary button only. Follows the system light/dark setting. + * Surfaces are opaque because they sit over arbitrary pages, not the dashboard glass. + */ +export const THEME_CSS = ` +:host { all: initial; } +*, *::before, *::after { box-sizing: border-box; } +.root { + --accent: #d9ff43; + --accent-ink: #12130f; + --bg: hsl(60 4% 10%); + --fg: hsl(60 4% 93%); + --danger: #f87171; + --success: #4ade80; + --shadow: 0 0 0 1px rgb(0 0 0 / 30%), 0 12px 32px -4px rgb(0 0 0 / 50%); + --c4: color-mix(in oklab, var(--fg) 4%, transparent); + --c6: color-mix(in oklab, var(--fg) 6%, transparent); + --c8: color-mix(in oklab, var(--fg) 8%, transparent); + --c10: color-mix(in oklab, var(--fg) 10%, transparent); + --c15: color-mix(in oklab, var(--fg) 15%, transparent); + --c45: color-mix(in oklab, var(--fg) 45%, transparent); + --c60: color-mix(in oklab, var(--fg) 60%, transparent); + --c80: color-mix(in oklab, var(--fg) 80%, transparent); + --surface: color-mix(in oklab, var(--fg) 3%, var(--bg)); + --ease-arrive: cubic-bezier(0.16, 1, 0.3, 1); + --ease-settle: cubic-bezier(0.22, 1, 0.36, 1); + position: fixed; inset: 0; pointer-events: none; + font: 400 12px/1.5 ${SANS_STACK}; + color: var(--fg); + -webkit-font-smoothing: antialiased; + font-synthesis: none; +} +@media (prefers-color-scheme: light) { + .root { + --bg: hsl(60 4% 97%); + --fg: hsl(60 4% 13%); + --danger: #dc2626; + --success: #15803d; + --shadow: 0 0 0 1px rgb(0 0 0 / 8%), 0 12px 32px -4px rgb(0 0 0 / 18%); + --surface: #fff; + } +} +.mono { font-family: ${MONO_STACK}; font-variant-numeric: tabular-nums; } +.card { + background: var(--surface); color: var(--fg); border-radius: 10px; box-shadow: var(--shadow); pointer-events: auto; +} +button { + display: inline-flex; align-items: center; justify-content: center; gap: 6px; height: 24px; padding: 0 8px; border: 0; border-radius: 6px; + font: 500 12px/1 ${SANS_STACK}; color: var(--fg); background: var(--c6); cursor: pointer; white-space: nowrap; + transition: transform 100ms ease-out, background-color 100ms ease-out, color 100ms ease-out, filter 100ms ease-out; +} +button:hover { background: var(--c10); } +button:active { transform: scale(0.97); } +button:disabled { opacity: 0.4; pointer-events: none; } +button.primary { background: var(--accent); color: var(--accent-ink); } +button.primary:hover { background: var(--accent); filter: brightness(0.95); } +button.ghost { background: transparent; color: var(--c60); } +button.ghost:hover { background: var(--c6); color: var(--fg); } +button.icon { width: 24px; padding: 0; } +button.icon svg { width: 14px; height: 14px; } +button.link { height: auto; padding: 0; background: none; border-radius: 3px; font-weight: 400; justify-content: flex-start; text-align: left; white-space: normal; } +button.link:hover { background: none; color: var(--fg); text-decoration: underline; text-underline-offset: 2px; } +button.link:active { transform: none; } +:focus-visible { outline: 2px solid color-mix(in oklab, var(--accent) 70%, transparent); outline-offset: 1px; } +kbd { display: inline-grid; place-items: center; min-width: 18px; height: 18px; padding: 0 4px; border-radius: 4px; background: var(--c8); color: var(--c80); font: 500 10px/1 ${MONO_STACK}; } +.toast { + position: fixed; left: 50%; bottom: 20px; transform: translate(-50%, 0); display: flex; align-items: center; gap: 8px; + padding: 8px 12px; border-radius: 8px; background: var(--surface); color: var(--fg); box-shadow: var(--shadow); font-weight: 500; + animation: ck-toast 200ms var(--ease-settle); +} +.toast .swatch { width: 12px; height: 12px; margin: 0; } +@keyframes ck-toast { from { opacity: 0; transform: translate(-50%, 6px); } to { opacity: 1; transform: translate(-50%, 0); } } +.swatch { display: inline-block; flex: none; width: 10px; height: 10px; margin-right: 6px; border-radius: 3px; box-shadow: inset 0 0 0 1px var(--c15); vertical-align: -1px; } +.chip { position: fixed; padding: 3px 6px; border-radius: 5px; background: var(--fg); color: var(--bg); white-space: nowrap; font-size: 11px; font-weight: 500; pointer-events: none; } +.outline { position: fixed; border: 1px solid var(--accent); border-radius: 2px; pointer-events: none; } +.outline.locked { border-width: 2px; } +.hint { margin: 0; color: var(--c60); padding: 10px 12px; } +.bar { + position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); display: flex; align-items: center; gap: 8px; padding: 4px 4px 4px 12px; + animation: ck-in 200ms var(--ease-arrive); +} +.bar .title { font-weight: 600; } +.bar .sep { width: 1px; height: 16px; background: var(--c10); } +.bar .tip { color: var(--c60); display: inline-flex; align-items: center; gap: 4px; } +@keyframes ck-in { from { opacity: 0; transform: translateX(-50%) translateY(6px); } to { opacity: 1; transform: translateX(-50%); } } +@media (prefers-reduced-motion: reduce) { + button, button:active { transition: none; transform: none; } + .toast { animation-name: ck-fade; } + .bar { animation-name: ck-fade; } + @keyframes ck-fade { from { opacity: 0; } to { opacity: 1; } } +} +@media (forced-colors: active) { + .card, .toast, .chip { border: 1px solid CanvasText; } + .outline { border-color: Highlight; } +} +`; + +/** Close glyph used by every page tool. Static markup, never page data. */ +export function closeIcon(doc: Document): SVGSVGElement { + const ns = "http://www.w3.org/2000/svg"; + const svg = doc.createElementNS(ns, "svg"); + svg.setAttribute("viewBox", "0 0 16 16"); + svg.setAttribute("aria-hidden", "true"); + const path = doc.createElementNS(ns, "path"); + path.setAttribute("d", "M4 4l8 8M12 4l-8 8"); + path.setAttribute("stroke", "currentColor"); + path.setAttribute("stroke-width", "1.5"); + path.setAttribute("stroke-linecap", "round"); + svg.append(path); + return svg; +} diff --git a/apps/browser-extension/src/content/tools.test.ts b/apps/browser-extension/src/content/tools.test.ts new file mode 100644 index 0000000..79a3fa4 --- /dev/null +++ b/apps/browser-extension/src/content/tools.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { runTool, type ToolController } from "./tools"; + +function fake(active = false): ToolController & { active: boolean } { + return { + active, + get isActive(): boolean { + return this.active; + }, + start(): void { + this.active = true; + }, + stop(): void { + this.active = false; + }, + }; +} + +describe("runTool", () => { + it("starting one tool stops the others", () => { + const controllers = { inspect: fake(true), pick: fake(), font: fake(), color: fake() }; + runTool(controllers, "pick", "start"); + expect(controllers.pick.active).toBe(true); + expect(controllers.inspect.active).toBe(false); + }); + + it("toggle turns an active tool off", () => { + const controllers = { inspect: fake(), pick: fake(true), font: fake(), color: fake() }; + runTool(controllers, "pick", "toggle"); + expect(controllers.pick.active).toBe(false); + }); + + it("start keeps an active tool on", () => { + const controllers = { inspect: fake(true), pick: fake(), font: fake(), color: fake() }; + runTool(controllers, "inspect", "start"); + expect(controllers.inspect.active).toBe(true); + }); +}); + +describe("runTool with the probe tools", () => { + it("starting Colour stops Font", () => { + const controllers = { inspect: fake(), pick: fake(), font: fake(true), color: fake() }; + runTool(controllers, "color", "start"); + expect(controllers.color.active).toBe(true); + expect(controllers.font.active).toBe(false); + }); +}); diff --git a/apps/browser-extension/src/content/tools.ts b/apps/browser-extension/src/content/tools.ts new file mode 100644 index 0000000..bcf5082 --- /dev/null +++ b/apps/browser-extension/src/content/tools.ts @@ -0,0 +1,16 @@ +import type { Tool } from "../messages"; + +export type ToolController = { readonly isActive: boolean; start: () => void; stop: () => void }; + +/** Starts or toggles one page tool and stops the other, so the two never fight over clicks. */ +export function runTool(controllers: Record, tool: Tool, action: "toggle" | "start"): void { + const target = controllers[tool]; + if (action === "toggle" && target.isActive) { + target.stop(); + return; + } + for (const [name, controller] of Object.entries(controllers)) { + if (name !== tool) controller.stop(); + } + target.start(); +} diff --git a/apps/browser-extension/src/fonts.ts b/apps/browser-extension/src/fonts.ts new file mode 100644 index 0000000..460d6a5 --- /dev/null +++ b/apps/browser-extension/src/fonts.ts @@ -0,0 +1,13 @@ +/** + * Geist, the dashboard's typeface, bundled with the extension; no network fetch. + * Page tools use the "CapKit" family names so a page that ships its own Geist is untouched. + */ +export const SANS_STACK = '"CapKit Geist", "Geist Variable", "Segoe UI Variable", system-ui, sans-serif'; +export const MONO_STACK = '"CapKit Geist Mono", "Geist Mono Variable", "Cascadia Mono", ui-monospace, monospace'; + +export function fontFaceCss(url: (path: string) => string): string { + return [ + `@font-face{font-family:"CapKit Geist";src:url("${url("fonts/geist-latin-wght-normal.woff2")}") format("woff2");font-weight:100 900;font-display:swap}`, + `@font-face{font-family:"CapKit Geist Mono";src:url("${url("fonts/geist-mono-latin-wght-normal.woff2")}") format("woff2");font-weight:100 900;font-display:swap}`, + ].join(""); +} diff --git a/apps/browser-extension/src/menus.test.ts b/apps/browser-extension/src/menus.test.ts new file mode 100644 index 0000000..87adce5 --- /dev/null +++ b/apps/browser-extension/src/menus.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { MENU_PARENT, installMenus, menuTitle, toolForCommand, toolForMenu } from "./menus"; + +describe("context menu", () => { + it("maps item ids to tools", () => { + expect(toolForMenu("capkit-inspect")).toBe("inspect"); + expect(toolForMenu("capkit-pick")).toBe("pick"); + expect(toolForMenu("capkit-font")).toBe("font"); + expect(toolForMenu("capkit-color")).toBe("color"); + expect(toolForMenu(MENU_PARENT)).toBeNull(); + expect(toolForMenu(7)).toBeNull(); + }); + + it("maps shortcut commands to tools", () => { + expect(toolForCommand("toggle-inspector")).toBe("inspect"); + expect(toolForCommand("toggle-picker")).toBe("pick"); + expect(toolForCommand("toggle-font")).toBe("font"); + expect(toolForCommand("toggle-color")).toBe("color"); + expect(toolForCommand("_execute_action")).toBeNull(); + }); + + it("shows the shortcut when one is set", () => { + expect(menuTitle("Inspect", "Alt+Shift+I")).toBe("Inspect (Alt+Shift+I)"); + expect(menuTitle("Inspect", "")).toBe("Inspect"); + expect(menuTitle("Inspect", undefined)).toBe("Inspect"); + }); + + it("builds CapKit → Inspect / Pick and comment / Font / Colour on web pages only", async () => { + const created: chrome.contextMenus.CreateProperties[] = []; + let cleared = false; + await installMenus( + { + removeAll: () => { + cleared = true; + return Promise.resolve(); + }, + create: (properties) => { + created.push(properties); + }, + }, + new Map([["toggle-picker", "Alt+Shift+C"]]), + ); + expect(cleared).toBe(true); + expect(created.map((item) => [item.id, item.parentId, item.title])).toEqual([ + [MENU_PARENT, undefined, "CapKit"], + ["capkit-inspect", MENU_PARENT, "Inspect"], + ["capkit-pick", MENU_PARENT, "Pick and comment (Alt+Shift+C)"], + ["capkit-font", MENU_PARENT, "Font"], + ["capkit-color", MENU_PARENT, "Colour"], + ]); + for (const item of created) expect(item.documentUrlPatterns).toEqual(["http://*/*", "https://*/*"]); + }); +}); diff --git a/apps/browser-extension/src/menus.ts b/apps/browser-extension/src/menus.ts new file mode 100644 index 0000000..94b201f --- /dev/null +++ b/apps/browser-extension/src/menus.ts @@ -0,0 +1,48 @@ +import type { Tool } from "./messages"; + +export const MENU_PARENT = "capkit"; + +/** Right-click → CapKit → one item per page tool; each names the command whose shortcut it shows. */ +export const MENU_ITEMS = [ + { id: "capkit-inspect", title: "Inspect", tool: "inspect", command: "toggle-inspector" }, + { id: "capkit-pick", title: "Pick and comment", tool: "pick", command: "toggle-picker" }, + { id: "capkit-font", title: "Font", tool: "font", command: "toggle-font" }, + { id: "capkit-color", title: "Colour", tool: "color", command: "toggle-color" }, +] as const satisfies readonly { id: string; title: string; tool: Tool; command: string }[]; + +/** Tools need a real web page; Chrome blocks extensions on its own pages. */ +const PAGE_PATTERNS = ["http://*/*", "https://*/*"]; +const CONTEXTS: NonNullable = ["page", "frame", "selection", "link", "editable", "image", "video", "audio"]; + +export type MenuApi = { + removeAll: () => Promise; + create: (properties: chrome.contextMenus.CreateProperties) => void; +}; + +export function toolForMenu(id: string | number): Tool | null { + return MENU_ITEMS.find((item) => item.id === id)?.tool ?? null; +} + +export function toolForCommand(command: string): Tool | null { + return MENU_ITEMS.find((item) => item.command === command)?.tool ?? null; +} + +/** "Inspect (Alt+Shift+I)"; the plain title when the user removed the shortcut. */ +export function menuTitle(title: string, shortcut: string | undefined): string { + return shortcut === undefined || shortcut === "" ? title : `${title} (${shortcut})`; +} + +/** Rebuilds the menu, so a shortcut changed in chrome://extensions/shortcuts shows after the next start. */ +export async function installMenus(api: MenuApi, shortcuts: ReadonlyMap): Promise { + await api.removeAll(); + api.create({ id: MENU_PARENT, title: "CapKit", contexts: CONTEXTS, documentUrlPatterns: PAGE_PATTERNS }); + for (const item of MENU_ITEMS) { + api.create({ + id: item.id, + parentId: MENU_PARENT, + title: menuTitle(item.title, shortcuts.get(item.command)), + contexts: CONTEXTS, + documentUrlPatterns: PAGE_PATTERNS, + }); + } +} diff --git a/apps/browser-extension/src/messages.ts b/apps/browser-extension/src/messages.ts index 22770a0..4c09f1d 100644 --- a/apps/browser-extension/src/messages.ts +++ b/apps/browser-extension/src/messages.ts @@ -9,6 +9,10 @@ import { viewportPointSchema, } from "@snaphub/devtools-protocol/protocol"; +/** The page tools. Only one runs at a time. */ +export const toolSchema = z.enum(["inspect", "pick", "font", "color"]); +export type Tool = z.infer; + /** 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 }), @@ -19,7 +23,7 @@ export const pageRequestSchema = z.discriminatedUnion("kind", [ area: physicalRectSchema.optional(), }), z.strictObject({ kind: z.literal("findSensitive"), viewport: physicalRectSchema, area: physicalRectSchema }), - z.strictObject({ kind: z.literal("toggle") }), + z.strictObject({ kind: z.literal("tool"), tool: toolSchema, action: z.enum(["toggle", "start"]) }), z.strictObject({ kind: z.literal("ping") }), ]); export type PageRequest = z.infer; @@ -45,7 +49,7 @@ export const backgroundRequestSchema = z.discriminatedUnion("kind", [ 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("startTool"), tool: toolSchema }), z.strictObject({ kind: z.literal("siteAccess"), tabId: z.number().int().optional() }), ]); export type BackgroundRequest = z.infer; diff --git a/apps/browser-extension/src/popup/Popup.test.tsx b/apps/browser-extension/src/popup/Popup.test.tsx index 05ecc63..e38843e 100644 --- a/apps/browser-extension/src/popup/Popup.test.tsx +++ b/apps/browser-extension/src/popup/Popup.test.tsx @@ -101,49 +101,110 @@ describe("Popup", () => { expect(screen.getByRole("button", { name: "Allow on all sites" })).toBeInTheDocument(); }); - it("says when the page can't be inspected and disables Inspect page", async () => { + it("says when the page can't be inspected and disables every tool", 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(); + expect(screen.getByText("These tools work on web pages (http and https) only.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: /^Inspect/ })).toBeDisabled(); + expect(screen.getByRole("button", { name: /^Pick and comment/ })).toBeDisabled(); + expect(screen.getByRole("button", { name: /^Font/ })).toBeDisabled(); + expect(screen.getByRole("button", { name: /^Colour/ })).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 { send } = fake({ retry: { state: "connected" }, siteAccess: { state: "allowed" }, startTool: { ok: false } }); const user = userEvent.setup(); render(); await screen.findByText("Connected to CapKit"); await waitFor(() => { - expect(screen.getByRole("button", { name: "Inspect page" })).toBeEnabled(); + expect(screen.getByRole("button", { name: /^Inspect/ })).toBeEnabled(); }); - await user.click(screen.getByRole("button", { name: "Inspect page" })); + await user.click(screen.getByRole("button", { name: /^Inspect/ })); 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 () => { + it("offers the tools 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(); + expect(await screen.findByRole("button", { name: /^Inspect/ })).toBeEnabled(); }); - it("starts the inspector from Inspect page", async () => { + it("starts the inspector from its row", 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(); + expect(screen.getByRole("button", { name: /^Inspect/ })).toBeEnabled(); }); - await user.click(screen.getByRole("button", { name: "Inspect page" })); - expect(calls).toContainEqual({ kind: "inspectActiveTab" }); + await user.click(screen.getByRole("button", { name: /^Inspect/ })); + expect(calls).toContainEqual({ kind: "startTool", tool: "inspect" }); await waitFor(() => { expect(close).toHaveBeenCalled(); }); close.mockRestore(); }); + + it("starts Pick and comment from its button", async () => { + const close = vi.spyOn(window, "close").mockImplementation(() => undefined); + const { send, calls } = fake({ retry: { state: "unreachable" }, siteAccess: { state: "needs-access", origin: "https://example.com/*" } }); + const user = userEvent.setup(); + render(); + const pick = await screen.findByRole("button", { name: /^Pick and comment/ }); + await waitFor(() => { + expect(pick).toBeEnabled(); + }); + await user.click(pick); + expect(calls).toContainEqual({ kind: "startTool", tool: "pick" }); + await waitFor(() => { + expect(close).toHaveBeenCalled(); + }); + close.mockRestore(); + }); + + it("explains when Pick and comment can't start", async () => { + const close = vi.spyOn(window, "close").mockImplementation(() => undefined); + const { send } = fake({ retry: { state: "unreachable" }, siteAccess: { state: "allowed" }, startTool: { ok: false } }); + const user = userEvent.setup(); + render(); + const pick = await screen.findByRole("button", { name: /^Pick and comment/ }); + await waitFor(() => { + expect(pick).toBeEnabled(); + }); + await user.click(pick); + expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't start Pick and comment here."); + expect(close).not.toHaveBeenCalled(); + close.mockRestore(); + }); + it("starts the font and colour tools", async () => { + const close = vi.spyOn(window, "close").mockImplementation(() => undefined); + const { send, calls } = fake({ retry: { state: "unreachable" }, siteAccess: { state: "allowed" } }); + const user = userEvent.setup(); + render(); + const font = await screen.findByRole("button", { name: /^Font/ }); + await waitFor(() => { + expect(font).toBeEnabled(); + }); + await user.click(font); + await user.click(screen.getByRole("button", { name: /^Colour/ })); + expect(calls).toContainEqual({ kind: "startTool", tool: "font" }); + expect(calls).toContainEqual({ kind: "startTool", tool: "color" }); + close.mockRestore(); + }); + + it("shows each tool's shortcut", async () => { + const { send } = fake({ retry: { state: "unreachable" }, siteAccess: { state: "allowed" } }); + const loadShortcuts = (): Promise> => Promise.resolve(new Map([["toggle-font", "Alt+Shift+F"]])); + render(); + const font = await screen.findByRole("button", { name: /^Font/ }); + await waitFor(() => { + expect(font).toHaveAttribute("aria-keyshortcuts", "Alt+Shift+F"); + }); + expect(screen.getByRole("button", { name: /^Inspect/ })).not.toHaveAttribute("aria-keyshortcuts"); + }); }); diff --git a/apps/browser-extension/src/popup/Popup.tsx b/apps/browser-extension/src/popup/Popup.tsx index 888b9fb..a6aed0e 100644 --- a/apps/browser-extension/src/popup/Popup.tsx +++ b/apps/browser-extension/src/popup/Popup.tsx @@ -1,18 +1,98 @@ -import { useCallback, useEffect, useState, type ClipboardEvent, type SyntheticEvent, type ReactElement } from "react"; +import { useCallback, useEffect, useState, type ClipboardEvent, type ReactElement, type SyntheticEvent } from "react"; import { z } from "zod"; -import { linkStatusSchema, siteAccessSchema, type BackgroundRequest, type LinkStatus, type SiteAccess } from "../messages"; +import { MENU_ITEMS } from "../menus"; +import { linkStatusSchema, siteAccessSchema, type BackgroundRequest, type LinkStatus, type SiteAccess, type Tool } from "../messages"; export type Transport = (request: BackgroundRequest) => Promise; export type RequestPermission = (origins: string[]) => Promise; +/** Command name to its current shortcut, as set in chrome://extensions/shortcuts. */ +export type LoadShortcuts = () => 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"; +// Same recipe as the dashboard's components/ui/Button. +const buttonBase = + "inline-flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-md px-2.5 text-[12px] font-medium outline-none transition-[transform,background-color,color,filter] duration-100 ease-out focus-visible:ring-2 focus-visible:ring-accent/50 disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none motion-reduce:active:scale-100"; +const secondary = `${buttonBase} bg-content/6 text-content hover:bg-content/10 active:scale-[0.97]`; +const primary = `${buttonBase} bg-accent text-accent-ink hover:brightness-95 active:scale-[0.97]`; + +type ToolCopy = { name: string; description: string; error: string; icon: ReactElement }; + +const iconProps = { + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + strokeWidth: 1.6, + strokeLinecap: "round", + strokeLinejoin: "round", + "aria-hidden": true, + className: "size-4", +} as const; + +const TOOL_COPY: Record = { + inspect: { + name: "Inspect", + description: "Spacing, styles and source", + error: "the inspector", + icon: ( + + + + ), + }, + pick: { + name: "Pick and comment", + description: "Notes on elements for an AI agent", + error: "Pick and comment", + icon: ( + + + + + ), + }, + font: { + name: "Font", + description: "Read text styles, copy as CSS", + error: "the font tool", + icon: ( + + + + + ), + }, + color: { + name: "Colour", + description: "Element colours and an eyedropper", + error: "the colour tool", + icon: ( + + + + ), + }, +}; + +/** The app mark, identical to apps/desktop/src-tauri/icons/icon.svg; fixed brand colours. */ +function CapKitLogo(): ReactElement { + return ( + + ); +} function wait(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); @@ -21,21 +101,42 @@ function wait(ms: number): Promise { function Spinner(): ReactElement { return ( + ); } diff --git a/apps/desktop/src/lib/recordingTauri.ts b/apps/desktop/src/lib/recordingTauri.ts index c07f2a9..1008582 100644 --- a/apps/desktop/src/lib/recordingTauri.ts +++ b/apps/desktop/src/lib/recordingTauri.ts @@ -227,6 +227,24 @@ export async function loadCursorTrack(path: string): Promise } } +/** Opens a recording in the default video player; Windows asks for an app when none is set. */ +export async function openRecording(path: string): Promise { + if (!isTauri()) return; + await invoke("open_recording", { path }); +} + +/** Puts the recording's video file on the clipboard, ready to paste into a folder, chat or mail. */ +export async function copyRecording(path: string): Promise { + if (!isTauri()) return; + await invoke("copy_recording", { path }); +} + +/** Opens the recording's folder in Explorer with the video selected. */ +export async function revealRecording(path: string): Promise { + if (!isTauri()) return; + await invoke("reveal_recording", { path }); +} + /** Renderable URL for a recorded artefact. */ export function recordingSrc(path: string): string { return isTauri() ? convertFileSrc(path) : path; diff --git a/docs/current-status.md b/docs/current-status.md index 971c05c..e26c172 100644 --- a/docs/current-status.md +++ b/docs/current-status.md @@ -56,6 +56,8 @@ This document records what exists in the runtime today. The roadmap remains the - **Implemented:** the extension answers hover and Find sensitive text for the window under the pointer. If it cannot answer, CapKit falls back to Windows accessibility for that one lookup, and `ui_region_at` is not called when the extension returned elements (counted in a test). - **Implemented:** the Note tool (shortcut N, shown only with Developer tools on) pins numbered notes; in Select, clicking a pin reopens its comment. Once a capture has a pin, Copy, Save and Copy & Save (C, S, A, and Enter) write the note's Markdown plus a screenshot instead of a plain image, and the Notes tab lists them. Clicking a note opens it in full (screenshot and complete Markdown). Notes commands return "Developer tools is off" when the switch is off. - **Implemented:** when the extension has no details, a note falls back to the hovered element's role, name and screen-pixel box. +- **Implemented, awaiting manual checks:** Pick and comment in the extension (Alt+Shift+C, popup button, right-click → CapKit). Copy writes compact plain text: a two-line header an agent can follow, then one item per pick (a note, or none to just point the element out). Picks last until the page reloads. Spec: [pick-and-comment](specs/pick-and-comment.md). +- **Implemented, awaiting manual checks:** Font (Alt+Shift+F) and Colour (Alt+Shift+K) tools in the extension, and the dashboard-style restyle of the popup and page panels with bundled Geist. Same spec. - **Pending:** manual checks in Aside and Chrome, and the release binary size measurement for the SQLite dependency. ### In-place annotation and completion diff --git a/package.json b/package.json index 01a9399..26c8627 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snaphub", - "version": "0.6.2", + "version": "0.7.0", "private": true, "packageManager": "pnpm@11.14.0", "scripts": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 60dd3d2..8a962d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,12 +10,12 @@ importers: apps/browser-extension: dependencies: - '@fontsource-variable/jetbrains-mono': - specifier: 5.2.8 - version: 5.2.8 - '@fontsource-variable/plus-jakarta-sans': - specifier: 5.2.8 - version: 5.2.8 + '@fontsource-variable/geist': + specifier: 5.3.0 + version: 5.3.0 + '@fontsource-variable/geist-mono': + specifier: 5.3.0 + version: 5.3.0 '@jridgewell/trace-mapping': specifier: ^0.3.31 version: 0.3.31 @@ -461,12 +461,6 @@ packages: '@fontsource-variable/geist@5.3.0': resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==} - '@fontsource-variable/jetbrains-mono@5.2.8': - resolution: {integrity: sha512-WBA9elru6Jdp5df2mES55wuOO0WIrn3kpXnI4+W2ek5u3ZgLS9XS4gmIlcQhiZOWEKl95meYdvK7xI+ETLCq/Q==} - - '@fontsource-variable/plus-jakarta-sans@5.2.8': - resolution: {integrity: sha512-iQecBizIdZxezODNHzOn4SvvRMrZL/S8k4MEXGDynCmUrImVW0VmX+tIAMqnADwH4haXlHSXqMgU6+kcfBQJdw==} - '@hugeicons/core-free-icons@4.2.3': resolution: {integrity: sha512-fpiU0qFZkv4ABi23xJ2m4qNr0BBfuIaYjPboN8WDA6aj9D+OzXa7eykxKOpACZRuGbDz1U9S5DsNx1d5KNnsgA==} @@ -3215,10 +3209,6 @@ snapshots: '@fontsource-variable/geist@5.3.0': {} - '@fontsource-variable/jetbrains-mono@5.2.8': {} - - '@fontsource-variable/plus-jakarta-sans@5.2.8': {} - '@hugeicons/core-free-icons@4.2.3': {} '@hugeicons/react@1.1.9(react@19.2.7)':