Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion apps/web/content/docs/grab.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: grab and inspect
meta_title: Grab and inspect elements for a coding agent with knobs
description: Grab any element on the page and copy its html, the components that rendered it and their source files for a coding agent, or inspect its box and css.
order: 5
updated: 2026-11-26
updated: 2026-11-27
---

## grab
Expand Down Expand Up @@ -44,6 +44,36 @@ mount({ grabKey: 'alt+shift+g' });

`grab: false` leaves grab out. `grab(elements)` copies elements from code.

## send each grab

every grab also fires one `knobs:grab` event on `window` as the copy starts,
with what it copies as its `detail`:

```js
window.addEventListener('knobs:grab', (event) => {
console.log(event.detail.content, event.detail.entries, event.detail.note);
});
```

`grabSend` sends each grab somewhere too, so nobody has to paste. a URL gets
a POST of `{ "type": "knobs.grab", "payload": ... }` as json; it has to be
the page's own origin, or http(s) on `localhost`, `127.0.0.1` or a
`.localhost` name. a function gets the payload:

```js
mount({ grabSend: '/api/grab' });
mount({ grabSend: (payload) => socket.send(JSON.stringify(payload)) });
```

with the script tag, set it on the tag:

```html
<script src="//unpkg.com/@vinena/knobs/dist/index.global.js" data-grab-send="/api/grab"></script>
```

the copy still happens. the toast says `Copied · Sent` once it went, and
`Send failed` when it did not.

## coming from react-grab

