@stefan.inc/feedback-engine 1.6.3 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -208,12 +208,14 @@ Untagged content still appears. Buttons, links, fields, headings, images, and te
208
208
 
209
209
  ## Set up your app's coding agents
210
210
 
211
- [`skills/feedback-accessibility/SKILL.md`](https://github.com/smirea/feedback-engine/blob/master/skills/feedback-accessibility/SKILL.md) is the playbook for making screens accessible and precise to point at, with a section for Svelte and one for React: the accessibility rules, what to tag, and how to check a screen. To have your app's agents follow it, add this to the app's `AGENTS.md` (or `CLAUDE.md`), with `React` in place of `Svelte` for a React app:
211
+ The package ships the [`feedback-accessibility`](https://github.com/smirea/feedback-engine/blob/master/packages/web/skills/feedback-accessibility/SKILL.md) skill, the playbook for making screens accessible and precise to point at, with a section for Svelte and one for React: the accessibility rules, what to tag, and how to check a screen. Run this once from the app's root, after installing the package:
212
212
 
213
- ```md
214
- - When you build or change a Svelte screen, row, card, or chart, follow Feedback's accessibility skill. Read the latest with `gh api repos/smirea/feedback-engine/contents/skills/feedback-accessibility/SKILL.md -H 'Accept: application/vnd.github.raw'`.
213
+ ```sh
214
+ bunx feedback-engine init
215
215
  ```
216
216
 
217
+ It links the skill into `.agents/skills/feedback-accessibility`, where agents that read the `.agents` folder find it by name, and adds a Feedback section to `AGENTS.md`, between `feedback-engine` markers. The section tells every agent what the editor is, how to read an export someone hands it, which skill to follow when it changes a screen, and how to check a screen with [`capture()`](#drive-it-from-a-script). When the app also has a `CLAUDE.md` that does not mention `AGENTS.md`, the section goes there too. Commit both: the link points into `node_modules`, so the skill always matches the installed version. Run `init` again after an upgrade to refresh the section.
218
+
217
219
  ## Give feedback
218
220
 
219
221
  The editor works as on iOS, with these differences:
@@ -263,7 +265,7 @@ The token is the switch. With `PROCRASTIMATE_TOKEN` set, **ProcrastiMate** shows
263
265
 
264
266
  ## Drive it from a script
265
267
 
266
- `setupFeedbackEngine()` also puts the engine on `globalThis.__feedbackEngine`. `__feedbackEngine.present()` opens the editor without the click, and `__feedbackEngine.lastExport` holds the files of the last export as `{ name, blob }`, written when a Share menu entry is chosen. `scripts/readme-images.ts` in the repository does both with Playwright.
268
+ `setupFeedbackEngine()` also puts the engine on `globalThis.__feedbackEngine`. `__feedbackEngine.capture()` reads the page and returns its JSON export, the `FeedbackReport` type, with no items, without drawing the screenshot or opening the editor, so an agent can check what a tap on each part of a screen selects: `await page.evaluate(() => __feedbackEngine.capture())` in Playwright. `__feedbackEngine.present()` opens the editor without the click, and `__feedbackEngine.lastExport` holds the files of the last export as `{ name, blob }`, written when a Share menu entry is chosen. `scripts/readme-images.ts` in the repository does both with Playwright.
267
269
 
268
270
  ## Webhooks
269
271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stefan.inc/feedback-engine",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "In-app feedback for Svelte and React: point at a component, write what should change, and export its name, file:line, and data for an agent.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -20,7 +20,11 @@
20
20
  "url": "git+https://github.com/smirea/feedback-engine.git",
21
21
  "directory": "packages/web"
22
22
  },
23
+ "bin": {
24
+ "feedback-engine": "./src/cli/index.js"
25
+ },
23
26
  "files": [
27
+ "skills",
24
28
  "src",
25
29
  "!src/**/*.test.ts"
26
30
  ],
@@ -0,0 +1,214 @@
1
+ ---
2
+ name: feedback-accessibility
3
+ description: Make a SwiftUI, Svelte, or React screen accessible and precise to point at in Feedback captures. Use when you build or change a screen, row, card, or chart in an app that uses Feedback, or when a Feedback tap selects the wrong thing.
4
+ ---
5
+
6
+ # Accessibility first, Feedback tags on top
7
+
8
+ A Feedback capture is built from two sources:
9
+
10
+ 1. **Elements**: what assistive technology reads, such as a text, a button, an image, or one data point of a chart. Only leaf elements become nodes. A container is walked through, even when it has a label.
11
+ 2. **Components**: the named regions of your app, such as a card, a row, or a screen.
12
+
13
+ Each package finds them its own way:
14
+
15
+ | Package | Elements come from | Components come from |
16
+ | --- | --- | --- |
17
+ | [SwiftUI](#swiftui) | The accessibility tree | `.feedback(...)` tags. SwiftUI exposes no view hierarchy at runtime. |
18
+ | [Svelte](#svelte) | The DOM, with ARIA roles and names | `{@attach feedback(...)}` tags. A compiled component leaves no record in the page. |
19
+ | [React](#react) | The DOM, with ARIA roles and names | React's own component tree, with no tag. `ref={feedback(...)}` tags add regions drawn inline. |
20
+
21
+ A tap selects the smallest node under the finger. Where no element or component sits under the point, the tap falls through to the nearest enclosing component, usually the whole screen. The one exception: inside the box of a node that already has feedback, a tap selects that item so its feedback can be edited, and a second tap on the same spot drills down to the smallest node.
22
+
23
+ So get accessibility right for people who use assistive technology, then add tags only where a tap is still ambiguous.
24
+
25
+ ## The rule: one tap, one obvious target
26
+
27
+ Tap anywhere on a region a person would point at and say "this": a card, a chart, a row, a section, a toolbar control, or a value inside a card. The selection must be that region, or something inside it that clearly belongs to it. It fails when:
28
+
29
+ - the tap selects something larger than the region under the finger, such as the whole screen when you tap a chart or the gap inside a card;
30
+ - a value someone would comment on, such as the big number on a card, can't be reached because it merged into a bigger element and no component sits around it;
31
+ - two different regions select the same node.
32
+
33
+ Stop there. Margins, gaps between sections, and empty space below a short list may fall through. A tap that selects a labeled element inside a component is already precise.
34
+
35
+ Read the section for your package. Each one stands alone.
36
+
37
+ ## SwiftUI
38
+
39
+ ### Accessibility (do this first)
40
+
41
+ - Give every icon-only button and image link an `accessibilityLabel`. Toolbar buttons built with `Button("Title", systemImage:)` already have one.
42
+ - Hide decorative images, separators, and placeholder art (initials tiles, stand-in icons) with `.accessibilityHidden(true)`.
43
+ - Mark section titles with `.accessibilityAddTraits(.isHeader)`. Don't render an empty header for a section without a title: it leaves an empty element.
44
+ - Combine a row or small card whose parts read as one sentence with `.accessibilityElement(children: .combine)`, such as `"Weight, 181.6 lb, Tue"`. That's good for VoiceOver, and the combined element is the tap target.
45
+ - Keep a container with independent controls as `.contain` (the default). Don't combine buttons into their surroundings.
46
+ - A paged `TabView` that gets combined reads only "page N of M". Give it an explicit label that says what the page shows.
47
+ - Charts: label the chart (`.accessibilityLabel("Steps chart")`), and let Swift Charts expose one element per data point, or set `accessibilityLabel` and `accessibilityValue` on the marks. Each data point becomes a tap target. The chart itself still needs a tag (see below).
48
+ - Don't hide meaningful content from accessibility to make a capture tidier. Fix the capture with a tag instead.
49
+
50
+ ### What to tag
51
+
52
+ - End the `body` of every screen, sheet, and reusable view struct (a row, a card, a section) with `.feedback(self)`. It names the component after its type and reports its stored properties. A wrapper that only forwards to one child view with the same frame doesn't need its own tag.
53
+ - When a screen draws regions in helper functions or inline (`private func chart(...) -> some View`), tag each region a person would point at, where it's drawn: `.feedback("Chart", data: plot)`, `.feedback("Summary", data: summary)`. Name it with the noun the user would say. Extracting the region into a struct with `.feedback(self)` is just as good when it has its own inputs and state.
54
+ - Always tag drawings that expose no elements of their own, or only some: charts (their axes, gutters, and gaps between marks are not elements), `Canvas` and shape drawings (body maps, heat maps, progress bars), and photos.
55
+ - Tag cards and grouped boxes whose background shows a visible frame, so a tap on the padding or a label-free area selects the card.
56
+ - Tag repeated rows through their struct, so Feedback can outline the same part in sibling rows.
57
+ - Inside a `.combine`d card, tag the key values someone would comment on, even a single `Text` or `Label`, because combining removed their elements. Group a number with its unit in one stack and tag the stack. Tags are found separately from accessibility, so they survive `.combine`.
58
+
59
+ ### What not to tag
60
+
61
+ - Outside a `.combine`d view, don't tag a single `Text`, `Button`, `Image`, or `Toggle`. It's already an element.
62
+ - Don't tag pure layout stacks that draw nothing.
63
+ - Two tags with the same frame are harmless, but one is enough: the inner one gets the taps and the outer one only shows in the path.
64
+
65
+ ### Lists and Forms
66
+
67
+ A `List` or `Form` section has no frame a tag can measure, and a modifier on `Section` applies to each row, so don't tag `Section`. Rows of plain text already fill their cell. For a row with custom content, tag the row background, which fills the whole cell: `.listRowBackground(Color.surface.feedback("Row"))`.
68
+
69
+ ### Where the tag goes
70
+
71
+ - A modifier after a `ForEach`, after a bare `if`/`else` at the top of `body`, or on a `Section` either doesn't compile or tags every child. Put the tag on the branch's view, or wrap the branches in a `Group` with one child per branch.
72
+ - Put the tag before a screen-margin `.padding(.horizontal)`, or the region includes the margins.
73
+ - A design-system container that is a region in its own right (a truncated list, a legend) tags itself. Give it `file: String = #fileID, line: Int = #line` parameters and pass them to `.feedback(_:data:file:line:)`, so the capture names the call site instead of the container's own file.
74
+
75
+ ### Data
76
+
77
+ - Pass values the region already computed for drawing. Never `map`, `filter`, sort, or look things up just to build `data:`: it runs on every render.
78
+ - Omit `data:` when the elements inside already name everything.
79
+ - Component data is capped at 1,500 characters. Pass a summary, such as a count, when the view holds a large collection.
80
+ - Pass explicit `data:` for a view whose `@Binding` getter can trap (`Binding(get: { selection! })`): `.feedback(self)` reads bindings when the capture is taken.
81
+
82
+ ### Verify each screen
83
+
84
+ Do this after changing a screen, in a Debug simulator build with realistic data:
85
+
86
+ 1. Open the screen, shake with `xcrun simctl notify_post <udid> com.apple.UIKit.SimulatorShake`, and within 5 s press the **Add Feedback** pill the shake shows at the top center. With agent-device, press `'role=button label="Add Feedback"'`. The label alone also matches the pill's window, and that press lands in the middle of the screen. The editor can take about 3 s to open over a long list.
87
+ 2. Export the tree: add one item, then **Share › JSON**. The file is written when the share sheet opens. Read it from the app's data container, not the pasteboard: `"$(xcrun simctl get_app_container <udid> <bundle id> data)/tmp/feedback.json"`.
88
+ 3. [Replay every tap](#replay-every-tap) on the export.
89
+ 4. Spot-check with real taps on the regions you changed: every card, a chart's mark and its empty plot area, a row, and the key values. Read the selection title under the screenshot. Check targets before adding any feedback, or tap twice inside a numbered box, since a first tap there selects the item instead of the smallest node. The canvas is a scaled screenshot, so convert app points with its frame: the element named `Screenshot` inside the scroll area of the same name, from `agent-device snapshot -i --json`. With agent-device, press the converted point with `--settle`. The diff it prints has the new selection title. Press the title to show its `file:line` and data in a popover.
90
+ 5. Check that VoiceOver output didn't get worse: agent-device's snapshot lists the elements VoiceOver reads.
91
+
92
+ Agent-device's XCTest runner turns accessibility on for the whole simulator, which is the same state a capture switches on, so its snapshots are a fair preview of the elements. The tags only show up in a capture.
93
+
94
+ ## Svelte
95
+
96
+ ### Accessibility (do this first)
97
+
98
+ - Use the element that has the role: `<button>`, `<a href>`, `<input>`, `<select>`, `<h1>` to `<h6>`. A `<div onclick>` has no role, so it is not an element in a capture. If you must build a control from a `<div>`, give it its `role`.
99
+ - Give every icon-only button an `aria-label`, and every `<img>` an `alt`. An image with `alt=""` is decorative and left out.
100
+ - Hide decorative marks, such as a colored dot or an initials tile, with `aria-hidden="true"`.
101
+ - Name a field with a `<label>` around it or an `aria-label`. The capture reads the name and the value together, such as `Text field "Title, Bananas"`.
102
+ - A button or a link merges everything inside it into one element, such as `Link "Work 3"`. That is right for a row that reads as one sentence. Tag an inner part when it needs feedback of its own.
103
+ - Landmarks, lists, and groups (`<main>`, `<nav>`, `<section>`, `<ul>`, `role="group"`) are walked through and never become nodes, even with a label. Tag one when a tap on its padding should select it.
104
+ - A modal `<dialog>`, an open `popover`, and an `aria-modal="true"` dialog are layers of their own. Use one of them for anything that covers the page, so taps on it select only what is inside it.
105
+
106
+ ### Tags
107
+
108
+ - Put `{@attach feedback()}` on the root element of every screen, dialog, and reusable component. It names the component after its file and reports its props and `$state` variables. A route file is named after its folders, so name a screen yourself: `{@attach feedback('ListsScreen', () => ({ filter }))}`.
109
+ - Tag a region drawn inline where it is drawn: `{@attach feedback('Chart', () => plot)}`.
110
+ - Always tag drawings that expose no elements: an `<svg>` chart, a `<canvas>`, a photo.
111
+ - Tag cards and grouped boxes whose background shows a visible frame.
112
+ - A component needs one root element to tag. A component that renders several siblings has no frame, so tag each sibling or wrap them.
113
+ - Don't tag an element with `display: contents`. It has no box.
114
+ - Outside a button or a link, don't tag a single text, button, image, or field. It's already an element.
115
+
116
+ ### Data
117
+
118
+ - The data function runs when a capture is taken, never while rendering, so it may read whatever the component has. Keep it cheap anyway: a capture runs it for every tag on the page.
119
+ - A bare `feedback()` reports every prop and every `$state` variable. Pass a function when that is too much, such as a component that receives a large list: `{@attach feedback(undefined, () => ({ count: items.length }))}`.
120
+ - A class shows under its own name, such as `TodoStore(lists: [...])`. Give it a `toFeedback()` method to choose what it reports.
121
+
122
+ ### A way to open Feedback
123
+
124
+ - With a mouse, Alt+Meta+click on anything opens the editor with that element selected. There is nothing to build.
125
+ - A phone has no modifier keys, and a shake does not work on the web yet. The simplest trigger is `setupFeedbackEngine({ button: true })`, a round Feedback button in a corner of every screen that the person can drag out of the way. Where a button on every screen is in the way, add an entry to a menu the app already has, such as Settings or an account menu, that starts a countdown instead: `<button onclick={() => globalThis.__feedbackEngine?.countdown()}>Send Feedback</button>`. The page shows a pill that counts down from 5 and then captures, so the person has time to leave the menu and open the screen they mean.
126
+ - Don't call `present()` from a menu. It captures at once, so the capture is the menu.
127
+ - Show the entry only when `globalThis.__feedbackEngine` exists, so it is gone from a build that leaves Feedback out.
128
+
129
+ ### Verify each screen
130
+
131
+ Do this after changing a screen, against the dev server, with realistic data:
132
+
133
+ 1. Open the screen in Playwright and read the tree as Feedback sees it: `await page.evaluate(() => __feedbackEngine.capture())` returns the JSON export without opening the editor. Save it as `feedback.json`.
134
+ 2. [Replay every tap](#replay-every-tap) on the export.
135
+ 3. Spot-check with real clicks on the regions you changed and read the selection title in the panel. Open the editor with `await page.evaluate(() => __feedbackEngine.present())`, or the way a person does, with Alt+Meta+click: `await page.getByRole('heading').first().click({ modifiers: ['Alt', 'Meta'] })`. The screenshot is scaled, so convert page points with the bounding box of the element with the role `img` and the name `Screenshot`.
136
+ 4. Check both a development build and a production build if untagged elements matter: only a development build gives them a `file:line`.
137
+
138
+ ## React
139
+
140
+ The app has `feedbackEngineReact()` in its Vite config, before the React plugin, or its `next.config` is wrapped in `withFeedbackEngine()`. That is what finds the components and gives each one its name and `file:line`. In a Next.js app, only client components are found. A server component is not a node, and the elements it draws are.
141
+
142
+ ### Accessibility (do this first)
143
+
144
+ - Use the element that has the role: `<button>`, `<a href>`, `<input>`, `<select>`, `<h1>` to `<h6>`. A `<div onClick>` has no role, so it is not an element in a capture. If you must build a control from a `<div>`, give it its `role`.
145
+ - Give every icon-only button an `aria-label`, and every `<img>` an `alt`. An image with `alt=""` is decorative and left out.
146
+ - Hide decorative marks, such as a colored dot or an initials tile, with `aria-hidden="true"`.
147
+ - Name a field with a `<label>` around it or an `aria-label`. The capture reads the name and the value together, such as `Text field "Title, Bananas"`.
148
+ - A button or a link merges everything inside it into one element, such as `Link "Work 3"`. That is right for a row that reads as one sentence. A component inside it is still a node of its own.
149
+ - Landmarks, lists, and groups (`<main>`, `<nav>`, `<section>`, `<ul>`, `role="group"`) are walked through and never become nodes, even with a label. Make one the root element of a component, or tag it, when a tap on its padding should select it.
150
+ - A modal `<dialog>`, an open `popover`, and an `aria-modal="true"` dialog are layers of their own. Use one of them for anything that covers the page, including what you render through a portal, so taps on it select only what is inside it.
151
+
152
+ ### Components
153
+
154
+ Every component of the app is in a capture already, under its own name, with its props and the `file:line` of its declaration. So the work is in how you write components, not in tagging them:
155
+
156
+ - Declare each component at the top level of a `.jsx` or `.tsx` module, with a capitalized name: a function, a class, an arrow function, or a `memo` or `forwardRef` call. A component declared inside another function, and one exported as `export default () => …` without a name, is not found.
157
+ - Make each region a person would point at its own component: a row, a card, a chart, a section with a visible frame. Extracting it is the React way to name it, and repeated rows then get the faint outline of the same part in their siblings.
158
+ - Give a component one root element with the box you mean. A component that renders several elements is one box around all of them, which is rarely the region a person points at.
159
+ - Name a component with the noun the user would say. An anonymous wrapper such as `Wrapper` or `Container` reads badly in a path.
160
+ - A component that only arranges others, such as `App` around the router or a provider, is harmless. It shares its box with what is inside it, which gets the taps.
161
+ - A library's components, such as a router's `Link` or a UI kit's `Button`, are not nodes. The elements they draw still are. Wrap one in a component of your own when it is a region.
162
+
163
+ ### Tags
164
+
165
+ `feedback(name, data)` from `@stefan.inc/feedback-engine/react` returns a ref.
166
+
167
+ - Tag a region drawn inline where it is drawn: `<figure ref={feedback('Chart', () => plot)}>`. Extracting the region into a component is just as good when it has its own inputs.
168
+ - Always give drawings that expose no elements a component or a tag: an `<svg>` chart, a `<canvas>`, a photo.
169
+ - To report state, tag the component's root element under the component's own name: `<dialog ref={feedback('TodoDetailDialog', () => ({ item: draft }))}>`. The tag's data replaces the props. Any other name makes a second node inside the component.
170
+ - On an element that already has a ref, call both from one ref function: `ref={node => { tag(node); inputRef.current = node; }}`, with `const tag = feedback('Name')` in the component's body.
171
+ - Don't tag an element with `display: contents`. It has no box.
172
+ - Don't tag a single text, button, image, or field. It's already an element.
173
+
174
+ ### Data
175
+
176
+ - A component's data is its props. `children` and functions are left out, and a prop that is JSX reads as its tag, such as `<Icon>`.
177
+ - Hook state is not in a capture, because React keeps it without names. Report the state that explains what the screen shows, such as a filter, a draft, or the open item, with a tag under the component's name.
178
+ - Do the same when the props are too much, such as a component that receives a large list: `feedback('TodoList', () => ({ count: items.length }))`.
179
+ - The data function runs when a capture is taken, never while rendering, so it may read whatever the component has.
180
+ - A class shows under its own name, such as `TodoStore(lists: [...])`. Give it a `toFeedback()` method to choose what it reports.
181
+
182
+ ### A way to open Feedback
183
+
184
+ - With a mouse, Alt+Meta+click on anything opens the editor with that element selected. There is nothing to build.
185
+ - A phone has no modifier keys, and a shake does not work on the web yet. The simplest trigger is `setupFeedbackEngine({ button: true })`, a round Feedback button in a corner of every screen that the person can drag out of the way. Where a button on every screen is in the way, add an entry to a menu the app already has, such as Settings or an account menu, that starts a countdown instead: `<button onClick={() => globalThis.__feedbackEngine?.countdown()}>Send Feedback</button>`. The page shows a pill that counts down from 5 and then captures, so the person has time to leave the menu and open the screen they mean.
186
+ - Don't call `present()` from a menu. It captures at once, so the capture is the menu.
187
+ - Show the entry only when `globalThis.__feedbackEngine` exists, so it is gone from a build that leaves Feedback out.
188
+
189
+ ### Verify each screen
190
+
191
+ Do this after changing a screen, against the dev server, with realistic data:
192
+
193
+ 1. Open the screen in Playwright and read the tree as Feedback sees it: `await page.evaluate(() => __feedbackEngine.capture())` returns the JSON export without opening the editor. Save it as `feedback.json`.
194
+ 2. [Replay every tap](#replay-every-tap) on the export. Add `--wrapper App`, with the name of each component that wraps the whole app, so the screen's own component counts as the root.
195
+ 3. Read the tree for what should not be there: a component named after a wrapper, the same name twice in one path, or a screen component missing because it was declared inside another function.
196
+ 4. Spot-check with real clicks on the regions you changed and read the selection title in the panel. Open the editor with `await page.evaluate(() => __feedbackEngine.present())`, or the way a person does, with Alt+Meta+click: `await page.getByRole('heading').first().click({ modifiers: ['Alt', 'Meta'] })`. The screenshot is scaled, so convert page points with the bounding box of the element with the role `img` and the name `Screenshot`.
197
+ 5. Check a production build once: components keep their names and locations there, and untagged elements lose their `file:line`.
198
+
199
+ ## Replay every tap
200
+
201
+ `scripts/taps.js`, in this skill's folder, reads a `feedback.json` from any package. It is plain JavaScript, so `node` or `bun` runs it. In a web app it ships with the package:
202
+
203
+ ```sh
204
+ node node_modules/@stefan.inc/feedback-engine/skills/feedback-accessibility/scripts/taps.js feedback.json
205
+ ```
206
+
207
+ Without a local copy, such as in an iOS app, stream it from GitHub:
208
+
209
+ ```sh
210
+ gh api repos/smirea/feedback-engine/contents/packages/web/skills/feedback-accessibility/scripts/taps.js \
211
+ -H 'Accept: application/vnd.github.raw' | node - feedback.json
212
+ ```
213
+
214
+ It mirrors Feedback's hit testing on an 8 pt grid and prints the share of taps that fall through to a screen or layer root, the bands where most of a row falls through, and the elements that sit directly under a root. Every band should be a margin, a gap, or empty space, and every listed element should be a precise target on its own, such as a lone button. Anything else is a missing tag or, in React, a region that should be its own component. This covers the parts of a long screen that the editor canvas doesn't show without scrolling.
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // Plain JavaScript, so `node` and `bun` both run it, from a checkout, from node_modules, or piped in.
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ const usage = `Replays Feedback's tap selection over a JSON export and reports where taps fall through.
6
+
7
+ Usage: taps.js <feedback.json | -> [--step 8] [--wrapper App]...
8
+
9
+ A tap "falls through" when it selects the screen, a layer, or a component that is the root of
10
+ its screen or layer, such as the screen view's own \`.feedback(self)\`. The report lists the
11
+ fall-through share, the bands of the capture where most of a row falls through, and the
12
+ elements that sit directly under a root, which are the usual candidates for a missing tag.
13
+
14
+ React finds every component, so a component that wraps the whole app, such as \`App\`, sits
15
+ above each screen's own component. Name it with --wrapper, and the components directly under
16
+ it count as roots in its place.
17
+
18
+ Pass - to read the export from stdin.`;
19
+
20
+ const args = process.argv.slice(2);
21
+ if (args.length === 0 || args.includes('--help')) {
22
+ console.error(usage);
23
+ process.exit(args.length === 0 ? 1 : 0);
24
+ }
25
+ const option = name => args.flatMap((arg, index) => (arg === name && index + 1 < args.length ? [args[index + 1]] : []));
26
+ const step = Number(option('--step')[0] ?? 8);
27
+ const wrappers = new Set(option('--wrapper'));
28
+
29
+ const { nodes } = JSON.parse(readFileSync(args[0] === '-' ? 0 : args[0], 'utf8'));
30
+ const byId = new Map(nodes.map(node => [node.id, node]));
31
+
32
+ const depth = new Map();
33
+ for (const node of nodes) depth.set(node.id, node.parent === undefined ? 0 : depth.get(node.parent) + 1);
34
+
35
+ const contains = ({ frame }, x, y) =>
36
+ frame.x <= x && x <= frame.x + frame.width && frame.y <= y && y <= frame.y + frame.height;
37
+ const area = ({ frame }) => frame.width * frame.height;
38
+
39
+ // Mirrors hitTest in the package: only the topmost layer covering the point competes, then the smallest node wins, and
40
+ // the deeper one on a tie.
41
+ function hit(x, y) {
42
+ const layer = Math.max(
43
+ 0,
44
+ ...nodes.filter(node => node.kind === 'layer' && contains(node, x, y)).map(node => node.layer),
45
+ );
46
+ let best;
47
+ for (const node of nodes) {
48
+ if (node.layer !== layer || node.kind === 'screen' || !contains(node, x, y)) continue;
49
+ if (!best || area(node) < area(best) || (area(node) === area(best) && depth.get(node.id) > depth.get(best.id)))
50
+ best = node;
51
+ }
52
+ return best ?? nodes[0];
53
+ }
54
+
55
+ const roots = new Set([0, ...nodes.filter(node => node.kind === 'layer').map(node => node.id)]);
56
+ let under = new Set(roots);
57
+ while (under.size > 0) {
58
+ const found = nodes.filter(node => node.kind === 'component' && under.has(node.parent) && !roots.has(node.id));
59
+ for (const node of found) roots.add(node.id);
60
+ under = new Set(found.filter(node => wrappers.has(node.name)).map(node => node.id));
61
+ }
62
+
63
+ const title = node => {
64
+ const name = node.label ? `${node.name} "${node.label.slice(0, 50)}"` : node.name;
65
+ return `#${node.id} ${name}${node.source ? ` (${node.source})` : ''}`;
66
+ };
67
+ const format = value => String(Math.round(value * 1e6) / 1e6);
68
+
69
+ const { width, height } = nodes[0].frame;
70
+ const rows = [];
71
+ let total = 0;
72
+ let through = 0;
73
+ for (let y = step / 2; y < height; y += step) {
74
+ let row = 0;
75
+ let count = 0;
76
+ for (let x = step / 2; x < width; x += step) {
77
+ count++;
78
+ if (roots.has(hit(x, y).id)) row++;
79
+ }
80
+ rows.push([y, row / count]);
81
+ total += count;
82
+ through += row;
83
+ }
84
+
85
+ console.log(
86
+ `Fall-through: ${Math.round((through / total) * 100)}% of ${total} grid points (${format(step)} pt grid over ${format(width)}x${format(height)} pt)`,
87
+ );
88
+ console.log('Bands where most of a row falls through (often margins and gaps, sometimes a missing tag):');
89
+ let band;
90
+ for (const [y, share] of [...rows, [height + step, 0]]) {
91
+ if (share > 0.5) band ??= y;
92
+ else if (band !== undefined) {
93
+ console.log(` y ${Math.round(band - step / 2)}-${Math.round(y - step / 2)}`);
94
+ band = undefined;
95
+ }
96
+ }
97
+ console.log('Elements directly under a root (each should be fine on its own, or belong to a tagged region):');
98
+ for (const node of nodes) {
99
+ if (node.kind === 'element' && roots.has(node.parent) && node.parent !== 0) {
100
+ console.log(` ${title(node)} under ${title(byId.get(node.parent))}`);
101
+ }
102
+ }
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, relative, resolve } from 'node:path';
4
+
5
+ const name = '@stefan.inc/feedback-engine';
6
+ const skill = 'feedback-accessibility';
7
+ const start = '<!-- feedback-engine:start -->';
8
+ const end = '<!-- feedback-engine:end -->';
9
+
10
+ const usage = `Usage: feedback-engine init
11
+
12
+ Run it from the root of an app that has ${name} installed. It links the package's
13
+ ${skill} skill into .agents/skills, and adds a section to AGENTS.md that tells the app's
14
+ agents about the skill, the editor, and __feedbackEngine.capture(). Run it again after an
15
+ upgrade: the skill follows the installed version through the link, and the section is replaced.`;
16
+
17
+ function fail(message) {
18
+ console.error(`feedback-engine: ${message}`);
19
+ process.exit(1);
20
+ }
21
+
22
+ /** The installed package, through node_modules rather than its real path, so the link survives an upgrade. */
23
+ function installed(root) {
24
+ for (let folder = root; ; folder = dirname(folder)) {
25
+ const candidate = join(folder, 'node_modules', name);
26
+ if (existsSync(join(candidate, 'package.json'))) return candidate;
27
+ if (dirname(folder) === folder) fail(`${name} is not installed here. Add it first: bun add ${name}`);
28
+ }
29
+ }
30
+
31
+ function link(root, source) {
32
+ const target = join(root, '.agents', 'skills', skill);
33
+ mkdirSync(dirname(target), { recursive: true });
34
+ const existing = lstatSync(target, { throwIfNoEntry: false });
35
+ if (existing && !existing.isSymbolicLink()) {
36
+ fail(`${relative(root, target)} already exists and is not a link. Remove it, and init links the installed skill.`);
37
+ }
38
+ if (existing) unlinkSync(target);
39
+ // A relative link works in every clone of the app. Windows links folders only as junctions, which need an absolute path.
40
+ if (process.platform === 'win32') symlinkSync(source, target, 'junction');
41
+ else symlinkSync(relative(dirname(target), source), target, 'dir');
42
+ return target;
43
+ }
44
+
45
+ function section(root) {
46
+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
47
+ const dependencies = { ...manifest.dependencies, ...manifest.devDependencies };
48
+ const framework = dependencies.svelte && !dependencies.react ? 'Svelte' : 'React';
49
+ const run = existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb')) ? 'bun' : 'node';
50
+ return `${start}
51
+ ## Feedback
52
+
53
+ This app uses [Feedback](https://github.com/smirea/feedback-engine/tree/master/packages/web) (\`${name}\`) to collect feedback on its screens. In the running app, Alt+Meta+click anything to open the editor on it. An export someone hands you, \`feedback.png\`, \`feedback.json\`, or a ZIP of both, names the component or element of each note and its \`file:line\`. [The report format](https://github.com/smirea/feedback-engine/blob/master/spec/report.md) describes the JSON.
54
+
55
+ - When you build or change a ${framework} screen, row, card, or chart, follow the \`${skill}\` skill: \`.agents/skills/${skill}/SKILL.md\`.
56
+ - To see a screen as Feedback reads it, open it in a browser and run \`await page.evaluate(() => __feedbackEngine.capture())\`. It returns the JSON export without opening the editor. Save it as \`feedback.json\`, and \`${run} .agents/skills/${skill}/scripts/taps.js feedback.json\` replays every tap on it.
57
+ ${end}`;
58
+ }
59
+
60
+ /** Replaces the section between the markers, or appends it, and leaves the rest of the file as it was. */
61
+ function write(file, text) {
62
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
63
+ const from = current.indexOf(start);
64
+ const to = current.indexOf(end);
65
+ if ((from === -1) !== (to === -1) || to < from)
66
+ fail(`${file} has only one of the feedback-engine markers. Fix it by hand.`);
67
+ const next =
68
+ from === -1
69
+ ? `${current}${current && !current.endsWith('\n') ? '\n' : ''}${current ? '\n' : ''}${text}\n`
70
+ : `${current.slice(0, from)}${text}${current.slice(to + end.length)}`;
71
+ if (next !== current) writeFileSync(file, next);
72
+ return next !== current;
73
+ }
74
+
75
+ const [command, ...rest] = process.argv.slice(2);
76
+ if (command === '--help' || command === '-h') {
77
+ console.log(usage);
78
+ process.exit(0);
79
+ }
80
+ if (command !== 'init' || rest.length > 0) fail(`unknown command.\n\n${usage}`);
81
+
82
+ const root = resolve('.');
83
+ if (!existsSync(join(root, 'package.json'))) fail('run init from the folder that holds the app’s package.json.');
84
+ const source = join(installed(root), 'skills', skill);
85
+ if (!existsSync(join(source, 'SKILL.md'))) fail(`${source} has no SKILL.md. Upgrade ${name}.`);
86
+
87
+ const linked = link(root, source);
88
+ console.log(`Linked ${relative(root, linked)} to ${relative(root, source)}`);
89
+
90
+ const text = section(root);
91
+ const files = [join(root, 'AGENTS.md')];
92
+ // Claude Code reads CLAUDE.md and not AGENTS.md, unless CLAUDE.md points to it.
93
+ const claude = join(root, 'CLAUDE.md');
94
+ if (existsSync(claude) && !readFileSync(claude, 'utf8').includes('AGENTS.md')) files.push(claude);
95
+ for (const file of files) console.log(`${write(file, text) ? 'Updated' : 'Unchanged'} ${relative(root, file)}`);
@@ -14,8 +14,34 @@ const rect = (frame: Frame) => ({
14
14
  export const formatNumber = (value: number) =>
15
15
  Number.isFinite(value) ? (Number.isInteger(value) ? String(value) : value.toFixed(1)) : String(value);
16
16
 
17
+ type Rect = { x: number; y: number; width: number; height: number };
18
+ type Pointer = { target: number; title: string; path: number[]; code?: string };
19
+
20
+ /** The JSON export, as `spec/report.md` defines it. */
21
+ export type FeedbackReport = {
22
+ app: string;
23
+ captured: string;
24
+ size: { width: number; height: number };
25
+ visible: Rect;
26
+ environment: { name: string; value: string }[];
27
+ items: (Pointer & { number: number; text: string })[];
28
+ references: (Pointer & { number: number; token: string })[];
29
+ context: { name: string; value: string }[];
30
+ nodes: {
31
+ id: number;
32
+ parent?: number;
33
+ layer: number;
34
+ kind: 'screen' | 'layer' | 'component' | 'element';
35
+ name: string;
36
+ label?: string;
37
+ frame: Rect;
38
+ source?: string;
39
+ data?: string;
40
+ }[];
41
+ };
42
+
17
43
  /** The JSON export as an object: everything the capture knows except the image. */
18
- export function report(capture: Capture, annotations: Annotations) {
44
+ export function report(capture: Capture, annotations: Annotations): FeedbackReport {
19
45
  const pointer = (target: number) => ({
20
46
  target,
21
47
  title: title(capture.nodes[target]!),
@@ -40,10 +40,10 @@ function environment(options: CaptureOptions, date: Date): ContextEntry[] {
40
40
  }
41
41
 
42
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.
43
+ * Reads the page at the moment of the trigger. The window scrolls to its origin while the page is read, so a sticky
44
+ * bar is where the screenshot draws it, and then returns to where it was.
45
45
  */
46
- export async function captureScreen(options: CaptureOptions): Promise<Screen> {
46
+ function readPage(options: CaptureOptions) {
47
47
  const date = new Date();
48
48
  const scroll = { x: scrollX, y: scrollY };
49
49
  const context = options.context.flatMap(({ name, value }) => {
@@ -60,19 +60,24 @@ export async function captureScreen(options: CaptureOptions): Promise<Screen> {
60
60
  const scene = readScene(scroll);
61
61
  if (moved) scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });
62
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,
63
+ const capture: Capture = {
64
+ date,
65
+ size: scene.size,
66
+ visible: { x: scroll.x, y: scroll.y, width: innerWidth, height: innerHeight },
67
+ nodes: buildTree(scene),
68
+ environment: environment(options, date),
69
+ context,
70
+ screenName: document.title || undefined,
77
71
  };
72
+ return { capture, scene };
73
+ }
74
+
75
+ /** Reads the page without drawing it, for automation that needs only the tree. */
76
+ export const captureTree = (options: CaptureOptions) => readPage(options).capture;
77
+
78
+ /** Reads the page and draws it. */
79
+ export async function captureScreen(options: CaptureOptions): Promise<Screen> {
80
+ const { capture, scene } = readPage(options);
81
+ const scale = captureScale(scene.size);
82
+ return { capture, image: await screenshot(scene.size, scale, capture.visible, scene.fixed), scale };
78
83
  }
@@ -1,6 +1,6 @@
1
1
  import { tick } from 'svelte';
2
- import type { Point } from '../core/index.ts';
3
- import { captureScreen, type Screen } from '../dom/capture.ts';
2
+ import { Annotations, reportJSON, type FeedbackReport, type Point } from '../core/index.ts';
3
+ import { captureScreen, captureTree, type Screen } from '../dom/capture.ts';
4
4
  import type { ProcrastimateConfig } from '../dom/procrastimate.ts';
5
5
  import { hostAttribute } from '../dom/tags.ts';
6
6
  import type { Webhook } from '../dom/webhook.ts';
@@ -139,6 +139,13 @@ export class Engine {
139
139
  }
140
140
  }
141
141
 
142
+ /** The JSON export of the page as it is now, with no items, without drawing it or opening the editor. */
143
+ report(): FeedbackReport {
144
+ const capture = captureTree({ app: this.options.app, version: this.options.version, context: this.providers });
145
+ // Through the export's own serializer, so the object has the file's keys, without the ones that have no value.
146
+ return JSON.parse(reportJSON(capture, new Annotations(), false));
147
+ }
148
+
142
149
  close() {
143
150
  const { focused } = this;
144
151
  this.screen = undefined;
@@ -1,6 +1,7 @@
1
1
  import { mount, unmount } from 'svelte';
2
2
  import { watchHold } from '../dom/hold.ts';
3
3
  import { hostAttribute } from '../dom/tags.ts';
4
+ import type { FeedbackReport } from '../core/index.ts';
4
5
  import { defaultShortcut, Engine, matchesShortcut, type FeedbackOptions } from './engine.ts';
5
6
  import Host from './Host.svelte';
6
7
 
@@ -17,6 +18,11 @@ export type FeedbackEngine = {
17
18
  * the screen they mean. Pressing the pill captures at once.
18
19
  */
19
20
  countdown(seconds?: number): void;
21
+ /**
22
+ * Reads the page as it is now and returns its JSON export, with no items, without drawing it or opening the editor.
23
+ * For agents and scripts that check a screen: `await page.evaluate(() => __feedbackEngine.capture())`.
24
+ */
25
+ capture(): Promise<FeedbackReport>;
20
26
  /** The files of the last export, for automation that cannot use the clipboard or a download. */
21
27
  readonly lastExport: { name: string; blob: Blob }[];
22
28
  /** Removes the shortcut and Feedback's UI from the page. */
@@ -24,7 +30,7 @@ export type FeedbackEngine = {
24
30
  };
25
31
 
26
32
  declare global {
27
- /** The engine of this page, for automation: `__feedbackEngine.present()` and `__feedbackEngine.lastExport`. */
33
+ /** The engine of this page, for automation: `__feedbackEngine.present()`, `__feedbackEngine.capture()`, and `__feedbackEngine.lastExport`. */
28
34
  var __feedbackEngine: FeedbackEngine | undefined;
29
35
  }
30
36
 
@@ -37,7 +43,15 @@ let current: { engine: FeedbackEngine; destroy: () => void } | undefined;
37
43
  */
38
44
  export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngine {
39
45
  if (typeof document === 'undefined') {
40
- return { context() {}, present: async () => {}, showPill() {}, countdown() {}, lastExport: [], destroy() {} };
46
+ return {
47
+ context() {},
48
+ present: async () => {},
49
+ showPill() {},
50
+ countdown() {},
51
+ capture: () => Promise.reject(new Error('Feedback captures only in a browser.')),
52
+ lastExport: [],
53
+ destroy() {},
54
+ };
41
55
  }
42
56
  current?.destroy();
43
57
 
@@ -99,6 +113,7 @@ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngi
99
113
  present: () => engine.present(),
100
114
  showPill: () => engine.showPill(),
101
115
  countdown: (seconds = 5) => engine.countdown(seconds),
116
+ capture: async () => engine.report(),
102
117
  get lastExport() {
103
118
  return engine.lastExport;
104
119
  },
@@ -3,7 +3,7 @@ import type { FeedbackOptions } from '../editor/engine.ts';
3
3
  import { setupFeedbackEngine as setup, type FeedbackEngine } from '../editor/setup.ts';
4
4
  import { readComponents } from './components.ts';
5
5
 
6
- export type { FeedbackRepresentable } from '../core/index.ts';
6
+ export type { FeedbackReport, FeedbackRepresentable } from '../core/index.ts';
7
7
  export { githubIcon, type Webhook, type WebhookValues } from '../dom/webhook.ts';
8
8
  export type { FeedbackOptions } from '../editor/engine.ts';
9
9
  export type { FeedbackEngine } from '../editor/setup.ts';
@@ -87,12 +87,43 @@ export type FeedbackEngine = {
87
87
  * the screen they mean. Pressing the pill captures at once.
88
88
  */
89
89
  countdown(seconds?: number): void;
90
+ /**
91
+ * Reads the page as it is now and returns its JSON export, with no items, without drawing it or opening the editor.
92
+ * For agents and scripts that check a screen: `await page.evaluate(() => __feedbackEngine.capture())`.
93
+ */
94
+ capture(): Promise<FeedbackReport>;
90
95
  /** The files of the last export, for automation that cannot use the clipboard or a download. */
91
96
  readonly lastExport: { name: string; blob: Blob }[];
92
97
  /** Removes the shortcut and Feedback's UI from the page. */
93
98
  destroy(): void;
94
99
  };
95
100
 
101
+ type Rect = { x: number; y: number; width: number; height: number };
102
+ type Pointer = { target: number; title: string; path: number[]; code?: string };
103
+
104
+ /** The JSON export, as `spec/report.md` defines it. */
105
+ export type FeedbackReport = {
106
+ app: string;
107
+ captured: string;
108
+ size: { width: number; height: number };
109
+ visible: Rect;
110
+ environment: { name: string; value: string }[];
111
+ items: (Pointer & { number: number; text: string })[];
112
+ references: (Pointer & { number: number; token: string })[];
113
+ context: { name: string; value: string }[];
114
+ nodes: {
115
+ id: number;
116
+ parent?: number;
117
+ layer: number;
118
+ kind: 'screen' | 'layer' | 'component' | 'element';
119
+ name: string;
120
+ label?: string;
121
+ frame: Rect;
122
+ source?: string;
123
+ data?: string;
124
+ }[];
125
+ };
126
+
96
127
  /** A value that Feedback describes as `toFeedback()` in its place, at any depth. */
97
128
  export type FeedbackRepresentable = { toFeedback(): unknown };
98
129
 
@@ -117,6 +148,6 @@ export const feedback: Named & {
117
148
  };
118
149
 
119
150
  declare global {
120
- /** The engine of this page, for automation: `__feedbackEngine.present()` and `__feedbackEngine.lastExport`. */
151
+ /** The engine of this page, for automation: `__feedbackEngine.present()`, `__feedbackEngine.capture()`, and `__feedbackEngine.lastExport`. */
121
152
  var __feedbackEngine: FeedbackEngine | undefined;
122
153
  }
@@ -1,7 +1,7 @@
1
1
  import type { Attachment } from 'svelte/attachments';
2
2
  import { tags } from '../dom/tags.ts';
3
3
 
4
- export type { FeedbackRepresentable } from '../core/index.ts';
4
+ export type { FeedbackReport, FeedbackRepresentable } from '../core/index.ts';
5
5
  export { githubIcon, type Webhook, type WebhookValues } from '../dom/webhook.ts';
6
6
  export type { FeedbackOptions } from '../editor/engine.ts';
7
7
  export { setupFeedbackEngine, type FeedbackEngine } from '../editor/setup.ts';