@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
@@ -0,0 +1,132 @@
1
+ <svelte:options css="injected" />
2
+
3
+ <script lang="ts">
4
+ import { Problem, taskTitle, type Fact, type FeedbackItem, type Session, type Toast } from '../core/index.ts';
5
+ import type { Screen } from '../dom/capture.ts';
6
+ import { buildExport } from '../dom/share.ts';
7
+ import { postId, postWebhook, type Webhook } from '../dom/webhook.ts';
8
+ import ProblemCard from './ProblemCard.svelte';
9
+
10
+ let {
11
+ screen,
12
+ session,
13
+ webhook,
14
+ onclose,
15
+ onposted,
16
+ }: {
17
+ screen: Screen;
18
+ session: Session;
19
+ webhook: Webhook;
20
+ onclose: () => void;
21
+ onposted: (items: FeedbackItem[], toast: Toast) => void;
22
+ } = $props();
23
+
24
+ // The editor makes a new sheet for each post, so the first values are the only ones.
25
+ // svelte-ignore state_referenced_locally
26
+ const items = [...session.items];
27
+ // svelte-ignore state_referenced_locally
28
+ const title = taskTitle(session.capture, items).placeholder;
29
+ // svelte-ignore state_referenced_locally
30
+ const report = session.compactJSON;
31
+ const id = postId();
32
+ let step = $state('Drawing the image');
33
+ let problem = $state<Problem>();
34
+
35
+ async function post() {
36
+ problem = undefined;
37
+ step = 'Drawing the image';
38
+ const started = performance.now();
39
+ const facts: Fact[] = [
40
+ { label: 'Post', value: id },
41
+ { label: 'Report', value: `${new TextEncoder().encode(report).length} bytes` },
42
+ ];
43
+ try {
44
+ const { image } = await buildExport(screen, session.annotations, 'image');
45
+ facts.push({ label: 'Image', value: `${image!.size} bytes` });
46
+ step = `Sending to ${webhook.name}`;
47
+ const link = await postWebhook(webhook, { id, title, image: image!, report });
48
+ onposted(items, { text: `Sent to ${webhook.name}`, link });
49
+ } catch (error) {
50
+ const elapsed = { label: 'Elapsed', value: `${((performance.now() - started) / 1000).toFixed(1)} s` };
51
+ problem = Problem.from(error).with(
52
+ [{ label: 'Step', value: step }, elapsed],
53
+ [...facts, ...session.capture.environment.map(entry => ({ label: entry.name, value: entry.value }))],
54
+ );
55
+ }
56
+ }
57
+
58
+ void post();
59
+ </script>
60
+
61
+ <div class="scrim" role="presentation">
62
+ <div class="sheet" role="dialog" tabindex="-1" aria-label="Send to {webhook.name}">
63
+ <h2>{webhook.name}</h2>
64
+ {#if problem}
65
+ <ProblemCard {problem} />
66
+ <button type="button" class="strong" onclick={() => void post()}>Retry</button>
67
+ <button type="button" onclick={onclose}>Cancel</button>
68
+ {:else}
69
+ <p role="status">{step}…</p>
70
+ {/if}
71
+ </div>
72
+ </div>
73
+
74
+ <style>
75
+ .scrim {
76
+ position: absolute;
77
+ inset: 0;
78
+ z-index: 5;
79
+ display: grid;
80
+ place-items: end center;
81
+ background: rgb(0 0 0 / 0.5);
82
+ }
83
+
84
+ .sheet {
85
+ display: grid;
86
+ gap: 8px;
87
+ width: min(100%, 480px);
88
+ max-height: 85%;
89
+ border-radius: 16px 16px 0 0;
90
+ padding: 16px;
91
+ box-sizing: border-box;
92
+ background: #1f1f1f;
93
+ overflow: auto;
94
+ }
95
+
96
+ h2 {
97
+ margin: 0;
98
+ font-size: 16px;
99
+ text-align: center;
100
+ }
101
+
102
+ p {
103
+ margin: 0;
104
+ color: #aeaeb2;
105
+ text-align: center;
106
+ }
107
+
108
+ button {
109
+ border: 0;
110
+ border-radius: 12px;
111
+ padding: 12px;
112
+ background: #2c2c2e;
113
+ color: inherit;
114
+ font: inherit;
115
+ cursor: pointer;
116
+ }
117
+
118
+ .strong {
119
+ background: #0a84ff;
120
+ font-weight: 600;
121
+ }
122
+
123
+ @media (min-width: 900px) {
124
+ .scrim {
125
+ place-items: center;
126
+ }
127
+
128
+ .sheet {
129
+ border-radius: 16px;
130
+ }
131
+ }
132
+ </style>
@@ -0,0 +1,154 @@
1
+ import { tick } from 'svelte';
2
+ import type { Point } from '../core/index.ts';
3
+ import { captureScreen, type Screen } from '../dom/capture.ts';
4
+ import type { ProcrastimateConfig } from '../dom/procrastimate.ts';
5
+ import { hostAttribute } from '../dom/tags.ts';
6
+ import type { Webhook } from '../dom/webhook.ts';
7
+
8
+ export type FeedbackOptions = {
9
+ /** The app's name in exports. Defaults to the document's title. */
10
+ app?: string;
11
+ version?: string;
12
+ /**
13
+ * What opens Feedback. A chord that ends in `Click`, such as the default `Alt+Meta+Click`, opens the editor with the
14
+ * element under the pointer selected. A chord that ends in a key, such as `Alt+Shift+F`, shows the Add Feedback
15
+ * pill. `false` turns it off.
16
+ */
17
+ shortcut?: string | false;
18
+ /**
19
+ * Shows a round Feedback button on every screen, for a phone or an app opened from the home screen, which have no
20
+ * keyboard. Pressing it captures the page. Drag it to move it to another height or the other side.
21
+ */
22
+ button?: boolean;
23
+ /**
24
+ * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
25
+ * which adds the entry by itself when it has a token. Set it for a proxy of your own.
26
+ */
27
+ procrastimate?: ProcrastimateConfig;
28
+ /**
29
+ * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
30
+ * webhook's `url`, with nothing more to fill in.
31
+ */
32
+ webhooks?: Webhook[];
33
+ };
34
+
35
+ export const defaultShortcut = 'Alt+Meta+Click';
36
+ const pillSeconds = 5;
37
+
38
+ /**
39
+ * What the pill and the editor show. One per page. It is plain TypeScript, not a `.svelte.ts` module with runes: Vite
40
+ * pre-bundles a package from `node_modules`, and that step compiles such a module without removing its types.
41
+ */
42
+ export class Engine {
43
+ readonly options: FeedbackOptions;
44
+ readonly providers: { name: string; value: () => unknown }[] = [];
45
+ pill = false;
46
+ /** The seconds left before the pill captures by itself, while a countdown runs. */
47
+ remaining: number | undefined;
48
+ screen: Screen | undefined;
49
+ /** Where the user pointed to open the editor, in the capture's coordinates. The editor starts with that node selected. */
50
+ pointed: Point | undefined;
51
+ /** Called after `pill`, `remaining`, or `screen` changes, so the host draws again. */
52
+ onchange = () => {};
53
+ /** The files of the last export, for automation that cannot use the clipboard or a download. */
54
+ lastExport: { name: string; blob: Blob }[] = [];
55
+ private capturing = false;
56
+ /** What had focus before the pill or the editor took it, to give it back on close. */
57
+ private focused: Element | null = null;
58
+ private timer: ReturnType<typeof setTimeout> | undefined;
59
+
60
+ constructor(options: FeedbackOptions) {
61
+ this.options = options;
62
+ }
63
+
64
+ /** Shows the pill. Left alone, it leaves after five seconds, so an accidental trigger costs nothing. Triggering again restarts the timer. */
65
+ showPill() {
66
+ if (this.screen || this.capturing) return;
67
+ this.remember();
68
+ this.pill = true;
69
+ this.remaining = undefined;
70
+ this.onchange();
71
+ clearTimeout(this.timer);
72
+ this.timer = setTimeout(() => this.hidePill(), pillSeconds * 1000);
73
+ }
74
+
75
+ /**
76
+ * Shows the pill counting down, then captures. For a trigger inside a menu, which would otherwise capture the menu:
77
+ * the user has the countdown to reach the screen they mean. Pressing the pill captures at once.
78
+ */
79
+ countdown(seconds: number) {
80
+ if (this.screen || this.capturing) return;
81
+ this.remember();
82
+ this.pill = true;
83
+ this.remaining = seconds;
84
+ this.onchange();
85
+ clearTimeout(this.timer);
86
+ const count = () => {
87
+ this.remaining! -= 1;
88
+ if (this.remaining! <= 0) return void this.present();
89
+ this.onchange();
90
+ this.timer = setTimeout(count, 1000);
91
+ };
92
+ this.timer = setTimeout(count, 1000);
93
+ }
94
+
95
+ hidePill() {
96
+ clearTimeout(this.timer);
97
+ this.pill = false;
98
+ this.remaining = undefined;
99
+ this.onchange();
100
+ }
101
+
102
+ /** Captures the page and opens the editor. Does nothing while the editor is open. `at` is where the user pointed, in the window. */
103
+ async present(at?: Point) {
104
+ if (this.screen || this.capturing) return;
105
+ this.remember();
106
+ this.hidePill();
107
+ this.capturing = true;
108
+ this.pointed = at && { x: at.x + scrollX, y: at.y + scrollY };
109
+ try {
110
+ this.screen = await captureScreen({
111
+ app: this.options.app,
112
+ version: this.options.version,
113
+ context: this.providers,
114
+ });
115
+ this.onchange();
116
+ } finally {
117
+ this.capturing = false;
118
+ }
119
+ }
120
+
121
+ close() {
122
+ const { focused } = this;
123
+ this.screen = undefined;
124
+ this.onchange();
125
+ this.focused = null;
126
+ // The page stays inert until the editor's modal dialog is gone, and an inert element cannot take focus.
127
+ void tick().then(() => (focused instanceof HTMLElement && focused.isConnected ? focused.focus() : undefined));
128
+ }
129
+
130
+ private remember() {
131
+ const active = document.activeElement;
132
+ if (active && !active.hasAttribute(hostAttribute)) this.focused = active;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Whether an event is the shortcut: a click of the main button for a chord that ends in `Click`, a key press for any
138
+ * other. Letters match by physical key, since Alt changes the character a Mac types.
139
+ */
140
+ export function matchesShortcut(shortcut: string, event: KeyboardEvent | MouseEvent) {
141
+ const keys = shortcut.split('+').map(key => key.trim().toLowerCase());
142
+ const key = keys.pop()!;
143
+ const modifiers = { alt: event.altKey, shift: event.shiftKey, ctrl: event.ctrlKey, meta: event.metaKey };
144
+ const wanted = new Set(
145
+ keys.map(name =>
146
+ name === 'cmd' || name === 'command' ? 'meta' : name === 'control' ? 'ctrl' : name === 'option' ? 'alt' : name,
147
+ ),
148
+ );
149
+ if (Object.entries(modifiers).some(([name, pressed]) => pressed !== wanted.has(name))) return false;
150
+ if (key === 'click') return 'button' in event && event.button === 0;
151
+ if (!('code' in event)) return false;
152
+ const code = /^[a-z]$/.test(key) ? `Key${key.toUpperCase()}` : /^\d$/.test(key) ? `Digit${key}` : undefined;
153
+ return code ? event.code === code : event.key.toLowerCase() === key;
154
+ }
@@ -0,0 +1,106 @@
1
+ import { mount, unmount } from 'svelte';
2
+ import { hostAttribute } from '../dom/tags.ts';
3
+ import { defaultShortcut, Engine, matchesShortcut, type FeedbackOptions } from './engine.ts';
4
+ import Host from './Host.svelte';
5
+
6
+ export type FeedbackEngine = {
7
+ /** Registers app state to attach to every capture. `value` runs when a capture is taken. Registering a name again replaces the earlier one. */
8
+ context(name: string, value: () => unknown): void;
9
+ /** Captures the page and opens the editor. Does nothing while the editor is open. */
10
+ present(): Promise<void>;
11
+ /** Shows the Add Feedback pill, as a keyboard shortcut does. Pressing it captures the page. Left alone, it leaves after 5 seconds. */
12
+ showPill(): void;
13
+ /**
14
+ * Shows the pill counting down from `seconds`, 5 unless given, then captures the page and opens the editor. For a
15
+ * trigger inside one of the app's menus, such as on a phone: the user has the countdown to leave the menu and reach
16
+ * the screen they mean. Pressing the pill captures at once.
17
+ */
18
+ countdown(seconds?: number): void;
19
+ /** The files of the last export, for automation that cannot use the clipboard or a download. */
20
+ readonly lastExport: { name: string; blob: Blob }[];
21
+ /** Removes the shortcut and Feedback's UI from the page. */
22
+ destroy(): void;
23
+ };
24
+
25
+ declare global {
26
+ /** The engine of this page, for automation: `__feedbackEngine.present()` and `__feedbackEngine.lastExport`. */
27
+ var __feedbackEngine: FeedbackEngine | undefined;
28
+ }
29
+
30
+ let current: { engine: FeedbackEngine; destroy: () => void } | undefined;
31
+
32
+ /**
33
+ * Turns Feedback on: Alt+Meta+click on anything captures the page and opens the editor on what was clicked. Call it
34
+ * once, in the browser. On a server it returns an engine that does nothing, so a layout can call it without a guard.
35
+ */
36
+ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngine {
37
+ if (typeof document === 'undefined') {
38
+ return { context() {}, present: async () => {}, showPill() {}, countdown() {}, lastExport: [], destroy() {} };
39
+ }
40
+ current?.destroy();
41
+
42
+ // Written by `feedbackProcrastimate()` when it has a token. Vite replaces the whole member expression, so it stays in
43
+ // one piece. Webpack has no `import.meta.env`. The cast needs no `import.meta.env` type from the app.
44
+ type Meta = { env?: Record<string, string | undefined> };
45
+ const proxy = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE;
46
+ const engine = new Engine({
47
+ ...options,
48
+ procrastimate: options.procrastimate ?? (proxy ? { url: proxy } : undefined),
49
+ });
50
+ const host = document.createElement('div');
51
+ host.setAttribute(hostAttribute, '');
52
+ // The shadow root keeps the app's styles out of the editor and the editor's styles out of the app.
53
+ const root = host.attachShadow({ mode: 'open' });
54
+ document.documentElement.append(host);
55
+ const component = mount(Host, { target: root, props: { engine } });
56
+
57
+ const shortcut = options.shortcut ?? defaultShortcut;
58
+ const keydown = (event: KeyboardEvent) => {
59
+ if (shortcut && matchesShortcut(shortcut, event)) {
60
+ event.preventDefault();
61
+ engine.showPill();
62
+ }
63
+ };
64
+ const pointerEvents = ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click'] as const;
65
+ const pointer = (event: MouseEvent) => {
66
+ if (!shortcut || !matchesShortcut(shortcut, event) || event.composedPath().includes(host)) return;
67
+ // The click is for Feedback, so the app must not act on it, move focus, or start a text selection.
68
+ event.preventDefault();
69
+ event.stopImmediatePropagation();
70
+ // A disabled control sends pointer events and no click, and a person still points at it.
71
+ if (event.type === 'pointerup') void engine.present({ x: event.clientX, y: event.clientY });
72
+ };
73
+ const hidden = () => {
74
+ if (document.visibilityState === 'hidden') engine.hidePill();
75
+ };
76
+ addEventListener('keydown', keydown);
77
+ // In the capture phase, so the chord reaches Feedback before the element under the pointer.
78
+ for (const type of pointerEvents) addEventListener(type, pointer, true);
79
+ document.addEventListener('visibilitychange', hidden);
80
+
81
+ const api: FeedbackEngine = {
82
+ context(name, value) {
83
+ const index = engine.providers.findIndex(provider => provider.name === name);
84
+ if (index !== -1) engine.providers.splice(index, 1);
85
+ engine.providers.push({ name, value });
86
+ },
87
+ present: () => engine.present(),
88
+ showPill: () => engine.showPill(),
89
+ countdown: (seconds = 5) => engine.countdown(seconds),
90
+ get lastExport() {
91
+ return engine.lastExport;
92
+ },
93
+ destroy() {
94
+ removeEventListener('keydown', keydown);
95
+ for (const type of pointerEvents) removeEventListener(type, pointer, true);
96
+ document.removeEventListener('visibilitychange', hidden);
97
+ void unmount(component);
98
+ host.remove();
99
+ if (current?.engine === api) current = undefined;
100
+ globalThis.__feedbackEngine = undefined;
101
+ },
102
+ };
103
+ current = { engine: api, destroy: api.destroy };
104
+ globalThis.__feedbackEngine = api;
105
+ return api;
106
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Adds Feedback to a Next.js config, for Turbopack and for webpack: it registers the app's components for captures,
3
+ * compiles the editor, and writes each HTML element's `file:line` into a `data-feedback-source` attribute.
4
+ */
5
+ export function withFeedbackEngine<Config extends object>(
6
+ config?: Config,
7
+ options?: {
8
+ /** Writes each HTML element's `file:line` into the page. Defaults to `next dev` only. Set it for a deployed preview. */
9
+ elementSources?: boolean;
10
+ /** The folder paths are written from. Defaults to the working directory. */
11
+ root?: string;
12
+ },
13
+ ): Config;
@@ -0,0 +1,69 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ const loader = fileURLToPath(new URL('./loader.js', import.meta.url));
4
+ const packageName = '@stefan.inc/feedback-engine';
5
+
6
+ /**
7
+ * Adds Feedback to a Next.js config, for Turbopack and for webpack.
8
+ *
9
+ * - It registers every component in the app's `.jsx` and `.tsx` files with its name and `file:line`.
10
+ * - It compiles the editor's Svelte files.
11
+ * - It writes each HTML element's `file:line` into a `data-feedback-source` attribute: in `next dev` by default, and in
12
+ * every build with `elementSources: true`.
13
+ *
14
+ * @template {Record<string, any>} Config
15
+ * @param {Config} [config]
16
+ * @param {{ elementSources?: boolean, root?: string }} [options]
17
+ * @returns {Config}
18
+ */
19
+ export function withFeedbackEngine(config = /** @type {Config} */ ({}), options = {}) {
20
+ const root = options.root ?? process.cwd();
21
+ const use = (/** @type {{ elementSources?: boolean, generate?: 'client' | 'server' }} */ settings) => ({
22
+ loader,
23
+ options: { root, elementSources: false, generate: 'client', ...settings },
24
+ });
25
+
26
+ const app = { not: 'foreign' };
27
+ const turbopackRules = {
28
+ '*.svelte': [
29
+ { condition: 'browser', loaders: [use({ generate: 'client' })], as: '*.js' },
30
+ { condition: { not: 'browser' }, loaders: [use({ generate: 'server' })], as: '*.js' },
31
+ ],
32
+ '*.{jsx,tsx}': [
33
+ {
34
+ condition: { all: [app, 'development'] },
35
+ loaders: [use({ elementSources: options.elementSources ?? true })],
36
+ },
37
+ {
38
+ condition: { all: [app, { not: 'development' }] },
39
+ loaders: [use({ elementSources: options.elementSources ?? false })],
40
+ },
41
+ ],
42
+ };
43
+ const userWebpack = config.webpack;
44
+
45
+ return {
46
+ ...config,
47
+ transpilePackages: [...new Set([...(config.transpilePackages ?? []), packageName])],
48
+ turbopack: {
49
+ ...config.turbopack,
50
+ rules: { ...config.turbopack?.rules, ...turbopackRules },
51
+ },
52
+ /**
53
+ * @param {any} webpackConfig
54
+ * @param {{ dev: boolean, isServer: boolean }} context
55
+ */
56
+ webpack(webpackConfig, context) {
57
+ webpackConfig.module.rules.push(
58
+ { test: /\.svelte$/, use: [use({ generate: context.isServer ? 'server' : 'client' })] },
59
+ {
60
+ test: /\.[jt]sx$/,
61
+ exclude: /[\\/]node_modules[\\/]/,
62
+ enforce: 'pre',
63
+ use: [use({ elementSources: options.elementSources ?? context.dev })],
64
+ },
65
+ );
66
+ return typeof userWebpack === 'function' ? userWebpack(webpackConfig, context) : webpackConfig;
67
+ },
68
+ };
69
+ }
@@ -0,0 +1,23 @@
1
+ import { relative, sep } from 'node:path';
2
+ import { addReact, compileEditor, packageSource } from '../vite/react.js';
3
+
4
+ /**
5
+ * The webpack loader that `withFeedbackEngine()` gives Turbopack and webpack. It compiles the editor's Svelte files, and
6
+ * runs `addReact` on the app's `.jsx` and `.tsx` modules.
7
+ *
8
+ * @this {{ resourcePath: string, getOptions(): { root: string, elementSources: boolean, generate: 'client' | 'server' } }}
9
+ * @param {string} code
10
+ */
11
+ function feedbackLoader(code) {
12
+ const file = this.resourcePath;
13
+ const options = this.getOptions();
14
+ if (file.endsWith('.svelte'))
15
+ return file.startsWith(packageSource) ? compileEditor(code, file, options.generate).code : code;
16
+ if (file.includes(`${sep}node_modules${sep}`) || file.startsWith(packageSource)) return code;
17
+ return (
18
+ addReact(code, relative(options.root, file).split(sep).join('/'), { elementSources: options.elementSources }) ??
19
+ code
20
+ );
21
+ }
22
+
23
+ export default feedbackLoader;
@@ -0,0 +1,101 @@
1
+ import type { Component } from '../dom/tags.ts';
2
+
3
+ declare global {
4
+ /** What the Vite plugin registers: each component of the app, with its name and the `file:line` of its declaration. */
5
+ var __feedbackComponents: WeakMap<object, [name: string, source: string]> | undefined;
6
+ }
7
+
8
+ /** The fields of a fiber, React's record of one rendered component or element. They are internal to React and have kept these names since React 17. */
9
+ type Fiber = {
10
+ tag: number;
11
+ type: unknown;
12
+ elementType: unknown;
13
+ stateNode: unknown;
14
+ memoizedProps: unknown;
15
+ child: Fiber | null;
16
+ sibling: Fiber | null;
17
+ };
18
+
19
+ const portal = 4;
20
+ /** A `<title>` or `<link>` that React 19 moves to the head. It is not a part of what its component draws. */
21
+ const hoisted = 26;
22
+ /** Function, class, `forwardRef`, and `memo` components. */
23
+ const composites = new Set([0, 1, 11, 14, 15]);
24
+
25
+ const registered = (type: unknown) =>
26
+ typeof type === 'function' || (typeof type === 'object' && type !== null)
27
+ ? globalThis.__feedbackComponents?.get(type)
28
+ : undefined;
29
+
30
+ /** The fiber tree React shows now, for every React root on the page. A DOM node's own fiber can be the previous render's. */
31
+ function trees(): Fiber[] {
32
+ const found: Fiber[] = [];
33
+ for (const node of [document, ...document.querySelectorAll('*')]) {
34
+ for (const key of Object.keys(node)) {
35
+ if (!key.startsWith('__reactContainer$')) continue;
36
+ // React empties the marker of a root that was unmounted, and leaves the property.
37
+ const root = (node as unknown as Record<string, { stateNode: { current: Fiber } } | null>)[key];
38
+ if (root) found.push(root.stateNode.current);
39
+ }
40
+ }
41
+ return found;
42
+ }
43
+
44
+ /** A prop that is JSX reads as its tag, such as `<Icon>`, instead of React's record of it. */
45
+ function shown(value: unknown) {
46
+ if (typeof value !== 'object' || value === null || !('$$typeof' in value)) return value;
47
+ const { type } = value as { type?: unknown };
48
+ if (typeof type === 'string') return `<${type}>`;
49
+ const named = type as { displayName?: string; name?: string } | undefined;
50
+ return `<${registered(type)?.[0] ?? named?.displayName ?? named?.name ?? 'Component'}>`;
51
+ }
52
+
53
+ /** A component's props as its data. `children` is what it draws, which the tree already shows, and a function says nothing. */
54
+ function data(props: unknown) {
55
+ if (typeof props !== 'object' || props === null) return undefined;
56
+ const entries = Object.entries(props)
57
+ .filter(([name, value]) => name !== 'children' && typeof value !== 'function')
58
+ .map(([name, value]) => [name, shown(value)] as const);
59
+ return entries.length ? () => Object.fromEntries(entries) : undefined;
60
+ }
61
+
62
+ /**
63
+ * Finds the app's components in React's own tree, so a capture needs no tag for them. A component counts when the
64
+ * Vite plugin registered it, which is how the app's components are told from a library's, and how a name survives a
65
+ * minified build. Its roots are the nearest elements it draws.
66
+ */
67
+ export function readComponents(): Map<Element, Component[]> {
68
+ const found = new Map<Element, Component[]>();
69
+ if (!globalThis.__feedbackComponents) return found;
70
+
71
+ /** Walks a fiber and its siblings, and returns the nearest elements they draw: in place, and through a portal. */
72
+ const walk = (first: Fiber | null) => {
73
+ const drawn = { own: [] as Element[], portal: [] as Element[] };
74
+ for (let fiber = first; fiber; fiber = fiber.sibling) {
75
+ if (fiber.tag === hoisted) continue;
76
+ if (typeof fiber.type === 'string' && fiber.stateNode instanceof Element) {
77
+ drawn.own.push(fiber.stateNode);
78
+ walk(fiber.child);
79
+ continue;
80
+ }
81
+ const below = walk(fiber.child);
82
+ const entry = composites.has(fiber.tag) ? (registered(fiber.type) ?? registered(fiber.elementType)) : undefined;
83
+ // What a component sends through a portal is a part of it, and its box only when it draws nothing in place.
84
+ const roots = below.own.length ? below.own : below.portal;
85
+ if (entry && roots.length) {
86
+ const component = { tag: { name: entry[0], source: entry[1], data: data(fiber.memoizedProps) }, roots };
87
+ for (const root of roots) found.set(root, [component, ...(found.get(root) ?? [])]);
88
+ }
89
+ if (fiber.tag === portal) {
90
+ drawn.portal.push(...below.own, ...below.portal);
91
+ } else {
92
+ drawn.own.push(...below.own);
93
+ drawn.portal.push(...below.portal);
94
+ }
95
+ }
96
+ return drawn;
97
+ };
98
+
99
+ for (const tree of trees()) walk(tree.child);
100
+ return found;
101
+ }
@@ -0,0 +1,44 @@
1
+ import { discovery, tags } from '../dom/tags.ts';
2
+ import type { FeedbackOptions } from '../editor/engine.ts';
3
+ import { setupFeedbackEngine as setup, type FeedbackEngine } from '../editor/setup.ts';
4
+ import { readComponents } from './components.ts';
5
+
6
+ export type { FeedbackRepresentable } from '../core/index.ts';
7
+ export { githubIcon, type Webhook, type WebhookValues } from '../dom/webhook.ts';
8
+ export type { FeedbackOptions } from '../editor/engine.ts';
9
+ export type { FeedbackEngine } from '../editor/setup.ts';
10
+
11
+ /**
12
+ * Turns Feedback on: Alt+Meta+click on anything captures the page and opens the editor on what was clicked. Call it
13
+ * once, in the browser, before or after React renders. On a server it returns an engine that does nothing.
14
+ */
15
+ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngine {
16
+ discovery.read = readComponents;
17
+ return setup(options);
18
+ }
19
+
20
+ type Ref = (element: Element | null) => void;
21
+ type Named = (name: string, data?: () => unknown) => Ref;
22
+
23
+ function tagged(source?: string): Named {
24
+ return (name, data) => {
25
+ let current: Element | undefined;
26
+ // React calls a ref with the element when it mounts and with `null` when it unmounts, and does both again on every render that passes a new function.
27
+ return element => {
28
+ if (current) tags.delete(current);
29
+ current = element ?? undefined;
30
+ if (element) tags.set(element, { name, data, source });
31
+ };
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Names an element in feedback captures: `<section ref={feedback('Chart', () => plot)}>`. The Vite plugin already
37
+ * finds every component of the app, so this is for a region drawn inline, and for a component's root element, under
38
+ * the component's own name, to report data that React keeps out of its props, such as state. `data` runs when a
39
+ * capture is taken.
40
+ */
41
+ export const feedback: Named & {
42
+ /** What the Vite plugin rewrites `feedback(` into. Not for app code. */
43
+ at(source: string): Named;
44
+ } = Object.assign(tagged(), { at: (source: string) => tagged(source) });