knobs has the same grab, the same line format and the same clipboard
Expand Down
39 changes: 39 additions & 0 deletions apps/web/content/reference/grab.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,45 @@ reads React's internals through [bippy](https://github.com/aidenybai/bippy),
both by Aiden Bai and MIT, see
[THIRD_PARTY_NOTICES.md](https://github.com/vinenastudio/knobs/blob/main/packages/devknobs/THIRD_PARTY_NOTICES.md).

## send each grab

every grab, from the keys or from `grab()`, fires one `knobs:grab` event on
`window` as the copy starts, before it is known whether the copy worked. its `detail` is
the payload: `content`, `entries` and `note` where there is one. it cannot be
canceled.

```js
window.addEventListener('knobs:grab', (event) => {
console.log(event.detail.content, event.detail.entries, event.detail.note);
});
```

the `grabSend` mount option sends each grab on as well, so nobody has to paste:

- a URL gets a POST with `Content-Type: application/json` and
`credentials: "same-origin"`, its body `{ "type": "knobs.grab", "payload": ... }`.
only the page's own origin, a relative path included, and http(s) on
`localhost`, `127.0.0.1` or a `.localhost` name are taken; any other URL is
ignored with one warning in the console.
- a function is called with the payload, and may return a promise.

```js
mount({ grabSend: '/api/grab' });
mount({ grabSend: (payload) => socket.send(JSON.stringify(payload)) });
```

the script tag build takes it from a `data-grab-send` attribute:

```html
<script src="//unpkg.com/@vinena/knobs/dist/index.global.js" data-grab-send="/api/grab"></script>
```

a send never stops the copy. once it went, the toast says `Copied · Sent`
(`Sent` alone where the copy failed). where it fails, a thrown error, a
rejected promise, a network error or a status that is not 2xx, the toast says
`Send failed`. a page whose own mount defers to the extension hands its
`grabSend` to the extension's copy, as it does its keys.

## migrating from react-grab

knobs covers it: the same grab, the same line format, the same
Expand Down
5 changes: 5 additions & 0 deletions packages/devknobs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# changelog

## Unreleased

- every grab fires a `knobs:grab` event on `window`, with what was copied as its `detail`
- `grabSend` sends each grab on as well: a URL on the page's origin or on localhost gets it as a json POST, a function gets the payload. the script tag takes it as `data-grab-send`. the copy still happens, and the toast says `Sent` or `Send failed`

## 0.7.6

- grab gathers many elements: drag a box around them, or shift and a click. each shows its number
Expand Down
16 changes: 16 additions & 0 deletions packages/devknobs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,22 @@ production. an icon from another origin that does not allow it (CORS) keeps
its own picture. the dev tab icon switch in the panel's settings turns it off,
or on for any host.

## send each grab

every grab fires one `knobs:grab` event on `window` as the copy starts, the payload as its
`detail`. `grabSend` also POSTs it as json (`{ "type": "knobs.grab", payload }`)
to a URL on the page's origin or on localhost, or hands it to a function. the
copy still happens:

```js
window.addEventListener("knobs:grab", (event) => console.log(event.detail.content));
mount({ grabSend: "/api/grab" });
```

```html
<script src="//unpkg.com/@vinena/knobs/dist/index.global.js" data-grab-send="/api/grab"></script>
```

## docs

- [start](https://knobs.dev/docs/start): install @vinena/knobs and mount it in
Expand Down
4 changes: 3 additions & 1 deletion packages/devknobs/src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { pin } from "./instance";
// Read as the script runs, the only time the document knows which one it is.
const script = document.currentScript;
bezelsBeside(script instanceof HTMLScriptElement ? script.src : "");
// `<script src=".../index.global.js" data-grab-send="/grab">` sends each grab there.
const grabSend = script instanceof HTMLScriptElement ? script.dataset.grabSend : undefined;

pin(window);
mount();
mount(grabSend ? { grabSend } : {});
17 changes: 17 additions & 0 deletions packages/devknobs/src/grab/clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// adapted from react-grab (MIT, Copyright (c) 2025 Aiden Bai)
import { copyText } from "./copy";
import { escapeText } from "./preview";
import { announceGrab, sendGrab } from "./send";
import type { GrabEntry, GrabPayload } from "./types";

export const KNOBS_TYPE = "application/x-knobs-grab";
Expand Down Expand Up @@ -49,3 +50,19 @@ export function clipboardData(payload: GrabPayload, now = Date.now()): Record<st
export function copyGrab(payload: GrabPayload): Promise<boolean> {
return copyText(payload.content, clipboardData(payload));
}

/** What became of a grab: whether it reached the clipboard, and the send target (null with none). */
export interface Delivery {
copied: Promise<boolean>;
sent: Promise<boolean | null>;
}

/**
* Hand a grab out: copy it first, inside the gesture that asked, then tell the
* page with a `knobs:grab` event and send it to the target. One call per grab.
*/
export function deliverGrab(payload: GrabPayload, copy: (payload: GrabPayload) => Promise<boolean> = copyGrab): Delivery {
const copied = copy(payload);
announceGrab(payload);
return { copied, sent: sendGrab(payload) };
}
4 changes: 2 additions & 2 deletions packages/devknobs/src/grab/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { copyGrab } from "./clipboard";
import { deliverGrab } from "./clipboard";
import { grabContext } from "./context";
import { isElement } from "./inspect";
import type { GrabOptions, GrabResult } from "./types";
Expand Down Expand Up @@ -32,5 +32,5 @@ export async function grab(
if (found.length === 0) return null;
const payload = await grabContext(found, options);
if (!payload.content.trim()) return null;
return { ...payload, copied: await copyGrab(payload) };
return { ...payload, copied: await deliverGrab(payload).copied };
}
14 changes: 10 additions & 4 deletions packages/devknobs/src/grab/mode.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { ensureStyle, removeStyle } from "../engine/style";
import { pause } from "../engine/touchpointer";
import { copyGrab } from "./clipboard";
import { copyGrab, deliverGrab } from "./clipboard";
import { componentOf, grabEntry, quickEntry } from "./context";
import { DWELL, settles, speedOf } from "./dwell";
import { grabTargetAt, isDevknobs } from "./hit";
import { isCLike } from "./keys";
import { createNavigator, stepOf } from "./navigate";
import { createOverlay, HIDE_WAIT, type Overlay } from "./overlay";
import { copiedText, flushPicks, picksPayload } from "./picks";
import { copiedText, flushPicks, picksPayload, settledText } from "./picks";
import { elementsInRect, isDrag, type Point, rectFrom } from "./rect";
import { createTray, type Tray, TRAY_CSS } from "./tray";
import type { GrabEntry } from "./types";
Expand Down Expand Up @@ -255,8 +255,14 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode {
const entries = elements.map((element) => ready.get(element) ?? page.quickEntry(element));
const anchor = elements[elements.length - 1] ?? null;
overlay.toast(copiedText(elements.length), anchor, true);
void page.copyGrab(picksPayload(entries, tray?.note())).then((copied) => {
if (!copied) overlay.toast("Copy failed", anchor, false);
const delivery = deliverGrab(picksPayload(entries, tray?.note()), page.copyGrab);
void delivery.copied.then((copied) => {
const failed = settledText(elements.length, copied, null);
if (failed) overlay.toast(failed.text, anchor, failed.good);
return delivery.sent.then((sent) => {
const settled = sent === null ? null : settledText(elements.length, copied, sent);
if (settled) overlay.toast(settled.text, anchor, settled.good);
});
});
for (const element of elements) warm(element);
exit();
Expand Down
10 changes: 10 additions & 0 deletions packages/devknobs/src/grab/picks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ export function copiedText(count: number): string {
return count > 1 ? `Copied ${count}` : "Copied";
}

/**
* What the toast says once the copy and the send are done, and whether that went well.
* Null where the first toast still holds: a copy with no target.
*/
export function settledText(count: number, copied: boolean, sent: boolean | null): { text: string; good: boolean } | null {
if (sent === true) return { text: copied ? `${copiedText(count)} · Sent` : "Sent", good: true };
if (sent === false) return { text: copied ? "Send failed" : "Copy and send failed", good: false };
return copied ? null : { text: "Copy failed", good: false };
}

function cleanNote(note: string | undefined): string | undefined {
const trimmed = note?.trim();
return trimmed ? trimmed : undefined;
Expand Down
89 changes: 89 additions & 0 deletions packages/devknobs/src/grab/send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { GrabPayload } from "./types";

/** Where each grab goes besides the clipboard: an endpoint to POST it to, or a function. */
export type GrabSend = string | ((payload: GrabPayload) => void | Promise<void>);

/** The event every grab dispatches on `window`, with the payload as its detail. */
export const GRAB_EVENT = "knobs:grab";

/** Is it a send target, read from another copy's options? */
export function isGrabSend(value: unknown): value is GrabSend {
return typeof value === "string" || typeof value === "function";
}

let target: GrabSend | null = null;

const LOCAL = /^(localhost|127\.0\.0\.1|.+\.localhost)$/;

/**
* The endpoint as an absolute URL where grab may send to it: the page's own
* origin, or http(s) on localhost, 127.0.0.1 or a `.localhost` name. Null otherwise.
*/
export function allowedEndpoint(url: string, base: string): string | null {
let parsed: URL;
try {
parsed = new URL(url, base);
} catch {
return null;
}
if (parsed.origin === "null" || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) return null;
if (parsed.origin === new URL(base).origin) return parsed.href;
if (LOCAL.test(parsed.hostname)) return parsed.href;
return null;
}

/** Set where grabs are sent, or with undefined send them nowhere. An endpoint grab may not send to is ignored. */
export function setGrabSend(send: GrabSend | undefined): void {
if (typeof send === "function") {
target = send;
return;
}
if (typeof send !== "string") {
target = null;
return;
}
target = allowedEndpoint(send, window.location.href);
if (!target) console.warn(`knobs: grab sends only to this page's origin or to localhost, not to ${send}`);
}

/** Tell the page about a grab. Listeners that throw do not reach grab. */
export function announceGrab(payload: GrabPayload): void {
if (typeof window === "undefined" || typeof window.dispatchEvent !== "function") return;
try {
window.dispatchEvent(new CustomEvent(GRAB_EVENT, { detail: payload }));
} catch {
// The page's trouble, not grab's.
}
}

/** How long a send may take before it counts as failed, in ms. */
export const SEND_TIMEOUT = 10000;

/** Send a grab to the target: true where it went, false where it failed or timed out, null with no target. */
export async function sendGrab(payload: GrabPayload, timeout = SEND_TIMEOUT): Promise<boolean | null> {
const send = target;
if (send === null) return null;
try {
if (typeof send === "function") {
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<false>((resolve) => {
timer = setTimeout(() => resolve(false), timeout);
});
try {
return await Promise.race([Promise.resolve(send(payload)).then(() => true), late]);
} finally {
clearTimeout(timer);
}
}
const response = await fetch(send, {
method: "POST",
credentials: "same-origin",
signal: AbortSignal.timeout(timeout),
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "knobs.grab", payload }),
});
return response.ok;
} catch {
return false;
}
}
5 changes: 4 additions & 1 deletion packages/devknobs/src/host.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { checkPatch } from "./engine/check";
import { isGrabSend } from "./grab/send";
import type { MountOptions } from "./index";

/**
* What a page's own mount may choose on a host's panel: its keys, grab, its
* color and whether the panel starts open. The rest is the host's to say.
* color, where grabs are sent and whether the panel starts open. The rest is the host's to say.
* Read field by field, as it comes from another copy, maybe of another version.
*/
export function pageChoices(options: object): MountOptions {
Expand All @@ -13,10 +14,12 @@ export function pageChoices(options: object): MountOptions {
const grab: unknown = Reflect.get(options, "grab");
const open: unknown = Reflect.get(options, "open");
const grabColor: unknown = Reflect.get(options, "grabColor");
const grabSend: unknown = Reflect.get(options, "grabSend");
if (typeof hotkey === "string") chosen.hotkey = hotkey;
if (typeof grabKey === "string") chosen.grabKey = grabKey;
if (typeof grab === "boolean") chosen.grab = grab;
if (typeof open === "boolean") chosen.open = open;
if (isGrabSend(grabSend)) chosen.grabSend = grabSend;
if (grabColor !== undefined) {
const patch = { grabColor };
try {
Expand Down
Loading
Loading