@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,74 @@
1
+ import type { Annotations } from './annotations.ts';
2
+ import { nearestSource, pathFrom, title, type Capture, type Frame } from './model.ts';
3
+
4
+ const round = (value: number) => Math.round(value * 10) / 10;
5
+
6
+ const rect = (frame: Frame) => ({
7
+ x: round(frame.x),
8
+ y: round(frame.y),
9
+ width: round(frame.width),
10
+ height: round(frame.height),
11
+ });
12
+
13
+ /** A whole number without decimals, anything else with one. */
14
+ export const formatNumber = (value: number) =>
15
+ Number.isFinite(value) ? (Number.isInteger(value) ? String(value) : value.toFixed(1)) : String(value);
16
+
17
+ /** The JSON export as an object: everything the capture knows except the image. */
18
+ export function report(capture: Capture, annotations: Annotations) {
19
+ const pointer = (target: number) => ({
20
+ target,
21
+ title: title(capture.nodes[target]!),
22
+ path: pathFrom(capture, target)
23
+ .map(node => node.id)
24
+ .toReversed(),
25
+ code: nearestSource(capture, target),
26
+ });
27
+ return {
28
+ app: capture.environment.find(entry => entry.name === 'App')?.value ?? 'App',
29
+ captured: capture.date.toISOString().replace(/\.\d+Z$/, 'Z'),
30
+ size: { width: round(capture.size.width), height: round(capture.size.height) },
31
+ visible: rect(capture.visible),
32
+ environment: capture.environment.map(({ name, value }) => ({ name, value })),
33
+ items: annotations.items.map(item => ({
34
+ number: annotations.number(item.target),
35
+ text: item.text,
36
+ ...pointer(item.target),
37
+ })),
38
+ references: annotations.used.map(reference => ({
39
+ number: reference.number,
40
+ token: reference.token,
41
+ ...pointer(reference.target),
42
+ })),
43
+ context: capture.context.map(({ name, value }) => ({ name, value })),
44
+ nodes: capture.nodes.map(node => ({
45
+ id: node.id,
46
+ parent: node.parent ?? undefined,
47
+ layer: node.layer,
48
+ kind: node.kind,
49
+ name: node.name,
50
+ label: node.label,
51
+ frame: rect(node.frame),
52
+ source: node.source,
53
+ data: node.data,
54
+ })),
55
+ };
56
+ }
57
+
58
+ function sorted(value: unknown): unknown {
59
+ if (Array.isArray(value)) return value.map(sorted);
60
+ if (value && typeof value === 'object') {
61
+ return Object.fromEntries(
62
+ Object.entries(value)
63
+ .filter(([, entry]) => entry !== undefined)
64
+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
65
+ .map(([key, entry]) => [key, sorted(entry)]),
66
+ );
67
+ }
68
+ return value;
69
+ }
70
+
71
+ /** One object with sorted keys. Keys without a value are left out. */
72
+ export function reportJSON(capture: Capture, annotations: Annotations, pretty = true) {
73
+ return JSON.stringify(sorted(report(capture, annotations)), null, pretty ? 2 : undefined);
74
+ }
@@ -0,0 +1,184 @@
1
+ import { Annotations, type FeedbackItem, type Reference } from './annotations.ts';
2
+ import { hitTest, pathFrom, similar, type Capture, type Node, type Point } from './model.ts';
3
+ import { reportJSON } from './report.ts';
4
+
5
+ /** Tapping a toast with a link opens it, such as the task a post created. */
6
+ export type Toast = { text: string; link?: string };
7
+
8
+ /** The editor's state and rules, without any drawing. */
9
+ export class Session {
10
+ readonly capture: Capture;
11
+ picked = 0;
12
+ /** How far up from the picked node the target sits. 0 is the picked node itself. */
13
+ level = 0;
14
+ /** A new item's text. It survives visits to targets that already have feedback. */
15
+ draft = '';
16
+ /** Unsaved changes to the target's existing feedback, dropped when the target changes. */
17
+ private revision: string | undefined;
18
+ toast: Toast | undefined;
19
+ readonly annotations = new Annotations();
20
+ /** What a tap picks while the text ends in `@`, and how far up from it the reference sits. */
21
+ private referencePick: number | undefined;
22
+ referenceLevel = 0;
23
+ /** The id of every item that was in a completed share. */
24
+ readonly shared = new Set<string>();
25
+
26
+ constructor(capture: Capture) {
27
+ this.capture = capture;
28
+ }
29
+
30
+ get items() {
31
+ return this.annotations.items;
32
+ }
33
+
34
+ /** Closing asks first when it would lose these, or a draft. */
35
+ get unshared() {
36
+ return this.items.filter(item => !this.shared.has(item.id));
37
+ }
38
+
39
+ markShared(items: FeedbackItem[]) {
40
+ for (const item of items) this.shared.add(item.id);
41
+ }
42
+
43
+ get path() {
44
+ return pathFrom(this.capture, this.picked);
45
+ }
46
+
47
+ get target(): Node {
48
+ const path = this.path;
49
+ return path[Math.min(this.level, path.length - 1)]!;
50
+ }
51
+
52
+ get similar() {
53
+ return this.target.kind === 'screen' || this.isReferencing ? [] : similar(this.capture, this.target.id);
54
+ }
55
+
56
+ /** The item on the target itself. Its parent's or child's feedback belongs to that level. */
57
+ get editing() {
58
+ return this.items.find(item => item.target === this.target.id);
59
+ }
60
+
61
+ get text() {
62
+ return this.editing ? (this.revision ?? this.editing.text) : this.draft;
63
+ }
64
+
65
+ set text(value: string) {
66
+ if (this.editing) this.revision = value;
67
+ else this.draft = value;
68
+ if (!this.isReferencing) this.referencePick = undefined;
69
+ }
70
+
71
+ /** Typing `@` at the start of a word makes the next tap pick a node to reference instead of moving the target. Typing anything else leaves the mode. */
72
+ get isReferencing() {
73
+ const text = this.text;
74
+ return text.endsWith('@') && (text.length === 1 || /\s/.test(text.at(-2)!));
75
+ }
76
+
77
+ get referencePath() {
78
+ return this.isReferencing && this.referencePick !== undefined ? pathFrom(this.capture, this.referencePick) : [];
79
+ }
80
+
81
+ get referenceTarget(): Node | undefined {
82
+ const path = this.referencePath;
83
+ return path[Math.min(this.referenceLevel, path.length - 1)];
84
+ }
85
+
86
+ /** The references the items and the text being typed name, so their boxes show while typing. */
87
+ get visibleReferences(): Reference[] {
88
+ return this.annotations.referencesIn([...this.items.map(item => item.text), this.text]);
89
+ }
90
+
91
+ colorIndex(node: number) {
92
+ return this.annotations.colorIndex(node);
93
+ }
94
+
95
+ stepReference(level: number) {
96
+ this.referenceLevel = level;
97
+ }
98
+
99
+ /** Replaces the `@` with the reference target's token. */
100
+ insertReference() {
101
+ const node = this.referenceTarget;
102
+ if (!node) return;
103
+ this.text = `${this.text.slice(0, -1)}${this.annotations.reference(node).token} `;
104
+ }
105
+
106
+ private get trimmed() {
107
+ return this.text.trim();
108
+ }
109
+
110
+ get canSubmit() {
111
+ return this.trimmed !== '' && this.trimmed !== this.editing?.text;
112
+ }
113
+
114
+ /** Closing would lose a new item's text or changes to an existing one. */
115
+ get isTyping() {
116
+ return this.draft.trim() !== '' || (this.editing !== undefined && this.canSubmit);
117
+ }
118
+
119
+ /**
120
+ * A tap inside an item's box selects that item, so its feedback comes back. Tapping the same spot again drills
121
+ * down to the most specific node. Screens and layers cover everything, so their feedback never captures a tap.
122
+ */
123
+ pick(point: Point) {
124
+ const id = hitTest(this.capture, point);
125
+ if (this.isReferencing) {
126
+ this.referencePick = id;
127
+ this.referenceLevel = 0;
128
+ return;
129
+ }
130
+ const flagged = new Set(this.items.map(item => item.target));
131
+ const level = Math.max(
132
+ 0,
133
+ pathFrom(this.capture, id).findIndex(
134
+ node => flagged.has(node.id) && node.kind !== 'screen' && node.kind !== 'layer',
135
+ ),
136
+ );
137
+ const drillsDown = id === this.picked && this.level === level;
138
+ this.retarget(() => {
139
+ this.picked = id;
140
+ this.level = drillsDown ? 0 : level;
141
+ });
142
+ }
143
+
144
+ select(id: number) {
145
+ this.retarget(() => {
146
+ this.picked = id;
147
+ this.level = 0;
148
+ });
149
+ }
150
+
151
+ step(level: number) {
152
+ this.retarget(() => {
153
+ this.level = level;
154
+ });
155
+ }
156
+
157
+ /** Unsaved changes stay while the same node remains the target, such as a second tap on it. */
158
+ private retarget(change: () => void) {
159
+ const before = this.target.id;
160
+ change();
161
+ if (this.target.id !== before) this.revision = undefined;
162
+ if (!this.isReferencing) this.referencePick = undefined;
163
+ }
164
+
165
+ submit() {
166
+ const text = this.trimmed;
167
+ if (!text) return;
168
+ if (!this.editing) this.draft = '';
169
+ this.annotations.submit(text, this.target.id);
170
+ this.select(0);
171
+ }
172
+
173
+ remove(id: string) {
174
+ this.annotations.remove(id);
175
+ }
176
+
177
+ get json() {
178
+ return reportJSON(this.capture, this.annotations);
179
+ }
180
+
181
+ get compactJSON() {
182
+ return reportJSON(this.capture, this.annotations, false);
183
+ }
184
+ }
@@ -0,0 +1,35 @@
1
+ import type { FeedbackItem } from './annotations.ts';
2
+ import { title, type Capture } from './model.ts';
3
+
4
+ export const taskTitleInstructions =
5
+ 'You name tasks for a developer. Given feedback items about an app screen, reply with one lowercase phrase of at ' +
6
+ 'most 8 words that covers every item, such as "bigger titles, remove the share button". No quotes, no trailing ' +
7
+ 'period, no preamble.';
8
+
9
+ /** A ProcrastiMate task's name: `<screen> Feedback: N changes` at first, then `N <screen> Feedback: <summary>` once a model has summarized the items. */
10
+ export function taskTitle(capture: Capture, items: FeedbackItem[]) {
11
+ const subject = [capture.screenName ?? capture.environment.find(entry => entry.name === 'App')?.value, 'Feedback']
12
+ .filter(Boolean)
13
+ .join(' ');
14
+ const count = items.length;
15
+ return {
16
+ subject,
17
+ count,
18
+ prompt: items
19
+ .map(
20
+ item =>
21
+ `- On ${title(capture.nodes[item.target]!)}: ${item.text
22
+ .split(/[\r\n]+/)
23
+ .filter(Boolean)
24
+ .join(' ')}`,
25
+ )
26
+ .join('\n'),
27
+ placeholder: `${subject}: ${count} ${count === 1 ? 'change' : 'changes'}`,
28
+ /** The model's reply on one line without the wrapping it sometimes adds. `undefined` when nothing is left, so the placeholder stays. */
29
+ summarized(reply: string) {
30
+ const line = reply.split(/[\r\n]+/).find(Boolean) ?? '';
31
+ const summary = line.replace(/^[\s"'“”‘’`*]+|[\s"'“”‘’`*]+$/g, '').replace(/^[.\s]+|[.\s]+$/g, '');
32
+ return summary ? `${count} ${subject}: ${summary}` : undefined;
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,117 @@
1
+ import type { Frame, Node, Size } from './model.ts';
2
+
3
+ /** What a platform reads off the live page, before it becomes a numbered tree. */
4
+ export type RawNode = {
5
+ /** Index of the nearest node above it in `RawScene.nodes`, or `null` directly under its layer. */
6
+ parent: number | null;
7
+ layer: number;
8
+ kind: 'component' | 'element';
9
+ name: string;
10
+ label?: string;
11
+ frame: Frame;
12
+ source?: string;
13
+ data?: string;
14
+ };
15
+
16
+ export type RawScene = {
17
+ size: Size;
18
+ /** Index 0 is the base screen. Later layers are presented on top of earlier ones. */
19
+ layers: { name: string; frame: Frame }[];
20
+ nodes: RawNode[];
21
+ };
22
+
23
+ const usable = (frame: Frame) =>
24
+ frame.width > 0 &&
25
+ frame.height > 0 &&
26
+ [frame.x, frame.y, frame.width, frame.height].every(value => Number.isFinite(value) && Math.abs(value) < 100_000);
27
+
28
+ const intersects = (a: Frame, b: Frame) =>
29
+ a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
30
+
31
+ const covers = (outer: Frame, inner: Frame) =>
32
+ outer.x <= inner.x &&
33
+ outer.y <= inner.y &&
34
+ outer.x + outer.width >= inner.x + inner.width &&
35
+ outer.y + outer.height >= inner.y + inner.height;
36
+
37
+ function clip(frame: Frame, bounds: Frame): Frame {
38
+ const x = Math.max(frame.x, bounds.x);
39
+ const y = Math.max(frame.y, bounds.y);
40
+ return {
41
+ x,
42
+ y,
43
+ width: Math.min(frame.x + frame.width, bounds.x + bounds.width) - x,
44
+ height: Math.min(frame.y + frame.height, bounds.y + bounds.height) - y,
45
+ };
46
+ }
47
+
48
+ type Entry = Omit<Node, 'id'>;
49
+
50
+ /**
51
+ * Numbers the scene depth-first in reading order, so every parent precedes its children. No tap can reach what a
52
+ * higher layer covers completely, so the tree leaves it out. Children of a node that is left out move to the nearest
53
+ * node above it that stays. Frames are clipped to the capture, so nothing reports a position outside the image.
54
+ */
55
+ export function buildTree(scene: RawScene): Node[] {
56
+ const screen = { x: 0, y: 0, ...scene.size };
57
+ const upper = scene.layers
58
+ .map((layer, index) => ({ index, frame: layer.frame }))
59
+ .slice(1)
60
+ .filter(layer => usable(layer.frame));
61
+ const shown = (frame: Frame, layer: number) =>
62
+ usable(frame) &&
63
+ intersects(frame, screen) &&
64
+ !upper.some(cover => cover.index > layer && covers(cover.frame, frame));
65
+
66
+ const entries: Entry[] = [{ parent: null, layer: 0, kind: 'screen', name: 'Screen', frame: screen }];
67
+ const layerEntry = [0];
68
+ for (const [index, layer] of scene.layers.entries()) {
69
+ if (index === 0) continue;
70
+ if (!shown(layer.frame, index)) {
71
+ layerEntry.push(0);
72
+ continue;
73
+ }
74
+ layerEntry.push(entries.length);
75
+ entries.push({ parent: 0, layer: index, kind: 'layer', name: layer.name, frame: layer.frame });
76
+ }
77
+
78
+ const entryOf: (number | undefined)[] = [];
79
+ for (const [index, raw] of scene.nodes.entries()) {
80
+ if (!shown(raw.frame, raw.layer)) continue;
81
+ let above = raw.parent;
82
+ while (above !== null && (entryOf[above] === undefined || scene.nodes[above]!.layer !== raw.layer)) {
83
+ above = scene.nodes[above]!.parent;
84
+ }
85
+ entryOf[index] = entries.length;
86
+ entries.push({
87
+ parent: above === null ? layerEntry[raw.layer]! : entryOf[above]!,
88
+ layer: raw.layer,
89
+ kind: raw.kind,
90
+ name: raw.name,
91
+ label: raw.label || undefined,
92
+ frame: raw.frame,
93
+ source: raw.source,
94
+ data: raw.data,
95
+ });
96
+ }
97
+
98
+ const children: number[][] = entries.map(() => []);
99
+ for (const [index, entry] of entries.entries()) if (entry.parent !== null) children[entry.parent]!.push(index);
100
+ const nodes: Node[] = [];
101
+ const visit = (index: number, parent: number | null) => {
102
+ const entry = entries[index]!;
103
+ const id = nodes.length;
104
+ nodes.push({ ...entry, id, parent, frame: clip(entry.frame, screen) });
105
+ const ordered = children[index]!.toSorted((a, b) => {
106
+ const first = entries[a]!;
107
+ const second = entries[b]!;
108
+ if (first.layer !== second.layer) return first.layer - second.layer;
109
+ return Math.abs(first.frame.y - second.frame.y) > 0.5
110
+ ? first.frame.y - second.frame.y
111
+ : first.frame.x - second.frame.x;
112
+ });
113
+ for (const child of ordered) visit(child, id);
114
+ };
115
+ visit(0, null);
116
+ return nodes;
117
+ }
@@ -0,0 +1,78 @@
1
+ import { buildTree, contextLimit, describe, type Capture, type ContextEntry } from '../core/index.ts';
2
+ import { readScene } from './scene.ts';
3
+ import { captureScale, screenshot } from './screenshot.ts';
4
+
5
+ export type Screen = { capture: Capture; image: HTMLCanvasElement; scale: number };
6
+
7
+ export type CaptureOptions = {
8
+ app?: string;
9
+ version?: string;
10
+ context: { name: string; value: () => unknown }[];
11
+ };
12
+
13
+ function browser() {
14
+ const brands = (
15
+ navigator as Navigator & { userAgentData?: { brands: { brand: string; version: string }[]; platform: string } }
16
+ ).userAgentData;
17
+ const brand = brands?.brands.find(entry => !/not.?a.?brand|chromium/i.test(entry.brand));
18
+ if (brand) return `${brand.brand} ${brand.version} · ${brands!.platform}`;
19
+ const agent = navigator.userAgent;
20
+ const match =
21
+ /(Firefox|Edg|Chrome)\/(\d+)/.exec(agent) ?? (/Version\/(\d+).*Safari/.exec(agent) && ['', 'Safari', RegExp.$1]);
22
+ const platform = /iPhone|iPad|Android|Mac OS X|Windows|Linux/.exec(agent)?.[0] ?? navigator.platform;
23
+ return match ? `${match[1] === 'Edg' ? 'Edge' : match[1]} ${match[2]} · ${platform}` : agent;
24
+ }
25
+
26
+ function environment(options: CaptureOptions, date: Date): ContextEntry[] {
27
+ const entries: (ContextEntry | false | undefined)[] = [
28
+ { name: 'App', value: options.app ?? (document.title || location.hostname) },
29
+ { name: 'Location', value: `${location.pathname}${location.search}${location.hash}` },
30
+ options.version !== undefined && { name: 'Version', value: options.version },
31
+ { name: 'Device', value: browser() },
32
+ {
33
+ name: 'Display',
34
+ value: `${innerWidth} × ${innerHeight} px @${Math.round(devicePixelRatio * 100) / 100}x · ${matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'} mode`,
35
+ },
36
+ { name: 'Captured', value: date.toISOString().replace(/\.\d+Z$/, 'Z') },
37
+ { name: 'Locale', value: navigator.language },
38
+ ];
39
+ return entries.filter(entry => !!entry);
40
+ }
41
+
42
+ /**
43
+ * Reads the page and draws it, at the moment of the trigger. The window scrolls to its origin while the page is read,
44
+ * so a sticky bar is where the screenshot draws it, and then returns to where it was.
45
+ */
46
+ export async function captureScreen(options: CaptureOptions): Promise<Screen> {
47
+ const date = new Date();
48
+ const scroll = { x: scrollX, y: scrollY };
49
+ const context = options.context.flatMap(({ name, value }) => {
50
+ try {
51
+ return [{ name, value: describe(value(), contextLimit) ?? '' }];
52
+ } catch (error) {
53
+ console.warn(`Feedback could not read the context ${name}`, error);
54
+ return [];
55
+ }
56
+ });
57
+ // Reading and scrolling back happen in one task, so the browser never paints the jump.
58
+ const moved = scroll.x !== 0 || scroll.y !== 0;
59
+ if (moved) scrollTo({ left: 0, top: 0, behavior: 'instant' });
60
+ const scene = readScene(scroll);
61
+ if (moved) scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });
62
+
63
+ const visible = { x: scroll.x, y: scroll.y, width: innerWidth, height: innerHeight };
64
+ const scale = captureScale(scene.size);
65
+ return {
66
+ capture: {
67
+ date,
68
+ size: scene.size,
69
+ visible,
70
+ nodes: buildTree(scene),
71
+ environment: environment(options, date),
72
+ context,
73
+ screenName: document.title || undefined,
74
+ },
75
+ image: await screenshot(scene.size, scale, visible, scene.fixed),
76
+ scale,
77
+ };
78
+ }