@stefan.inc/feedback-engine 1.11.0 → 1.12.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
@@ -200,6 +200,23 @@ export function Feedback() {
200
200
  - To keep Feedback off a production deploy, render `<Feedback />` only where you want it, for example behind `process.env.NEXT_PUBLIC_VERCEL_ENV !== 'production'`.
201
201
  - [Post to ProcrastiMate](#post-to-procrastimate) works the same in Next.js as in Vite: pass `procrastimate: { projects: ['Your Project'] }` to `setupFeedbackEngine()`.
202
202
 
203
+ ## Attach state to reproduce a report
204
+
205
+ ```ts
206
+ setupFeedbackEngine({
207
+ metadata: () => ({ 'Signed in as': store.user?.email ?? 'nobody' }),
208
+ files: [
209
+ { name: 'store.json', data: () => store.snapshot() },
210
+ { name: 'history.json', data: () => fetchHistory() },
211
+ ],
212
+ });
213
+ ```
214
+
215
+ - `metadata` adds `label: value` lines under the image export's title. They are also the first entries of `environment` in `feedback.json`, after `App`.
216
+ - `files` adds the app's own files to every export but the image: **Data**, **Image + Data**, ProcrastiMate, and webhooks. Each `data` runs when the capture is taken, so the files match the screenshot. It returns a `Blob`, a string, or any other value, which is written as JSON, or a promise of one. `null` leaves the file out, for a screen that has nothing to put in it. Pass `type` to set the media type. A file whose `data` throws, or takes longer than 10 seconds, is left out, and the editor names it in a red toast.
217
+ - A name may not repeat or be one of Feedback's own, `feedback.json` and `feedback.png`. `setupFeedbackEngine()` throws on one.
218
+ - A ZIP deflates each file that shrinks, so a large JSON state stays small. ProcrastiMate attaches each file to the task, in parts when it is over 16 MB, and a webhook gets each as a `file` part.
219
+
203
220
  ## Component data and untagged content
204
221
 
205
222
  Data reads like code, with the limits of the iOS package: `{kg: 72.575, note: null}` for a plain object, `Entry(kg: 72.575, note: null)` for a class instance, 3 decimals, 3 levels, 10 elements, and 1,500 characters. Functions and DOM nodes are skipped at any depth. Give a class a `toFeedback()` method to choose how it reads.
@@ -223,7 +240,7 @@ The editor works as on iOS, with these differences:
223
240
  - Hover the screenshot to see what a click would select.
224
241
  - Hold Ctrl and scroll, or pinch on a trackpad, to zoom up to 4×.
225
242
  - Enter adds the feedback. Shift with Enter adds a line.
226
- - **Share** lists **Image**, **JSON**, and **Image and JSON (ZIP)**. Each one then offers **Copy Feedback**, **Save File**, and, where the browser can share files, **Share…**. A browser takes one clipboard item per copy, so copying the ZIP export puts one item on the clipboard with the image and the JSON, and the place you paste into picks the one it reads.
243
+ - **Share** lists the destinations that have no button beside it, then **Image**, **Data**, and **Image + Data**, then **New Webhook**. **Data** is `feedback.json`, or a `feedback.zip` of it and the app's [files](#attach-state-to-reproduce-a-report) when there are any. **Image + Data** is always one `feedback.zip`. Each export then offers **Copy Feedback**, **Save File**, and, where the browser can share files, **Share…**. A browser takes one clipboard item per copy, so copying **Image + Data** puts one item on the clipboard with the image and the JSON, and the place you paste into picks the one it reads.
227
244
 
228
245
  ## Post to ProcrastiMate
229
246
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stefan.inc/feedback-engine",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "In-app feedback for Svelte and React: point at a component, write what should change, and export its name, file:line, and data for an agent.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -196,6 +196,29 @@ Do this after changing a screen, against the dev server, with realistic data:
196
196
  4. Spot-check with real clicks on the regions you changed and read the selection title in the panel. Open the editor with `await page.evaluate(() => __feedbackEngine.present())`, or the way a person does, with Alt+Meta+click: `await page.getByRole('heading').first().click({ modifiers: ['Alt', 'Meta'] })`. The screenshot is scaled, so convert page points with the bounding box of the element with the role `img` and the name `Screenshot`.
197
197
  5. Check a production build once: components keep their names and locations there, and untagged elements lose their `file:line`.
198
198
 
199
+ ## State to reproduce a report (web)
200
+
201
+ A screenshot shows what went wrong, not how to get back there. Give the export what reproduces the screen. Every function runs when the capture is taken, so what it returns matches the screenshot.
202
+
203
+ ```ts
204
+ setupFeedbackEngine({
205
+ // `label: value` lines under the image's title, and the first `environment` entries of feedback.json.
206
+ metadata: () => ({ 'Signed in as': store.user?.email ?? 'nobody', 'Plan': store.plan }),
207
+ // Files in every export but the image: Data, Image + Data, ProcrastiMate, and webhooks.
208
+ files: [
209
+ { name: 'store.json', data: () => store.snapshot() }, // any value is written as JSON
210
+ { name: 'log.txt', data: () => log.join('\n') }, // a string is text
211
+ { name: 'history.json', data: () => fetchHistory() }, // a promise works too
212
+ { name: 'draft.json', data: () => editor?.draft ?? null }, // null leaves the file out
213
+ ],
214
+ });
215
+ ```
216
+
217
+ - `metadata` is one short line per fact a reader needs at a glance, such as who is signed in or which mode is on. Keep it to a few lines: the image prints every one.
218
+ - `context(name, () => value)` stays for state worth reading in `feedback.json` without opening a file. It is described like component data and cut at 8,000 characters, so a whole store belongs in `files`.
219
+ - Give `files` the formats the app already loads, such as its save file, so the person who reads the report can open the same state. Don't invent a format for feedback.
220
+ - A file whose `data` throws or takes longer than 10 seconds is left out and named in a red toast in the editor. The rest of the export still goes.
221
+
199
222
  ## Replay every tap
200
223
 
201
224
  `scripts/taps.js`, in this skill's folder, reads a `feedback.json` from any package. It is plain JavaScript, so `node` or `bun` runs it. In a web app it ships with the package:
@@ -8,20 +8,30 @@ import {
8
8
  type ContextEntry,
9
9
  type Frame,
10
10
  } from '../core/index.ts';
11
+ import { makeFiles, type FeedbackFile, type FileFailure } from './files.ts';
11
12
  import { readScene, type Scene } from './scene.ts';
12
13
  import { takePicture, type Picture } from './screenshot.ts';
13
14
 
14
15
  /**
15
16
  * A capture and its picture. `image` is the whole picture on one canvas, at the screen's pixel ratio or lower when the
16
17
  * capture is too large for one, which the editor shows until it draws the part in view sharp. `pixelRatio` is the
17
- * screen's, the resolution an export aims for.
18
+ * screen's, the resolution an export aims for. `files` are the app's own, made at the moment of the capture.
18
19
  */
19
- export type Screen = { capture: Capture; picture: Picture; image: HTMLCanvasElement; pixelRatio: number };
20
+ export type Screen = {
21
+ capture: Capture;
22
+ picture: Picture;
23
+ image: HTMLCanvasElement;
24
+ pixelRatio: number;
25
+ files: File[];
26
+ failures: FileFailure[];
27
+ };
20
28
 
21
29
  export type CaptureOptions = {
22
30
  app?: string;
23
31
  version?: string;
32
+ metadata?: () => Record<string, string>;
24
33
  context: { name: string; value: () => unknown }[];
34
+ files?: FeedbackFile[];
25
35
  };
26
36
 
27
37
  function browser() {
@@ -37,9 +47,19 @@ function browser() {
37
47
  return match ? `${match[1] === 'Edg' ? 'Edge' : match[1]} ${match[2]} · ${platform}` : agent;
38
48
  }
39
49
 
50
+ function metadata(options: CaptureOptions): ContextEntry[] {
51
+ try {
52
+ return Object.entries(options.metadata?.() ?? {}).map(([name, value]) => ({ name, value: String(value) }));
53
+ } catch (error) {
54
+ console.warn('Feedback could not read the metadata', error);
55
+ return [];
56
+ }
57
+ }
58
+
40
59
  function environment(options: CaptureOptions, date: Date): ContextEntry[] {
41
60
  const entries: (ContextEntry | false | undefined)[] = [
42
61
  { name: 'App', value: options.app ?? (document.title || location.hostname) },
62
+ ...metadata(options),
43
63
  { name: 'Location', value: `${location.pathname}${location.search}${location.hash}` },
44
64
  options.version !== undefined && { name: 'Version', value: options.version },
45
65
  { name: 'Device', value: browser() },
@@ -48,7 +68,6 @@ function environment(options: CaptureOptions, date: Date): ContextEntry[] {
48
68
  value: `${innerWidth} × ${innerHeight} px @${Math.round(devicePixelRatio * 100) / 100}x · ${matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'} mode`,
49
69
  },
50
70
  { name: 'Captured', value: date.toISOString().replace(/\.\d+Z$/, 'Z') },
51
- { name: 'Locale', value: navigator.language },
52
71
  ];
53
72
  return entries.filter(entry => !!entry);
54
73
  }
@@ -115,8 +134,10 @@ export const captureTree = (options: CaptureOptions) => readPage(options).captur
115
134
 
116
135
  /** Reads the page and copies it. */
117
136
  export async function captureScreen(options: CaptureOptions): Promise<Screen> {
137
+ const made = makeFiles(options.files ?? []);
118
138
  const { capture, scene, top } = readPage(options);
119
139
  const picture = await takePicture(scene.size, top, capture.visible, scene.fixed);
120
140
  const pixelRatio = devicePixelRatio;
121
- return { capture, picture, image: picture.canvas(pixelRatio), pixelRatio };
141
+ const { files, failures } = await made;
142
+ return { capture, picture, image: picture.canvas(pixelRatio), pixelRatio, files, failures };
122
143
  }
@@ -0,0 +1,75 @@
1
+ /** A file the app adds to every export, made when a capture is taken. */
2
+ export type FeedbackFile = {
3
+ /** The file's name in every export, such as `save.json`. */
4
+ name: string;
5
+ /**
6
+ * Makes the file when a capture is taken, so it matches the screenshot. A `Blob` is used as it is, a string as text,
7
+ * and anything else as JSON. `null` or `undefined` leaves the file out, for a screen that has nothing to put in it.
8
+ */
9
+ data: () => unknown;
10
+ /** The media type. Without it, a `Blob` keeps its own, `.json` is `application/json`, and other text is `text/plain`. */
11
+ type?: string;
12
+ };
13
+
14
+ /** A file the app registered that could not be made, and why. */
15
+ export type FileFailure = { name: string; error: unknown };
16
+
17
+ /** How long the editor waits for a file before it opens without it. */
18
+ export const fileSeconds = 10;
19
+
20
+ /** Names the package's own files take in an export. */
21
+ const reserved = new Set(['feedback.json', 'feedback.png', 'feedback.jpg']);
22
+
23
+ /** Throws at setup on a name that would collide in a ZIP, so a bad list fails before anyone captures. */
24
+ export function checkFiles(files: FeedbackFile[]) {
25
+ const seen = new Set<string>();
26
+ for (const { name } of files) {
27
+ if (!name || name.includes('/')) throw new Error(`A feedback file needs a plain file name, not "${name}".`);
28
+ if (reserved.has(name)) throw new Error(`${name} is Feedback's own file. Give the app's file another name.`);
29
+ if (seen.has(name)) throw new Error(`Two feedback files are named ${name}.`);
30
+ seen.add(name);
31
+ }
32
+ }
33
+
34
+ function toFile({ name, type }: FeedbackFile, value: unknown): File | undefined {
35
+ if (value === null || value === undefined) return undefined;
36
+ if (value instanceof Blob) return new File([value], name, { type: type ?? value.type });
37
+ const json = typeof value !== 'string';
38
+ const text = json ? JSON.stringify(value) : value;
39
+ if (text === undefined) throw new Error('It is a value JSON cannot write.');
40
+ return new File([text], name, {
41
+ type: type ?? (json || name.endsWith('.json') ? 'application/json' : 'text/plain'),
42
+ });
43
+ }
44
+
45
+ /**
46
+ * Starts every generator at once, in the same task as the capture, so each file is the app's state at that moment.
47
+ * A generator that throws, rejects, or takes longer than `fileSeconds` leaves its file out and is reported, so one
48
+ * broken file never blocks feedback.
49
+ */
50
+ export async function makeFiles(files: FeedbackFile[]): Promise<{ files: File[]; failures: FileFailure[] }> {
51
+ const results = await Promise.allSettled(
52
+ files.map(file => {
53
+ try {
54
+ const made = Promise.resolve(file.data()).then(value => toFile(file, value));
55
+ let timer: ReturnType<typeof setTimeout> | undefined;
56
+ const late = new Promise<never>((_, reject) => {
57
+ timer = setTimeout(
58
+ () => reject(new Error(`It took longer than ${fileSeconds} seconds.`)),
59
+ fileSeconds * 1000,
60
+ );
61
+ });
62
+ return Promise.race([made, late]).finally(() => clearTimeout(timer));
63
+ } catch (error) {
64
+ return Promise.reject(error);
65
+ }
66
+ }),
67
+ );
68
+ const made: File[] = [];
69
+ const failures: FileFailure[] = [];
70
+ results.forEach((result, index) => {
71
+ if (result.status === 'rejected') failures.push({ name: files[index]!.name, error: result.reason });
72
+ else if (result.value) made.push(result.value);
73
+ });
74
+ return { files: made, failures };
75
+ }
@@ -15,8 +15,6 @@ export type ProcrastimateConfig = {
15
15
  space?: string;
16
16
  };
17
17
 
18
- /** ProcrastiMate's `FILE_PART_BYTES` (`shared/images.ts` there): the most it takes as a file in one request. */
19
- export const fileMaxBytes = 16 * 1024 * 1024;
20
18
  export const defaultProcrastimateApp = 'https://procrastimate.stf.lol';
21
19
 
22
20
  export const procrastimateAppURL = (config: ProcrastimateConfig) =>
@@ -2,7 +2,7 @@ import type { Annotations } from '../core/annotations.ts';
2
2
  import { Problem, type Fact } from '../core/problem.ts';
3
3
  import type { Screen } from './capture.ts';
4
4
  import { annotatedImage } from './image.ts';
5
- import { encodeTaskImages, fileMaxBytes, procrastimateAppURL, type ProcrastimateConfig } from './procrastimate.ts';
5
+ import { encodeTaskImages, procrastimateAppURL, type ProcrastimateConfig } from './procrastimate.ts';
6
6
  import { postId } from './webhook.ts';
7
7
 
8
8
  export const FEEDBACK_READY = 'feedback:ready';
@@ -121,7 +121,8 @@ export function runOnLightClick(event: MouseEvent | undefined, action: () => voi
121
121
 
122
122
  /**
123
123
  * Opens ProcrastiMate's `/feedback` popup synchronously (so the browser's click gesture allows `window.open`) while
124
- * encoding the screenshot in parallel, then hands over the draft over `postMessage` once the popup signals ready.
124
+ * encoding the screenshot in parallel, then hands over the draft over `postMessage` once the popup signals ready. The
125
+ * draft carries the app's own files, which ProcrastiMate attaches to the task beside `feedback.json`.
125
126
  * No credential ever leaves ProcrastiMate's own origin.
126
127
  */
127
128
  export function openProcrastimatePopup({
@@ -153,16 +154,6 @@ export function openProcrastimatePopup({
153
154
  const nonce = postId();
154
155
  const url = `${base}/feedback?nonce=${encodeURIComponent(nonce)}`;
155
156
  const environment: Fact[] = screen.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
156
- const reportBytes = new TextEncoder().encode(report).byteLength;
157
- if (reportBytes > fileMaxBytes) {
158
- onerror(
159
- Problem.from(new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.')).with(
160
- [{ label: 'Report', value: `${reportBytes} bytes` }],
161
- environment,
162
- ),
163
- );
164
- return { cancel() {} };
165
- }
166
157
 
167
158
  const popup = window.open(url, 'feedback-procrastimate', popupFeatures());
168
159
  if (!isRealPopup(popup, expectedOrigin, location.origin)) {
@@ -223,6 +214,7 @@ export function openProcrastimatePopup({
223
214
  space: config.space,
224
215
  image,
225
216
  report,
217
+ files: screen.files,
226
218
  },
227
219
  expectedOrigin,
228
220
  );
package/src/dom/share.ts CHANGED
@@ -4,12 +4,12 @@ import type { Screen } from './capture.ts';
4
4
  import { annotatedImage } from './image.ts';
5
5
  import { zip } from './zip.ts';
6
6
 
7
- export type ExportFormat = 'image' | 'json' | 'zip';
7
+ export type ExportFormat = 'image' | 'data' | 'all';
8
8
 
9
9
  export const exportTitles: Record<ExportFormat, string> = {
10
10
  image: 'Image',
11
- json: 'JSON',
12
- zip: 'Image and JSON (ZIP)',
11
+ data: 'Data',
12
+ all: 'Image + Data',
13
13
  };
14
14
 
15
15
  /** One export: the file to save or share, and the parts the clipboard takes. */
@@ -30,16 +30,26 @@ export function encodeImage(screen: Screen, annotations: Annotations, encoding:
30
30
  );
31
31
  }
32
32
 
33
+ /** Every export but the image is the data: `feedback.json` and the app's own files, in this order. */
34
+ export function dataFiles(screen: Screen, json: string): File[] {
35
+ return [new File([json], 'feedback.json', { type: 'application/json' }), ...screen.files];
36
+ }
37
+
38
+ async function archive(files: File[]) {
39
+ const entries = await Promise.all(
40
+ files.map(async file => ({ name: `feedback/${file.name}`, bytes: new Uint8Array(await file.arrayBuffer()) })),
41
+ );
42
+ return new File([await zip(entries)], 'feedback.zip', { type: 'application/zip' });
43
+ }
44
+
45
+ /** Data is `feedback.json` alone, or a ZIP when the app adds files. Image + Data is always a ZIP. */
33
46
  export async function buildExport(screen: Screen, annotations: Annotations, format: ExportFormat): Promise<Export> {
34
- const image = format === 'json' ? undefined : await encodeImage(screen, annotations, { format: 'png' });
35
- const json = format === 'image' ? undefined : reportJSON(screen.capture, annotations);
36
- if (format === 'image') return { file: new File([image!], 'feedback.png', { type: 'image/png' }), image };
37
- if (format === 'json') return { file: new File([json!], 'feedback.json', { type: 'application/json' }), json };
38
- const archive = zip([
39
- { name: 'feedback/feedback.png', bytes: new Uint8Array(await image!.arrayBuffer()) },
40
- { name: 'feedback/feedback.json', bytes: new TextEncoder().encode(json) },
41
- ]);
42
- return { file: new File([archive], 'feedback.zip', { type: 'application/zip' }), image, json };
47
+ const image = format === 'data' ? undefined : await encodeImage(screen, annotations, { format: 'png' });
48
+ if (format === 'image') return { file: image!, image };
49
+ const json = reportJSON(screen.capture, annotations);
50
+ const data = dataFiles(screen, json);
51
+ if (format === 'data') return { file: data.length === 1 ? data[0]! : await archive(data), json };
52
+ return { file: await archive([image!, ...data]), image, json };
43
53
  }
44
54
 
45
55
  /**
@@ -35,7 +35,8 @@ export type WebhookPost = {
35
35
  /**
36
36
  * What a post carries beside its `id` and `title`. An app's webhook sends the image export as PNG and the JSON export,
37
37
  * as `image` and `report`. A saved webhook sends the image and the JSON export if it was saved with them, as `image`
38
- * and `feedback`, and the environment as `device`.
38
+ * and `feedback`, and the environment as `device`. Both send each of the app's own files as a `file` part, a saved
39
+ * webhook only with the JSON export.
39
40
  */
40
41
  export type WebhookContents = { kind: 'report' } | { kind: 'saved'; image?: ImageEncoding; feedback: boolean };
41
42
 
@@ -62,16 +63,14 @@ export async function postFiles(
62
63
  annotations: Annotations,
63
64
  ): Promise<WebhookPost['files']> {
64
65
  const report = () => reportJSON(screen.capture, annotations, false);
66
+ const files = screen.files.map(file => ({ name: 'file', file }));
65
67
  if (contents.kind === 'report') {
66
68
  const image = await encodeImage(screen, annotations, { format: 'png' });
67
- return [
68
- { name: 'image', file: image },
69
- { name: 'report', file: json('feedback.json', report()) },
70
- ];
69
+ return [{ name: 'image', file: image }, { name: 'report', file: json('feedback.json', report()) }, ...files];
71
70
  }
72
71
  return [
73
72
  ...(contents.image ? [{ name: 'image', file: await encodeImage(screen, annotations, contents.image) }] : []),
74
- ...(contents.feedback ? [{ name: 'feedback', file: json('feedback.json', report()) }] : []),
73
+ ...(contents.feedback ? [{ name: 'feedback', file: json('feedback.json', report()) }, ...files] : []),
75
74
  { name: 'device', file: json('device.json', deviceJSON(screen.capture.environment)) },
76
75
  ];
77
76
  }
@@ -111,7 +110,7 @@ export async function postWebhook(webhook: Webhook, post: WebhookPost): Promise<
111
110
  const form = new FormData();
112
111
  form.set('id', post.id);
113
112
  form.set('title', post.title);
114
- for (const { name, file } of post.files) form.set(name, file);
113
+ for (const { name, file } of post.files) form.append(name, file);
115
114
  let response: Response;
116
115
  try {
117
116
  response = await fetch(url, { method: 'POST', headers, body: form });
package/src/dom/zip.ts CHANGED
@@ -10,8 +10,17 @@ function crc32(bytes: Uint8Array) {
10
10
  return (crc ^ 0xffffffff) >>> 0;
11
11
  }
12
12
 
13
- /** A ZIP archive of the files, stored without compression. A PNG is already compressed, and the JSON is small. */
14
- export function zip(files: { name: string; bytes: Uint8Array }[]): Blob {
13
+ async function deflate(bytes: Uint8Array): Promise<Uint8Array | undefined> {
14
+ if (typeof CompressionStream === 'undefined') return undefined;
15
+ const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream('deflate-raw'));
16
+ return new Uint8Array(await new Response(stream).arrayBuffer());
17
+ }
18
+
19
+ /**
20
+ * A ZIP archive of the files. Each is deflated when that makes it smaller, as an app's JSON state does many times over,
21
+ * and stored as it is otherwise, as a PNG is.
22
+ */
23
+ export async function zip(files: { name: string; bytes: Uint8Array }[]): Promise<Blob> {
15
24
  const encoder = new TextEncoder();
16
25
  const parts: Uint8Array[] = [];
17
26
  const directory: Uint8Array[] = [];
@@ -19,12 +28,17 @@ export function zip(files: { name: string; bytes: Uint8Array }[]): Blob {
19
28
  for (const file of files) {
20
29
  const name = encoder.encode(file.name);
21
30
  const crc = crc32(file.bytes);
31
+ const deflated = await deflate(file.bytes);
32
+ const compressed = deflated && deflated.length < file.bytes.length;
33
+ const stored = compressed ? deflated : file.bytes;
34
+ const method = compressed ? 8 : 0;
22
35
  const header = new DataView(new ArrayBuffer(30));
23
36
  header.setUint32(0, 0x04034b50, true);
24
37
  header.setUint16(4, 20, true);
25
38
  header.setUint16(6, 0x0800, true);
39
+ header.setUint16(8, method, true);
26
40
  header.setUint32(14, crc, true);
27
- header.setUint32(18, file.bytes.length, true);
41
+ header.setUint32(18, stored.length, true);
28
42
  header.setUint32(22, file.bytes.length, true);
29
43
  header.setUint16(26, name.length, true);
30
44
  const entry = new DataView(new ArrayBuffer(46));
@@ -32,14 +46,15 @@ export function zip(files: { name: string; bytes: Uint8Array }[]): Blob {
32
46
  entry.setUint16(4, 20, true);
33
47
  entry.setUint16(6, 20, true);
34
48
  entry.setUint16(8, 0x0800, true);
49
+ entry.setUint16(10, method, true);
35
50
  entry.setUint32(16, crc, true);
36
- entry.setUint32(20, file.bytes.length, true);
51
+ entry.setUint32(20, stored.length, true);
37
52
  entry.setUint32(24, file.bytes.length, true);
38
53
  entry.setUint16(28, name.length, true);
39
54
  entry.setUint32(42, offset, true);
40
- parts.push(new Uint8Array(header.buffer), name, file.bytes);
55
+ parts.push(new Uint8Array(header.buffer), name, stored);
41
56
  directory.push(new Uint8Array(entry.buffer), name);
42
- offset += 30 + name.length + file.bytes.length;
57
+ offset += 30 + name.length + stored.length;
43
58
  }
44
59
  const directorySize = directory.reduce((sum, part) => sum + part.length, 0);
45
60
  const end = new DataView(new ArrayBuffer(22));
@@ -38,10 +38,16 @@
38
38
 
39
39
  // The host makes a new editor for each capture, so the first value is the only one.
40
40
  // svelte-ignore state_referenced_locally
41
- const { capture } = screen;
41
+ const { capture, failures } = screen;
42
42
  const session = new Session(capture);
43
43
  // svelte-ignore state_referenced_locally
44
44
  if (engine.pointed) session.pick(engine.pointed);
45
+ if (failures[0]) {
46
+ session.toast = {
47
+ text: `Couldn’t attach ${failures.map(failure => failure.name).join(', ')}`,
48
+ problem: Problem.from(failures[0].error).with([{ label: 'File', value: failures[0].name }]),
49
+ };
50
+ }
45
51
  const maxZoom = 4;
46
52
 
47
53
  /** `Session` is plain TypeScript, so every change to it goes through `act`, and everything drawn reads `view`. */
@@ -107,6 +113,7 @@
107
113
  let editing = $state<{ webhook?: SavedWebhook }>();
108
114
  const targets = $derived(destinations({ ...engine.options, saved }));
109
115
  const pinned = $derived(pinnedDestinations(targets, engine.options.pinned));
116
+ const listed = $derived(targets.filter(target => !pinned.includes(target)));
110
117
  let confirmsClose = $state(false);
111
118
  let pending = $state<{ format: ExportFormat; ready: Export }>();
112
119
  let failure = $state<{ title: string; problem: Problem }>();
@@ -412,15 +419,15 @@
412
419
  </button>
413
420
  {#if showsShare}
414
421
  <div class="popup" role="menu">
415
- {#each Object.entries(exportTitles) as [format, name] (format)}
416
- <button type="button" role="menuitem" onclick={() => void choose(format as ExportFormat)}>{name}</button>
417
- {/each}
418
- {#each targets as destination, index (index)}
422
+ {#each listed as destination, index (index)}
419
423
  <button type="button" role="menuitem" class="destination" onclick={event => send(destination, event)}>
420
424
  {#if destination.image}<img src={destination.image} alt="" />{/if}
421
425
  {destination.name}
422
426
  </button>
423
427
  {/each}
428
+ {#each Object.entries(exportTitles) as [format, name] (format)}
429
+ <button type="button" role="menuitem" onclick={() => void choose(format as ExportFormat)}>{name}</button>
430
+ {/each}
424
431
  <button type="button" role="menuitem" class="destination" onclick={() => edit()}>
425
432
  <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14" /></svg>
426
433
  New Webhook
@@ -3,7 +3,7 @@ import type { ProcrastimateConfig } from '../dom/procrastimate.ts';
3
3
  import { procrastimateIcon } from '../dom/procrastimate-icon.ts';
4
4
  import { githubIcon, type Delivery, type Webhook } from '../dom/webhook.ts';
5
5
 
6
- /** A server the feedback can be posted to, as the Share menu lists it after the exports. */
6
+ /** A server the feedback can be posted to, as the Share menu lists it before the exports. */
7
7
  export type Destination = { name: string; image?: string } & (
8
8
  | { kind: 'procrastimate' }
9
9
  | { kind: 'webhook'; delivery: Delivery }
@@ -37,8 +37,9 @@ export function destinations(options: {
37
37
  }
38
38
 
39
39
  /**
40
- * The destinations that also get a button beside Share: the ones `pinned` names, in its order, or the first two
41
- * without it. A name with no destination is skipped, since a webhook can join the list after setup.
40
+ * The destinations that get a button beside Share instead of an entry in its menu: the ones `pinned` names, in its
41
+ * order, or the first two without it. A name with no destination is skipped, since a webhook can join the list after
42
+ * setup.
42
43
  */
43
44
  export function pinnedDestinations(all: Destination[], pinned: string[] | undefined): Destination[] {
44
45
  if (!pinned) return all.slice(0, 2);
@@ -1,6 +1,7 @@
1
1
  import { tick } from 'svelte';
2
2
  import { Annotations, reportJSON, type FeedbackReport, type Point } from '../core/index.ts';
3
3
  import { captureScreen, captureTree, type Screen } from '../dom/capture.ts';
4
+ import type { FeedbackFile } from '../dom/files.ts';
4
5
  import type { ProcrastimateConfig } from '../dom/procrastimate.ts';
5
6
  import { hostAttribute } from '../dom/tags.ts';
6
7
  import type { Webhook } from '../dom/webhook.ts';
@@ -9,6 +10,16 @@ export type FeedbackOptions = {
9
10
  /** The app's name in exports. Defaults to the document's title. */
10
11
  app?: string;
11
12
  version?: string;
13
+ /**
14
+ * Lines the image export prints under its title, as `label: value`, such as `{ 'Signed in': 'ana@example.com' }`.
15
+ * They are the first entries of the JSON export's `environment` after `App`. Runs when a capture is taken.
16
+ */
17
+ metadata?: () => Record<string, string>;
18
+ /**
19
+ * The app's own files, such as its saved state, in every export but the image: the Data export, the ZIP, ProcrastiMate,
20
+ * and webhooks. Each `data` runs when a capture is taken, so the files match the screenshot.
21
+ */
22
+ files?: FeedbackFile[];
12
23
  /**
13
24
  * What opens Feedback. A chord that ends in `Click`, such as the default `Alt+Meta+Click`, opens the editor with the
14
25
  * element under the pointer selected. A chord that ends in a key, such as `Alt+Shift+F`, shows the Add Feedback
@@ -31,15 +42,15 @@ export type FeedbackOptions = {
31
42
  */
32
43
  procrastimate?: ProcrastimateConfig;
33
44
  /**
34
- * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
35
- * webhook's `url`, with nothing more to fill in. The menu lists ProcrastiMate, then the webhooks with `githubIcon`,
36
- * then the others.
45
+ * Adds one entry to the Share menu per webhook. Choosing it posts the image export, the JSON export, and the app's
46
+ * `files` to the webhook's `url`, with nothing more to fill in. The menu lists ProcrastiMate, then the webhooks with
47
+ * `githubIcon`, then the others.
37
48
  */
38
49
  webhooks?: Webhook[];
39
50
  /**
40
- * The Share menu entries that also get a button beside Share, by name, in this order: `'ProcrastiMate'` or a
41
- * webhook's `name`. A name the menu does not list is skipped. Without it, the first two of ProcrastiMate and the
42
- * webhooks get one. `[]` gives none.
51
+ * The destinations that get a button beside Share instead of an entry in its menu, by name, in this order:
52
+ * `'ProcrastiMate'` or a webhook's `name`. A name with no destination is skipped. Without it, the first two of
53
+ * ProcrastiMate and the webhooks get one. `[]` gives none.
43
54
  */
44
55
  pinned?: string[];
45
56
  };
@@ -126,11 +137,7 @@ export class Engine {
126
137
  this.hidePill();
127
138
  this.capturing = true;
128
139
  try {
129
- const screen = await captureScreen({
130
- app: this.options.app,
131
- version: this.options.version,
132
- context: this.providers,
133
- });
140
+ const screen = await captureScreen({ ...this.options, context: this.providers });
134
141
  const { visible } = screen.capture;
135
142
  this.pointed = at && { x: at.x + visible.x, y: at.y + visible.y };
136
143
  this.screen = screen;
@@ -143,7 +150,7 @@ export class Engine {
143
150
 
144
151
  /** The JSON export of the page as it is now, with no items, without drawing it or opening the editor. */
145
152
  report(): FeedbackReport {
146
- const capture = captureTree({ app: this.options.app, version: this.options.version, context: this.providers });
153
+ const capture = captureTree({ ...this.options, context: this.providers });
147
154
  // Through the export's own serializer, so the object has the file's keys, without the ones that have no value.
148
155
  return JSON.parse(reportJSON(capture, new Annotations(), false));
149
156
  }
@@ -1,4 +1,5 @@
1
1
  import { mount, unmount } from 'svelte';
2
+ import { checkFiles } from '../dom/files.ts';
2
3
  import { watchHold } from '../dom/hold.ts';
3
4
  import { hostAttribute } from '../dom/tags.ts';
4
5
  import type { FeedbackReport } from '../core/index.ts';
@@ -57,6 +58,7 @@ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngi
57
58
 
58
59
  if (options.procrastimate && !options.procrastimate.projects?.length)
59
60
  throw new Error('setupFeedbackEngine({ procrastimate }) needs the projects Feedback may post to, by name or id.');
61
+ checkFiles(options.files ?? []);
60
62
  const engine = new Engine(options);
61
63
  const host = document.createElement('div');
62
64
  host.setAttribute(hostAttribute, '');
@@ -4,6 +4,7 @@ import { setupFeedbackEngine as setup, type FeedbackEngine } from '../editor/set
4
4
  import { readComponents } from './components.ts';
5
5
 
6
6
  export type { FeedbackReport, FeedbackRepresentable } from '../core/index.ts';
7
+ export type { FeedbackFile } from '../dom/files.ts';
7
8
  export { githubIcon, type Webhook, type WebhookValues } from '../dom/webhook.ts';
8
9
  export type { FeedbackOptions } from '../editor/engine.ts';
9
10
  export type { FeedbackEngine } from '../editor/setup.ts';
@@ -7,6 +7,16 @@ export type FeedbackOptions = {
7
7
  /** The app's name in exports. Defaults to the document's title. */
8
8
  app?: string;
9
9
  version?: string;
10
+ /**
11
+ * Lines the image export prints under its title, as `label: value`, such as `{ 'Signed in': 'ana@example.com' }`.
12
+ * They are the first entries of the JSON export's `environment` after `App`. Runs when a capture is taken.
13
+ */
14
+ metadata?: () => Record<string, string>;
15
+ /**
16
+ * The app's own files, such as its saved state, in every export but the image: the Data export, the ZIP, ProcrastiMate,
17
+ * and webhooks. Each `data` runs when a capture is taken, so the files match the screenshot.
18
+ */
19
+ files?: FeedbackFile[];
10
20
  /**
11
21
  * What opens Feedback. A chord that ends in `Click`, such as the default `Alt+Meta+Click`, opens the editor with the
12
22
  * element under the pointer selected. A chord that ends in a key, such as `Alt+Shift+F`, shows the Add Feedback
@@ -44,19 +54,32 @@ export type FeedbackOptions = {
44
54
  space?: string;
45
55
  };
46
56
  /**
47
- * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
48
- * webhook's `url`, with nothing more to fill in. The menu lists ProcrastiMate, then the webhooks with `githubIcon`,
49
- * then the others.
57
+ * Adds one entry to the Share menu per webhook. Choosing it posts the image export, the JSON export, and the app's
58
+ * `files` to the webhook's `url`, with nothing more to fill in. The menu lists ProcrastiMate, then the webhooks with
59
+ * `githubIcon`, then the others.
50
60
  */
51
61
  webhooks?: Webhook[];
52
62
  /**
53
- * The Share menu entries that also get a button beside Share, by name, in this order: `'ProcrastiMate'` or a
54
- * webhook's `name`. A name the menu does not list is skipped. Without it, the first two of ProcrastiMate and the
55
- * webhooks get one. `[]` gives none.
63
+ * The destinations that get a button beside Share instead of an entry in its menu, by name, in this order:
64
+ * `'ProcrastiMate'` or a webhook's `name`. A name with no destination is skipped. Without it, the first two of
65
+ * ProcrastiMate and the webhooks get one. `[]` gives none.
56
66
  */
57
67
  pinned?: string[];
58
68
  };
59
69
 
70
+ /** A file the app adds to every export, made when a capture is taken. */
71
+ export type FeedbackFile = {
72
+ /** The file's name in every export, such as `save.json`. */
73
+ name: string;
74
+ /**
75
+ * Makes the file when a capture is taken, so it matches the screenshot. A `Blob` is used as it is, a string as text,
76
+ * and anything else as JSON. `null` or `undefined` leaves the file out, for a screen that has nothing to put in it.
77
+ */
78
+ data: () => unknown;
79
+ /** The media type. Without it, a `Blob` keeps its own, `.json` is `application/json`, and other text is `text/plain`. */
80
+ type?: string;
81
+ };
82
+
60
83
  /** One entry of the Share menu that posts the feedback to a server of the app's own. `docs/webhooks.md` has the request. */
61
84
  export type Webhook = {
62
85
  /** The entry's name in the Share menu, such as `GitHub Issue`. */
@@ -2,6 +2,7 @@ import type { Attachment } from 'svelte/attachments';
2
2
  import { tags } from '../dom/tags.ts';
3
3
 
4
4
  export type { FeedbackReport, FeedbackRepresentable } from '../core/index.ts';
5
+ export type { FeedbackFile } from '../dom/files.ts';
5
6
  export { githubIcon, type Webhook, type WebhookValues } from '../dom/webhook.ts';
6
7
  export type { FeedbackOptions } from '../editor/engine.ts';
7
8
  export { setupFeedbackEngine, type FeedbackEngine } from '../editor/setup.ts';