From 4083c43f273e6d018a2adc9104084d9d17c63b87 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 21:16:15 +0530 Subject: [PATCH 01/16] feat(marketing): add deterministic launch film composition and renderer A 52.6 s 1080p60 product film (capture, Screen Draw, Showcase, recording with auto-zoom, size reveal) built as an HTML timeline driven by window.seek(ms) and rendered frame by frame to H.264 via headless Edge and ffmpeg. Renders land in marketing/launch-video/out/, which is ignored. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + marketing/launch-video/icons.js | 2 + marketing/launch-video/index.html | 225 ++++++++ marketing/launch-video/package.json | 4 + marketing/launch-video/render.ts | 207 ++++++++ marketing/launch-video/timeline.js | 794 ++++++++++++++++++++++++++++ 6 files changed, 1233 insertions(+) create mode 100644 marketing/launch-video/icons.js create mode 100644 marketing/launch-video/index.html create mode 100644 marketing/launch-video/package.json create mode 100644 marketing/launch-video/render.ts create mode 100644 marketing/launch-video/timeline.js diff --git a/.gitignore b/.gitignore index bfd5e8c..2068474 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ scripts .gitignore CHANGELOG.md AGENTS.md +marketing/launch-video/out/ diff --git a/marketing/launch-video/icons.js b/marketing/launch-video/icons.js new file mode 100644 index 0000000..16391dd --- /dev/null +++ b/marketing/launch-video/icons.js @@ -0,0 +1,2 @@ +// Generated once from @hugeicons/core-free-icons (Stroke Rounded, MIT) for the launch video. Do not edit by hand. +window.ICONS = {"Copy01":"","Download04":"","Pin":"","Square":"","Highlighter":"","Blur":"","Hashtag":"","Undo03":"","Cursor01":"","PaintBrush02":"","Spotlight":"","Record":"","Mic01":"","Video01":"","StopCircle":"","Pause":"","ZoomInArea":"","Presentation01":"","Image02":"","Settings02":"","ArrowUpRight01":"","Text":"","Tick02":"","Film01":"","Frame":"","Scan":"","PencilEdit01":"","Circle":"","HardDrive":""}; diff --git a/marketing/launch-video/index.html b/marketing/launch-video/index.html new file mode 100644 index 0000000..a4b1bb8 --- /dev/null +++ b/marketing/launch-video/index.html @@ -0,0 +1,225 @@ + + + + +CapKit — launch video + + + +
+
+
+
+
+
+
+
+
+
+
+ + + + diff --git a/marketing/launch-video/package.json b/marketing/launch-video/package.json new file mode 100644 index 0000000..e986b24 --- /dev/null +++ b/marketing/launch-video/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "type": "module" +} diff --git a/marketing/launch-video/render.ts b/marketing/launch-video/render.ts new file mode 100644 index 0000000..e4b115e --- /dev/null +++ b/marketing/launch-video/render.ts @@ -0,0 +1,207 @@ +/** + * Renders the CapKit launch video frame by frame. + * + * The composition in `index.html` is fully deterministic: `window.seek(ms)` + * paints the exact state for a timestamp, so every frame is captured from a + * still page and piped into ffmpeg. No CSS animation or wall-clock timing is + * involved, which keeps the output identical across machines and frame rates. + * + * Usage (Node 24+, run from the repository root): + * node marketing/launch-video/render.ts --serve # live preview server + * node marketing/launch-video/render.ts # 1080p60 MP4 + * node marketing/launch-video/render.ts --fps=30 --from=14000 --to=22000 + * + * Requirements, resolved without adding a workspace dependency: + * - `playwright-core`: set PLAYWRIGHT_CORE to its folder, otherwise the npx + * cache used by the Playwright MCP server is searched. + * - A Chromium browser: Microsoft Edge by default, or CHROME_PATH. + * - ffmpeg on PATH, or FFMPEG. + * - Fonts come from the desktop app's installed Fontsource packages, so run + * `pnpm.cmd install` first. + */ +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import { dirname, extname, join, resolve, sep } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const ROOT = dirname(fileURLToPath(import.meta.url)); +const REPO = resolve(ROOT, "../.."); +const FONT_ROOT = join(REPO, "apps/desktop/node_modules/@fontsource-variable"); +const FONT_FILES: Readonly> = { + "caveat.woff2": "caveat/files/caveat-latin-wght-normal.woff2", + "jakarta.woff2": "plus-jakarta-sans/files/plus-jakarta-sans-latin-wght-normal.woff2", + "mono.woff2": "jetbrains-mono/files/jetbrains-mono-latin-wght-normal.woff2", +}; +const MIME: Readonly> = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".woff2": "font/woff2", +}; +const WIDTH = 1920; +const HEIGHT = 1080; + +type Options = { + serve: boolean; + fps: number; + from: number; + to: number | null; + out: string; +}; + +function parseOptions(argv: readonly string[]): Options { + const options: Options = { + from: 0, + fps: 60, + out: join(ROOT, "out", "capkit-launch.mp4"), + serve: false, + to: null, + }; + for (const arg of argv) { + const [key, value = ""] = arg.replace(/^--/, "").split("="); + if (key === "serve") options.serve = true; + else if (key === "fps") options.fps = positiveNumber(key, value); + else if (key === "from") options.from = positiveNumber(key, value, true); + else if (key === "to") options.to = positiveNumber(key, value); + else if (key === "out") options.out = resolve(value); + else throw new Error(`Unknown option: ${arg}`); + } + return options; +} + +function positiveNumber(name: string, raw: string, allowZero = false): number { + const value = Number(raw); + if (!Number.isFinite(value) || value < 0 || (!allowZero && value === 0)) { + throw new Error(`--${name} must be a ${allowZero ? "non-negative" : "positive"} number.`); + } + return value; +} + +function startServer(): Promise<{ server: Server; url: string }> { + const server = createServer((request, response) => { + const pathname = decodeURIComponent(new URL(request.url ?? "/", "http://local").pathname); + let filePath: string; + if (pathname.startsWith("/fonts/")) { + const font = FONT_FILES[pathname.slice("/fonts/".length)]; + filePath = font === undefined ? "" : join(FONT_ROOT, font); + } else { + filePath = resolve(ROOT, `.${pathname === "/" ? "/index.html" : pathname}`); + // Never serve files outside the composition folder. + if (!filePath.startsWith(ROOT + sep)) filePath = ""; + } + if (filePath === "" || !existsSync(filePath)) { + response.writeHead(404).end("Not found"); + return; + } + response.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" }); + response.end(readFileSync(filePath)); + }); + return new Promise((resolveServer) => { + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + resolveServer({ server, url: `http://127.0.0.1:${port}/` }); + }); + }); +} + +type PlaywrightModule = { + chromium: { + launch: (options: Record) => Promise<{ + newPage: (options: Record) => Promise; + close: () => Promise; + }>; + }; +}; +type PlaywrightPage = { + goto: (url: string) => Promise; + evaluate: (script: string) => Promise; + screenshot: (options: Record) => Promise; +}; + +function findPlaywrightCore(): string { + const fromEnv = process.env.PLAYWRIGHT_CORE; + if (fromEnv !== undefined && existsSync(fromEnv)) return fromEnv; + const npxCache = join(process.env.LOCALAPPDATA ?? "", "npm-cache", "_npx"); + if (existsSync(npxCache)) { + for (const entry of readdirSync(npxCache)) { + const candidate = join(npxCache, entry, "node_modules", "playwright-core"); + if (existsSync(join(candidate, "package.json"))) return candidate; + } + } + throw new Error("playwright-core was not found. Set PLAYWRIGHT_CORE to its folder."); +} + +async function loadPlaywright(): Promise { + const entry = pathToFileURL(join(findPlaywrightCore(), "index.mjs")).href; + // The module is loaded from an external path, so its type cannot be + // inferred; the shape above covers the three calls this script makes. + return (await import(entry)) as PlaywrightModule; +} + +async function render(options: Options, url: string): Promise { + const { chromium } = await loadPlaywright(); + const executablePath = process.env.CHROME_PATH; + const browser = await chromium.launch( + executablePath === undefined ? { channel: "msedge" } : { executablePath }, + ); + try { + const page = await browser.newPage({ deviceScaleFactor: 1, viewport: { height: HEIGHT, width: WIDTH } }); + await page.goto(`${url}?render`); + await page.evaluate("document.fonts.ready.then(() => true)"); + const duration = await page.evaluate("window.DURATION"); + const end = Math.min(options.to ?? duration, duration); + const frameCount = Math.ceil(((end - options.from) / 1000) * options.fps); + + mkdirSync(dirname(options.out), { recursive: true }); + const ffmpeg = spawn( + process.env.FFMPEG ?? "ffmpeg", + [ + "-y", "-loglevel", "error", + "-f", "image2pipe", "-framerate", String(options.fps), "-c:v", "png", "-i", "-", + "-c:v", "libx264", "-preset", "slow", "-crf", "14", "-pix_fmt", "yuv420p", + "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", + "-movflags", "+faststart", options.out, + ], + { stdio: ["pipe", "inherit", "inherit"] }, + ); + const finished = new Promise((resolveExit, rejectExit) => { + ffmpeg.on("error", rejectExit); + ffmpeg.on("close", (code) => { + if (code === 0) resolveExit(); + else rejectExit(new Error(`ffmpeg exited with code ${String(code)}`)); + }); + }); + + const started = Date.now(); + for (let frame = 0; frame < frameCount; frame += 1) { + const time = options.from + (frame * 1000) / options.fps; + await page.evaluate(`window.seek(${time.toFixed(3)})`); + const png = await page.screenshot({ type: "png" }); + if (!ffmpeg.stdin.write(png)) { + await new Promise((drain) => ffmpeg.stdin.once("drain", drain)); + } + if (frame % options.fps === 0) { + const elapsed = (Date.now() - started) / 1000; + process.stdout.write(`\rframe ${frame}/${frameCount} · ${elapsed.toFixed(0)}s`); + } + } + ffmpeg.stdin.end(); + await finished; + process.stdout.write(`\nWrote ${options.out}\n`); + } finally { + await browser.close(); + } +} + +const options = parseOptions(process.argv.slice(2)); +const { server, url } = await startServer(); +if (options.serve) { + process.stdout.write(`Preview: ${url}?play (append &from= to start later, or ?t= for a still)\n`); +} else { + try { + await render(options, url); + } finally { + server.close(); + } +} diff --git a/marketing/launch-video/timeline.js b/marketing/launch-video/timeline.js new file mode 100644 index 0000000..e0fbc67 --- /dev/null +++ b/marketing/launch-video/timeline.js @@ -0,0 +1,794 @@ +/* + * CapKit launch video — deterministic timeline. + * + * Every visual is a pure function of time: `window.seek(ms)` paints the exact + * frame for that timestamp. There are no CSS transitions, animations, timers or + * random values, so render.ts can capture frames at any rate and get identical + * output. Coordinates are 1920×1080 stage pixels; "desk" coordinates are the + * simulated Windows desktop before the camera/studio transforms are applied. + */ +(() => { + "use strict"; + + /* ------------------------------------------------------------ timing ---- */ + const S1 = 3500; // capture + annotate + const S3 = 16000; // screen draw + const S4 = 23600; // showcase + const S5 = 32200; // record + auto zoom + const S6 = 43000; // size reveal + const S7 = 47600; // end card + const END = 52600; + window.DURATION = END; + + /* ------------------------------------------------------------ easing ---- */ + function bezier(x1, y1, x2, y2) { + const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx; + const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by; + const sx = (t) => ((ax * t + bx) * t + cx) * t; + const sy = (t) => ((ay * t + by) * t + cy) * t; + return (x) => { + if (x <= 0) return 0; + if (x >= 1) return 1; + let lo = 0, hi = 1, t = x; + for (let i = 0; i < 24; i += 1) { + t = (lo + hi) / 2; + if (sx(t) < x) lo = t; else hi = t; + } + return sy(t); + }; + } + const ease = { + out: bezier(0.23, 1, 0.32, 1), + inOut: bezier(0.77, 0, 0.175, 1), + drawer: bezier(0.32, 0.72, 0, 1), + move: bezier(0.45, 0, 0.2, 1), // cursor travel: human, slightly front-loaded + linear: (x) => x, + }; + const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v)); + const lerp = (a, b, p) => a + (b - a) * p; + /** Eased progress of `t` through [start, start + dur]. */ + const prog = (t, start, dur, e = ease.out) => e(clamp((t - start) / dur)); + /** Fade in over [a, b], fade out over [c, d]. */ + const window01 = (t, a, b, c, d) => prog(t, a, b - a) * (1 - prog(t, c, d - c)); + + /* ------------------------------------------------------------- DOM ------ */ + const $ = (q) => document.querySelector(q); + function el(parent, cls, style, html) { + const node = document.createElement("div"); + if (cls) node.className = cls; + if (style) node.style.cssText = style; + if (html) node.innerHTML = html; + parent.appendChild(node); + return node; + } + const icon = (name, size = 22) => + `${window.ICONS[name]}`; + function show(node, o) { + node.style.opacity = String(o); + node.style.visibility = o < 0.002 ? "hidden" : "visible"; + } + function tf(node, x, y, s = 1, o = 1, extra = "") { + node.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0) scale(${s.toFixed(4)}) ${extra}`; + show(node, o); + } + + const stage = $("#stage"); + const deskWrap = $("#deskWrap"); + const deskCam = $("#deskCam"); + + /* -------------------------------------------------------- product UI ---- */ + function chartSvg() { + const values = [38, 42, 40, 47, 51, 49, 58, 62, 60, 71, 78, 86]; + const w = 560, h = 196; + const pts = values.map((v, i) => [(i / (values.length - 1)) * w, h - (v / 100) * h]); + const line = pts.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`).join(" "); + const grid = [0.25, 0.5, 0.75].map((g) => ``).join(""); + return ` + + ${grid} + + `; + } + + function productWindow(live, blurEmails) { + const id = (name) => (live ? ` id="${name}"` : ""); + const email = (v) => `${v}`; + const row = (done, label) => + `
${label}
`; + return `
+
Orbit — Release Center
—☐✕
+
Orbit
+

Release 2.4

Launch checklist · Week 43
+
Ship release
+
Signups
12,480
+18.2%
+
Conversion
4.2%
+0.6
+
Churn
1.1%
−0.3
+
Weekly active
LAST 12 WEEKS
${chartSvg()}
+
Launch checklist
${row(true, "Pricing page")}${row(true, "Docs updated")}${row(false, "Status page")}${row(false, "Press kit")}
+
+
CustomerEmailPlanMRR
+
Acme Studio${email("maya@acmestudio.io")}Pro$1,240
+
Northwind${email("j.ortiz@northwind.co")}Team$860
+
Lumen Labs${email("ops@lumenlabs.dev")}Pro$2,110
+
+
`; + } + + function logoSvg(prefix) { + return ` + + + + + `; + } + + /* --------------------------------------------------------- desktop ------ */ + el(deskCam, "wallpaper abs"); + el(deskCam, "taskbar", "", + `${logoSvg("tb")} +
ENG9:41
`); + el(deskCam, "", "", productWindow(true, false)); + const kpiSignups = $("#kpiSignups"); + + /* capture overlay */ + const cap = el(deskCam, "abs", "width:1920px;height:1080px"); + const tintFull = el(cap, "abs tint", "width:1920px;height:1080px"); + const snap = el(cap, "snap", "left:612px;top:426px;width:600px;height:280px"); + const anno = el(cap, "abs", "width:1920px;height:1080px"); + const annoRect = el(anno, "anno-rect", "left:910px;top:290px;width:0;height:0"); + const annoHl = el(anno, "anno-hl", "left:624px;top:438px;width:0;height:28px"); + const BADGES = [[1496, 496], [1496, 540], [1496, 584]]; + const badges = BADGES.map(([x, y], i) => el(anno, "badge", `left:${x}px;top:${y}px`, String(i + 1))); + const blurBox = el(anno, "blur", "left:826px;top:780px;width:0;height:0"); + const sel = el(cap, "sel", "left:596px;top:284px;width:0;height:0"); + const HANDLES = [[0, 0], [0.5, 0], [1, 0], [1, 0.5], [1, 1], [0.5, 1], [0, 1], [0, 0.5]]; + const handles = HANDLES.map(([hx, hy]) => el(sel, "handle", `left:${hx * 100}%;top:${hy * 100}%`)); + const dims = el(cap, "dims", "left:596px;top:246px", "0 × 0 px"); + const hint = el(cap, "hint", "left:0;top:0", "Drag to select · Click to grab a window"); + const rail = el(cap, "dock v", "left:1556px;top:284px"); + const railTools = [["Copy01", "C"], ["Download04", "S"], ["Pin", ""]].map(([name, key]) => + el(rail, "tool", "", icon(name) + (key ? `${key}` : ""))); + const toolDock = el(cap, "dock", "left:596px;top:922px"); + const tools = ["Cursor01", "Square", "Highlighter", "Blur", "Hashtag", "Undo03"].map((name) => + el(toolDock, "tool", "", icon(name))); + const toastCopy = el(deskCam, "toast", "left:960px;top:930px", + `${icon("Tick02", 16)}Copied to clipboard 948 × 626`); + + /* screen draw */ + const draw = el(deskCam, "abs", "width:1920px;height:1080px"); + const spot = el(draw, "abs", "width:1920px;height:1080px"); + const inkSvg = el(draw, "abs", "width:1920px;height:1080px"); + { + const cx = 1449, cy = 246, pts = []; + for (let i = 0; i <= 120; i += 1) { + const a = -0.35 * Math.PI + (i / 120) * 2.3 * Math.PI; + const rx = 122 * (1 + 0.025 * Math.sin(3 * a)); + const ry = 48 * (1 + 0.05 * Math.cos(2 * a)); + pts.push(`${i ? "L" : "M"}${(cx + rx * Math.cos(a)).toFixed(1)} ${(cy + ry * Math.sin(a) + i * 0.09).toFixed(1)}`); + } + inkSvg.innerHTML = ` + + + `; + } + const inkCircle = $("#inkCircle"), inkArrow = $("#inkArrow"), inkHead = $("#inkHead"); + const inkLens = [inkCircle, inkArrow, inkHead].map((p) => p.getTotalLength()); + [inkCircle, inkArrow, inkHead].forEach((p, i) => { p.style.strokeDasharray = `${inkLens[i]} ${inkLens[i]}`; }); + const scrawl = el(draw, "scrawl", "left:828px;top:212px", "ship it friday!"); + const drawDockRow = el(draw, "abs", "width:1920px;top:962px;display:flex;justify-content:center"); + const drawDock = el(drawDockRow, "dock", "position:relative"); + const drawTools = ["PencilEdit01", "Highlighter", "ArrowUpRight01", "Square", "Text", "Spotlight"].map((n) => + el(drawDock, "tool", "", icon(n))); + el(drawDock, "sep"); + ["#d9ff43", "#ff5b4d", "#60a5fa", "#ffffff"].forEach((c, i) => + el(drawDock, `swatch${i === 1 ? " on" : ""}`, `background:${c}`)); + const live = el(draw, "live", "left:1590px;top:72px", "Desktop stays live"); + + /* recording */ + const rec = el(deskCam, "abs", "width:1920px;height:1080px"); + const recBorder = el(rec, "recborder"); + const countdown = el(rec, "count", "left:960px;top:520px", "3"); + const recDock = el(rec, "rec", "left:680px;top:958px;width:560px", + `00:00Region · Display 1 + ${icon("Mic01")}${icon("Video01")}${icon("Pause")} + ${icon("StopCircle", 18)}Stop`); + const recTime = recDock.querySelector(".time"); + const recStop = recDock.querySelector(".stop"); + + /* stage-level layers */ + const studioBg = $("#studioBg"); + studioBg.style.background = + "radial-gradient(circle at 18% 12%, rgb(217 255 67 / 26%), transparent 30%), radial-gradient(circle at 83% 82%, rgb(95 148 130 / 42%), transparent 34%), linear-gradient(135deg, #26352e, #101411 70%)"; + const studioUi = $("#studioUi"); + const timelinePanel = el(studioUi, "timeline", "", + `
Clip
+
Zoom
`); + const zoomTrack = timelinePanel.querySelectorAll(".track")[1]; + const ZOOM_BLOCKS = [[0.17, 0.47, "1.8× · click"], [0.5, 0.93, "pan · click"]]; + const zoomBlocks = ZOOM_BLOCKS.map(([a, b, label]) => + el(zoomTrack, "zoomblk", `left:${a * 100}%;width:${(b - a) * 100}%`, label)); + const playhead = el(timelinePanel, "playhead", "left:110px"); + const autoPill = el(studioUi, "live", "left:260px;top:842px", `Auto-zoom from your clicks`); + const camBubble = el(stage, "cam", "left:0;top:0;z-index:30;transform-origin:0 0", + ` + + + + + `); + + /* showcase */ + const showcase = $("#showcase"); + const LOOKS = [ + { label: "Spotlight", bg: "radial-gradient(circle at 18% 12%,rgb(217 255 67 / 36%),transparent 27%),radial-gradient(circle at 83% 82%,rgb(95 148 130 / 48%),transparent 32%),linear-gradient(135deg,#26352e,#121714 70%)", s: 1, r: 14, rx: 0, ry: 0, bezel: 0, shadow: 1 }, + { label: "Editorial", bg: "#ecebe5", s: 0.93, r: 8, rx: 0, ry: 0, bezel: 0, shadow: 0.35 }, + { label: "Midnight", bg: "radial-gradient(circle at 50% 40%, #232624, #0f1110 70%)", s: 0.97, r: 14, rx: 0, ry: 0, bezel: 0, shadow: 0.9 }, + { label: "Poster", bg: "linear-gradient(135deg,#f3a46f 0%,#a76591 100%)", s: 0.9, r: 18, rx: 9, ry: -16, bezel: 0, shadow: 1 }, + { label: "Device", bg: "linear-gradient(135deg,#8de3ef 0%,#31577a 100%)", s: 0.88, r: 16, rx: 0, ry: 0, bezel: 1, shadow: 1 }, + { label: "Bare", bg: "repeating-conic-gradient(#e7e6e0 0 25%, #f7f6f2 0 50%) 0 0 / 22px 22px", s: 1, r: 0, rx: 0, ry: 0, bezel: 0, shadow: 0 }, + ]; + const backdrops = LOOKS.map((look) => el(showcase, "bd", `background:${look.bg}`)); + const shot = el(showcase, "", ""); + shot.id = "shot"; + const shotShadow = el(shot, "abs", "inset:0;width:948px;height:626px;box-shadow:0 60px 140px rgb(0 0 0 / 55%), 0 14px 34px rgb(0 0 0 / 30%)"); + const shotBezel = el(shot, ""); + shotBezel.id = "shotBezel"; + const shotClip = el(shot, ""); + shotClip.id = "shotClip"; + const shotInner = el(shotClip, ""); + shotInner.id = "shotInner"; + shotInner.innerHTML = productWindow(false, true); + el(shotInner, "anno-rect", "left:910px;top:290px;width:312px;height:130px"); + el(shotInner, "anno-hl", "left:624px;top:438px;width:172px;height:28px"); + BADGES.forEach(([x, y], i) => el(shotInner, "badge", `left:${x}px;top:${y}px`, String(i + 1))); + const looksStrip = el(showcase, "looks"); + const lookTiles = LOOKS.map((look) => + el(looksStrip, "look", "", `
${look.label}`)); + const copyBtn = el(showcase, "btn dark", "left:1515px;top:60px", `${icon("Copy01")}Copy`); + const exportBtn = el(showcase, "btn light", "left:1640px;top:60px", `${icon("Download04")}Export`); + const toastExport = el(showcase, "toast", "left:1290px;top:128px", + `${icon("Tick02", 16)}Exported PNG · 2× · Pictures › CapKit`); + + /* corners used by the intro → desktop transition */ + const frameCorners = $("#frameCorners"); + const corners = [ + "border-top-width:5px;border-left-width:5px;border-top-left-radius:14px", + "border-top-width:5px;border-right-width:5px;border-top-right-radius:14px", + "border-bottom-width:5px;border-right-width:5px;border-bottom-right-radius:14px", + "border-bottom-width:5px;border-left-width:5px;border-bottom-left-radius:14px", + ].map((style) => el(frameCorners, "corner", style)); + + /* outro / intro overlay */ + const outro = $("#outro"); + const introLogo = el(outro, "", "position:absolute;left:850px;top:250px;width:220px;height:220px", logoSvg("in")); + const introLines = el(outro, "abs", "width:1920px;top:540px;text-align:center;font:750 92px/1.08 Jakarta;letter-spacing:-0.045em;color:#f6f6f1"); + introLines.innerHTML = + ["Everything", "you", "show,"].map((w) => `${w}`).join("") + + "
" + + ["in", "one", 'tiny', 'tool.'].map((w) => `${w}`).join(""); + const introWords = Array.from(introLines.querySelectorAll(".w")); + + const sizeEye = el(outro, "meta-line", "top:262px", "The entire download"); + const bigSize = el(outro, "bigsize", "top:318px", ""); + const ticks = el(outro, "ticks", "left:360px;top:668px;width:1200px"); + const STATS = ["≈33 MB RAM at idle", "0% CPU while waiting", "No account. No cloud."]; + const stats = STATS.map((html, i) => el(outro, "stat", `left:${560 + i * 400}px;top:712px`, html)); + const CHIPS = [["Scan", "Capture"], ["PaintBrush02", "Draw"], ["Presentation01", "Showcase"], ["Video01", "Record"]]; + const chips = CHIPS.map(([name, label], i) => + el(outro, "chip", `left:${452 + i * 262}px;top:812px;width:236px;justify-content:center`, icon(name, 26) + label)); + + const endLogo = el(outro, "", "position:absolute;left:0;top:0;width:150px;height:150px", logoSvg("end")); + const endWord = el(outro, "word", "left:818px;top:322px", "CapKit"); + const endTag = el(outro, "tag", "top:530px", "The lightweight desktop toolkit to capture, record, and showcase."); + const endMeta = el(outro, "meta-line", "top:620px", "Windows 11  ·  Microsoft Store"); + + /* cursor + ripples (stage space, mapped through the camera) */ + const cursor = el(stage, "", "z-index:45;transform-origin:0 0"); + cursor.id = "cursor"; + cursor.innerHTML = ` + + + `; + const cursorKinds = Array.from(cursor.querySelectorAll("svg")); + const ripplesLayer = el(stage, "", "position:absolute;left:0;top:0;z-index:44"); + + const scrim = $("#scrim"); + const hl = $("#hl"); + const hlEye = $("#hlEye"); + const hlText = $("#hlText"); + const hlPlate = document.createElement("div"); + hlPlate.style.cssText = "position:absolute;left:-44px;top:-34px;right:-48px;bottom:-30px;border-radius:40px;background:rgb(12 13 11 / 86%);border:2px solid rgb(255 255 255 / 10%);z-index:-1"; + hlText.style.position = "relative"; + const keys = $("#keys"); + + /* ------------------------------------------------------- headlines ------ */ + const HEADLINES = [ + { start: S1, end: S1 + 5000, eye: "01 — Capture · Alt + Shift + S", text: "Capture any *region.*", hero: true }, + { start: S1 + 5000, end: S3, eye: "", text: "Mark it up in *place.*", hero: false }, + { start: S3, end: S4, eye: "02 — Screen Draw · Alt + Shift + A", text: "Draw on a *live* screen.", hero: true }, + { start: S4, end: S5, eye: "03 — Showcase", text: "Make it *launch-ready.*", hero: true }, + { start: S5, end: S5 + 6200, eye: "04 — Record · Alt + Shift + R", text: "Record your *screen.*", hero: true }, + { start: S5 + 6200, end: S6, eye: "", text: "Smooth zoom, from your *clicks.*", hero: false }, + ]; + let builtHeadline = -1; + let hlWords = []; + function renderHeadline(t) { + const index = HEADLINES.findIndex((h) => t >= h.start && t < h.end); + if (index < 0) { + show(hl, 0); + show(scrim, 0); + return; + } + const h = HEADLINES[index]; + if (builtHeadline !== index) { + builtHeadline = index; + hlEye.textContent = h.eye; + hlEye.style.display = h.eye ? "block" : "none"; + hlText.innerHTML = ""; + hlText.append(hlPlate); + hlText.insertAdjacentHTML("beforeend", h.text.split(" ").map((word) => { + const lime = word.startsWith("*"); + const clean = word.replaceAll("*", ""); + return `${clean}`; + }).join(" ")); + hlWords = Array.from(hlText.querySelectorAll(".w")); + } + const local = t - h.start; + const exit = 1 - prog(t, h.end - 280, 280); + const width = hl.offsetWidth, height = hl.offsetHeight; + const eyeHeight = h.eye ? hlEye.offsetHeight + 22 : 0; + const CORNER_SCALE = 0.4; + const cornerX = 96, cornerY = 70 - eyeHeight * CORNER_SCALE; + if (h.hero) { + hlWords.forEach((word, i) => { + const p = prog(local, 120 + i * 70, 720); + word.style.transform = `translateY(${((1 - p) * 0.42).toFixed(3)}em)`; + word.style.opacity = String(p); + }); + const move = prog(local, 1100, 720, ease.inOut); + const x = lerp((1920 - width) / 2, cornerX, move); + const y = lerp((1080 - height) / 2, cornerY, move); + tf(hl, x, y, lerp(1, CORNER_SCALE, move), exit); + hlEye.style.opacity = String(prog(local, 0, 400) * (1 - prog(local, 1100, 260))); + hlPlate.style.opacity = String(prog(local, 1450, 400)); + show(scrim, prog(local, 0, 260) * (1 - prog(local, 1100, 620, ease.inOut))); + } else { + hlWords.forEach((word) => { word.style.transform = "none"; word.style.opacity = "1"; }); + const p = prog(local, 0, 320); + tf(hl, cornerX, cornerY + (1 - p) * 10, CORNER_SCALE, p * exit); + hlPlate.style.opacity = "1"; + show(scrim, 0); + } + } + + /* --------------------------------------------------------- keycaps ------ */ + const KEYS = [ + { start: S1 + 1900, end: S1 + 2700, press: S1 + 2150, keys: ["Alt", "Shift", "S"] }, + { start: S1 + 10600, end: S1 + 11300, press: S1 + 10800, keys: ["C"] }, + { start: S3 + 1900, end: S3 + 2600, press: S3 + 2150, keys: ["Alt", "Shift", "A"] }, + { start: S3 + 6800, end: S3 + 7400, press: S3 + 7000, keys: ["Esc"] }, + { start: S5 + 1900, end: S5 + 2600, press: S5 + 2150, keys: ["Alt", "Shift", "R"] }, + ]; + let builtKeys = -1; + function renderKeys(t) { + const index = KEYS.findIndex((k) => t >= k.start && t < k.end); + if (index < 0) { show(keys, 0); return; } + const k = KEYS[index]; + if (builtKeys !== index) { + builtKeys = index; + keys.innerHTML = k.keys.map((key) => `${key}`).join('+'); + } + const p = prog(t, k.start, 220); + const o = p * (1 - prog(t, k.end - 220, 220)); + tf(keys, (1920 - keys.offsetWidth) / 2, 952 + (1 - p) * 14, 1, o); + const pressed = t >= k.press && t < k.press + 170; + keys.querySelectorAll(".key").forEach((key) => { + key.style.transform = pressed ? "translateY(3px) scale(0.96)" : "none"; + key.style.boxShadow = pressed ? "0 1px 0 #0b0c0a, 0 10px 24px rgb(0 0 0 / 40%)" : ""; + key.style.background = pressed ? "linear-gradient(#3a3d2c, #23261c)" : ""; + key.style.borderColor = pressed ? "rgb(217 255 67 / 70%)" : ""; + }); + } + + /* ---------------------------------------------------------- cursor ------ */ + const at = (base, rows) => rows.map(([dt, x, y]) => [base + dt, x, y]); + const PLAYBACK_START = S5 + 7100, PLAYBACK_DUR = 3200; + const circleStart = inkCircle.getPointAtLength(0); + const circleEnd = inkCircle.getPointAtLength(inkLens[0]); + const arrowStart = inkArrow.getPointAtLength(0); + const arrowEnd = inkArrow.getPointAtLength(inkLens[1]); + const WAYPOINTS = [ + ...at(S1, [[1700, 1300, 700], [2500, 1300, 700], [3100, 900, 520], [3200, 900, 520], [3600, 596, 284], [3700, 596, 284], + [4500, 1544, 910], [5000, 1544, 910], [5450, 678, 952], [5550, 678, 952], [5900, 910, 290], [5950, 910, 290], + [6600, 1222, 420], [6700, 1222, 420], [7050, 730, 952], [7150, 730, 952], [7450, 624, 452], [7500, 624, 452], + [7950, 796, 452], [8050, 796, 452], [8350, 834, 952], [8450, 834, 952], [8650, 1496, 496], [8750, 1496, 496], + [8900, 1496, 540], [9000, 1496, 540], [9150, 1496, 584], [9300, 1496, 584], [9600, 782, 952], [9700, 782, 952], + [9950, 826, 780], [10000, 826, 780], [10450, 1084, 892], [12500, 1084, 892]]), + ...at(S3, [[2600, 1084, 892], [2900, circleStart.x, circleStart.y], [3700, circleEnd.x, circleEnd.y], + [3800, arrowStart.x, arrowStart.y], [4300, arrowEnd.x, arrowEnd.y], [4450, arrowEnd.x, arrowEnd.y], + [4550, 830, 268], [5350, 1080, 268], [5550, 1449, 246], [5800, 1449, 246], [6900, 912, 520], [7600, 912, 520]]), + ...at(S4, [[1900, 1300, 760], [2000, 1300, 760], [2400, 717, 946], [2900, 717, 946], [3200, 879, 946], [3700, 879, 946], + [4050, 1203, 946], [4550, 1203, 946], [4850, 1041, 946], [5400, 1041, 946], [5950, 1705, 83], [8600, 1705, 83]]), + ...at(S5, [[3600, 1200, 700], [3700, 1200, 700], [4300, 758, 355], [4600, 758, 355], [5200, 1449, 246], + [5500, 1449, 246], [5900, 1182, 988], [6200, 1182, 988]]), + ]; + /** Intervals where the cursor follows an ink path exactly. */ + const PATH_FOLLOW = [ + { t0: S3 + 2900, t1: S3 + 3700, path: inkCircle, len: inkLens[0], e: ease.inOut }, + { t0: S3 + 3800, t1: S3 + 4300, path: inkArrow, len: inkLens[1], e: ease.inOut }, + ]; + const PLAYBACK_CURSOR = [[0, 1200, 700], [0.15, 1200, 700], [0.25, 758, 355], [0.35, 758, 355], [0.55, 1449, 246], [0.62, 1449, 246], [0.85, 1200, 640], [1, 1200, 640]]; + const VISIBLE = [[S1 + 1700, S1 + 11900], [S3 + 2600, S3 + 7300], [S4 + 1900, S4 + 8300], [S5 + 3600, S5 + 6150], [PLAYBACK_START, PLAYBACK_START + PLAYBACK_DUR + 300]]; + const KINDS = [[0, "arrow"], [S1 + 2300, "cross"], [S1 + 4500, "arrow"], [S3 + 2600, "pen"], [S3 + 7300, "arrow"]]; + const CLICKS = [S1 + 5500, S1 + 7100, S1 + 8400, S1 + 8700, S1 + 8950, S1 + 9200, S1 + 9650, + S4 + 2450, S4 + 3250, S4 + 4100, S4 + 4900, S4 + 6000, S5 + 4400, S5 + 5300, S5 + 5950]; + + function interpolate(rows, t, e = ease.move) { + if (t <= rows[0][0]) return [rows[0][1], rows[0][2]]; + for (let i = 0; i < rows.length - 1; i += 1) { + const [t0, x0, y0] = rows[i]; + const [t1, x1, y1] = rows[i + 1]; + if (t <= t1) { + const p = t1 === t0 ? 1 : e((t - t0) / (t1 - t0)); + return [lerp(x0, x1, p), lerp(y0, y1, p)]; + } + } + const last = rows[rows.length - 1]; + return [last[1], last[2]]; + } + function deskCursor(t) { + if (t >= PLAYBACK_START - 200) { + const f = clamp((t - PLAYBACK_START) / PLAYBACK_DUR); + return interpolate(PLAYBACK_CURSOR, f); + } + for (const follow of PATH_FOLLOW) { + if (t >= follow.t0 && t <= follow.t1) { + const point = follow.path.getPointAtLength(follow.e((t - follow.t0) / (follow.t1 - follow.t0)) * follow.len); + return [point.x, point.y]; + } + } + return interpolate(WAYPOINTS, t); + } + + /* ---------------------------------------------------------- camera ------ */ + const CAMERA = [[0, 1, 960, 540], [0.17, 1, 960, 540], [0.3, 1.8, 758, 355], [0.45, 1.8, 758, 355], [0.6, 1.8, 1449, 246], [0.78, 1.8, 1449, 246], [0.93, 1, 960, 540], [1, 1, 960, 540]]; + function cameraAt(t) { + if (t < PLAYBACK_START || t > S6 + 600) return { s: 1, tx: 0, ty: 0 }; + const f = clamp((t - PLAYBACK_START) / PLAYBACK_DUR); + let s = 1, fx = 960, fy = 540; + for (let i = 0; i < CAMERA.length - 1; i += 1) { + const a = CAMERA[i], b = CAMERA[i + 1]; + if (f <= b[0]) { + const p = ease.inOut((f - a[0]) / (b[0] - a[0])); + s = lerp(a[1], b[1], p); fx = lerp(a[2], b[2], p); fy = lerp(a[3], b[3], p); + break; + } + } + const tx = clamp(960 - fx * s, 1920 - 1920 * s, 0); + const ty = clamp(540 - fy * s, 1080 - 1080 * s, 0); + return { s, tx, ty }; + } + const STUDIO = { s: 0.62, x: 960 - 960 * 0.62, y: 440 - 540 * 0.62 }; + function wrapAt(t) { + const p = prog(t, S5 + 6100, 800, ease.inOut); + return { s: lerp(1, STUDIO.s, p), x: lerp(0, STUDIO.x, p), y: lerp(0, STUDIO.y, p), p }; + } + + /* ripples */ + const RIPPLES = [ + [S5 + 4400, 758, 355], [S5 + 5300, 1449, 246], + [PLAYBACK_START + 0.27 * PLAYBACK_DUR, 758, 355], [PLAYBACK_START + 0.58 * PLAYBACK_DUR, 1449, 246], + ].map(([time, x, y]) => ({ time, x, y, node: el(ripplesLayer, "ripple", "left:0;top:0") })); + + /* ------------------------------------------------------------ render ---- */ + function renderDesk(t, cam, wrap) { + // Which desktop layers are visible + let deskO = 0; + if (t >= S1 + 1100 && t < S4 + 300) deskO = prog(t, S1 + 1100, 420); + if (t >= S5 + 300 && t < S6 + 600) deskO = 1 - prog(t, S6, 450); + show(deskWrap, deskO); + deskWrap.style.transform = `translate3d(${wrap.x}px, ${wrap.y}px, 0) scale(${wrap.s})`; + deskWrap.style.borderRadius = `${(wrap.p * 18) / wrap.s}px`; + deskWrap.style.boxShadow = wrap.p > 0 ? `0 0 0 ${1.5 / wrap.s}px rgb(255 255 255 / ${0.12 * wrap.p}), 0 ${60 / wrap.s}px ${140 / wrap.s}px rgb(0 0 0 / ${0.5 * wrap.p})` : "none"; + deskCam.style.transform = `translate3d(${cam.tx}px, ${cam.ty}px, 0) scale(${cam.s})`; + + // Live data: the desktop keeps changing while Screen Draw is open. + const ticksSince = t - (S3 + 2700); + const signups = ticksSince < 0 ? 12480 : Math.min(12486, 12481 + Math.floor(ticksSince / 700)); + kpiSignups.textContent = signups.toLocaleString("en-US"); + + /* --- capture + annotate (S1) --- */ + const L = t - S1; + const capO = t >= S1 && t < S3 ? 1 - prog(L, 11500, 300) : 0; + show(cap, capO); + if (capO > 0) { + const dragging = L >= 3700; + show(tintFull, dragging ? 0 : prog(L, 2300, 200)); + tf(snap, 0, 0, lerp(1.03, 1, prog(L, 3000, 180)), prog(L, 3000, 150) * (1 - prog(L, 3250, 150))); + const [hx, hy] = deskCursor(t); + tf(hint, hx + 26, hy + 30, 1, prog(L, 2400, 200) * (1 - prog(L, 3500, 150))); + + const dp = prog(L, 3700, 800, ease.move); + const sw = lerp(0, 948, dp), sh = lerp(0, 626, dp); + sel.style.width = `${sw}px`; + sel.style.height = `${sh}px`; + sel.style.boxShadow = "0 0 0 1px rgb(0 0 0 / 25%), 0 0 0 4000px rgb(7 8 7 / 64%)"; + show(sel, dragging ? 1 : 0); + dims.textContent = `${Math.round(sw)} × ${Math.round(sh)} px`; + tf(dims, 0, 0, 1, dragging ? 1 : 0); + handles.forEach((handle, i) => { + const p = prog(L, 4550 + i * 18, 200); + handle.style.transform = `scale(${p})`; + }); + tf(rail, (1 - prog(L, 4600, 260)) * 12, 0, 1, prog(L, 4600, 220)); + tf(toolDock, 0, (1 - prog(L, 4650, 260)) * 12, 1, prog(L, 4650, 220)); + + const activeTool = L < 5500 ? 0 : L < 7100 ? 1 : L < 8400 ? 2 : L < 9650 ? 4 : 3; + tools.forEach((tool, i) => tool.classList.toggle("on", i === activeTool)); + const copying = L >= 10800 && L < 11050; + railTools[0].classList.toggle("on", copying); + + const rp = prog(L, 5950, 650, ease.move); + annoRect.style.width = `${312 * rp}px`; + annoRect.style.height = `${130 * rp}px`; + show(annoRect, L >= 5950 ? 1 : 0); + annoHl.style.width = `${172 * prog(L, 7500, 450, ease.move)}px`; + show(annoHl, L >= 7500 ? 0.62 : 0); + [8700, 8950, 9200].forEach((popAt, i) => { + const p = prog(L, popAt, 260); + tf(badges[i], 0, 0, lerp(0.5, 1, p), L >= popAt ? Math.min(1, p * 1.6) : 0); + }); + const bp = prog(L, 10000, 450, ease.move); + blurBox.style.width = `${258 * bp}px`; + blurBox.style.height = `${112 * bp}px`; + show(blurBox, L >= 10000 ? 1 : 0); + + } + const toastP = prog(L, 10850, 260); + tf(toastCopy, 0, (1 - toastP) * 10, lerp(0.97, 1, toastP), L >= 10850 && L < 12400 ? toastP * (1 - prog(L, 12100, 200)) : 0); + + /* --- screen draw (S3) --- */ + const D = t - S3; + const drawO = t >= S3 && t < S4 ? 1 - prog(D, 7050, 300) : 0; + show(draw, drawO); + if (drawO > 0) { + const dockP = prog(D, 2600, 260); + tf(drawDockRow, 0, (1 - dockP) * 16, 1, dockP); + tf(live, 0, (1 - prog(D, 2700, 260)) * -8, 1, prog(D, 2700, 240)); + const tool = D < 3750 ? 0 : D < 4500 ? 2 : D < 5500 ? 4 : 5; + drawTools.forEach((node, i) => node.classList.toggle("on", i === tool)); + inkCircle.style.strokeDashoffset = String(inkLens[0] * (1 - prog(D, 2900, 800, ease.inOut))); + inkArrow.style.strokeDashoffset = String(inkLens[1] * (1 - prog(D, 3800, 500, ease.inOut))); + inkHead.style.strokeDashoffset = String(inkLens[2] * (1 - prog(D, 4300, 150, ease.linear))); + show(inkCircle, D >= 2900 ? 1 : 0); + show(inkArrow, D >= 3800 ? 1 : 0); + show(inkHead, D >= 4300 ? 1 : 0); + const writeP = prog(D, 4550, 800, ease.linear); + scrawl.style.clipPath = `inset(-20px ${((1 - writeP) * 100).toFixed(2)}% -20px -10px)`; + show(scrawl, D >= 4550 ? 1 : 0); + const spotO = prog(D, 5550, 260); + const [sx, sy] = deskCursor(t); + spot.style.background = `radial-gradient(circle at ${sx}px ${sy}px, transparent 0, transparent 186px, rgb(7 8 7 / 74%) 198px)`; + show(spot, spotO); + } + + /* --- recording (S5) --- */ + const R = t - S5; + const recO = t >= S5 && t < S6 ? 1 - prog(R, 6100, 180) : 0; + show(rec, recO); + if (recO > 0) { + const digits = ["3", "2", "1"]; + const step = Math.floor((R - 2500) / 300); + if (step >= 0 && step < 3) { + const local = R - 2500 - step * 300; + countdown.textContent = digits[step]; + tf(countdown, 0, 0, lerp(0.86, 1, prog(local, 0, 160)), prog(local, 0, 120) * (1 - prog(local, 220, 80))); + } else { + show(countdown, 0); + } + show(recBorder, prog(R, 3400, 160)); + tf(recDock, 0, (1 - prog(R, 3400, 280)) * 16, 1, prog(R, 3400, 240)); + const elapsed = Math.max(0, Math.floor((R - 3400) / 1000)); + recTime.textContent = `00:${String(elapsed).padStart(2, "0")}`; + recStop.style.transform = R >= 5950 && R < 6100 ? "scale(0.95)" : "none"; + } + } + + function renderCursorAndRipples(t, cam, wrap) { + const [dx, dy] = deskCursor(t); + const sx = (dx * cam.s + cam.tx) * wrap.s + wrap.x; + const sy = (dy * cam.s + cam.ty) * wrap.s + wrap.y; + let o = 0; + for (const [a, b] of VISIBLE) if (t >= a - 150 && t <= b + 150) o = Math.max(o, prog(t, a - 150, 150) * (1 - prog(t, b, 150))); + let kind = "arrow"; + for (const [time, k] of KINDS) if (t >= time) kind = k; + cursorKinds.forEach((svg) => { svg.style.display = svg.dataset.k === kind ? "block" : "none"; }); + const pressed = CLICKS.some((c) => t >= c && t < c + 140); + const scale = cam.s * wrap.s * (pressed ? 0.86 : 1); + tf(cursor, sx, sy, scale, o); + for (const ripple of RIPPLES) { + const p = clamp((t - ripple.time) / 520); + const active = t >= ripple.time && p < 1; + const rx = (ripple.x * cam.s + cam.tx) * wrap.s + wrap.x; + const ry = (ripple.y * cam.s + cam.ty) * wrap.s + wrap.y; + tf(ripple.node, rx, ry, lerp(0.35, 1.7, ease.out(p)) * cam.s * wrap.s, active ? 0.9 * (1 - p) : 0); + } + } + + function renderStudio(t, wrap) { + const R = t - S5; + const out = 1 - prog(t, S6, 450); + show(studioBg, t >= S5 ? prog(R, 6100, 500) * out : 0); + const panelP = prog(R, 6500, 320); + tf(timelinePanel, 0, (1 - panelP) * 20, 1, panelP); + tf(autoPill, 0, (1 - prog(R, 7300, 260)) * 8, 1, prog(R, 7300, 240)); + show(studioUi, t >= S5 + 6400 ? out : 0); + const f = clamp((t - PLAYBACK_START) / PLAYBACK_DUR); + playhead.style.transform = `translateX(${(f * 1268).toFixed(1)}px)`; + zoomBlocks.forEach((block, i) => { + const [a, b] = ZOOM_BLOCKS[i]; + block.style.opacity = f >= a && f <= b ? "1" : "0.55"; + }); + + // Camera bubble: recorder corner → studio canvas corner + const camIn = prog(R, 3450, 320); + const recPos = { x: 1650, y: 750, s: 1 }; + const studioPos = { x: wrap.x + 1660 * STUDIO.s - 10, y: wrap.y + 790 * STUDIO.s - 6, s: 0.62 }; + const p = wrap.p; + const bx = lerp(recPos.x, studioPos.x, p), by = lerp(recPos.y, studioPos.y, p), bs = lerp(recPos.s, studioPos.s, p); + const visible = t >= S5 + 3450 && t < S6 + 600; + tf(camBubble, bx, by + (1 - camIn) * 12, bs * lerp(0.92, 1, camIn), visible ? camIn * out : 0); + } + + function renderShowcase(t) { + const C = t - S4; + const visible = t >= S4 + 300 && t < S5 + 300; + show(showcase, visible ? 1 : 0); + if (!visible) return; + const CLICK_AT = [[0, 0], [2450, 1], [3250, 2], [4100, 4], [4900, 3]]; + let from = 0, to = 0, switchAt = 0; + for (const [time, look] of CLICK_AT) if (C >= time) { from = to; to = look; switchAt = time; } + const p = switchAt === 0 ? 1 : prog(C, switchAt, 480, ease.inOut); + const a = LOOKS[from], b = LOOKS[to]; + const mix = (key) => lerp(a[key], b[key], p); + backdrops.forEach((bd, i) => { + const fade = prog(C, switchAt, 380); + show(bd, i === to ? 1 : i === from && switchAt !== 0 ? 1 - fade : 0); + bd.style.zIndex = i === to ? "1" : "0"; + }); + const enter = prog(C, 1100, 760); + const s = mix("s") * lerp(0.94, 1, enter); + shot.style.transform = `translate3d(486px, ${142 + (1 - enter) * 40}px, 0) perspective(2400px) rotateX(${mix("rx")}deg) rotateY(${mix("ry")}deg) scale(${s})`; + shot.style.zIndex = "2"; + show(shot, enter); + shotClip.style.borderRadius = `${mix("r")}px`; + shotShadow.style.borderRadius = `${mix("r")}px`; + shotShadow.style.opacity = String(mix("shadow")); + shotBezel.style.opacity = String(mix("bezel")); + lookTiles.forEach((tile, i) => tile.classList.toggle("on", i === to)); + const ui = prog(C, 1500, 300); + tf(looksStrip, 0, (1 - ui) * 16, 1, ui, "translateX(-50%)"); + looksStrip.style.transform = `translateX(-50%) translateY(${((1 - ui) * 16).toFixed(1)}px)`; + looksStrip.style.zIndex = "3"; + tf(copyBtn, 0, (1 - ui) * -10, 1, ui); + tf(exportBtn, 0, (1 - ui) * -10, C >= 6000 && C < 6140 ? 0.95 : 1, ui); + copyBtn.style.zIndex = exportBtn.style.zIndex = "3"; + const toastP = prog(C, 6050, 260); + tf(toastExport, 0, (1 - toastP) * -10, lerp(0.97, 1, toastP), C >= 6050 ? toastP : 0); + toastExport.style.zIndex = "4"; + } + + function renderIntroOutro(t) { + /* intro */ + const introOut = 1 - prog(t, 3000, 380); + const introVisible = t < 3500; + show(introLogo, introVisible ? prog(t, 150, 450) * introOut : 0); + if (introVisible) { + introLogo.style.transform = `translateY(${(-prog(t, 3000, 380) * 12).toFixed(1)}px) scale(${lerp(0.9, 1, prog(t, 150, 700))})`; + $("#inBr").style.strokeDashoffset = String(1 - prog(t, 350, 850, ease.inOut)); + $("#inSq").style.transform = `scale(${prog(t, 800, 450)})`; + $("#inAr").style.strokeDashoffset = String(1 - prog(t, 1100, 350, ease.inOut)); + introWords.forEach((word, i) => { + const p = prog(t, 1450 + i * 75, 720); + word.style.transform = `translateY(${((1 - p) * 0.4).toFixed(3)}em)`; + word.style.opacity = String(p); + }); + } + show(introLines, introVisible ? introOut : 0); + + /* corners: logo frame expands to the full screen as the desktop arrives */ + const cP = prog(t, S1 + 1100, 760, ease.inOut); + const box = { x: lerp(866, 26, cP), y: lerp(266, 26, cP), w: lerp(188, 1868, cP), h: lerp(188, 1028, cP) }; + const cornersO = t >= S1 + 1000 && t < S1 + 2200 ? prog(t, S1 + 1000, 150) * (1 - prog(t, S1 + 1750, 350)) : 0; + show(frameCorners, cornersO); + const size = lerp(40, 64, cP); + corners.forEach((corner, i) => { + const x = i === 0 || i === 3 ? box.x : box.x + box.w - size; + const y = i < 2 ? box.y : box.y + box.h - size; + corner.style.left = `${x}px`; + corner.style.top = `${y}px`; + corner.style.width = corner.style.height = `${size}px`; + }); + frameCorners.style.zIndex = "55"; + + /* size reveal */ + const Z = t - S6; + const sizeVisible = t >= S6 && t < S7 + 200; + const sizeOut = 1 - prog(Z, 3900, 400); + show(sizeEye, sizeVisible ? prog(Z, 500, 320) * sizeOut : 0); + sizeEye.style.transform = `translateY(${((1 - prog(Z, 500, 400)) * 10).toFixed(1)}px)`; + const countP = prog(Z, 650, 1200, ease.out); + bigSize.innerHTML = `${(5.4 * countP).toFixed(1)}MB`; + show(bigSize, sizeVisible ? prog(Z, 600, 300) * sizeOut : 0); + bigSize.style.transform = `translateY(${((1 - prog(Z, 600, 600)) * 24).toFixed(1)}px)`; + ticks.style.transform = `scaleX(${prog(Z, 900, 700, ease.inOut)})`; + ticks.style.transformOrigin = "50% 50%"; + show(ticks, sizeVisible ? sizeOut : 0); + stats.forEach((stat, i) => { + const p = prog(Z, 1900 + i * 140, 420); + tf(stat, 0, (1 - p) * 12, 1, sizeVisible ? p * sizeOut : 0, "translateX(-50%)"); + stat.style.transform = `translateX(-50%) translateY(${((1 - p) * 12).toFixed(1)}px)`; + }); + const converge = prog(Z, 3900, 520, ease.inOut); + chips.forEach((chip, i) => { + const p = prog(Z, 2500 + i * 110, 420); + const homeX = 452 + i * 262 + 118; + const dx = (960 - homeX) * converge; + const dy = (420 - 844) * converge; + tf(chip, dx, (1 - p) * 14 + dy, lerp(1, 0.35, converge), sizeVisible ? p * (1 - prog(Z, 4150, 260)) : 0); + }); + + /* end card */ + const E = t - S7; + const endVisible = t >= S7 - 200; + const fadeAll = 1 - prog(t, END - 600, 600, ease.inOut); + const logoIn = prog(E, -200, 650); + const slide = prog(E, 700, 650, ease.inOut); + const logoX = lerp(960 - 75, 632, slide); + tf(endLogo, logoX, 322, lerp(0.6, 1, logoIn), endVisible ? logoIn * fadeAll : 0); + endLogo.style.transformOrigin = "75px 75px"; + $("#endBr").style.strokeDashoffset = String(1 - prog(E, -100, 700, ease.inOut)); + $("#endSq").style.transform = `scale(${prog(E, 100, 450)})`; + $("#endAr").style.strokeDashoffset = String(1 - prog(E, 350, 350, ease.inOut)); + const wordP = prog(E, 850, 600); + endWord.style.clipPath = `inset(-20px ${((1 - wordP) * 100).toFixed(1)}% -20px -20px)`; + tf(endWord, (1 - wordP) * -24, 0, 1, endVisible ? wordP * fadeAll : 0); + const tagP = prog(E, 1350, 520); + tf(endTag, 0, (1 - tagP) * 12, 1, tagP * fadeAll); + const metaP = prog(E, 1700, 520); + tf(endMeta, 0, (1 - metaP) * 10, 1, metaP * fadeAll); + } + + function seek(ms) { + const t = clamp(ms, 0, END); + const cam = cameraAt(t); + const wrap = t >= S5 && t < S6 + 600 ? wrapAt(t) : { s: 1, x: 0, y: 0, p: 0 }; + renderDesk(t, cam, wrap); + renderStudio(t, wrap); + renderShowcase(t); + renderCursorAndRipples(t, cam, wrap); + renderHeadline(t); + renderKeys(t); + renderIntroOutro(t); + } + window.seek = seek; + + /* ----------------------------------------------------- preview modes ---- */ + const params = new URLSearchParams(location.search); + if (params.has("play")) { + const from = Number(params.get("from") ?? 0); + document.fonts.ready.then(() => { + const started = performance.now(); + const frame = (now) => { + const t = from + (now - started); + seek(t % END); + requestAnimationFrame(frame); + }; + requestAnimationFrame(frame); + }); + } else { + seek(Number(params.get("t") ?? 0)); + document.fonts.ready.then(() => seek(Number(params.get("t") ?? 0))); + } +})(); From 840490b88537d8273226ee0f9338eeb8eaf19f60 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 21:34:13 +0530 Subject: [PATCH 02/16] feat(store): MSIX startup task, device capabilities, and license notices - Open at startup uses a manifest windows.startupTask when CapKit has package identity; unpackaged builds keep the autostart plugin entry. Both sit behind a StartupBackend trait, and a startup-task activation is treated like --background. - Settings reads and changes startup through validated IPC. It locks the switch when the user (in Windows) or a policy controls the task, and links to Startup settings. - Declare microphone and webcam device capabilities. - build-msix.ps1 stages LICENSE.txt and a THIRD_PARTY_NOTICES.txt generated from cargo metadata and pnpm licenses. - Drop the unused JS autostart plugin and its webview permissions. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG-PUBLIC.md | 8 + apps/desktop/package.json | 1 - apps/desktop/src-tauri/Cargo.toml | 2 + .../src-tauri/capabilities/default.json | 3 - apps/desktop/src-tauri/msix/AppxManifest.xml | 18 +- apps/desktop/src-tauri/src/domain.rs | 87 +++++++ apps/desktop/src-tauri/src/error.rs | 6 + apps/desktop/src-tauri/src/lib.rs | 75 +++++- apps/desktop/src-tauri/src/platform/mod.rs | 18 +- .../src-tauri/src/platform/plugin_startup.rs | 50 ++++ .../src-tauri/src/platform/windows_shell.rs | 6 + .../src-tauri/src/platform/windows_startup.rs | 92 +++++++ .../src/components/dashboard/SettingsView.tsx | 99 +++++--- apps/desktop/src/lib/startup.test.ts | 63 +++++ apps/desktop/src/lib/startup.ts | 65 +++++ docs/current-status.md | 1 + docs/decision-log.md | 6 +- docs/microsoft-store-release.md | 25 +- package.json | 3 +- pnpm-lock.yaml | 10 - scripts/build-msix.ps1 | 7 + scripts/third-party-notices.ts | 235 ++++++++++++++++++ 22 files changed, 827 insertions(+), 53 deletions(-) create mode 100644 apps/desktop/src-tauri/src/platform/plugin_startup.rs create mode 100644 apps/desktop/src-tauri/src/platform/windows_startup.rs create mode 100644 apps/desktop/src/lib/startup.test.ts create mode 100644 apps/desktop/src/lib/startup.ts create mode 100644 scripts/third-party-notices.ts diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index a5e5d48..bd867af 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,6 +2,14 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. +## Unreleased — 2026-10-29 + +### Improved + +- Open at startup works in the Microsoft Store version, using Windows' own startup list. +- If you turned CapKit off in Windows' startup settings, CapKit's Settings now tells you so and opens the right Windows page to turn it back on. +- The Store version asks for camera and microphone access through Windows' standard prompts. + ## 0.3.0 — 2026-09-28 ### Fixed diff --git a/apps/desktop/package.json b/apps/desktop/package.json index bb92a85..7c09392 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -22,7 +22,6 @@ "@hugeicons/core-free-icons": "4.2.3", "@hugeicons/react": "1.1.9", "@tauri-apps/api": "^2.11.1", - "@tauri-apps/plugin-autostart": "^2.5.1", "@tauri-apps/plugin-dialog": "^2.7.1", "@tauri-apps/plugin-global-shortcut": "^2.3.2", "konva": "^10.3.0", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 2541e52..505564e 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -35,6 +35,8 @@ xcap = { version = "0.9.6", features = ["image", "wgc"] } [target.'cfg(target_os = "windows")'.dependencies] windows = { version = "0.62.2", features = [ "Foundation", "Globalization", "Graphics_Imaging", "Storage", "Storage_Streams", + # Package identity and the MSIX startup task (Store build only). + "ApplicationModel", "ApplicationModel_Activation", "Win32_Foundation", "Win32_System_Com", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", # Recording: a Windows Graphics Capture frame pool onto our own D3D11 device. diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index d618432..63fd658 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -11,9 +11,6 @@ "core:window:allow-start-dragging", "core:window:allow-set-resizable", "dialog:default", - "autostart:allow-enable", - "autostart:allow-disable", - "autostart:allow-is-enabled", "global-shortcut:default" ] } diff --git a/apps/desktop/src-tauri/msix/AppxManifest.xml b/apps/desktop/src-tauri/msix/AppxManifest.xml index e08d2a7..b2d2d9e 100644 --- a/apps/desktop/src-tauri/msix/AppxManifest.xml +++ b/apps/desktop/src-tauri/msix/AppxManifest.xml @@ -4,7 +4,8 @@ xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="uap uap10 rescap"> + xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" + IgnorableNamespaces="uap uap10 rescap desktop"> + + + + + + + + + diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index 612308a..99d730f 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -422,3 +422,90 @@ mod request_tests { assert_eq!(request.system_audio_device_id, None); } } + +/// Whether CapKit opens when the user signs in, and who decides. +/// +/// The policy and user variants come from the MSIX startup task: once a user +/// turns CapKit off in Windows Settings or Task Manager, or a policy pins the +/// state, the app cannot change it and the UI must say so. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StartupStatus { + Enabled, + Disabled, + DisabledByUser, + DisabledByPolicy, + EnabledByPolicy, +} + +impl StartupStatus { + /// Maps a `Windows.ApplicationModel.StartupTaskState` value. Unknown + /// future values read as disabled rather than failing the settings page. + pub fn from_task_state(state: i32) -> Self { + match state { + 1 => Self::DisabledByUser, + 2 => Self::Enabled, + 3 => Self::DisabledByPolicy, + 4 => Self::EnabledByPolicy, + _ => Self::Disabled, + } + } +} + +/// `package` is the MSIX startup task (Store build); `app` is the per-user +/// sign-in entry CapKit writes itself in the unpackaged installer and dev builds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StartupManager { + Package, + App, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupStateDto { + pub status: StartupStatus, + pub managed_by: StartupManager, +} + +#[cfg(test)] +mod startup_tests { + use super::{StartupManager, StartupStateDto, StartupStatus}; + + #[test] + fn maps_every_documented_task_state() { + assert_eq!(StartupStatus::from_task_state(0), StartupStatus::Disabled); + assert_eq!( + StartupStatus::from_task_state(1), + StartupStatus::DisabledByUser + ); + assert_eq!(StartupStatus::from_task_state(2), StartupStatus::Enabled); + assert_eq!( + StartupStatus::from_task_state(3), + StartupStatus::DisabledByPolicy + ); + assert_eq!( + StartupStatus::from_task_state(4), + StartupStatus::EnabledByPolicy + ); + } + + #[test] + fn unknown_task_state_reads_as_disabled() { + assert_eq!(StartupStatus::from_task_state(99), StartupStatus::Disabled); + assert_eq!(StartupStatus::from_task_state(-1), StartupStatus::Disabled); + } + + #[test] + fn startup_state_serializes_for_the_settings_schema() { + let value = serde_json::to_value(StartupStateDto { + status: StartupStatus::DisabledByUser, + managed_by: StartupManager::Package, + }) + .expect("startup state serializes"); + assert_eq!( + value, + serde_json::json!({ "status": "disabled-by-user", "managedBy": "package" }) + ); + } +} diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index 224cee5..35c63f9 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -20,6 +20,8 @@ pub enum SnaphubError { Shortcut(String), #[error("SH-WINDOW-001: {0}")] Window(String), + #[error("SH-STARTUP-001: {0}")] + Startup(String), } impl SnaphubError { @@ -46,6 +48,10 @@ impl SnaphubError { pub fn audio(error: impl std::fmt::Display) -> Self { Self::Audio(error.to_string()) } + + pub fn startup(error: impl std::fmt::Display) -> Self { + Self::Startup(error.to_string()) + } } impl serde::Serialize for SnaphubError { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 5dfb48e..9a5fba9 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -7,7 +7,7 @@ use std::{ collections::HashMap, path::{Path, PathBuf}, str::FromStr, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, OnceLock}, time::Duration, }; @@ -16,8 +16,11 @@ use domain::{ CompletionStatus, DetectedTargetDto, DisplayDto, MediaFileDto, MediaFolderDto, OnScreenSessionDto, Point, RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, Rect, SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, + StartupStateDto, }; use error::SnaphubError; +use platform::StartupBackend; +use platform::plugin_startup::PluginStartup; use platform::xcap_backend::{XcapPlatformBackend, display_bounds}; use services::capture::CaptureService; use services::recording::RecordingService; @@ -183,9 +186,29 @@ fn show_capture_surface(app: AppHandle) -> Result<(), SnaphubError> { Ok(()) } +/// True when this process started at sign-in: through the unpackaged sign-in +/// entry, which passes `--background`, or through the MSIX startup task, +/// which cannot pass arguments. Either way the dashboard stays hidden. +fn launched_in_background() -> bool { + static BACKGROUND: OnceLock = OnceLock::new(); + *BACKGROUND.get_or_init(|| { + if std::env::args().any(|argument| argument == "--background") { + return true; + } + #[cfg(target_os = "windows")] + { + platform::windows_startup::launched_by_startup_task() + } + #[cfg(not(target_os = "windows"))] + { + false + } + }) +} + #[tauri::command] fn dashboard_ready(app: AppHandle) -> Result<(), SnaphubError> { - if std::env::args().any(|argument| argument == "--background") { + if launched_in_background() { return Ok(()); } show_dashboard(&app) @@ -1681,6 +1704,47 @@ fn open_camera_privacy_settings() -> Result<(), SnaphubError> { } } +/// The package startup task in the Store build; the plugin's sign-in entry +/// otherwise. Never both: Store policy rejects a packaged app's Run entry. +fn startup_backend(app: &AppHandle) -> Box { + #[cfg(target_os = "windows")] + if platform::windows_startup::is_packaged() { + return Box::new(platform::windows_startup::PackagedStartupTask); + } + Box::new(PluginStartup::new(app.clone())) +} + +#[tauri::command] +async fn get_startup_state(app: AppHandle) -> Result { + tauri::async_runtime::spawn_blocking(move || startup_backend(&app).state()) + .await + .map_err(|error| SnaphubError::startup(format!("Startup worker failed: {error}")))? +} + +#[tauri::command] +async fn set_startup_enabled( + app: AppHandle, + enabled: bool, +) -> Result { + tauri::async_runtime::spawn_blocking(move || startup_backend(&app).set_enabled(enabled)) + .await + .map_err(|error| SnaphubError::startup(format!("Startup worker failed: {error}")))? +} + +#[tauri::command] +fn open_startup_settings() -> Result<(), SnaphubError> { + #[cfg(target_os = "windows")] + { + platform::windows_shell::open_startup_settings() + } + #[cfg(not(target_os = "windows"))] + { + Err(SnaphubError::Startup( + "Startup settings are only available on Windows".into(), + )) + } +} + #[tauri::command] fn close_camera(app: AppHandle) -> Result<(), SnaphubError> { if let Some(window) = app.get_webview_window("camera") { @@ -2272,10 +2336,13 @@ pub fn run() { camera_ready, close_camera, prepare_camera_permission, - open_camera_privacy_settings + open_camera_privacy_settings, + get_startup_state, + set_startup_enabled, + open_startup_settings ]) .setup(move |app| { - if std::env::args().any(|argument| argument == "--background") + if launched_in_background() && let Some(window) = app.get_webview_window("dashboard") { window.hide()?; diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs index 933db98..e829052 100644 --- a/apps/desktop/src-tauri/src/platform/mod.rs +++ b/apps/desktop/src-tauri/src/platform/mod.rs @@ -3,11 +3,12 @@ use image::RgbaImage; use crate::{ domain::{ AudioDeviceDto, DetectedTargetDto, DisplayDto, Point, RecordingArtifactsDto, - RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, + RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, StartupStateDto, }, error::SnaphubError, }; +pub(crate) mod plugin_startup; #[cfg(target_os = "windows")] pub(crate) mod windows_display; #[cfg(target_os = "windows")] @@ -15,6 +16,8 @@ pub(crate) mod windows_recorder; #[cfg(target_os = "windows")] pub mod windows_shell; #[cfg(target_os = "windows")] +pub(crate) mod windows_startup; +#[cfg(target_os = "windows")] pub(crate) mod windows_ui; #[cfg(target_os = "windows")] pub(crate) mod windows_webview; @@ -89,3 +92,16 @@ pub trait AudioDeviceBackend: Send + Sync { pub trait WindowCaptureExclusionBackend: Send + Sync { fn set_excluded(&self, hwnd: isize, excluded: bool) -> Result<(), SnaphubError>; } + +/// Opening CapKit when the user signs in. +/// +/// The Store (MSIX) build must use the manifest startup task: Store policy +/// rejects packaged apps that write their own Run entry. The unpackaged +/// installer has no package identity, so it keeps the per-user Run entry. +pub trait StartupBackend { + fn state(&self) -> Result; + /// Returns the resulting state. It can differ from the request when the + /// user turned CapKit off in Windows or a policy controls it; the caller + /// shows that state instead of treating it as a failure. + fn set_enabled(&self, enabled: bool) -> Result; +} diff --git a/apps/desktop/src-tauri/src/platform/plugin_startup.rs b/apps/desktop/src-tauri/src/platform/plugin_startup.rs new file mode 100644 index 0000000..a993375 --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/plugin_startup.rs @@ -0,0 +1,50 @@ +use tauri::AppHandle; +use tauri_plugin_autostart::ManagerExt; + +use crate::{ + domain::{StartupManager, StartupStateDto, StartupStatus}, + error::SnaphubError, + platform::StartupBackend, +}; + +/// The sign-in entry written by `tauri-plugin-autostart` (the per-user Run +/// key on Windows) for builds without package identity. The entry launches +/// CapKit with `--background`. Never use this in the Store build. +pub(crate) struct PluginStartup { + app: AppHandle, +} + +impl PluginStartup { + pub(crate) fn new(app: AppHandle) -> Self { + Self { app } + } +} + +impl StartupBackend for PluginStartup { + fn state(&self) -> Result { + let enabled = self + .app + .autolaunch() + .is_enabled() + .map_err(SnaphubError::startup)?; + Ok(StartupStateDto { + status: if enabled { + StartupStatus::Enabled + } else { + StartupStatus::Disabled + }, + managed_by: StartupManager::App, + }) + } + + fn set_enabled(&self, enabled: bool) -> Result { + let manager = self.app.autolaunch(); + if enabled { + manager.enable() + } else { + manager.disable() + } + .map_err(SnaphubError::startup)?; + self.state() + } +} diff --git a/apps/desktop/src-tauri/src/platform/windows_shell.rs b/apps/desktop/src-tauri/src/platform/windows_shell.rs index 3ccafc4..40b0f57 100644 --- a/apps/desktop/src-tauri/src/platform/windows_shell.rs +++ b/apps/desktop/src-tauri/src/platform/windows_shell.rs @@ -16,6 +16,12 @@ pub fn open_camera_privacy_settings() -> Result<(), SnaphubError> { open_uri("ms-settings:privacy-webcam") } +/// Opens Settings > Apps > Startup, the only place a user can turn the +/// startup task back on after turning it off there or in Task Manager. +pub fn open_startup_settings() -> Result<(), SnaphubError> { + open_uri("ms-settings:startupapps") +} + fn open_uri(uri: &str) -> Result<(), SnaphubError> { let verb = wide(OsStr::new("open")); let target = wide(OsStr::new(uri)); diff --git a/apps/desktop/src-tauri/src/platform/windows_startup.rs b/apps/desktop/src-tauri/src/platform/windows_startup.rs new file mode 100644 index 0000000..cb3602f --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/windows_startup.rs @@ -0,0 +1,92 @@ +use std::sync::OnceLock; + +use windows::{ + ApplicationModel::{ + Activation::ActivationKind, AppInstance, Package, StartupTask, StartupTaskState, + }, + core::HSTRING, +}; + +use crate::{ + domain::{StartupManager, StartupStateDto, StartupStatus}, + error::SnaphubError, + platform::StartupBackend, +}; + +/// Must match the `desktop:StartupTask` `TaskId` in `msix/AppxManifest.xml`. +const STARTUP_TASK_ID: &str = "CapKitStartup"; + +/// True when this process runs from an installed MSIX package. Package +/// identity cannot change during a process, so the lookup runs once. +pub(crate) fn is_packaged() -> bool { + static PACKAGED: OnceLock = OnceLock::new(); + *PACKAGED.get_or_init(|| Package::Current().is_ok()) +} + +/// True when Windows started this process through the startup task. That +/// activation cannot carry arguments, so this is the packaged equivalent of +/// the `--background` flag the unpackaged sign-in entry passes. +pub(crate) fn launched_by_startup_task() -> bool { + is_packaged() + && AppInstance::GetActivatedEventArgs() + .and_then(|arguments| arguments.Kind()) + .is_ok_and(|kind| kind == ActivationKind::StartupTask) +} + +/// The manifest startup task of the Store build. +/// +/// Calls block on WinRT async operations, so run them off the main thread. +pub(crate) struct PackagedStartupTask; + +impl PackagedStartupTask { + fn task() -> Result { + StartupTask::GetAsync(&HSTRING::from(STARTUP_TASK_ID)) + .and_then(|operation| operation.join()) + .map_err(|error| { + SnaphubError::startup(format!( + "Startup task {STARTUP_TASK_ID} is unavailable: {error}" + )) + }) + } +} + +fn package_state(state: StartupTaskState) -> StartupStateDto { + StartupStateDto { + status: StartupStatus::from_task_state(state.0), + managed_by: StartupManager::Package, + } +} + +impl StartupBackend for PackagedStartupTask { + fn state(&self) -> Result { + Self::task()? + .State() + .map(package_state) + .map_err(SnaphubError::startup) + } + + fn set_enabled(&self, enabled: bool) -> Result { + let task = Self::task()?; + let current = task.State().map_err(SnaphubError::startup)?; + // Windows ignores both calls once the user turned CapKit off in + // Settings or Task Manager, or a policy owns the state. + if !matches!( + StartupStatus::from_task_state(current.0), + StartupStatus::Enabled | StartupStatus::Disabled + ) { + return Ok(package_state(current)); + } + if enabled { + // Desktop apps get no consent dialog here; the result is final. + task.RequestEnableAsync() + .and_then(|operation| operation.join()) + .map(package_state) + .map_err(SnaphubError::startup) + } else { + task.Disable().map_err(SnaphubError::startup)?; + task.State() + .map(package_state) + .map_err(SnaphubError::startup) + } + } +} diff --git a/apps/desktop/src/components/dashboard/SettingsView.tsx b/apps/desktop/src/components/dashboard/SettingsView.tsx index bf88813..0e082c8 100644 --- a/apps/desktop/src/components/dashboard/SettingsView.tsx +++ b/apps/desktop/src/components/dashboard/SettingsView.tsx @@ -40,6 +40,13 @@ import { updateGlobalShortcuts, } from "../../lib/tauri"; import { captureCursor, onScreenCursor } from "../../lib/cursor"; +import { + getStartupState, + openStartupSettings, + presentStartupState, + setStartupEnabled, + type StartupState, +} from "../../lib/startup"; import { SettingsTabs, type SettingsTabId } from "./SettingsTabs"; import { ToolbarConfiguration } from "./ToolbarConfiguration"; @@ -137,6 +144,10 @@ export function SettingsView(): React.JSX.Element { const [recordingDirectory, setRecordingDirectoryState] = useState("Videos\\Capkit"); const [recordingMessage, setRecordingMessage] = useState(null); const [choosingRecordingDirectory, setChoosingRecordingDirectory] = useState(false); + // Null until the native state loads; the saved preference stands in. + const [startupState, setStartupState] = useState(null); + const [changingStartup, setChangingStartup] = useState(false); + const [startupMessage, setStartupMessage] = useState(null); const [activeTab, setActiveTab] = useState("general"); const [openSections, setOpenSections] = useState>(defaultOpenSections); @@ -153,14 +164,20 @@ export function SettingsView(): React.JSX.Element { useEffect(() => { if (!isTauri()) return; - void import("@tauri-apps/plugin-autostart") - .then(({ isEnabled }) => isEnabled()) - .then((enabled) => { - if (enabled !== settings.openAtStartup) updateSettings({ ...settings, openAtStartup: enabled }); - }) - .catch((error: unknown) => console.error("SH-AUTOSTART-READ-001", error)); + void loadStartupState(); }, []); + // Turning CapKit back on happens in Windows Settings, so re-read the state + // when the user returns. Only while that is the pending fix; no polling. + useEffect(() => { + if (startupState?.status !== "disabled-by-user") return; + function refresh(): void { + void loadStartupState(); + } + window.addEventListener("focus", refresh); + return (): void => window.removeEventListener("focus", refresh); + }, [startupState?.status]); + useEffect(() => { if (!isTauri()) return; void registerShortcuts(settings.shortcuts).catch((error: unknown) => { @@ -246,16 +263,42 @@ export function SettingsView(): React.JSX.Element { update({ ...settings, customColors, palette }); } - async function toggleAutostart(enabled: boolean): Promise { - update({ ...settings, openAtStartup: enabled }); - if (!isTauri()) return; + function applyStartupState(state: StartupState): void { + setStartupState(state); + const isOn = presentStartupState(state).isOn; + if (isOn !== settings.openAtStartup) updateSettings({ ...settings, openAtStartup: isOn }); + } + + async function loadStartupState(): Promise { try { - const plugin = await import("@tauri-apps/plugin-autostart"); - if (enabled) await plugin.enable(); - else await plugin.disable(); + applyStartupState(await getStartupState()); + setStartupMessage(null); } catch (error: unknown) { - update({ ...settings, openAtStartup: !enabled }); - console.error("SH-AUTOSTART-WRITE-001", error); + setStartupMessage(describeInvokeError(error, "Startup setting could not be loaded")); + } + } + + async function changeStartup(enabled: boolean): Promise { + if (!isTauri()) { + update({ ...settings, openAtStartup: enabled }); + return; + } + setChangingStartup(true); + setStartupMessage(null); + try { + applyStartupState(await setStartupEnabled(enabled)); + } catch (error: unknown) { + setStartupMessage(describeInvokeError(error, "Startup setting could not be changed")); + } finally { + setChangingStartup(false); + } + } + + async function showStartupSettings(): Promise { + try { + await openStartupSettings(); + } catch (error: unknown) { + setStartupMessage(describeInvokeError(error, "Windows Settings could not be opened")); } } @@ -375,17 +418,6 @@ export function SettingsView(): React.JSX.Element { } } - async function resetStartup(): Promise { - update({ ...settings, openAtStartup: false }); - if (!isTauri()) return; - try { - const plugin = await import("@tauri-apps/plugin-autostart"); - await plugin.disable(); - } catch (error: unknown) { - console.error("SH-AUTOSTART-RESET-001", error); - } - } - function resetDetection(): void { update({ ...settings, @@ -480,6 +512,8 @@ export function SettingsView(): React.JSX.Element { } } + const startup = presentStartupState(startupState ?? { status: settings.openAtStartup ? "enabled" : "disabled", managedBy: "app" }); + return (
@@ -495,8 +529,15 @@ export function SettingsView(): React.JSX.Element { {activeTab === "general" ? ( <> - void toggleAutostart(enabled)} /> - void resetStartup()} /> + void changeStartup(enabled)} /> + {startup.notice === null ? null : ( +
+

{startup.notice}

+ {startup.canOpenWindowsSettings ? : null} +
+ )} + {startupMessage === null ? null :

{startupMessage}

} + void changeStartup(false)} />
{accentColors.map((color) => update({ ...settings, accentColor: color })} />)}
@@ -829,8 +870,8 @@ function ColorButton({ color, label, selected, disabled = false, onClick }: Colo function SectionReset({ onClick }: { onClick: () => void }): React.JSX.Element { return
; } -type ToggleFieldProps = { label: string; description: string; checked: boolean; onChange: (checked: boolean) => void }; -function ToggleField({ label, description, checked, onChange }: ToggleFieldProps): React.JSX.Element { return ; } +type ToggleFieldProps = { label: string; description: string; checked: boolean; disabled?: boolean; onChange: (checked: boolean) => void }; +function ToggleField({ label, description, checked, disabled = false, onChange }: ToggleFieldProps): React.JSX.Element { return ; } type ShortcutRowProps = { label: string; description: string; value: string; defaultValue: string; recording: boolean; onRecord: () => void; onReset: () => void }; function ShortcutRow({ label, description, value, defaultValue, recording, onRecord, onReset }: ShortcutRowProps): React.JSX.Element { return

{label}

{description}

; } diff --git a/apps/desktop/src/lib/startup.test.ts b/apps/desktop/src/lib/startup.test.ts new file mode 100644 index 0000000..eb6663f --- /dev/null +++ b/apps/desktop/src/lib/startup.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getStartupState, presentStartupState, setStartupEnabled, type StartupState } from "./startup"; + +const tauri = vi.hoisted(() => ({ invoke: vi.fn<(command: string, args?: unknown) => Promise>(), isTauri: vi.fn(() => true) })); + +vi.mock("@tauri-apps/api/core", () => tauri); + +describe("presentStartupState", () => { + it("lets CapKit change its own states", () => { + expect(presentStartupState({ status: "enabled", managedBy: "package" })).toEqual({ isOn: true, canChange: true, notice: null, canOpenWindowsSettings: false }); + expect(presentStartupState({ status: "disabled", managedBy: "app" })).toEqual({ isOn: false, canChange: true, notice: null, canOpenWindowsSettings: false }); + }); + + it("locks the switch and points to Windows when the user turned it off there", () => { + const presentation = presentStartupState({ status: "disabled-by-user", managedBy: "package" }); + expect(presentation.isOn).toBe(false); + expect(presentation.canChange).toBe(false); + expect(presentation.canOpenWindowsSettings).toBe(true); + expect(presentation.notice).toMatch(/Settings › Apps › Startup/); + }); + + it.each<[StartupState["status"], boolean]>([ + ["disabled-by-policy", false], + ["enabled-by-policy", true], + ])("locks the switch under %s", (status, isOn) => { + expect(presentStartupState({ status, managedBy: "package" })).toEqual({ + isOn, + canChange: false, + notice: "Your organization manages this setting.", + canOpenWindowsSettings: false, + }); + }); +}); + +describe("startup IPC", () => { + beforeEach(() => { + tauri.invoke.mockReset(); + tauri.isTauri.mockReturnValue(true); + }); + + it("validates the native state", async () => { + tauri.invoke.mockResolvedValueOnce({ status: "disabled-by-user", managedBy: "package" }); + await expect(getStartupState()).resolves.toEqual({ status: "disabled-by-user", managedBy: "package" }); + expect(tauri.invoke).toHaveBeenCalledWith("get_startup_state"); + }); + + it("rejects an unknown native state", async () => { + tauri.invoke.mockResolvedValueOnce({ status: "maybe", managedBy: "package" }); + await expect(getStartupState()).rejects.toThrow(); + }); + + it("returns the state Windows settled on, not the request", async () => { + tauri.invoke.mockResolvedValueOnce({ status: "disabled-by-user", managedBy: "package" }); + await expect(setStartupEnabled(true)).resolves.toEqual({ status: "disabled-by-user", managedBy: "package" }); + expect(tauri.invoke).toHaveBeenCalledWith("set_startup_enabled", { enabled: true }); + }); + + it("echoes the request outside the desktop shell", async () => { + tauri.isTauri.mockReturnValue(false); + await expect(setStartupEnabled(true)).resolves.toEqual({ status: "enabled", managedBy: "app" }); + expect(tauri.invoke).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/src/lib/startup.ts b/apps/desktop/src/lib/startup.ts new file mode 100644 index 0000000..a5a3bce --- /dev/null +++ b/apps/desktop/src/lib/startup.ts @@ -0,0 +1,65 @@ +import { invoke, isTauri } from "@tauri-apps/api/core"; +import { z } from "zod"; + +/** + * Open-at-sign-in state from the native side. `managedBy: "package"` is the + * Store build's MSIX startup task; `"app"` is the sign-in entry CapKit writes + * itself in the unpackaged build. + */ +export const startupStateSchema = z.object({ + status: z.enum(["enabled", "disabled", "disabled-by-user", "disabled-by-policy", "enabled-by-policy"]), + managedBy: z.enum(["package", "app"]), +}); + +export type StartupState = z.infer; + +export type StartupPresentation = { + isOn: boolean; + canChange: boolean; + /** Why the switch is locked, or null when CapKit controls it. */ + notice: string | null; + canOpenWindowsSettings: boolean; +}; + +/** + * Maps a startup state to what the Settings switch shows. Windows only lets + * the user undo a "turned off in Windows" choice from Windows itself, and a + * policy state cannot be changed at all, so both lock the switch. + */ +export function presentStartupState(state: StartupState): StartupPresentation { + switch (state.status) { + case "enabled": + return { isOn: true, canChange: true, notice: null, canOpenWindowsSettings: false }; + case "disabled": + return { isOn: false, canChange: true, notice: null, canOpenWindowsSettings: false }; + case "disabled-by-user": + return { + isOn: false, + canChange: false, + notice: "Turned off in Windows. Turn CapKit back on in Settings › Apps › Startup.", + canOpenWindowsSettings: true, + }; + case "disabled-by-policy": + return { isOn: false, canChange: false, notice: "Your organization manages this setting.", canOpenWindowsSettings: false }; + case "enabled-by-policy": + return { isOn: true, canChange: false, notice: "Your organization manages this setting.", canOpenWindowsSettings: false }; + } +} + +export async function getStartupState(): Promise { + if (!isTauri()) return { status: "disabled", managedBy: "app" }; + const raw: unknown = await invoke("get_startup_state"); + return startupStateSchema.parse(raw); +} + +/** Resolves with the resulting state, which can differ from the request. */ +export async function setStartupEnabled(enabled: boolean): Promise { + if (!isTauri()) return { status: enabled ? "enabled" : "disabled", managedBy: "app" }; + const raw: unknown = await invoke("set_startup_enabled", { enabled }); + return startupStateSchema.parse(raw); +} + +export async function openStartupSettings(): Promise { + if (!isTauri()) return; + await invoke("open_startup_settings"); +} diff --git a/docs/current-status.md b/docs/current-status.md index c07547d..d3b81a9 100644 --- a/docs/current-status.md +++ b/docs/current-status.md @@ -24,6 +24,7 @@ This document records what exists in the runtime today. The roadmap remains the - **Implemented:** Cloud remains a centered `Coming Soon...` placeholder; Showcase now opens a full-width scene builder with saved-capture selection, independently adjustable top/right/bottom/left padding (plus linked mode), background and frame visibility toggles, live background/radius controls, browser/glass/device frames, direct image dragging plus zoom/position/tilt/depth, shadows, effects, title/note layers, and local preset save/reset. - **Implemented:** A repeatable x64 Microsoft Store pipeline builds a full-trust Desktop Bridge `.msix`, symbols, and `.msixupload` with the reserved Partner Center identity. MakeAppx semantic validation and the initial Windows App Certification Kit run pass overall; interactive packaged-runtime checks remain required through a locally trusted build or private Store flight. - **Implemented:** Release executables use the Windows GUI subsystem, preventing an empty terminal window from appearing when an installed build starts. Debug builds retain console output, and the Store packager rejects any future console-subsystem executable. +- **Implemented:** The Store package uses a manifest startup task for Open at startup, chosen at runtime by package identity. The unpackaged build keeps its sign-in entry. When the user or a policy controls the task, Settings locks the switch and explains why. The package declares the microphone and webcam capabilities, and ships `LICENSE.txt` and generated third-party notices. Physical packaged-runtime testing is still pending. - **Implemented:** Self-hosted Plus Jakarta Sans for interface text and JetBrains Mono for shortcuts, dimensions, color values, and technical data. - **Implemented:** The dashboard window remains native-hidden through WebView bootstrap and is revealed only after its first styled React frame, preventing the repeated white startup flash. diff --git a/docs/decision-log.md b/docs/decision-log.md index 4c5b190..f4dc0d3 100644 --- a/docs/decision-log.md +++ b/docs/decision-log.md @@ -194,7 +194,11 @@ - **Confirmed:** The Store build is a manually assembled x64 Desktop Bridge MSIX with `packagedClassicApp`, `mediumIL`, and `runFullTrust`, preserving Win32 access required by capture, tray, global shortcuts, clipboard, scrolling input, and pin windows. - **Confirmed:** Store artifacts are generated as `.msix` and `.msixupload`; the Store submission uses `.msixupload` and Microsoft supplies the certified production signature. - **Provisional:** ARM64 packaging follows after the x64 packaged-runtime acceptance matrix passes. -- **Unresolved:** The existing Tauri autostart plugin must be physically validated across a Store update because MSIX installation paths are versioned. Use a manifest-declared startup task if registry-based startup does not survive updates. +- **Superseded (2026-10-29):** The Store build no longer uses the Tauri autostart plugin. + - **Confirmed:** Open at startup uses a manifest-declared `windows.startupTask`, because Store policy rejects a packaged app's own Run entry and MSIX install paths are versioned. + - **Confirmed:** Builds without package identity keep the plugin's sign-in entry. + - **Confirmed:** The manifest also declares the `microphone` and `webcam` device capabilities for recording. + - **Confirmed:** Packages ship `LICENSE.txt` and generated third-party notices. - **Confirmed:** Windows release binaries use PE GUI subsystem `2`; debug binaries keep console output. Store packaging validates this header so an installed release cannot regress to opening a terminal window. ## 2026-07-23 - Product renamed to CapKit diff --git a/docs/microsoft-store-release.md b/docs/microsoft-store-release.md index 4657fba..5033cc0 100644 --- a/docs/microsoft-store-release.md +++ b/docs/microsoft-store-release.md @@ -28,9 +28,13 @@ pnpm.cmd bundle:store For a later Store version: ```powershell -powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build-msix.ps1 -PackageVersion 1.0.2.0 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build-msix.ps1 -PackageVersion 1.3.0.0 ``` +**Confirmed (Microsoft rule):** A Store package version has four segments. The first segment cannot be `0`, the last must be `0`, and every new submission must be higher than the last one. So the app version `0.3.0` cannot become package `0.3.0.0`. The build script rejects it. + +**Provisional:** Package versions map app `0.X.Y` to `1.X.Y.0`, so app 0.3.0 ships as `1.3.0.0`. That is also higher than the earlier `1.0.2.0` build. + Outputs are written under `apps/desktop/src-tauri/target/store`: - `CapKit__x64.msix`: raw x64 package @@ -53,6 +57,18 @@ pnpm.cmd test:store The package targets x64 Windows Desktop with Windows 11 build `22000` as its minimum. ARM64 remains a separate future package and acceptance matrix. +**Confirmed:** Open at startup uses a manifest `windows.startupTask` (`CapKitStartup`, declared `Enabled="false"`), never a Run registry entry. At runtime, CapKit checks for package identity. If it has one, Settings drives the startup task. If not (the NSIS installer and dev builds), it keeps the `tauri-plugin-autostart` sign-in entry. A startup-task launch can't pass arguments, so CapKit treats that activation like `--background` and stays in the tray. If a user turns CapKit off in Settings > Apps > Startup or in Task Manager, Windows doesn't let the app turn it back on. CapKit then locks the switch, explains why, and links to `ms-settings:startupapps`. + +**Confirmed:** The manifest declares the `microphone` and `webcam` device capabilities for recording audio and the camera overlay. Windows shows its own consent prompt, and lists CapKit under the camera and microphone privacy settings. The Partner Center privacy policy URL must stay published, because the app accesses these devices. + +**Confirmed:** Every package contains `LICENSE.txt` and a `THIRD_PARTY_NOTICES.txt` generated at build time by `scripts/third-party-notices.ts` (`pnpm.cmd notices`). The notices cover: + +- the Rust crates linked into the Windows x64 binary; +- the production npm packages bundled into the frontend, including the OFL-1.1 fonts Plus Jakarta Sans, JetBrains Mono, and Caveat; +- the verbatim license texts for all of these. + +A few packages publish no license file. The notices list them with their declared license and source address. + ## Store acceptance checklist Automated build acceptance: @@ -81,8 +97,13 @@ Physical packaged-app acceptance remains required before submission: 7. Confirm Save, save-folder selection, dashboard thumbnails, View, Open Folder, and Delete work outside the package install directory. 8. Confirm Pin renders the capture, remains always on top, and can copy, save, click through, and close. 9. Confirm automatic and manual scrolling capture. -10. Confirm the startup preference persists through a Store update. The existing Tauri autostart plugin must be validated against the versioned MSIX install path; if it fails, replace it with a declared Windows startup task before certification. +10. Confirm the startup task: + - Turning it on in Settings opens CapKit into the tray at the next sign-in. + - Turning it off in Windows Settings locks the CapKit switch, and "Open Startup settings" reaches the right page. + - The setting survives a Store update. 11. Run the Windows App Certification Kit and resolve every blocker. 12. Uninstall and confirm package files are removed while user-authored captures remain intact. +13. Confirm the microphone and camera consent prompts appear, CapKit is listed under the camera and microphone privacy settings, and recordings capture microphone audio and the camera track. +14. Open `THIRD_PARTY_NOTICES.txt` and `LICENSE.txt` in the install folder and confirm both are current. Do not claim packaged-runtime acceptance from a successful build alone. Screen capture, shortcuts, startup, shell integration, and window behavior require physical testing of the installed Store package. diff --git a/package.json b/package.json index 0926edf..159249c 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "bundle:store": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build-msix.ps1", "test:store": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/test-msix.ps1", "version:bump": "node scripts/bump-version.ts", - "version:check": "node scripts/check-version.ts" + "version:check": "node scripts/check-version.ts", + "notices": "node scripts/third-party-notices.ts" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index adad060..5cfba48 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -28,9 +28,6 @@ importers: '@tauri-apps/api': specifier: ^2.11.1 version: 2.11.1 - '@tauri-apps/plugin-autostart': - specifier: ^2.5.1 - version: 2.5.1 '@tauri-apps/plugin-dialog': specifier: ^2.7.1 version: 2.7.1 @@ -920,9 +917,6 @@ packages: engines: {node: '>= 10'} hasBin: true - '@tauri-apps/plugin-autostart@2.5.1': - resolution: {integrity: sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w==} - '@tauri-apps/plugin-dialog@2.7.1': resolution: {integrity: sha512-OK1UBXYt+ojcmxMktzzuyonYIFta8CmAASpX+CA+DTGK24KlHjhYI6x2iOJ/TjZF4N7/ACK1oFmEOjIY9IhzOQ==} @@ -3457,10 +3451,6 @@ snapshots: '@tauri-apps/cli-win32-ia32-msvc': 2.11.4 '@tauri-apps/cli-win32-x64-msvc': 2.11.4 - '@tauri-apps/plugin-autostart@2.5.1': - dependencies: - '@tauri-apps/api': 2.11.1 - '@tauri-apps/plugin-dialog@2.7.1': dependencies: '@tauri-apps/api': 2.11.1 diff --git a/scripts/build-msix.ps1 b/scripts/build-msix.ps1 index af823af..28de2b8 100644 --- a/scripts/build-msix.ps1 +++ b/scripts/build-msix.ps1 @@ -88,6 +88,13 @@ Copy-Item -LiteralPath $executablePath -Destination (Join-Path $stageRoot 'capki foreach ($asset in @('Square44x44Logo.png', 'Square150x150Logo.png', 'StoreLogo.png')) { Copy-Item -LiteralPath (Join-Path $iconRoot $asset) -Destination (Join-Path $assetsRoot $asset) } +# License review: CapKit's license and the notices for every bundled crate, +# npm package, and font ship inside the package. +Copy-Item -LiteralPath (Join-Path $repoRoot 'LICENSE') -Destination (Join-Path $stageRoot 'LICENSE.txt') +Invoke-Checked -Command 'node' -Arguments @( + (Join-Path $repoRoot 'scripts\third-party-notices.ts'), + '--out', (Join-Path $stageRoot 'THIRD_PARTY_NOTICES.txt') +) $manifest = (Get-Content -LiteralPath $manifestTemplate -Raw).Replace('__PACKAGE_VERSION__', $PackageVersion) [System.IO.File]::WriteAllText( diff --git a/scripts/third-party-notices.ts b/scripts/third-party-notices.ts new file mode 100644 index 0000000..cde1776 --- /dev/null +++ b/scripts/third-party-notices.ts @@ -0,0 +1,235 @@ +/** + * Writes THIRD_PARTY_NOTICES.txt for the shipped desktop app. + * + * Covers what actually ends up in the package: Rust crates linked into + * `capkit-desktop.exe` for Windows x64 (normal dependencies only; build + * scripts, proc macros, and dev dependencies never ship), and the production + * npm packages bundled into the frontend, including the OFL-1.1 fonts. + * License files are copied verbatim from each package; identical texts are + * printed once with the packages that use them. + * + * Usage (Node 24+, from the repository root, after `pnpm.cmd install`): + * node scripts/third-party-notices.ts [--out ] + */ +import { execFileSync } from "node:child_process"; +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +const ROOT = join(import.meta.dirname, ".."); +const CARGO_MANIFEST = join(ROOT, "apps", "desktop", "src-tauri", "Cargo.toml"); +const DESKTOP_PACKAGE = "@snaphub/desktop"; +const TARGET = "x86_64-pc-windows-msvc"; +const LICENSE_FILE = /^(licen[cs]e|copying|notice|unlicense)([-_.].*)?$/i; +// Type declarations are erased at build time; nothing from them ships. +const TYPE_ONLY_PACKAGE = /^(@types\/|csstype$)/; + +type Component = { + ecosystem: "Rust crate" | "npm package"; + name: string; + version: string; + license: string; + source: string; + licenseTexts: readonly string[]; +}; + +function record(value: unknown, context: string): Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`${context} is not an object`); + } + // Narrowed above: a non-null, non-array object. + return value as Record; +} + +function list(value: unknown, context: string): unknown[] { + if (!Array.isArray(value)) throw new Error(`${context} is not an array`); + return value; +} + +function text(value: unknown, context: string): string { + if (typeof value !== "string") throw new Error(`${context} is not a string`); + return value; +} + +function optionalText(value: unknown): string | null { + return typeof value === "string" && value.trim() !== "" ? value : null; +} + +function readLicenseTexts(directory: string, declaredFile: string | null): string[] { + const names = new Set(); + if (declaredFile !== null) names.add(declaredFile); + for (const entry of readdirSync(directory, { withFileTypes: true })) { + if (entry.isFile() && LICENSE_FILE.test(entry.name)) names.add(entry.name); + } + return [...names] + .sort() + .map((name) => readFileSync(resolve(directory, name), "utf8").replace(/\r\n/g, "\n").trim()) + .filter((content) => content !== ""); +} + +function rustComponents(): Component[] { + const metadata = record( + JSON.parse( + execFileSync( + "cargo", + ["metadata", "--format-version", "1", "--locked", "--filter-platform", TARGET, "--manifest-path", CARGO_MANIFEST], + { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }, + ), + ), + "cargo metadata", + ); + const packages = new Map>(); + for (const entry of list(metadata.packages, "packages")) { + const item = record(entry, "package"); + packages.set(text(item.id, "package id"), item); + } + const resolveGraph = record(metadata.resolve, "resolve"); + const rootId = text(resolveGraph.root, "resolve root"); + const edges = new Map(); + for (const entry of list(resolveGraph.nodes, "resolve nodes")) { + const node = record(entry, "resolve node"); + const normal = list(node.deps, "node deps") + .map((dep) => record(dep, "node dep")) + .filter((dep) => + list(dep.dep_kinds, "dep kinds").some((kind) => record(kind, "dep kind").kind === null), + ) + .map((dep) => text(dep.pkg, "dep pkg")); + edges.set(text(node.id, "node id"), normal); + } + + const isProcMacro = (item: Record): boolean => + list(item.targets, "targets").some((target) => + list(record(target, "target").kind, "target kind").includes("proc-macro"), + ); + + const shipped = new Set(); + const pending = [...(edges.get(rootId) ?? [])]; + while (pending.length > 0) { + const id = pending.pop(); + if (id === undefined || shipped.has(id)) continue; + const item = packages.get(id); + // Proc macros run inside the compiler; neither they nor their own + // dependencies are linked into the binary. + if (item === undefined || isProcMacro(item)) continue; + shipped.add(id); + pending.push(...(edges.get(id) ?? [])); + } + + return [...shipped].map((id) => { + const item = record(packages.get(id), "shipped package"); + const name = text(item.name, "package name"); + const directory = dirname(text(item.manifest_path, "manifest path")); + return { + ecosystem: "Rust crate", + name, + version: text(item.version, "package version"), + license: optionalText(item.license) ?? "See license file", + source: optionalText(item.repository) ?? `https://crates.io/crates/${name}`, + licenseTexts: readLicenseTexts(directory, optionalText(item.license_file)), + } satisfies Component; + }); +} + +function npmComponents(): Component[] { + const pnpmArguments = ["--filter", DESKTOP_PACKAGE, "licenses", "list", "--prod", "--json"]; + // `pnpm` is a .cmd shim on Windows, which execFile cannot start directly. + const [command, commandArguments] = process.platform === "win32" + ? ["cmd.exe", ["/d", "/c", "pnpm.cmd", ...pnpmArguments]] + : ["pnpm", pnpmArguments]; + const output = execFileSync(command, commandArguments, { + cwd: ROOT, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + const byLicense = record(JSON.parse(output), "pnpm licenses"); + const components: Component[] = []; + for (const entries of Object.values(byLicense)) { + for (const entry of list(entries, "license group")) { + const item = record(entry, "npm package"); + const name = text(item.name, "npm name"); + if (TYPE_ONLY_PACKAGE.test(name)) continue; + const versions = list(item.versions, "npm versions").map((version) => text(version, "npm version")); + const paths = list(item.paths, "npm paths").map((path) => text(path, "npm path")); + versions.forEach((version, index) => { + const directory = paths[index] ?? paths[0]; + components.push({ + ecosystem: "npm package", + name, + version, + license: text(item.license, "npm license"), + source: optionalText(item.homepage) ?? `https://www.npmjs.com/package/${name}`, + licenseTexts: directory === undefined ? [] : readLicenseTexts(directory, null), + }); + }); + } + } + return components; +} + +function render(components: readonly Component[], appVersion: string): string { + const sorted = [...components].sort( + (left, right) => + left.ecosystem.localeCompare(right.ecosystem) + || left.name.localeCompare(right.name) + || left.version.localeCompare(right.version), + ); + const users = new Map(); + const missing: string[] = []; + for (const component of sorted) { + const label = `${component.name} ${component.version}`; + if (component.licenseTexts.length === 0) missing.push(`${label} (${component.license}, ${component.source})`); + for (const licenseText of component.licenseTexts) { + users.set(licenseText, [...(users.get(licenseText) ?? []), label]); + } + } + + const lines = [ + "CapKit third-party notices", + `CapKit ${appVersion}`, + "", + "CapKit includes the open-source software listed below. Each component is", + "used under its own license, reproduced in full in the License texts", + "section. CapKit's own license is in LICENSE.txt.", + "", + ]; + for (const ecosystem of ["Rust crate", "npm package"] as const) { + const group = sorted.filter((component) => component.ecosystem === ecosystem); + lines.push(`== ${ecosystem}s (${group.length}) ==`, ""); + for (const component of group) { + lines.push(`${component.name} ${component.version} | ${component.license} | ${component.source}`); + } + lines.push(""); + } + if (missing.length > 0) { + lines.push( + "== Components without a bundled license file ==", + "", + "These packages publish no license file. Their declared license applies;", + "source code and license terms are available at the listed address.", + "", + ...missing, + "", + ); + } + lines.push("== License texts ==", ""); + for (const [licenseText, labels] of users) { + lines.push("-".repeat(78), `Used by: ${labels.join(", ")}`, "-".repeat(78), "", licenseText, ""); + } + return `${lines.join("\r\n")}\r\n`; +} + +function parseOut(argv: readonly string[]): string { + const index = argv.indexOf("--out"); + if (index === -1) return join(ROOT, "apps", "desktop", "src-tauri", "target", "THIRD_PARTY_NOTICES.txt"); + const value = argv[index + 1]; + if (value === undefined || value.startsWith("--")) throw new Error("--out needs a file path"); + return resolve(value); +} + +const out = parseOut(process.argv.slice(2)); +const appVersion = text( + record(JSON.parse(readFileSync(join(ROOT, "apps", "desktop", "package.json"), "utf8")), "package.json").version, + "app version", +); +const components = [...rustComponents(), ...npmComponents()]; +writeFileSync(out, render(components, appVersion), "utf8"); +process.stdout.write(`Wrote ${components.length} components to ${out}\n`); From 9de7786009f7eef38a28efacd5f20b160bf15a79 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 21:47:24 +0530 Subject: [PATCH 03/16] feat(capture): eyedropper copies the snapshot colour under the pointer Press I in the capture overlay to copy #RRGGBB, Shift+I for rgb(). The colour is read from the frozen snapshot's physical pixel and copied as text through a new ClipboardBackend::copy_text. A capture-mode shortcut bound to I keeps priority while a selection is ready. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src-tauri/src/domain.rs | 23 ++++ apps/desktop/src-tauri/src/lib.rs | 17 ++- apps/desktop/src-tauri/src/platform/mod.rs | 1 + .../src-tauri/src/platform/xcap_backend.rs | 7 ++ .../desktop/src-tauri/src/services/capture.rs | 119 +++++++++++++++++- apps/desktop/src/App.test.tsx | 29 +++++ apps/desktop/src/App.tsx | 67 +++++++++- apps/desktop/src/domain/capture.ts | 9 ++ apps/desktop/src/lib/eyedropper.test.ts | 23 ++++ apps/desktop/src/lib/eyedropper.ts | 22 ++++ apps/desktop/src/lib/tauri.ts | 16 +++ 11 files changed, 322 insertions(+), 11 deletions(-) create mode 100644 apps/desktop/src/lib/eyedropper.test.ts create mode 100644 apps/desktop/src/lib/eyedropper.ts diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index 99d730f..24a9c2f 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -205,6 +205,29 @@ pub struct CompletionResult { pub cleanup_warning: Option, } +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ColorFormat { + Hex, + Rgb, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PickColorRequest { + pub session_id: String, + /// Display-local logical coordinates, the same space as the selection. + pub point: Point, + pub format: ColorFormat, +} + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PickedColorDto { + pub hex: String, + pub copied: String, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScrollingCaptureRequest { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 9a5fba9..daa1c80 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -14,9 +14,9 @@ use std::{ use domain::{ AudioDeviceDto, CaptureSessionDto, CompletionAction, CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, MediaFileDto, MediaFolderDto, - OnScreenSessionDto, Point, RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, - RecordingStatsDto, Rect, SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, - StartupStateDto, + OnScreenSessionDto, PickColorRequest, PickedColorDto, Point, RecordingArtifactsDto, + RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, Rect, SavedCaptureDto, + ScrollingCaptureRequest, ScrollingCaptureResult, StartupStateDto, }; use error::SnaphubError; use platform::StartupBackend; @@ -380,6 +380,16 @@ async fn retry_capture_save( Ok(result) } +#[tauri::command] +fn pick_capture_color( + window: WebviewWindow, + service: tauri::State<'_, CaptureService>, + request: PickColorRequest, +) -> Result { + ensure_capture_window(&window)?; + service.pick_color(&request) +} + // Hide first so Escape feels instant, then wait for cancellation off the main thread. #[tauri::command] async fn cancel_capture( @@ -2281,6 +2291,7 @@ pub fn run() { dismiss_on_screen, save_on_screen_capture, complete_capture, + pick_capture_color, retry_capture_save, cancel_capture, dismiss_capture, diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs index e829052..9858472 100644 --- a/apps/desktop/src-tauri/src/platform/mod.rs +++ b/apps/desktop/src-tauri/src/platform/mod.rs @@ -41,6 +41,7 @@ pub trait TargetDetectionBackend: Send + Sync { pub trait ClipboardBackend: Send + Sync { fn copy_image(&self, image: &RgbaImage) -> Result<(), SnaphubError>; + fn copy_text(&self, text: &str) -> Result<(), SnaphubError>; } pub trait PermissionBackend: Send + Sync { diff --git a/apps/desktop/src-tauri/src/platform/xcap_backend.rs b/apps/desktop/src-tauri/src/platform/xcap_backend.rs index 0237e70..d286c76 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -216,6 +216,13 @@ impl ClipboardBackend for XcapPlatformBackend { }) .map_err(SnaphubError::clipboard) } + + fn copy_text(&self, text: &str) -> Result<(), SnaphubError> { + let mut clipboard = Clipboard::new().map_err(SnaphubError::clipboard)?; + clipboard + .set_text(text.to_owned()) + .map_err(SnaphubError::clipboard) + } } impl PermissionBackend for XcapPlatformBackend { diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index ced078f..500c724 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -29,9 +29,10 @@ use uuid::Uuid; use crate::{ domain::{ - Annotation, AnnotationScene, CaptureSessionDto, CompletionAction, CompletionRequest, - CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, Point, Rect, - SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, + Annotation, AnnotationScene, CaptureSessionDto, ColorFormat, CompletionAction, + CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, + PickColorRequest, PickedColorDto, Point, Rect, SavedCaptureDto, ScrollingCaptureRequest, + ScrollingCaptureResult, }, error::SnaphubError, platform::{ @@ -635,6 +636,25 @@ impl CaptureService { self.clipboard.copy_image(&image) } + /// Copies the frozen snapshot's colour at a display-local logical point. + /// Reads the captured physical pixel, so the value matches the screen rather than the scaled preview. + pub fn pick_color(&self, request: &PickColorRequest) -> Result { + let id = parse_session_id(&request.session_id)?; + let pixel = { + let sessions = self + .sessions + .lock() + .map_err(|_| SnaphubError::Session("Capture state is unavailable".into()))?; + let asset = sessions + .get(&id) + .ok_or_else(|| SnaphubError::Session("Capture session has expired".into()))?; + pixel_at(&asset.image, request.point, asset.scale_factor)? + }; + let picked = format_color(pixel, request.format); + self.clipboard.copy_text(&picked.copied)?; + Ok(picked) + } + pub fn save_image_path(&self, path: &Path) -> Result { let image = image::open(path) .map_err(SnaphubError::export)? @@ -877,6 +897,31 @@ fn target_area(target: &DetectedTargetDto) -> f64 { target.bounds.width * target.bounds.height } +fn pixel_at(image: &RgbaImage, point: Point, scale: f64) -> Result, SnaphubError> { + if !point.x.is_finite() || !point.y.is_finite() || point.x < 0.0 || point.y < 0.0 { + return Err(SnaphubError::Session("Colour point is invalid".into())); + } + let x = (point.x * scale).floor(); + let y = (point.y * scale).floor(); + if x >= f64::from(image.width()) || y >= f64::from(image.height()) { + return Err(SnaphubError::Session( + "Colour point falls outside the captured display".into(), + )); + } + // Bounds-checked above, so the truncating casts stay inside the image. + Ok(*image.get_pixel(x as u32, y as u32)) +} + +fn format_color(pixel: Rgba, format: ColorFormat) -> PickedColorDto { + let [red, green, blue, _] = pixel.0; + let hex = format!("#{red:02X}{green:02X}{blue:02X}"); + let copied = match format { + ColorFormat::Hex => hex.clone(), + ColorFormat::Rgb => format!("rgb({red}, {green}, {blue})"), + }; + PickedColorDto { hex, copied } +} + fn parse_session_id(session_id: &str) -> Result { Uuid::parse_str(session_id).map_err(|_| SnaphubError::Session("Invalid capture session".into())) } @@ -1514,6 +1559,7 @@ mod tests { struct FakeBackend { source: RgbaImage, copied: Mutex>, + copied_text: Mutex>, clipboard_calls: AtomicUsize, fail_clipboard: AtomicBool, clipboard_entered: Mutex>>, @@ -1525,6 +1571,7 @@ mod tests { Self { source: RgbaImage::from_pixel(20, 20, Rgba([240, 241, 237, 255])), copied: Mutex::new(None), + copied_text: Mutex::new(None), clipboard_calls: AtomicUsize::new(0), fail_clipboard: AtomicBool::new(false), clipboard_entered: Mutex::new(None), @@ -1574,6 +1621,14 @@ mod tests { *self.copied.lock().unwrap() = Some(image.clone()); Ok(()) } + + fn copy_text(&self, text: &str) -> Result<(), SnaphubError> { + if self.fail_clipboard.load(Ordering::SeqCst) { + return Err(SnaphubError::Clipboard("Fake clipboard failure".into())); + } + *self.copied_text.lock().unwrap() = Some(text.to_owned()); + Ok(()) + } } impl TargetDetectionBackend for FakeBackend { @@ -1738,6 +1793,64 @@ mod tests { assert!(result.is_err()); } + #[test] + fn pick_color_reads_the_physical_pixel_and_copies_text() { + let directory = TestDirectory::new("pick-color"); + let mut fake = FakeBackend::new(); + fake.source.put_pixel(7, 9, Rgba([18, 171, 255, 255])); + let backend = Arc::new(fake); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + let picked = service + .pick_color(&PickColorRequest { + session_id: session_id.clone(), + point: Point { x: 3.6, y: 4.9 }, + format: ColorFormat::Rgb, + }) + .expect("colour should be picked"); + assert_eq!(picked.hex, "#12ABFF"); + assert_eq!(picked.copied, "rgb(18, 171, 255)"); + assert_eq!( + backend.copied_text.lock().unwrap().as_deref(), + Some("rgb(18, 171, 255)") + ); + let hex = service + .pick_color(&PickColorRequest { + session_id, + point: Point { x: 0.0, y: 0.0 }, + format: ColorFormat::Hex, + }) + .expect("colour should be picked"); + assert_eq!(hex.copied, "#F0F1ED"); + } + + #[test] + fn pick_color_rejects_points_outside_the_snapshot() { + let directory = TestDirectory::new("pick-color-bounds"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + for point in [ + Point { x: 10.0, y: 2.0 }, + Point { x: -0.5, y: 2.0 }, + Point { + x: f64::NAN, + y: 2.0, + }, + ] { + assert!( + service + .pick_color(&PickColorRequest { + session_id: session_id.clone(), + point, + format: ColorFormat::Hex, + }) + .is_err() + ); + } + assert!(backend.copied_text.lock().unwrap().is_none()); + } + #[test] fn copy_and_save_renders_once_and_saves_clipboard_pixels() { let directory = TestDirectory::new("copy-save"); diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 4754237..3060266 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -10,6 +10,7 @@ const captureMocks = vi.hoisted(() => ({ captureScrolling: vi.fn(), completeCapture: vi.fn(), listeners: [] as (() => void)[], + pickCaptureColor: vi.fn(), requestCapture: vi.fn(), retryCaptureSave: vi.fn(), showCaptureSurface: vi.fn(), @@ -23,6 +24,7 @@ vi.mock("./lib/tauri", async (importOriginal) => { cancelManualScrolling: captureMocks.cancelManualScrolling, captureScrolling: captureMocks.captureScrolling, completeCapture: captureMocks.completeCapture, + pickCaptureColor: captureMocks.pickCaptureColor, listenForCaptureRequest: vi.fn((callback: () => void) => { captureMocks.listeners.push(callback); return Promise.resolve((): void => { @@ -323,6 +325,33 @@ describe("App", () => { await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledTimes(1)); }); + it("copies the colour under the pointer with I and rgb with Shift+I", async () => { + captureMocks.pickCaptureColor.mockImplementation( + (_sessionId: string, _point: unknown, format: "hex" | "rgb") => + Promise.resolve({ hex: "#12ABFF", copied: format === "hex" ? "#12ABFF" : "rgb(18, 171, 255)" }), + ); + render(); + + expect(await screen.findAllByText(/Hover to preview targets/)).not.toHaveLength(0); + fireEvent.pointerMove(screen.getByRole("main"), { clientX: 40, clientY: 60, pointerId: 1 }); + fireEvent.keyDown(window, { key: "i" }); + expect(await screen.findAllByText(/Copied #12ABFF/)).not.toHaveLength(0); + fireEvent.keyDown(window, { key: "I", shiftKey: true }); + expect(await screen.findAllByText(/Copied rgb\(18, 171, 255\)/)).not.toHaveLength(0); + expect(captureMocks.pickCaptureColor).toHaveBeenNthCalledWith( + 1, + expect.any(String), + { x: 40, y: 60 }, + "hex", + ); + expect(captureMocks.pickCaptureColor).toHaveBeenLastCalledWith( + expect.any(String), + { x: 40, y: 60 }, + "rgb", + ); + expect(screen.getByRole("main")).toBeInTheDocument(); + }); + it("dismisses capture with Escape before a region is selected", async () => { render(); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index e9f6915..2a0d550 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -19,6 +19,7 @@ import { } from "./domain/annotations"; import type { CaptureSession, + ColorFormat, CompletionAction, DetectedTarget, Point, @@ -27,6 +28,7 @@ import type { import { useSnaphubSettings } from "./domain/settings"; import { chooseToolbarPlacement, clampRect, isUsableSelection, normalizeRect } from "./lib/geometry"; import { captureCursor } from "./lib/cursor"; +import { eyedropperFormat } from "./lib/eyedropper"; import { createVisualTargetDetector, type VisualTargetDetector } from "./lib/visualTargets"; import { cancelCapture, @@ -40,6 +42,7 @@ import { describeInvokeError, listTargets, listenForCaptureRequest, + pickCaptureColor, requestCapture, retryCaptureSave, showCaptureSurface, @@ -88,8 +91,11 @@ export function App(): React.JSX.Element { const [hoverTarget, setHoverTarget] = useState(null); const [targets, setTargets] = useState([]); const [isDraftingSelection, setIsDraftingSelection] = useState(false); - const [message, setMessage] = useState("Hover to preview targets / drag to draw a rectangle"); + const [message, setMessage] = useState("Hover to preview targets / drag to draw a rectangle / I copies a colour"); const [scrollingCapture, setScrollingCapture] = useState(null); + // The swatch shows only while its message is still the current one. + const [pickedSwatch, setPickedSwatch] = useState<{ hex: string; message: string } | null>(null); + const lastPointer = useRef(null); const uiLookupSequence = useRef(0); const uiLookupInFlight = useRef(false); const pendingUiLookup = useRef(null); @@ -196,7 +202,7 @@ export function App(): React.JSX.Element { }); dispatchScene({ type: "reset" }); }); - setMessage("Hover to preview targets / drag to draw a rectangle"); + setMessage("Hover to preview targets / drag to draw a rectangle / I copies a colour"); let readyTimeout: number | undefined; await Promise.race([ backdropReady, @@ -700,6 +706,30 @@ export function App(): React.JSX.Element { } }, [completionState.phase, session]); + useEffect(() => { + // Window-level so the eyedropper knows the pointer even over the annotation canvas or toolbars. + function trackPointer(event: PointerEvent): void { + lastPointer.current = { x: event.clientX, y: event.clientY }; + } + window.addEventListener("pointermove", trackPointer, { capture: true, passive: true }); + return (): void => { + window.removeEventListener("pointermove", trackPointer, { capture: true }); + }; + }, []); + + const pickColor = useCallback(async (format: ColorFormat): Promise => { + const point = lastPointer.current; + if (session === null || point === null) return; + try { + const picked = await pickCaptureColor(session.id, point, format); + const pickedMessage = `Copied ${picked.copied}`; + setPickedSwatch({ hex: picked.hex, message: pickedMessage }); + setMessage(pickedMessage); + } catch (error) { + setMessage(`Could not copy colour · ${describeInvokeError(error, "The colour could not be read")}`); + } + }, [session]); + useEffect(() => { function handleKeyDown(event: KeyboardEvent): void { // Escape is the capture surface's unconditional exit hatch. Handle it in @@ -729,7 +759,18 @@ export function App(): React.JSX.Element { && !busy && completionState.phase === "idle"; const key = event.key.toUpperCase(); - if ( + const { captureModeCopy, captureModeSave, captureModeCopyAndSave } = settingsRef.current.shortcuts; + const colorFormat = busy || scrollingCapture !== null || event.repeat + ? null + : eyedropperFormat( + event, + [captureModeCopy, captureModeSave, captureModeCopyAndSave], + selectedCompletionReady, + ); + if (colorFormat !== null) { + event.preventDefault(); + void pickColor(colorFormat); + } else if ( selectedCompletionReady && hasNoModifiers && key === settingsRef.current.shortcuts.captureModeCopy @@ -775,6 +816,7 @@ export function App(): React.JSX.Element { handleCancel, handleComplete, isDraftingSelection, + pickColor, scrollingCapture, selection, ]); @@ -784,6 +826,7 @@ export function App(): React.JSX.Element { } const viewport = viewportBounds(session.display); + const swatchHex = pickedSwatch !== null && pickedSwatch.message === message ? pickedSwatch.hex : null; const toolBarX = selection === null ? 16 : Math.max(16, Math.min(selection.x, viewport.width - 430)); const toolBarY = selection === null || toolbarPlacement === null @@ -838,7 +881,8 @@ export function App(): React.JSX.Element { {selection === null ?
: null} {selection === null ? ( -
+
+ {swatchHex === null ? null : } {message}
) : isDraftingSelection ? ( @@ -939,13 +983,26 @@ export function App(): React.JSX.Element { /> )} -
+
+ {swatchHex === null ? null : } Capkit / {message}
); } +function ColorSwatch({ hex }: { hex: string }): React.JSX.Element { + return ( +
) : null} diff --git a/apps/desktop/src/components/CompletionToolbar.test.tsx b/apps/desktop/src/components/CompletionToolbar.test.tsx index aa10b2b..86e6286 100644 --- a/apps/desktop/src/components/CompletionToolbar.test.tsx +++ b/apps/desktop/src/components/CompletionToolbar.test.tsx @@ -10,7 +10,7 @@ const actions: readonly { action: CompletionAction; label: string }[] = [ { action: "pin", label: "Pin" }, ]; -function renderToolbar(onComplete: (action: CompletionAction) => void): void { +function renderToolbar(onComplete: (action: CompletionAction) => void, onCopyText?: () => void): void { render( void): void { statusSide="right" onComplete={onComplete} onRetrySave={() => undefined} + {...(onCopyText === undefined ? {} : { onCopyText })} />, ); } @@ -65,4 +66,14 @@ describe("CompletionToolbar", () => { expect(onComplete).toHaveBeenNthCalledWith(1, action); expect(onComplete).toHaveBeenNthCalledWith(2, action); }); + + it("shows Copy text only when the OS can read text", () => { + renderToolbar(() => undefined); + expect(screen.queryByRole("button", { name: "Copy text" })).toBeNull(); + cleanup(); + const onCopyText = vi.fn(); + renderToolbar(() => undefined, onCopyText); + fireEvent.click(screen.getByRole("button", { name: "Copy text" })); + expect(onCopyText).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/desktop/src/components/CompletionToolbar.tsx b/apps/desktop/src/components/CompletionToolbar.tsx index 6fba1c3..6f8be8c 100644 --- a/apps/desktop/src/components/CompletionToolbar.tsx +++ b/apps/desktop/src/components/CompletionToolbar.tsx @@ -1,6 +1,14 @@ import { useEffect, useRef } from "react"; import type { CompletionAction } from "../domain/capture"; -import { Clipboard, Copy, Download, Pin, Refresh, type CapkitIconProps } from "./icons"; +import { + Clipboard, + Copy, + Download, + Pin, + Refresh, + TextSelection, + type CapkitIconProps, +} from "./icons"; import { ToolButton } from "./ToolButton"; export type CompletionToolbarState = "idle" | "working" | "save-pending"; @@ -15,6 +23,8 @@ type CompletionToolbarProps = { statusSide: "left" | "right"; onComplete: (action: CompletionAction) => void; onRetrySave: () => void; + /** Present only when the OS can read text; the button is hidden otherwise. */ + onCopyText?: () => void; }; export function CompletionToolbar({ @@ -27,6 +37,7 @@ export function CompletionToolbar({ statusSide, onComplete, onRetrySave, + onCopyText, }: CompletionToolbarProps): React.JSX.Element { const retryButtonRef = useRef(null); const disabled = state !== "idle"; @@ -74,6 +85,14 @@ export function CompletionToolbar({ label="Pin" onClick={() => onComplete("pin")} /> + {onCopyText === undefined ? null : ( + + )}
{state === "idle" && statusMessage === "" ? null : ( diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx index ffa2e0d..f6c5218 100644 --- a/apps/desktop/src/components/icons.tsx +++ b/apps/desktop/src/components/icons.tsx @@ -61,6 +61,7 @@ import { ScanIcon, ScrollVerticalIcon, SearchAreaIcon, + SecurityCheckIcon, Settings02Icon, SlidersHorizontalIcon, SmartPhone01Icon, @@ -69,9 +70,11 @@ import { SpotlightIcon, SquareIcon, SquareRoundCornerIcon, + StarIcon, Sun03Icon, Tablet01Icon, TextIcon, + TextSelectionIcon, Tick02Icon, Undo03Icon, Upload04Icon, @@ -171,6 +174,7 @@ export const Rows = createCapkitIcon(LayoutThreeRowIcon); export const Save = createCapkitIcon(SaveIcon); export const Scan = createCapkitIcon(ScanIcon); export const SearchArea = createCapkitIcon(SearchAreaIcon); +export const SecurityCheck = createCapkitIcon(SecurityCheckIcon); export const SelectPointer = createCapkitIcon(Cursor01Icon); export const Settings = createCapkitIcon(Settings02Icon); export const Sliders = createCapkitIcon(SlidersHorizontalIcon); @@ -179,9 +183,11 @@ export const Sparkles = createCapkitIcon(SparklesIcon); export const Spotlight = createCapkitIcon(SpotlightIcon); export const SquareShape = createCapkitIcon(SquareIcon); export const RoundedSquareShape = createCapkitIcon(SquareRoundCornerIcon); +export const Star = createCapkitIcon(StarIcon); export const Sun = createCapkitIcon(Sun03Icon); export const Tablet = createCapkitIcon(Tablet01Icon); export const Text = createCapkitIcon(TextIcon); +export const TextSelection = createCapkitIcon(TextSelectionIcon); export const Tick = createCapkitIcon(Tick02Icon); export const Undo = createCapkitIcon(Undo03Icon); export const Upload = createCapkitIcon(Upload04Icon); diff --git a/apps/desktop/src/domain/capture.ts b/apps/desktop/src/domain/capture.ts index 20f46e0..204943d 100644 --- a/apps/desktop/src/domain/capture.ts +++ b/apps/desktop/src/domain/capture.ts @@ -73,6 +73,33 @@ export const pickedColorSchema = z.object({ }); export type PickedColor = z.infer; +/** Word bounds are selection-local logical pixels, ready to become annotations. */ +export const recognizedWordSchema = z.object({ + text: z.string(), + bounds: rectSchema, +}); +export type RecognizedWord = z.infer; + +export const recognizedLineSchema = z.object({ + text: z.string(), + words: z.array(recognizedWordSchema), +}); +export type RecognizedLine = z.infer; + +export const recognizedTextSchema = z.object({ + text: z.string(), + lines: z.array(recognizedLineSchema), + language: z.string(), +}); +export type RecognizedText = z.infer; + +export const textCopyResultSchema = z.object({ + status: z.enum(["copied", "empty"]), + text: z.string(), + cleanupWarning: z.string().nullable().optional(), +}); +export type TextCopyResult = z.infer; + export const scrollingCaptureResultSchema = z.object({ outputPath: z.string(), frameCount: z.number().int().positive(), diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts index 2ca34d1..53de481 100644 --- a/apps/desktop/src/lib/tauri.ts +++ b/apps/desktop/src/lib/tauri.ts @@ -18,9 +18,11 @@ import { displaySchema, pickedColorSchema, pointSchema, + recognizedTextSchema, rectSchema, scrollingCaptureResultSchema, savedCaptureSchema, + textCopyResultSchema, type CaptureSession, type ColorFormat, type CompletionAction, @@ -28,9 +30,11 @@ import { type DetectedTarget, type Display, type Point, + type RecognizedText, type Rect, type ScrollingCaptureResult, type SavedCapture, + type TextCopyResult, } from "../domain/capture"; const backendSessionSchema = captureSessionSchema.omit({ snapshotUrl: true }).extend({ @@ -187,6 +191,36 @@ export async function pickCaptureColor( return pickedColorSchema.parse(raw); } +export async function isTextRecognitionSupported(): Promise { + if (!isTauri()) return false; + const raw: unknown = await invoke("text_recognition_supported"); + return z.boolean().parse(raw); +} + +/** Reads text in the raw selection (annotations excluded). The capture stays open. */ +export async function recognizeCaptureText( + sessionId: string, + selection: Rect, +): Promise { + if (!isTauri()) throw new Error("Text recognition requires the desktop app"); + const raw: unknown = await invoke("recognize_capture_text", { + request: { sessionId, selection }, + }); + return recognizedTextSchema.parse(raw); +} + +/** Copies the selection's text and closes the capture; `empty` leaves it open. */ +export async function copyCaptureText( + sessionId: string, + selection: Rect, +): Promise { + if (!isTauri()) throw new Error("Text recognition requires the desktop app"); + const raw: unknown = await invoke("copy_capture_text", { + request: { sessionId, selection }, + }); + return textCopyResultSchema.parse(raw); +} + export async function retryCaptureSave(sessionId: string): Promise { if (!isTauri()) return createDemoCompletionResult("copy-and-save"); const raw: unknown = await invoke("retry_capture_save", { sessionId }); From 51aa492a30e3a8acf9af9d95e313faa18de95319 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 22:05:18 +0530 Subject: [PATCH 06/16] feat(capture): suggest redactions for sensitive text in a selection Find sensitive text reads the selection with the OS OCR engine and flags emails, phone numbers, Luhn-valid card numbers, provider API keys, JWTs and high-entropy strings. Matches map back to the OCR word boxes they cover and are previewed over the selection; nothing changes until the user confirms. Confirmed items become blackout annotations in a single undo step. Blackout is used instead of pixelate because pixelated text can be partly reconstructed. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/App.test.tsx | 59 ++++++ apps/desktop/src/App.tsx | 101 +++++++++- .../src/components/CompletionToolbar.tsx | 12 ++ .../src/components/RedactionReviewPanel.tsx | 178 +++++++++++++++++ .../desktop/src/lib/redactionPatterns.test.ts | 109 +++++++++++ apps/desktop/src/lib/redactionPatterns.ts | 183 ++++++++++++++++++ 6 files changed, 641 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/components/RedactionReviewPanel.tsx create mode 100644 apps/desktop/src/lib/redactionPatterns.test.ts create mode 100644 apps/desktop/src/lib/redactionPatterns.ts diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 46a9f96..2cb69b2 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -10,6 +10,7 @@ const captureMocks = vi.hoisted(() => ({ captureScrolling: vi.fn(), completeCapture: vi.fn(), copyCaptureText: vi.fn(), + recognizeCaptureText: vi.fn(), isTextRecognitionSupported: vi.fn(), listeners: [] as (() => void)[], pickCaptureColor: vi.fn(), @@ -27,6 +28,7 @@ vi.mock("./lib/tauri", async (importOriginal) => { captureScrolling: captureMocks.captureScrolling, completeCapture: captureMocks.completeCapture, copyCaptureText: captureMocks.copyCaptureText, + recognizeCaptureText: captureMocks.recognizeCaptureText, isTextRecognitionSupported: captureMocks.isTextRecognitionSupported, pickCaptureColor: captureMocks.pickCaptureColor, listenForCaptureRequest: vi.fn((callback: () => void) => { @@ -380,6 +382,63 @@ describe("App", () => { expect(captureMocks.completeCapture).not.toHaveBeenCalled(); }); + it("blacks out only the confirmed sensitive text in one step", async () => { + captureMocks.isTextRecognitionSupported.mockResolvedValue(true); + captureMocks.recognizeCaptureText.mockResolvedValue({ + text: "Mail nakul@example.com or call +91 98765 43210", + language: "en-US", + lines: [{ + text: "Mail nakul@example.com or call +91 98765 43210", + words: [ + { text: "Mail", bounds: { x: 4, y: 10, width: 30, height: 14 } }, + { text: "nakul@example.com", bounds: { x: 40, y: 10, width: 120, height: 14 } }, + { text: "or", bounds: { x: 166, y: 10, width: 14, height: 14 } }, + { text: "call", bounds: { x: 186, y: 10, width: 26, height: 14 } }, + { text: "+91", bounds: { x: 218, y: 10, width: 24, height: 14 } }, + { text: "98765", bounds: { x: 248, y: 10, width: 40, height: 14 } }, + { text: "43210", bounds: { x: 294, y: 10, width: 40, height: 14 } }, + ], + }], + }); + render(); + await selectRegion(); + + fireEvent.click(await screen.findByRole("button", { name: "Find sensitive text" })); + const phone = await screen.findByRole("checkbox", { name: /Phone number/ }); + expect(screen.getByRole("checkbox", { name: /Email address/ })).toBeChecked(); + fireEvent.click(phone); + expect(phone).not.toBeChecked(); + fireEvent.click(screen.getByRole("button", { name: "Black out 1" })); + expect(await screen.findAllByText(/Blacked out 1 item/)).not.toHaveLength(0); + expect(screen.queryByRole("region", { name: "Sensitive text" })).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + await waitFor(() => expect(captureMocks.completeCapture).toHaveBeenCalledTimes(1)); + expect(captureMocks.completeCapture).toHaveBeenCalledWith( + "copy", + expect.any(String), + expect.anything(), + { + version: 1, + elements: [expect.objectContaining({ + kind: "blackout", + bounds: { x: 37, y: 7, width: 126, height: 20 }, + })], + }, + ); + }); + + it("says so when nothing sensitive is found", async () => { + captureMocks.isTextRecognitionSupported.mockResolvedValue(true); + captureMocks.recognizeCaptureText.mockResolvedValue({ text: "", language: "en-US", lines: [] }); + render(); + await selectRegion(); + fireEvent.click(await screen.findByRole("button", { name: "Find sensitive text" })); + expect(await screen.findByText(/No emails, phone numbers/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Close" })); + expect(screen.queryByText(/No emails, phone numbers/)).toBeNull(); + }); + it("hides Copy text when the OS cannot read text", async () => { render(); await selectRegion(); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 9d8c01f..241dc8a 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -4,6 +4,11 @@ import { AnnotationCanvas } from "./components/AnnotationCanvas"; import { AnnotationToolbar } from "./components/AnnotationToolbar"; import { CaptureBackdrop } from "./components/CaptureBackdrop"; import { CompletionToolbar } from "./components/CompletionToolbar"; +import { + RedactionPreview, + RedactionReviewPanel, + type RedactionReview, +} from "./components/RedactionReviewPanel"; import { SelectionFrame, type ResizeHandle } from "./components/SelectionFrame"; import { ScrollingCapturePanel, @@ -29,6 +34,7 @@ import { useSnaphubSettings } from "./domain/settings"; import { chooseToolbarPlacement, clampRect, isUsableSelection, normalizeRect } from "./lib/geometry"; import { captureCursor } from "./lib/cursor"; import { eyedropperFormat } from "./lib/eyedropper"; +import { suggestRedactions } from "./lib/redactionPatterns"; import { createVisualTargetDetector, type VisualTargetDetector } from "./lib/visualTargets"; import { cancelCapture, @@ -45,6 +51,7 @@ import { listTargets, listenForCaptureRequest, pickCaptureColor, + recognizeCaptureText, requestCapture, retryCaptureSave, showCaptureSurface, @@ -98,6 +105,8 @@ export function App(): React.JSX.Element { // The swatch shows only while its message is still the current one. const [pickedSwatch, setPickedSwatch] = useState<{ hex: string; message: string } | null>(null); const [canReadText, setCanReadText] = useState(false); + const [redactionReview, setRedactionReview] = useState(null); + const redactionSequence = useRef(0); const lastPointer = useRef(null); const uiLookupSequence = useRef(0); const uiLookupInFlight = useRef(false); @@ -709,6 +718,81 @@ export function App(): React.JSX.Element { } }, [busy, completionState.phase, scrollingCapture, selection, session]); + const findSensitiveText = useCallback(async (): Promise => { + if ( + session === null + || selection === null + || busy + || scrollingCapture !== null + || completionState.phase !== "idle" + || completionInFlight.current + ) return; + const sequence = redactionSequence.current + 1; + redactionSequence.current = sequence; + const reviewedSelection = selection; + setCompletionState({ phase: "idle", message: "" }); + setRedactionReview({ phase: "reading" }); + try { + const recognized = await recognizeCaptureText(session.id, reviewedSelection); + if (redactionSequence.current !== sequence) return; + const suggestions = suggestRedactions(recognized, reviewedSelection); + setRedactionReview({ + phase: "ready", + suggestions, + selectedIds: new Set(suggestions.map((suggestion) => suggestion.id)), + }); + } catch (error: unknown) { + if (redactionSequence.current !== sequence) return; + setRedactionReview({ + phase: "error", + message: `Could not read text. ${describeInvokeError(error, "The text recognition service did not return a diagnostic")}`, + }); + } + }, [busy, completionState.phase, scrollingCapture, selection, session]); + + const closeRedactionReview = useCallback((): void => { + redactionSequence.current += 1; + setRedactionReview(null); + }, []); + + const toggleRedactionSuggestion = useCallback((suggestionId: string): void => { + setRedactionReview((current) => { + if (current?.phase !== "ready") return current; + const selectedIds = new Set(current.selectedIds); + if (selectedIds.has(suggestionId)) selectedIds.delete(suggestionId); + else selectedIds.add(suggestionId); + return { ...current, selectedIds }; + }); + }, []); + + const applyRedactions = useCallback((): void => { + if (redactionReview?.phase !== "ready") return; + // Blackout, not pixelate: large-block pixelation of text can be partly reversed. + const blackouts: Annotation[] = redactionReview.suggestions + .filter((suggestion) => redactionReview.selectedIds.has(suggestion.id)) + .map((suggestion) => ({ + id: crypto.randomUUID(), + kind: "blackout", + bounds: suggestion.bounds, + color: "#090a08", + intensity: 1, + opacity: 1, + })); + if (blackouts.length === 0) return; + // One replace, so a single undo removes the whole batch. + dispatchScene({ + type: "replace", + scene: { version: 1, elements: [...history.present.elements, ...blackouts] }, + }); + closeRedactionReview(); + setMessage(`Blacked out ${blackouts.length === 1 ? "1 item" : `${String(blackouts.length)} items`} · Ctrl+Z to undo`); + }, [closeRedactionReview, history.present.elements, redactionReview]); + + useEffect(() => { + // Suggestions are positioned for one selection; any change makes them stale. + closeRedactionReview(); + }, [closeRedactionReview, selection, session?.id]); + const handleRetrySave = useCallback(async (): Promise => { if ( session === null @@ -985,6 +1069,7 @@ export function App(): React.JSX.Element { onDelete={(annotationId) => dispatchScene({ type: "delete", annotationId })} onUpdate={(annotation) => dispatchScene({ type: "update", annotation })} /> + {redactionReview === null ? null : } {completionState.phase === "idle" ? null : ( ) : null} diff --git a/apps/desktop/src/components/CompletionToolbar.tsx b/apps/desktop/src/components/CompletionToolbar.tsx index 6f8be8c..edae56e 100644 --- a/apps/desktop/src/components/CompletionToolbar.tsx +++ b/apps/desktop/src/components/CompletionToolbar.tsx @@ -6,6 +6,7 @@ import { Download, Pin, Refresh, + SecurityCheck, TextSelection, type CapkitIconProps, } from "./icons"; @@ -25,6 +26,8 @@ type CompletionToolbarProps = { onRetrySave: () => void; /** Present only when the OS can read text; the button is hidden otherwise. */ onCopyText?: () => void; + /** Present only when the OS can read text; opens redaction suggestions. */ + onFindSensitive?: () => void; }; export function CompletionToolbar({ @@ -38,6 +41,7 @@ export function CompletionToolbar({ onComplete, onRetrySave, onCopyText, + onFindSensitive, }: CompletionToolbarProps): React.JSX.Element { const retryButtonRef = useRef(null); const disabled = state !== "idle"; @@ -93,6 +97,14 @@ export function CompletionToolbar({ onClick={onCopyText} /> )} + {onFindSensitive === undefined ? null : ( + + )}
{state === "idle" && statusMessage === "" ? null : ( diff --git a/apps/desktop/src/components/RedactionReviewPanel.tsx b/apps/desktop/src/components/RedactionReviewPanel.tsx new file mode 100644 index 0000000..1383462 --- /dev/null +++ b/apps/desktop/src/components/RedactionReviewPanel.tsx @@ -0,0 +1,178 @@ +import { useEffect, useRef } from "react"; +import { + SENSITIVE_KIND_LABELS, + type RedactionSuggestion, +} from "../lib/redactionPatterns"; +import { Refresh } from "./icons"; + +export type RedactionReview = + | { phase: "reading" } + | { + phase: "ready"; + suggestions: readonly RedactionSuggestion[]; + selectedIds: ReadonlySet; + } + | { phase: "error"; message: string }; + +type RedactionReviewPanelProps = { + review: RedactionReview; + side: "left" | "right"; + onToggle: (suggestionId: string) => void; + onApply: () => void; + onClose: () => void; +}; + +const BUTTON_BASE = + "rounded-lg px-3 py-2 text-xs font-semibold outline-none transition focus-visible:ring-2 focus-visible:ring-white active:scale-96 motion-reduce:transition-none motion-reduce:active:scale-100"; + +/** Lists detected sensitive text; nothing is redacted until the user applies it. */ +export function RedactionReviewPanel({ + review, + side, + onToggle, + onApply, + onClose, +}: RedactionReviewPanelProps): React.JSX.Element { + const firstControlRef = useRef(null); + const position = side === "left" ? "right-full top-0 mr-2" : "left-full top-0 ml-2"; + + useEffect(() => { + if (review.phase !== "reading") firstControlRef.current?.focus(); + }, [review.phase]); + + const selectedCount = review.phase === "ready" ? review.selectedIds.size : 0; + + return ( +
+

+ Sensitive text +

+ + {review.phase === "reading" ? ( +

+

+ ) : null} + + {review.phase === "error" ? ( + <> +

+ {review.message} +

+ + + ) : null} + + {review.phase === "ready" && review.suggestions.length === 0 ? ( + <> +

+ No emails, phone numbers, card numbers or keys were found. +

+ + + ) : null} + + {review.phase === "ready" && review.suggestions.length > 0 ? ( + <> +

+ Check what to black out. Review the result before sharing. +

+
+ Suggestions to black out + {review.suggestions.map((suggestion, index) => ( + + ))} +
+
+ + +
+ + ) : null} +
+ ); +} + +/** Dashed previews of the checked suggestions, drawn over the selection. */ +export function RedactionPreview({ review }: { review: RedactionReview }): React.JSX.Element | null { + if (review.phase !== "ready") return null; + return ( + ) : null}
diff --git a/apps/desktop/src/components/dashboard/RecordView.test.tsx b/apps/desktop/src/components/dashboard/RecordView.test.tsx index a641a0d..5343d94 100644 --- a/apps/desktop/src/components/dashboard/RecordView.test.tsx +++ b/apps/desktop/src/components/dashboard/RecordView.test.tsx @@ -26,6 +26,8 @@ const track: CursorTrack = { ys: [10, 300], events: [{ time: 1, kind: "down", button: "left", x: 400, y: 300 }], shapes: [{ time: 0, shape: "default" }], + keysRecorded: false, + keys: [], displayBounds: { x: 0, y: 0, width: 1920, height: 1080 }, scaleFactor: 1, }; diff --git a/apps/desktop/src/components/dashboard/RecordingPreview.test.tsx b/apps/desktop/src/components/dashboard/RecordingPreview.test.tsx index 574c206..f0ade04 100644 --- a/apps/desktop/src/components/dashboard/RecordingPreview.test.tsx +++ b/apps/desktop/src/components/dashboard/RecordingPreview.test.tsx @@ -26,6 +26,8 @@ const track: CursorTrack = { ys: [10, 300], events: [], shapes: [{ time: 0, shape: "default" }], + keysRecorded: false, + keys: [], displayBounds: { x: 0, y: 0, width: 1920, height: 1080 }, scaleFactor: 1, }; diff --git a/apps/desktop/src/components/dashboard/StudioView.test.tsx b/apps/desktop/src/components/dashboard/StudioView.test.tsx index 88ed0bb..13c99a1 100644 --- a/apps/desktop/src/components/dashboard/StudioView.test.tsx +++ b/apps/desktop/src/components/dashboard/StudioView.test.tsx @@ -29,6 +29,8 @@ const track: CursorTrack = { { time: 1.1, kind: "up", button: "left", x: 400, y: 300 }, ], shapes: [{ time: 0, shape: "default" }], + keysRecorded: false, + keys: [], displayBounds: { x: 0, y: 0, width: 1920, height: 1080 }, scaleFactor: 1, }; diff --git a/apps/desktop/src/components/dashboard/StudioView.tsx b/apps/desktop/src/components/dashboard/StudioView.tsx index 2bcfb9f..5b99ee6 100644 --- a/apps/desktop/src/components/dashboard/StudioView.tsx +++ b/apps/desktop/src/components/dashboard/StudioView.tsx @@ -31,7 +31,8 @@ import { import { loadCursorTrack, recordingSrc } from "../../lib/recordingTauri"; import { describeInvokeError } from "../../lib/tauri"; import { clickPulseAt, paintFrame } from "../../lib/videoCompositor"; -import { canEncodeVideo, downloadExport, exportVideo, keyframesFor, smoothedCursor } from "../../lib/videoExport"; +import { keystrokeChipsAt, type KeystrokeSettings } from "../../domain/keystrokes"; +import { canEncodeVideo, downloadExport, exportVideo, keyframesFor, keystrokeEntriesFor, smoothedCursor } from "../../lib/videoExport"; import { SelectPointer, Download, Film, Palette, Pause, Play, Speaker } from "../icons"; import { AudioPanel, MotionPanel, StagePanel } from "./studio/StudioPanels"; import { Timeline } from "./studio/Timeline"; @@ -141,6 +142,7 @@ export function StudioView({ initialRecording = null }: { initialRecording?: Rec const keyframes = useMemo(() => keyframesFor(scene, track, mediaSize), [scene, track, mediaSize]); const cursorPath = useMemo(() => smoothedCursor(track, scene, previewFps), [track, scene]); + const keystrokes = useMemo(() => keystrokeEntriesFor(scene, track), [scene, track]); const clickTimes = useMemo( () => (track?.events ?? []).filter((event) => event.kind === "down").map((event) => event.time), [track], @@ -170,13 +172,14 @@ export function StudioView({ initialRecording = null }: { initialRecording?: Rec camera: hasCameraTrack ? cameraRef.current : null, cursor: cursorPath.length === 0 ? null : cursorAt(cursorPath, at), clickPulse: clickPulseAt(track?.events ?? [], at), + keystrokes: keystrokeChipsAt(keystrokes, at), }, stageBox, keyframes, at, ); }, - [scene, mediaSize, stageBox, keyframes, cursorPath, track, hasCameraTrack], + [scene, mediaSize, stageBox, keyframes, cursorPath, keystrokes, track, hasCameraTrack], ); useEffect(() => { @@ -520,9 +523,11 @@ export function StudioView({ initialRecording = null }: { initialRecording?: Rec clickCount={clickTimes.length} hasCameraTrack={hasCameraTrack} hasCursorTrack={track !== null} + keysRecorded={track?.keysRecorded ?? false} scene={scene} onPatchCamera={(next: Partial) => patch({ camera: { ...scene.camera, ...next } })} onPatchCursor={(next: Partial) => patch({ cursor: { ...scene.cursor, ...next } })} + onPatchKeystrokes={(next: Partial) => patch({ keystrokes: { ...scene.keystrokes, ...next } })} onPatchZoom={(next: Partial) => patch({ zoom: { ...scene.zoom, ...next } })} /> ) : null} diff --git a/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx b/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx index 5862170..9c4fb3c 100644 --- a/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx +++ b/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx @@ -15,11 +15,17 @@ import { type VideoScene, type ZoomSettings, } from "../../../domain/videoScene"; -import { SelectPointer, Frame, Image, Layers, MagicWand, Mic, Palette, Speaker, Sparkles, Video } from "../../icons"; +import { keystrokeModes, keystrokePositions, type KeystrokeMode, type KeystrokeSettings } from "../../../domain/keystrokes"; +import { SelectPointer, Frame, Image, Keyboard, Layers, MagicWand, Mic, Palette, Speaker, Sparkles, Video } from "../../icons"; import { Chip, CollapsibleSection, ColorField, ControlLabel, Slider, Toggle } from "../showcase/primitives"; export type ScenePatch = (patch: Partial) => void; +const keystrokeModeLabels: Record = { + shortcuts: { label: "Shortcuts", description: "Show only Ctrl, Alt, and Win shortcuts" }, + all: { label: "All keys", description: "Show shortcuts and named keys such as Enter and Tab" }, +}; + /** Background, padding, and effects — the Showcase treatment applied to video. */ export function StagePanel({ scene, onPatch, onApplyLook }: { scene: VideoScene; onPatch: ScenePatch; onApplyLook: (look: Look) => void }): React.JSX.Element { const activePreset: BackgroundPresetId | null = scene.scene.background.kind === "preset" ? scene.scene.background.id : null; @@ -160,14 +166,18 @@ export function MotionPanel({ onPatchCursor, onPatchZoom, onPatchCamera, + keysRecorded, + onPatchKeystrokes, }: { scene: VideoScene; hasCursorTrack: boolean; + keysRecorded: boolean; hasCameraTrack: boolean; clickCount: number; onPatchCursor: (patch: Partial) => void; onPatchZoom: (patch: Partial) => void; onPatchCamera: (patch: Partial) => void; + onPatchKeystrokes: (patch: Partial) => void; }): React.JSX.Element { return (
@@ -216,6 +226,34 @@ export function MotionPanel({ onChange={(value) => onPatchZoom({ holdSeconds: value / 100 })} /> + + + {keysRecorded ? null : ( +

+ Keys were not recorded for this clip. Turn on Keystrokes in the recorder to show shortcuts next time. +

+ )} + onPatchKeystrokes({ show: value })} /> +
+ +
+ {keystrokeModes.map((mode) => ( + onPatchKeystrokes({ mode })}> + {keystrokeModeLabels[mode].label} + + ))} +
+
+ {keystrokePositions.map((position) => ( + onPatchKeystrokes({ position })}> + {position} + + ))} +
+ onPatchKeystrokes({ size: value })} /> + onPatchKeystrokes({ clickLabels: value })} /> +
+
diff --git a/apps/desktop/src/domain/cursorTrack.ts b/apps/desktop/src/domain/cursorTrack.ts index 1d4146c..66a46fa 100644 --- a/apps/desktop/src/domain/cursorTrack.ts +++ b/apps/desktop/src/domain/cursorTrack.ts @@ -22,6 +22,23 @@ export const cursorShapeSpanSchema = z.object({ export type CursorShapeSpan = z.infer; +/** + * One key press. Typed characters arrive as `kind: "text"` with an empty key + * and no modifiers: the recorder never stores what was typed, only that + * typing happened. + */ +export const keyEventSchema = z.object({ + time: z.number(), + kind: z.enum(["key", "text"]), + key: z.string(), + ctrl: z.boolean(), + shift: z.boolean(), + alt: z.boolean(), + meta: z.boolean(), +}); + +export type KeyEvent = z.infer; + /** * Positions arrive as parallel arrays rather than an array of points. * @@ -35,6 +52,10 @@ export const cursorTrackSchema = z.object({ ys: z.array(z.number()), events: z.array(cursorEventSchema), shapes: z.array(cursorShapeSpanSchema), + /** False when keystrokes were off for the recording, including every + * recording made before the option existed. */ + keysRecorded: z.boolean().default(false), + keys: z.array(keyEventSchema).default([]), /** The recorded area: the whole display, or the crop origin for Window and Region. */ displayBounds: rectSchema, scaleFactor: z.number(), diff --git a/apps/desktop/src/domain/keystrokes.test.ts b/apps/desktop/src/domain/keystrokes.test.ts new file mode 100644 index 0000000..250af9b --- /dev/null +++ b/apps/desktop/src/domain/keystrokes.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vitest"; +import { decodeCursorTrack, type CursorEvent, type KeyEvent } from "./cursorTrack"; +import { + defaultKeystrokeSettings, + keystrokeChipsAt, + keystrokeEntries, + keystrokeHoldSeconds, + keystrokeLabel, +} from "./keystrokes"; + +function key(time: number, name: string, modifiers: Partial> = {}): KeyEvent { + return { time, kind: "key", key: name, ctrl: false, shift: false, alt: false, meta: false, ...modifiers }; +} + +function typed(time: number): KeyEvent { + return { time, kind: "text", key: "", ctrl: false, shift: false, alt: false, meta: false }; +} + +const click: CursorEvent = { time: 2, kind: "down", button: "right", x: 10, y: 10 }; + +describe("keystrokeLabel", () => { + it("orders modifiers the way Windows writes shortcuts", () => { + expect(keystrokeLabel(key(0, "S", { shift: true, meta: true }))).toBe("Win + Shift + S"); + expect(keystrokeLabel(key(0, "Esc", { ctrl: true, shift: true }))).toBe("Ctrl + Shift + Esc"); + expect(keystrokeLabel(key(0, "Enter"))).toBe("Enter"); + }); +}); + +describe("keystrokeEntries", () => { + const keys = [key(1, "C", { ctrl: true }), key(1.5, "Enter"), typed(1.6), key(1.7, "Tab", { shift: true })]; + + it("shows only command shortcuts by default and never typed text", () => { + expect(keystrokeEntries(keys, [], defaultKeystrokeSettings).map((entry) => entry.label)).toEqual(["Ctrl + C"]); + }); + + it("adds named keys in all-keys mode", () => { + const labels = keystrokeEntries(keys, [], { ...defaultKeystrokeSettings, mode: "all" }).map((entry) => entry.label); + expect(labels).toEqual(["Ctrl + C", "Enter", "Shift + Tab"]); + }); + + it("merges click labels in time order when enabled", () => { + const entries = keystrokeEntries([key(3, "V", { ctrl: true })], [click, { ...click, kind: "up" }], { + ...defaultKeystrokeSettings, + clickLabels: true, + }); + expect(entries).toEqual([ + { time: 2, label: "Right click" }, + { time: 3, label: "Ctrl + V" }, + ]); + }); +}); + +describe("keystrokeChipsAt", () => { + const entries = [ + { time: 1, label: "Ctrl + Z" }, + { time: 1.4, label: "Ctrl + Z" }, + { time: 1.8, label: "Ctrl + Z" }, + { time: 2, label: "Ctrl + S" }, + ]; + + it("shows nothing before the first press", () => { + expect(keystrokeChipsAt(entries, 0.5)).toEqual([]); + }); + + it("counts repeats instead of stacking copies", () => { + expect(keystrokeChipsAt(entries, 2.1).map((chip) => chip.label)).toEqual(["Ctrl + Z ×3", "Ctrl + S"]); + }); + + it("counts only the presses that have happened so far", () => { + expect(keystrokeChipsAt(entries, 1.5).map((chip) => chip.label)).toEqual(["Ctrl + Z ×2"]); + }); + + it("fades in, holds, then disappears", () => { + const single = [{ time: 1, label: "F5" }]; + expect(keystrokeChipsAt(single, 1)[0]?.opacity).toBe(0); + expect(keystrokeChipsAt(single, 1.5)[0]?.opacity).toBe(1); + const fading = keystrokeChipsAt(single, 1 + keystrokeHoldSeconds - 0.1)[0]?.opacity ?? 0; + expect(fading).toBeGreaterThan(0); + expect(fading).toBeLessThan(1); + expect(keystrokeChipsAt(single, 1 + keystrokeHoldSeconds)).toEqual([]); + }); + + it("keeps at most three labels on screen", () => { + const burst = ["A", "B", "C", "D"].map((name, index) => ({ time: 1 + index * 0.1, label: `Ctrl + ${name}` })); + expect(keystrokeChipsAt(burst, 1.5).map((chip) => chip.label)).toEqual(["Ctrl + B", "Ctrl + C", "Ctrl + D"]); + }); +}); + +describe("cursor track decoding", () => { + it("reads recordings made before keystrokes existed as having none", () => { + const track = decodeCursorTrack({ + version: 1, + times: [], + xs: [], + ys: [], + events: [], + shapes: [], + displayBounds: { x: 0, y: 0, width: 100, height: 100 }, + scaleFactor: 1, + }); + expect(track.keysRecorded).toBe(false); + expect(track.keys).toEqual([]); + }); + + it("rejects an unknown key kind", () => { + expect(() => + decodeCursorTrack({ + version: 1, + times: [], + xs: [], + ys: [], + events: [], + shapes: [], + keysRecorded: true, + keys: [{ ...key(0, "A"), kind: "chord" }], + displayBounds: { x: 0, y: 0, width: 100, height: 100 }, + scaleFactor: 1, + }), + ).toThrow(); + }); +}); diff --git a/apps/desktop/src/domain/keystrokes.ts b/apps/desktop/src/domain/keystrokes.ts new file mode 100644 index 0000000..f8a27e2 --- /dev/null +++ b/apps/desktop/src/domain/keystrokes.ts @@ -0,0 +1,130 @@ +import { z } from "zod"; +import type { CursorEvent, KeyEvent } from "./cursorTrack"; + +/* -------------------------------------------------------------------------- */ +/* Settings */ +/* -------------------------------------------------------------------------- */ + +export const keystrokeModes = ["shortcuts", "all"] as const; +export type KeystrokeMode = (typeof keystrokeModes)[number]; + +export const keystrokePositions = ["bottom", "top"] as const; +export type KeystrokePosition = (typeof keystrokePositions)[number]; + +export const keystrokeSettingsSchema = z.object({ + show: z.boolean(), + /** "shortcuts" shows only Ctrl, Alt, and Win combinations; "all" adds named + * keys such as Enter, Tab, and the arrows. Typed text is never shown. */ + mode: z.enum(keystrokeModes), + position: z.enum(keystrokePositions), + /** Percent of the default label size. */ + size: z.number(), + /** Also labels mouse presses ("Left click") next to the keys. */ + clickLabels: z.boolean(), +}); + +export type KeystrokeSettings = z.infer; + +export const defaultKeystrokeSettings: KeystrokeSettings = { + show: true, + mode: "shortcuts", + position: "bottom", + size: 100, + clickLabels: false, +}; + +/* -------------------------------------------------------------------------- */ +/* Labels */ +/* -------------------------------------------------------------------------- */ + +/** Seconds a label stays on screen after its last press. */ +export const keystrokeHoldSeconds = 1.2; +const fadeInSeconds = 0.08; +const fadeOutSeconds = 0.25; +/** More than this and the row starts covering the content being demonstrated. */ +const maxVisibleLabels = 3; + +/** A label to paint and how opaque it is at the current time. */ +export type KeystrokeChip = { readonly label: string; readonly opacity: number }; + +/** A press reduced to its label, ready for display. */ +export type KeystrokeEntry = { readonly time: number; readonly label: string }; + +/** "Win + Shift + S", in the order Windows itself writes shortcuts. */ +export function keystrokeLabel(event: KeyEvent): string { + const parts: string[] = []; + if (event.meta) parts.push("Win"); + if (event.ctrl) parts.push("Ctrl"); + if (event.alt) parts.push("Alt"); + if (event.shift) parts.push("Shift"); + parts.push(event.key); + return parts.join(" + "); +} + +function isShown(event: KeyEvent, mode: KeystrokeMode): boolean { + if (event.kind !== "key" || event.key === "") return false; + if (mode === "all") return true; + return event.ctrl || event.alt || event.meta; +} + +const clickNames: Record = { + left: "Left click", + right: "Right click", + middle: "Middle click", +}; + +/** + * Every press the overlay will label, sorted by time. + * + * Computed once per track and settings change rather than per frame; the + * per-frame work is then a single pass over this list. + */ +export function keystrokeEntries( + keys: readonly KeyEvent[], + clicks: readonly CursorEvent[], + settings: KeystrokeSettings, +): readonly KeystrokeEntry[] { + const entries: KeystrokeEntry[] = keys + .filter((event) => isShown(event, settings.mode)) + .map((event) => ({ time: event.time, label: keystrokeLabel(event) })); + if (settings.clickLabels) { + for (const click of clicks) { + if (click.kind === "down") entries.push({ time: click.time, label: clickNames[click.button] }); + } + } + return entries.sort((left, right) => left.time - right.time); +} + +/** + * The labels visible at `time`, oldest first. + * + * Repeating the same press while its label is still up counts it ("Ctrl + Z + * ×3") instead of stacking copies, which is what keeps undo runs and arrow-key + * navigation readable. + */ +export function keystrokeChipsAt(entries: readonly KeystrokeEntry[], time: number): readonly KeystrokeChip[] { + const groups: { label: string; first: number; last: number; count: number }[] = []; + for (const entry of entries) { + if (entry.time > time) break; + const previous = groups.at(-1); + if (previous?.label === entry.label && entry.time - previous.last < keystrokeHoldSeconds) { + previous.last = entry.time; + previous.count += 1; + } else { + groups.push({ label: entry.label, first: entry.time, last: entry.time, count: 1 }); + } + } + + const chips: KeystrokeChip[] = []; + for (const group of groups.slice(-maxVisibleLabels)) { + const age = time - group.last; + if (age >= keystrokeHoldSeconds) continue; + const fadeIn = Math.min(1, (time - group.first) / fadeInSeconds); + const fadeOut = Math.min(1, (keystrokeHoldSeconds - age) / fadeOutSeconds); + chips.push({ + label: group.count > 1 ? `${group.label} ×${String(group.count)}` : group.label, + opacity: Math.max(0, Math.min(fadeIn, fadeOut)), + }); + } + return chips; +} diff --git a/apps/desktop/src/domain/recording.test.ts b/apps/desktop/src/domain/recording.test.ts index 8a60ba1..172b622 100644 --- a/apps/desktop/src/domain/recording.test.ts +++ b/apps/desktop/src/domain/recording.test.ts @@ -121,6 +121,15 @@ describe("requests", () => { // smooth it; burning it in would make that impossible. expect(toRecordingRequest(defaultRecorderSettings, display, null).captureCursor).toBe(false); }); + + it("keeps keystrokes off unless the user opts in, including for older stored settings", () => { + const legacy = JSON.parse(JSON.stringify(defaultRecorderSettings)) as Record; + delete legacy.captureKeystrokes; + const parsed = readRecorderSettings(JSON.stringify(legacy)); + expect(parsed.captureKeystrokes).toBe(false); + expect(toRecordingRequest(parsed, display, null).captureKeystrokes).toBe(false); + expect(toRecordingRequest({ ...parsed, captureKeystrokes: true }, display, null).captureKeystrokes).toBe(true); + }); }); describe("stored settings", () => { diff --git a/apps/desktop/src/domain/recording.ts b/apps/desktop/src/domain/recording.ts index 39ab830..e145fee 100644 --- a/apps/desktop/src/domain/recording.ts +++ b/apps/desktop/src/domain/recording.ts @@ -95,6 +95,12 @@ export const recorderSettingsSchema = z.object({ * this on permanently bakes the raw pointer into the frames. */ captureCursor: z.boolean(), + /** + * Records key presses for the Studio overlay. Off by default and opt-in: + * shortcut names are kept, but typed characters are stored only as "typing + * happened", never as the text itself. + */ + captureKeystrokes: z.boolean().default(false), }); export type RecorderSettings = z.infer; @@ -109,6 +115,7 @@ export const defaultRecorderSettings: RecorderSettings = { microphoneDeviceId: "", systemAudioDeviceId: "", captureCursor: false, + captureKeystrokes: false, }; export const recordRegionSelectionSchema = z.object({ @@ -175,6 +182,7 @@ export function toRecordingRequest( region: { x: number; y: number; width: number; height: number } | null; fps: number; captureCursor: boolean; + captureKeystrokes: boolean; systemAudio: boolean; microphone: boolean; microphoneDeviceId: string | null; @@ -188,6 +196,7 @@ export function toRecordingRequest( region: crop, fps: resolveFrameRate(settings.fps, source.refreshRate), captureCursor: settings.captureCursor, + captureKeystrokes: settings.captureKeystrokes, systemAudio: settings.systemAudio, microphone: settings.microphone, microphoneDeviceId: settings.microphoneDeviceId === "" ? null : settings.microphoneDeviceId, diff --git a/apps/desktop/src/domain/videoScene.ts b/apps/desktop/src/domain/videoScene.ts index abcce69..cb84d11 100644 --- a/apps/desktop/src/domain/videoScene.ts +++ b/apps/desktop/src/domain/videoScene.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { cursorTrackSchema } from "./cursorTrack"; +import { defaultKeystrokeSettings, keystrokeSettingsSchema, type KeystrokeChip } from "./keystrokes"; import { defaultEffectSettings, defaultFrameSettings, @@ -123,6 +124,8 @@ export const videoSceneSchema = z.object({ cursor: cursorStyleSchema, camera: cameraLayoutSchema, zoom: zoomSettingsSchema, + /** Defaulted so scenes saved before the overlay existed still load. */ + keystrokes: keystrokeSettingsSchema.default(() => ({ ...defaultKeystrokeSettings })), trim: trimSchema, audio: audioMixSchema, }); @@ -140,6 +143,7 @@ export function defaultVideoScene(durationSeconds: number): VideoScene { cursor: defaultCursorStyle, camera: { ...defaultCameraLayout, show: false }, zoom: defaultZoomSettings, + keystrokes: defaultKeystrokeSettings, trim: { start: 0, end: Math.max(0.1, durationSeconds) }, audio: defaultAudioMix, }; @@ -159,6 +163,8 @@ export type VideoSources = { readonly cursor: { readonly x: number; readonly y: number } | null; /** 0 to 1, ramping down after a click for the highlight ring. */ readonly clickPulse: number; + /** Key and click labels visible at this frame. */ + readonly keystrokes: readonly KeystrokeChip[]; }; export const emptyCursorTrack = cursorTrackSchema.parse({ diff --git a/apps/desktop/src/lib/videoCompositor.test.ts b/apps/desktop/src/lib/videoCompositor.test.ts index 6505e01..954fac7 100644 --- a/apps/desktop/src/lib/videoCompositor.test.ts +++ b/apps/desktop/src/lib/videoCompositor.test.ts @@ -31,6 +31,8 @@ function fakeContext(): CanvasRenderingContext2D { fill: vi.fn(() => calls.push("fill")), stroke: vi.fn(() => calls.push("stroke")), drawImage: vi.fn(() => calls.push("drawImage")), + fillText: vi.fn((text: string) => calls.push(`fillText:${text}`)), + measureText: vi.fn((text: string) => ({ width: text.length * 8 })), translate: vi.fn(), scale: vi.fn(), createLinearGradient: vi.fn(() => gradient), @@ -59,6 +61,15 @@ function fakeContext(): CanvasRenderingContext2D { set shadowOffsetY(value: unknown) { void value; }, + set font(value: unknown) { + void value; + }, + set textBaseline(value: unknown) { + void value; + }, + set textAlign(value: unknown) { + void value; + }, }; return context as unknown as CanvasRenderingContext2D; } @@ -77,6 +88,7 @@ describe("paintFrame", () => { camera: null, cursor: null, clickPulse: 0, + keystrokes: [], }, stage, [], 0); const fillIndex = context.calls.indexOf("fillRect"); @@ -96,6 +108,7 @@ describe("paintFrame", () => { camera: null, cursor: null, clickPulse: 0, + keystrokes: [], }, stage, [], 0); // With no background, no padding, and no media, the only fill left is the // placeholder rect — never more than one before the clip. @@ -114,6 +127,7 @@ describe("paintFrame", () => { camera: null, cursor: null, clickPulse: 0, + keystrokes: [], }, stage, [], 0); expect(context.calls).toContain("drawImage"); }); @@ -128,6 +142,7 @@ describe("paintFrame", () => { camera: null, cursor: { x: 500, y: 500 }, clickPulse: 1, + keystrokes: [], }, stage, [], 0); // The cursor glyph is drawn via a path (moveTo/lineTo), not arc; the click // ring is the only `arc` call, so hiding the cursor removes it too. @@ -144,6 +159,7 @@ describe("paintFrame", () => { camera: null, cursor: { x: 500, y: 500 }, clickPulse: 1, + keystrokes: [], }, stage, [], 0); expect(active.arc).toHaveBeenCalled(); @@ -155,6 +171,7 @@ describe("paintFrame", () => { camera: null, cursor: { x: 500, y: 500 }, clickPulse: 0, + keystrokes: [], }, stage, [], 0); expect(idle.arc).not.toHaveBeenCalled(); }); @@ -169,6 +186,7 @@ describe("paintFrame", () => { camera: null, cursor: null, clickPulse: 0, + keystrokes: [], }, stage, [], 0); // Camera enabled but no source: only the media draw happens. expect(withoutCamera.drawImage).toHaveBeenCalledTimes(1); @@ -184,10 +202,34 @@ describe("paintFrame", () => { camera: cameraSource, cursor: null, clickPulse: 0, + keystrokes: [], }, stage, [], 0); expect(withCamera.drawImage).toHaveBeenCalledTimes(2); }); + it("paints key labels only when they are shown", () => { + const scene = defaultVideoScene(5); + const sources = { + media: {} as CanvasImageSource, + mediaSize, + background: null, + camera: null, + cursor: null, + clickPulse: 0, + keystrokes: [ + { label: "Ctrl + C", opacity: 1 }, + { label: "Ctrl + V", opacity: 0.5 }, + ], + }; + const shown = fakeContext() as unknown as { calls: string[] }; + paintFrame(shown as unknown as CanvasRenderingContext2D, scene, sources, stage, [], 0); + expect(shown.calls.filter((call) => call.startsWith("fillText:"))).toEqual(["fillText:Ctrl + C", "fillText:Ctrl + V"]); + + const hidden = fakeContext() as unknown as { calls: string[] }; + paintFrame(hidden as unknown as CanvasRenderingContext2D, { ...scene, keystrokes: { ...scene.keystrokes, show: false } }, sources, stage, [], 0); + expect(hidden.calls.some((call) => call.startsWith("fillText:"))).toBe(false); + }); + it("never throws across the default scene, with or without sources", () => { const scene = defaultVideoScene(5); for (const sources of [ @@ -195,7 +237,7 @@ describe("paintFrame", () => { { media: {} as CanvasImageSource, camera: {} as CanvasImageSource, cursor: { x: 1, y: 1 } }, ]) { expect(() => - paintFrame(fakeContext(), scene, { ...sources, mediaSize, background: null, clickPulse: 0.5 }, stage, [], 0), + paintFrame(fakeContext(), scene, { ...sources, mediaSize, background: null, clickPulse: 0.5, keystrokes: [] }, stage, [], 0), ).not.toThrow(); } }); diff --git a/apps/desktop/src/lib/videoCompositor.ts b/apps/desktop/src/lib/videoCompositor.ts index 898ddd4..67bf7f8 100644 --- a/apps/desktop/src/lib/videoCompositor.ts +++ b/apps/desktop/src/lib/videoCompositor.ts @@ -112,6 +112,61 @@ export function paintFrame( paintCamera(context, scene, sources.camera, stage); } + if (scene.keystrokes.show && sources.keystrokes.length > 0) { + paintKeystrokes(context, scene.keystrokes, sources.keystrokes, { x, y, width, height }); + } + + context.restore(); +} + +const keystrokeFont = '"Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif'; + +/** + * Key labels as a centred row of pills over the recorded frame. + * + * Sized from the frame, not the stage, so a label covers the same share of the + * content in a 480p GIF as in a 4K MP4. Painted after the camera so a bubble + * in the corner never hides a shortcut. + */ +function paintKeystrokes( + context: Canvas2D, + settings: VideoScene["keystrokes"], + chips: VideoSources["keystrokes"], + media: { x: number; y: number; width: number; height: number }, +): void { + const fontSize = Math.min(96, Math.max(10, media.height * 0.036 * (settings.size / 100))); + const pillHeight = fontSize * 1.9; + const paddingX = fontSize * 0.85; + const gap = fontSize * 0.45; + const margin = fontSize * 1.3; + + context.save(); + context.font = `600 ${String(Math.round(fontSize))}px ${keystrokeFont}`; + context.textBaseline = "middle"; + context.textAlign = "left"; + + const widths = chips.map((chip) => context.measureText(chip.label).width + paddingX * 2); + const rowWidth = widths.reduce((total, width) => total + width, 0) + gap * Math.max(0, chips.length - 1); + let left = media.x + (media.width - rowWidth) / 2; + const top = settings.position === "top" ? media.y + margin : media.y + media.height - margin - pillHeight; + + chips.forEach((chip, index) => { + const width = widths[index] ?? 0; + context.globalAlpha = chip.opacity; + context.shadowColor = "rgb(0 0 0 / 35%)"; + context.shadowBlur = fontSize * 0.8; + context.shadowOffsetY = fontSize * 0.15; + context.fillStyle = "rgb(16 18 16 / 84%)"; + roundedRect(context, left, top, width, pillHeight, fontSize * 0.5); + context.fill(); + context.shadowColor = "transparent"; + context.strokeStyle = "rgb(255 255 255 / 16%)"; + context.lineWidth = Math.max(1, fontSize * 0.06); + context.stroke(); + context.fillStyle = "#f5f6f3"; + context.fillText(chip.label, left + paddingX, top + pillHeight / 2); + left += width + gap; + }); context.restore(); } diff --git a/apps/desktop/src/lib/videoExport.ts b/apps/desktop/src/lib/videoExport.ts index b106218..bc70dba 100644 --- a/apps/desktop/src/lib/videoExport.ts +++ b/apps/desktop/src/lib/videoExport.ts @@ -3,6 +3,7 @@ import type { CursorTrack } from "../domain/cursorTrack"; import { cursorAt, smoothCursorPath, toPoints } from "../domain/cursorTrack"; import type { Size } from "../domain/showcase"; import { trimmedDuration, type VideoScene, type VideoSources } from "../domain/videoScene"; +import { keystrokeChipsAt, keystrokeEntries, type KeystrokeEntry } from "../domain/keystrokes"; import { clusterClicks, generateZoomKeyframes, mergeKeyframes, type ZoomKeyframe } from "../domain/zoomKeyframes"; import { planEncode, retryBitrate, type EncodePlan } from "./exportSize"; import { clickPulseAt, paintFrame } from "./videoCompositor"; @@ -24,6 +25,12 @@ export type ExportRequest = { readonly signal?: AbortSignal; }; +/** Key and click labels for a composition, empty when the overlay is off. */ +export function keystrokeEntriesFor(scene: VideoScene, track: CursorTrack | null): readonly KeystrokeEntry[] { + if (track === null || !scene.keystrokes.show) return []; + return keystrokeEntries(track.keys, track.events, scene.keystrokes); +} + /** Zoom keyframes for a composition, auto-generated then overridden by manual ones. */ export function keyframesFor(scene: VideoScene, track: CursorTrack | null, media: Size): readonly ZoomKeyframe[] { if (!scene.zoom.enabled) return scene.zoom.manual; @@ -112,14 +119,15 @@ export async function exportVideo(request: ExportRequest): Promise { const keyframes = keyframesFor(scene, request.track, mediaSize); const cursorPath = smoothedCursor(request.track, scene, fps); const events = request.track?.events ?? []; + const keystrokes = keystrokeEntriesFor(scene, request.track); if (request.format === "gif") { - return exportGif({ ...request, width, height, frames, duration, canvas, context, mediaSize, keyframes, cursorPath, events }); + return exportGif({ ...request, width, height, frames, duration, canvas, context, mediaSize, keyframes, cursorPath, events, keystrokes }); } const targetBytes = request.targetBytes ?? null; const plan = planEncode({ width, height }, fps, duration, targetBytes); - const mp4: Mp4Context = { ...request, width, height, duration, canvas, context, mediaSize, keyframes, cursorPath, events }; + const mp4: Mp4Context = { ...request, width, height, duration, canvas, context, mediaSize, keyframes, cursorPath, events, keystrokes }; if (targetBytes === null) return encodeMp4(mp4, plan, (fraction) => request.onProgress?.(fraction)); // A sized export reports progress across a possible second pass as one bar. @@ -143,6 +151,7 @@ type Mp4Context = ExportRequest & { keyframes: readonly ZoomKeyframe[]; cursorPath: readonly { t: number; x: number; y: number }[]; events: readonly { time: number; kind: string }[]; + keystrokes: readonly KeystrokeEntry[]; }; async function encodeMp4(mp4: Mp4Context, plan: EncodePlan, onProgress: (fraction: number) => void): Promise { @@ -219,6 +228,7 @@ type GifContext = ExportRequest & { keyframes: readonly ZoomKeyframe[]; cursorPath: readonly { t: number; x: number; y: number }[]; events: readonly { time: number; kind: string }[]; + keystrokes: readonly KeystrokeEntry[]; }; /** @@ -255,7 +265,7 @@ async function exportGif(gif: GifContext): Promise { function drawOne( context: OffscreenCanvasRenderingContext2D, scene: VideoScene, - request: Pick, + request: Pick & { readonly keystrokes: readonly KeystrokeEntry[] }, stage: Size, mediaSize: Size, keyframes: readonly ZoomKeyframe[], @@ -271,6 +281,7 @@ function drawOne( camera: request.camera, cursor: cursorPath.length === 0 ? null : cursorAt(cursorPath, absolute), clickPulse: clickPulseAt(events, absolute), + keystrokes: keystrokeChipsAt(request.keystrokes, absolute), }; paintFrame(context, scene, sources, stage, keyframes, absolute); } From eeb5b5ae1814a39f05b6adbf9bd748e915dd4af3 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 22:19:27 +0530 Subject: [PATCH 08/16] feat(studio): zoom follows typing Automatic zoom now also targets bursts of typing: three or more presses with gaps under 1.2 s, with Backspace and Delete counted. The caret is never recorded, so each burst focuses on the click that placed the caret, or on the pointer if nothing was clicked first. A click ends a burst. Typing bursts go through the same generator as click clusters, so the camera pans between nearby moments rather than pulling out. The generator now holds the zoom until the latest end it has seen, so a click inside a long burst no longer zooms out early. Studio's Zoom section adds a Follow typing toggle. It is on by default and disabled when a recording has no keys. Co-Authored-By: Claude Opus 5.5 --- .../dashboard/studio/StudioPanels.tsx | 6 ++ apps/desktop/src/domain/videoScene.ts | 3 + apps/desktop/src/domain/zoomKeyframes.test.ts | 59 +++++++++++++- apps/desktop/src/domain/zoomKeyframes.ts | 81 ++++++++++++++++++- apps/desktop/src/lib/videoExport.test.ts | 40 ++++++++- apps/desktop/src/lib/videoExport.ts | 13 ++- 6 files changed, 194 insertions(+), 8 deletions(-) diff --git a/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx b/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx index 9c4fb3c..75bf474 100644 --- a/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx +++ b/apps/desktop/src/components/dashboard/studio/StudioPanels.tsx @@ -205,6 +205,12 @@ export function MotionPanel({ onPatchZoom({ enabled: value })} /> + onPatchZoom({ followTyping: value })} + /> onPatchZoom({ scale: value / 100 })} /> ; export const defaultZoomSettings: ZoomSettings = { enabled: true, ...defaultZoomOptions, + followTyping: true, manual: [], }; diff --git a/apps/desktop/src/domain/zoomKeyframes.test.ts b/apps/desktop/src/domain/zoomKeyframes.test.ts index 39ef18e..ccc7a60 100644 --- a/apps/desktop/src/domain/zoomKeyframes.test.ts +++ b/apps/desktop/src/domain/zoomKeyframes.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; -import type { CursorEvent } from "./cursorTrack"; +import type { CursorEvent, KeyEvent } from "./cursorTrack"; import { clampFocus, clusterClicks, defaultZoomOptions, generateZoomKeyframes, mergeKeyframes, + typingClusters, zoomAt, type ZoomKeyframe, } from "./zoomKeyframes"; @@ -123,3 +124,59 @@ describe("merging and sampling", () => { expect(zoomAt([], 1)).toEqual({ scale: 1, cx: 0.5, cy: 0.5 }); }); }); + +function typed(time: number): KeyEvent { + return { time, kind: "text", key: "", ctrl: false, shift: false, alt: false, meta: false }; +} + +function named(time: number, key: string, ctrl = false): KeyEvent { + return { time, kind: "key", key, ctrl, shift: false, alt: false, meta: false }; +} + +const noPointer = (): null => null; + +describe("typing", () => { + it("zooms to the click that placed the caret", () => { + const clusters = typingClusters([typed(2), typed(2.2), typed(2.4), typed(2.6)], [press(1, 300, 400)], noPointer); + expect(clusters).toEqual([{ start: 2, end: 2.6, cx: 300, cy: 400, count: 4 }]); + }); + + it("falls back to the pointer when nothing was clicked first", () => { + const clusters = typingClusters([typed(1), typed(1.1), typed(1.2)], [], () => ({ x: 50, y: 60 })); + expect(clusters[0]).toMatchObject({ cx: 50, cy: 60 }); + }); + + it("ignores shortcuts and a couple of stray keys", () => { + const keys = [named(1, "C", true), named(1.1, "V", true), named(1.2, "Z", true), typed(5), typed(5.1)]; + expect(typingClusters(keys, [press(0, 1, 1)], noPointer)).toEqual([]); + }); + + it("keeps correcting a typo inside one burst", () => { + const keys = [typed(1), typed(1.2), named(1.4, "Backspace"), typed(1.6)]; + expect(typingClusters(keys, [press(0, 1, 1)], noPointer)).toHaveLength(1); + }); + + it("splits on a pause and on a click that moves the caret", () => { + const keys = [typed(1), typed(1.2), typed(1.4), typed(4), typed(4.2), typed(4.4), typed(4.7), typed(4.9), typed(5.1)]; + const clicks = [press(0, 10, 10), press(4.6, 800, 500)]; + const clusters = typingClusters(keys, clicks, noPointer); + expect(clusters.map((cluster) => [cluster.start, cluster.cx])).toEqual([ + [1, 10], + [4, 10], + [4.7, 800], + ]); + }); + + it("holds the zoom until a typing burst ends, even when a click starts later inside it", () => { + const keyframes = generateZoomKeyframes( + [ + { start: 1, end: 6, cx: 400, cy: 300, count: 20 }, + { start: 3, end: 3, cx: 900, cy: 500, count: 1 }, + ], + source, + ); + const pullOut = keyframes.at(-1); + expect(pullOut?.scale).toBe(1); + expect(pullOut?.time).toBeCloseTo(6 + defaultZoomOptions.holdSeconds + defaultZoomOptions.transitionSeconds); + }); +}); diff --git a/apps/desktop/src/domain/zoomKeyframes.ts b/apps/desktop/src/domain/zoomKeyframes.ts index bdd2882..8603a2a 100644 --- a/apps/desktop/src/domain/zoomKeyframes.ts +++ b/apps/desktop/src/domain/zoomKeyframes.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import type { CursorEvent } from "./cursorTrack"; +import type { CursorEvent, KeyEvent } from "./cursorTrack"; import type { Size } from "./showcase"; /* -------------------------------------------------------------------------- */ @@ -104,6 +104,75 @@ export function clusterClicks( return clusters; } +/* -------------------------------------------------------------------------- */ +/* Typing */ +/* -------------------------------------------------------------------------- */ + +export type TypingOptions = { + /** A pause longer than this ends the burst. */ + readonly gapSeconds?: number; + /** Fewer presses than this is a shortcut or a stray key, not typing. */ + readonly minPresses?: number; +}; + +/** Unmodified editing keys continue a burst, so correcting a typo does not end it. */ +const editingKeys = new Set(["Backspace", "Delete"]); + +function isTypingPress(event: KeyEvent): boolean { + if (event.kind === "text") return true; + return editingKeys.has(event.key) && !event.ctrl && !event.alt && !event.meta; +} + +/** + * Turns bursts of typing into zoom targets, shaped like click clusters so + * the same generator can bridge between the two. + * + * The caret is never recorded, so the focus is the last click before the burst + * (almost always the click that placed the caret), falling back to where the + * pointer was when typing began. A click ends a burst, because the caret has + * moved. + */ +export function typingClusters( + keys: readonly KeyEvent[], + clicks: readonly CursorEvent[], + pointerAt: (time: number) => { readonly x: number; readonly y: number } | null, + options: TypingOptions = {}, +): readonly ClickCluster[] { + const gap = options.gapSeconds ?? 1.2; + const minPresses = options.minPresses ?? 3; + const presses = clicks.filter((event) => event.kind === "down"); + const typing = keys.filter(isTypingPress); + + const bursts: { start: number; end: number; count: number }[] = []; + // Both lists are in time order, so one cursor finds the clicks that fell + // between the previous press and this one. + let clickIndex = 0; + for (const press of typing) { + let clickedSince = false; + while (clickIndex < presses.length && (presses[clickIndex]?.time ?? Infinity) <= press.time) { + clickedSince = true; + clickIndex += 1; + } + const current = bursts.at(-1); + if (current !== undefined && press.time - current.end <= gap && !clickedSince) { + current.end = press.time; + current.count += 1; + } else { + bursts.push({ start: press.time, end: press.time, count: 1 }); + } + } + + const clusters: ClickCluster[] = []; + for (const burst of bursts) { + if (burst.count < minPresses) continue; + const placedCaret = presses.filter((click) => click.time <= burst.start).at(-1); + const focus = placedCaret ?? pointerAt(burst.start); + if (focus === null) continue; + clusters.push({ start: burst.start, end: burst.end, cx: focus.x, cy: focus.y, count: burst.count }); + } + return clusters; +} + /* -------------------------------------------------------------------------- */ /* Keyframe generation */ /* -------------------------------------------------------------------------- */ @@ -153,10 +222,14 @@ export function generateZoomKeyframes( // pulling out, so the camera glides between them instead of popping. const bridged = [first]; let last = first; + // A click can land inside a typing burst, so the zoom holds until the + // latest end seen, not just the end of the last cluster to start. + let end = first.end; let next = clusters[index + 1]; - while (next !== undefined && next.start - last.end <= options.bridgeSeconds) { + while (next !== undefined && next.start - end <= options.bridgeSeconds) { bridged.push(next); last = next; + end = Math.max(end, next.end); index += 1; next = clusters[index + 1]; } @@ -170,8 +243,8 @@ export function generateZoomKeyframes( } const focus = { cx: last.cx / source.width, cy: last.cy / source.height }; - keyframes.push(at(last.end + options.holdSeconds, options.scale, focus.cx, focus.cy)); - keyframes.push(at(last.end + options.holdSeconds + options.transitionSeconds, 1, focus.cx, focus.cy)); + keyframes.push(at(end + options.holdSeconds, options.scale, focus.cx, focus.cy)); + keyframes.push(at(end + options.holdSeconds + options.transitionSeconds, 1, focus.cx, focus.cy)); index += 1; } diff --git a/apps/desktop/src/lib/videoExport.test.ts b/apps/desktop/src/lib/videoExport.test.ts index 4ea52b0..9b68f34 100644 --- a/apps/desktop/src/lib/videoExport.test.ts +++ b/apps/desktop/src/lib/videoExport.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from "vitest"; -import { GifEncoder, seekAll } from "./videoExport"; +import { decodeCursorTrack } from "../domain/cursorTrack"; +import { defaultVideoScene } from "../domain/videoScene"; +import { GifEncoder, keyframesFor, seekAll } from "./videoExport"; /** A plain object shaped like `ImageData`, since jsdom has no real Canvas. */ function fakeFrame(width: number, height: number, rgb: readonly [number, number, number]): ImageData { @@ -118,3 +120,39 @@ describe("seekAll", () => { expect(video.currentTime).toBe(1.5); }); }); + +describe("keyframesFor", () => { + const typing = [1, 1.2, 1.4, 1.6].map((time) => ({ + time, + kind: "text" as const, + key: "", + ctrl: false, + shift: false, + alt: false, + meta: false, + })); + const track = decodeCursorTrack({ + version: 1, + times: [0, 2], + xs: [400, 400], + ys: [300, 300], + events: [], + shapes: [], + keysRecorded: true, + keys: typing, + displayBounds: { x: 0, y: 0, width: 1920, height: 1080 }, + scaleFactor: 1, + }); + const media = { width: 1920, height: 1080 }; + + it("zooms to typing when follow typing is on", () => { + const keyframes = keyframesFor(defaultVideoScene(5), track, media); + expect(keyframes.some((frame) => frame.scale > 1)).toBe(true); + }); + + it("ignores typing when follow typing is off", () => { + const scene = defaultVideoScene(5); + const keyframes = keyframesFor({ ...scene, zoom: { ...scene.zoom, followTyping: false } }, track, media); + expect(keyframes).toEqual([]); + }); +}); diff --git a/apps/desktop/src/lib/videoExport.ts b/apps/desktop/src/lib/videoExport.ts index bc70dba..491eeda 100644 --- a/apps/desktop/src/lib/videoExport.ts +++ b/apps/desktop/src/lib/videoExport.ts @@ -4,7 +4,7 @@ import { cursorAt, smoothCursorPath, toPoints } from "../domain/cursorTrack"; import type { Size } from "../domain/showcase"; import { trimmedDuration, type VideoScene, type VideoSources } from "../domain/videoScene"; import { keystrokeChipsAt, keystrokeEntries, type KeystrokeEntry } from "../domain/keystrokes"; -import { clusterClicks, generateZoomKeyframes, mergeKeyframes, type ZoomKeyframe } from "../domain/zoomKeyframes"; +import { clusterClicks, generateZoomKeyframes, mergeKeyframes, typingClusters, type ZoomKeyframe } from "../domain/zoomKeyframes"; import { planEncode, retryBitrate, type EncodePlan } from "./exportSize"; import { clickPulseAt, paintFrame } from "./videoCompositor"; @@ -31,11 +31,20 @@ export function keystrokeEntriesFor(scene: VideoScene, track: CursorTrack | null return keystrokeEntries(track.keys, track.events, scene.keystrokes); } +function pointerLookup(track: CursorTrack): (time: number) => { x: number; y: number } | null { + const points = toPoints(track); + return (time) => cursorAt(points, time); +} + /** Zoom keyframes for a composition, auto-generated then overridden by manual ones. */ export function keyframesFor(scene: VideoScene, track: CursorTrack | null, media: Size): readonly ZoomKeyframe[] { if (!scene.zoom.enabled) return scene.zoom.manual; const events = track?.events ?? []; - const clusters = clusterClicks(events); + const typing = + track !== null && scene.zoom.followTyping && track.keys.length > 0 + ? typingClusters(track.keys, events, pointerLookup(track)) + : []; + const clusters = [...clusterClicks(events), ...typing].sort((left, right) => left.start - right.start); const auto = generateZoomKeyframes(clusters, media, { scale: scene.zoom.scale, leadSeconds: scene.zoom.leadSeconds, From d3a20899a92c5fb0cd996b5b1fd73d00f336e010 Mon Sep 17 00:00:00 2001 From: Nakul Srivastava Date: Thu, 29 Oct 2026 22:30:37 +0530 Subject: [PATCH 09/16] feat(showcase): default style and Save & Showcase from the completion rail Star a saved Showcase style to apply it to captures sent to Showcase. The completion rail gains Save & Showcase, which saves the capture and opens it in the dashboard's Showcase tab with that style. The capture path is handed over through a one-shot native slot so a freshly built dashboard still receives it, and only files inside the save folder are accepted. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src-tauri/src/lib.rs | 58 ++++++++++++++++++- apps/desktop/src/App.test.tsx | 31 +++++++++- apps/desktop/src/App.tsx | 11 +++- .../src/components/CompletionToolbar.test.tsx | 16 ++++- .../src/components/CompletionToolbar.tsx | 10 ++++ .../components/dashboard/DashboardPanel.tsx | 45 ++++++++++++-- .../dashboard/ShowcaseView.test.tsx | 47 +++++++++++++++ .../src/components/dashboard/ShowcaseView.tsx | 41 ++++++++++++- .../dashboard/showcase/BackgroundPanel.tsx | 19 +++++- apps/desktop/src/domain/capture.test.ts | 23 +++++++- apps/desktop/src/domain/capture.ts | 13 +++++ apps/desktop/src/domain/showcase.test.ts | 30 ++++++++++ apps/desktop/src/domain/showcase.ts | 26 +++++++++ apps/desktop/src/lib/tauri.ts | 19 ++++++ 14 files changed, 376 insertions(+), 13 deletions(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index a977692..36a6e68 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -119,6 +119,12 @@ struct OnScreenActiveState { struct OnScreenModeRegistry(Mutex); +/// A saved capture waiting for the dashboard to open it in Showcase. +/// +/// A slot rather than an event alone: when the dashboard has to be built, its +/// listeners do not exist yet, so it takes the capture once it has loaded. +struct PendingShowcase(Mutex>); + #[tauri::command] async fn begin_capture(app: AppHandle) -> Result { #[cfg(debug_assertions)] @@ -208,13 +214,58 @@ fn launched_in_background() -> bool { } #[tauri::command] -fn dashboard_ready(app: AppHandle) -> Result<(), SnaphubError> { - if launched_in_background() { +fn dashboard_ready( + app: AppHandle, + pending: tauri::State<'_, PendingShowcase>, +) -> Result<(), SnaphubError> { + // A capture sent to Showcase is an explicit request to see the dashboard, + // even in a session that started hidden at sign-in. + let showcase_requested = pending.0.lock().is_ok_and(|slot| slot.is_some()); + if launched_in_background() && !showcase_requested { return Ok(()); } show_dashboard(&app) } +/// Opens a saved capture in the dashboard's Showcase tab. +/// +/// Only files inside the save folder are accepted, the same rule the library +/// uses, so a capture window cannot point the dashboard at arbitrary files. +#[tauri::command] +async fn open_in_showcase(app: AppHandle, path: String) -> Result<(), SnaphubError> { + app.state::() + .validated_saved_capture(Path::new(&path))?; + *app.state::() + .0 + .lock() + .map_err(|_| SnaphubError::Window("Showcase request state is unavailable".into()))? = + Some(path); + let existing = app.get_webview_window("dashboard"); + show_dashboard(&app)?; + if let Some(window) = existing { + let _ = window.emit("capkit://showcase-requested", ()); + } + Ok(()) +} + +/// Hands the pending Showcase capture to the dashboard, at most once. +#[tauri::command] +fn take_pending_showcase( + window: WebviewWindow, + pending: tauri::State<'_, PendingShowcase>, +) -> Result, SnaphubError> { + if window.label() != "dashboard" { + return Err(SnaphubError::Session( + "Only the dashboard can open Showcase captures".into(), + )); + } + Ok(pending + .0 + .lock() + .map_err(|_| SnaphubError::Window("Showcase request state is unavailable".into()))? + .take()) +} + #[tauri::command] fn on_screen_session( registry: tauri::State<'_, OnScreenModeRegistry>, @@ -2332,10 +2383,13 @@ pub fn run() { .manage(PinnedCaptureRegistry(Mutex::new(HashMap::new()))) .manage(RecordRegionRegistry(Mutex::new(None))) .manage(OnScreenModeRegistry(Mutex::new(OnScreenModeState::Idle))) + .manage(PendingShowcase(Mutex::new(None))) .invoke_handler(tauri::generate_handler![ begin_capture, show_capture_surface, dashboard_ready, + open_in_showcase, + take_pending_showcase, on_screen_session, on_screen_snapshot, on_screen_ready, diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 2cb69b2..37b9bf4 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -13,6 +13,7 @@ const captureMocks = vi.hoisted(() => ({ recognizeCaptureText: vi.fn(), isTextRecognitionSupported: vi.fn(), listeners: [] as (() => void)[], + openInShowcase: vi.fn(), pickCaptureColor: vi.fn(), requestCapture: vi.fn(), retryCaptureSave: vi.fn(), @@ -30,6 +31,7 @@ vi.mock("./lib/tauri", async (importOriginal) => { copyCaptureText: captureMocks.copyCaptureText, recognizeCaptureText: captureMocks.recognizeCaptureText, isTextRecognitionSupported: captureMocks.isTextRecognitionSupported, + openInShowcase: captureMocks.openInShowcase, pickCaptureColor: captureMocks.pickCaptureColor, listenForCaptureRequest: vi.fn((callback: () => void) => { captureMocks.listeners.push(callback); @@ -516,7 +518,34 @@ describe("App", () => { expect(combined).toHaveTextContent("A"); expect( Array.from(toolbar.querySelectorAll("button")).map((button) => button.getAttribute("aria-label")), - ).toEqual(["Copy", "Copy & Save", "Save", "Pin"]); + ).toEqual(["Copy", "Copy & Save", "Save", "Pin", "Save & Showcase"]); + }); + + it("saves, then opens the saved file in Showcase", async () => { + captureMocks.openInShowcase.mockResolvedValue(undefined); + render(); + await selectRegion(); + fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); + + await waitFor(() => expect(captureMocks.openInShowcase).toHaveBeenCalledWith("Demo/Capkit.png")); + expect(captureMocks.completeCapture).toHaveBeenCalledTimes(1); + expect(captureMocks.completeCapture.mock.calls[0]?.[0]).toBe("save"); + }); + + it("does not open Showcase when the save is still pending", async () => { + captureMocks.completeCapture.mockResolvedValueOnce({ + action: "save", + cleanupWarning: null, + diagnostic: "SH-EXPORT-001: disk full", + outputPath: null, + status: "save-pending", + }); + render(); + await selectRegion(); + fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); + + expect(await screen.findByRole("button", { name: "Retry save" })).toBeVisible(); + expect(captureMocks.openInShowcase).not.toHaveBeenCalled(); }); it("ignores the completion key without a selection, with modifiers, or in an editable field", async () => { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 241dc8a..e3e6d6f 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -41,6 +41,7 @@ import { cancelManualScrolling, captureScrolling, completeCapture, + openInShowcase, completeScrollingCapture, copyCaptureText, detectTargets, @@ -596,7 +597,7 @@ export function App(): React.JSX.Element { }, [session]); const handleComplete = useCallback( - async (action: CompletionAction): Promise => { + async (action: CompletionAction, followUp: "none" | "showcase" = "none"): Promise => { if ( session === null || selection === null @@ -645,6 +646,13 @@ export function App(): React.JSX.Element { : `${successMessage} · ${result.cleanupWarning}`, ); clearCaptureUi(); + // The capture window is already hidden, so a failure here has no UI to + // land in; the image itself is saved either way. + if (followUp === "showcase" && result.outputPath !== null) { + void openInShowcase(result.outputPath).catch((error: unknown) => { + console.error("SH-SHOWCASE-OPEN-001", error); + }); + } } catch (error: unknown) { if ( activeSessionId.current === sessionId @@ -1118,6 +1126,7 @@ export function App(): React.JSX.Element { statusSide={actionRailX < viewport.width / 2 ? "right" : "left"} onComplete={(action) => void handleComplete(action)} onRetrySave={() => void handleRetrySave()} + onShowcase={() => void handleComplete("save", "showcase")} {...(canReadText ? { onCopyText: () => void handleCopyText(), diff --git a/apps/desktop/src/components/CompletionToolbar.test.tsx b/apps/desktop/src/components/CompletionToolbar.test.tsx index 86e6286..9673df4 100644 --- a/apps/desktop/src/components/CompletionToolbar.test.tsx +++ b/apps/desktop/src/components/CompletionToolbar.test.tsx @@ -10,7 +10,11 @@ const actions: readonly { action: CompletionAction; label: string }[] = [ { action: "pin", label: "Pin" }, ]; -function renderToolbar(onComplete: (action: CompletionAction) => void, onCopyText?: () => void): void { +function renderToolbar( + onComplete: (action: CompletionAction) => void, + onCopyText?: () => void, + onShowcase: () => void = () => undefined, +): void { render( void, onCopyTex statusSide="right" onComplete={onComplete} onRetrySave={() => undefined} + onShowcase={onShowcase} {...(onCopyText === undefined ? {} : { onCopyText })} />, ); @@ -76,4 +81,13 @@ describe("CompletionToolbar", () => { fireEvent.click(screen.getByRole("button", { name: "Copy text" })); expect(onCopyText).toHaveBeenCalledOnce(); }); + + it("saves and opens Showcase from its own action, not through onComplete", () => { + const onComplete = vi.fn(); + const onShowcase = vi.fn(); + renderToolbar(onComplete, undefined, onShowcase); + fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); + expect(onShowcase).toHaveBeenCalledOnce(); + expect(onComplete).not.toHaveBeenCalled(); + }); }); diff --git a/apps/desktop/src/components/CompletionToolbar.tsx b/apps/desktop/src/components/CompletionToolbar.tsx index edae56e..5c14e48 100644 --- a/apps/desktop/src/components/CompletionToolbar.tsx +++ b/apps/desktop/src/components/CompletionToolbar.tsx @@ -5,6 +5,7 @@ import { Copy, Download, Pin, + Presentation, Refresh, SecurityCheck, TextSelection, @@ -24,6 +25,8 @@ type CompletionToolbarProps = { statusSide: "left" | "right"; onComplete: (action: CompletionAction) => void; onRetrySave: () => void; + /** Saves, then opens the capture in Showcase with the default style. */ + onShowcase: () => void; /** Present only when the OS can read text; the button is hidden otherwise. */ onCopyText?: () => void; /** Present only when the OS can read text; opens redaction suggestions. */ @@ -40,6 +43,7 @@ export function CompletionToolbar({ statusSide, onComplete, onRetrySave, + onShowcase, onCopyText, onFindSensitive, }: CompletionToolbarProps): React.JSX.Element { @@ -89,6 +93,12 @@ export function CompletionToolbar({ label="Pin" onClick={() => onComplete("pin")} /> + {onCopyText === undefined ? null : ( ("screenshots"); const [showcaseCapture, setShowcaseCapture] = useState(null); + const [isShowcaseStylePending, setIsShowcaseStylePending] = useState(false); const [version, setVersion] = useState(null); const { settings, updateSettings } = useSnaphubSettings(); + const clearShowcaseStylePending = useCallback((): void => { + setIsShowcaseStylePending(false); + }, []); useEffect(() => { let cancelled = false; @@ -57,6 +61,34 @@ export function DashboardPanel(): React.JSX.Element { return (): void => window.cancelAnimationFrame(frame); }, []); + // A capture sent from the completion rail. Pulled on mount, because a freshly + // built dashboard missed the event, and again whenever an open one is asked. + // The take is one-shot, so the result is applied even after a cleanup: + // StrictMode's rehearsal unmount would otherwise discard the only copy. + useEffect(() => { + if (!isTauri()) return; + const openPending = async (): Promise => { + const path = await takePendingShowcase(); + if (path === null) return; + const captures = await listSavedCaptures(); + setShowcaseCapture(findSavedCapture(captures, path)); + setIsShowcaseStylePending(true); + setActiveTab("showcase"); + }; + const report = (error: unknown): void => { + console.error("SH-SHOWCASE-PENDING-001", error); + }; + void openPending().catch(report); + const unlisten = listenForShowcaseRequest(() => { + void openPending().catch(report); + }); + return (): void => { + void unlisten.then((stop) => { + stop(); + }); + }; + }, []); + useEffect(() => { if (!isTauri()) return; void updateGlobalShortcuts(settings.shortcuts).catch((error: unknown) => { @@ -139,11 +171,16 @@ export function DashboardPanel(): React.JSX.Element { { setShowcaseCapture(capture ?? null); + setIsShowcaseStylePending(true); setActiveTab("showcase"); }} /> ) : activeTab === "showcase" ? ( - + ) : activeTab === "settings" ? ( ) : ( diff --git a/apps/desktop/src/components/dashboard/ShowcaseView.test.tsx b/apps/desktop/src/components/dashboard/ShowcaseView.test.tsx index 18238e4..816cf8d 100644 --- a/apps/desktop/src/components/dashboard/ShowcaseView.test.tsx +++ b/apps/desktop/src/components/dashboard/ShowcaseView.test.tsx @@ -218,4 +218,51 @@ describe("ShowcaseView", () => { fireEvent.click(screen.getByRole("button", { name: "Delete the Launch shots style" })); expect(screen.queryByRole("button", { name: "Apply the Launch shots style" })).toBeNull(); }); + + it("applies the starred style to captures sent to Showcase, and only to those", () => { + render(); + fireEvent.click(screen.getByRole("tab", { name: "Show Text controls" })); + fireEvent.click(screen.getByRole("switch", { name: "Add title" })); + fireEvent.click(screen.getByRole("button", { name: "Saved styles" })); + fireEvent.change(screen.getByRole("textbox", { name: "Style name" }), { target: { value: "Launch shots" } }); + fireEvent.click(screen.getByRole("button", { name: "Save the current composition as a style" })); + + const star = screen.getByRole("button", { name: "Apply Launch shots to captures sent to Showcase" }); + expect(star).toHaveAttribute("aria-pressed", "false"); + fireEvent.click(star); + expect(star).toHaveAttribute("aria-pressed", "true"); + expect(window.localStorage.getItem("capkit.showcase.defaultStyle")).toMatch(/^Launch shots-/); + cleanup(); + + // Without the stored work in progress, only the default style can turn the title on. + window.localStorage.removeItem("capkit.showcase.preset"); + render(); + fireEvent.click(screen.getByRole("tab", { name: "Show Text controls" })); + expect(screen.getByRole("switch", { name: "Add title" })).not.toBeChecked(); + cleanup(); + + // Revisiting the tab with the same capture must not re-apply it over edits. + render(); + fireEvent.click(screen.getByRole("tab", { name: "Show Text controls" })); + expect(screen.getByRole("switch", { name: "Add title" })).not.toBeChecked(); + cleanup(); + + const onApplied = vi.fn(); + render(); + fireEvent.click(screen.getByRole("tab", { name: "Show Text controls" })); + expect(screen.getByRole("switch", { name: "Add title" })).toBeChecked(); + expect(screen.getByText("Launch shots applied")).toBeVisible(); + expect(onApplied).toHaveBeenCalled(); + }); + + it("clears the default when its style is deleted", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Saved styles" })); + fireEvent.change(screen.getByRole("textbox", { name: "Style name" }), { target: { value: "Launch shots" } }); + fireEvent.click(screen.getByRole("button", { name: "Save the current composition as a style" })); + fireEvent.click(screen.getByRole("button", { name: "Apply Launch shots to captures sent to Showcase" })); + + fireEvent.click(screen.getByRole("button", { name: "Delete the Launch shots style" })); + expect(window.localStorage.getItem("capkit.showcase.defaultStyle")).toBeNull(); + }); }); diff --git a/apps/desktop/src/components/dashboard/ShowcaseView.tsx b/apps/desktop/src/components/dashboard/ShowcaseView.tsx index bfea015..93a3f08 100644 --- a/apps/desktop/src/components/dashboard/ShowcaseView.tsx +++ b/apps/desktop/src/components/dashboard/ShowcaseView.tsx @@ -25,6 +25,7 @@ import { mergeMediaFolders, mergeMediaItems, mergeSavedStyles, + readDefaultStyle, normalizeCrop, orientedSize, outputSize, @@ -34,6 +35,7 @@ import { showcaseLibraryStorageKey, showcasePresetSchema, showcasePresetStorageKey, + showcaseDefaultStyleStorageKey, showcaseStylesStorageKey, spotlightGradient, stageAspectRatio, @@ -76,6 +78,10 @@ type Composition = { type ShowcaseViewProps = { initialCapture?: SavedCapture | null; + /** True for the first mount after a capture is handed over, so the default + * style is applied once and not again when the tab is revisited. */ + applyDefaultStyle?: boolean; + onDefaultStyleApplied?: () => void; }; const demoNaturalSize: Size = { width: 1280, height: 800 }; @@ -101,7 +107,11 @@ const selectClass = * happens *around* it, and the canvas owns framing and output. The whole * composition is a single undoable snapshot, so nothing here is destructive. */ -export function ShowcaseView({ initialCapture = null }: ShowcaseViewProps): React.JSX.Element { +export function ShowcaseView({ + initialCapture = null, + applyDefaultStyle = false, + onDefaultStyleApplied, +}: ShowcaseViewProps): React.JSX.Element { const composition = useUndoable(defaultComposition); const { image, scene, frame, text } = composition.value; const { update, replace, undo, redo } = composition; @@ -113,6 +123,7 @@ export function ShowcaseView({ initialCapture = null }: ShowcaseViewProps): Reac const [libraryImages, setLibraryImages] = useState([]); const [folders, setFolders] = useState([]); const [styles, setStyles] = useState([]); + const [defaultStyleId, setDefaultStyleId] = useState(null); const [styleName, setStyleName] = useState(""); const [stylesOpen, setStylesOpen] = useState(false); const [search, setSearch] = useState(""); @@ -215,11 +226,24 @@ export function ShowcaseView({ initialCapture = null }: ShowcaseViewProps): Reac if (raw === null) return; try { setStyles(savedStyleLibrarySchema.parse(JSON.parse(raw) as unknown)); + setDefaultStyleId(readDefaultStyle(window.localStorage)?.id ?? null); } catch { // An unreadable style library is dropped rather than blocking the studio. } }, []); + // Declared after the restore effects so, on the first mount, the default + // style wins over the stored work in progress instead of being overwritten. + useEffect(() => { + if (initialCapture === null || !applyDefaultStyle) return; + onDefaultStyleApplied?.(); + const style = readDefaultStyle(window.localStorage); + if (style === null) return; + replace({ image: style.preset.image, scene: style.preset.scene, frame: style.preset.frame, text: style.preset.text }); + autoStyledRef.current = "*"; + setStatus(`${style.name} applied`); + }, [applyDefaultStyle, initialCapture, onDefaultStyleApplied, replace]); + useEffect(() => { if (!isTauri()) return; const raw = window.localStorage.getItem(showcaseLibraryStorageKey); @@ -549,6 +573,14 @@ export function ShowcaseView({ initialCapture = null }: ShowcaseViewProps): Reac setStatus(`Saved “${name}”`); } + function changeDefaultStyle(id: string | null): void { + setDefaultStyleId(id); + if (id === null) window.localStorage.removeItem(showcaseDefaultStyleStorageKey); + else window.localStorage.setItem(showcaseDefaultStyleStorageKey, id); + const name = styles.find((style) => style.id === id)?.name; + setStatus(name === undefined ? "No default style" : `${name} will style captures sent to Showcase`); + } + function applyStyle(style: SavedStyle): void { replace({ image: style.preset.image, scene: style.preset.scene, frame: style.preset.frame, text: style.preset.text }); autoStyledRef.current = "*"; @@ -876,7 +908,12 @@ export function ShowcaseView({ initialCapture = null }: ShowcaseViewProps): Reac onAddImage={() => void runImport("background")} onApplyLook={applyLook} onApplyStyle={applyStyle} - onDeleteStyle={(id) => persistStyles(styles.filter((style) => style.id !== id))} + defaultStyleId={defaultStyleId} + onDefaultStyleChange={changeDefaultStyle} + onDeleteStyle={(id) => { + persistStyles(styles.filter((style) => style.id !== id)); + if (id === defaultStyleId) changeDefaultStyle(null); + }} onPaddingChange={updatePadding} onPatchFrame={patchFrame} onPatchImage={patchImage} diff --git a/apps/desktop/src/components/dashboard/showcase/BackgroundPanel.tsx b/apps/desktop/src/components/dashboard/showcase/BackgroundPanel.tsx index 5183bf6..2e914f3 100644 --- a/apps/desktop/src/components/dashboard/showcase/BackgroundPanel.tsx +++ b/apps/desktop/src/components/dashboard/showcase/BackgroundPanel.tsx @@ -1,4 +1,4 @@ -import { Computer, Copy, Delete, Download, FolderAdd, Frame, Image, ImageAdd, Layers, MagicWand, Palette, Redo, RotateCounterClockwise, Save, Smartphone, Sparkles, Tablet, Text, Tick, Undo } from "../../icons"; +import { Computer, Copy, Delete, Download, FolderAdd, Frame, Image, ImageAdd, Layers, MagicWand, Palette, Redo, RotateCounterClockwise, Save, Smartphone, Sparkles, Star, Tablet, Text, Tick, Undo } from "../../icons"; import { backgroundPresets, defaultEffectSettings, @@ -51,6 +51,8 @@ export type BackgroundPanelProps = { libraryImages: readonly MediaItem[]; folders: readonly MediaFolder[]; styles: readonly SavedStyle[]; + /** The style applied to captures sent to Showcase, or null. */ + defaultStyleId: string | null; styleName: string; search: string; stylesOpen: boolean; @@ -79,6 +81,7 @@ export type BackgroundPanelProps = { onSaveStyle: () => void; onApplyStyle: (style: SavedStyle) => void; onDeleteStyle: (id: string) => void; + onDefaultStyleChange: (id: string | null) => void; }; /** Everything that happens *around* the image, plus the studio's own actions. */ @@ -138,6 +141,20 @@ export function BackgroundPanel(props: BackgroundPanelProps): React.JSX.Element