@stefan.inc/feedback-engine 0.0.0-stage → 1.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 +89 -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 +107 -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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stefan Mirea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @stefan.inc/feedback-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Point at your app. Say what's wrong. Hand an agent the exact component and line of code.**
4
+
5
+ Alt+Meta+click anything in your Svelte or React app, click any component on the frozen screenshot, and write what should change. Feedback exports one file that names every component you flagged, where it lives in the source, and the data it was showing, so an agent can act on the feedback without guessing.
6
+
7
+ ```sh
8
+ bun add @stefan.inc/feedback-engine
9
+ ```
10
+
11
+ The package has one entry point per framework, `/svelte` and `/react`, with build plugins in `/vite` and `/next`. It ships TypeScript and Svelte source, and your app's bundler compiles it.
12
+
13
+ Setup for Svelte, React, and Next.js, and everything else the package does, is in the [repository's README](https://github.com/smirea/feedback-engine#web). [CHANGELOG.md](https://github.com/smirea/feedback-engine/blob/master/packages/web/CHANGELOG.md) lists every release.
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
- "name": "@stefan.inc/feedback-engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@stefan.inc/feedback-engine",
3
+ "version": "1.0.0",
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
+ "keywords": [
6
+ "accessibility",
7
+ "agents",
8
+ "annotation",
9
+ "feedback",
10
+ "nextjs",
11
+ "react",
12
+ "screenshot",
13
+ "svelte",
14
+ "vite"
15
+ ],
16
+ "homepage": "https://github.com/smirea/feedback-engine#web",
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/smirea/feedback-engine.git",
21
+ "directory": "packages/web"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "!src/**/*.test.ts"
26
+ ],
27
+ "type": "module",
28
+ "exports": {
29
+ "./react": {
30
+ "types": "./src/react/public.d.ts",
31
+ "default": "./src/react/index.ts"
32
+ },
33
+ "./svelte": {
34
+ "svelte": "./src/svelte/index.ts",
35
+ "default": "./src/svelte/index.ts"
36
+ },
37
+ "./vite": {
38
+ "types": "./src/vite/index.d.ts",
39
+ "default": "./src/vite/index.js"
40
+ },
41
+ "./next": {
42
+ "types": "./src/next/index.d.ts",
43
+ "default": "./src/next/index.js"
44
+ },
45
+ "./core": "./src/core/index.ts"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "dom-accessibility-api": "^0.7.1",
52
+ "modern-screenshot": "^4.7.0",
53
+ "oxc-parser": "^0.158.0"
54
+ },
55
+ "peerDependencies": {
56
+ "svelte": "^5.29.0"
57
+ }
58
+ }
@@ -0,0 +1,104 @@
1
+ import type { Node } from './model.ts';
2
+
3
+ export type FeedbackItem = { id: string; target: number; text: string };
4
+
5
+ /** A node that feedback text points at with a token such as `@1_Dialog`. */
6
+ export type Reference = { number: number; target: number; token: string };
7
+
8
+ export type Segment = { text: string; reference?: Reference };
9
+
10
+ export const tag = (reference: Reference) => `@${reference.number}`;
11
+
12
+ /**
13
+ * Everything a share exports besides the capture. Items and references share one count: a node takes the next number
14
+ * and color the first time it is flagged or referenced, and keeps them for the capture, so no two boxes show the same
15
+ * number. Removing an item leaves its number unused, since tokens in other texts may still name it.
16
+ */
17
+ export class Annotations {
18
+ items: FeedbackItem[] = [];
19
+ references: Reference[] = [];
20
+ private marked: number[] = [];
21
+
22
+ colorIndex(node: number) {
23
+ const index = this.marked.indexOf(node);
24
+ return index === -1 ? this.marked.length : index;
25
+ }
26
+
27
+ /** The node's number, or the one it would take next. */
28
+ number(node: number) {
29
+ return this.colorIndex(node) + 1;
30
+ }
31
+
32
+ /** Updates the target's item, or adds one. */
33
+ submit(text: string, target: number) {
34
+ const item = this.items.find(existing => existing.target === target);
35
+ if (item) {
36
+ item.text = text;
37
+ } else {
38
+ this.items.push({ id: crypto.randomUUID(), target, text });
39
+ this.mark(target);
40
+ }
41
+ }
42
+
43
+ remove(id: string) {
44
+ this.items = this.items.filter(item => item.id !== id);
45
+ }
46
+
47
+ /** The node's reference. A node referenced again gets the same one. */
48
+ reference(node: Node): Reference {
49
+ const existing = this.references.find(reference => reference.target === node.id);
50
+ if (existing) return existing;
51
+ const words = node.name
52
+ .split(/[^\p{L}\p{N}]+/u)
53
+ .filter(Boolean)
54
+ .join('_');
55
+ this.mark(node.id);
56
+ const number = this.number(node.id);
57
+ const reference = { number, target: node.id, token: `@${number}_${words || 'Node'}` };
58
+ this.references.push(reference);
59
+ return reference;
60
+ }
61
+
62
+ private mark(node: number) {
63
+ if (!this.marked.includes(node)) this.marked.push(node);
64
+ }
65
+
66
+ /** The references some item's text names, by number. */
67
+ get used() {
68
+ return this.referencesIn(this.items.map(item => item.text));
69
+ }
70
+
71
+ referencesIn(texts: string[]) {
72
+ const tokens = new Set(texts.flatMap(text => this.segments(text).map(segment => segment.reference?.token)));
73
+ return this.references.filter(reference => tokens.has(reference.token)).toSorted((a, b) => a.number - b.number);
74
+ }
75
+
76
+ /** The text split into plain runs and reference tokens. A token followed by more letters is plain text, since it names nothing. */
77
+ segments(text: string): Segment[] {
78
+ const segments: Segment[] = [];
79
+ const plain = (run: string) => {
80
+ if (!run) return;
81
+ const last = segments.at(-1);
82
+ if (last && !last.reference) last.text += run;
83
+ else segments.push({ text: run });
84
+ };
85
+ let rest = 0;
86
+ for (const match of text.matchAll(/@\d+_[\p{L}\p{N}_]+/gu)) {
87
+ const reference = this.references.find(known => known.token === match[0]);
88
+ if (reference) {
89
+ plain(text.slice(rest, match.index));
90
+ segments.push({ text: reference.token, reference });
91
+ } else {
92
+ plain(text.slice(rest, match.index + match[0].length));
93
+ }
94
+ rest = match.index + match[0].length;
95
+ }
96
+ plain(text.slice(rest));
97
+ return segments;
98
+ }
99
+ }
100
+
101
+ /** The colors items and references take, in order. They are iOS's system colors, so both platforms' exports match. */
102
+ export const palette = ['#FF3B30', '#007AFF', '#34C759', '#FF9500', '#AF52DE', '#FF2D55', '#30B0C7', '#5856D6'];
103
+
104
+ export const paletteColor = (index: number) => palette[index % palette.length]!;
@@ -0,0 +1,82 @@
1
+ import type { Frame, Point, Size } from './model.ts';
2
+
3
+ export const cards = {
4
+ margin: 24,
5
+ column: 280,
6
+ gutter: 36,
7
+ spacing: 12,
8
+ badge: 20,
9
+ padding: 10,
10
+ rightColumnPenalty: 80,
11
+ };
12
+
13
+ export type Card = { isLeft: boolean; origin: Point };
14
+ export type Layout = { shot: Frame; cards: Card[]; environment: Point; size: Size };
15
+
16
+ /** From the card's badge to the nearest side of the target, at the badge's height when the target spans it. */
17
+ export function line(card: Card, target: Frame): { start: Point; end: Point } {
18
+ const start = {
19
+ x: card.isLeft ? card.origin.x + cards.column : card.origin.x,
20
+ y: card.origin.y + cards.padding + cards.badge / 2,
21
+ };
22
+ const end = {
23
+ x: card.isLeft ? target.x : target.x + target.width,
24
+ y: Math.min(Math.max(start.y, target.y + 2), target.y + target.height - 2),
25
+ };
26
+ return { start, end };
27
+ }
28
+
29
+ const length = (card: Card, target: Frame) => {
30
+ const { start, end } = line(card, target);
31
+ return Math.hypot(end.x - start.x, end.y - start.y);
32
+ };
33
+
34
+ /**
35
+ * Where the image export puts each item's card. A card sits in the left column, as level with its target as the cards
36
+ * above it allow. It moves to the right column when that makes its line to the target at least `rightColumnPenalty`
37
+ * points shorter, as for a button at the right edge. The environment always sits at the top of the right column, and
38
+ * right-column cards start below it. A tall capture is cut half the height that was on screen below the lowest box or
39
+ * card, and never shorter than that height, and `shot` is the part that is drawn. `targets` and
40
+ * `references` are frames in the capture. The layout's frames are in the image.
41
+ */
42
+ export function place(
43
+ targets: Frame[],
44
+ heights: number[],
45
+ screen: Size,
46
+ environmentHeight: number,
47
+ viewport: number,
48
+ references: Frame[] = [],
49
+ ): Layout {
50
+ const { margin, column, gutter, spacing, rightColumnPenalty } = cards;
51
+ const shot = { x: margin + column + gutter, y: margin, width: screen.width, height: screen.height };
52
+ const rightX = shot.x + shot.width + gutter;
53
+ const moved = targets.map(target => ({ ...target, x: target.x + shot.x, y: target.y + shot.y }));
54
+ const midY = (index: number) => moved[index]!.y + moved[index]!.height / 2;
55
+ const placed: Card[] = moved.map(() => ({ isLeft: true, origin: { x: 0, y: 0 } }));
56
+ let nextLeft = margin;
57
+ let nextRight = margin + environmentHeight + spacing * 2;
58
+ const order = moved.map((_, index) => index).toSorted((a, b) => midY(a) - midY(b) || a - b);
59
+ for (const index of order) {
60
+ const desired = Math.max(midY(index) - heights[index]! / 2, margin);
61
+ const left: Card = { isLeft: true, origin: { x: margin, y: Math.max(desired, nextLeft) } };
62
+ const right: Card = { isLeft: false, origin: { x: rightX, y: Math.max(desired, nextRight) } };
63
+ const card = length(left, moved[index]!) - length(right, moved[index]!) >= rightColumnPenalty ? right : left;
64
+ placed[index] = card;
65
+ if (card.isLeft) nextLeft = card.origin.y + heights[index]! + spacing;
66
+ else nextRight = card.origin.y + heights[index]! + spacing;
67
+ }
68
+
69
+ const lowest = Math.max(
70
+ 0,
71
+ ...[...targets, ...references].map(frame => frame.y + frame.height),
72
+ ...placed.map((card, index) => card.origin.y + heights[index]! - shot.y),
73
+ );
74
+ shot.height = Math.min(screen.height, Math.max(viewport, lowest + viewport / 2));
75
+ const height = Math.max(shot.y + shot.height, nextLeft - spacing, nextRight - spacing) + margin;
76
+ return {
77
+ shot,
78
+ cards: placed,
79
+ environment: { x: rightX, y: margin },
80
+ size: { width: rightX + column + margin, height },
81
+ };
82
+ }
@@ -0,0 +1,143 @@
1
+ export const dataLimit = 1500;
2
+ export const contextLimit = 8000;
3
+ const maxElements = 10;
4
+
5
+ type Depth = { level: number; max: number };
6
+ const next = (depth: Depth) => ({ level: depth.level + 1, max: depth.max });
7
+
8
+ /** A value that Feedback describes as `toFeedback()` in its place, at any depth. */
9
+ export type FeedbackRepresentable = { toFeedback(): unknown };
10
+
11
+ const truncate = (text: string, limit: number) => (text.length > limit ? `${text.slice(0, limit)}… (truncated)` : text);
12
+
13
+ /**
14
+ * Describes a value the way it reads in code. A plain object at the top level is one `label: value` line per
15
+ * property. A larger `limit` is for app-wide context, which gets the room to nest deeper.
16
+ */
17
+ export function describe(value: unknown, limit = dataLimit): string | undefined {
18
+ const depth = { level: 0, max: limit > dataLimit ? 6 : 3 };
19
+ const unwrapped = unwrap(value);
20
+ if (isPlain(unwrapped)) {
21
+ const lines = fields(unwrapped, depth).map(([label, text]) => `${label}: ${text}`);
22
+ return lines.length ? truncate(lines.join('\n'), limit) : undefined;
23
+ }
24
+ const text = render(unwrapped, depth);
25
+ return text === undefined ? undefined : truncate(text, limit);
26
+ }
27
+
28
+ function unwrap(value: unknown): unknown {
29
+ return typeof (value as FeedbackRepresentable | null)?.toFeedback === 'function'
30
+ ? (value as FeedbackRepresentable).toFeedback()
31
+ : value;
32
+ }
33
+
34
+ function isPlain(value: unknown): value is Record<string, unknown> {
35
+ if (value === null || typeof value !== 'object') return false;
36
+ const prototype = Object.getPrototypeOf(value);
37
+ return prototype === Object.prototype || prototype === null;
38
+ }
39
+
40
+ /** `undefined` hides the value: it is a function, a DOM node, or an object made only of those. Strings are quoted below the top level so they stand apart from the punctuation around them. */
41
+ function render(input: unknown, depth: Depth): string | undefined {
42
+ const value = unwrap(input);
43
+ if (value === null) return 'null';
44
+ switch (typeof value) {
45
+ case 'undefined':
46
+ return 'undefined';
47
+ case 'string':
48
+ return depth.level > 0 ? JSON.stringify(value) : value;
49
+ case 'number':
50
+ return number(value);
51
+ case 'bigint':
52
+ return `${value}n`;
53
+ case 'boolean':
54
+ return String(value);
55
+ case 'function':
56
+ case 'symbol':
57
+ return undefined;
58
+ }
59
+ const object = value as object;
60
+ if (isOpaque(object)) return undefined;
61
+ if (object instanceof Date) return Number.isNaN(object.getTime()) ? 'Invalid Date' : object.toISOString();
62
+ if (object instanceof Error) return `${object.name}(${JSON.stringify(object.message)})`;
63
+ const deep = depth.level >= depth.max;
64
+ if (Array.isArray(object) || object instanceof Set) {
65
+ const values = [...object];
66
+ if (deep && values.length) return '[…]';
67
+ return `[${limited(values.map(entry => render(entry, next(depth))).filter(text => text !== undefined))}]`;
68
+ }
69
+ if (object instanceof Map) {
70
+ if (deep && object.size) return '[…]';
71
+ const pairs = [...object].map(
72
+ ([key, entry]) => `${render(key, next(depth)) ?? '…'}: ${render(entry, next(depth)) ?? '…'}`,
73
+ );
74
+ return pairs.length ? `[${limited(pairs)}]` : '[:]';
75
+ }
76
+ const name = isPlain(object) ? '' : (object.constructor?.name ?? '');
77
+ const [open, close] = name ? [`${name}(`, ')'] : ['{', '}'];
78
+ const keys = fieldNames(object);
79
+ if (deep && keys.length) return `${open}…${close}`;
80
+ const parts = fields(object, next(depth));
81
+ if (!parts.length && keys.length) return undefined;
82
+ return `${open}${parts.map(([label, text]) => `${label}: ${text}`).join(', ')}${close}`;
83
+ }
84
+
85
+ function fields(object: object, depth: Depth): [string, string][] {
86
+ const parts: [string, string][] = [];
87
+ for (const key of fieldNames(object)) {
88
+ let value: unknown;
89
+ try {
90
+ value = (object as Record<string, unknown>)[key];
91
+ } catch {
92
+ continue;
93
+ }
94
+ const text = render(value, depth);
95
+ if (text !== undefined) parts.push([key, text]);
96
+ }
97
+ return parts;
98
+ }
99
+
100
+ /** Own properties, then getters from the class. Svelte compiles a class's `$state` fields into getters on the prototype, so they would otherwise read as empty. */
101
+ function fieldNames(object: object): string[] {
102
+ const names = Object.keys(object);
103
+ for (
104
+ let prototype = Object.getPrototypeOf(object);
105
+ prototype && prototype !== Object.prototype;
106
+ prototype = Object.getPrototypeOf(prototype)
107
+ ) {
108
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(prototype))) {
109
+ if (descriptor.get && !names.includes(key)) names.push(key);
110
+ }
111
+ }
112
+ return names;
113
+ }
114
+
115
+ function isOpaque(object: object) {
116
+ return (
117
+ (typeof Node !== 'undefined' && object instanceof Node) ||
118
+ (typeof Window !== 'undefined' && object instanceof Window) ||
119
+ object instanceof Promise ||
120
+ object instanceof WeakMap ||
121
+ object instanceof WeakSet
122
+ );
123
+ }
124
+
125
+ function limited(parts: string[]) {
126
+ return parts.length > maxElements
127
+ ? [...parts.slice(0, maxElements), `… ${parts.length - maxElements} more`].join(', ')
128
+ : parts.join(', ');
129
+ }
130
+
131
+ /** Binary floating point turns 72.575 into 72.57477920000001, so floats keep 3 decimals, or 3 significant digits below 1, and switch to exponent notation where that would take more than 15 decimals. */
132
+ function number(value: number) {
133
+ if (!Number.isFinite(value) || Number.isInteger(value)) return String(value);
134
+ const magnitude = Math.abs(value);
135
+ const decimals = magnitude >= 1 ? 3 : 2 - Math.floor(Math.log10(magnitude));
136
+ if (decimals > 15)
137
+ return value
138
+ .toExponential(2)
139
+ .replace(/\.?0+e/, 'e')
140
+ .replace('e+', 'e');
141
+ const text = value.toFixed(decimals).replace(/\.?0+$/, '');
142
+ return text === '-0' ? '0' : text;
143
+ }
@@ -0,0 +1,9 @@
1
+ export * from './annotations.ts';
2
+ export * from './cardLayout.ts';
3
+ export * from './describe.ts';
4
+ export * from './model.ts';
5
+ export * from './problem.ts';
6
+ export * from './report.ts';
7
+ export * from './session.ts';
8
+ export * from './taskTitle.ts';
9
+ export * from './tree.ts';
@@ -0,0 +1,133 @@
1
+ export type Point = { x: number; y: number };
2
+ export type Size = { width: number; height: number };
3
+ export type Frame = Point & Size;
4
+
5
+ export type NodeKind = 'screen' | 'layer' | 'component' | 'element';
6
+
7
+ export type Node = {
8
+ id: number;
9
+ parent: number | null;
10
+ /** 0 for the base screen. Higher layers are presented on top. */
11
+ layer: number;
12
+ kind: NodeKind;
13
+ /** Component name, layer name, or element role. */
14
+ name: string;
15
+ /** Visible text of an element. */
16
+ label?: string;
17
+ frame: Frame;
18
+ /** `file:line`. Components always have one. Elements have one where the framework records it. */
19
+ source?: string;
20
+ data?: string;
21
+ };
22
+
23
+ export type ContextEntry = { name: string; value: string };
24
+
25
+ export type Capture = {
26
+ date: Date;
27
+ /** Size of the whole capture, taller than the window when the page scrolls. */
28
+ size: Size;
29
+ /** The part of the capture that was on screen when it was taken. */
30
+ visible: Frame;
31
+ /** Indexed by `Node.id`. Node 0 is the whole capture. */
32
+ nodes: Node[];
33
+ environment: ContextEntry[];
34
+ context: ContextEntry[];
35
+ screenName?: string;
36
+ };
37
+
38
+ export const contains = (frame: Frame, point: Point) =>
39
+ point.x >= frame.x && point.x < frame.x + frame.width && point.y >= frame.y && point.y < frame.y + frame.height;
40
+
41
+ export const area = (frame: Frame) => frame.width * frame.height;
42
+
43
+ export const title = (node: Node) => (node.label ? `${node.name} "${node.label}"` : node.name);
44
+
45
+ /** The node and its ancestors, from the node itself up to the screen. */
46
+ export function pathFrom(capture: Capture, id: number): Node[] {
47
+ const path: Node[] = [];
48
+ for (let current: number | null = id; current !== null; current = capture.nodes[current]!.parent) {
49
+ path.push(capture.nodes[current]!);
50
+ }
51
+ return path;
52
+ }
53
+
54
+ export function childrenOf(capture: Capture): number[][] {
55
+ const children: number[][] = capture.nodes.map(() => []);
56
+ for (const node of capture.nodes) if (node.parent !== null) children[node.parent]!.push(node.id);
57
+ return children;
58
+ }
59
+
60
+ export function depthsOf(capture: Capture): number[] {
61
+ const depths = capture.nodes.map(() => 0);
62
+ for (const node of capture.nodes) if (node.parent !== null) depths[node.id] = depths[node.parent]! + 1;
63
+ return depths;
64
+ }
65
+
66
+ /** Picks the most specific node under a point. Only the topmost layer covering the point competes, so a dialog hides the page it covers. */
67
+ export function hitTest(capture: Capture, point: Point): number {
68
+ const layer = Math.max(
69
+ 0,
70
+ ...capture.nodes.filter(node => node.kind === 'layer' && contains(node.frame, point)).map(node => node.layer),
71
+ );
72
+ const depths = depthsOf(capture);
73
+ let best: Node | undefined;
74
+ for (const node of capture.nodes) {
75
+ if (node.layer !== layer || node.kind === 'screen' || !contains(node.frame, point)) continue;
76
+ if (
77
+ !best ||
78
+ area(node.frame) < area(best.frame) ||
79
+ (area(node.frame) === area(best.frame) && depths[node.id]! > depths[best.id]!)
80
+ ) {
81
+ best = node;
82
+ }
83
+ }
84
+ return best?.id ?? 0;
85
+ }
86
+
87
+ /** Two nodes are the same kind of thing when they are the same component tag or the same element role. */
88
+ const sameKind = (a: Node, b: Node) =>
89
+ a.kind === b.kind && (a.kind === 'component' ? a.source === b.source : a.kind !== 'element' || a.name === b.name);
90
+
91
+ /**
92
+ * Nodes that play the same part as `id` in sibling components, such as the same button in every row of a list.
93
+ * Siblings are components with the same tag as a component on the node's path and the same enclosing component.
94
+ * Inside each, the node is found by walking down the same kinds at the same positions. The nearest component with
95
+ * siblings wins, so a tagged part inside a repeated row matches its copies in the other rows.
96
+ */
97
+ export function similar(capture: Capture, id: number): number[] {
98
+ const path = pathFrom(capture, id);
99
+ const children = childrenOf(capture);
100
+ const enclosing = (node: number) =>
101
+ pathFrom(capture, node)
102
+ .slice(1)
103
+ .find(above => above.kind !== 'element')?.id;
104
+ for (const [anchor, component] of path.entries()) {
105
+ if (component.kind !== 'component') continue;
106
+ const context = enclosing(component.id);
107
+ const steps = path.slice(0, anchor).map(node => ({
108
+ node,
109
+ index: children[node.parent!]!.filter(sibling => sameKind(capture.nodes[sibling]!, node)).indexOf(node.id),
110
+ }));
111
+ const matches: number[] = [];
112
+ for (const sibling of capture.nodes) {
113
+ if (sibling.id === component.id || !sameKind(sibling, component) || enclosing(sibling.id) !== context) continue;
114
+ let current: number | undefined = sibling.id;
115
+ for (const step of steps.toReversed()) {
116
+ if (current === undefined) break;
117
+ current = children[current]!.filter(child => sameKind(capture.nodes[child]!, step.node))[step.index];
118
+ }
119
+ if (current !== undefined) matches.push(current);
120
+ }
121
+ if (matches.length) return matches;
122
+ }
123
+ return [];
124
+ }
125
+
126
+ /** The `file:line` an item on this node points an agent at: its own, or the nearest one above it. */
127
+ export function nearestSource(capture: Capture, id: number): string | undefined {
128
+ return pathFrom(capture, id).find(node => node.source)?.source;
129
+ }
130
+
131
+ export function nearestComponent(capture: Capture, id: number): Node | undefined {
132
+ return pathFrom(capture, id).find(node => node.kind === 'component');
133
+ }
@@ -0,0 +1,51 @@
1
+ export type Fact = { label: string; value: string };
2
+
3
+ const describe = (error: unknown): string =>
4
+ error instanceof Error
5
+ ? `${error.name}: ${error.message}${error.cause === undefined ? '' : ` (cause: ${describe(error.cause)})`}`
6
+ : String(error);
7
+
8
+ /**
9
+ * A failure the editor shows: one line to read, and facts to expand and copy, so a post that fails can be diagnosed
10
+ * without reproducing it. The iOS package's `Problem` has the same facts.
11
+ */
12
+ export class Problem extends Error {
13
+ constructor(
14
+ message: string,
15
+ readonly facts: Fact[] = [],
16
+ ) {
17
+ super(message);
18
+ this.name = 'Problem';
19
+ }
20
+
21
+ /** Keeps a `Problem`'s own facts. Any other error gets its name, message, and cause. */
22
+ static from(error: unknown): Problem {
23
+ if (error instanceof Problem) return error;
24
+ return new Problem(error instanceof Error ? error.message : String(error), [
25
+ { label: 'Error', value: describe(error) },
26
+ ]);
27
+ }
28
+
29
+ /** A request that got no answer, or one it could not use. The body is cut at 2,000 characters. */
30
+ static request(method: string, url: string, status: number | undefined, body: string | undefined, error: unknown) {
31
+ const facts: Fact[] = [{ label: 'Request', value: `${method} ${url}` }];
32
+ if (status !== undefined) facts.push({ label: 'Status', value: String(status) });
33
+ if (body) facts.push({ label: 'Response', value: body.length > 2000 ? `${body.slice(0, 2000)}…` : body });
34
+ facts.push({ label: 'Error', value: describe(error) });
35
+ return new Problem(error instanceof Error ? error.message : String(error), facts);
36
+ }
37
+
38
+ /** `before` and `after` around the problem's own facts. */
39
+ with(before: Fact[] = [], after: Fact[] = []) {
40
+ return new Problem(this.message, [...before, ...this.facts, ...after]);
41
+ }
42
+
43
+ get details() {
44
+ return this.facts.map(fact => `${fact.label}: ${fact.value}`).join('\n');
45
+ }
46
+
47
+ /** What Copy puts on the clipboard. */
48
+ get text() {
49
+ return this.facts.length ? `${this.message}\n\n${this.details}` : this.message;
50
+ }
51
+ }