diff --git a/apps/web/content/docs/grab.md b/apps/web/content/docs/grab.md index 0ba50a2d..65b44bdb 100644 --- a/apps/web/content/docs/grab.md +++ b/apps/web/content/docs/grab.md @@ -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-05 +updated: 2026-11-26 --- ## grab @@ -17,10 +17,22 @@ the components that rendered it and where they live go on the clipboard: paste that into your agent and it can find the code. -- shift and a click gather several elements, one line each. -- the arrows move to the parent, a child or a sibling. enter or `c` copies. +- drag a box, or shift and a click, to gather several elements. each gets a + number, and a tray at the bottom lists them, with a note for each and one + for all. `n` writes a note. +- enter, `c` or the tray's copy button copies them all, numbered, each note + under its element. +- the arrows move to the parent, a child or a sibling. - escape or `⇧G` again turns grab off. +``` +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 +``` + 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]` diff --git a/packages/devknobs/src/grab/mode.ts b/packages/devknobs/src/grab/mode.ts index c5539bbf..9bf02b80 100644 --- a/packages/devknobs/src/grab/mode.ts +++ b/packages/devknobs/src/grab/mode.ts @@ -1,15 +1,18 @@ import { ensureStyle, removeStyle } from "../engine/style"; import { pause } from "../engine/touchpointer"; import { copyGrab } from "./clipboard"; -import { componentOf, grabEntry, joinEntries, quickEntry } from "./context"; +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, togglePick } from "./picks"; +import { copiedText, flushPicks, picksPayload } from "./picks"; +import { elementsInRect, isDrag, type Point, rectFrom } from "./rect"; +import { createTray, type Tray, TRAY_CSS } from "./tray"; import type { GrabEntry } from "./types"; import { ownSelector } from "../mark"; +import { letterMatches } from "../ui/keys"; /** How long the pointer rests on an element before its context is worked out, in ms. */ const PREPARE = 80; @@ -18,6 +21,9 @@ const PREPARE = 80; /** The least time between two hit tests as the pointer moves, in ms. */ const HIT_EVERY = 32; +/** The least time between two looks at what a drag would gather, in ms. */ +const PREVIEW_EVERY = 100; + /** Pointer and mouse events that would reach the page's own handlers. */ const BLOCKED = [ "pointerdown", @@ -66,6 +72,8 @@ export interface ModePage { componentOf: typeof componentOf; copyGrab: typeof copyGrab; createOverlay: (quiet?: boolean, model?: boolean) => Overlay; + createTray: typeof createTray; + elementsInRect: typeof elementsInRect; grabEntry: typeof grabEntry; grabTargetAt: typeof grabTargetAt; quickEntry: typeof quickEntry; @@ -75,6 +83,8 @@ const PAGE: ModePage = { componentOf, copyGrab, createOverlay, + createTray, + elementsInRect, grabEntry, grabTargetAt, quickEntry, @@ -99,7 +109,8 @@ function onControl(event: Event): boolean { /** * Grab, on: the element under the pointer gets a box and a label, a click - * copies it, shift and a click gather more, and the arrows walk the tree. + * copies it, shift and a click or a drag gather more, and the arrows walk the + * tree. What is gathered is listed in a tray, with a note for each and one for all. * The context of the element under the pointer is worked out while it rests * there, so a click can copy it whole in the click itself, as Safari wants. * The box goes to an element once the pointer settles on it, and not to those @@ -131,6 +142,17 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { let hitTimer = 0; let settleTimer = 0; let stopped = false; + /** The gathered elements, with their notes, while there is one. */ + let tray: Tray | null = null; + /** Where the primary button went down on the page, while it is down. */ + let down: Point | null = null; + /** Where a drag is now, once the press went far enough to be one. */ + let dragTo: Point | null = null; + let preview: Element[] = []; + let previewAt = Number.NEGATIVE_INFINITY; + let previewTimer = 0; + /** The click after a drag is the drag's own, and copies nothing. */ + let swallowClick = false; ensureStyle("grab-cursor").textContent = `*:not(${ownSelector()}){cursor:crosshair!important}`; // The touch pointer gives the mouse back while grab picks. @@ -159,10 +181,61 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { function draw(): void { if (stopped) return; if (current && !current.isConnected) current = null; - picked = picked.filter((element) => element.isConnected); + const kept = picked.filter((element) => element.isConnected); + if (kept.length !== picked.length) { + if (tray) { + // The tray drops the row's note too; its onRemove draws again, which takes the next one. + tray.remove(picked.findLastIndex((element) => !element.isConnected)); + return; + } + picked = kept; + syncTray(); + } overlay.draw(current, current ? labelOf(current) : { tag: "", name: null }, picked); } + /** The tray comes with the first pick, lists them all, and goes with the last. */ + function syncTray(): void { + if (purpose || stopped) return; + if (picked.length === 0) { + tray?.destroy(); + tray = null; + return; + } + if (!tray) { + tray = page.createTray({ + onRemove: (index) => setPicks(picked.filter((_, at) => at !== index)), + onCopy: () => copy(picked), + }); + overlay.mount(tray.node, TRAY_CSS); + } + tray.update(picked.map((element) => ({ label: labelOf(element) }))); + } + + function setPicks(next: Element[]): void { + picked = next; + syncTray(); + draw(); + } + + /** Take one out, its note with it where the tray has one. */ + function unpick(element: Element): void { + const index = picked.indexOf(element); + if (index < 0) return; + if (tray) tray.remove(index); + else setPicks(picked.filter((_, at) => at !== index)); + } + + /** Gather an element, or take it back out where it was gathered. */ + function toggle(element: Element): void { + if (picked.includes(element)) { + unpick(element); + return; + } + warm(element); + setPicks([...picked, element]); + } + function select(element: Element | null): void { if (element === current) return; current = element; @@ -182,7 +255,8 @@ 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({ content: joinEntries(entries), entries }).then((copied) => { + const notes = tray?.notes(); + void page.copyGrab(picksPayload(entries, notes?.each, notes?.all)).then((copied) => { if (!copied) overlay.toast("Copy failed", anchor, false); }); for (const element of elements) warm(element); @@ -234,10 +308,68 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { hit(true); } + /** Draw the drag's rectangle, and look again at what it would gather once in a while. */ + function drawDrag(): void { + if (!down || !dragTo) return; + const rect = rectFrom(down, dragTo); + const now = performance.now(); + const wait = PREVIEW_EVERY - (now - previewAt); + if (wait <= 0) { + clearTimeout(previewTimer); + previewTimer = 0; + previewAt = now; + preview = page.elementsInRect(document, rect); + } else if (!previewTimer) { + previewTimer = window.setTimeout(() => { + previewTimer = 0; + drawDrag(); + }, wait); + } + overlay.marquee(rect, preview); + } + + function endDrag(): void { + clearTimeout(previewTimer); + previewTimer = 0; + down = null; + dragTo = null; + preview = []; + previewAt = Number.NEGATIVE_INFINITY; + } + + /** A drag let go: what it went around is gathered, after what was before. It copies nothing. */ + function finishDrag(at: Point): void { + const from = down; + const dragged = dragTo !== null; + endDrag(); + if (!from || !dragged) return; + overlay.marquee(null, []); + swallowClick = true; + const added = page.elementsInRect(document, rectFrom(from, at)).filter((element) => !picked.includes(element)); + for (const element of added) warm(element); + if (added.length > 0) setPicks([...picked, ...added]); + } + + function onPointerCancel(): void { + if (dragTo) overlay.marquee(null, []); + endDrag(); + } + /** The hit test runs at most once in a while, and once more where the pointer came to rest. */ function onPointerMove(event: PointerEvent): void { if (!event.isPrimary) return; point = { x: event.clientX, y: event.clientY }; + if (down && (dragTo || isDrag(down, point))) { + if (!dragTo) { + // The box is not shown while a drag is drawn. + drop(); + navigator.clear(); + select(null); + } + dragTo = point; + drawDrag(); + return; + } overlay.point(point.x); const wait = HIT_EVERY - (performance.now() - hitAt); if (wait <= 0) { @@ -248,10 +380,25 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { } function onBlocked(event: Event): void { + // A drag let go over knobs' own UI, the tray too, still ends. + if (event.type === "pointerup" && down) { + const up = event as PointerEvent; + if (up.isPrimary) finishDrag({ x: up.clientX, y: up.clientY }); + } if (fromDevknobs(event)) return; event.preventDefault(); event.stopPropagation(); + if (event.type === "pointerdown" && !purpose) { + const press = event as PointerEvent; + swallowClick = false; + if (press.isPrimary && press.button === 0) down = { x: press.clientX, y: press.clientY }; + return; + } if (event.type !== "click" || !(event instanceof MouseEvent)) return; + if (swallowClick) { + swallowClick = false; + return; + } resolve({ x: event.clientX, y: event.clientY }); const target = page.grabTargetAt(document, event.clientX, event.clientY) ?? @@ -263,15 +410,15 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { return; } if (event.shiftKey) { - picked = togglePick(picked, target); - warm(target); - draw(); + toggle(target); return; } copy(flushPicks(picked, target)); } function keydown(event: KeyboardEvent): void { + // What is typed in the tray is the tray's, its escape too. + if (tray?.contains(event.composedPath()[0] ?? null)) return; if (event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); @@ -308,6 +455,31 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { exit(); return; } + const plain = !event.metaKey && !event.ctrlKey && !event.altKey; + if (event.key === "Enter" && event.shiftKey && plain) { + resolve(); + if (!current?.isConnected) return; + event.preventDefault(); + event.stopImmediatePropagation(); + toggle(current); + return; + } + if ((event.key === "Backspace" || event.key === "Delete") && plain && !isTyping(event)) { + resolve(); + if (!current || !picked.includes(current)) return; + event.preventDefault(); + event.stopImmediatePropagation(); + unpick(current); + return; + } + if (tray && plain && !event.shiftKey && !isTyping(event) && letterMatches(event, "n")) { + event.preventDefault(); + event.stopImmediatePropagation(); + resolve(); + const index = current ? picked.indexOf(current) : -1; + tray.focusNote(index >= 0 ? index : null); + return; + } if (event.key !== "Enter" && !isCLike(event.key, event.code)) return; resolve(); const elements = flushPicks(picked, current); @@ -317,24 +489,23 @@ export function startMode(options: ModeOptions, page: ModePage = PAGE): Mode { copy(elements); } - function onKeyup(event: KeyboardEvent): void { - if (event.key === "Shift" && picked.length > 0) copy(picked); - } - for (const type of BLOCKED) window.addEventListener(type, onBlocked, true); window.addEventListener("pointermove", onPointerMove, true); - window.addEventListener("keyup", onKeyup, true); + window.addEventListener("pointercancel", onPointerCancel, true); function stop(): void { if (stopped) return; stopped = true; clearTimeout(prepareTimer); drop(); + endDrag(); for (const type of BLOCKED) window.removeEventListener(type, onBlocked, true); window.removeEventListener("pointermove", onPointerMove, true); - window.removeEventListener("keyup", onKeyup, true); + window.removeEventListener("pointercancel", onPointerCancel, true); removeStyle("grab-cursor"); pause(false); + tray?.destroy(); + tray = null; overlay.destroy(); } diff --git a/packages/devknobs/src/grab/overlay.ts b/packages/devknobs/src/grab/overlay.ts index 9f7fb2be..3aa8ab2e 100644 --- a/packages/devknobs/src/grab/overlay.ts +++ b/packages/devknobs/src/grab/overlay.ts @@ -65,6 +65,12 @@ const CARD_WIDTH = 264; const CARD_HEIGHT = 180; /** The most characters of an element's name on the card. A longer one is cut in its middle. */ const NAME_MAX = 26; +/** How long a gathered box, its number and the drag's rectangle take to come in, in ms. */ +const APPEAR = 120; +/** How tall a gathered box's number is, and the least it is wide, in px. */ +export const BADGE = 18; +/** How far a number sits out from its box's top left corner, in px, so it covers little of the element. */ +const BADGE_OUT = 12; /** How solid two layers of one color are, the first over the second, each in percent. */ function over(top: number, under: number): number { @@ -168,6 +174,38 @@ ${colorRules("p3")} background: color-mix(in srgb, var(--grab) 5%, transparent); transition: border-color ${FADE}ms ease-out, background-color ${FADE}ms ease-out; } +.pick, .marquee { animation: appear ${APPEAR}ms ease-out; } +.pick.preview { + border-color: color-mix(in srgb, var(--grab) 20%, transparent); + background: color-mix(in srgb, var(--grab) 3%, transparent); +} +.pick-num { + position: absolute; + top: 0; + left: 0; + min-width: ${BADGE}px; + height: ${BADGE}px; + box-sizing: border-box; + padding: 0 5px; + border-radius: ${BADGE / 2}px; + color: #ffffff; + background: var(--grab); + box-shadow: 0 0 0 1px rgb(255 255 255 / 40%), 0 1px 3px rgb(0 0 0 / 24%); + font-size: 11px; + font-weight: 600; + line-height: ${BADGE}px; + text-align: center; + font-variant-numeric: tabular-nums; +} +.marquee { + position: absolute; + top: 0; + left: 0; + box-sizing: border-box; + border: 1px dashed var(--grab); + background: color-mix(in srgb, var(--grab) 6%, transparent); +} +@keyframes appear { from { opacity: 0; } } .tint { position: absolute; inset: 0; @@ -260,7 +298,7 @@ ${RINGS.map((ring) => `.tint.${ring} { background: ${boxTint(ring)}; }`).join("\ .card .mark { flex: none; display: grid; overflow: visible; } .card .mark.fail { color: var(--quiet); } .layer [hidden] { display: none; } -.layer[data-still] * { transition: none; } +.layer[data-still] * { transition: none; animation: none; } `; function clamp(value: number, low: number, high: number): number { @@ -322,6 +360,20 @@ export function cardPlace( return { x: clamp(box.left, MARGIN, view.width - card.width - MARGIN), y }; } +/** + * Where a gathered box's number goes from the box's top left corner: out + * over the corner, so it covers little of the element, and in as far as it + * must to stay in the window. + */ +export function badgeOffset(box: { left: number; top: number }): { x: number; y: number } { + return { x: Math.max(-BADGE_OUT, -box.left), y: Math.max(-BADGE_OUT, -box.top) }; +} + +/** The number a gathered box shows, at `index` in the order they were picked. */ +export function pickNumber(index: number): string { + return String(index + 1); +} + /** The first px length of a computed `border-radius`, or 0 where it has none. */ export function parseRadius(value: string): number { const match = /(\d*\.?\d+)px/.exec(value); @@ -436,6 +488,13 @@ export interface Overlay { * with the check, and goes with the toast. */ toast(text: string, near: Element | null, check: boolean): void; + /** + * Draw a drag's rectangle, in the window's px, and a light box on each + * element it would gather. Null takes both away. + */ + marquee(rect: { left: number; top: number; right: number; bottom: number } | null, preview: Element[]): void; + /** Put a node of another part of grab on the layer, over all of it, with its own styles. It goes with the layer. */ + mount(node: HTMLElement, css?: string): void; /** Fade out and go, once a toast is over where there is one. */ destroy(): void; } @@ -563,6 +622,17 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { label.append(head, card.rows); } else label.append(check, tag, name); const picks: HTMLElement[] = []; + /** The number on each gathered box, by the same index. */ + const nums: HTMLElement[] = []; + /** The light boxes on what a drag would gather. */ + const previews: HTMLElement[] = []; + const frameNode = document.createElement("div"); + frameNode.className = "marquee"; + frameNode.hidden = true; + /** What other parts of grab put on the layer. */ + const mounted: HTMLElement[] = []; + /** Their styles, each put on the layer once. */ + const mountedCss = new Set(); /** The areas of the box, under the box's own line. */ const tints = (model ? RINGS : []).map((ring) => { const node = document.createElement("div"); @@ -570,7 +640,7 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { layer.append(node); return { ring, node }; }); - layer.append(glow, glide, tip); + layer.append(glow, frameNode, glide, tip); root.append(layer); (document.body ?? document.documentElement).append(host); // In the top layer, so it boxes what is in the page's dialogs and popovers too, and under the panel. @@ -596,6 +666,10 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { let picked: Element[] = []; /** Where each gathered element was last read, or null for one that is gone. */ let shapes: (Shape | null)[] = []; + /** The drag's rectangle, and what it would gather with where each was last read. */ + let rect: { left: number; top: number; right: number; bottom: number } | null = null; + let previewed: Element[] = []; + let previewShapes: (Shape | null)[] = []; let at: readonly number[] | null = null; let target: Shape | null = null; let labelAt: readonly number[] | null = null; @@ -648,7 +722,8 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { if (isCustomColor(name)) layer.style.setProperty("--grab", name); else layer.style.removeProperty("--grab"); } - if (bar && label.dataset.bar !== bar) label.dataset.bar = bar; + if (!bar) return; + for (const node of [label, ...mounted]) if (node.dataset.bar !== bar) node.dataset.bar = bar; } function schedule(): void { @@ -656,7 +731,7 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { } function sync(): void { - if (!element && picked.length === 0) return; + if (!element && picked.length === 0 && previewed.length === 0) return; stale = true; schedule(); } @@ -676,20 +751,53 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { return [rect.left, rect.top, rect.width, rect.height, radius]; } + /** The gathered boxes, each with its number, and the light ones of a drag, which have none. */ function drawPicks(ratio: number): void { while (picks.length < shapes.length) { const node = document.createElement("div"); node.className = "pick"; + const num = document.createElement("span"); + num.className = "pick-num"; + node.append(num); layer.insertBefore(node, glide); picks.push(node); + nums.push(num); + } + while (previews.length < previewShapes.length) { + const node = document.createElement("div"); + node.className = "pick preview"; + layer.insertBefore(node, glide); + previews.push(node); } picks.forEach((node, index) => { const shape = shapes[index] ?? null; if (node.hidden !== (shape === null)) node.hidden = shape === null; + if (!shape) return; + place(node, shape, ratio); + const num = nums[index]; + if (!num) return; + const said = pickNumber(index); + if (num.textContent !== said) num.textContent = said; + const off = badgeOffset({ left: shape[0], top: shape[1] }); + write(num, "transform", `translate(${off.x}px, ${off.y}px)`); + }); + previews.forEach((node, index) => { + const shape = previewShapes[index] ?? null; + if (node.hidden !== (shape === null)) node.hidden = shape === null; if (shape) place(node, shape, ratio); }); } + function drawMarquee(): void { + if (frameNode.hidden !== (rect === null)) frameNode.hidden = rect === null; + if (!rect) return; + const left = Math.min(rect.left, rect.right); + const top = Math.min(rect.top, rect.bottom); + write(frameNode, "transform", `translate(${left}px, ${top}px)`); + write(frameNode, "width", `${Math.abs(rect.right - rect.left)}px`); + write(frameNode, "height", `${Math.abs(rect.bottom - rect.top)}px`); + } + function drawBox(parts: BoxParts): void { write(glide, "transform", parts.at); write(box, "--unit", `${parts.unit}px`); @@ -752,6 +860,7 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { function measure(): void { if (element && !element.isConnected) element = null; shapes = picked.map((pick) => (pick.isConnected ? shapeOf(pick) : null)); + previewShapes = previewed.map((one) => (one.isConnected ? shapeOf(one) : null)); if (model) measureBox(); if (element || toasting) { const { theme, grab } = read(element); @@ -825,6 +934,7 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { paint(); drawPicks(ratio); } + drawMarquee(); box.classList.toggle("on", shown); label.classList.toggle("toast", toasting); label.classList.toggle("on", shown || toasting); @@ -957,14 +1067,40 @@ export function createOverlay(quiet = false, model = false): BoxOverlay { only = ring; schedule(); }, + marquee(next, preview) { + if (closing) return; + rect = next; + const list = next ? preview : []; + if (list.length !== previewed.length || list.some((one, index) => one !== previewed[index])) { + previewed = list; + stale = true; + } + schedule(); + }, + mount(node, css) { + if (closing) return; + if (css && !mountedCss.has(css)) { + mountedCss.add(css); + addStyle(root, css); + } + if (bar) node.dataset.bar = bar; + for (let at = mounted.length - 1; at >= 0; at--) if (!mounted[at]?.isConnected) mounted.splice(at, 1); + layer.append(node); + mounted.push(node); + }, destroy() { if (closing) return; closing = true; clearTimeout(hideTimer); glow.classList.remove("on"); + for (const node of mounted.splice(0)) node.remove(); picked = []; shapes = []; + rect = null; + previewed = []; + previewShapes = []; drawPicks(1); + drawMarquee(); if (toasting) return; hide(); fadeTimer = window.setTimeout(remove, fade()); diff --git a/packages/devknobs/src/grab/picks.ts b/packages/devknobs/src/grab/picks.ts index 2bf9f6ce..5aa3921a 100644 --- a/packages/devknobs/src/grab/picks.ts +++ b/packages/devknobs/src/grab/picks.ts @@ -1,10 +1,7 @@ -/** - * 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. - */ -export function togglePick(picked: readonly T[], item: T): T[] { - return picked.includes(item) ? picked.filter((entry) => entry !== item) : [...picked, item]; -} +import type { GrabEntry, GrabPayload } from "./types"; + +/** Indent for a note under a numbered element. */ +const NOTE_INDENT = " "; /** 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[] { @@ -16,3 +13,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/tray.ts b/packages/devknobs/src/grab/tray.ts new file mode 100644 index 00000000..33313476 --- /dev/null +++ b/packages/devknobs/src/grab/tray.ts @@ -0,0 +1,358 @@ +import { baseMatchMedia } from "../engine/matchmedia"; +import { markOwn } from "../mark"; + +/** How long the tray takes to come in, in ms. */ +const SHOW = 150; + +/** + * The tray of gathered elements, at the bottom of the window inside grab's + * layer. It goes by the page as the label does: dark by default, light where + * the overlay sets `data-bar="light"` on it. + */ +export const TRAY_CSS = ` +.tray { + --bar: #161616; + --quiet: #a7a7a7; + --rim: rgb(255 255 255 / 12%); + --field: rgb(255 255 255 / 6%); + --hover: rgb(255 255 255 / 10%); + position: fixed; + left: 50%; + bottom: calc(16px + env(safe-area-inset-bottom, 0px)); + z-index: 1; + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; + width: min(380px, calc(100vw - 32px)); + max-height: 40vh; + padding: 6px; + transform: translateX(-50%); + pointer-events: auto; + color: #ffffff; + background: var(--bar); + border-radius: 13px; + box-shadow: 0 0 0 1px var(--rim), 0 2px 8px rgb(0 0 0 / 24%); + font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + font-size: 13px; + line-height: 16px; +} +.tray[data-bar="light"] { + --bar: #ffffff; + --quiet: #737373; + --rim: rgb(0 0 0 / 10%); + --field: rgb(0 0 0 / 4%); + --hover: rgb(0 0 0 / 8%); + color: #171717; + box-shadow: 0 0 0 1px var(--rim), 0 2px 8px rgb(0 0 0 / 32%); +} +.tray.in { animation: tray-in ${SHOW}ms ease-out; } +@keyframes tray-in { + from { opacity: 0; transform: translate(-50%, 6px); } +} +@media (prefers-reduced-motion: reduce) { + .tray.in { animation: none; } +} +.layer[data-still] .tray { animation: none; } +.tray .list { + display: grid; + gap: 2px; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; +} +.tray .item { + display: flex; + align-items: center; + gap: 6px; + min-height: 28px; + padding: 2px 2px 2px 6px; + border-radius: 8px; +} +.tray .num { + flex: none; + display: grid; + place-items: center; + min-width: 16px; + height: 16px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 8px; + color: #ffffff; + background: var(--grab, #0a84ff); + font-size: 11px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} +.tray .name { + flex: 0 1 auto; + min-width: 0; + max-width: 45%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.tray .name .tag { color: var(--quiet); } +.tray input, .tray textarea { + all: unset; + box-sizing: border-box; + min-width: 0; + padding: 4px 6px; + color: inherit; + background: var(--field); + border-radius: 4px; + font: inherit; +} +.tray input { flex: 1 1 auto; height: 24px; } +.tray textarea { + display: block; + width: 100%; + border-radius: 8px; + white-space: pre-wrap; + resize: none; +} +.tray input::placeholder, .tray textarea::placeholder { color: var(--quiet); } +.tray input:focus-visible, .tray textarea:focus-visible, .tray button:focus-visible { + outline: 1px solid var(--quiet, #a7a7a7); + outline-offset: -1px; +} +.tray button { + all: unset; + box-sizing: border-box; + cursor: pointer; + border-radius: 4px; + font: inherit; +} +.tray .remove { + flex: none; + display: grid; + place-items: center; + width: 24px; + height: 24px; + color: var(--quiet); + font-size: 16px; +} +.tray .remove:hover { color: inherit; background: var(--hover); } +.tray .foot { display: flex; align-items: center; gap: 8px; } +.tray .hint { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--quiet); + font-size: 11px; +} +.tray .copy { + flex: none; + height: 24px; + padding: 0 10px; + color: #ffffff; + background: var(--grab, #0a84ff); + font-weight: 500; +} +.tray .copy:hover { filter: brightness(1.08); } +`; + +export interface TrayItem { + label: { tag: string; name: string | null }; +} + +export interface TrayOptions { + /** A row's remove button was pressed. The tray has dropped its note already. */ + onRemove(index: number): void; + onCopy(): void; +} + +export interface Tray { + node: HTMLElement; + update(items: TrayItem[]): void; + /** Take a row out as its remove button does: its note goes, and `onRemove` is told. */ + remove(index: number): void; + /** Each row's note and the overall one, as typed. */ + notes(): { each: string[]; all: string }; + /** Focus a row's note, or with null the overall note. */ + focusNote(index: number | null): void; + contains(target: EventTarget | null): boolean; + destroy(): void; +} + +/** + * The notes kept when the list changes: the one at `removed` dropped, then + * cut or filled with empty ones to `length`. + */ +export function alignNotes(notes: readonly string[], removed: number | null, length: number): string[] { + const kept = removed === null ? [...notes] : notes.filter((_, index) => index !== removed); + return Array.from({ length }, (_, index) => kept[index] ?? ""); +} + +interface Row { + node: HTMLElement; + num: HTMLElement; + tag: HTMLElement; + name: HTMLElement; + input: HTMLInputElement; + remove: HTMLButtonElement; + key: string; +} + +function element(tag: K, className = ""): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (className) node.className = className; + return node; +} + +function isField(target: EventTarget | null): target is HTMLInputElement | HTMLTextAreaElement { + return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement; +} + +export function createTray(options: TrayOptions): Tray { + const node = element("div", "tray"); + markOwn(node, "grab-tray"); + node.setAttribute("role", "region"); + node.setAttribute("aria-label", "Picked elements"); + const list = element("div", "list"); + const all = element("textarea"); + all.rows = 2; + all.placeholder = "Note for all"; + all.setAttribute("aria-label", "Note for all"); + const foot = element("div", "foot"); + const hint = element("div", "hint"); + hint.textContent = "⇧ click or drag to add · n note · ↩ copy · esc"; + const copy = element("button", "copy"); + copy.type = "button"; + foot.append(hint, copy); + node.append(list, all, foot); + + const rows: Row[] = []; + let shown = false; + + function makeRow(): Row { + const row: Row = { + node: element("div", "item"), + num: element("span", "num"), + tag: element("span", "tag"), + name: element("span", "name"), + input: element("input"), + remove: element("button", "remove"), + key: "", + }; + row.input.type = "text"; + row.input.placeholder = "Note"; + row.input.spellcheck = false; + row.remove.type = "button"; + row.remove.textContent = "×"; + row.remove.addEventListener("click", () => removeAt(rows.indexOf(row))); + row.node.append(row.num, row.name, row.input, row.remove); + return row; + } + + function removeAt(index: number): void { + if (index < 0 || index >= rows.length) return; + const notes = alignNotes( + rows.map((each) => each.input.value), + index, + rows.length - 1, + ); + rows.forEach((each, at) => { + if (at < notes.length) each.input.value = notes[at] ?? ""; + }); + options.onRemove(index); + } + + function fill(row: Row, item: TrayItem, index: number): void { + const number = String(index + 1); + const key = `${number}\n${item.label.tag}\n${item.label.name ?? ""}`; + if (row.key === key) return; + row.key = key; + row.num.textContent = number; + row.tag.textContent = item.label.tag; + row.name.replaceChildren(row.tag); + if (item.label.name) row.name.append(` ${item.label.name}`); + row.name.title = item.label.name ? `${item.label.tag} ${item.label.name}` : item.label.tag; + row.input.setAttribute("aria-label", `Note for ${number}`); + row.remove.setAttribute("aria-label", `Remove ${number}`); + } + + function update(items: TrayItem[]): void { + while (rows.length > items.length) rows.pop()?.node.remove(); + while (rows.length < items.length) { + const row = makeRow(); + rows.push(row); + list.append(row.node); + } + items.forEach((item, index) => { + const row = rows[index]; + if (row) fill(row, item, index); + }); + copy.textContent = `Copy ${items.length}`; + if (items.length > 0 && !shown) { + shown = true; + const still = baseMatchMedia("(prefers-reduced-motion: reduce)").matches; + node.classList.toggle("in", !still); + } + if (items.length === 0) { + shown = false; + node.classList.remove("in"); + } + } + + function onKey(event: KeyboardEvent): void { + const target = event.composedPath()[0] ?? null; + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + if (target instanceof HTMLElement) target.blur(); + return; + } + if (event.key === "Enter" && !event.isComposing) { + const command = event.metaKey || event.ctrlKey; + if (command || (target instanceof HTMLInputElement && !event.shiftKey)) { + event.preventDefault(); + event.stopPropagation(); + options.onCopy(); + return; + } + } + if (isField(target)) event.stopPropagation(); + } + + function onType(event: KeyboardEvent): void { + 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); + copy.addEventListener("click", () => options.onCopy()); + + return { + node, + update, + remove: removeAt, + notes() { + return { each: rows.map((row) => row.input.value), all: all.value }; + }, + focusNote(index) { + const field = index === null ? all : rows[index]?.input; + field?.focus({ preventScroll: true }); + field?.scrollIntoView({ block: "nearest" }); + }, + contains(target) { + return target instanceof Node && node.contains(target); + }, + destroy() { + node.removeEventListener("mousedown", onPress); + node.removeEventListener("keydown", onKey); + node.removeEventListener("keyup", onType); + node.removeEventListener("keypress", onType); + node.remove(); + }, + }; +} 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-dwell.test.ts b/packages/devknobs/test/grab-dwell.test.ts index bed2406d..5011c2cb 100644 --- a/packages/devknobs/test/grab-dwell.test.ts +++ b/packages/devknobs/test/grab-dwell.test.ts @@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; import { DWELL, SLOW, settles, speedOf } from "../src/grab/dwell"; import { type Mode, type ModePage, startMode } from "../src/grab/mode"; import type { Overlay } from "../src/grab/overlay"; +import type { PageRect } from "../src/grab/rect"; +import type { Tray, TrayOptions } from "../src/grab/tray"; import type { GrabEntry } from "../src/grab/types"; import { as, type FakeElement, node } from "./grab-tree"; @@ -50,9 +52,51 @@ let draws: { element: Element | null; tag: string; picked: Element[] }[]; let toasts: (Element | null)[]; let warmed: Element[]; let copies: string[][]; +/** The text of each copy. */ +let texts: string[]; +/** Each drag rectangle the overlay was told to draw, null where it was taken away. */ +let marquees: (PageRect | null)[]; let exits: number; let mode: Mode | null = null; +/** A tray as the mode sees it: what it lists, the notes typed in it, and where the focus went. */ +interface FakeTray { + options: TrayOptions; + items: string[]; + each: string[]; + all: string; + focused: (number | null)[]; + destroyed: boolean; +} +let trays: FakeTray[]; +/** An element the fake tray holds, for keys typed in the tray. */ +const inTray = new EventTarget(); + +function tray(): FakeTray | undefined { + return trays[trays.length - 1]; +} + +function createTray(options: TrayOptions): Tray { + const fake: FakeTray = { options, items: [], each: [], all: "", focused: [], destroyed: false }; + trays.push(fake); + return { + node: {} as HTMLElement, + update: (items) => { + fake.items = items.map((item) => item.label.tag); + }, + remove: (index) => { + fake.each = fake.each.filter((_, at) => at !== index); + options.onRemove(index); + }, + notes: () => ({ each: fake.each, all: fake.all }), + focusNote: (index) => fake.focused.push(index), + contains: (target) => target === inTray, + destroy: () => { + fake.destroyed = true; + }, + }; +} + function entryOf(element: Element): GrabEntry { const tagName = element.tagName.toLowerCase(); return { tagName, content: tagName, selector: tagName, source: null, stackContext: "", frames: [] }; @@ -62,6 +106,8 @@ const overlay: Overlay = { draw: (element, label, picked) => draws.push({ element, tag: label.tag, picked }), point: () => undefined, toast: (_text, near) => toasts.push(near), + marquee: (rect) => marquees.push(rect), + mount: () => undefined, destroy: () => undefined, }; @@ -69,9 +115,14 @@ const page: ModePage = { componentOf: () => null, copyGrab: async (payload) => { copies.push(payload.entries.map((entry) => entry.tagName)); + texts.push(payload.content); return true; }, createOverlay: () => overlay, + createTray, + // Each element is 100 px wide from the left, and the whole of it must be in the drag. + elementsInRect: (_doc, rect) => + laid.filter((_, index) => rect.left <= index * 100 && rect.right >= index * 100 + 100).map(as), grabEntry: async (element) => { warmed.push(element); return entryOf(element); @@ -114,11 +165,37 @@ function click(x: number, shiftKey = false): void { window.dispatchEvent(event); } -function press(key: string): void { +function pointer(type: string, x: number): void { + const event = Object.assign(new Event(type, { cancelable: true }), { + isPrimary: true, + button: 0, + clientX: x, + clientY: 10, + }); + window.dispatchEvent(event); +} + +/** Press at one x, go to the other in steps, let go there, and the click that follows. */ +function drag(from: number, to: number): void { + pointer("pointerdown", from); + for (let step = 1; step <= 4; step++) { + wait(40); + move(from + ((to - from) * step) / 4); + } + pointer("pointerup", to); + click(to); +} + +function keyup(key: string): void { + window.dispatchEvent(Object.assign(new Event("keyup"), { key, code: key })); +} + +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: false, + shiftKey, metaKey: false, ctrlKey: false, altKey: false, @@ -151,6 +228,9 @@ beforeEach(() => { toasts = []; warmed = []; copies = []; + texts = []; + marquees = []; + trays = []; exits = 0; const style = { setAttribute: () => undefined, remove: () => undefined, textContent: "" }; Object.defineProperty(globalThis, "window", { @@ -311,3 +391,159 @@ describe("a click or a key while the box waits", () => { expect(jest.getTimerCount()).toBe(0); }); }); + +/** What is gathered, as the overlay was last told. */ +function gathered(): Element[] { + return draws[draws.length - 1]?.picked ?? []; +} + +describe("gathering many", () => { + test("one element with no notes copies its line alone", () => { + start(50); + click(50); + expect(texts).toEqual(["a"]); + }); + + test("letting go of shift copies nothing", () => { + start(50); + click(50, true); + keyup("Shift"); + expect(copies).toEqual([]); + expect(exits).toBe(0); + expect(gathered()).toEqual([as(a)]); + }); + + test("a drag gathers what it went around, after what was gathered, and copies nothing", () => { + start(250); + click(250, true); + drag(0, 205); + expect(gathered()).toEqual([as(c), as(a), as(b)]); + expect(tray()?.items).toEqual(["c", "a", "b"]); + expect(copies).toEqual([]); + expect(exits).toBe(0); + expect(marquees.length).toBeGreaterThan(1); + expect(marquees[marquees.length - 1]).toBeNull(); + expect(warmed).toEqual(expect.arrayContaining([as(a), as(b)])); + }); + + test("a drag over gathered elements keeps them as they were", () => { + start(50); + click(50, true); + drag(0, 205); + expect(gathered()).toEqual([as(a), as(b)]); + }); + + test("the box is not shown while a drag is drawn", () => { + start(50); + pointer("pointerdown", 0); + wait(40); + move(150); + expect(boxed()).toBeNull(); + wait(500); + expect(boxed()).toBeNull(); + }); + + test("shift and enter gather the boxed element, and take it back out", () => { + start(50); + press("Enter", true); + expect(gathered()).toEqual([as(a)]); + expect(tray()?.items).toEqual(["a"]); + press("Enter", true); + expect(gathered()).toEqual([]); + expect(tray()?.destroyed).toBe(true); + expect(copies).toEqual([]); + }); + + test("backspace takes the boxed element out, and its note with it", () => { + start(50); + click(50, true); + wait(40); + move(250); + click(250, true); + const fake = tray(); + if (fake) fake.each = ["", "for c"]; + press("Backspace"); + expect(gathered()).toEqual([as(a)]); + expect(fake?.each).toEqual([""]); + expect(copies).toEqual([]); + }); + + test("a gathered element taken off the page loses its own note, and the others keep theirs", () => { + start(50); + click(50, true); + click(150, true); + click(250, true); + const fake = tray(); + expect(fake?.items).toEqual(["a", "b", "c"]); + if (fake) fake.each = ["for a", "for b", "for c"]; + a.isConnected = false; + c.isConnected = false; + wait(40); + move(150); + wait(40); + move(150); + expect(gathered()).toEqual([as(b)]); + expect(fake?.items).toEqual(["b"]); + expect(fake?.each).toEqual(["for b"]); + }); + + test("n writes a note for the boxed element, or for all", () => { + start(50); + click(50, true); + wait(40); + move(250); + click(250, true); + press("n"); + expect(tray()?.focused).toEqual([1]); + move(150); + wait(40); + press("n"); + expect(tray()?.focused).toEqual([1, null]); + }); + + test("a copy carries the notes, numbered", () => { + start(50); + click(50, true); + click(250, true); + const fake = tray(); + if (fake) { + fake.each = ["make it blue", " "]; + fake.all = "same spacing"; + } + press("Enter"); + expect(copies).toEqual([["a", "c"]]); + expect(texts).toEqual(["1. a\n Note: make it blue\n2. c\n\nNote: same spacing"]); + expect(exits).toBe(1); + 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); + click(250, true); + tray()?.options.onCopy(); + expect(copies).toEqual([["a", "c"]]); + }); +}); diff --git a/packages/devknobs/test/grab-overlay.test.ts b/packages/devknobs/test/grab-overlay.test.ts index d386de74..b9692924 100644 --- a/packages/devknobs/test/grab-overlay.test.ts +++ b/packages/devknobs/test/grab-overlay.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; import { + BADGE, + badgeOffset, type BoxParts, boxParts, boxRadius, @@ -7,6 +9,7 @@ import { labelPlace, LERP, parseRadius, + pickNumber, snap, TOAST_TIME, tweenStep, @@ -247,4 +250,33 @@ describe("CSS", () => { const glide = rules.find(([, selector]) => selector?.trim() === ".glide"); expect(glide?.[2]).toContain("will-change: transform"); }); + + test("draws a gathered box's number round, in grab's color, on figures of one width", () => { + const num = [...CSS.matchAll(/([^{}]+)\{([^}]*)\}/g)].find(([, selector]) => selector?.trim() === ".pick-num"); + expect(num?.[2]).toContain(`min-width: ${BADGE}px`); + expect(num?.[2]).toContain(`border-radius: ${BADGE / 2}px`); + expect(num?.[2]).toContain("background: var(--grab)"); + expect(num?.[2]).toContain("font-variant-numeric: tabular-nums"); + }); + + test("fades the boxes and the drag's rectangle in, and not at all with reduced motion", () => { + expect(CSS).toMatch(/\.pick, \.marquee \{ animation: appear 120ms ease-out; \}/); + expect(CSS).toContain(".layer[data-still] * { transition: none; animation: none; }"); + }); +}); + +describe("gathered numbers", () => { + test("count from one in the order they were picked", () => { + expect(["a", "b", "c"].map((_, index) => pickNumber(index))).toEqual(["1", "2", "3"]); + }); + + test("sit out over the box's top left corner", () => { + expect(badgeOffset({ left: 100, top: 80 })).toEqual({ x: -12, y: -12 }); + }); + + test("come in as far as they must to stay in the window", () => { + expect(badgeOffset({ left: 4, top: 100 })).toEqual({ x: -4, y: -12 }); + expect(badgeOffset({ left: 100, top: 5 })).toEqual({ x: -12, y: -5 }); + expect(badgeOffset({ left: -30, top: -5 })).toEqual({ x: 30, y: 5 }); + }); }); diff --git a/packages/devknobs/test/grab-picks.test.ts b/packages/devknobs/test/grab-picks.test.ts index 57f40801..70b5058a 100644 --- a/packages/devknobs/test/grab-picks.test.ts +++ b/packages/devknobs/test/grab-picks.test.ts @@ -1,14 +1,25 @@ 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 } from "../src/grab/picks"; +import type { GrabEntry } from "../src/grab/types"; -describe("picks", () => { - test("shift and a click gather, and a second one takes it back out", () => { - let picked = togglePick([], "a"); - picked = togglePick(picked, "b"); - expect(picked).toEqual(["a", "b"]); - expect(togglePick(picked, "a")).toEqual(["b"]); - }); +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 = '[