@zumer/snapdom-plugins 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -170,87 +170,71 @@ snapdom(el, { plugins: [htmlInCanvas()] });
170
170
 
171
171
  ---
172
172
 
173
- ### `prompt-export`
173
+ ### `agent-map`
174
174
 
175
- Adds a `toPrompt()` export method that returns an LLM-ready package: a structured element map with bounding boxes, a pre-formatted prompt text, and (optionally) an annotated screenshot. Tuned for vision-language models, browser-agent pipelines, visual QA, and any workflow that pairs a capture with structured metadata.
175
+ Produces a Set-of-Mark package for **visual agents**: an annotated screenshot with numbered badges on interactive elements, plus a compact JSON map from badge index → role / accessible name / bbox / state. One call, fully client-side.
176
176
 
177
177
  ```js
178
- import { promptExport } from '@zumer/snapdom-plugins/prompt-export';
178
+ import { agentMap } from '@zumer/snapdom-plugins/agent-map';
179
179
 
180
- const result = await snapdom(el, { plugins: [promptExport()] });
181
- // Default: no image, just the structured map + prompt text (cheapest)
182
- const { elements, prompt, dimensions } = await result.toPrompt();
183
- ```
184
-
185
- To also include the annotated image (for tasks that truly depend on vision):
180
+ const result = await snapdom(el, { plugins: [agentMap()] });
181
+ const { image, map, dimensions } = await result.toAgentMap();
186
182
 
187
- ```js
188
- const result = await snapdom(el, {
189
- plugins: [promptExport({ include: ['image', 'elements', 'prompt'] })]
190
- });
191
- const { image, elements, prompt, dimensions } = await result.toPrompt();
183
+ // image: data URL of the screenshot with numbered red badges overlaid
184
+ // map: [{ i, n, r, b, s? }, …] — index, name, role, bbox, state
185
+ // Agent says "click element 2" → map[2].b gives [x, y, w, h]
192
186
  ```
193
187
 
194
- The returned object (fields present only if requested via `include`):
195
-
196
- | Field | Type | Description |
197
- |-------|------|-------------|
198
- | `elements` | `Array` | One entry per detected element: `{ id, tag, type, name, text, bbox, attributes, state?, styles?, covered? }` |
199
- | `prompt` | `string` | Pre-formatted text describing interactive + semantic elements |
200
- | `image` | `string` | Data URL of the (optionally annotated) screenshot — **only when `include` contains `'image'`** |
201
- | `dimensions` | `{width, height}` | Scaled dimensions (always present) |
202
-
203
- `elements` is split into two `type`s:
204
- - `'interactive'` — buttons, links, inputs, `[role]`/`[tabindex]` targets. These get numbered badges overlaid on the screenshot when `annotate` is on.
205
- - `'semantic'` — headings, paragraphs, `<nav>`, `<main>`, images with `alt`, table cells, etc. Structural context, not overlaid.
188
+ Map entry shape (default `fields: 'minimal'`):
206
189
 
207
- Each `bbox` is in pixel coordinates of the returned image (scaled against `maxImageWidth`).
190
+ | Key | Type | Description |
191
+ |-----|------|-------------|
192
+ | `i` | `number` | Index matching the badge drawn on the image |
193
+ | `n` | `string` | Accessible name (aria-label → labelledby → alt → title → labels → textContent, truncated to 60 chars) |
194
+ | `r` | `string` | ARIA-style role (`button`, `link`, `checkbox`, `radio`, `textbox`, `combobox`, `slider`, `heading`, …) — derived from `role` attribute or implicit role of the element |
195
+ | `b` | `[x, y, w, h]` | Bounding box in pixels, scaled against `maxImageWidth` |
196
+ | `s` | `object?` | State: included only when at least one key is meaningful — `checked`, `disabled`, `focus`, `expanded`, `pressed`, `selected`, `value`, `open`, `selectedText`, `covered` |
208
197
 
