π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
fix(capture): freeze the click target rect before the page removes it
Luis Ortiz622594bca9f5
diff --git a/src/core/capture/__tests__/element-meta.test.ts b/src/core/capture/__tests__/element-meta.test.tsnew file mode 100644index 0000000..fd6ce48--- /dev/null+++ b/src/core/capture/__tests__/element-meta.test.ts@@ -0,0 +1,50 @@+// @vitest-environment jsdom+import { describe, expect, it } from 'vitest';+import { extractElementMeta } from '@/core/capture/dom/element-meta';++function withRect(el: HTMLElement, rect: { x: number; y: number; width: number; height: number }) {+ el.getBoundingClientRect = () => ({ ...rect, top: rect.y, left: rect.x, right: 0, bottom: 0, toJSON: () => ({}) });+ return el;+}++function menuItem(): HTMLElement {+ const el = document.createElement('button');+ el.textContent = 'Copy link';+ document.body.appendChild(el);+ return el;+}++describe('extractElementMeta', () => {+ it('measures the element when nothing was frozen at event time', () => {+ const el = withRect(menuItem(), { x: 12, y: 34, width: 100, height: 20 });+ expect(extractElementMeta(el).rect).toEqual({ x: 12, y: 34, width: 100, height: 20 });+ });++ it('prefers the live measurement while the element is still laid out', () => {+ const el = withRect(menuItem(), { x: 12, y: 34, width: 100, height: 20 });+ const stale = { x: 999, y: 999, width: 5, height: 5 };+ expect(extractElementMeta(el, stale).rect).toEqual({ x: 12, y: 34, width: 100, height: 20 });+ });++ it('falls back to the click-time rect once the element leaves the layout', () => {+ const el = withRect(menuItem(), { x: 12, y: 34, width: 100, height: 20 });+ const atClick = { x: 12, y: 34, width: 100, height: 20 };+ withRect(el, { x: 0, y: 0, width: 0, height: 0 });+ el.remove();+ expect(extractElementMeta(el, atClick).rect).toEqual(atClick);+ });++ it('still reports a degenerate rect when there is nothing better to offer', () => {+ const el = withRect(menuItem(), { x: 0, y: 0, width: 0, height: 0 });+ expect(extractElementMeta(el).rect).toEqual({ x: 0, y: 0, width: 0, height: 0 });+ });++ it('keeps reading the label off a detached element, which needs no layout', () => {+ const el = withRect(menuItem(), { x: 0, y: 0, width: 0, height: 0 });+ el.setAttribute('aria-label', 'Copy link');+ el.remove();+ const meta = extractElementMeta(el, { x: 12, y: 34, width: 100, height: 20 });+ expect(meta.ariaLabel).toBe('Copy link');+ expect(meta.rect).toEqual({ x: 12, y: 34, width: 100, height: 20 });+ });+});diff --git a/src/core/capture/dom/element-meta.ts b/src/core/capture/dom/element-meta.tsindex d118bed..5b4ac41 100644--- a/src/core/capture/dom/element-meta.ts+++ b/src/core/capture/dom/element-meta.ts@@ -22,8 +22,21 @@ function getCleanText(el: HTMLElement): string | null {}}-export function extractElementMeta(el: HTMLElement): ElementMeta {- const rect = el.getBoundingClientRect();+export interface FrozenRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export function freezeRect(el: Element): FrozenRect {+ const { x, y, width, height } = el.getBoundingClientRect();+ return { x, y, width, height };+}++export function extractElementMeta(el: HTMLElement, atEvent?: FrozenRect): ElementMeta {+ const live = freezeRect(el);+ const rect = live.width > 0 || live.height > 0 ? live : (atEvent ?? live);let cssSelector: string;try {cssSelector = getCssSelector(el);@@ -42,7 +55,7 @@ export function extractElementMeta(el: HTMLElement): ElementMeta {href: el instanceof HTMLAnchorElement ? el.href : null,inputType: el instanceof HTMLInputElement ? el.type : null,dataTestId: el.getAttribute('data-testid') || el.getAttribute('data-test-id') || el.getAttribute('data-qa') || null,- rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },+ rect,devicePixelRatio: window.devicePixelRatio,};}diff --git a/src/core/capture/events/handlers.ts b/src/core/capture/events/handlers.tsindex 0c94021..9336f1c 100644--- a/src/core/capture/events/handlers.ts+++ b/src/core/capture/events/handlers.ts@@ -4,7 +4,7 @@ import { localStorage } from '@/lib/browser-api';import { HoverRing } from '@/lib/hover-ring';import { sendMessage } from '@/lib/messaging';import { extractDOMContext } from '../dom/context';-import { extractElementMeta } from '../dom/element-meta';+import { extractElementMeta, freezeRect } from '../dom/element-meta';import {findFocusableAncestor,isMimikElement,@@ -93,14 +93,17 @@ class CaptureController {}}- private async captureAction(action: string, target: HTMLElement, point?: { x: number; y: number }) {- const elementMeta = extractElementMeta(target);- await sendMessage('captureStep', {- guideId: this.guideId,- action,- elementMeta: point ? { ...elementMeta, clickPoint: point } : elementMeta,- domContext: extractDOMContext(target, action),- });+ private capture(action: string, target: HTMLElement, point?: { x: number; y: number }) {+ const atEvent = freezeRect(target);+ return async () => {+ const elementMeta = extractElementMeta(target, atEvent);+ await sendMessage('captureStep', {+ guideId: this.guideId,+ action,+ elementMeta: point ? { ...elementMeta, clickPoint: point } : elementMeta,+ domContext: extractDOMContext(target, action),+ });+ };}private enqueue(task: () => Promise<unknown>) {@@ -154,9 +157,10 @@ class CaptureController {lastClickTime = now;if (isTextField(target)) {+ const atEvent = freezeRect(target);this.enqueue(async () => {if (this.input.active && this.input.target !== target) await this.input.finalize();- if (!this.input.active) await this.input.start(target);+ if (!this.input.active) await this.input.start(target, atEvent);});return;}@@ -164,7 +168,7 @@ class CaptureController {if (isNavigatingClick(target)) {me.preventDefault();me.stopImmediatePropagation();- this.enqueue(() => this.captureAction('click', target, { x: me.clientX, y: me.clientY }));+ this.enqueue(this.capture('click', target, { x: me.clientX, y: me.clientY }));const anchor = target.closest('a[href]') as HTMLAnchorElement;if (anchor) {const href = anchor.href;@@ -177,7 +181,7 @@ class CaptureController {return;}- this.enqueue(() => this.captureAction('click', target, { x: me.clientX, y: me.clientY }));+ this.enqueue(this.capture('click', target, { x: me.clientX, y: me.clientY }));}private onAuxClick(e: Event) {@@ -185,9 +189,7 @@ class CaptureController {if (!raw || !(raw instanceof Element)) return;const target = findFocusableAncestor(raw);if (isMimikElement(target)) return;- this.enqueue(() =>- this.captureAction('auxclick', target, { x: (e as MouseEvent).clientX, y: (e as MouseEvent).clientY }),- );+ this.enqueue(this.capture('auxclick', target, { x: (e as MouseEvent).clientX, y: (e as MouseEvent).clientY }));}private onKeydown(e: Event) {@@ -201,7 +203,7 @@ class CaptureController {}if (isTextField(target)) return;- this.enqueue(() => this.captureAction(`keydown:${ke.key}`, target));+ this.enqueue(this.capture(`keydown:${ke.key}`, target));}private onInput(e: Event) {@@ -218,7 +220,7 @@ class CaptureController {return;if (target instanceof HTMLSelectElement) {- this.enqueue(() => this.captureAction('input', target));+ this.enqueue(this.capture('input', target));return;}@@ -248,7 +250,7 @@ class CaptureController {? ((e as ClipboardEvent).target as HTMLElement): document.activeElement;if (!target || !(target instanceof HTMLElement) || isMimikElement(target)) return;- this.enqueue(() => this.captureAction(e.type, target));+ this.enqueue(this.capture(e.type, target));}private onPointerDown(e: Event) {@@ -272,7 +274,7 @@ class CaptureController {if (dx >= DRAG_MIN_PX || dy >= DRAG_MIN_PX) {const target = findFocusableAncestor(this.dragStartElement);- if (!isMimikElement(target)) this.enqueue(() => this.captureAction('drag', target));+ if (!isMimikElement(target)) this.enqueue(this.capture('drag', target));}this.dragStartX = this.dragStartY = null;@@ -281,7 +283,7 @@ class CaptureController {private onDragEnd(e: Event) {if (!e.target || !(e.target instanceof Element) || isMimikElement(e.target)) return;- this.enqueue(() => this.captureAction('drag', findFocusableAncestor(e.target as Element)));+ this.enqueue(this.capture('drag', findFocusableAncestor(e.target as Element)));}stop() {diff --git a/src/core/capture/events/input-session.ts b/src/core/capture/events/input-session.tsindex 46bd7ea..54ee14b 100644--- a/src/core/capture/events/input-session.ts+++ b/src/core/capture/events/input-session.ts@@ -1,7 +1,7 @@import { logger } from '@/lib/logger';import { sendMessage } from '@/lib/messaging';import { extractDOMContext } from '../dom/context';-import { extractElementMeta } from '../dom/element-meta';+import { extractElementMeta, type FrozenRect, freezeRect } from '../dom/element-meta';import { getFieldLabel, getFieldValue } from '../dom/element-utils';export class InputSession {@@ -9,6 +9,7 @@ export class InputSession {target: HTMLElement | null = null;private guideId: string;+ private atEvent: FrozenRect | undefined;constructor(guideId: string) {this.guideId = guideId;@@ -18,11 +19,12 @@ export class InputSession {return this.stepId !== null;}- async start(target: HTMLElement) {+ async start(target: HTMLElement, atEvent?: FrozenRect) {+ this.atEvent = atEvent;const res = await sendMessage('captureStep', {guideId: this.guideId,action: 'input',- elementMeta: extractElementMeta(target),+ elementMeta: extractElementMeta(target, atEvent),domContext: extractDOMContext(target, 'input'),});if ('stepId' in res) {@@ -33,6 +35,7 @@ export class InputSession {update(target: HTMLElement) {if (!this.stepId) return;+ this.atEvent = freezeRect(target);const val = getFieldValue(target);const desc = val ? `Type "${val}" in ${getFieldLabel(target)}` : `Clear ${getFieldLabel(target)}`;sendMessage('updateInputStep', { stepId: this.stepId, description: desc, inputValue: val || undefined }).catch(@@ -44,11 +47,13 @@ export class InputSession {if (!this.target || !this.stepId) return;const target = this.target;const stepId = this.stepId;+ const atEvent = this.atEvent;this.stepId = null;this.target = null;+ this.atEvent = undefined;await sendMessage('finalizeInputStep', {stepId,- elementMeta: extractElementMeta(target),+ elementMeta: extractElementMeta(target, atEvent),domContext: extractDOMContext(target, 'input'),});}diff --git a/src/core/screenshot/__tests__/geometry.test.ts b/src/core/screenshot/__tests__/geometry.test.tsindex d7778e6..7658baa 100644--- a/src/core/screenshot/__tests__/geometry.test.ts+++ b/src/core/screenshot/__tests__/geometry.test.ts@@ -7,6 +7,7 @@ import {moveAnnotation,panBy,resizeAnnotation,+ resolveTarget,resolveViewport,zoomBy,} from '@/core/screenshot/geometry';@@ -59,6 +60,38 @@ describe('resolveViewport', () => {expect(v.width).toBeLessThanOrEqual(1000);expect(v.height).toBeLessThanOrEqual(800);});++ it('shows the whole page rather than the top-left corner when the element vanished before measuring', () => {+ const s = makeScreenshot({ bounds: { x: 0, y: 0, width: 0, height: 0 }, pixelRatio: 2 });+ expect(resolveViewport(s)).toEqual({ x: 0, y: 0, width: 1000, height: 800 });+ });+});++describe('resolveTarget', () => {+ it('derives the target from bounds at the captured pixel ratio', () => {+ const s = makeScreenshot({ bounds: { x: 50, y: 60, width: 100, height: 20 }, pixelRatio: 2 });+ expect(resolveTarget(s)).toMatchObject({ x: 100, y: 120, width: 200, height: 40 });+ });++ it('prefers an explicit target from the editor', () => {+ const s = makeScreenshot({+ bounds: { x: 50, y: 60, width: 100, height: 20 },+ edits: { target: { x: 1, y: 2, width: 3, height: 4, border: 'dashed', color: '#fff' } },+ });+ expect(resolveTarget(s)).toMatchObject({ x: 1, y: 2, width: 3, height: 4 });+ });++ it('respects a target the user deliberately removed', () => {+ expect(+ resolveTarget(makeScreenshot({ bounds: { x: 5, y: 5, width: 9, height: 9 }, edits: { target: null } })),+ ).toBe(null);+ });++ it('reports no target rather than one pinned to the origin when the element vanished before measuring', () => {+ const zeroed = { x: 0, y: 0, width: 0, height: 0, border: 'dashed' as const, color: '#4F46E5' };+ expect(resolveTarget(makeScreenshot({ edits: { target: zeroed } }))).toBe(null);+ expect(resolveTarget(makeScreenshot({ bounds: { x: 0, y: 0, width: 0, height: 0 }, pixelRatio: 2 }))).toBe(null);+ });});const IMG = { width: 1000, height: 800 };diff --git a/src/core/screenshot/geometry.ts b/src/core/screenshot/geometry.tsindex ee2b517..3173d99 100644--- a/src/core/screenshot/geometry.ts+++ b/src/core/screenshot/geometry.ts@@ -8,6 +8,14 @@ export function clamp(val: number, min: number, max: number): number {return Math.max(min, Math.min(max, val));}+function hasArea<T extends { width: number; height: number }>(rect: T | null | undefined): rect is T {+ return !!rect && rect.width > 0 && rect.height > 0;+}++export function resolveFrameViewport(screenshot: Screenshot): ScreenshotBounds {+ return screenshot.edits?.viewport ?? { x: 0, y: 0, width: screenshot.width, height: screenshot.height };+}+export function resolveViewport(screenshot: Screenshot): ScreenshotBounds {const imgW = screenshot.width;const imgH = screenshot.height;@@ -15,7 +23,7 @@ export function resolveViewport(screenshot: Screenshot): ScreenshotBounds {if (explicit) return explicit;const bounds = screenshot.bounds;- if (!bounds) return { x: 0, y: 0, width: imgW, height: imgH };+ if (!hasArea(bounds)) return { x: 0, y: 0, width: imgW, height: imgH };const dpr = screenshot.pixelRatio || 1;const bx = bounds.x * dpr;@@ -198,10 +206,10 @@ export type TargetSource = Pick<Screenshot, 'edits' | 'bounds' | 'pixelRatio'>;export function resolveTarget(screenshot: TargetSource): ClickTarget | null {const explicit = screenshot.edits?.target;- if (explicit !== undefined) return explicit;+ if (explicit !== undefined) return hasArea(explicit) ? explicit : null;const bounds = screenshot.bounds;- if (!bounds) return null;+ if (!hasArea(bounds)) return null;const dpr = screenshot.pixelRatio || 1;return {