Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(desktop): record typing as one step read from the accessibility tree

Luis Ortizae24810192cb
diff --git a/AGENTS.md b/AGENTS.md
index 421c7fc..42e77c0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -207,8 +207,9 @@ A fourth source, `screen`, knows only where the click landed: it fills `rect` wi
the click point, `clickPoint`, `devicePixelRatio`, `app` and `window`, and leaves every identity field
null.
-`tag`, `cssSelector`, `href`, `inputType` and `dataTestId` are DOM-only and absent elsewhere.
-`app` and `window` are the reverse β€” desktop only.
+`tag`, `cssSelector`, `href` and `dataTestId` are DOM-only and absent elsewhere. `app` and `window`
+are the reverse β€” desktop only. `inputType` is mostly DOM-only, but a desktop typing step sets it to
+`password` when the field says so, because that is the one input type a screen capture can learn.
Consumers must not branch on `source`. Read the shared fields first and treat the DOM-only ones as
refinements: `buildFallbackDescription` reaches the same wording through `role === 'checkbox'` that
@@ -306,6 +307,11 @@ the way in and the rectangle with `screenToDipRect` on the way out, the same con
`UIA_CheckBoxControlTypeId`. An unmapped control type yields a null role rather than an invented
name.
+`focusedElement()` is the second call, and it is what makes typing capture possible without reading
+keystrokes. It reports `isPassword` alongside the usual fields, and the value is discarded at the
+addon boundary when that flag is set, so a password never reaches our data even though UIAutomation
+already withholds it.
+
## Desktop Storage
The desktop app reuses `@mimik/core/guides` for everything except the screenshot bytes β€” Electron's
@@ -506,8 +512,32 @@ a 28 px box around the click when there is no element, when the rectangle covers
frame, or when it does not fit inside the frame. Without those two guards an unsupported application
returns its top-level window and the target outlines the entire screenshot.
-`DesktopRecorder` takes the display grab as a constructor argument defaulting to `captureDisplay`, so
-`check:pipeline` feeds it a generated frame. The crop arithmetic, the sink, the step write and all
+Typing is one step, and the text in it is read rather than reconstructed. The keyboard hook decides
+only *when* a typing session starts and ends; what was typed comes from the focused element's value
+in the accessibility tree at the moment the session closes. That is the whole reason there is no
+keycode table, no layout handling, no dead-key state and no IME composition tracking in this
+codebase β€” the machinery those need exists to answer a question we do not ask.
+
+A session opens on any key that is not a modifier, not `Enter`, `Tab` or `Escape`, and not held with
+`Ctrl`, `Alt` or `Meta`. It closes on any of those, on a click, on pause, on stop, or after 1200 ms
+with no keys. `Shift` plus a letter still counts as typing, which is why modifiers are tested
+individually rather than as a set.
+
+Closing a session does not guarantee a step. The focused element is read first, and nothing is
+written unless it is a text field with something in it β€” so pressing `n` in a file manager, or
+typing into a surface that exposes no value, costs nothing. The exception is a password field, which
+by design reports no value at all: there the step is written anyway, with no `inputValue`, and
+`buildFallbackDescription` words it as "Type password" rather than naming the field's contents.
+
+Rich text is the gap. `ValuePattern` is what the value is read through, and a word processor or a
+browser's `contenteditable` exposes `TextPattern` instead, so typing there closes a session and
+writes nothing. Clicks in those applications still capture normally.
+
+`DesktopRecorder` takes its region, its overlay hiding and its sink positionally, and everything
+else β€” the display grab, the settings, the overlay hit test, the element lookup and the focused
+field β€” through one optional hooks object, so `check:pipeline` replaces exactly the ones it needs
+and names them at the call site. The grab defaults to `captureDisplay`, and `check:pipeline` feeds
+it a generated frame instead. The crop arithmetic, the sink, the step write and all
four document exporters then run without a working screen-capture path, which matters because a real
grab depends on the machine it runs on. Whether a real grab works is `check:capture`'s question, not
this one's.
diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.ts
index f23aaff..0e0229c 100644
--- a/apps/desktop/scripts/check-pipeline.ts
+++ b/apps/desktop/scripts/check-pipeline.ts
@@ -3,11 +3,13 @@ import { join } from 'node:path';
import { app, BrowserWindow, nativeImage, protocol, screen } from 'electron';
import { ask } from '../src/main/ask';
import type { ScreenElement } from '../src/main/capture/element';
+import type { KeyAction } from '../src/main/capture/input-hook';
import {
type CaptureRequest,
DesktopRecorder,
frameFor,
isRepeatClick,
+ isTypingKey,
shouldCapture,
targetRect,
} from '../src/main/capture/recorder';
@@ -69,8 +71,7 @@ app.whenReady().then(async () => {
() => region,
(fn) => fn(),
(request) => ask(win.webContents, 'mimik:capture:step', { ...request, guideId: activeGuide }),
- syntheticDisplay,
- () => settings,
+ { grab: syntheticDisplay, settings: () => settings },
);
activeGuide = await ask<string>(win.webContents, 'mimik:capture:startGuide');
@@ -142,8 +143,18 @@ app.whenReady().then(async () => {
textContent: null,
ariaLabel: 'Save',
altText: null,
+ password: false,
rect: { x: region.x + 40, y: region.y + 30, width: 120, height: 32 },
};
+ let field: ScreenElement | null = {
+ role: 'textbox',
+ name: 'SearchBox',
+ textContent: 'hello world',
+ ariaLabel: 'Search',
+ altText: null,
+ password: false,
+ rect: { x: region.x + 20, y: region.y + 20, width: 200, height: 24 },
+ };
let seen: CaptureRequest | null = null;
const metaRecorder = new DesktopRecorder(
() => region,
@@ -152,13 +163,16 @@ app.whenReady().then(async () => {
seen = request;
return Promise.resolve(null);
},
- syntheticDisplay,
- () => ({ ...REGION_MODE, showCursor: false }),
- () => false,
- () => Promise.resolve(control),
+ {
+ grab: syntheticDisplay,
+ settings: () => ({ ...REGION_MODE, showCursor: true }),
+ lookup: () => Promise.resolve(control),
+ focused: () => Promise.resolve(field),
+ },
);
await metaRecorder.capture({ x: region.x + 60, y: region.y + 40 });
- const meta = (seen as CaptureRequest | null)?.elementMeta;
+ const clicked = seen as CaptureRequest | null;
+ const meta = clicked?.elementMeta;
results.push({
name: 'accessibility metadata reaches the step',
ok:
@@ -171,6 +185,79 @@ app.whenReady().then(async () => {
detail: `source ${meta?.source ?? 'none'}, role ${meta?.role ?? 'none'}, named ${meta?.ariaLabel ?? 'none'}`,
});
+ seen = null;
+ await metaRecorder.captureTyping();
+ const typed = seen as CaptureRequest | null;
+
+ seen = null;
+ field = { ...control };
+ await metaRecorder.captureTyping();
+ const onAButton = seen as CaptureRequest | null;
+
+ seen = null;
+ field = {
+ role: 'textbox',
+ name: null,
+ textContent: null,
+ ariaLabel: 'Search',
+ altText: null,
+ password: false,
+ rect: null,
+ };
+ await metaRecorder.captureTyping();
+ const empty = seen as CaptureRequest | null;
+
+ seen = null;
+ field = {
+ role: 'textbox',
+ name: null,
+ textContent: null,
+ ariaLabel: 'Password',
+ altText: null,
+ password: true,
+ rect: { x: region.x + 20, y: region.y + 60, width: 200, height: 24 },
+ };
+ await metaRecorder.captureTyping();
+ const secret = seen as CaptureRequest | null;
+
+ results.push({
+ name: 'typing lands as one input step',
+ ok:
+ typed?.action === 'input' &&
+ typed.inputValue === 'hello world' &&
+ typed.elementMeta.ariaLabel === 'Search' &&
+ typed.cursor === undefined &&
+ clicked?.cursor !== undefined &&
+ onAButton === null &&
+ empty === null,
+ detail: `wrote ${typed?.action ?? 'nothing'} carrying "${typed?.inputValue ?? ''}"; a button and an empty field wrote nothing`,
+ });
+
+ results.push({
+ name: 'a password is a step but never a value',
+ ok:
+ secret?.action === 'input' &&
+ secret.inputValue === undefined &&
+ secret.elementMeta.inputType === 'password' &&
+ secret.elementMeta.textContent === null,
+ detail: `wrote ${secret?.action ?? 'nothing'} with inputValue ${String(secret?.inputValue)} and no captured text`,
+ });
+
+ const press = (keycode: number, held: Partial<KeyAction> = {}) =>
+ isTypingKey({ kind: 'keydown', keycode, shift: false, alt: false, ctrl: false, meta: false, at: 0, ...held });
+ results.push({
+ name: 'only typing keys open a session',
+ ok:
+ press(30) &&
+ press(30, { shift: true }) &&
+ !press(30, { ctrl: true }) &&
+ !press(28) &&
+ !press(15) &&
+ !press(1) &&
+ !press(42),
+ detail: 'a letter types, shift still types, a shortcut does not, and Enter, Tab, Escape and Shift all close the session',
+ });
+
const page = { x: 0, y: 0, width: 800, height: 600 };
const click = { x: 160, y: 66 };
const boxed = (rect: ScreenElement['rect']) => targetRect({ ...control, rect }, page, click).width;
diff --git a/apps/desktop/src/main/capture/element.ts b/apps/desktop/src/main/capture/element.ts
index 409ecc9..e9479a8 100644
--- a/apps/desktop/src/main/capture/element.ts
+++ b/apps/desktop/src/main/capture/element.ts
@@ -10,11 +10,15 @@ export interface ScreenElement {
textContent: string | null;
ariaLabel: string | null;
altText: string | null;
+ password: boolean;
rect: { x: number; y: number; width: number; height: number } | null;
}
+const TEXT_ROLES = new Set(['textbox', 'combobox']);
+
type Addon = {
elementAtPoint(x: number, y: number): Promise<UiElement | null>;
+ focusedElement(): Promise<UiElement | null>;
isSupported(): boolean;
};
@@ -52,24 +56,38 @@ function toPhysical(point: { x: number; y: number }): { x: number; y: number } {
}
}
-export async function elementAt(point: { x: number; y: number }): Promise<ScreenElement | null> {
- const native = await load();
- if (!native) return null;
-
- const at = toPhysical(point);
- const found = await within(native.elementAtPoint(Math.round(at.x), Math.round(at.y)), LOOKUP_TIMEOUT_MS);
- if (!found) return null;
-
+function describe(found: UiElement): ScreenElement {
return {
role: found.role ?? null,
name: found.automationId ?? null,
- textContent: found.value ?? null,
+ textContent: found.isPassword ? null : (found.value ?? null),
ariaLabel: found.name ?? null,
altText: found.helpText ?? null,
+ password: found.isPassword,
rect: toDip(found.rect ?? null),
};
}
+export function isTextField(element: ScreenElement | null): boolean {
+ return element?.role !== undefined && element?.role !== null && TEXT_ROLES.has(element.role);
+}
+
+export async function elementAt(point: { x: number; y: number }): Promise<ScreenElement | null> {
+ const native = await load();
+ if (!native) return null;
+
+ const at = toPhysical(point);
+ const found = await within(native.elementAtPoint(Math.round(at.x), Math.round(at.y)), LOOKUP_TIMEOUT_MS);
+ return found ? describe(found) : null;
+}
+
+export async function focusedField(): Promise<ScreenElement | null> {
+ const native = await load();
+ if (!native) return null;
+ const found = await within(native.focusedElement(), LOOKUP_TIMEOUT_MS);
+ return found ? describe(found) : null;
+}
+
export async function elementLookupAvailable(): Promise<boolean> {
const native = await load();
return native?.isSupported() ?? false;
diff --git a/apps/desktop/src/main/capture/recorder.ts b/apps/desktop/src/main/capture/recorder.ts
index 48cd0a8..5df08f7 100644
--- a/apps/desktop/src/main/capture/recorder.ts
+++ b/apps/desktop/src/main/capture/recorder.ts
@@ -2,9 +2,10 @@ import { randomUUID } from 'node:crypto';
import type { CaptureImage } from '@mimik/core/capture/sink';
import type { ElementMeta } from '@mimik/core/guides/types';
import { screen } from 'electron';
-import { elementAt, type ScreenElement } from './element';
+import { cursorPoint } from './displays';
+import { elementAt, focusedField, isTextField, type ScreenElement } from './element';
import { focusedWindow } from './focused-window';
-import { type InputAction, InputHook } from './input-hook';
+import { type InputAction, InputHook, type KeyAction, type PointerAction } from './input-hook';
import type { Region } from './region';
import { type Capture, captureArea, type Rect } from './screenshot';
import { writeScreenshot } from './screenshot-store';
@@ -13,10 +14,44 @@ import { type CaptureMode, type CaptureSettings, DEFAULT_CAPTURE_SETTINGS } from
const TARGET_SIZE = 28;
const SETTLE_MS = 60;
const REPEAT_CLICK_MS = 500;
+const TYPING_IDLE_MS = 1200;
-export interface CursorMark {
+const KEY = {
+ escape: 1,
+ tab: 15,
+ enter: 28,
+ ctrl: 29,
+ shift: 42,
+ shiftRight: 54,
+ alt: 56,
+ capsLock: 58,
+ numpadEnter: 3612,
+ ctrlRight: 3613,
+ altRight: 3640,
+ meta: 3675,
+ metaRight: 3676,
+} as const;
+
+const MODIFIER_KEYS: ReadonlySet<number> = new Set([
+ KEY.ctrl,
+ KEY.ctrlRight,
+ KEY.shift,
+ KEY.shiftRight,
+ KEY.alt,
+ KEY.altRight,
+ KEY.meta,
+ KEY.metaRight,
+ KEY.capsLock,
+]);
+
+const COMMIT_KEYS: ReadonlySet<number> = new Set([KEY.enter, KEY.numpadEnter, KEY.tab, KEY.escape]);
+
+export interface Point {
x: number;
y: number;
+}
+
+export interface CursorMark extends Point {
style: CaptureSettings['cursorStyle'];
scale: number;
}
@@ -25,16 +60,25 @@ export interface CaptureRequest {
action: string;
elementMeta: ElementMeta;
image: CaptureImage;
+ inputValue?: string;
cursor?: CursorMark;
}
+export interface RecorderHooks {
+ grab?: (area: Rect) => Promise<Capture>;
+ settings?: () => CaptureSettings;
+ ignores?: (point: Point) => boolean;
+ lookup?: (point: Point) => Promise<ScreenElement | null>;
+ focused?: () => Promise<ScreenElement | null>;
+}
+
export type RecorderStart = { ok: true } | { ok: false; reason: string; detail: string };
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
-function inside(region: Region, point: { x: number; y: number }): boolean {
+function inside(region: Region, point: Point): boolean {
return (
point.x >= region.x &&
point.y >= region.y &&
@@ -47,28 +91,25 @@ export function isRepeatClick(previousAt: number | null, at: number): boolean {
return previousAt !== null && at - previousAt <= REPEAT_CLICK_MS;
}
-export function shouldCapture(settings: CaptureSettings, region: Region, point: { x: number; y: number }): boolean {
+export function shouldCapture(settings: CaptureSettings, region: Region, point: Point): boolean {
if (settings.captureMode !== 'region') return true;
return inside(region, point) || settings.captureOutsideClicks;
}
-export function frameFor(
- mode: CaptureMode,
- point: { x: number; y: number },
- region: Region,
- window: Rect | null,
-): Rect {
+export function frameFor(mode: CaptureMode, point: Point, region: Region, window: Rect | null): Rect {
const display = screen.getDisplayNearestPoint(point).bounds;
if (mode === 'screen') return display;
if (mode === 'window') return window && inside(window, point) ? window : display;
return inside(region, point) ? region : display;
}
-export function targetRect(
- element: ScreenElement | null,
- framed: Rect,
- point: { x: number; y: number },
-): ElementMeta['rect'] {
+export function isTypingKey(action: KeyAction): boolean {
+ if (MODIFIER_KEYS.has(action.keycode)) return false;
+ if (action.ctrl || action.alt || action.meta) return false;
+ return !COMMIT_KEYS.has(action.keycode);
+}
+
+export function targetRect(element: ScreenElement | null, framed: Rect, point: Point): ElementMeta['rect'] {
const local = { x: point.x - framed.x, y: point.y - framed.y };
const box = {
x: local.x - TARGET_SIZE / 2,
@@ -85,22 +126,38 @@ export function targetRect(
return inner;
}
+export function centreOf(element: ScreenElement | null): Point | null {
+ const rect = element?.rect;
+ if (!rect) return null;
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
+}
+
export class DesktopRecorder {
private hook = new InputHook();
private queue: Promise<unknown> = Promise.resolve();
private paused = false;
private running = false;
private lastClickAt: number | null = null;
+ private typing = false;
+ private idle: NodeJS.Timeout | null = null;
+ private readonly grab: (area: Rect) => Promise<Capture>;
+ private readonly settings: () => CaptureSettings;
+ private readonly ignores: (point: Point) => boolean;
+ private readonly lookup: (point: Point) => Promise<ScreenElement | null>;
+ private readonly focused: () => Promise<ScreenElement | null>;
constructor(
private readonly region: () => Region,
private readonly withHidden: <T>(fn: () => Promise<T>) => Promise<T>,
private readonly send: (request: CaptureRequest) => Promise<unknown>,
- private readonly grab: (area: Rect) => Promise<Capture> = captureArea,
- private readonly settings: () => CaptureSettings = () => DEFAULT_CAPTURE_SETTINGS,
- private readonly ignores: (point: { x: number; y: number }) => boolean = () => false,
- private readonly lookup: (point: { x: number; y: number }) => Promise<ScreenElement | null> = elementAt,
- ) {}
+ hooks: RecorderHooks = {},
+ ) {
+ this.grab = hooks.grab ?? captureArea;
+ this.settings = hooks.settings ?? (() => DEFAULT_CAPTURE_SETTINGS);
+ this.ignores = hooks.ignores ?? (() => false);
+ this.lookup = hooks.lookup ?? elementAt;
+ this.focused = hooks.focused ?? focusedField;
+ }
async start(): Promise<RecorderStart> {
if (this.running) return { ok: true };
@@ -113,6 +170,7 @@ export class DesktopRecorder {
}
pause(): void {
+ this.commitTyping();
this.paused = true;
}
@@ -121,6 +179,7 @@ export class DesktopRecorder {
}
stop(): void {
+ this.commitTyping();
this.hook.stop();
this.running = false;
this.paused = false;
@@ -131,7 +190,12 @@ export class DesktopRecorder {
}
private onAction(action: InputAction): void {
- if (action.kind !== 'click' || !this.isRecording) return;
+ if (!this.isRecording) return;
+ if (action.kind === 'click') this.onClick(action);
+ else this.onKey(action);
+ }
+
+ private onClick(action: PointerAction): void {
const point = { x: action.x, y: action.y };
if (this.ignores(point)) return;
if (!shouldCapture(this.settings(), this.region(), point)) return;
@@ -139,20 +203,57 @@ export class DesktopRecorder {
const repeat = isRepeatClick(this.lastClickAt, at);
this.lastClickAt = at;
if (repeat) return;
- this.enqueue(point);
+ this.commitTyping();
+ this.enqueue(() => this.capture(point));
+ }
+
+ private onKey(action: KeyAction): void {
+ if (MODIFIER_KEYS.has(action.keycode)) return;
+ if (!isTypingKey(action)) {
+ this.commitTyping();
+ return;
+ }
+ this.typing = true;
+ if (this.idle) clearTimeout(this.idle);
+ this.idle = setTimeout(() => this.commitTyping(), TYPING_IDLE_MS);
+ this.idle.unref?.();
+ }
+
+ private commitTyping(): void {
+ if (this.idle) {
+ clearTimeout(this.idle);
+ this.idle = null;
+ }
+ if (!this.typing) return;
+ this.typing = false;
+ this.enqueue(() => this.captureTyping());
+ }
+
+ private enqueue(job: () => Promise<void>): void {
+ this.queue = this.queue.then(job).catch((error) => {
+ process.stderr.write(`mimik: capture failed: ${error instanceof Error ? error.message : String(error)}\n`);
+ });
+ }
+
+ async capture(point: Point): Promise<void> {
+ await this.write('click', point, this.lookup(point));
}
- private enqueue(point: { x: number; y: number }): void {
- this.queue = this.queue
- .then(() => this.capture(point))
- .catch((error) => {
- process.stderr.write(`mimik: capture failed: ${error instanceof Error ? error.message : String(error)}\n`);
- });
+ async captureTyping(): Promise<void> {
+ const field = await this.focused();
+ if (!isTextField(field) || !field) return;
+ if (!field.password && !field.textContent) return;
+ const typed = field.password ? undefined : (field.textContent ?? undefined);
+ await this.write('input', centreOf(field) ?? cursorPoint(), Promise.resolve(field), typed);
}
- async capture(point: { x: number; y: number }): Promise<void> {
+ private async write(
+ action: string,
+ point: Point,
+ element: Promise<ScreenElement | null>,
+ inputValue?: string,
+ ): Promise<void> {
const settings = this.settings();
- const element = this.lookup(point);
const region = this.region();
const taken = await this.withHidden(async () => {
@@ -169,7 +270,7 @@ export class DesktopRecorder {
const target = await element;
await this.send({
- action: 'click',
+ action,
elementMeta: {
source: target ? 'uia' : 'screen',
textContent: target?.textContent ?? null,
@@ -179,6 +280,7 @@ export class DesktopRecorder {
name: target?.name ?? null,
role: target?.role ?? null,
rect: targetRect(target, framed, point),
+ ...(target?.password ? { inputType: 'password' } : {}),
devicePixelRatio: scale,
clickPoint: local,
...(found.ok ? { app: found.window.app, window: { title: found.window.title } } : {}),
@@ -189,7 +291,10 @@ export class DesktopRecorder {
width: shot.width,
height: shot.height,
},
- ...(settings.showCursor ? { cursor: { x: local.x, y: local.y, style: settings.cursorStyle, scale } } : {}),
+ ...(inputValue === undefined ? {} : { inputValue }),
+ ...(settings.showCursor && action === 'click'
+ ? { cursor: { x: local.x, y: local.y, style: settings.cursorStyle, scale } }
+ : {}),
});
}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index e35fa7e..741bb88 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -202,9 +202,10 @@ if (!app.requestSingleInstanceLock()) {
overlay?.setBusy(false);
}
},
- undefined,
- () => captureSettings ?? loadSettings(),
- (point) => overlay?.ignores(point) ?? false,
+ {
+ settings: () => captureSettings ?? loadSettings(),
+ ignores: (point) => overlay?.ignores(point) ?? false,
+ },
);
ipcMain.handle('mimik:capture:settings:get', () => captureSettings ?? loadSettings());
diff --git a/apps/desktop/src/renderer/capture-sink.ts b/apps/desktop/src/renderer/capture-sink.ts
index 0e530aa..2c2806f 100644
--- a/apps/desktop/src/renderer/capture-sink.ts
+++ b/apps/desktop/src/renderer/capture-sink.ts
@@ -21,7 +21,7 @@ import type { StoredScreenshot } from '@mimik/core/guides/types';
import type { CursorMark } from '@mimik/core/screenshot/types';
import { DEFAULT_TARGET_COLOR } from '@mimik/core/screenshot/types';
-export type DesktopCaptureStepData = CaptureStepData & { cursor?: CursorMark };
+export type DesktopCaptureStepData = CaptureStepData & { cursor?: CursorMark; inputValue?: string };
export class DesktopCaptureSink implements CaptureSink {
async startGuide(): Promise<string> {
@@ -79,6 +79,7 @@ export class DesktopCaptureSink implements CaptureSink {
screenshotId,
elementMeta: meta,
descriptionSource: 'heuristic',
+ ...(data.inputValue === undefined ? {} : { inputValue: data.inputValue }),
});
await addStepToGuide(data.guideId, stepId);
diff --git a/packages/capture-native/index.d.ts b/packages/capture-native/index.d.ts
index 90a2eca..5b06506 100644
--- a/packages/capture-native/index.d.ts
+++ b/packages/capture-native/index.d.ts
@@ -18,6 +18,8 @@ export interface ElementRect {
height: number
}
+export declare function focusedElement(): Promise<UiElement | null>
+
export declare function isSupported(): boolean
export interface UiElement {
@@ -26,5 +28,6 @@ export interface UiElement {
automationId?: string
value?: string
helpText?: string
+ isPassword: boolean
rect?: ElementRect
}
diff --git a/packages/capture-native/index.js b/packages/capture-native/index.js
index 1dae1f0..0f8bf0a 100644
--- a/packages/capture-native/index.js
+++ b/packages/capture-native/index.js
@@ -779,4 +779,5 @@ function __napiStampBindingTarget(exportsObject, target) {
module.exports.__napiBindingTarget = __napiStampBindingTarget(nativeBinding, __napiLoadedBindingTarget)
module.exports = nativeBinding
module.exports.elementAtPoint = nativeBinding.elementAtPoint
+module.exports.focusedElement = nativeBinding.focusedElement
module.exports.isSupported = nativeBinding.isSupported
diff --git a/packages/capture-native/src/lib.rs b/packages/capture-native/src/lib.rs
index 7237a30..8143c15 100644
--- a/packages/capture-native/src/lib.rs
+++ b/packages/capture-native/src/lib.rs
@@ -22,26 +22,28 @@ pub struct UiElement {
pub automation_id: Option<String>,
pub value: Option<String>,
pub help_text: Option<String>,
+ pub is_password: bool,
pub rect: Option<ElementRect>,
}
-pub struct ElementAtPoint {
- x: i32,
- y: i32,
+pub struct ElementLookup {
+ at: Option<(i32, i32)>,
}
-impl Task for ElementAtPoint {
+impl Task for ElementLookup {
type Output = Option<UiElement>;
type JsValue = Option<UiElement>;
#[cfg(windows)]
fn compute(&mut self) -> Result<Self::Output> {
- win::element_at_point(self.x, self.y)
+ match self.at {
+ Some((x, y)) => win::element_at_point(x, y),
+ None => win::focused_element(),
+ }
}
#[cfg(not(windows))]
fn compute(&mut self) -> Result<Self::Output> {
- let _ = (self.x, self.y);
Ok(None)
}
@@ -51,8 +53,13 @@ impl Task for ElementAtPoint {
}
#[napi(ts_return_type = "Promise<UiElement | null>")]
-pub fn element_at_point(x: i32, y: i32) -> AsyncTask<ElementAtPoint> {
- AsyncTask::new(ElementAtPoint { x, y })
+pub fn element_at_point(x: i32, y: i32) -> AsyncTask<ElementLookup> {
+ AsyncTask::new(ElementLookup { at: Some((x, y)) })
+}
+
+#[napi(ts_return_type = "Promise<UiElement | null>")]
+pub fn focused_element() -> AsyncTask<ElementLookup> {
+ AsyncTask::new(ElementLookup { at: None })
}
#[napi]
diff --git a/packages/capture-native/src/win.rs b/packages/capture-native/src/win.rs
index 0fc6fe8..acdf9e8 100644
--- a/packages/capture-native/src/win.rs
+++ b/packages/capture-native/src/win.rs
@@ -111,18 +111,30 @@ fn rect_of(element: &IUIAutomationElement) -> Option<ElementRect> {
})
}
+fn describe(found: &IUIAutomationElement) -> UiElement {
+ UiElement {
+ role: role(unsafe { found.CurrentControlType() }.unwrap_or_default()),
+ name: text(unsafe { found.CurrentName() }),
+ automation_id: text(unsafe { found.CurrentAutomationId() }),
+ value: value_of(found),
+ help_text: text(unsafe { found.CurrentHelpText() }),
+ is_password: unsafe { found.CurrentIsPassword() }
+ .map(|flag| flag.as_bool())
+ .unwrap_or(false),
+ rect: rect_of(found),
+ }
+}
+
pub fn element_at_point(x: i32, y: i32) -> Result<Option<UiElement>> {
let found = automation()
.and_then(|uia| unsafe { uia.ElementFromPoint(POINT { x, y }) })
.map_err(|error| napi::Error::from_reason(error.message()))?;
+ Ok(Some(describe(&found)))
+}
- let help = text(unsafe { found.CurrentHelpText() });
- Ok(Some(UiElement {
- role: role(unsafe { found.CurrentControlType() }.unwrap_or_default()),
- name: text(unsafe { found.CurrentName() }),
- automation_id: text(unsafe { found.CurrentAutomationId() }),
- value: value_of(&found),
- help_text: help,
- rect: rect_of(&found),
- }))
+pub fn focused_element() -> Result<Option<UiElement>> {
+ let found = automation()
+ .and_then(|uia| unsafe { uia.GetFocusedElement() })
+ .map_err(|error| napi::Error::from_reason(error.message()))?;
+ Ok(Some(describe(&found)))
}
diff --git a/packages/core/src/capture/step-description.ts b/packages/core/src/capture/step-description.ts
index 98c4a39..d9b2f3e 100644
--- a/packages/core/src/capture/step-description.ts
+++ b/packages/core/src/capture/step-description.ts
@@ -28,6 +28,7 @@ export function buildFallbackDescription(action: string, meta: ElementMeta): str
if (meta.href) return i18n.t('steps.clickLink', [target]);
return i18n.t('steps.click', [target]);
case 'input':
+ if (meta.inputType === 'password') return i18n.t('steps.typeSecret');
if (meta.inputType) return i18n.t('steps.typeIntoField', [meta.inputType, target]);
return i18n.t('steps.typeInto', [target]);
case 'copy':