209
- Each interactive entry also carries:
210
- - `name` — the computed accessible name (aria-label → labelledby → alt → title → labels[0] → textContent)
211
- - `state` — runtime state: `{ checked, disabled, focus, open, value, selectedText }` (only keys that apply)
212
- - `styles` — visually-meaningful computed props filtered to drop defaults
213
- - `covered: true` when another element is painted on top of the bbox center (an agent won't click through a modal)
198
+ Example map for a checkout form:
214
199
 
215
200
  ```js
216
- // Example — feed a vision-capable LLM
217
- const { image, elements } = await result.toPrompt({
218
- include: ['image', 'elements', 'prompt']
219
- });
220
-
221
- // image is a data URL → pass as image input
222
- // elements is JSON → pass as structured context alongside the image
223
- // "Click element [3]" → look up elements[3].bbox for real coordinates
201
+ [
202
+ { i: 0, n: 'Email', r: 'textbox', b: [28, 80, 280, 34], s: { value: 'ada@example.com' } },
203
+ { i: 1, n: 'Send product updates', r: 'checkbox', b: [28, 134, 13, 13], s: { checked: true } },
204
+ { i: 2, n: 'Apply coupon', r: 'button', b: [28, 176, 114, 38], s: { expanded: false } },
205
+ { i: 3, n: 'Remove coupon', r: 'button', b: [150, 176, 140, 38], s: { disabled: true } },
206
+ { i: 4, n: 'Pay $53.90', r: 'button', b: [28, 220, 97, 38] }
207
+ ]
224
208
  ```
225
209
 
210
+ #### Options
211
+
226
212
  | Option | Type | Default | Description |
227
213
  |--------|------|---------|-------------|
228
- | `include` | `string[]` | `['elements', 'prompt']` | Fields to return. Add `'image'` for tasks that need vision (chart content, layout QA, canvas). Use `['prompt']` for the cheapest text-only mode. |
229
- | `annotate` | `boolean` | `true` | Overlay numbered badges on interactive elements (only affects the image when included) |
230
- | `promptMode` | `'compact' \| 'verbose'` | `'compact'` | Prompt text verbosity. Compact omits coords when badges are on the image. |
231
- | `includeCoords` | `boolean` | `true` | Include bbox in the prompt text |
232
- | `imageFormat` | `'png' \| 'jpg' \| 'webp'` | `'png'` | Output image format (only used when `image` is included) |
233
- | `imageQuality` | `number` | `0.8` | Quality for lossy formats (0–1) |
234
- | `maxImageWidth` | `number` | `1024` | Max width in px; downscales and rescales bboxes if larger |
235
- | `interactiveSelector` | `string` | see below | CSS selector for the interactive element set |
236
- | `semanticSelector` | `string` | see below | CSS selector for the semantic element set |
237
- | `labelStyle` | `object` | `{}` | Override styles for the numbered badges (`position`, `color`, `backgroundColor`, etc.) |
214
+ | `image` | `'annotated' \| 'raw' \| false` | `'annotated'` | `'annotated'` overlays numbered badges; `'raw'` skips badges; `false` skips image generation entirely (no canvas draw, no toDataURL — cheapest path). |
215
+ | `fields` | `'minimal' \| 'full'` | `'minimal'` | `'full'` adds `t` (raw text content) and `a` (meaningful attributes) per entry. |
216
+ | `semantic` | `boolean` | `false` | Include non-interactive structural elements (headings, paragraphs, landmarks). Off by default — agents act on interactive. |
217
+ | `maxImageWidth` | `number` | `1024` | Downscale target for the image; bboxes rescale to match. |
218
+ | `imageFormat` | `'png' \| 'jpg' \| 'webp'` | `'png'` | Image format (only used when image is rendered). |
219
+ | `imageQuality` | `number` | `0.8` | Quality for lossy formats. |
220
+ | `interactiveSelector` | `string` | see below | CSS selector for interactive elements. |
221
+ | `semanticSelector` | `string` | see below | CSS selector for semantic elements (used when `semantic: true`). |
222
+ | `labelStyle` | `object` | `{}` | Override badge styles. |
238
223
 
239
224
  Defaults:
240
- - **interactive**: `a[href], button, input, select, textarea, [role="button"|"link"|"tab"|"menuitem"|"checkbox"|"radio"], [tabindex]:not([tabindex="-1"]), summary, [contenteditable="true"]`
241
- - **semantic**: `h1–h6, p, li, img[alt], nav, main, article, section, header, footer, label, td, th, figcaption, blockquote, legend`
225
+ - **interactive**: `a[href], button, input, select, textarea, [role="button"|"link"|"tab"|"menuitem"|"checkbox"|"radio"|"switch"|"slider"|"combobox"|"textbox"], [tabindex]:not([tabindex="-1"]), summary, [contenteditable="true"]`
226
+ - **semantic**: `h1–h6, nav, main, article, section, header, footer, figcaption, blockquote, legend, p`
242
227
 
243
- Both per-call options (`opts.include`, `opts.imageFormat`, etc.) and constructor options are supported; per-call wins.
228
+ Per-call options override constructor options (e.g. `result.toAgentMap({ image: false })`).
244
229
 
245
- The image is the most expensive part of `toPrompt()` to produce (canvas draw + data-URL serialization), so the default skips it. Add `'image'` to `include` when the task actually uses vision:
230
+ #### When to use
246
231
 
247
- ```js
248
- // Vision-dependent task (chart content, layout QA, visual diff)
249
- await result.toPrompt({ include: ['image', 'elements', 'prompt'] });
232
+ - Visual agents using Set-of-Mark prompting — one call gives you both the labelled image and the coordinate lookup table.
233
+ - Computer-use / browser-agent harnesses that need click coordinates for a vision model's output.
234
+ - Visual QA with an LLM judge — compare before/after captures with structured element identity.
235
+ - Dataset generation for vision-LLM fine-tuning — (image, map) pairs.
250
236
 
251
- // Pure structured agent loop (cheapest)
252
- await result.toPrompt({ include: ['prompt'] });
253
- ```
237
+ Because it runs entirely in the browser, it works in contexts where Playwright / Puppeteer can't: Chrome extensions, SaaS web apps capturing the user's own page, Electron apps capturing their own window.
254
238
 
255
239
  ---
256
240
 
package/agent-map.js ADDED
@@ -0,0 +1,376 @@
1
+ /**
2
+ * agentMap – Official SnapDOM Plugin
3
+ *
4
+ * Produces a Set-of-Mark package for visual agents: an annotated screenshot
5
+ * with numbered badges on interactive elements, plus a compact JSON map from
6
+ * badge index → role / name / bbox / state. Designed for one-call capture
7
+ * on the client side — visual agents, computer-use harnesses, dataset
8
+ * generation for vision training, visual QA.
9
+ *
10
+ * Usage:
11
+ * import { agentMap } from '@zumer/snapdom-plugins/agent-map';
12
+ * const result = await snapdom(el, { plugins: [agentMap()] });
13
+ * const { image, map, dimensions } = await result.toAgentMap();
14
+ *
15
+ * // model reply: "click element 2" → map[2].b gives [x, y, w, h]
16
+ *
17
+ * @param {Object} [options]
18
+ * @param {'annotated'|'raw'|false} [options.image='annotated'] Image output
19
+ * mode. 'annotated' draws numbered badges on the rendered image, 'raw'
20
+ * returns the image without badges, false skips image generation (cheapest).
21
+ * @param {'minimal'|'full'} [options.fields='minimal'] Per-entry shape.
22
+ * 'minimal' returns {i, n, r, b, s?}. 'full' adds {t (text), a (attrs)}.
23
+ * @param {boolean} [options.semantic=false] Include non-interactive semantic
24
+ * elements (headings, paragraphs, nav, main, landmarks). Off by default —
25
+ * agents typically only act on interactive.
26
+ * @param {number} [options.maxImageWidth=1024] Downscale target for the image.
27
+ * @param {'png'|'jpg'|'webp'} [options.imageFormat='png'] Image format.
28
+ * @param {number} [options.imageQuality=0.8] Quality for lossy formats.
29
+ * @param {string} [options.interactiveSelector] CSS selector (default below).
30
+ * @param {string} [options.semanticSelector] CSS selector (default below).
31
+ * @param {Object} [options.labelStyle={}] Override badge styles.
32
+ * @returns {Object} SnapDOM plugin
33
+ */
34
+
35
+ const DEFAULT_INTERACTIVE =
36
+ 'a[href], button, input, select, textarea, ' +
37
+ '[role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [role="switch"], [role="slider"], [role="combobox"], [role="textbox"], ' +
38
+ '[tabindex]:not([tabindex="-1"]), summary, [contenteditable="true"]';
39
+
40
+ const DEFAULT_SEMANTIC =
41
+ 'h1, h2, h3, h4, h5, h6, nav, main, article, section, header, footer, ' +
42
+ 'figcaption, blockquote, legend, p';
43
+
44
+ export function agentMap(options = {}) {
45
+ const {
46
+ image = 'annotated',
47
+ fields = 'minimal',
48
+ semantic = false,
49
+ maxImageWidth = 1024,
50
+ imageFormat = 'png',
51
+ imageQuality = 0.8,
52
+ interactiveSelector = DEFAULT_INTERACTIVE,
53
+ semanticSelector = DEFAULT_SEMANTIC,
54
+ labelStyle = {},
55
+ } = options;
56
+
57
+ return {
58
+ name: 'agent-map',
59
+
60
+ afterClone(ctx) {
61
+ const meta = extractMap(
62
+ ctx.element,
63
+ interactiveSelector,
64
+ semantic ? semanticSelector : null,
65
+ fields
66
+ );
67
+ // snapdom's export ctx is a fresh spread of ctx.options, so we stash on
68
+ // both for the agentMap() call below to find it.
69
+ ctx.__agentMapMeta = meta;
70
+ if (ctx.options) ctx.options.__agentMapMeta = meta;
71
+
72
+ if (image === 'annotated') {
73
+ addAnnotations(ctx.clone, meta.map, labelStyle);
74
+ }
75
+ },
76
+
77
+ defineExports() {
78
+ return {
79
+ agentMap: async (ctx, opts = {}) => {
80
+ const meta = ctx.__agentMapMeta;
81
+ const wantImage = opts.image !== undefined ? opts.image : image;
82
+
83
+ if (!meta || !meta.map.length) {
84
+ const out = { dimensions: { width: 0, height: 0 }, map: [] };
85
+ if (wantImage) out.image = ctx.export.url;
86
+ return out;
87
+ }
88
+
89
+ const format = opts.imageFormat || imageFormat;
90
+ const quality = opts.imageQuality || imageQuality;
91
+ const maxWidth = opts.maxImageWidth || maxImageWidth;
92
+
93
+ // Scale dimensions — whether we rasterize or not, bboxes get resized
94
+ // to the target output size so callers can overlay them on the image.
95
+ let w, h, dataURL;
96
+ if (wantImage) {
97
+ const img = new Image();
98
+ img.src = ctx.export.url;
99
+ await new Promise((res, rej) => { img.onload = res; img.onerror = rej; });
100
+ const ratio = img.naturalWidth > maxWidth ? maxWidth / img.naturalWidth : 1;
101
+ w = Math.round(img.naturalWidth * ratio);
102
+ h = Math.round(img.naturalHeight * ratio);
103
+ const canvas = document.createElement('canvas');
104
+ canvas.width = w;
105
+ canvas.height = h;
106
+ canvas.getContext('2d').drawImage(img, 0, 0, w, h);
107
+ const mime =
108
+ format === 'jpg' || format === 'jpeg' ? 'image/jpeg'
109
+ : format === 'webp' ? 'image/webp'
110
+ : 'image/png';
111
+ dataURL = canvas.toDataURL(mime, quality);
112
+ } else {
113
+ const sourceW = meta.dimensions.width || 1;
114
+ const ratio = sourceW > maxWidth ? maxWidth / sourceW : 1;
115
+ w = Math.round(sourceW * ratio);
116
+ h = Math.round(meta.dimensions.height * ratio);
117
+ }
118
+
119
+ const sx = w / (meta.dimensions.width || 1);
120
+ const sy = h / (meta.dimensions.height || 1);
121
+
122
+ const scaledMap = meta.map.map(e => {
123
+ const scaled = { ...e, b: [
124
+ Math.round(e.b[0] * sx),
125
+ Math.round(e.b[1] * sy),
126
+ Math.round(e.b[2] * sx),
127
+ Math.round(e.b[3] * sy),
128
+ ] };
129
+ return scaled;
130
+ });
131
+
132
+ const out = { dimensions: { width: w, height: h }, map: scaledMap };
133
+ if (wantImage) out.image = dataURL;
134
+ return out;
135
+ },
136
+ };
137
+ },
138
+ };
139
+ }
140
+
141
+ /* ── Role derivation ────────────────────────────── */
142
+
143
+ function deriveRole(el) {
144
+ const explicit = el.getAttribute('role');
145
+ if (explicit) return explicit;
146
+ const tag = el.tagName.toLowerCase();
147
+ const type = (el.type || '').toLowerCase();
148
+ if (tag === 'button') return 'button';
149
+ if (tag === 'a' && el.hasAttribute('href')) return 'link';
150
+ if (tag === 'input') {
151
+ if (type === 'checkbox') return 'checkbox';
152
+ if (type === 'radio') return 'radio';
153
+ if (type === 'range') return 'slider';
154
+ if (type === 'file') return 'file';
155
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'image') return 'button';
156
+ return 'textbox';
157
+ }
158
+ if (tag === 'select') return 'combobox';
159
+ if (tag === 'textarea') return 'textbox';
160
+ if (tag === 'summary') return 'button';
161
+ if (tag === 'details') return 'group';
162
+ if (/^h[1-6]$/.test(tag)) return 'heading';
163
+ if (tag === 'nav') return 'navigation';
164
+ if (tag === 'main') return 'main';
165
+ if (tag === 'header') return 'banner';
166
+ if (tag === 'footer') return 'contentinfo';
167
+ if (tag === 'article') return 'article';
168
+ if (tag === 'section') return 'region';
169
+ if (tag === 'p') return 'paragraph';
170
+ if (tag === 'img') return 'image';
171
+ return tag;
172
+ }
173
+
174
+ /* ── Accessible name ────────────────────────────── */
175
+
176
+ function accessibleName(el) {
177
+ const ariaLabel = el.getAttribute('aria-label');
178
+ if (ariaLabel && ariaLabel.trim()) return ariaLabel.trim();
179
+
180
+ const labelledBy = el.getAttribute('aria-labelledby');
181
+ if (labelledBy) {
182
+ const root = el.getRootNode();
183
+ const getById = (id) =>
184
+ root && typeof root.getElementById === 'function'
185
+ ? root.getElementById(id) : document.getElementById(id);
186
+ const parts = labelledBy.trim().split(/\s+/)
187
+ .map(id => { const r = getById(id); return r ? (r.textContent || '').trim() : ''; })
188
+ .filter(Boolean);
189
+ if (parts.length) return parts.join(' ');
190
+ }
191
+
192
+ if (el.tagName === 'IMG' || (el.tagName === 'INPUT' && (el.type || '').toLowerCase() === 'image')) {
193
+ const alt = el.getAttribute('alt');
194
+ if (alt && alt.trim()) return alt.trim();
195
+ }
196
+
197
+ const title = el.getAttribute('title');
198
+ if (title && title.trim()) return title.trim();
199
+
200
+ if (el.labels && el.labels[0]) {
201
+ const t = (el.labels[0].textContent || '').trim();
202
+ if (t) return t;
203
+ }
204
+
205
+ const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
206
+ if (text) return text.length > 60 ? text.slice(0, 59) + '…' : text;
207
+ return '';
208
+ }
209
+
210
+ /* ── State extraction ───────────────────────────── */
211
+
212
+ /**
213
+ * Builds the `s` (state) object. Only meaningful states — never default
214
+ * values that add no signal for an agent. Critically, aria-expanded and
215
+ * aria-pressed are included for BOTH values (true and false) because
216
+ * "pressed: false" on a toggle is meaningful information.
217
+ */
218
+ function deriveState(el, role, rect) {
219
+ const s = {};
220
+
221
+ try {
222
+ if (el.matches(':checked')) s.checked = true;
223
+ else if (role === 'checkbox' || role === 'radio') {
224
+ // include checked:false for form groups where an agent needs to
225
+ // know "unchecked" is a valid state distinct from "not a checkbox".
226
+ s.checked = false;
227
+ }
228
+ if (el.matches(':disabled')) s.disabled = true;
229
+ if (el.matches(':focus')) s.focus = true;
230
+ } catch { /* exotic nodes */ }
231
+
232
+ const expanded = el.getAttribute('aria-expanded');
233
+ if (expanded === 'true') s.expanded = true;
234
+ else if (expanded === 'false') s.expanded = false;
235
+
236
+ const pressed = el.getAttribute('aria-pressed');
237
+ if (pressed === 'true') s.pressed = true;
238
+ else if (pressed === 'false') s.pressed = false;
239
+
240
+ const selected = el.getAttribute('aria-selected');
241
+ if (selected === 'true') s.selected = true;
242
+ else if (selected === 'false' && (role === 'tab' || role === 'option')) s.selected = false;
243
+
244
+ if (el.tagName === 'INPUT') {
245
+ const type = (el.type || 'text').toLowerCase();
246
+ if (type !== 'checkbox' && type !== 'radio' && type !== 'submit' && type !== 'button' && type !== 'reset' && el.value) {
247
+ s.value = el.value;
248
+ }
249
+ } else if (el.tagName === 'TEXTAREA') {
250
+ if (el.value) s.value = el.value;
251
+ } else if (el.tagName === 'SELECT') {
252
+ s.value = el.value;
253
+ const opt = el.options && el.options[el.selectedIndex];
254
+ if (opt) s.selectedText = opt.text || '';
255
+ } else if (el.tagName === 'DETAILS') {
256
+ s.open = !!el.open;
257
+ }
258
+
259
+ // Covered — element visually occluded by something else at its center.
260
+ if (rect && rect.width && rect.height) {
261
+ const cx = rect.left + rect.width / 2;
262
+ const cy = rect.top + rect.height / 2;
263
+ if (cx >= 0 && cy >= 0) {
264
+ const doc = el.ownerDocument || document;
265
+ if (doc.elementFromPoint) {
266
+ const top = doc.elementFromPoint(cx, cy);
267
+ if (top && top !== el && !(el.contains && el.contains(top))) {
268
+ s.covered = true;
269
+ }
270
+ }
271
+ }
272
+ }
273
+
274
+ return Object.keys(s).length ? s : null;
275
+ }
276
+
277
+ /* ── Map extraction ─────────────────────────────── */
278
+
279
+ function extractMap(element, interactiveSelector, semanticSelector, fields) {
280
+ const rootRect = element.getBoundingClientRect();
281
+ const map = [];
282
+ let i = 0;
283
+ const tracked = new Set();
284
+
285
+ for (const el of element.querySelectorAll(interactiveSelector)) {
286
+ const entry = buildEntry(el, rootRect, i, fields, 'interactive');
287
+ if (entry) { map.push(entry); tracked.add(el); i++; }
288
+ }
289
+
290
+ if (semanticSelector) {
291
+ for (const el of element.querySelectorAll(semanticSelector)) {
292
+ if (tracked.has(el)) continue;
293
+ const entry = buildEntry(el, rootRect, i, fields, 'semantic');
294
+ if (entry) { map.push(entry); i++; }
295
+ }
296
+ }
297
+
298
+ return {
299
+ map,
300
+ dimensions: { width: rootRect.width, height: rootRect.height },
301
+ };
302
+ }
303
+
304
+ function buildEntry(el, rootRect, i, fields, kind) {
305
+ const rect = el.getBoundingClientRect();
306
+ const b = [
307
+ Math.round(rect.left - rootRect.left),
308
+ Math.round(rect.top - rootRect.top),
309
+ Math.round(rect.width),
310
+ Math.round(rect.height),
311
+ ];
312
+ if (b[2] <= 0 && b[3] <= 0) return null;
313
+
314
+ const role = deriveRole(el);
315
+ const n = accessibleName(el);
316
+
317
+ const entry = { i, n, r: role, b };
318
+
319
+ if (kind === 'interactive') {
320
+ const s = deriveState(el, role, rect);
321
+ if (s) entry.s = s;
322
+ }
323
+
324
+ if (fields === 'full') {
325
+ const t = (el.textContent || '').replace(/\s+/g, ' ').trim();
326
+ if (t && t !== n) entry.t = t.length > 160 ? t.slice(0, 159) + '…' : t;
327
+ const a = {};
328
+ for (const name of ['href', 'type', 'name', 'placeholder', 'alt', 'title', 'role', 'aria-label']) {
329
+ const v = el.getAttribute(name);
330
+ if (v && v !== 'false') a[name] = v;
331
+ }
332
+ if (Object.keys(a).length) entry.a = a;
333
+ }
334
+
335
+ return entry;
336
+ }
337
+
338
+ /* ── Annotations ────────────────────────────────── */
339
+
340
+ function addAnnotations(clone, entries, customStyle) {
341
+ const interactive = entries.filter(e => !e.isSemanticOnly);
342
+ if (!interactive.length) return;
343
+
344
+ const overlay = document.createElement('div');
345
+ overlay.setAttribute('data-snap-agent-overlay', 'true');
346
+ Object.assign(overlay.style, {
347
+ position: 'absolute',
348
+ top: '0', left: '0', width: '100%', height: '100%',
349
+ pointerEvents: 'none',
350
+ zIndex: '2147483647',
351
+ overflow: 'visible',
352
+ });
353
+
354
+ for (const e of interactive) {
355
+ const badge = document.createElement('span');
356
+ badge.textContent = String(e.i);
357
+ const cx = e.b[0] + e.b[2] / 2;
358
+ const cy = e.b[1] + e.b[3] / 2;
359
+ Object.assign(badge.style, {
360
+ position: 'absolute',
361
+ left: cx + 'px', top: cy + 'px',
362
+ transform: 'translate(-50%, -50%)',
363
+ minWidth: '18px', height: '18px',
364
+ lineHeight: '18px', fontSize: '11px', fontWeight: '700',
365
+ fontFamily: 'system-ui, -apple-system, sans-serif',
366
+ color: '#fff', backgroundColor: 'rgba(220, 38, 38, 0.92)',
367
+ borderRadius: '9px', textAlign: 'center', padding: '0 4px',
368
+ boxSizing: 'border-box', boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
369
+ ...customStyle,
370
+ });
371
+ overlay.appendChild(badge);
372
+ }
373
+
374
+ clone.style.position = 'relative';
375
+ clone.appendChild(overlay);
376
+ }
package/html-in-canvas.js CHANGED
@@ -9,13 +9,21 @@
9
9
 
