@stefan.inc/feedback-engine 0.0.0-stage → 0.0.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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +57 -5
  4. package/src/core/annotations.ts +104 -0
  5. package/src/core/cardLayout.ts +82 -0
  6. package/src/core/describe.ts +143 -0
  7. package/src/core/index.ts +9 -0
  8. package/src/core/model.ts +133 -0
  9. package/src/core/problem.ts +51 -0
  10. package/src/core/report.ts +74 -0
  11. package/src/core/session.ts +184 -0
  12. package/src/core/taskTitle.ts +35 -0
  13. package/src/core/tree.ts +117 -0
  14. package/src/dom/capture.ts +78 -0
  15. package/src/dom/image.ts +316 -0
  16. package/src/dom/procrastimate.ts +205 -0
  17. package/src/dom/scene.ts +286 -0
  18. package/src/dom/screenshot.ts +118 -0
  19. package/src/dom/share.ts +71 -0
  20. package/src/dom/tags.ts +21 -0
  21. package/src/dom/webhook.ts +80 -0
  22. package/src/dom/zip.ts +52 -0
  23. package/src/editor/Button.svelte +125 -0
  24. package/src/editor/Editor.svelte +1078 -0
  25. package/src/editor/Host.svelte +31 -0
  26. package/src/editor/ItemsSheet.svelte +233 -0
  27. package/src/editor/Pill.svelte +65 -0
  28. package/src/editor/ProblemCard.svelte +67 -0
  29. package/src/editor/ProcrastimateSheet.svelte +304 -0
  30. package/src/editor/WebhookSheet.svelte +132 -0
  31. package/src/editor/engine.ts +154 -0
  32. package/src/editor/setup.ts +106 -0
  33. package/src/next/index.d.ts +13 -0
  34. package/src/next/index.js +69 -0
  35. package/src/next/loader.js +23 -0
  36. package/src/react/components.ts +101 -0
  37. package/src/react/index.ts +44 -0
  38. package/src/react/public.d.ts +101 -0
  39. package/src/svelte/index.ts +32 -0
  40. package/src/vite/index.d.ts +44 -0
  41. package/src/vite/index.js +207 -0
  42. package/src/vite/react.js +172 -0
