deictic 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/API.md +71 -17
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/cli.js +1 -1
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client/index.d.ts +13 -13
  7. package/dist/client/index.d.ts.map +1 -1
  8. package/dist/client/index.js +11 -7
  9. package/dist/client/index.js.map +1 -1
  10. package/dist/react/client.d.ts +19 -0
  11. package/dist/react/client.d.ts.map +1 -0
  12. package/dist/react/client.js +504 -0
  13. package/dist/react/client.js.map +1 -0
  14. package/dist/react/index.d.ts +2 -0
  15. package/dist/react/index.js +1 -0
  16. package/dist/recommended/index.d.ts +15 -7
  17. package/dist/recommended/index.d.ts.map +1 -1
  18. package/dist/recommended/index.js +1 -1
  19. package/dist/recordings/client.d.ts.map +1 -1
  20. package/dist/recordings/client.js +48 -5
  21. package/dist/recordings/client.js.map +1 -1
  22. package/dist/screenshots/client.d.ts +9 -1
  23. package/dist/screenshots/client.d.ts.map +1 -1
  24. package/dist/screenshots/rrweb.d.ts +0 -6
  25. package/dist/screenshots/rrweb.d.ts.map +1 -1
  26. package/dist/screenshots/rrweb.js +46 -12
  27. package/dist/screenshots/rrweb.js.map +1 -1
  28. package/dist/shared/board.js +1 -1
  29. package/dist/shared/client.js +44 -2
  30. package/dist/shared/client.js.map +1 -1
  31. package/dist/shared/dom.js +7 -1
  32. package/dist/shared/dom.js.map +1 -1
  33. package/dist/shared/drawer.js +1 -1
  34. package/dist/shared/endpoints.js +1 -1
  35. package/dist/shared/index.d.ts +6 -0
  36. package/dist/shared/index.d.ts.map +1 -1
  37. package/dist/shared/index10.d.ts +70 -0
  38. package/dist/shared/index10.d.ts.map +1 -0
  39. package/dist/shared/index3.d.ts +11 -0
  40. package/dist/shared/index3.d.ts.map +1 -1
  41. package/dist/shared/index7.d.ts +92 -312
  42. package/dist/shared/index7.d.ts.map +1 -1
  43. package/dist/shared/index8.d.ts +324 -47
  44. package/dist/shared/index8.d.ts.map +1 -1
  45. package/dist/shared/index9.d.ts +45 -63
  46. package/dist/shared/index9.d.ts.map +1 -1
  47. package/dist/shared/init.js +15 -11
  48. package/dist/shared/init.js.map +1 -1
  49. package/dist/shared/marks.js +7 -1
  50. package/dist/shared/marks.js.map +1 -1
  51. package/dist/shared/package.js +3 -1
  52. package/dist/shared/packages.js +1 -1
  53. package/dist/shared/playwright.js +39 -1
  54. package/dist/shared/playwright.js.map +1 -1
  55. package/dist/shared/react.js +25 -0
  56. package/dist/shared/react.js.map +1 -0
  57. package/dist/shared/recommended.js +6 -3
  58. package/dist/shared/recommended.js.map +1 -1
  59. package/dist/shared/recording.js +80 -3
  60. package/dist/shared/recording.js.map +1 -1
  61. package/dist/shared/recordings.js +30 -2
  62. package/dist/shared/recordings.js.map +1 -1
  63. package/dist/shared/screenshots.js.map +1 -1
  64. package/dist/shared/src.js.map +1 -1
  65. package/dist/shared/task.js +1 -0
  66. package/dist/shared/task.js.map +1 -1
  67. package/dist/shared/tasks.js +11 -0
  68. package/dist/shared/tasks.js.map +1 -1
  69. package/dist/tailwind/client.d.ts +1 -1
  70. package/dist/tailwind/index.d.ts +1 -1
  71. package/dist/tasks/client.d.ts +1 -1
  72. package/dist/tasks/client.js +45 -19
  73. package/dist/tasks/client.js.map +1 -1
  74. package/dist/tasks/index.d.ts +1 -1
  75. package/dist/voice/client.d.ts +1 -1
  76. package/dist/voice/client.js +1 -1
  77. package/dist/voice/index.d.ts +1 -1
  78. package/package.json +25 -1
  79. package/src/cli/bun.ts +2 -2
  80. package/src/cli/init.ts +14 -9
  81. package/src/cli/recording.ts +90 -4
  82. package/src/cli/task.ts +4 -0
  83. package/src/cli.ts +13 -6
  84. package/src/client/dom.ts +14 -0
  85. package/src/client/index.ts +21 -14
  86. package/src/index.ts +6 -0
  87. package/src/plugins/react/client.ts +162 -0
  88. package/src/plugins/react/index.ts +130 -0
  89. package/src/plugins/react/renders.ts +219 -0
  90. package/src/plugins/react/serialize.ts +139 -0
  91. package/src/plugins/react/timeline.ts +143 -0
  92. package/src/plugins/recommended/index.ts +17 -5
  93. package/src/plugins/recordings/client.ts +64 -4
  94. package/src/plugins/recordings/marks.ts +7 -0
  95. package/src/plugins/recordings/replay.ts +30 -2
  96. package/src/plugins/screenshots/client.ts +42 -2
  97. package/src/plugins/screenshots/index.ts +11 -0
  98. package/src/plugins/screenshots/playwright.ts +65 -1
  99. package/src/plugins/screenshots/rrweb.ts +55 -28
  100. package/src/plugins/screenshots/states.ts +26 -0
  101. package/src/plugins/tasks/client.ts +41 -6
  102. package/src/plugins/tasks/composer.ts +24 -7
  103. package/src/plugins/tasks/index.ts +16 -2