10
10
  const PLUGIN_NAME = 'html-in-canvas'
11
11
 
12
- function isDrawElementImageAvailable() {
12
+ /**
13
+ * The WICG canvas-place-element spec evolved: Chrome ~130+ exposes drawElement(),
14
+ * earlier flagged builds shipped drawElementImage(). Detect either.
15
+ * @returns {'drawElement'|'drawElementImage'|null}
16
+ */
17
+ function detectDrawApi() {
13
18
  try {
14
19
  const c = document.createElement('canvas')
15
20
  const ctx = c.getContext('2d')
16
- return ctx && typeof ctx.drawElementImage === 'function'
21
+ if (!ctx) return null
22
+ if (typeof ctx.drawElement === 'function') return 'drawElement'
23
+ if (typeof ctx.drawElementImage === 'function') return 'drawElementImage'
24
+ return null
17
25
  } catch {
18
- return false
26
+ return null
19
27
  }
20
28
  }
21
29
 
@@ -23,9 +31,10 @@ function isDrawElementImageAvailable() {
23
31
  * @returns {import('../../src/core/plugins.js').Plugin}
24
32
  */
25
33
  export function htmlInCanvasPlugin() {
26
- const available = isDrawElementImageAvailable()
34
+ const drawApi = detectDrawApi()
35
+ const available = !!drawApi
27
36
  if (!available) {
28
- console.warn('[snapdom] html-in-canvas plugin: drawElementImage not available. Enable chrome://flags/#canvas-draw-element')
37
+ console.warn('[snapdom] html-in-canvas plugin: drawElement / drawElementImage not available. Enable chrome://flags/#canvas-draw-element')
29
38
  }
30
39
 
31
40
  return {
@@ -92,27 +101,34 @@ export function htmlInCanvasPlugin() {
92
101
 
93
102
  canvas.appendChild(wrapper)
94
103
 
95
- const container = document.createElement('div')
96
- container.id = 'snapdom-html-in-canvas-temp'
97
- container.style.cssText = 'position:fixed;left:-9999px;top:0;visibility:hidden;'
98
- container.appendChild(canvas)
99
- document.body.appendChild(container)
104
+ // Append directly to body, taken out of flow with position:fixed + z-index:-1
105
+ // so it sits behind the page's content (covered by body/main backgrounds)
106
+ // while still being painted. visibility:hidden / opacity:0 / left:-9999px
107
+ // skip the paint pass and trigger "No cached paint record".
108
+ canvas.style.cssText = 'position:fixed;top:0;left:0;z-index:-1;'
109
+ document.body.appendChild(canvas)
100
110
 
101
111
  try {
102
- await new Promise(r => requestAnimationFrame(r))
112
+ canvas.getBoundingClientRect()
113
+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))
114
+
103
115
  const ctx2d = canvas.getContext('2d')
104
- if (!ctx2d || typeof ctx2d.drawElementImage !== 'function') {
105
- throw new Error('drawElementImage not available')
116
+ const fn = ctx2d && (ctx2d[drawApi] || ctx2d.drawElement || ctx2d.drawElementImage)
117
+ if (typeof fn !== 'function') {
118
+ throw new Error('drawElement / drawElementImage not available on this canvas context')
106
119
  }
107
120
  ctx2d.save()
108
121
  ctx2d.scale(dpr * scale, dpr * scale)
109
- ctx2d.drawElementImage(wrapper, 0, 0, width, height)
122
+ fn.call(ctx2d, wrapper, 0, 0, width, height)
110
123
  ctx2d.restore()
111
124
  return canvas
125
+ } catch (e) {
126
+ if (e && /paint record/i.test(e.message || '')) {
127
+ throw new Error('Browser had no paint record for the element. Make sure the document is fully loaded and visible before calling html-in-canvas (drawElement requires a real paint pass).')
128
+ }
129
+ throw e
112
130
  } finally {
113
- try {
114
- document.body.removeChild(container)
115
- } catch {}
131
+ try { canvas.remove() } catch {}
116
132
  }
117
133
  }
118
134
  }
package/index.js CHANGED
@@ -12,5 +12,5 @@ export { replaceText } from './replace-text.js';
12
12
  export { filter } from './filter.js';
13
13
  export { colorTint } from './color-tint.js';
14
14
  export { pdfImage } from './pdf-image.js';
15
- export { promptExport } from './prompt-export.js';
15
+ export { agentMap } from './agent-map.js';
16
16
  // export { htmlInCanvas } from './html-in-canvas.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-plugins",
3
- "version": "1.2.0",
3
+ "version": "2.1.0",
4
4
  "description": "Official plugins for SnapDOM",
5
5
  "type": "module",
6
6
  "exports": {
@@ -12,7 +12,7 @@
12
12
  "./color-tint": "./color-tint.js",
13
13
  "./html-in-canvas": "./html-in-canvas.js",
14
14
  "./pdf-image": "./pdf-image.js",
15
- "./prompt-export": "./prompt-export.js"
15
+ "./agent-map": "./agent-map.js"
16
16
  },
17
17
  "files": [
18
18
  "*.js",
package/prompt-export.js DELETED
@@ -1,550 +0,0 @@
1
- /**
2
- * promptExport – Official SnapDOM Plugin
3
- * Produces an LLM-ready package: annotated screenshot + structured element
4
- * map + prompt text. Tuned for vision-capable LLMs reading the image + map
5
- * together (Set-of-Mark pattern).
6
- *
7
- * Usage:
8
- * import { promptExport } from '@zumer/snapdom-plugins/prompt-export';
9
- * const result = await snapdom(el, { plugins: [promptExport()] });
10
- * const { image, elements, dimensions, prompt } = await result.toPrompt();
11
- *
12
- * @param {Object} [options]
13
- * @param {boolean} [options.annotate=true] - Overlay numbered badges on interactive elements
14
- * @param {string} [options.imageFormat='png'] - Output image format ('png'|'jpg'|'webp')
15
- * @param {number} [options.imageQuality=0.8] - Quality for lossy formats (0..1)
16
- * @param {number} [options.maxImageWidth=1024] - Max width in px (downscales if larger)
17
- * @param {string} [options.interactiveSelector] - Custom CSS selector for interactive elements
18
- * @param {string} [options.semanticSelector] - Custom CSS selector for semantic elements
19
- * @param {Object} [options.labelStyle={}] - Override styles for annotation badges
20
- * @param {'compact'|'verbose'} [options.promptMode='compact'] - Prompt text verbosity
21
- * @param {boolean} [options.includeCoords=true] - Include bbox in the prompt text
22
- * @param {string[]} [options.include] - Which fields to return. Default
23
- * ['elements', 'prompt']. For vision-dependent tasks (chart content, layout QA,
24
- * canvas) pass ['image', 'elements', 'prompt'] or add 'image' to the array. For
25
- * text-only agent prompts pass ['prompt'] (cheapest — skips canvas draw entirely).
26
- * Accepted values: 'image', 'elements', 'prompt'.
27
- * @returns {Object} SnapDOM plugin
28
- */
29
-
30
- const DEFAULT_INTERACTIVE =
31
- 'a[href], button, input, select, textarea, ' +
32
- '[role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], ' +
33
- '[tabindex]:not([tabindex="-1"]), summary, [contenteditable="true"]';
34
-
35
- const DEFAULT_SEMANTIC =
36
- 'h1, h2, h3, h4, h5, h6, p, li, img[alt], nav, main, article, section, ' +
37
- 'header, footer, label, td, th, figcaption, blockquote, legend';
38
-
39
- const COLLECTED_ATTRS = [
40
- 'role', 'aria-label', 'aria-expanded', 'aria-checked', 'aria-disabled',
41
- 'alt', 'href', 'placeholder', 'name', 'type', 'value', 'title', 'disabled',
42
- ];
43
-
44
- const VISUAL_FIELDS = [
45
- 'display', 'visibility', 'opacity',
46
- 'color', 'backgroundColor',
47
- 'fontSize', 'fontWeight',
48
- 'cursor', 'overflow',
49
- ];
50
-
51
- // Common computed-style values that carry no information. Keeping the
52
- // `styles` object small is the difference between a useful LLM input and
53
- // token bloat on every element.
54
- const VISUAL_SKIP = new Set(['initial', 'normal', 'visible', 'auto', 'static', '0']);
55
- function isDefaultStyleValue(prop, value) {
56
- if (!value) return true;
57
- if (VISUAL_SKIP.has(value)) return true;
58
- if (prop === 'cursor' && value === 'none') return true;
59
- if (prop === 'color' && value === 'rgb(0, 0, 0)') return true;
60
- if (prop === 'backgroundColor' && value === 'rgba(0, 0, 0, 0)') return true;
61
- if (prop === 'fontWeight' && (value === '400' || value === 'normal')) return true;
62
- if (prop === 'opacity' && value === '1') return true;
63
- return false;
64
- }
65
-
66
- // Default omits 'image'. Benchmarking showed the text + JSON map is enough
67
- // to answer most UI-inspection questions and uses ~14× fewer tokens. Pass
68
- // `include: ['image', 'elements', 'prompt']` explicitly when the task truly
69
- // depends on vision (charts, canvas content, layout QA).
70
- const DEFAULT_INCLUDE = ['elements', 'prompt'];
71
-
72
- export function promptExport(options = {}) {
73
- const {
74
- annotate = true,
75
- imageFormat = 'png',
76
- imageQuality = 0.8,
77
- maxImageWidth = 1024,
78
- interactiveSelector = DEFAULT_INTERACTIVE,
79
- semanticSelector = DEFAULT_SEMANTIC,
80
- labelStyle = {},
81
- promptMode = 'compact',
82
- includeCoords = true,
83
- include = DEFAULT_INCLUDE,
84
- } = options;
85
-
86
- return {
87
- name: 'prompt-export',
88
-
89
- afterClone(ctx) {
90
- const meta = extractMetadata(ctx.element, interactiveSelector, semanticSelector);
91
- // snapdom spreads a fresh ctx for the export phase from ctx.options,
92
- // so write to both so the prompt() call below can read it.
93
- ctx.__promptMetadata = meta;
94
- if (ctx.options) ctx.options.__promptMetadata = meta;
95
-
96
- if (annotate) {
97
- addAnnotations(ctx.clone, meta.elements, labelStyle);
98
- }
99
- },
100
-
101
- defineExports() {
102
- return {
103
- prompt: async (ctx, opts = {}) => {
104
- const meta = ctx.__promptMetadata;
105
- const wantSet = new Set(opts.include || include || DEFAULT_INCLUDE);
106
- const wantImage = wantSet.has('image');
107
- const wantElements = wantSet.has('elements');
108
- const wantPrompt = wantSet.has('prompt');
109
-
110
- if (!meta || !meta.elements.length) {
111
- const empty = { dimensions: { width: 0, height: 0 } };
112
- if (wantImage) empty.image = ctx.export.url;
113
- if (wantElements) empty.elements = [];
114
- if (wantPrompt) empty.prompt = '';
115
- return empty;
116
- }
117
-
118
- const format = opts.imageFormat || imageFormat;
119
- const quality = opts.imageQuality || imageQuality;
120
- const maxWidth = opts.maxImageWidth || maxImageWidth;
121
- const mode = opts.promptMode || promptMode;
122
- const withCoords = opts.includeCoords !== undefined ? opts.includeCoords : includeCoords;
123
-
124
- // Only load + rasterize the SVG when the caller actually wants the
125
- // image. Skipping saves the img decode + canvas draw + toDataURL —
126
- // the most expensive steps of this export.
127
- let w, h, dataURL;
128
- if (wantImage) {
129
- const img = new Image();
130
- img.src = ctx.export.url;
131
- await new Promise((res, rej) => { img.onload = res; img.onerror = rej; });
132
- const ratio = img.naturalWidth > maxWidth ? maxWidth / img.naturalWidth : 1;
133
- w = Math.round(img.naturalWidth * ratio);
134
- h = Math.round(img.naturalHeight * ratio);
135
- const canvas = document.createElement('canvas');
136
- canvas.width = w;
137
- canvas.height = h;
138
- canvas.getContext('2d').drawImage(img, 0, 0, w, h);
139
- const mime =
140
- format === 'jpg' || format === 'jpeg' ? 'image/jpeg'
141
- : format === 'webp' ? 'image/webp'
142
- : 'image/png';
143
- dataURL = canvas.toDataURL(mime, quality);
144
- } else {
145
- // No image — scale bboxes to the same target width the image would
146
- // have used, so downstream callers can still render the map over
147
- // a separately-rendered screenshot at the same scale.
148
- const sourceW = meta.dimensions.width || 1;
149
- const ratio = sourceW > maxWidth ? maxWidth / sourceW : 1;
150
- w = Math.round(sourceW * ratio);
151
- h = Math.round(meta.dimensions.height * ratio);
152
- }
153
-
154
- const sx = w / (meta.dimensions.width || 1);
155
- const sy = h / (meta.dimensions.height || 1);
156
-
157
- const scaledElements = meta.elements.map((el) => ({
158
- ...el,
159
- bbox: {
160
- x: Math.round(el.bbox.x * sx),
161
- y: Math.round(el.bbox.y * sy),
162
- width: Math.round(el.bbox.width * sx),
163
- height: Math.round(el.bbox.height * sy),
164
- },
165
- }));
166
-
167
- const emitCoords = mode === 'verbose' ? true : (withCoords && !annotate);
168
- const promptText = (wantPrompt)
169
- ? (mode === 'verbose'
170
- ? formatPromptVerbose(scaledElements, { width: w, height: h }, emitCoords)
171
- : formatPromptCompact(scaledElements, { width: w, height: h }, emitCoords))
172
- : null;
173
-
174
- const out = { dimensions: { width: w, height: h } };
175
- if (wantImage) out.image = dataURL;
176
- if (wantElements) out.elements = scaledElements;
177
- if (wantPrompt) out.prompt = promptText;
178
- return out;
179
- },
180
- };
181
- },
182
- };
183
- }
184
-
185
- /* ── Accessible name ──────────────────────────── */
186
-
187
- function truncate(str, max) {
188
- if (!str) return '';
189
- if (str.length <= max) return str;
190
- return str.slice(0, max - 1) + '…';
191
- }
192
-
193
- /**
194
- * Compute the element's accessible name following a simplified WAI-ARIA order.
195
- * This is what an LLM agent reads first to know what the element IS.
196
- */
197
- function accessibleName(el) {
198
- const ariaLabel = el.getAttribute('aria-label');
199
- if (ariaLabel && ariaLabel.trim()) return ariaLabel.trim();
200
-
201
- const labelledBy = el.getAttribute('aria-labelledby');
202
- if (labelledBy) {
203
- const root = el.getRootNode();
204
- const getById = (id) =>
205
- root && typeof root.getElementById === 'function'
206
- ? root.getElementById(id)
207
- : document.getElementById(id);
208
- const parts = labelledBy.trim().split(/\s+/)
209
- .map((id) => {
210
- const ref = getById(id);
211
- return ref ? (ref.textContent || '').trim() : '';
212
- })
213
- .filter(Boolean);
214
- if (parts.length) return parts.join(' ');
215
- }
216
-
217
- if (el.tagName === 'IMG') {
218
- const alt = el.getAttribute('alt');
219
- if (alt && alt.trim()) return alt.trim();
220
- }
221
-
222
- const title = el.getAttribute('title');
223
- if (title && title.trim()) return title.trim();
224
-
225
- if (el.labels && el.labels[0]) {
226
- const t = (el.labels[0].textContent || '').trim();
227
- if (t) return t;
228
- }
229
-
230
- const text = (el.textContent || '').trim();
231
- return text ? truncate(text, 40) : '';
232
- }
233
-
234
- /* ── DOM state ────────────────────────────────── */
235
-
236
- /**
237
- * Capture real runtime state (not just ARIA attributes). This is what
238
- * separates a useful map from a static screenshot annotation: an agent can
239
- * see "checkbox is unchecked / select has value=X / details is closed".
240
- */
241
- function computeState(el) {
242
- const state = {};
243
- try {
244
- if (el.matches(':checked')) state.checked = true;
245
- if (el.matches(':disabled')) state.disabled = true;
246
- if (el.matches(':focus')) state.focus = true;
247
- } catch { /* some selectors may fail on exotic nodes */ }
248
-
249
- const tag = el.tagName;
250
- if (tag === 'INPUT') {
251
- // Checkbox/radio: `value` defaults to "on" when no explicit value attr
252
- // is set — noise. The meaningful signal is `checked`. Skip value here.
253
- const type = (el.type || 'text').toLowerCase();
254
- if (type !== 'checkbox' && type !== 'radio' && el.value) {
255
- state.value = el.value;
256
- }
257
- } else if (tag === 'TEXTAREA') {
258
- if (el.value) state.value = el.value;
259
- } else if (tag === 'SELECT') {
260
- state.value = el.value;
261
- const opt = el.options && el.options[el.selectedIndex];
262
- if (opt) state.selectedText = opt.text || '';
263
- } else if (tag === 'DETAILS') {
264
- state.open = !!el.open;
265
- } else if (el.hasAttribute && el.hasAttribute('open')) {
266
- state.open = true;
267
- }
268
-
269
- return Object.keys(state).length ? state : null;
270
- }
271
-
272
- /* ── Visual styles ────────────────────────────── */
273
-
274
- /**
275
- * Pull a small set of visually-meaningful computed styles. Reads from the
276
- * live element (the clone uses class-based styling so its inline style is
277
- * empty and a detached `getComputedStyle(cloneNode)` returns initial values).
278
- * The computed style of the original is what snapdom used to build the
279
- * capture, so the result matches what the screenshot shows.
280
- */
281
- function computeVisualStyles(el) {
282
- let cs;
283
- try { cs = getComputedStyle(el); } catch { return null; }
284
- if (!cs) return null;
285
- const out = {};
286
- for (const prop of VISUAL_FIELDS) {
287
- const v = cs[prop];
288
- if (isDefaultStyleValue(prop, v)) continue;
289
- out[prop] = v;
290
- }
291
- return Object.keys(out).length ? out : null;
292
- }
293
-
294
- /* ── Covered detection ────────────────────────── */
295
-
296
- /**
297
- * True when another element is painted on top of the center of this one.
298
- * An agent that knows a button is covered by a modal won't try to click it.
299
- */
300
- function isCovered(el, rect) {
301
- if (!rect.width || !rect.height) return false;
302
- const cx = rect.left + rect.width / 2;
303
- const cy = rect.top + rect.height / 2;
304
- if (cx < 0 || cy < 0) return false;
305
- const doc = el.ownerDocument || document;
306
- if (!doc.elementFromPoint) return false;
307
- const top = doc.elementFromPoint(cx, cy);
308
- if (!top || top === el) return false;
309
- if (el.contains && el.contains(top)) return false;
310
- return true;
311
- }
312
-
313
- /* ── Metadata extraction ──────────────────────── */
314
-
315
- function extractMetadata(element, interactiveSelector, semanticSelector) {
316
- const rootRect = element.getBoundingClientRect();
317
- const elements = [];
318
- let id = 0;
319
-
320
- const tracked = new Set();
321
-
322
- for (const el of element.querySelectorAll(interactiveSelector)) {
323
- const entry = buildEntry(el, rootRect, id, 'interactive');
324
- if (entry) {
325
- elements.push(entry);
326
- tracked.add(el);
327
- id++;
328
- }
329
- }
330
-
331
- for (const el of element.querySelectorAll(semanticSelector)) {
332
- if (tracked.has(el)) continue;
333
- const entry = buildEntry(el, rootRect, id, 'semantic');
334
- if (entry) {
335
- elements.push(entry);
336
- id++;
337
- }
338
- }
339
-
340
- return {
341
- elements,
342
- dimensions: { width: rootRect.width, height: rootRect.height },
343
- };
344
- }
345
-
346
- function buildEntry(el, rootRect, id, type) {
347
- const rect = el.getBoundingClientRect();
348
- const bbox = {
349
- x: Math.round(rect.left - rootRect.left),
350
- y: Math.round(rect.top - rootRect.top),
351
- width: Math.round(rect.width),
352
- height: Math.round(rect.height),
353
- };
354
-
355
- if (bbox.width <= 0 && bbox.height <= 0) return null;
356
-
357
- const tag = el.tagName.toLowerCase();
358
- const maxText = type === 'interactive' ? 200 : 120;
359
- const text = (el.textContent || '').trim().slice(0, maxText);
360
-
361
- const attributes = {};
362
- for (const attr of COLLECTED_ATTRS) {
363
- const val = el.getAttribute(attr);
364
- if (val == null || val === '' || val === 'false') continue;
365
- attributes[attr] = val;
366
- }
367
-
368
- // For <img>, replace the (potentially long, cache-busted) src with just the
369
- // filename — "logo.svg" is more useful to an LLM than the full URL.
370
- if (tag === 'img' && el.src) {
371
- try {
372
- const base = (el.ownerDocument && el.ownerDocument.location)
373
- ? el.ownerDocument.location.href
374
- : (typeof location !== 'undefined' ? location.href : undefined);
375
- const url = base ? new URL(el.src, base) : new URL(el.src);
376
- attributes.src = url.pathname.split('/').pop() || el.src;
377
- } catch {
378
- attributes.src = el.src;
379
- }
380
- }
381
-
382
- const entry = {
383
- id,
384
- tag,
385
- type,
386
- name: accessibleName(el),
387
- text,
388
- bbox,
389
- attributes,
390
- };
391
-
392
- const styles = computeVisualStyles(el);
393
- if (styles) entry.styles = styles;
394
-
395
- if (type === 'interactive') {
396
- const state = computeState(el);
397
- if (state) {
398
- // Drop state.value when it just echoes attributes.value — no
399
- // divergence between the initial HTML attribute and the current
400
- // property, nothing for the LLM to learn from the repeat.
401
- if (state.value !== undefined && state.value === attributes.value) {
402
- delete state.value;
403
- }
404
- if (Object.keys(state).length) entry.state = state;
405
- }
406
- if (isCovered(el, rect)) entry.covered = true;
407
- }
408
-
409
- return entry;
410
- }
411
-
412
- /* ── Visual annotations ───────────────────────── */
413
-
414
- function addAnnotations(clone, elements, customStyle) {
415
- const interactive = elements.filter((e) => e.type === 'interactive');
416
- if (!interactive.length) return;
417
-
418
- const overlay = document.createElement('div');
419
- overlay.setAttribute('data-snap-prompt-overlay', 'true');
420
- Object.assign(overlay.style, {
421
- position: 'absolute',
422
- top: '0',
423
- left: '0',
424
- width: '100%',
425
- height: '100%',
426
- pointerEvents: 'none',
427
- zIndex: '2147483647',
428
- overflow: 'visible',
429
- });
430
-
431
- for (const el of interactive) {
432
- const badge = document.createElement('span');
433
- badge.textContent = String(el.id);
434
- badge.setAttribute('data-snap-prompt-label', String(el.id));
435
- // Center the badge on the element's bbox, not on its top-left corner:
436
- // `translate(-50%, -50%)` offsets from the anchor point.
437
- const cx = el.bbox.x + el.bbox.width / 2;
438
- const cy = el.bbox.y + el.bbox.height / 2;
439
- Object.assign(badge.style, {
440
- position: 'absolute',
441
- left: `${cx}px`,
442
- top: `${cy}px`,
443
- transform: 'translate(-50%, -50%)',
444
- minWidth: '18px',
445
- height: '18px',
446
- lineHeight: '18px',
447
- fontSize: '11px',
448
- fontWeight: '700',
449
- fontFamily: 'system-ui, -apple-system, sans-serif',
450
- color: '#fff',
451
- backgroundColor: 'rgba(220, 38, 38, 0.92)',
452
- borderRadius: '9px',
453
- textAlign: 'center',
454
- padding: '0 4px',
455
- boxSizing: 'border-box',
456
- boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
457
- ...customStyle,
458
- });
459
- overlay.appendChild(badge);
460
- }
461
-
462
- clone.style.position = 'relative';
463
- clone.appendChild(overlay);
464
- }
465
-
466
- /* ── Prompt text formatters ───────────────────── */
467
-
468
- function stateToStr(state) {
469
- if (!state) return '';
470
- const flags = [];
471
- const pairs = [];
472
- for (const k of Object.keys(state)) {
473
- const v = state[k];
474
- if (v === true) flags.push(k);
475
- else pairs.push(`${k}=${JSON.stringify(v)}`);
476
- }
477
- if (!flags.length && !pairs.length) return '';
478
- return ` {${[...flags, ...pairs].join(', ')}}`;
479
- }
480
-
481
- function coordsToStr(bbox) {
482
- return ` (${bbox.x},${bbox.y} ${bbox.width}×${bbox.height})`;
483
- }
484
-
485
- function formatPromptCompact(elements, dimensions, withCoords) {
486
- const lines = [`Screenshot (${dimensions.width}×${dimensions.height}px).`];
487
-
488
- const interactive = elements.filter((e) => e.type === 'interactive');
489
- const semantic = elements.filter((e) => e.type === 'semantic');
490
-
491
- if (interactive.length) {
492
- lines.push('', 'Interactive:');
493
- for (const el of interactive) {
494
- const name = el.name ? ` "${truncate(el.name, 60)}"` : '';
495
- const st = stateToStr(el.state);
496
- const cov = el.covered ? ' (covered)' : '';
497
- const coords = withCoords ? coordsToStr(el.bbox) : '';
498
- lines.push(` [${el.id}] ${el.tag}${name}${st}${cov}${coords}`);
499
- }
500
- }
501
-
502
- if (semantic.length) {
503
- lines.push('', 'Semantic:');
504
- for (const el of semantic) {
505
- const name = el.name ? ` "${truncate(el.name, 60)}"` : '';
506
- lines.push(` [${el.id}] ${el.tag}${name}`);
507
- }
508
- }
509
-
510
- return lines.join('\n');
511
- }
512
-
513
- function formatPromptVerbose(elements, dimensions, withCoords) {
514
- const lines = [
515
- `Screenshot of a web page (${dimensions.width}×${dimensions.height}px).`,
516
- '',
517
- ];
518
-
519
- const interactive = elements.filter((e) => e.type === 'interactive');
520
- const semantic = elements.filter((e) => e.type === 'semantic');
521
-
522
- if (interactive.length) {
523
- lines.push('Interactive elements:');
524
- for (const el of interactive) {
525
- const name = el.name ? ` "${truncate(el.name, 80)}"` : '';
526
- const attrParts = Object.entries(el.attributes).map(([k, v]) => `${k}="${v}"`);
527
- const attrs = attrParts.length ? ' ' + attrParts.join(' ') : '';
528
- const pos = withCoords ? coordsToStr(el.bbox) : '';
529
- const st = stateToStr(el.state);
530
- const cov = el.covered ? ' (covered)' : '';
531
- lines.push(` [${el.id}] <${el.tag}>${name}${pos}${attrs}${st}${cov}`);
532
- }
533
- lines.push('');
534
- }
535
-
536
- if (semantic.length) {
537
- lines.push('Semantic structure:');
538
- for (const el of semantic) {
539
- const name = el.name ? ` "${truncate(el.name, 80)}"` : '';
540
- const attrParts = [];
541
- if (el.attributes.alt) attrParts.push(`alt="${el.attributes.alt}"`);
542
- if (el.attributes.role) attrParts.push(`role="${el.attributes.role}"`);
543
- const attrs = attrParts.length ? ' ' + attrParts.join(' ') : '';
544
- lines.push(` [${el.id}] <${el.tag}>${name}${attrs}`);
545
- }
546
- lines.push('');
547
- }
548
-
549
- return lines.join('\n');
550
- }