@@ -0,0 +1,286 @@
1
+ import { computeAccessibleName, getRole } from 'dom-accessibility-api';
2
+ import { describe, type Frame, type Point, type RawNode, type RawScene } from '../core/index.ts';
3
+ import { discovery, hostAttribute, sourceAttribute, tags, type Component } from './tags.ts';
4
+
5
+ /** Roles whose content merges into one element, as VoiceOver reads a button as one stop. */
6
+ const controls: Record<string, string> = {
7
+ button: 'Button',
8
+ link: 'Link',
9
+ switch: 'Switch',
10
+ checkbox: 'Checkbox',
11
+ radio: 'Radio button',
12
+ textbox: 'Text field',
13
+ searchbox: 'Search field',
14
+ combobox: 'Combo box',
15
+ listbox: 'List box',
16
+ slider: 'Slider',
17
+ spinbutton: 'Stepper',
18
+ tab: 'Tab',
19
+ option: 'Option',
20
+ menuitem: 'Menu item',
21
+ menuitemcheckbox: 'Menu item',
22
+ menuitemradio: 'Menu item',
23
+ heading: 'Header',
24
+ img: 'Image',
25
+ progressbar: 'Progress',
26
+ meter: 'Meter',
27
+ };
28
+
29
+ const skipped = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'HEAD', 'LINK', 'META', 'TITLE', 'BR', 'WBR']);
30
+ const leaves = new Set([
31
+ 'svg',
32
+ 'CANVAS',
33
+ 'VIDEO',
34
+ 'AUDIO',
35
+ 'IFRAME',
36
+ 'OBJECT',
37
+ 'EMBED',
38
+ 'SELECT',
39
+ 'TEXTAREA',
40
+ 'INPUT',
41
+ 'IMG',
42
+ ]);
43
+
44
+ type SvelteElement = Element & { __svelte_meta?: { loc?: { file: string; line: number } } };
45
+
46
+ /** A root of content that stays put while the page scrolls: a `position: fixed` element, a modal dialog, or an open popover. */
47
+ export type FixedRoot = { element: HTMLElement; frame: Frame; layer: number; backdrop?: string };
48
+
49
+ export type Scene = RawScene & { fixed: FixedRoot[] };
50
+
51
+ const union = (a: Frame, b: Frame): Frame => {
52
+ const x = Math.min(a.x, b.x);
53
+ const y = Math.min(a.y, b.y);
54
+ return {
55
+ x,
56
+ y,
57
+ width: Math.max(a.x + a.width, b.x + b.width) - x,
58
+ height: Math.max(a.y + a.height, b.y + b.height) - y,
59
+ };
60
+ };
61
+
62
+ const intersect = (a: Frame, b: Frame): Frame => {
63
+ const x = Math.max(a.x, b.x);
64
+ const y = Math.max(a.y, b.y);
65
+ return {
66
+ x,
67
+ y,
68
+ width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x),
69
+ height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y),
70
+ };
71
+ };
72
+
73
+ function layerRoots(): Element[] {
74
+ const roots = new Set<Element>();
75
+ for (const selector of ['dialog:modal', '[popover]:popover-open', '[aria-modal="true"]']) {
76
+ try {
77
+ for (const element of document.querySelectorAll(selector)) roots.add(element);
78
+ } catch {
79
+ // A browser without this selector has no such layer to find.
80
+ }
81
+ }
82
+ return [...roots].filter(root => !root.closest(`[${hostAttribute}]`));
83
+ }
84
+
85
+ function layerName(root: Element) {
86
+ const role = root.getAttribute('role');
87
+ if (role === 'alertdialog') return 'Alert';
88
+ if (role === 'menu' || root.querySelector(':scope > [role="menu"]')) return 'Menu';
89
+ return root.tagName === 'DIALOG' || role === 'dialog' ? 'Dialog' : 'Popover';
90
+ }
91
+
92
+ const normalized = (value: string | null | undefined) => (value ?? '').replace(/\s+/g, ' ').trim();
93
+
94
+ const isControl = (element: Element) => leaves.has(element.tagName) || (getRole(element) ?? '') in controls;
95
+
96
+ /**
97
+ * The words of a text and of the formatting inside it. A control inside it, such as the field a label wraps, is its own
98
+ * element. Neighboring text nodes join as they are, since React writes `{count}%` as two of them.
99
+ */
100
+ function text(element: Element): string {
101
+ let words = '';
102
+ for (const child of element.childNodes) {
103
+ if (child.nodeType === Node.TEXT_NODE) words += child.textContent ?? '';
104
+ else if (child instanceof Element && !isControl(child)) words += ` ${text(child)} `;
105
+ }
106
+ return normalized(words);
107
+ }
108
+
109
+ function label(element: Element, role: string) {
110
+ const name = normalized(computeAccessibleName(element));
111
+ if (element instanceof HTMLInputElement && (element.type === 'checkbox' || element.type === 'radio')) {
112
+ return [name, element.checked ? 'on' : 'off'].filter(Boolean).join(', ');
113
+ }
114
+ if (role === 'switch' || role === 'checkbox' || role === 'radio') {
115
+ return [name, element.getAttribute('aria-checked') === 'true' ? 'on' : 'off'].filter(Boolean).join(', ');
116
+ }
117
+ if (element instanceof HTMLSelectElement) {
118
+ return [name, normalized(element.selectedOptions[0]?.textContent)].filter(Boolean).join(', ');
119
+ }
120
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
121
+ const value = element instanceof HTMLInputElement && element.type === 'password' ? '' : element.value;
122
+ return [name, value].filter(Boolean).join(', ') || element.placeholder;
123
+ }
124
+ return name;
125
+ }
126
+
127
+ /**
128
+ * Reads the page into a scene. Frames are in capture coordinates: the document's, with content that stays put while
129
+ * the page scrolls placed over the part that was on screen. Call it with the window scrolled to its origin, so a
130
+ * sticky bar sits where the screenshot draws it, and pass the scroll position the user had as `scroll`.
131
+ */
132
+ export function readScene(scroll: Point): Scene {
133
+ const root = document.documentElement;
134
+ const size = { width: Math.max(root.scrollWidth, innerWidth), height: Math.max(root.scrollHeight, innerHeight) };
135
+ const roots = layerRoots();
136
+ const scene: Scene = { size, layers: [{ name: 'Screen', frame: { x: 0, y: 0, ...size } }], nodes: [], fixed: [] };
137
+
138
+ type Walk = {
139
+ parent: number | null;
140
+ layer: number;
141
+ clip: Frame | undefined;
142
+ /** `text` inside a text, whose own words are already in its label. `all` inside a control or hidden content, where only tagged components still become nodes. */
143
+ merged: 'none' | 'text' | 'all';
144
+ fixed: boolean;
145
+ };
146
+
147
+ const frameOf = (element: Element, fixed: boolean): Frame => {
148
+ const rect = element.getBoundingClientRect();
149
+ return {
150
+ x: rect.x + (fixed ? scroll.x : 0),
151
+ y: rect.y + (fixed ? scroll.y : 0),
152
+ width: rect.width,
153
+ height: rect.height,
154
+ };
155
+ };
156
+
157
+ let discovered: Map<Element, Component[]> | undefined;
158
+ try {
159
+ discovered = discovery.read?.();
160
+ } catch (error) {
161
+ // The reader depends on a framework's internals. Without it the capture still has the elements and the tags.
162
+ console.warn("Feedback could not read the framework's components", error);
163
+ }
164
+ /** Where each component already is, by its roots and then by layer. Its later roots in that layer grow the same node. */
165
+ const placed = new Map<Element[], Map<number, number>>();
166
+
167
+ /** The components rooted at an element, outermost first: the ones the framework knows, then the element's own tag. */
168
+ const componentsAt = (element: Element, isLayer: boolean): Component[] => {
169
+ // A dialog or a menu is one root of the screen that opens it. That screen is not the layer, so only a component that draws nothing else is.
170
+ const found = (discovered?.get(element) ?? []).filter(component => !isLayer || component.roots.length === 1);
171
+ const tag = tags.get(element);
172
+ if (!tag) return found;
173
+ // A tag that repeats the name of a component rooted here adds data to it, such as state the framework does not expose.
174
+ const same = found.findLastIndex(component => component.tag.name === tag.name);
175
+ if (same === -1) return [...found, { tag, roots: [element] }];
176
+ const known = found[same]!;
177
+ return found.with(same, { tag: { ...known.tag, data: tag.data ?? known.tag.data }, roots: known.roots });
178
+ };
179
+
180
+ const add = (node: Omit<RawNode, 'frame'>, frame: Frame, clip: Frame | undefined) => {
181
+ const clipped = clip ? intersect(frame, clip) : frame;
182
+ if (!clipped.width || !clipped.height) return null;
183
+ scene.nodes.push({ ...node, frame: clipped });
184
+ return scene.nodes.length - 1;
185
+ };
186
+
187
+ const visit = (element: Element, walk: Walk) => {
188
+ if (skipped.has(element.tagName) || element.hasAttribute(hostAttribute)) return;
189
+ const style = getComputedStyle(element);
190
+ if (style.display === 'none' || Number(style.opacity) === 0) return;
191
+
192
+ let { parent, layer, clip, merged, fixed } = walk;
193
+ const isLayer = roots.includes(element);
194
+ if (style.position === 'fixed' || isLayer) {
195
+ // A layer is its own root even inside a fixed shell or another layer: the browser lifts it to the top layer.
196
+ if (isLayer) {
197
+ const frame = frameOf(element, true);
198
+ layer = scene.layers.length;
199
+ scene.layers.push({ name: layerName(element), frame });
200
+ scene.fixed.push({
201
+ element: element as HTMLElement,
202
+ frame,
203
+ layer,
204
+ backdrop: getComputedStyle(element, '::backdrop').backgroundColor,
205
+ });
206
+ parent = null;
207
+ merged = 'none';
208
+ } else if (!fixed) {
209
+ scene.fixed.push({ element: element as HTMLElement, frame: frameOf(element, true), layer });
210
+ }
211
+ fixed = true;
212
+ clip = undefined;
213
+ }
214
+
215
+ const frame = frameOf(element, fixed);
216
+ const visible = style.visibility === 'visible';
217
+ const hidden = merged === 'all' || element.getAttribute('aria-hidden') === 'true' || element.hasAttribute('inert');
218
+ const location = (element as SvelteElement).__svelte_meta?.loc;
219
+ const source = location
220
+ ? `${location.file}:${location.line}`
221
+ : (element.getAttribute(sourceAttribute) ?? undefined);
222
+
223
+ for (const component of visible ? componentsAt(element, isLayer) : []) {
224
+ const { tag } = component;
225
+ const layers = placed.get(component.roots) ?? new Map<number, number>();
226
+ placed.set(component.roots, layers);
227
+ const index = layers.get(layer);
228
+ if (index !== undefined) {
229
+ const clipped = clip ? intersect(frame, clip) : frame;
230
+ if (clipped.width && clipped.height) scene.nodes[index]!.frame = union(scene.nodes[index]!.frame, clipped);
231
+ parent = index;
232
+ continue;
233
+ }
234
+ let data: string | undefined;
235
+ try {
236
+ data = tag.data ? describe(tag.data()) : undefined;
237
+ } catch (error) {
238
+ console.warn(`Feedback could not read the data of ${tag.name}`, error);
239
+ }
240
+ const added = add({ parent, layer, kind: 'component', name: tag.name, source: tag.source, data }, frame, clip);
241
+ if (added === null) continue;
242
+ layers.set(layer, added);
243
+ parent = added;
244
+ }
245
+
246
+ if (visible && !hidden) {
247
+ const role = getRole(element) ?? '';
248
+ const native = element.tagName === 'INPUT' || element.tagName === 'SELECT' || element.tagName === 'TEXTAREA';
249
+ const name = controls[role] ?? (native ? 'Text field' : undefined);
250
+ const ownText =
251
+ merged === 'none' &&
252
+ [...element.childNodes].some(child => child.nodeType === Node.TEXT_NODE && child.textContent?.trim());
253
+ if (name || ownText) {
254
+ const found = add(
255
+ {
256
+ parent,
257
+ layer,
258
+ kind: 'element',
259
+ name: name ?? 'Text',
260
+ label: name ? label(element, role) : text(element),
261
+ source,
262
+ },
263
+ frame,
264
+ clip,
265
+ );
266
+ if (found !== null) parent = found;
267
+ merged = name ? 'all' : 'text';
268
+ }
269
+ } else if (hidden) {
270
+ merged = 'all';
271
+ }
272
+
273
+ if (leaves.has(element.tagName)) return;
274
+ if (
275
+ element !== root &&
276
+ element !== document.body &&
277
+ (style.overflowX !== 'visible' || style.overflowY !== 'visible')
278
+ ) {
279
+ clip = clip ? intersect(clip, frame) : frame;
280
+ }
281
+ for (const child of element.children) visit(child, { parent, layer, clip, merged, fixed });
282
+ };
283
+
284
+ visit(document.body, { parent: null, layer: 0, clip: undefined, merged: 'none', fixed: false });
285
+ return scene;
286
+ }
@@ -0,0 +1,118 @@
1
+ import { domToCanvas } from 'modern-screenshot';
2
+ import type { Frame, Size } from '../core/index.ts';
3
+ import type { FixedRoot } from './scene.ts';
4
+ import { hostAttribute } from './tags.ts';
5
+
6
+ /** iOS Safari refuses a larger canvas, and other browsers stop at 16,384 pixels a side. */
7
+ const pixelBudget = 16_000_000;
8
+ const maxSide = 16_384;
9
+
10
+ /** The device's pixel ratio, lowered until the whole capture fits a canvas. */
11
+ export function captureScale(size: Size) {
12
+ return Math.min(
13
+ devicePixelRatio,
14
+ Math.sqrt(pixelBudget / (size.width * size.height)),
15
+ maxSide / size.width,
16
+ maxSide / size.height,
17
+ );
18
+ }
19
+
20
+ /**
21
+ * Draws the page at full length. The browser gives a page no way to read its own pixels, so the DOM is drawn again
22
+ * into a canvas. The document goes first, without the content that stays put while the page scrolls. Each such root
23
+ * is then drawn where it was on screen, over a modal's backdrop, which a re-draw of the DOM leaves out.
24
+ */
25
+ export function screenshot(size: Size, scale: number, visible: Frame, fixed: FixedRoot[]) {
26
+ return withFieldState(() => draw(size, scale, visible, fixed));
27
+ }
28
+
29
+ /**
30
+ * The re-draw copies attributes, and what a field holds is a property. This writes the text of each text area and the
31
+ * state of each checkbox and radio button into their attributes while `work` runs, then puts the attributes back.
32
+ */
33
+ async function withFieldState<T>(work: () => Promise<T>) {
34
+ const restore: (() => void)[] = [];
35
+ for (const field of document.querySelectorAll('textarea, input[type="checkbox"], input[type="radio"]')) {
36
+ if (field instanceof HTMLTextAreaElement) {
37
+ const before = field.textContent;
38
+ if (before === field.value) continue;
39
+ field.textContent = field.value;
40
+ restore.push(() => (field.textContent = before));
41
+ } else if (field instanceof HTMLInputElement && field.hasAttribute('checked') !== field.checked) {
42
+ field.toggleAttribute('checked', field.checked);
43
+ restore.push(() => field.toggleAttribute('checked', !field.checked));
44
+ }
45
+ }
46
+ try {
47
+ return await work();
48
+ } finally {
49
+ for (const undo of restore) undo();
50
+ }
51
+ }
52
+
53
+ /**
54
+ * What the browser paints behind the page: the root's background, else the body's, which the root takes over, else the
55
+ * canvas color of the page's color scheme. The re-draw is transparent where the page sets no background.
56
+ */
57
+ function pageBackground() {
58
+ for (const element of [document.documentElement, document.body]) {
59
+ const color = element && getComputedStyle(element).backgroundColor;
60
+ if (color && color !== 'transparent' && color !== 'rgba(0, 0, 0, 0)') return color;
61
+ }
62
+ const probe = document.createElement('div');
63
+ probe.style.cssText = 'position: fixed; background: Canvas';
64
+ document.documentElement.append(probe);
65
+ const color = getComputedStyle(probe).backgroundColor;
66
+ probe.remove();
67
+ return color;
68
+ }
69
+
70
+ async function draw(size: Size, scale: number, visible: Frame, fixed: FixedRoot[]) {
71
+ const roots = new Set<Node>(fixed.map(root => root.element));
72
+ const canvas = await domToCanvas(document.documentElement, {
73
+ width: size.width,
74
+ height: size.height,
75
+ scale,
76
+ backgroundColor: pageBackground(),
77
+ filter: node => !(roots.has(node) || (node instanceof Element && node.hasAttribute(hostAttribute))),
78
+ });
79
+ // The library sizes the canvas with inline styles. The editor sizes it instead.
80
+ canvas.removeAttribute('style');
81
+ const context = canvas.getContext('2d')!;
82
+ context.scale(scale, scale);
83
+ // A modal dialog or popover sits in the browser's top layer, above every other fixed root, whatever the DOM order.
84
+ const layered = [
85
+ ...fixed.filter(root => root.backdrop === undefined),
86
+ ...fixed.filter(root => root.backdrop !== undefined),
87
+ ];
88
+ for (const root of layered) {
89
+ if (root.backdrop) {
90
+ context.fillStyle = root.backdrop;
91
+ context.fillRect(visible.x, visible.y, visible.width, visible.height);
92
+ }
93
+ const { frame } = root;
94
+ if (!frame.width || !frame.height) continue;
95
+ const drawn = await domToCanvas(root.element, {
96
+ width: frame.width,
97
+ height: frame.height,
98
+ scale,
99
+ // A layer inside this root is drawn by its own turn.
100
+ filter: node => node === root.element || !roots.has(node),
101
+ style: {
102
+ // A copy of a popover is not open, and a closed popover is `display: none`.
103
+ display: getComputedStyle(root.element).display,
104
+ position: 'static',
105
+ inset: 'auto',
106
+ margin: '0',
107
+ transform: 'none',
108
+ translate: 'none',
109
+ width: `${frame.width}px`,
110
+ height: `${frame.height}px`,
111
+ maxWidth: 'none',
112
+ maxHeight: 'none',
113
+ },
114
+ });
115
+ context.drawImage(drawn, frame.x, frame.y, frame.width, frame.height);
116
+ }
117
+ return canvas;
118
+ }
@@ -0,0 +1,71 @@
1
+ import type { Annotations } from '../core/index.ts';
2
+ import { reportJSON } from '../core/index.ts';
3
+ import type { Screen } from './capture.ts';
4
+ import { annotatedImage } from './image.ts';
5
+ import { zip } from './zip.ts';
6
+
7
+ export type ExportFormat = 'image' | 'json' | 'zip';
8
+
9
+ export const exportTitles: Record<ExportFormat, string> = {
10
+ image: 'Image',
11
+ json: 'JSON',
12
+ zip: 'Image and JSON (ZIP)',
13
+ };
14
+
15
+ /** One export: the file to save or share, and the parts the clipboard takes. */
16
+ export type Export = { file: File; image?: Blob; json?: string };
17
+
18
+ const toBlob = (canvas: HTMLCanvasElement) =>
19
+ new Promise<Blob>((resolve, reject) =>
20
+ canvas.toBlob(
21
+ blob => (blob ? resolve(blob) : reject(new Error('The browser could not encode the image'))),
22
+ 'image/png',
23
+ ),
24
+ );
25
+
26
+ export async function buildExport(screen: Screen, annotations: Annotations, format: ExportFormat): Promise<Export> {
27
+ const image = format === 'json' ? undefined : await toBlob(annotatedImage(screen, annotations));
28
+ const json = format === 'image' ? undefined : reportJSON(screen.capture, annotations);
29
+ if (format === 'image') return { file: new File([image!], 'feedback.png', { type: 'image/png' }), image };
30
+ if (format === 'json') return { file: new File([json!], 'feedback.json', { type: 'application/json' }), json };
31
+ const archive = zip([
32
+ { name: 'feedback/feedback.png', bytes: new Uint8Array(await image!.arrayBuffer()) },
33
+ { name: 'feedback/feedback.json', bytes: new TextEncoder().encode(json) },
34
+ ]);
35
+ return { file: new File([archive], 'feedback.zip', { type: 'application/zip' }), image, json };
36
+ }
37
+
38
+ /**
39
+ * Puts the export on the clipboard, ready to paste into a chat with an agent. Browsers take one clipboard item per
40
+ * write, so an export with an image and JSON is one item with both, and the paste target picks the one it reads.
41
+ */
42
+ export async function copyExport({ image, json }: Export) {
43
+ if (!image) return navigator.clipboard.writeText(json!);
44
+ await navigator.clipboard.write([
45
+ new ClipboardItem({
46
+ 'image/png': image,
47
+ ...(json === undefined ? {} : { 'text/plain': new Blob([json], { type: 'text/plain' }) }),
48
+ }),
49
+ ]);
50
+ }
51
+
52
+ export function saveExport({ file }: Export) {
53
+ const link = document.createElement('a');
54
+ link.href = URL.createObjectURL(file);
55
+ link.download = file.name;
56
+ link.click();
57
+ setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
58
+ }
59
+
60
+ export const canShare = ({ file }: Export) => !!navigator.canShare?.({ files: [file] });
61
+
62
+ /** Hands the file to the system share sheet. Resolves to `false` when the user backs out of it. */
63
+ export async function shareExport({ file }: Export) {
64
+ try {
65
+ await navigator.share({ files: [file] });
66
+ return true;
67
+ } catch (error) {
68
+ if ((error as Error).name === 'AbortError') return false;
69
+ throw error;
70
+ }
71
+ }
@@ -0,0 +1,21 @@
1
+ /** What a `feedback()` tag records on its element. `data` runs when a capture is taken. */
2
+ export type Tag = { name: string; source?: string; data?: () => unknown };
3
+
4
+ /** One entry per tagged element, so tagging costs nothing until a capture reads it. */
5
+ export const tags = new WeakMap<Element, Tag>();
6
+
7
+ /** A component a framework knows without a tag, and the elements it draws. Several, when it renders siblings. */
8
+ export type Component = { tag: Tag; roots: Element[] };
9
+
10
+ /**
11
+ * How a capture finds components without tags. An entry point sets `read` when its framework keeps a component tree
12
+ * at runtime, as React does. It runs once per capture and gives, for each element, the components that element is a
13
+ * root of, outermost first.
14
+ */
15
+ export const discovery: { read?: () => Map<Element, Component[]> } = {};
16
+
17
+ /** Marks the element that holds the pill and the editor, so a capture leaves Feedback's own UI out. */
18
+ export const hostAttribute = 'data-feedback-engine';
19
+
20
+ /** An element's `file:line`, written by a build plugin for a framework that does not record one itself. */
21
+ export const sourceAttribute = 'data-feedback-source';
@@ -0,0 +1,80 @@
1
+ import { Problem } from '../core/problem.ts';
2
+
3
+ /** One entry of the Share menu that posts the feedback to a server of the app's own. `docs/webhooks.md` has the request. */
4
+ export type Webhook = {
5
+ /** The entry's name in the Share menu, such as `GitHub Issue`. */
6
+ name: string;
7
+ /** Where the post goes. A path, such as `/api/feedback`, is on the page's own origin. */
8
+ url: string;
9
+ /** An icon beside the name: anything an `<img>` loads, such as `githubIcon` or a data URL. */
10
+ image?: string;
11
+ /** Sent with the post, such as `Authorization`. Whatever a page sends is public. */
12
+ headers?: Record<string, string>;
13
+ /** Added to the URL's query. */
14
+ query?: Record<string, string>;
15
+ };
16
+
17
+ export type WebhookPost = {
18
+ /** Made once per post and sent again on a retry, so a server can tell a retry from a second post. */
19
+ id: string;
20
+ title: string;
21
+ /** The image export, as PNG. */
22
+ image: Blob;
23
+ /** The JSON export. */
24
+ report: string;
25
+ };
26
+
27
+ /**
28
+ * GitHub's mark in white, for a webhook that files issues. The iOS package draws the same path
29
+ * (`GitHubIcon.swift`), which has only absolute `M`, `L`, `C`, and `Z` commands so that a few lines can read it.
30
+ */
31
+ export const githubIcon = `data:image/svg+xml,${encodeURIComponent(
32
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="white"><path d="M6.766 11.328C4.703 11.078 3.25 9.594 3.25 7.672C3.25 6.891 3.531 6.047 4 5.484C3.797 4.969 3.828 3.875 4.063 3.422C4.688 3.344 5.531 3.672 6.031 4.125C6.625 3.938 7.25 3.844 8.016 3.844C8.781 3.844 9.406 3.938 9.969 4.109C10.453 3.672 11.313 3.344 11.938 3.422C12.156 3.844 12.188 4.937 11.984 5.469C12.484 6.062 12.75 6.859 12.75 7.672C12.75 9.594 11.297 11.047 9.203 11.312C9.734 11.656 10.093 12.406 10.093 13.266L10.093 14.891C10.093 15.359 10.484 15.625 10.953 15.438C13.781 14.359 16 11.53 16 8.03C16 3.61 12.406 0 7.984 0C3.563 0 0 3.61 0 8.031C-0.009 11.347 2.058 14.314 5.172 15.453C5.594 15.609 6 15.328 6 14.906L6 13.656C5.781 13.75 5.5 13.812 5.25 13.812C4.219 13.812 3.61 13.25 3.172 12.203C3 11.781 2.812 11.531 2.453 11.484C2.266 11.469 2.203 11.391 2.203 11.297C2.203 11.109 2.516 10.969 2.828 10.969C3.281 10.969 3.672 11.25 4.078 11.829C4.391 12.281 4.718 12.484 5.109 12.484C5.5 12.484 5.75 12.344 6.109 11.984C6.375 11.719 6.579 11.484 6.766 11.328Z"/></svg>',
33
+ )}`;
34
+
35
+ /** `crypto.randomUUID` exists only in a secure context, and a phone often opens a dev server over plain HTTP. */
36
+ export function postId() {
37
+ if (crypto.randomUUID) return crypto.randomUUID();
38
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
39
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
40
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
41
+ const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
42
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
43
+ }
44
+
45
+ /**
46
+ * Sends one post and returns the link the server answered with, if any, for the toast. The link is the server's to
47
+ * choose, so only a web address is kept: the toast opens it.
48
+ */
49
+ export async function postWebhook(webhook: Webhook, post: WebhookPost): Promise<string | undefined> {
50
+ const url = new URL(webhook.url, location.href);
51
+ for (const [name, value] of Object.entries(webhook.query ?? {})) url.searchParams.set(name, value);
52
+ const form = new FormData();
53
+ form.set('id', post.id);
54
+ form.set('title', post.title);
55
+ form.set('image', new File([post.image], 'feedback.png', { type: 'image/png' }));
56
+ form.set('report', new File([post.report], 'feedback.json', { type: 'application/json' }));
57
+ let response: Response;
58
+ try {
59
+ response = await fetch(url, { method: 'POST', headers: webhook.headers, body: form });
60
+ } catch (error) {
61
+ throw Problem.request('POST', url.href, undefined, undefined, error);
62
+ }
63
+ const text = await response.text().catch(() => '');
64
+ let answer: { url?: unknown; message?: unknown } = {};
65
+ try {
66
+ const parsed: unknown = JSON.parse(text);
67
+ if (parsed && typeof parsed === 'object') answer = parsed;
68
+ } catch {
69
+ // An empty answer, or a proxy's HTML error page, which the details show as it came.
70
+ }
71
+ if (!response.ok) {
72
+ const message =
73
+ typeof answer.message === 'string'
74
+ ? `${webhook.name}: ${answer.message}`
75
+ : `${webhook.name} answered ${response.status}.`;
76
+ throw Problem.request('POST', url.href, response.status, text, new Error(message));
77
+ }
78
+ if (typeof answer.url !== 'string' || !URL.canParse(answer.url)) return undefined;
79
+ return /^https?:$/.test(new URL(answer.url).protocol) ? answer.url : undefined;
80
+ }
package/src/dom/zip.ts ADDED
@@ -0,0 +1,52 @@
1
+ const table = Uint32Array.from({ length: 256 }, (_, index) => {
2
+ let value = index;
3
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
4
+ return value >>> 0;
5
+ });
6
+
7
+ function crc32(bytes: Uint8Array) {
8
+ let crc = 0xffffffff;
9
+ for (const byte of bytes) crc = table[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
10
+ return (crc ^ 0xffffffff) >>> 0;
11
+ }
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 {
15
+ const encoder = new TextEncoder();
16
+ const parts: Uint8Array[] = [];
17
+ const directory: Uint8Array[] = [];
18
+ let offset = 0;
19
+ for (const file of files) {
20
+ const name = encoder.encode(file.name);
21
+ const crc = crc32(file.bytes);
22
+ const header = new DataView(new ArrayBuffer(30));
23
+ header.setUint32(0, 0x04034b50, true);
24
+ header.setUint16(4, 20, true);
25
+ header.setUint16(6, 0x0800, true);
26
+ header.setUint32(14, crc, true);
27
+ header.setUint32(18, file.bytes.length, true);
28
+ header.setUint32(22, file.bytes.length, true);
29
+ header.setUint16(26, name.length, true);
30
+ const entry = new DataView(new ArrayBuffer(46));
31
+ entry.setUint32(0, 0x02014b50, true);
32
+ entry.setUint16(4, 20, true);
33
+ entry.setUint16(6, 20, true);
34
+ entry.setUint16(8, 0x0800, true);
35
+ entry.setUint32(16, crc, true);
36
+ entry.setUint32(20, file.bytes.length, true);
37
+ entry.setUint32(24, file.bytes.length, true);
38
+ entry.setUint16(28, name.length, true);
39
+ entry.setUint32(42, offset, true);
40
+ parts.push(new Uint8Array(header.buffer), name, file.bytes);
41
+ directory.push(new Uint8Array(entry.buffer), name);
42
+ offset += 30 + name.length + file.bytes.length;
43
+ }
44
+ const directorySize = directory.reduce((sum, part) => sum + part.length, 0);
45
+ const end = new DataView(new ArrayBuffer(22));
46
+ end.setUint32(0, 0x06054b50, true);
47
+ end.setUint16(8, files.length, true);
48
+ end.setUint16(10, files.length, true);
49
+ end.setUint32(12, directorySize, true);
50
+ end.setUint32(16, offset, true);
51
+ return new Blob([...parts, ...directory, new Uint8Array(end.buffer)] as BlobPart[], { type: 'application/zip' });
52
+ }