From 9ad7ccc39ceb761f6a30b9255e24db3c5a3fe2dc Mon Sep 17 00:00:00 2001 From: Mert Duzgun <46185450+mert-duzgun@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:03:05 +0300 Subject: [PATCH 1/7] feat(devknobs): grab numbers picks with notes, and finds the elements in a dragged box --- packages/devknobs/src/grab/picks.ts | 47 +++++++- packages/devknobs/src/grab/rect.ts | 128 ++++++++++++++++++++++ packages/devknobs/src/grab/types.ts | 6 +- packages/devknobs/test/grab-picks.test.ts | 77 ++++++++++++- packages/devknobs/test/grab-rect.test.ts | 127 +++++++++++++++++++++ 5 files changed, 382 insertions(+), 3 deletions(-) create mode 100644 packages/devknobs/src/grab/rect.ts create mode 100644 packages/devknobs/test/grab-rect.test.ts diff --git a/packages/devknobs/src/grab/picks.ts b/packages/devknobs/src/grab/picks.ts index 2bf9f6ce..fc058c9d 100644 --- a/packages/devknobs/src/grab/picks.ts +++ b/packages/devknobs/src/grab/picks.ts @@ -1,6 +1,11 @@ +import type { GrabEntry, GrabPayload } from "./types"; + +/** Indent for a note under a numbered element. */ +const NOTE_INDENT = " "; + /** * Shift and a click gather elements, and a click again takes one back out. - * They are copied together once shift is let go, or with a plain click. + * They are copied together with a plain click, Enter, C or the tray's button. */ export function togglePick(picked: readonly T[], item: T): T[] { return picked.includes(item) ? picked.filter((entry) => entry !== item) : [...picked, item]; @@ -16,3 +21,43 @@ export function flushPicks(picked: readonly T[], clicked: T | null): T[] { export function copiedText(count: number): string { return count > 1 ? `Copied ${count}` : "Copied"; } + +function cleanNote(note: string | undefined): string | undefined { + const trimmed = note?.trim(); + return trimmed ? trimmed : undefined; +} + +/** + * The text a copy of the picks puts on the clipboard. One element with no note is its + * line alone. Otherwise each element is numbered, its note on the next line under it, + * and the note for all goes last after a blank line. + */ +export function formatPicks(entries: readonly GrabEntry[], note?: string): string { + const overall = cleanNote(note); + const only = entries.length === 1 ? entries[0] : undefined; + if (only && !cleanNote(only.note) && !overall) return only.content; + const blocks = entries.map((entry, index) => { + const line = `${index + 1}. ${entry.content}`; + const own = cleanNote(entry.note); + if (!own) return line; + return `${line}\n${NOTE_INDENT}Note: ${own.split("\n").join(`\n${NOTE_INDENT}`)}`; + }); + if (overall) blocks.push(`${blocks.length > 0 ? "\n" : ""}Note: ${overall}`); + return blocks.join("\n"); +} + +/** A payload from the picks and the tray's notes, one per pick and one for all. Empty notes are left out. */ +export function picksPayload( + entries: readonly GrabEntry[], + notes: readonly (string | undefined)[] = [], + note?: string, +): GrabPayload { + const noted = entries.map((entry, index) => { + const { note: _old, ...rest } = entry; + const own = cleanNote(notes[index]); + return own ? { ...rest, note: own } : rest; + }); + const overall = cleanNote(note); + const content = formatPicks(noted, overall); + return overall ? { content, entries: noted, note: overall } : { content, entries: noted }; +} diff --git a/packages/devknobs/src/grab/rect.ts b/packages/devknobs/src/grab/rect.ts new file mode 100644 index 00000000..5f6d864b --- /dev/null +++ b/packages/devknobs/src/grab/rect.ts @@ -0,0 +1,128 @@ +import { isDevknobs } from "./hit"; + +/** A box on the page, in viewport pixels. */ +export interface PageRect { + left: number; + top: number; + right: number; + bottom: number; +} + +export interface Point { + x: number; + y: number; +} + +/** How far the pointer goes before a press is a drag, not a click. */ +const DRAG_DISTANCE = 6; + +/** How far an element may stick out of the drag and still count. */ +const TOLERANCE = 1; + +/** Tags a drag never takes, nor anything in them. */ +const SKIPPED = new Set(["head", "script", "style", "template"]); + +const FILTER_ACCEPT = 1; +const FILTER_REJECT = 2; +const FILTER_SKIP = 3; + +/** The box between two corners, in either order. */ +export function rectFrom(a: Point, b: Point): PageRect { + return { + left: Math.min(a.x, b.x), + top: Math.min(a.y, b.y), + right: Math.max(a.x, b.x), + bottom: Math.max(a.y, b.y), + }; +} + +/** The pointer moved more than 6 px between going down and coming up. */ +export function isDrag(a: Point, b: Point): boolean { + return Math.hypot(b.x - a.x, b.y - a.y) > DRAG_DISTANCE; +} + +/** The box lies fully inside the drag, give or take a pixel. */ +export function insideRect(box: PageRect, rect: PageRect): boolean { + return ( + box.left >= rect.left - TOLERANCE && + box.top >= rect.top - TOLERANCE && + box.right <= rect.right + TOLERANCE && + box.bottom <= rect.bottom + TOLERANCE + ); +} + +export interface RectCandidate { + element: T; + rect: PageRect; +} + +/** + * The candidates a drag takes: inside the drag, outermost only (one whose ancestor + * also counts is left out), in the order given, at most `max`. + */ +export function pickInRect( + candidates: readonly RectCandidate[], + rect: PageRect, + parentOf: (element: T) => T | null, + max = 30, +): T[] { + const counting = new Set(); + for (const candidate of candidates) { + if (insideRect(candidate.rect, rect)) counting.add(candidate.element); + } + const picked: T[] = []; + for (const candidate of candidates) { + if (picked.length >= max) break; + if (!counting.has(candidate.element)) continue; + let outermost = true; + for (let up = parentOf(candidate.element); up !== null; up = parentOf(up)) { + if (counting.has(up)) { + outermost = false; + break; + } + } + if (outermost) picked.push(candidate.element); + } + return picked; +} + +function inSvg(element: Element): boolean { + for (let up = element.parentElement; up; up = up.parentElement) { + if (up.tagName.toLowerCase() === "svg") return true; + } + return false; +} + +/** + * The page's elements a drag over `rect` takes, in document order, at most `max`. + * Not knobs' own UI, nor hidden ones; shadow roots and frames are not entered. + */ +export function elementsInRect(doc: Document, rect: PageRect, max = 30): Element[] { + const body = doc.body; + if (!body) return []; + const view = doc.defaultView; + const candidates: RectCandidate[] = []; + const taken = new Set(); + const walker = doc.createTreeWalker(body, 1, { + acceptNode(node) { + const element = node as Element; + const parent = element.parentElement; + if (parent && taken.has(parent)) return FILTER_REJECT; + const tag = element.tagName.toLowerCase(); + if (SKIPPED.has(tag) || isDevknobs(element) || inSvg(element)) return FILTER_REJECT; + const box = element.getBoundingClientRect(); + if (box.width <= 0 || box.height <= 0 || !insideRect(box, rect)) return FILTER_SKIP; + const style = view?.getComputedStyle(element); + if (style?.display === "none") return FILTER_REJECT; + if (style?.visibility === "hidden") return FILTER_SKIP; + return FILTER_ACCEPT; + }, + }); + while (candidates.length < max) { + const element = walker.nextNode() as Element | null; + if (!element) break; + taken.add(element); + candidates.push({ element, rect: element.getBoundingClientRect() }); + } + return pickInRect(candidates, rect, (element) => element.parentElement, max); +} diff --git a/packages/devknobs/src/grab/types.ts b/packages/devknobs/src/grab/types.ts index ac10faa3..6eca3a47 100644 --- a/packages/devknobs/src/grab/types.ts +++ b/packages/devknobs/src/grab/types.ts @@ -45,12 +45,16 @@ export interface GrabEntry { source: ResolvedSource | null; stackContext: string; frames: GrabFrame[]; + /** What the user wrote about this element in the tray, trimmed. Left out when empty. */ + note?: string; } export interface GrabPayload { - /** Every entry's line, one per line. */ + /** Every entry's line, one per line, numbered with their notes when there is more than one or a note. */ content: string; entries: GrabEntry[]; + /** The tray's note for all the elements, trimmed. Left out when empty. */ + note?: string; } /** What `grab` hands back: the payload, and whether it reached the clipboard. */ diff --git a/packages/devknobs/test/grab-picks.test.ts b/packages/devknobs/test/grab-picks.test.ts index 57f40801..bd8e1f70 100644 --- a/packages/devknobs/test/grab-picks.test.ts +++ b/packages/devknobs/test/grab-picks.test.ts @@ -1,5 +1,23 @@ import { describe, expect, test } from "bun:test"; -import { copiedText, flushPicks, togglePick } from "../src/grab/picks"; +import { joinEntries } from "../src/grab/context"; +import { copiedText, flushPicks, formatPicks, picksPayload, togglePick } from "../src/grab/picks"; +import type { GrabEntry } from "../src/grab/types"; + +function entry(content: string, note?: string): GrabEntry { + const base: GrabEntry = { + tagName: "button", + componentName: "Save", + content, + selector: "button", + source: null, + stackContext: "", + frames: [], + }; + return note === undefined ? base : { ...base, note }; +} + +const SAVE = '[ in SaveButton (at src/App.jsx:5:5)] + Note: make it blue +2. [Docs in Nav (at src/Nav.jsx:12:9)] + +Note: same spacing for all of these +``` + for a file, a line and a column on every component, React needs a devtools hook from its first render: the React devtools extension, or the [early script](/docs/start). diff --git a/apps/web/content/reference/grab.md b/apps/web/content/reference/grab.md index 8c20cb83..f9fb5d3c 100644 --- a/apps/web/content/reference/grab.md +++ b/apps/web/content/reference/grab.md @@ -40,14 +40,45 @@ while it is on: - a click copies the element, and grab ends. the page's own click, mouse and pointer handlers never hear of it, and its hover handlers neither. - shift and a click gather elements, lighter boxes, and a second one takes one - back out. letting go of shift, or a click without it, copies them all, one - line each. + back out. `⇧↩` (`Shift Enter` off a Mac) gathers the boxed element or takes + it back out, and backspace or delete takes it out. letting go of shift copies + nothing: what is gathered stays until a copy, escape or its removal. +- drag a box on the page, with shift or without, to gather every element fully + inside it: the outermost ones, in page order, 30 at most. those it would take + show lighter boxes while you drag. ones gathered before stay, and a drag + never copies. knobs' own ui, hidden elements, shadow roots and frames are + left out. +- each gathered element shows its number, 1, 2, 3 in the order it was + gathered, in a badge at its box's top left. the numbers close up when one + goes. +- a tray at the bottom of the window lists them: the number, the tag and the + component, a one-line note and a remove button. under the list are a note + for all and a "Copy N" button. `n` writes the boxed element's note where it + is gathered, or else the note for all. enter in a note, or `⌘↩` (`Ctrl +Enter` off a Mac) anywhere, copies. escape in the tray goes back to picking, + and what is typed in it never moves the box or copies. +- a click without shift, enter, `c` or the tray's button copies them all, the + clicked one last where it is new, and grab ends. - up goes to the parent, down back the way it came or to the first child, left and right (and tab, shift-tab) to the previous and the next element, siblings first, then the sibling of the nearest parent that has one. enter or `c` copies. - a check and "Copied" show by the element for a moment, the box still on it. +one element with no notes copies as its line alone. more than one, or a note, +and each element is numbered, its note on the next line under it, and the note +for all goes last after a blank line. empty notes are left out: + +``` +1. [ in SaveButton (at src/App.jsx:5:5)] + Note: make it blue +2. [Docs in Nav (at src/Nav.jsx:12:9)] + +Note: same spacing for all of these +``` + +the json carries each element's `note`, and the note for all as `note`. + the context of the element under the pointer is worked out while the pointer rests there, so a click copies it whole, inside the click, as Safari wants. where it is not ready yet, the click copies it without lines and columns, by diff --git a/packages/devknobs/CHANGELOG.md b/packages/devknobs/CHANGELOG.md index 553276d2..9ff7312a 100644 --- a/packages/devknobs/CHANGELOG.md +++ b/packages/devknobs/CHANGELOG.md @@ -1,5 +1,12 @@ # changelog +## Unreleased + +- grab gathers many elements: drag a box around them, or shift and a click. each shows its number +- a tray lists what is gathered, with a note for each and one for all. `n` writes a note, enter, `c` or the tray's button copies them all +- more than one element, or a note, copies numbered, each note under its element and the note for all last +- letting go of shift no longer copies + ## 0.7.5 - the page under Safari's bottom bar lines up with the page above it on pages that pin a section while they scroll, and on any page with a viewport length in a class name, such as Tailwind's `h-[260svh]` From 99e106429230bc39655e1a573b63c9fd7a454185 Mon Sep 17 00:00:00 2001 From: Mert Duzgun <46185450+mert-duzgun@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:25:08 +0300 Subject: [PATCH 6/7] fix(devknobs): grab's tray keeps keys for grab after a click, quiet focus ring --- packages/devknobs/src/grab/mode.ts | 5 ++-- packages/devknobs/src/grab/picks.ts | 8 ------- packages/devknobs/src/grab/tray.ts | 22 +++++++---------- packages/devknobs/test/grab-dwell.test.ts | 29 +++++++++++++++++++++-- packages/devknobs/test/grab-picks.test.ts | 9 +------ packages/devknobs/test/grab-tray.test.ts | 9 +------ 6 files changed, 39 insertions(+), 43 deletions(-) diff --git a/packages/devknobs/src/grab/mode.ts b/packages/devknobs/src/grab/mode.ts index 760e64c6..9bf02b80 100644 --- a/packages/devknobs/src/grab/mode.ts +++ b/packages/devknobs/src/grab/mode.ts @@ -9,7 +9,7 @@ import { createNavigator, stepOf } from "./navigate"; import { createOverlay, HIDE_WAIT, type Overlay } from "./overlay"; import { copiedText, flushPicks, picksPayload } from "./picks"; import { elementsInRect, isDrag, type Point, rectFrom } from "./rect"; -import { createTray, isTrayEvent, type Tray, TRAY_CSS } from "./tray"; +import { createTray, type Tray, TRAY_CSS } from "./tray"; import type { GrabEntry } from "./types"; import { ownSelector } from "../mark"; import { letterMatches } from "../ui/keys"; @@ -206,7 +206,6 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { tray = page.createTray({ onRemove: (index) => setPicks(picked.filter((_, at) => at !== index)), onCopy: () => copy(picked), - onEscape: () => undefined, }); overlay.mount(tray.node, TRAY_CSS); } @@ -419,7 +418,7 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { function keydown(event: KeyboardEvent): void { // What is typed in the tray is the tray's, its escape too. - if (isTrayEvent(event)) return; + if (tray?.contains(event.composedPath()[0] ?? null)) return; if (event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); diff --git a/packages/devknobs/src/grab/picks.ts b/packages/devknobs/src/grab/picks.ts index fc058c9d..5aa3921a 100644 --- a/packages/devknobs/src/grab/picks.ts +++ b/packages/devknobs/src/grab/picks.ts @@ -3,14 +3,6 @@ import type { GrabEntry, GrabPayload } from "./types"; /** Indent for a note under a numbered element. */ const NOTE_INDENT = " "; -/** - * Shift and a click gather elements, and a click again takes one back out. - * They are copied together with a plain click, Enter, C or the tray's button. - */ -export function togglePick(picked: readonly T[], item: T): T[] { - return picked.includes(item) ? picked.filter((entry) => entry !== item) : [...picked, item]; -} - /** What a copy takes: the gathered elements, in order, and the one clicked last if it is new. */ export function flushPicks(picked: readonly T[], clicked: T | null): T[] { if (clicked === null || picked.includes(clicked)) return [...picked]; diff --git a/packages/devknobs/src/grab/tray.ts b/packages/devknobs/src/grab/tray.ts index 5a06d935..33313476 100644 --- a/packages/devknobs/src/grab/tray.ts +++ b/packages/devknobs/src/grab/tray.ts @@ -113,7 +113,7 @@ export const TRAY_CSS = ` } .tray input::placeholder, .tray textarea::placeholder { color: var(--quiet); } .tray input:focus-visible, .tray textarea:focus-visible, .tray button:focus-visible { - outline: 2px solid var(--grab, #0a84ff); + outline: 1px solid var(--quiet, #a7a7a7); outline-offset: -1px; } .tray button { @@ -162,8 +162,6 @@ export interface TrayOptions { /** A row's remove button was pressed. The tray has dropped its note already. */ onRemove(index: number): void; onCopy(): void; - /** Esc in the tray: the field is blurred, back to picking. */ - onEscape(): void; } export interface Tray { @@ -188,14 +186,6 @@ export function alignNotes(notes: readonly string[], removed: number | null, len return Array.from({ length }, (_, index) => kept[index] ?? ""); } -const trays = new Set(); - -/** Whether an event happened in a tray, so grab's own keys leave it alone. */ -export function isTrayEvent(event: Event): boolean { - if (trays.size === 0) return false; - return event.composedPath().some((node) => node instanceof HTMLElement && trays.has(node)); -} - interface Row { node: HTMLElement; num: HTMLElement; @@ -233,7 +223,6 @@ export function createTray(options: TrayOptions): Tray { copy.type = "button"; foot.append(hint, copy); node.append(list, all, foot); - trays.add(node); const rows: Row[] = []; let shown = false; @@ -314,7 +303,6 @@ export function createTray(options: TrayOptions): Tray { event.preventDefault(); event.stopPropagation(); if (target instanceof HTMLElement) target.blur(); - options.onEscape(); return; } if (event.key === "Enter" && !event.isComposing) { @@ -333,6 +321,12 @@ export function createTray(options: TrayOptions): Tray { if (isField(event.composedPath()[0] ?? null)) event.stopPropagation(); } + /** A press on a button keeps the focus where it was, so grab's keys stay grab's. */ + function onPress(event: MouseEvent): void { + if (!isField(event.composedPath()[0] ?? null)) event.preventDefault(); + } + + node.addEventListener("mousedown", onPress); node.addEventListener("keydown", onKey); node.addEventListener("keyup", onType); node.addEventListener("keypress", onType); @@ -354,7 +348,7 @@ export function createTray(options: TrayOptions): Tray { return target instanceof Node && node.contains(target); }, destroy() { - trays.delete(node); + node.removeEventListener("mousedown", onPress); node.removeEventListener("keydown", onKey); node.removeEventListener("keyup", onType); node.removeEventListener("keypress", onType); diff --git a/packages/devknobs/test/grab-dwell.test.ts b/packages/devknobs/test/grab-dwell.test.ts index d4c6c679..f9a05a78 100644 --- a/packages/devknobs/test/grab-dwell.test.ts +++ b/packages/devknobs/test/grab-dwell.test.ts @@ -69,6 +69,8 @@ interface FakeTray { destroyed: boolean; } let trays: FakeTray[]; +/** An element the fake tray holds, for keys typed in the tray. */ +const inTray = {} as EventTarget; function tray(): FakeTray | undefined { return trays[trays.length - 1]; @@ -88,7 +90,7 @@ function createTray(options: TrayOptions): Tray { }, notes: () => ({ each: fake.each, all: fake.all }), focusNote: (index) => fake.focused.push(index), - contains: () => false, + contains: (target) => target === inTray, destroy: () => { fake.destroyed = true; }, @@ -188,8 +190,9 @@ function keyup(key: string): void { window.dispatchEvent(Object.assign(new Event("keyup"), { key, code: key })); } -function press(key: string, shiftKey = false): void { +function press(key: string, shiftKey = false, target: EventTarget | null = null): void { const event = Object.assign(new Event("keydown", { cancelable: true }), { + composedPath: () => (target ? [target] : []), key, code: key, shiftKey, @@ -514,6 +517,28 @@ describe("gathering many", () => { expect(fake?.destroyed).toBe(true); }); + test("keys pressed in the tray are left to it", () => { + start(50); + click(50, true); + click(250, true); + const before = draws.length; + for (const [key, shift] of [ + ["c", false], + ["Enter", false], + ["ArrowUp", false], + ["Backspace", false], + ["n", false], + ["Enter", true], + ] as const) { + press(key, shift, inTray); + } + expect(copies).toEqual([]); + expect(gathered()).toEqual([as(a), as(c)]); + expect(draws.length).toBe(before); + expect(tray()?.focused).toEqual([]); + expect(exits).toBe(0); + }); + test("the tray's copy button copies them all", () => { start(50); click(50, true); diff --git a/packages/devknobs/test/grab-picks.test.ts b/packages/devknobs/test/grab-picks.test.ts index bd8e1f70..70b5058a 100644 --- a/packages/devknobs/test/grab-picks.test.ts +++ b/packages/devknobs/test/grab-picks.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { joinEntries } from "../src/grab/context"; -import { copiedText, flushPicks, formatPicks, picksPayload, togglePick } from "../src/grab/picks"; +import { copiedText, flushPicks, formatPicks, picksPayload } from "../src/grab/picks"; import type { GrabEntry } from "../src/grab/types"; function entry(content: string, note?: string): GrabEntry { @@ -20,13 +20,6 @@ const SAVE = '[