@stefan.inc/feedback-engine 1.6.3 → 1.7.1
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 +8 -6
- package/package.json +5 -1
- package/skills/feedback-accessibility/SKILL.md +214 -0
- package/skills/feedback-accessibility/scripts/taps.js +102 -0
- package/src/cli/index.js +128 -0
- package/src/core/extent.ts +37 -0
- package/src/core/index.ts +1 -0
- package/src/core/report.ts +27 -1
- package/src/dom/capture.ts +66 -22
- package/src/dom/image.ts +3 -3
- package/src/dom/screenshot.ts +147 -52
- package/src/editor/Editor.svelte +73 -5
- package/src/editor/engine.ts +13 -4
- package/src/editor/setup.ts +17 -2
- package/src/react/index.ts +1 -1
- package/src/react/public.d.ts +32 -1
- package/src/svelte/index.ts +1 -1
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
|
-
[`
|
|
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
|
-
```
|
|
214
|
-
|
|
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. In a monorepo, run it from the repository's root: it finds the package in the workspace that installed it, so the skill and the section sit where every agent in the repository reads them.
|
|
218
|
+
|
|
217
219
|
## Give feedback
|
|
218
220
|
|
|
219
221
|
The editor works as on iOS, with these differences:
|
|
@@ -246,7 +248,7 @@ The token is the switch. With `PROCRASTIMATE_TOKEN` set, **ProcrastiMate** shows
|
|
|
246
248
|
## How capture works
|
|
247
249
|
|
|
248
250
|
- The browser gives a page no way to read its own pixels without a permission prompt, so Feedback draws the DOM again into a canvas with [modern-screenshot](https://github.com/qq15725/modern-screenshot). On the example app, a scrolled page differs from the browser's own screenshot in under 0.5% of pixels, and a page with an open dialog in about 1%.
|
|
249
|
-
- The
|
|
251
|
+
- The document is copied in one pass, as vector images of the DOM, so the editor draws the part in view sharp at any zoom and the image export draws at the screen's pixel ratio. Nothing scrolls on screen. The window jumps to its origin and back inside one task, so a sticky bar is read where the document has it, and scroll listeners run.
|
|
250
252
|
- Content that stays put while the page scrolls, such as a `position: fixed` tab bar, is drawn where it was on screen, over the visible part of the capture.
|
|
251
253
|
- A modal `<dialog>`, an open popover, and an `aria-modal` dialog are separate layers. Clicks on a layer only select what is inside it, and whatever it hides completely is left out of the tree.
|
|
252
254
|
- Roles and names come from the DOM with [dom-accessibility-api](https://github.com/eps1lon/dom-accessibility-api). There is nothing to switch on first, and reading a screen takes a few milliseconds.
|
|
@@ -254,7 +256,7 @@ The token is the switch. With `PROCRASTIMATE_TOKEN` set, **ProcrastiMate** shows
|
|
|
254
256
|
## Limits
|
|
255
257
|
|
|
256
258
|
- The screenshot is a re-draw, not the screen's pixels. A `<canvas>`, an inline SVG, and an image from another origin that allows CORS are drawn. An image from an origin that does not allow CORS, a `<video>`, and an iframe can come out blank, and a field's placeholder is drawn in its text color. It is tested in Chromium, in Google Chrome, and in Playwright's WebKit, not in Safari itself.
|
|
257
|
-
- A
|
|
259
|
+
- A capture stops at 16,000 device pixels tall, 8,000 CSS pixels on a 2x screen, as on iOS, and ends between two rows. When the page was scrolled deep, it starts partway down with the part on screen near its middle.
|
|
258
260
|
- A scroll container inside the page shows what was on screen in it.
|
|
259
261
|
- A minified production build shows a class's minified name in component data, such as `a(count: 2)`.
|
|
260
262
|
- Element locations for untagged content exist only in development builds, unless a React app turns on `elementSources`. Components keep theirs in every build.
|
|
@@ -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.
|
|
3
|
+
"version": "1.7.1",
|
|
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
|
+
}
|
package/src/cli/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
lstatSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
symlinkSync,
|
|
9
|
+
unlinkSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from 'node:fs';
|
|
12
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
13
|
+
|
|
14
|
+
const name = '@stefan.inc/feedback-engine';
|
|
15
|
+
const skill = 'feedback-accessibility';
|
|
16
|
+
const start = '<!-- feedback-engine:start -->';
|
|
17
|
+
const end = '<!-- feedback-engine:end -->';
|
|
18
|
+
|
|
19
|
+
const usage = `Usage: feedback-engine init
|
|
20
|
+
|
|
21
|
+
Run it from the root of an app that has ${name} installed, or from the root of a
|
|
22
|
+
workspace whose app has it. It links the package's
|
|
23
|
+
${skill} skill into .agents/skills, and adds a section to AGENTS.md that tells the app's
|
|
24
|
+
agents about the skill, the editor, and __feedbackEngine.capture(). Run it again after an
|
|
25
|
+
upgrade: the skill follows the installed version through the link, and the section is replaced.`;
|
|
26
|
+
|
|
27
|
+
function fail(message) {
|
|
28
|
+
console.error(`feedback-engine: ${message}`);
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The workspace folders a root `package.json` lists, for the `dir/*` and plain-folder patterns npm, Bun, and Yarn take. */
|
|
33
|
+
function workspaces(root) {
|
|
34
|
+
const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
35
|
+
const patterns = Array.isArray(manifest.workspaces) ? manifest.workspaces : (manifest.workspaces?.packages ?? []);
|
|
36
|
+
return patterns.flatMap(pattern => {
|
|
37
|
+
if (!pattern.endsWith('/*')) return [join(root, pattern)];
|
|
38
|
+
const parent = join(root, pattern.slice(0, -2));
|
|
39
|
+
if (!existsSync(parent)) return [];
|
|
40
|
+
return readdirSync(parent, { withFileTypes: true })
|
|
41
|
+
.filter(entry => entry.isDirectory())
|
|
42
|
+
.map(entry => join(parent, entry.name));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The installed package, through node_modules rather than its real path, so the link survives an upgrade, and the app
|
|
48
|
+
* that depends on it. In a workspace whose packages each keep their own node_modules, as Bun's isolated installs do,
|
|
49
|
+
* that app is the workspace package that has it.
|
|
50
|
+
*/
|
|
51
|
+
function installed(root) {
|
|
52
|
+
const at = folder => join(folder, 'node_modules', name);
|
|
53
|
+
const has = folder => existsSync(join(at(folder), 'package.json'));
|
|
54
|
+
for (let folder = root; ; folder = dirname(folder)) {
|
|
55
|
+
if (has(folder)) return { source: at(folder), app: root };
|
|
56
|
+
if (dirname(folder) === folder) break;
|
|
57
|
+
}
|
|
58
|
+
const app = workspaces(root).find(has);
|
|
59
|
+
if (app) return { source: at(app), app };
|
|
60
|
+
fail(`${name} is not installed here. Add it first: bun add ${name}`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function link(root, source) {
|
|
64
|
+
const target = join(root, '.agents', 'skills', skill);
|
|
65
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
66
|
+
const existing = lstatSync(target, { throwIfNoEntry: false });
|
|
67
|
+
if (existing && !existing.isSymbolicLink()) {
|
|
68
|
+
fail(`${relative(root, target)} already exists and is not a link. Remove it, and init links the installed skill.`);
|
|
69
|
+
}
|
|
70
|
+
if (existing) unlinkSync(target);
|
|
71
|
+
// A relative link works in every clone of the app. Windows links folders only as junctions, which need an absolute path.
|
|
72
|
+
if (process.platform === 'win32') symlinkSync(source, target, 'junction');
|
|
73
|
+
else symlinkSync(relative(dirname(target), source), target, 'dir');
|
|
74
|
+
return target;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function section(root, app) {
|
|
78
|
+
const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8'));
|
|
79
|
+
const dependencies = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
80
|
+
const framework = dependencies.svelte && !dependencies.react ? 'Svelte' : 'React';
|
|
81
|
+
const run = existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb')) ? 'bun' : 'node';
|
|
82
|
+
return `${start}
|
|
83
|
+
## Feedback
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
- When you build or change a ${framework} screen, row, card, or chart, follow the \`${skill}\` skill: \`.agents/skills/${skill}/SKILL.md\`.
|
|
88
|
+
- 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.
|
|
89
|
+
${end}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Replaces the section between the markers, or appends it, and leaves the rest of the file as it was. */
|
|
93
|
+
function write(file, text) {
|
|
94
|
+
const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
95
|
+
const from = current.indexOf(start);
|
|
96
|
+
const to = current.indexOf(end);
|
|
97
|
+
if ((from === -1) !== (to === -1) || to < from)
|
|
98
|
+
fail(`${file} has only one of the feedback-engine markers. Fix it by hand.`);
|
|
99
|
+
const next =
|
|
100
|
+
from === -1
|
|
101
|
+
? `${current}${current && !current.endsWith('\n') ? '\n' : ''}${current ? '\n' : ''}${text}\n`
|
|
102
|
+
: `${current.slice(0, from)}${text}${current.slice(to + end.length)}`;
|
|
103
|
+
if (next !== current) writeFileSync(file, next);
|
|
104
|
+
return next !== current;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
108
|
+
if (command === '--help' || command === '-h') {
|
|
109
|
+
console.log(usage);
|
|
110
|
+
process.exit(0);
|
|
111
|
+
}
|
|
112
|
+
if (command !== 'init' || rest.length > 0) fail(`unknown command.\n\n${usage}`);
|
|
113
|
+
|
|
114
|
+
const root = resolve('.');
|
|
115
|
+
if (!existsSync(join(root, 'package.json'))) fail('run init from the folder that holds the app’s package.json.');
|
|
116
|
+
const { source: installation, app } = installed(root);
|
|
117
|
+
const source = join(installation, 'skills', skill);
|
|
118
|
+
if (!existsSync(join(source, 'SKILL.md'))) fail(`${source} has no SKILL.md. Upgrade ${name}.`);
|
|
119
|
+
|
|
120
|
+
const linked = link(root, source);
|
|
121
|
+
console.log(`Linked ${relative(root, linked)} to ${relative(root, source)}`);
|
|
122
|
+
|
|
123
|
+
const text = section(root, app);
|
|
124
|
+
const files = [join(root, 'AGENTS.md')];
|
|
125
|
+
// Claude Code reads CLAUDE.md and not AGENTS.md, unless CLAUDE.md points to it.
|
|
126
|
+
const claude = join(root, 'CLAUDE.md');
|
|
127
|
+
if (existsSync(claude) && !readFileSync(claude, 'utf8').includes('AGENTS.md')) files.push(claude);
|
|
128
|
+
for (const file of files) console.log(`${write(file, text) ? 'Updated' : 'Unchanged'} ${relative(root, file)}`);
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Frame } from './model.ts';
|
|
2
|
+
|
|
3
|
+
/** The tallest capture in device pixels, as on iOS, where Core Animation stops drawing a taller image. */
|
|
4
|
+
export const captureLimit = 16_000;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Where a capture that reaches its height limit should end: the lowest y from `floor` down to `limit` that no frame
|
|
8
|
+
* crosses, so the last row is whole. `undefined` when frames cover the whole range. iOS's `Stitch.cut`.
|
|
9
|
+
*/
|
|
10
|
+
export function cut(limit: number, floor: number, frames: Frame[]): number | undefined {
|
|
11
|
+
const candidates = [limit, ...frames.flatMap(frame => [frame.y, frame.y + frame.height])].filter(
|
|
12
|
+
y => y === limit || (y > floor && y < limit),
|
|
13
|
+
);
|
|
14
|
+
return candidates
|
|
15
|
+
.toSorted((a, b) => b - a)
|
|
16
|
+
.find(y => !frames.some(frame => frame.y < y - 0.5 && frame.y + frame.height > y + 0.5));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The part of a page a capture covers, from `top` down `height` points, by the iOS rules. A page up to `limit` tall is
|
|
21
|
+
* captured whole. A longer one is captured `limit` tall from its top, or, when the window is scrolled more than half
|
|
22
|
+
* the room the limit leaves below the screen, with the part on screen near the middle. A capture that stops before
|
|
23
|
+
* the page's end ends between two rows in its last screen, where none of `rows` crosses the cut.
|
|
24
|
+
*/
|
|
25
|
+
export function captureRange(page: number, screen: number, scroll: number, limit: number, rows: Frame[]) {
|
|
26
|
+
if (page <= limit) return { top: 0, height: page };
|
|
27
|
+
const reach = limit - screen;
|
|
28
|
+
const top = scroll > reach / 2 ? Math.max(0, Math.min(scroll - reach / 2, page - limit)) : 0;
|
|
29
|
+
const end = top + limit;
|
|
30
|
+
if (end >= page) return { top, height: page - top };
|
|
31
|
+
const ending = cut(
|
|
32
|
+
end,
|
|
33
|
+
end - screen,
|
|
34
|
+
rows.filter(row => row.height < screen),
|
|
35
|
+
);
|
|
36
|
+
return { top, height: (ending ?? end) - top };
|
|
37
|
+
}
|
package/src/core/index.ts
CHANGED
package/src/core/report.ts
CHANGED
|
@@ -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]!),
|
package/src/dom/capture.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import {
|
|
2
|
+
buildTree,
|
|
3
|
+
captureLimit,
|
|
4
|
+
captureRange,
|
|
5
|
+
contextLimit,
|
|
6
|
+
describe,
|
|
7
|
+
type Capture,
|
|
8
|
+
type ContextEntry,
|
|
9
|
+
type Frame,
|
|
10
|
+
} from '../core/index.ts';
|
|
11
|
+
import { readScene, type Scene } from './scene.ts';
|
|
12
|
+
import { takePicture, type Picture } from './screenshot.ts';
|
|
4
13
|
|
|
5
|
-
|
|
14
|
+
/**
|
|
15
|
+
* A capture and its picture. `image` is the whole picture on one canvas, at the screen's pixel ratio or lower when the
|
|
16
|
+
* capture is too large for one, which the editor shows until it draws the part in view sharp. `pixelRatio` is the
|
|
17
|
+
* screen's, the resolution an export aims for.
|
|
18
|
+
*/
|
|
19
|
+
export type Screen = { capture: Capture; picture: Picture; image: HTMLCanvasElement; pixelRatio: number };
|
|
6
20
|
|
|
7
21
|
export type CaptureOptions = {
|
|
8
22
|
app?: string;
|
|
@@ -39,11 +53,27 @@ function environment(options: CaptureOptions, date: Date): ContextEntry[] {
|
|
|
39
53
|
return entries.filter(entry => !!entry);
|
|
40
54
|
}
|
|
41
55
|
|
|
56
|
+
/** Moves the scene up by `top` and ends it `height` points down. The tree leaves out what is outside. */
|
|
57
|
+
function cropped(scene: Scene, top: number, height: number): Scene {
|
|
58
|
+
const up = (frame: Frame) => ({ ...frame, y: frame.y - top });
|
|
59
|
+
return {
|
|
60
|
+
size: { width: scene.size.width, height },
|
|
61
|
+
layers: scene.layers.map((layer, index) =>
|
|
62
|
+
index === 0
|
|
63
|
+
? { ...layer, frame: { x: 0, y: 0, width: scene.size.width, height } }
|
|
64
|
+
: { ...layer, frame: up(layer.frame) },
|
|
65
|
+
),
|
|
66
|
+
nodes: scene.nodes.map(node => ({ ...node, frame: up(node.frame) })),
|
|
67
|
+
fixed: scene.fixed.map(root => ({ ...root, frame: up(root.frame) })),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
42
71
|
/**
|
|
43
|
-
* Reads the page
|
|
44
|
-
*
|
|
72
|
+
* Reads the page at the moment of the trigger. The window scrolls to its origin while the page is read, so a sticky
|
|
73
|
+
* bar is where the picture draws it, and then returns to where it was. A page taller than iOS's limit of 16,000 pixels
|
|
74
|
+
* is captured by the iOS rules, which `captureRange` holds, and `top` is where the capture starts in the document.
|
|
45
75
|
*/
|
|
46
|
-
|
|
76
|
+
function readPage(options: CaptureOptions) {
|
|
47
77
|
const date = new Date();
|
|
48
78
|
const scroll = { x: scrollX, y: scrollY };
|
|
49
79
|
const context = options.context.flatMap(({ name, value }) => {
|
|
@@ -57,22 +87,36 @@ export async function captureScreen(options: CaptureOptions): Promise<Screen> {
|
|
|
57
87
|
// Reading and scrolling back happen in one task, so the browser never paints the jump.
|
|
58
88
|
const moved = scroll.x !== 0 || scroll.y !== 0;
|
|
59
89
|
if (moved) scrollTo({ left: 0, top: 0, behavior: 'instant' });
|
|
60
|
-
const
|
|
90
|
+
const page = readScene(scroll);
|
|
61
91
|
if (moved) scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });
|
|
62
92
|
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
},
|
|
75
|
-
|
|
76
|
-
|
|
93
|
+
const { top, height } = captureRange(
|
|
94
|
+
page.size.height,
|
|
95
|
+
innerHeight,
|
|
96
|
+
scroll.y,
|
|
97
|
+
Math.floor(captureLimit / devicePixelRatio),
|
|
98
|
+
page.nodes.filter(node => node.layer === 0).map(node => node.frame),
|
|
99
|
+
);
|
|
100
|
+
const scene = cropped(page, top, height);
|
|
101
|
+
const capture: Capture = {
|
|
102
|
+
date,
|
|
103
|
+
size: scene.size,
|
|
104
|
+
visible: { x: scroll.x, y: scroll.y - top, width: innerWidth, height: innerHeight },
|
|
105
|
+
nodes: buildTree(scene),
|
|
106
|
+
environment: environment(options, date),
|
|
107
|
+
context,
|
|
108
|
+
screenName: document.title || undefined,
|
|
77
109
|
};
|
|
110
|
+
return { capture, scene, top };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Reads the page without drawing it, for automation that needs only the tree. */
|
|
114
|
+
export const captureTree = (options: CaptureOptions) => readPage(options).capture;
|
|
115
|
+
|
|
116
|
+
/** Reads the page and copies it. */
|
|
117
|
+
export async function captureScreen(options: CaptureOptions): Promise<Screen> {
|
|
118
|
+
const { capture, scene, top } = readPage(options);
|
|
119
|
+
const picture = await takePicture(scene.size, top, capture.visible, scene.fixed);
|
|
120
|
+
const pixelRatio = devicePixelRatio;
|
|
121
|
+
return { capture, picture, image: picture.canvas(pixelRatio), pixelRatio };
|
|
78
122
|
}
|
package/src/dom/image.ts
CHANGED
|
@@ -204,7 +204,7 @@ function watermark(context: CanvasRenderingContext2D, { isLeft, origin }: Card)
|
|
|
204
204
|
* The image export: the screenshot with numbered boxes, each item's text and code location in a card beside it, a
|
|
205
205
|
* tagged box for each referenced node, and the capture's environment, so the one file is enough on its own.
|
|
206
206
|
*/
|
|
207
|
-
export function annotatedImage({ capture,
|
|
207
|
+
export function annotatedImage({ capture, picture, pixelRatio }: Screen, annotations: Annotations): HTMLCanvasElement {
|
|
208
208
|
const { column, padding, badge: badgeSize } = metrics;
|
|
209
209
|
const textWidth = column - padding * 3 - badgeSize;
|
|
210
210
|
const canvas = document.createElement('canvas');
|
|
@@ -307,7 +307,7 @@ export function annotatedImage({ capture, image, scale }: Screen, annotations: A
|
|
|
307
307
|
annotations.used.map(reference => capture.nodes[reference.target]!.frame),
|
|
308
308
|
);
|
|
309
309
|
const { shot, size } = placed;
|
|
310
|
-
const exportScale = Math.min(
|
|
310
|
+
const exportScale = Math.min(pixelRatio, Math.sqrt(pixelBudget / (size.width * size.height)));
|
|
311
311
|
canvas.width = Math.round(size.width * exportScale);
|
|
312
312
|
canvas.height = Math.round(size.height * exportScale);
|
|
313
313
|
context.scale(exportScale, exportScale);
|
|
@@ -317,7 +317,7 @@ export function annotatedImage({ capture, image, scale }: Screen, annotations: A
|
|
|
317
317
|
context.save();
|
|
318
318
|
roundedRect(context, shot, 12);
|
|
319
319
|
context.clip();
|
|
320
|
-
|
|
320
|
+
picture.draw(context, { x: 0, y: 0, width: shot.width, height: shot.height }, shot, 1);
|
|
321
321
|
context.restore();
|
|
322
322
|
roundedRect(context, shot, 12);
|
|
323
323
|
context.lineWidth = 1;
|
package/src/dom/screenshot.ts
CHANGED
|
@@ -1,33 +1,101 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { Frame, Size } from '../core/index.ts';
|
|
1
|
+
import { createContext, destroyContext, domToForeignObjectSvg, loadMedia, type Options } from 'modern-screenshot';
|
|
2
|
+
import type { Frame, Point, Size } from '../core/index.ts';
|
|
3
3
|
import type { FixedRoot } from './scene.ts';
|
|
4
4
|
import { hostAttribute } from './tags.ts';
|
|
5
5
|
|
|
6
|
-
/** iOS Safari refuses a larger canvas
|
|
6
|
+
/** iOS Safari refuses a larger canvas. */
|
|
7
7
|
const pixelBudget = 16_000_000;
|
|
8
8
|
const maxSide = 16_384;
|
|
9
9
|
|
|
10
|
-
/** The
|
|
11
|
-
export function
|
|
10
|
+
/** The largest scale up to `wanted` at which `size` fits one canvas. */
|
|
11
|
+
export function canvasScale(size: Size, wanted: number) {
|
|
12
12
|
return Math.min(
|
|
13
|
-
|
|
13
|
+
wanted,
|
|
14
14
|
Math.sqrt(pixelBudget / (size.width * size.height)),
|
|
15
15
|
maxSide / size.width,
|
|
16
16
|
maxSide / size.height,
|
|
17
17
|
);
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
/** One copy of the DOM as an SVG image, at its place in the capture, after `backdrop` covers the part that was on screen. */
|
|
21
|
+
type Part = { image?: HTMLImageElement; frame: Frame; backdrop?: { color: string; frame: Frame } };
|
|
22
|
+
|
|
23
|
+
const intersect = (a: Frame, b: Frame): Frame | undefined => {
|
|
24
|
+
const x = Math.max(a.x, b.x);
|
|
25
|
+
const y = Math.max(a.y, b.y);
|
|
26
|
+
const width = Math.min(a.x + a.width, b.x + b.width) - x;
|
|
27
|
+
const height = Math.min(a.y + a.height, b.y + b.height) - y;
|
|
28
|
+
return width > 0 && height > 0 ? { x, y, width, height } : undefined;
|
|
29
|
+
};
|
|
30
|
+
|
|
20
31
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* is then drawn where it was on screen, over a modal's backdrop, which a re-draw of the DOM leaves out.
|
|
32
|
+
* The frozen page, kept as vector copies of the DOM, so any part of it can be drawn sharp at any scale long after the
|
|
33
|
+
* page moved on: the editor draws what is in view at the screen's resolution, and an export draws at its own.
|
|
24
34
|
*/
|
|
25
|
-
export
|
|
26
|
-
|
|
35
|
+
export class Picture {
|
|
36
|
+
constructor(
|
|
37
|
+
readonly size: Size,
|
|
38
|
+
private readonly parts: Part[],
|
|
39
|
+
) {}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Draws `region` of the capture into `context` with its corner at `at` and `scale` units per point. Each copy is
|
|
43
|
+
* drawn only where it meets the region, so the browser rasterizes no more of it than shows.
|
|
44
|
+
*/
|
|
45
|
+
draw(context: CanvasRenderingContext2D, region: Frame, at: Point, scale: number) {
|
|
46
|
+
const place = (frame: Frame) => ({
|
|
47
|
+
x: at.x + (frame.x - region.x) * scale,
|
|
48
|
+
y: at.y + (frame.y - region.y) * scale,
|
|
49
|
+
width: frame.width * scale,
|
|
50
|
+
height: frame.height * scale,
|
|
51
|
+
});
|
|
52
|
+
for (const { image, frame, backdrop } of this.parts) {
|
|
53
|
+
const tinted = backdrop && intersect(backdrop.frame, region);
|
|
54
|
+
if (tinted) {
|
|
55
|
+
const target = place(tinted);
|
|
56
|
+
context.fillStyle = backdrop.color;
|
|
57
|
+
context.fillRect(target.x, target.y, target.width, target.height);
|
|
58
|
+
}
|
|
59
|
+
const shown = image && intersect(frame, region);
|
|
60
|
+
if (!shown) continue;
|
|
61
|
+
const target = place(shown);
|
|
62
|
+
context.drawImage(
|
|
63
|
+
image,
|
|
64
|
+
shown.x - frame.x,
|
|
65
|
+
shown.y - frame.y,
|
|
66
|
+
shown.width,
|
|
67
|
+
shown.height,
|
|
68
|
+
target.x,
|
|
69
|
+
target.y,
|
|
70
|
+
target.width,
|
|
71
|
+
target.height,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The whole capture on a canvas, at `scale` or as close to it as one canvas allows. */
|
|
77
|
+
canvas(scale: number) {
|
|
78
|
+
const fitted = canvasScale(this.size, scale);
|
|
79
|
+
const canvas = document.createElement('canvas');
|
|
80
|
+
canvas.width = Math.round(this.size.width * fitted);
|
|
81
|
+
canvas.height = Math.round(this.size.height * fitted);
|
|
82
|
+
this.draw(canvas.getContext('2d')!, { x: 0, y: 0, ...this.size }, { x: 0, y: 0 }, fitted);
|
|
83
|
+
return canvas;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Copies the page, from `top` down `size.height` points. The browser gives a page no way to read its own pixels, so the
|
|
89
|
+
* DOM is copied into an SVG image. The document goes first, without the content that stays put while the page
|
|
90
|
+
* scrolls. Each such root is then copied on its own and drawn where it was on screen, over a modal's backdrop, which a
|
|
91
|
+
* copy of the DOM leaves out. `visible` and the roots' frames are in capture coordinates.
|
|
92
|
+
*/
|
|
93
|
+
export function takePicture(size: Size, top: number, visible: Frame, fixed: FixedRoot[]) {
|
|
94
|
+
return withFieldState(() => copy(size, top, visible, fixed));
|
|
27
95
|
}
|
|
28
96
|
|
|
29
97
|
/**
|
|
30
|
-
* The
|
|
98
|
+
* The copy carries attributes, and what a field holds is a property. This writes the text of each text area and the
|
|
31
99
|
* state of each checkbox and radio button into their attributes while `work` runs, then puts the attributes back.
|
|
32
100
|
*/
|
|
33
101
|
async function withFieldState<T>(work: () => Promise<T>) {
|
|
@@ -52,7 +120,7 @@ async function withFieldState<T>(work: () => Promise<T>) {
|
|
|
52
120
|
|
|
53
121
|
/**
|
|
54
122
|
* What the browser paints behind the page: the root's background, else the body's, which the root takes over, else the
|
|
55
|
-
* canvas color of the page's color scheme. The
|
|
123
|
+
* canvas color of the page's color scheme. The copy is transparent where the page sets no background.
|
|
56
124
|
*/
|
|
57
125
|
function pageBackground() {
|
|
58
126
|
for (const element of [document.documentElement, document.body]) {
|
|
@@ -67,52 +135,79 @@ function pageBackground() {
|
|
|
67
135
|
return color;
|
|
68
136
|
}
|
|
69
137
|
|
|
70
|
-
|
|
138
|
+
/** What modern-screenshot's `svgToDataUrl` does, which it does not export. */
|
|
139
|
+
function svgImageURL(svg: SVGElement) {
|
|
140
|
+
// XML 1.0 has no place for control characters or lone surrogates, and a page's text can hold them.
|
|
141
|
+
// oxlint-disable-next-line no-control-regex
|
|
142
|
+
const invalid = /[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu;
|
|
143
|
+
const markup = new XMLSerializer().serializeToString(svg).replace(invalid, '');
|
|
144
|
+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Copies `node` into a decoded SVG image. modern-screenshot draws a copy with images again after an interval, for
|
|
149
|
+
* browsers that decode the images inside an SVG image only once it is first drawn. It waits once per image, which held
|
|
150
|
+
* Safari 2.4 s on a page with 20 icons, so the copy is drawn once and waits one interval in all.
|
|
151
|
+
*/
|
|
152
|
+
async function svgImage(node: Element, options: Options) {
|
|
153
|
+
const context = await createContext(node, options);
|
|
154
|
+
try {
|
|
155
|
+
const svg = await domToForeignObjectSvg(context);
|
|
156
|
+
const image = await loadMedia(svgImageURL(svg), { timeout: context.timeout });
|
|
157
|
+
if (context.drawImageCount > 0) {
|
|
158
|
+
document.createElement('canvas').getContext('2d')!.drawImage(image, 0, 0, 1, 1);
|
|
159
|
+
await new Promise(resolve => setTimeout(resolve, context.drawImageInterval));
|
|
160
|
+
}
|
|
161
|
+
return image;
|
|
162
|
+
} finally {
|
|
163
|
+
destroyContext(context);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function copy(size: Size, top: number, visible: Frame, fixed: FixedRoot[]) {
|
|
71
168
|
const roots = new Set<Node>(fixed.map(root => root.element));
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
169
|
+
const parts: Part[] = [
|
|
170
|
+
{
|
|
171
|
+
image: await svgImage(document.documentElement, {
|
|
172
|
+
width: size.width,
|
|
173
|
+
height: top + size.height,
|
|
174
|
+
backgroundColor: pageBackground(),
|
|
175
|
+
filter: node => !(roots.has(node) || (node instanceof Element && node.hasAttribute(hostAttribute))),
|
|
176
|
+
}),
|
|
177
|
+
frame: { x: 0, y: -top, width: size.width, height: top + size.height },
|
|
178
|
+
},
|
|
179
|
+
];
|
|
83
180
|
// A modal dialog or popover sits in the browser's top layer, above every other fixed root, whatever the DOM order.
|
|
84
181
|
const layered = [
|
|
85
182
|
...fixed.filter(root => root.backdrop === undefined),
|
|
86
183
|
...fixed.filter(root => root.backdrop !== undefined),
|
|
87
184
|
];
|
|
88
185
|
for (const root of layered) {
|
|
89
|
-
if (root.backdrop) {
|
|
90
|
-
context.fillStyle = root.backdrop;
|
|
91
|
-
context.fillRect(visible.x, visible.y, visible.width, visible.height);
|
|
92
|
-
}
|
|
93
186
|
const { frame } = root;
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
width
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
187
|
+
const backdrop = root.backdrop ? { color: root.backdrop, frame: visible } : undefined;
|
|
188
|
+
const image =
|
|
189
|
+
frame.width && frame.height
|
|
190
|
+
? await svgImage(root.element, {
|
|
191
|
+
width: frame.width,
|
|
192
|
+
height: frame.height,
|
|
193
|
+
// A layer inside this root is drawn by its own turn.
|
|
194
|
+
filter: node => node === root.element || !roots.has(node),
|
|
195
|
+
style: {
|
|
196
|
+
// A copy of a popover is not open, and a closed popover is `display: none`.
|
|
197
|
+
display: getComputedStyle(root.element).display,
|
|
198
|
+
position: 'static',
|
|
199
|
+
inset: 'auto',
|
|
200
|
+
margin: '0',
|
|
201
|
+
transform: 'none',
|
|
202
|
+
translate: 'none',
|
|
203
|
+
width: `${frame.width}px`,
|
|
204
|
+
height: `${frame.height}px`,
|
|
205
|
+
maxWidth: 'none',
|
|
206
|
+
maxHeight: 'none',
|
|
207
|
+
},
|
|
208
|
+
})
|
|
209
|
+
: undefined;
|
|
210
|
+
parts.push({ image, frame, backdrop });
|
|
116
211
|
}
|
|
117
|
-
return
|
|
212
|
+
return new Picture(size, parts);
|
|
118
213
|
}
|
package/src/editor/Editor.svelte
CHANGED
|
@@ -88,6 +88,7 @@
|
|
|
88
88
|
|
|
89
89
|
let dialog = $state<HTMLDialogElement>();
|
|
90
90
|
let pane = $state<HTMLElement>();
|
|
91
|
+
let sharp = $state<HTMLCanvasElement>();
|
|
91
92
|
let field = $state<HTMLTextAreaElement>();
|
|
92
93
|
let paneSize = $state({ width: 0, height: 0 });
|
|
93
94
|
let zoom = $state(1);
|
|
@@ -149,6 +150,53 @@
|
|
|
149
150
|
return () => removeEventListener('resize', measure);
|
|
150
151
|
});
|
|
151
152
|
|
|
153
|
+
/**
|
|
154
|
+
* The base image has as many pixels as one canvas can hold, which a zoom or a tall capture can outgrow. Then the part
|
|
155
|
+
* in view is drawn again from the picture at the screen's resolution, over the base image, once scrolling settles
|
|
156
|
+
* into a frame. A zoom hides it at once, since its place and scale no longer match.
|
|
157
|
+
*/
|
|
158
|
+
let sharpening = 0;
|
|
159
|
+
function sharpen() {
|
|
160
|
+
cancelAnimationFrame(sharpening);
|
|
161
|
+
sharpening = requestAnimationFrame(() => {
|
|
162
|
+
const canvas = sharp;
|
|
163
|
+
if (!pane || !canvas) return;
|
|
164
|
+
const ratio = devicePixelRatio;
|
|
165
|
+
if (scale * ratio <= screen.image.width / capture.size.width + 0.01) {
|
|
166
|
+
canvas.hidden = true;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const shown = pane.getBoundingClientRect();
|
|
170
|
+
const whole = canvas.parentElement!.getBoundingClientRect();
|
|
171
|
+
const left = Math.floor(Math.max(0, shown.left - whole.left));
|
|
172
|
+
const top = Math.floor(Math.max(0, shown.top - whole.top));
|
|
173
|
+
const width = Math.ceil(Math.min(whole.width, shown.right - whole.left)) - left;
|
|
174
|
+
const height = Math.ceil(Math.min(whole.height, shown.bottom - whole.top)) - top;
|
|
175
|
+
if (width <= 0 || height <= 0) {
|
|
176
|
+
canvas.hidden = true;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
canvas.width = Math.round(width * ratio);
|
|
180
|
+
canvas.height = Math.round(height * ratio);
|
|
181
|
+
canvas.style.cssText = `left:${left}px;top:${top}px;width:${width}px;height:${height}px`;
|
|
182
|
+
screen.picture.draw(
|
|
183
|
+
canvas.getContext('2d')!,
|
|
184
|
+
{ x: left / scale, y: top / scale, width: width / scale, height: height / scale },
|
|
185
|
+
{ x: 0, y: 0 },
|
|
186
|
+
scale * ratio,
|
|
187
|
+
);
|
|
188
|
+
canvas.hidden = false;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
$effect(() => {
|
|
193
|
+
void scale;
|
|
194
|
+
void paneSize;
|
|
195
|
+
if (sharp) sharp.hidden = true;
|
|
196
|
+
sharpen();
|
|
197
|
+
return () => cancelAnimationFrame(sharpening);
|
|
198
|
+
});
|
|
199
|
+
|
|
152
200
|
$effect(() => {
|
|
153
201
|
const toast = view.toast;
|
|
154
202
|
if (!toast || toast.problem) return;
|
|
@@ -364,6 +412,7 @@
|
|
|
364
412
|
aria-label="Screenshot"
|
|
365
413
|
bind:this={pane}
|
|
366
414
|
onwheel={wheel}
|
|
415
|
+
onscroll={sharpen}
|
|
367
416
|
onpointerdown={pointer}
|
|
368
417
|
onpointermove={pointer}
|
|
369
418
|
onpointerup={pointer}
|
|
@@ -379,10 +428,15 @@
|
|
|
379
428
|
onclick={event => act(() => session.pick(pointAt(event)))}
|
|
380
429
|
onmousemove={event => (hover = hitTest(capture, pointAt(event)))}
|
|
381
430
|
onmouseleave={() => (hover = undefined)}
|
|
382
|
-
{@attach node => {
|
|
383
|
-
node.prepend(screen.image);
|
|
384
|
-
}}
|
|
385
431
|
>
|
|
432
|
+
<div
|
|
433
|
+
class="picture"
|
|
434
|
+
{@attach node => {
|
|
435
|
+
node.prepend(screen.image);
|
|
436
|
+
}}
|
|
437
|
+
>
|
|
438
|
+
<canvas class="sharp" hidden bind:this={sharp}></canvas>
|
|
439
|
+
</div>
|
|
386
440
|
{#each view.similar as id (id)}
|
|
387
441
|
<span class="box similar" style={box(capture.nodes[id]!.frame)}></span>
|
|
388
442
|
{/each}
|
|
@@ -861,11 +915,25 @@
|
|
|
861
915
|
}
|
|
862
916
|
|
|
863
917
|
/* The picture is clipped, not the boxes over it, so a number badge on a box at the edge stays whole. */
|
|
864
|
-
.
|
|
918
|
+
.picture {
|
|
919
|
+
position: absolute;
|
|
920
|
+
inset: 0;
|
|
921
|
+
overflow: hidden;
|
|
922
|
+
border-radius: 10px;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
.picture :global(canvas) {
|
|
865
926
|
display: block;
|
|
866
927
|
width: 100%;
|
|
867
928
|
height: 100%;
|
|
868
|
-
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
.picture .sharp {
|
|
932
|
+
position: absolute;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
.sharp[hidden] {
|
|
936
|
+
display: none;
|
|
869
937
|
}
|
|
870
938
|
|
|
871
939
|
.box {
|
package/src/editor/engine.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { tick } from 'svelte';
|
|
2
|
-
import type
|
|
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';
|
|
@@ -125,13 +125,15 @@ export class Engine {
|
|
|
125
125
|
this.remember();
|
|
126
126
|
this.hidePill();
|
|
127
127
|
this.capturing = true;
|
|
128
|
-
this.pointed = at && { x: at.x + scrollX, y: at.y + scrollY };
|
|
129
128
|
try {
|
|
130
|
-
|
|
129
|
+
const screen = await captureScreen({
|
|
131
130
|
app: this.options.app,
|
|
132
131
|
version: this.options.version,
|
|
133
132
|
context: this.providers,
|
|
134
133
|
});
|
|
134
|
+
const { visible } = screen.capture;
|
|
135
|
+
this.pointed = at && { x: at.x + visible.x, y: at.y + visible.y };
|
|
136
|
+
this.screen = screen;
|
|
135
137
|
} finally {
|
|
136
138
|
this.capturing = false;
|
|
137
139
|
this.holding = false;
|
|
@@ -139,6 +141,13 @@ export class Engine {
|
|
|
139
141
|
}
|
|
140
142
|
}
|
|
141
143
|
|
|
144
|
+
/** The JSON export of the page as it is now, with no items, without drawing it or opening the editor. */
|
|
145
|
+
report(): FeedbackReport {
|
|
146
|
+
const capture = captureTree({ app: this.options.app, version: this.options.version, context: this.providers });
|
|
147
|
+
// Through the export's own serializer, so the object has the file's keys, without the ones that have no value.
|
|
148
|
+
return JSON.parse(reportJSON(capture, new Annotations(), false));
|
|
149
|
+
}
|
|
150
|
+
|
|
142
151
|
close() {
|
|
143
152
|
const { focused } = this;
|
|
144
153
|
this.screen = undefined;
|
package/src/editor/setup.ts
CHANGED
|
@@ -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 {
|
|
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
|
},
|
package/src/react/index.ts
CHANGED
|
@@ -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';
|
package/src/react/public.d.ts
CHANGED
|
@@ -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
|
}
|
package/src/svelte/index.ts
CHANGED
|
@@ -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';
|