@@ -1,19 +1,23 @@
1
1
  /**
2
2
  * `deictic/recommended`: the plugins for describing a change rather than making it. Alt-click an element, say what
3
3
  * should change, attach a screenshot to draw on, a screen recording or your voice, and it goes to a Vercel Board.
4
- * A recording has the page's console and its requests in it too.
4
+ * A recording has the page's console and its requests in it too, and in a React project a task has the props and
5
+ * state of the components that wrote its element.
5
6
  *
6
7
  * Only the server halves, as every factory is: each names its page half, which the integration imports. A plugin
7
- * outside the preset (Tailwind, your own) goes beside it: `plugins: [...recommended(), tailwind()]`.
8
+ * outside the preset (Tailwind, your own) goes beside it: `plugins: [...deicticRecommended(), tailwind()]`. Named for
9
+ * deictic, as a config imports other presets called `recommended`.
8
10
  */
9
11
  import type { ServerPlugin } from '#src/index.ts';
10
12
  import { annotations, type AnnotationsOptions } from '#src/plugins/annotations/index.ts';
11
13
  import { logs, type LogsOptions } from '#src/plugins/logs/index.ts';
12
14
  import { network, type NetworkOptions } from '#src/plugins/network/index.ts';
15
+ import { type ReactOptions, reactState } from '#src/plugins/react/index.ts';
13
16
  import { recordings, type RecordingsOptions } from '#src/plugins/recordings/index.ts';
14
17
  import { screenshots, type ScreenshotsOptions } from '#src/plugins/screenshots/index.ts';
15
18
  import { tasks, type TasksOptions } from '#src/plugins/tasks/index.ts';
16
19
  import { voice, type VoiceOptions } from '#src/plugins/voice/index.ts';
20
+ import { installed } from '#src/tools/packages.ts';
17
21
 
18
22
  /** Each plugin's options, by its name, or `false` to leave it out. */
19
23
  export interface RecommendedOptions {
@@ -26,13 +30,18 @@ export interface RecommendedOptions {
26
30
  logs?: LogsOptions | false;
27
31
  /** The page's requests in a recording, masked. */
28
32
  network?: NetworkOptions | false;
33
+ /**
34
+ * The props, state and hooks of the components that wrote a task's element: where the project has React (found from
35
+ * the working directory, where the dev server starts), unless it's `false`.
36
+ */
37
+ react?: ReactOptions | false;
29
38
  }
30
39
 
31
40
  /**
32
41
  * Tasks, screenshots, annotations, recordings and voice, in that order, the order of their tabs, then what a
33
- * recording has besides the page: logs and network.
42
+ * recording has besides the page: logs and network, and React's state where the project has React.
34
43
  */
35
- export function recommended(options: RecommendedOptions = {}): ServerPlugin[] {
44
+ export function deicticRecommended(options: RecommendedOptions = {}): ServerPlugin[] {
36
45
  const plugins: ServerPlugin[] = [];
37
46
  if (options.tasks !== false) plugins.push(tasks(options.tasks));
38
47
  if (options.screenshots !== false) plugins.push(screenshots(options.screenshots));
@@ -42,7 +51,10 @@ export function recommended(options: RecommendedOptions = {}): ServerPlugin[] {
42
51
  // Nothing without recordings to be in.
43
52
  if (options.recordings !== false && options.logs !== false) plugins.push(logs(options.logs));
44
53
  if (options.recordings !== false && options.network !== false) plugins.push(network(options.network));
54
+ // Its page half reads React's fibers: nothing to read without React, and bippy to install for nothing.
55
+ if (options.react !== false && (options.react !== undefined || installed(process.cwd(), 'react')))
56
+ plugins.push(reactState(options.react));
45
57
  return plugins;
46
58
  }
47
59
 
48
- export default recommended;
60
+ export default deicticRecommended;
@@ -10,7 +10,8 @@
10
10
  * the time running, and turns the mic back on where it was.
11
11
  *
12
12
  * Nothing of deictic's is recorded: the overlay is blocked, as rrweb blocks. The marks are, as custom
13
- * events: the page's annotations, as SVGs in page coordinates, at the start and at each change.
13
+ * events: the page's annotations, as SVGs in page coordinates, at the start and at each change. So are React's
14
+ * commits, where the react plugin is loaded, while its button is on (P): off by default, and as it was last left.
14
15
  */
15
16
  import { toolButton } from '#src/client/dom.ts';
16
17
  import { playMark, trayed } from '#src/client/drawer.ts';
@@ -21,7 +22,7 @@ import type { ResolvedMasking } from '#src/plugins/screenshots/index.ts';
21
22
  import type { Take } from '#src/plugins/voice/index.ts';
22
23
 
23
24
  import type { Kept, Meta, Recorder, Recording, RecordPlugin, VoiceClip } from './index.ts';
24
- import { END, MARKS, PAGE } from './marks.ts';
25
+ import { END, MARKS, PAGE, REACT } from './marks.ts';
25
26
  import { dropOurs } from './ours.ts';
26
27
 
27
28
  /** Where the recording going on is kept, for the tab's next page to carry on with. */
@@ -38,8 +39,29 @@ interface Carried {
38
39
  /** The mic's clips so far, and whether it was on. */
39
40
  clips: VoiceClip[];
40
41
  mic: boolean;
42
+ /** Whether React's commits were going in. */
43
+ react?: boolean;
41
44
  }
42
45
 
46
+ /** Whether the last recording had React's commits going in when it ended, for the next to start as it was left. */
47
+ const REACT_ON = 'deictic:recording:react';
48
+
49
+ const reactWanted = () => {
50
+ try {
51
+ return localStorage.getItem(REACT_ON) === 'true';
52
+ } catch {
53
+ return false;
54
+ }
55
+ };
56
+
57
+ const wantReact = (on: boolean) => {
58
+ try {
59
+ localStorage.setItem(REACT_ON, String(on));
60
+ } catch {
61
+ // Not remembered, then: the next recording starts without.
62
+ }
63
+ };
64
+
43
65
  function carried(): Carried | undefined {
44
66
  try {
45
67
  return (JSON.parse(sessionStorage.getItem(GOING) ?? 'null') as Carried | null) ?? undefined;
@@ -69,6 +91,7 @@ const STYLE = `
69
91
  .tool-panel.vertical .recorder .live { flex-direction: column; gap: 2px; padding: 4px 0; }
70
92
  .recorder .dot { width: 8px; height: 8px; border-radius: 50%; background: #ef4444; animation: deictic-blink 1.2s infinite; }
71
93
  .recorder .mic[aria-pressed='true'], .recorder .mic[aria-pressed='true']:hover { background: #ef4444; color: #fff; }
94
+ .recorder .react[aria-pressed='true'], .recorder .react[aria-pressed='true']:hover { background: #087ea4; color: #fff; }
72
95
  .recorder .wave { width: 44px; height: 18px; }
73
96
  .tool-panel.vertical .recorder .wave { width: 28px; }
74
97
  @keyframes deictic-blink { 50% { opacity: 0.3; } }
@@ -79,6 +102,9 @@ const RECORD = '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3" fil
79
102
  const STOP = '<rect x="6" y="6" width="12" height="12" rx="1" fill="currentColor"/>';
80
103
  const DISCARD = '<path d="M6 6l12 12M18 6 6 18"/>';
81
104
  const MIC = '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/>';
105
+ /** An atom, as React's own mark is drawn. */
106
+ const ATOM =
107
+ '<circle cx="12" cy="12" r="1.6" fill="currentColor"/><ellipse cx="12" cy="12" rx="10" ry="4"/><ellipse cx="12" cy="12" rx="10" ry="4" transform="rotate(60 12 12)"/><ellipse cx="12" cy="12" rx="10" ry="4" transform="rotate(120 12 12)"/>';
82
108
 
83
109
  const clock = (ms: number) => {
84
110
  const s = Math.floor(ms / 1000);
@@ -219,11 +245,14 @@ export default defineClientPlugin<never, never, Recorder>({
219
245
  // The mic, where the voice plugin is loaded: each stretch it's on is a clip, at its time in the recording.
220
246
  const voice = use('voice');
221
247
  let take: Take | undefined;
248
+ // React's commits, where the react plugin counts them: what stops them going in while they do.
249
+ const commits = use('react')?.commits;
250
+ let unreact: (() => void) | undefined;
222
251
  /** What the next page carries on from, kept as it changes: a page that's going has no time to say it then. */
223
252
  let over = false;
224
253
  const save = () =>
225
254
  // Not once it's ended, as its last events go: the next page would carry on with one that's over.
226
- over || carry({ id, startedAt, seq, clips, mic: take !== undefined });
255
+ over || carry({ id, startedAt, seq, clips, mic: take !== undefined, react: unreact !== undefined });
227
256
  const unsubscribe = marks?.subscribe(mark);
228
257
 
229
258
  // One part at a time, each with its place. A part that didn't arrive goes again with the next, before it.
@@ -310,6 +339,34 @@ export default defineClientPlugin<never, never, Recorder>({
310
339
  // On, as the page before left it: a browser that was let use the mic gives it again without asking.
311
340
  if (from?.mic === true) toggle();
312
341
 
342
+ const react =
343
+ commits === undefined
344
+ ? undefined
345
+ : toolButton(ATOM, "Record React's commits: what rendered, how long it took, and why", 'P', () =>
346
+ reactOn(unreact === undefined),
347
+ );
348
+ react?.classList.add('react');
349
+ const reactOn = (on: boolean) => {
350
+ if (commits === undefined || react === undefined || on === (unreact !== undefined)) return;
351
+ if (on) {
352
+ rrweb.record.addCustomEvent(REACT, { on: true });
353
+ unreact = commits((commit) => rrweb.record.addCustomEvent(REACT, commit));
354
+ } else {
355
+ // What's waiting goes first, then where it stops.
356
+ unreact?.();
357
+ unreact = undefined;
358
+ rrweb.record.addCustomEvent(REACT, { on: false });
359
+ }
360
+ react.setAttribute('aria-pressed', String(on));
361
+ react.title = on ? "Stop recording React's commits" : "Record React's commits: what rendered, how long it took, and why";
362
+ react.setAttribute('aria-label', react.title);
363
+ wantReact(on);
364
+ save();
365
+ };
366
+ react?.setAttribute('aria-pressed', 'false');
367
+ // As the page before left it, or a new one as the last was left.
368
+ if (from?.react ?? reactWanted()) reactOn(true);
369
+
313
370
  // The page is going, for another or for good, with no time to wait for anything: what's sent of the mic's
314
371
  // take is its clip, the next page is told where things stand, and the last events go as the page does.
315
372
  const leave = () => {
@@ -327,6 +384,9 @@ export default defineClientPlugin<never, never, Recorder>({
327
384
  addEventListener('pagehide', leave);
328
385
 
329
386
  const end = async (kept: boolean) => {
387
+ // What's waiting of React's commits goes in before the end, and the next recording starts as this one ends.
388
+ unreact?.();
389
+ unreact = undefined;
330
390
  rrweb.record.addCustomEvent(END, {});
331
391
  stopRecording?.();
332
392
  unsubscribe?.();
@@ -357,7 +417,7 @@ export default defineClientPlugin<never, never, Recorder>({
357
417
  // Record's key again: it's Stop while one is going.
358
418
  const stop = toolButton(STOP, 'Stop', 'R', () => void end(true));
359
419
  const discard = toolButton(DISCARD, 'Discard', 'Shift+R', () => void end(false));
360
- going.replaceChildren(live, ...(mic ? [mic, wave] : []), stop, discard);
420
+ going.replaceChildren(live, ...(mic ? [mic, wave] : []), ...(react ? [react] : []), stop, discard);
361
421
  // The panel stays while it goes: its controls are what ends it.
362
422
  const unkeep = tools.keep();
363
423
  start.hidden = true;
@@ -15,3 +15,10 @@ export const PAGE = 'deictic.page';
15
15
  * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.
16
16
  */
17
17
  export const END = 'deictic.end';
18
+
19
+ /**
20
+ * The custom event for React's commits, where the react plugin is loaded and they're asked for (the recording's React
21
+ * button): a `Commit` each (`deictic/react`'s), and `{ on }` where the recording starts and stops having them, so a
22
+ * stretch without them isn't read as one where nothing rendered.
23
+ */
24
+ export const REACT = 'deictic.react';
@@ -24,7 +24,7 @@
24
24
  * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says
25
25
  * where one is.
26
26
  */
27
- import { MARKS } from './marks.ts';
27
+ import { MARKS, REACT } from './marks.ts';
28
28
 
29
29
  /** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */
30
30
  export interface ReplaySources {
@@ -76,7 +76,10 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
76
76
  #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
77
77
  #log li.open .text { display: block; white-space: pre-wrap; }
78
78
  #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
79
- #log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }
79
+ #log.no-console li.console, #log.no-network li.network, #log.no-react li.react, #log.only-bad li:not(.bad) { display: none; }
80
+ #log li.react .label { color: #58c4dc; }
81
+ #log li.react.warn .label { color: #fbbf24; }
82
+ #main .rr-player .rr-progress .slow-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #fbbf24; pointer-events: none; }
80
83
  #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }
81
84
  body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
82
85
  #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
@@ -112,6 +115,7 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
112
115
  <div class="filters">
113
116
  <button type="button" data-hides="no-console" aria-pressed="true">Console</button>
114
117
  <button type="button" data-hides="no-network" aria-pressed="true">Network</button>
118
+ <button type="button" data-hides="no-react" aria-pressed="true" hidden title="React's commits: what rendered, how long it took, and why">React</button>
115
119
  <button type="button" data-shows="only-bad" aria-pressed="false" title="Errors, and requests that failed">Problems</button>
116
120
  </div>
117
121
  <ol></ol>
@@ -154,6 +158,27 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
154
158
  const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();
155
159
  const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);
156
160
  const rows = [];
161
+ // React's commits, where the recording had them on: a row an entry, slow ones (past a frame) marked.
162
+ const ms = (n) => (n === undefined ? '' : (n < 10 ? n.toFixed(1) : Math.round(n)) + ' ms');
163
+ for (const e of events) {
164
+ if (e.type !== 5 || bare || e.data.tag !== ${JSON.stringify(REACT)}) continue;
165
+ const at = e.timestamp - t0;
166
+ const c = e.data.payload;
167
+ if (c.on !== undefined) {
168
+ rows.push({ at, kind: 'react', label: 'React', text: c.on ? 'commits recorded from here' : 'commits no longer recorded', more: [] });
169
+ continue;
170
+ }
171
+ const named = (c.components ?? []).map((r) => r.name + (r.count > 1 ? ' ×' + r.count : '') + ' (' + r.why + ')');
172
+ const text = (named.length > 0 ? named.slice(0, 3).join(', ') : (c.more ?? 0) + ' components') + (named.length > 3 || (c.more && named.length > 0) ? ', …' : '');
173
+ const more = [
174
+ [c.commits > 1 ? c.commits + ' commits' + (c.over === undefined ? '' : ' over ' + (c.over / 1000).toFixed(1) + ' s') : '1 commit', c.priority, ms(c.ms), c.slowest === undefined ? '' : 'slowest ' + ms(c.slowest)].filter(Boolean).join(' · '),
175
+ ...(c.components ?? []).map((r) => [r.name + (r.count > 1 ? ' ×' + r.count : ''), r.at, ms(r.ms), r.selfMs === undefined ? '' : ms(r.selfMs) + ' own', r.why].filter(Boolean).join(' · ')),
176
+ ...(c.more ? ['and ' + c.more + ' more'] : []),
177
+ ];
178
+ // One slow commit is what makes a page stutter, not many quick ones.
179
+ const slow = (c.slowest ?? c.ms) > 16;
180
+ rows.push({ at, kind: 'react', label: c.ms === undefined ? 'React' : ms(c.ms), warn: slow, slow, text: (c.over === undefined ? '' : c.commits + ' commits: ') + text, more });
181
+ }
157
182
  for (const e of events) {
158
183
  if (e.type !== 6 || bare) continue;
159
184
  const at = e.timestamp - t0;
@@ -179,8 +204,10 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
179
204
  }
180
205
  }
181
206
  }
207
+ rows.sort((a, b) => a.at - b.at);
182
208
  const logged = rows.length > 0;
183
209
  const log = document.getElementById('log');
210
+ if (rows.some((r) => r.kind === 'react')) log.querySelector('[data-hides="no-react"]').hidden = false;
184
211
  if (logged) document.body.classList.add('logged');
185
212
  // The panel's room, where the window is wide enough to show it (as the stylesheet has it).
186
213
  const side = () => (logged && innerWidth >= 900 ? 340 : 0);
@@ -241,6 +268,7 @@ export const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!
241
268
  row.el.append(go, more);
242
269
  list.append(row.el);
243
270
  // An error, or a request that failed, is a mark on the timeline too.
271
+ if (row.slow && bar) bar.append(Object.assign(cell('i', 'slow-mark', ''), { title: row.label + ': ' + row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));
244
272
  if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));
245
273
  }
246
274
  for (const button of log.querySelectorAll('.filters button')) {
@@ -6,7 +6,7 @@
6
6
  * Its tool in the tool panel takes the window as it is, with what's drawn on the page, and puts the shot in the
7
7
  * tray, for the next task.
8
8
  */
9
- import { toolButton } from '#src/client/dom.ts';
9
+ import { POPUP_CLOSED, POPUP_OPENED, type PopupOpened, toolButton } from '#src/client/dom.ts';
10
10
  import { trayed } from '#src/client/drawer.ts';
11
11
  import { defineClientPlugin } from '#src/index.ts';
12
12
  import type { Annotations } from '#src/plugins/annotations/index.ts';
@@ -29,6 +29,15 @@ export type PageCapture = (
29
29
  },
30
30
  ) => Promise<{ body: Blob | string; type: string; box: Box }>;
31
31
 
32
+ /**
33
+ * What a renderer that can take the page at once makes of it, synchronously: as `PageCapture` answers, or nothing
34
+ * where it isn't ready (what it imports hasn't loaded). `prepare` loads it, once the page has started.
35
+ */
36
+ export interface PageFreeze {
37
+ freeze: (element: Element, options: Parameters<PageCapture>[1]) => Awaited<ReturnType<PageCapture>> | undefined;
38
+ prepare: () => void;
39
+ }
40
+
32
41
  /** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */
33
42
  export const notOurs = (node: Node) => !(node instanceof Element && node.localName === 'deictic-overlay');
34
43
 
@@ -39,6 +48,8 @@ export function boxOf(element: Element, area: NonNullable<CaptureOptions['area']
39
48
  }
40
49
 
41
50
  const BLANK = '#d4d4d8';
51
+ /** How long after its press a popup may first ask for the shot it froze, in milliseconds: later, it's another's. */
52
+ const ASKED = 60_000;
42
53
  /** A camera, on a 24-pixel grid. */
43
54
  const CAMERA = '<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>';
44
55
 
@@ -70,11 +81,17 @@ export function mask(copy: Node, m: ResolvedMasking): void {
70
81
  }
71
82
  }
72
83
 
73
- export function screenshotsClient(capture: PageCapture) {
84
+ export function screenshotsClient(capture: PageCapture, freezer?: PageFreeze) {
74
85
  return defineClientPlugin<never, never, Capture>({
75
86
  name: 'screenshots',
87
+ ...(freezer === undefined ? {} : { pressed: ({ use }, element) => use('screenshots')?.freeze(element) }),
76
88
  setup: ({ base, request, options, use, tools, tray, drawer, lightbox }) => {
77
89
  const { masking, renderer } = options as { masking: ResolvedMasking; renderer: unknown };
90
+ // Ready for a press, which can't wait for an import: once the page has started, while the browser is idle.
91
+ if (freezer !== undefined) {
92
+ if (typeof requestIdleCallback === 'function') requestIdleCallback(freezer.prepare, { timeout: 5000 });
93
+ else setTimeout(freezer.prepare, 1000);
94
+ }
78
95
  // Asked at each shot: the annotations plugin may be set up after this one.
79
96
  const overlay = (area: Box) => {
80
97
  const marks: Annotations | undefined = use('annotations');
@@ -88,7 +105,30 @@ export function screenshotsClient(capture: PageCapture) {
88
105
  if (id === undefined) throw new Error(`screenshots: ${problem ?? res.statusText}`);
89
106
  return { id, url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`, box: drawn ?? box, size };
90
107
  };
108
+ // The last press's page, and its shot once it's asked for: the popup that press opened has it while it's open,
109
+ // whichever of its tabs asks. Not a popup opened on another element, nor one long after the press.
110
+ let last:
111
+ { element: Element; at: number; made: Awaited<ReturnType<PageCapture>>; size: Shot['size']; shot?: Promise<Shot> } | undefined;
112
+ window.addEventListener(POPUP_CLOSED, () => (last = undefined));
113
+ window.addEventListener(POPUP_OPENED, (e) => {
114
+ if (last !== undefined && (e as CustomEvent<PopupOpened>).detail.element !== last.element) last = undefined;
115
+ });
91
116
  const api: Capture = {
117
+ freeze: (element) => {
118
+ const { clientWidth: width, clientHeight: height } = document.documentElement;
119
+ const made = freezer?.freeze(element, { area: 'viewport', masking, renderer, overlay });
120
+ last = made === undefined ? undefined : { element, at: performance.now(), made, size: { width, height } };
121
+ },
122
+ frozen: (element) => {
123
+ if (last?.element !== element || (last.shot === undefined && performance.now() - last.at > ASKED)) return undefined;
124
+ const { made, size } = last;
125
+ if (last.shot === undefined) {
126
+ last.shot = add(made.body, made.type, { box: made.box, size });
127
+ // Asked for while the popup opens, and maybe never used: a failure is said where it's awaited.
128
+ last.shot.catch(() => {});
129
+ }
130
+ return last.shot;
131
+ },
92
132
  capture: async (element, { area = 'viewport' } = {}) => {
93
133
  const { body, type, box } = await capture(element, { area, masking, renderer, overlay });
94
134
  const { clientWidth, clientHeight } = document.documentElement;
@@ -48,6 +48,17 @@ export interface Capture {
48
48
  upload(png: Blob, of: Pick<Shot, 'box' | 'size'>): Promise<Shot>;
49
49
  /** A copy of an element with what a shot hides hidden in it too: for a plugin that sends its HTML somewhere. */
50
50
  masked(element: Element): Element;
51
+ /**
52
+ * Keeps what a shot of the page now needs, to render later: the overlay calls it (through the plugin's
53
+ * `pressed`) as a shortcut's press goes down, so a tooltip, a hover's styles or a focused menu are still there.
54
+ * Only a renderer that can take the page at once does (`rrweb()`, once it has loaded); the last press's is kept.
55
+ */
56
+ freeze(element: Element): void;
57
+ /**
58
+ * The shot of the page as the last press on `element` froze it, rendered on the first ask, or nothing where the
59
+ * last press was on another element or nothing was frozen: then `capture` takes the page as it is now.
60
+ */
61
+ frozen(element: Element): Promise<Shot> | undefined;
51
62
  }
52
63
 
53
64
  /** The server's half, for other plugins' server halves. */
@@ -38,6 +38,16 @@ export interface Snapshot {
38
38
  clip?: Box;
39
39
  /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */
40
40
  overlay?: string;
41
+ /** The nodes in each interactive state as the shot was taken, which a copy of the DOM can't be in itself. */
42
+ states?: States;
43
+ }
44
+
45
+ /** The snapshot's nodes that matched each pseudo-class: what was hovered, focused, and around the focus. */
46
+ export interface States {
47
+ hover?: number[];
48
+ focus?: number[];
49
+ focusVisible?: number[];
50
+ focusWithin?: number[];
41
51
  }
42
52
 
43
53
  const HOST = '<!doctype html><html><body style="margin:0"></body></html>';
@@ -101,7 +111,7 @@ export async function render(input: unknown, options: BrowserOptions): Promise<{
101
111
  await page.addScriptTag({ path: bundle() });
102
112
  // The shot, and the attribute that sizes each canvas's picture, which the page's code can't import.
103
113
  const given = { ...shot, size: CANVAS_SIZE };
104
- const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size }) => {
114
+ const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size, states }) => {
105
115
  const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })
106
116
  .rrwebSnapshot;
107
117
  const mirror = createMirror();
@@ -120,6 +130,60 @@ export async function render(input: unknown, options: BrowserOptions): Promise<{
120
130
  const hidden = doc.createElement('style');
121
131
  hidden.textContent = 'noscript { display: none !important; }';
122
132
  doc.head.append(hidden);
133
+ // What was hovered and focused: a copy of the DOM is in no state, so each rule of those pseudo-classes is
134
+ // copied under a class of its own, and the nodes that were in it get the class. Nested rules and grouping ones
135
+ // (a Tailwind `hover:` class is `&:hover { @media (hover: hover) { … } }`) are copied whole.
136
+ if (states !== undefined) {
137
+ const pseudo: [string, string][] = [
138
+ [':focus-visible', 'deictic-focus-visible'],
139
+ [':focus-within', 'deictic-focus-within'],
140
+ [':focus', 'deictic-focus'],
141
+ [':hover', 'deictic-hover'],
142
+ ];
143
+ type Rules = { cssRules: CSSRuleList; insertRule: (rule: string, index: number) => number };
144
+ const copy = (into: Rules) => {
145
+ const list = into.cssRules;
146
+ for (let i = 0; i < list.length; i++) {
147
+ const rule = list[i] as CSSRule & Partial<Rules> & { selectorText?: string };
148
+ if (rule.cssRules !== undefined && rule.insertRule !== undefined) copy(rule as Rules);
149
+ const selector = rule.selectorText;
150
+ if (selector === undefined || !rule.cssText.startsWith(selector)) continue;
151
+ let stated = selector;
152
+ for (const [name, className] of pseudo) stated = stated.split(name).join(`.${className}`);
153
+ if (stated === selector) continue;
154
+ try {
155
+ into.insertRule(stated + rule.cssText.slice(selector.length), i + 1);
156
+ i++;
157
+ } catch {
158
+ // A selector this browser won't take back: that state goes unshown.
159
+ }
160
+ }
161
+ };
162
+ const roots: (Document | ShadowRoot)[] = [doc];
163
+ for (let i = 0; i < roots.length; i++)
164
+ for (const el of roots[i]!.querySelectorAll('*')) if (el.shadowRoot !== null) roots.push(el.shadowRoot);
165
+ for (const root of roots) {
166
+ for (const sheet of [...root.styleSheets, ...root.adoptedStyleSheets]) {
167
+ try {
168
+ copy(sheet);
169
+ } catch {
170
+ // Another origin's, which can't be read: rrweb inlines what it can.
171
+ }
172
+ }
173
+ }
174
+ const classes = {
175
+ hover: 'deictic-hover',
176
+ focus: 'deictic-focus',
177
+ focusVisible: 'deictic-focus-visible',
178
+ focusWithin: 'deictic-focus-within',
179
+ };
180
+ for (const [name, className] of Object.entries(classes)) {
181
+ for (const id of states[name as keyof typeof classes] ?? []) {
182
+ const node = mirror.getNode(id);
183
+ if (isElement(node)) node.classList.add(className);
184
+ }
185
+ }
186
+ }
123
187
  // The sandbox runs no scripts, and where scripts don't run, a canvas shows what's inside the canvas instead of
124
188
  // what was drawn on the canvas: so each canvas's picture goes inside the canvas, at the size the page laid the
125
189
  // canvas out at. rrweb's own drawing of the picture on the canvas never shows.
@@ -1,13 +1,21 @@
1
1
  /**
2
- * The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the
3
- * first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
2
+ * The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported as the page
3
+ * starts), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
4
4
  * to show it as the page does: the viewport and the window around it, where it's scrolled to, the pixel density, the page's URL.
5
- * And which node of the snapshot the element is, so the server says where it is in what it drew.
5
+ * And which node of the snapshot the element is, so the server says where it is in what it drew, and which match
6
+ * `:hover` and `:focus` and the like, which a copy of the DOM has no state for and the server gives them again.
7
+ *
8
+ * It takes the page at once, so a press can freeze it (`PageFreeze`): rrweb-snapshot is imported once the page has
9
+ * started, while the browser is idle, and a press before it has loaded is taken as the task goes, as without.
6
10
  */
11
+ import type * as RrwebSnapshot from 'rrweb-snapshot';
7
12
 
8
13
  import { CANVAS_SIZE, keepWebGLDrawing } from './canvas.ts';
9
- import { boxOf, screenshotsClient } from './client.ts';
14
+ import { boxOf, type PageCapture, type PageFreeze, screenshotsClient } from './client.ts';
10
15
  import type { Snapshot, SnapshotNode } from './playwright.ts';
16
+ import { statesOf } from './states.ts';
17
+
18
+ type Rrweb = typeof RrwebSnapshot;
11
19
 
12
20
  // As the page loads, before the page makes its canvases.
13
21
  keepWebGLDrawing();
@@ -19,30 +27,32 @@ function withoutOurs(node: SnapshotNode): SnapshotNode {
19
27
  return { ...node, childNodes };
20
28
  }
21
29
 
22
- export default screenshotsClient(async (element, { area, masking, overlay }) => {
23
- const { snapshot, createMirror } = await import('rrweb-snapshot').catch((e: unknown) => {
24
- throw new Error('the rrweb() renderer needs rrweb-snapshot: add it to your devDependencies', { cause: e });
25
- });
30
+ let loading: Promise<Rrweb> | undefined;
31
+ let loaded: Rrweb | undefined;
32
+ const load = () =>
33
+ (loading ??= import('rrweb-snapshot').then(
34
+ (module) => (loaded = module),
35
+ (e: unknown) => {
36
+ loading = undefined;
37
+ throw new Error('the rrweb() renderer needs rrweb-snapshot: add it to your devDependencies', { cause: e });
38
+ },
39
+ ));
40
+
41
+ /** The page now, at once: what the server renders. */
42
+ function take(rrweb: Rrweb, element: Element, { area, masking, overlay }: Parameters<PageCapture>[1]) {
43
+ const { snapshot, createMirror } = rrweb;
26
44
  const mirror = createMirror();
27
- // In a frame, after the page drew in it: a WebGL canvas reads back blank once its frame is shown, unless the page
28
- // keeps its drawing buffer, and the page's own callbacks for the frame were asked for before this one.
29
- const taken = await new Promise<ReturnType<typeof snapshot>>((done) =>
30
- requestAnimationFrame(() =>
31
- done(
32
- snapshot(document, {
33
- mirror,
34
- inlineStylesheet: true,
35
- // A canvas as a picture of what it shows, which the server draws on the canvas it rebuilds.
36
- recordCanvas: true,
37
- blockClass: masking.blockClass,
38
- blockSelector: masking.blockSelector ?? null,
39
- maskTextClass: masking.maskTextClass,
40
- maskTextSelector: masking.maskTextSelector ?? null,
41
- maskAllInputs: masking.maskAllInputs,
42
- }),
43
- ),
44
- ),
45
- );
45
+ const taken = snapshot(document, {
46
+ mirror,
47
+ inlineStylesheet: true,
48
+ // A canvas as a picture of what it shows, which the server draws on the canvas it rebuilds.
49
+ recordCanvas: true,
50
+ blockClass: masking.blockClass,
51
+ blockSelector: masking.blockSelector ?? null,
52
+ maskTextClass: masking.maskTextClass,
53
+ maskTextSelector: masking.maskTextSelector ?? null,
54
+ maskAllInputs: masking.maskAllInputs,
55
+ });
46
56
  if (taken === null) throw new Error('screenshots: rrweb took no snapshot of this page');
47
57
  // Each canvas's size as the page lays it out, and whether in a line, as which the server shows the canvas's picture.
48
58
  for (const canvas of document.querySelectorAll('canvas')) {
@@ -55,6 +65,7 @@ export default screenshotsClient(async (element, { area, masking, overlay }) =>
55
65
  const viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
56
66
  // Over the viewport, which the server renders before cutting out an element's part.
57
67
  const marks = overlay({ x: 0, y: 0, ...viewport });
68
+ const states = statesOf((el) => mirror.getId(el));
58
69
  const body: Snapshot = {
59
70
  snapshot: withoutOurs(taken),
60
71
  ...(mirror.getId(element) === -1 ? {} : { element: mirror.getId(element) }),
@@ -62,10 +73,26 @@ export default screenshotsClient(async (element, { area, masking, overlay }) =>
62
73
  viewport,
63
74
  window: { width: innerWidth, height: innerHeight },
64
75
  ...(marks === undefined ? {} : { overlay: marks }),
76
+ ...(Object.keys(states).length === 0 ? {} : { states }),
65
77
  scroll: { x: scrollX, y: scrollY },
66
78
  scale: Math.min(devicePixelRatio, 2),
67
79
  // A shot of the element alone is the part of the viewport it fills.
68
80
  ...(area === 'element' ? { clip: element.getBoundingClientRect().toJSON() as Snapshot['clip'] } : {}),
69
81
  };
70
82
  return { body: JSON.stringify(body), type: 'application/json', box };
71
- });
83
+ }
84
+
85
+ const freezer: PageFreeze = {
86
+ // Not in a frame: a press is now, before the page's own handlers change it. A WebGL canvas shows what it drew,
87
+ // as `keepWebGLDrawing` has it keep its buffer.
88
+ freeze: (element, options) => (loaded === undefined ? undefined : take(loaded, element, options)),
89
+ prepare: () => void load().catch(() => {}),
90
+ };
91
+
92
+ export default screenshotsClient(async (element, options) => {
93
+ const rrweb = await load();
94
+ // In a frame, after the page drew in it: a WebGL canvas reads back blank once its frame is shown, unless the page
95
+ // keeps its drawing buffer, and the page's own callbacks for the frame were asked for before this one.
96
+ await new Promise((done) => requestAnimationFrame(done));
97
+ return take(rrweb, element, options);
98
+ }, freezer);
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What a copy of the DOM loses: which elements are hovered and focused. The `rrweb()` renderer reads it as it takes
3
+ * the page, and its server half gives the rebuilt page those states again (`playwright.ts`). Self-contained, with
4
+ * nothing from outside it, so a test can run this very function in a browser.
5
+ */
6
+ import type { States } from './playwright.ts';
7
+
8
+ /** Which nodes match each state now, by the snapshot's IDs (`id`), through open shadow roots, deictic's overlay left out. */
9
+ export function statesOf(id: (el: Element) => number, root: Document = document): States {
10
+ const pseudo = { hover: ':hover', focus: ':focus', focusVisible: ':focus-visible', focusWithin: ':focus-within' } as const;
11
+ const states: States = {};
12
+ for (const [name, selector] of Object.entries(pseudo) as [keyof States, string][]) {
13
+ const ids: number[] = [];
14
+ const within = (inside: Document | ShadowRoot) => {
15
+ for (const el of inside.querySelectorAll(selector)) {
16
+ if (el.localName === 'deictic-overlay') continue;
17
+ const known = id(el);
18
+ if (known !== -1) ids.push(known);
19
+ if (el.shadowRoot !== null) within(el.shadowRoot);
20
+ }
21
+ };
22
+ within(root);
23
+ if (ids.length > 0) states[name] = ids;
24
+ }
25
+ return states;
26
+ }