deictic 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/API.md +150 -37
  2. package/README.md +4 -3
  3. package/dist/annotations/client.d.ts +1 -1
  4. package/dist/annotations/client.d.ts.map +1 -1
  5. package/dist/annotations/client.js +161 -176
  6. package/dist/annotations/client.js.map +1 -1
  7. package/dist/annotations/index.d.ts +2 -11
  8. package/dist/client/index.d.ts +7 -6
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +1007 -192
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/index.d.ts +2 -2
  13. package/dist/recommended/index.d.ts +2 -2
  14. package/dist/recordings/client.d.ts.map +1 -1
  15. package/dist/recordings/client.js +82 -153
  16. package/dist/recordings/client.js.map +1 -1
  17. package/dist/screenshots/client.d.ts.map +1 -1
  18. package/dist/shared/annotations.js +3 -4
  19. package/dist/shared/annotations.js.map +1 -1
  20. package/dist/shared/board.js +1 -1
  21. package/dist/shared/client.js +45 -2
  22. package/dist/shared/client.js.map +1 -1
  23. package/dist/shared/component.js +62 -0
  24. package/dist/shared/component.js.map +1 -0
  25. package/dist/shared/dom.js +79 -0
  26. package/dist/shared/dom.js.map +1 -0
  27. package/dist/shared/drawer.js +217 -0
  28. package/dist/shared/drawer.js.map +1 -0
  29. package/dist/shared/endpoints.js +34 -8
  30. package/dist/shared/endpoints.js.map +1 -1
  31. package/dist/shared/find.js +2 -1
  32. package/dist/shared/find.js.map +1 -1
  33. package/dist/shared/index.d.ts +124 -11
  34. package/dist/shared/index.d.ts.map +1 -1
  35. package/dist/shared/index2.d.ts +9 -19
  36. package/dist/shared/index2.d.ts.map +1 -1
  37. package/dist/shared/index7.d.ts +105 -26
  38. package/dist/shared/index7.d.ts.map +1 -1
  39. package/dist/shared/index9.d.ts +1 -1
  40. package/dist/shared/init.js +12 -10
  41. package/dist/shared/init.js.map +1 -1
  42. package/dist/shared/integration.d.ts +1 -1
  43. package/dist/shared/packages.js +1 -1
  44. package/dist/shared/recording.js +31 -3
  45. package/dist/shared/recording.js.map +1 -1
  46. package/dist/shared/src.js.map +1 -1
  47. package/dist/shared/task.js +72 -21
  48. package/dist/shared/task.js.map +1 -1
  49. package/dist/shared/tasks.js +330 -166
  50. package/dist/shared/tasks.js.map +1 -1
  51. package/dist/shared/vb.js +1 -1
  52. package/dist/shared/voice2.js +6 -4
  53. package/dist/shared/voice2.js.map +1 -1
  54. package/dist/shared/watch.js +14 -14
  55. package/dist/shared/watch.js.map +1 -1
  56. package/dist/tailwind/index.js +6 -2
  57. package/dist/tailwind/index.js.map +1 -1
  58. package/dist/tasks/client.d.ts +2 -2
  59. package/dist/tasks/client.d.ts.map +1 -1
  60. package/dist/tasks/client.js +1829 -742
  61. package/dist/tasks/client.js.map +1 -1
  62. package/dist/tasks/index.d.ts +2 -2
  63. package/dist/voice/client.d.ts.map +1 -1
  64. package/dist/voice/client.js +154 -57
  65. package/dist/voice/client.js.map +1 -1
  66. package/package.json +1 -1
  67. package/skills/deictic/SKILL.md +22 -28
  68. package/src/cli/find.ts +3 -1
  69. package/src/cli/init.ts +13 -11
  70. package/src/cli/recording.ts +34 -3
  71. package/src/cli/task.ts +94 -23
  72. package/src/cli/voice.ts +9 -4
  73. package/src/cli/watch.ts +14 -13
  74. package/src/client/away.ts +3 -1
  75. package/src/client/component.ts +98 -0
  76. package/src/client/dom.ts +70 -0
  77. package/src/client/drawer.ts +258 -0
  78. package/src/client/index.ts +220 -128
  79. package/src/client/lightbox.ts +8 -8
  80. package/src/client/lighting.ts +279 -0
  81. package/src/client/style.ts +263 -44
  82. package/src/client/tools.ts +279 -0
  83. package/src/client/tooltip.ts +25 -5
  84. package/src/client/tray.ts +48 -0
  85. package/src/index.ts +121 -10
  86. package/src/plugins/annotations/client.ts +103 -129
  87. package/src/plugins/annotations/draw.ts +68 -72
  88. package/src/plugins/annotations/index.ts +12 -19
  89. package/src/plugins/recordings/client.ts +89 -167
  90. package/src/plugins/screenshots/client.ts +53 -2
  91. package/src/plugins/tailwind/index.ts +6 -2
  92. package/src/plugins/tasks/client.ts +219 -749
  93. package/src/plugins/tasks/composer.ts +797 -0
  94. package/src/plugins/tasks/drawer.ts +516 -0
  95. package/src/plugins/tasks/index.ts +459 -192
  96. package/src/plugins/tasks/pins.ts +275 -0
  97. package/src/plugins/tasks/store.ts +132 -0
  98. package/src/plugins/voice/client.ts +96 -5
  99. package/src/tools/endpoints.ts +18 -7
  100. package/src/tools/source.ts +25 -5
  101. package/skills/deictic/references/recordings.md +0 -13
  102. package/skills/deictic/references/tasks.md +0 -21
  103. package/skills/deictic/references/watch.md +0 -17
package/src/cli/task.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * page, what's attached with the command to look at each, the replies, and the other open tasks about the same page.
4
4
  */
5
5
  import { existsSync, mkdirSync, readFileSync } from 'node:fs';
6
- import { dirname, join, resolve } from 'node:path';
6
+ import { dirname, join, relative, resolve } from 'node:path';
7
7
 
8
8
  import { deicticDirs, download, ME, type Message, read, vbJson } from './board.ts';
9
9
 
@@ -30,29 +30,94 @@ export function run(id: string, values: { out?: string }): void {
30
30
  const facts: [string, (v: string) => string | undefined][] = [
31
31
  ['deictic.project', (v) => `Project ${v}`],
32
32
  ['deictic.at', (v) => `${v} <${label('deictic.tag') ?? '?'}>`],
33
+ // From its own line out: before the label, tasks said it in their text, which is printed below as it is.
34
+ // The first is often a shared component (`ui/label.tsx`), which the task isn't about changing everywhere.
35
+ ['deictic.source', (v) => `Source: ${at?.replace(/:\d+$/, '') ?? '?'} ← ${v} (a shared component's change is usually at the next)`],
33
36
  ['deictic.url', (v) => v],
34
37
  ['deictic.viewport', (v) => `Viewport ${v}`],
35
38
  ['deictic.count', (v) => (v === '1' ? undefined : `${v} elements on the page come from that line`)],
36
- ['deictic.position', (v) => `In the screenshot at x,y ${v}, ${label('deictic.size') ?? '?'} (CSS pixels from its top left)`],
39
+ [
40
+ 'deictic.point',
41
+ // Circled only in a shot taken as the task went, which no label tells from one drawn on before.
42
+ (v) =>
43
+ `About the spot at x,y ${v} in that element (CSS px from its top left): a screenshot taken as the task was added has it circled`,
44
+ ],
45
+ // A task added before shots were numbered had its one shot's place here.
46
+ ['deictic.position', (v) => `In the screenshot at x,y ${v}, ${label('deictic.size') ?? '?'} (CSS px)`],
37
47
  ];
38
48
  for (const [key, say] of facts) {
39
49
  const value = label(key);
40
50
  const line = value === undefined ? undefined : say(value);
41
51
  if (line !== undefined) console.log(line);
42
52
  }
43
- // What no label holds: what's attached and drawn on it.
53
+ if (at === undefined)
54
+ console.log("About the page as a whole: no element was attached, so find it from the words, the page's URL and the screenshot");
55
+ for (const line of drawn(root)) console.log(line);
56
+ // A task added before these were labels says them after its words.
44
57
  const told = (pointed ? where.slice(0, pointed.index) : where).trim();
45
58
  if (told !== '') console.log(told);
46
59
  if (pointed) console.log(`\nPointed at, inside it: ${pointed[1]}\n ${pointed[2]}`);
60
+ const path = label('deictic.pointed');
61
+ if (path !== undefined) {
62
+ const file = root.attachments.some((a) => a.name === 'pointed.html') ? 'pointed.html' : 'element.html';
63
+ // Markup no line marks, a dependency's.
64
+ console.log(
65
+ `\nPointed at, inside it: ${path} (its HTML is in ${file}): what they mean, though no line marks it; find it by its classes`,
66
+ );
67
+ }
47
68
 
48
69
  if (at !== undefined) placeOf(at, label('deictic.line'));
49
- attachments(root, values.out === undefined ? undefined : resolve(values.out));
70
+ const out = values.out === undefined ? undefined : resolve(values.out);
71
+ if (root.attachments.length > 0) console.log('\nAttached:');
72
+ attachments(root, out, ' ', String(root.id));
50
73
 
51
74
  if (replies.length > 0) console.log('\nReplies:');
52
- for (const r of replies) console.log(` ${r.author?.handle ?? r.by.actor}: ${r.text}`);
75
+ for (const r of replies) {
76
+ console.log(` ${r.author?.handle ?? r.by.actor}: ${r.text}`);
77
+ // A reply may attach what a task does: shots, a recording, a voice note.
78
+ for (const line of drawn(r)) console.log(` ${line}`);
79
+ attachments(r, out, ' ');
80
+ }
81
+ // Said once, not as a command per file: most tasks need their shots, and `--out` gets everything at once.
82
+ if (out === undefined && [root, ...replies].some((m) => m.attachments.length > 0))
83
+ console.log(`\nTo download what's attached: ${ME} task ${root.id} --out <dir>`);
53
84
  others(root);
54
85
  }
55
86
 
87
+ /**
88
+ * What the attached files don't say, from the numbered labels: where the element is in each shot and the notes on it, the
89
+ * notes drawn on the page, and what wasn't kept any more. Where a recording replays, `recording` says.
90
+ */
91
+ function drawn({ labels, attachments }: Message): string[] {
92
+ const numbered = (prefix: string) => {
93
+ const out: string[] = [];
94
+ for (let n = 1; labels[`${prefix}.${n}`] !== undefined; n++) out.push(labels[`${prefix}.${n}`]!);
95
+ return out;
96
+ };
97
+ const notes = (prefix: string) => numbered(`${prefix}.note`).map((note) => JSON.stringify(note));
98
+ const lines: string[] = [];
99
+ // `deictic.screenshot.N` is the Nth PNG attached, `deictic.recording.N` the Nth recording.
100
+ for (const [i, { name }] of attachments.filter((a) => a.type === 'image/png').entries()) {
101
+ const shot = `deictic.screenshot.${i + 1}`;
102
+ const position = labels[`${shot}.position`];
103
+ if (position === undefined) continue;
104
+ const said = notes(shot);
105
+ lines.push(
106
+ `${name}: the element at x,y ${position}, ${labels[`${shot}.size`] ?? '?'} (CSS px)${said.length === 0 ? '' : `; notes drawn on it: ${said.join(', ')}`}`,
107
+ );
108
+ }
109
+ // The others it's about, after the one it names first: the Nth element's HTML is `element.N.html`.
110
+ for (const [i, other] of numbered('deictic.also').entries()) {
111
+ const html = attachments.some((a) => a.name === `element.${i + 2}.html`) ? ` (its HTML is in element.${i + 2}.html)` : '';
112
+ lines.push(`Also about ${other}${html}`);
113
+ }
114
+ const onPage = notes('deictic');
115
+ if (onPage.length > 0) lines.push(`Notes drawn on the page: ${onPage.join(', ')}`);
116
+ const dropped = numbered('deictic.dropped');
117
+ if (dropped.length > 0) lines.push(`Not attached, as it wasn't kept any more: ${dropped.join(', ')}`);
118
+ return lines;
119
+ }
120
+
56
121
  /** The place as the task saw it, against the file now: the element's opening tag may have moved or changed. */
57
122
  function placeOf(at: string, first: string | undefined): void {
58
123
  const file = at.replace(/:\d+:\d+$/, '');
@@ -65,43 +130,49 @@ function placeOf(at: string, first: string | undefined): void {
65
130
  return;
66
131
  }
67
132
  const lines = readFileSync(path, 'utf8').split('\n');
133
+ const shown = relative(process.cwd(), path) || path;
68
134
  // The tag's first line may follow other code on its line: `const App = () => <h1>`.
69
135
  const now = lines[line - 1]?.trim();
70
136
  if (first === undefined || now?.includes(first.slice(0, 40))) {
71
- console.log(`\nFile: ${path}:${line}, as the task saw it.`);
137
+ console.log(`\nFile: ${shown}:${line}, as the task saw it.`);
72
138
  return;
73
139
  }
74
140
  const moved = lines.findIndex((l) => l.includes(first.slice(0, 40)));
75
141
  console.log(
76
142
  moved >= 0
77
- ? `\nFile: moved to ${path}:${moved + 1} (the task says line ${line}).`
78
- : `\nFile: ${path}:${line} no longer reads as the task saw it; it was:\n ${first}`,
143
+ ? `\nFile: moved to ${shown}:${moved + 1} (the task says line ${line}).`
144
+ : `\nFile: ${shown}:${line} no longer reads as the task saw it; it was:\n ${first}`,
79
145
  );
80
146
  }
81
147
 
82
- /** What's attached, with the command to look at each, downloaded to `out` where it's given. */
83
- function attachments(root: Message, out: string | undefined): void {
84
- if (root.attachments.length > 0) console.log('\nAttached:');
85
- if (out !== undefined) mkdirSync(out, { recursive: true });
86
- for (const a of root.attachments) {
148
+ /**
149
+ * A message's files, with the command to read a recording or voice clip by, downloaded to `out` where it's given. The
150
+ * task's own are read by its ID (all its voice clips at once); a reply's recording by where it replays, and its voice
151
+ * note by the clip's ID.
152
+ */
153
+ function attachments(message: Message, out: string | undefined, indent: string, task?: string): void {
154
+ if (out !== undefined && message.attachments.length > 0) mkdirSync(out, { recursive: true });
155
+ const recordings = message.attachments.filter((a) => a.name.startsWith('recording-'));
156
+ for (const a of message.attachments) {
87
157
  const kb = `${Math.round(a.size / 1024)} KB`;
88
158
  if (out !== undefined) download(a, join(out, a.name));
89
- const saved = out === undefined ? '' : ` → ${join(out, a.name)}`;
90
- // To a file's path: the CLI writes what it's given, and refuses a folder.
91
- const get = saved || `: ${ME} vb download ${a.id} ${a.name}`;
159
+ const saved = out === undefined ? '' : ` → ${relative(process.cwd(), join(out, a.name))}`;
92
160
  if (a.name.startsWith('recording-')) {
93
- console.log(` ${a.name} (${kb})${saved}`);
94
- console.log(` timeline: ${ME} recording ${root.id}`);
95
- console.log(` frames: ${ME} frame ${root.id}`);
161
+ const n = recordings.indexOf(a) + 1;
162
+ const ref = task === undefined ? message.labels[`deictic.recording.${n}.replay`] : `${task}${n > 1 ? ` --nth ${n}` : ''}`;
163
+ console.log(`${indent}${a.name} (${kb})${saved}`);
164
+ if (ref !== undefined) console.log(`${indent} ${ME} recording ${ref} (timeline), ${ME} frame ${ref} (frames)`);
96
165
  } else if (a.name.startsWith('voice-')) {
97
- console.log(` ${a.name} (${kb}), a voice clip${saved}`);
98
- console.log(` speech: ${ME} voice ${root.id}`);
166
+ console.log(`${indent}${a.name} (${kb}), a voice clip${saved}`);
167
+ if (task === undefined) console.log(`${indent} ${ME} voice ${/^voice-(.+)\.\w+$/.exec(a.name)?.[1] ?? a.id} (speech)`);
99
168
  } else if (a.name === 'element.html') {
100
- console.log(` ${a.name} (${kb}), the element's HTML as it rendered, if you need it${get}`);
169
+ console.log(`${indent}${a.name} (${kb}), the element's HTML as it rendered, if you need it${saved}`);
101
170
  } else {
102
- console.log(` ${a.name} (${a.type}, ${kb})${get}`);
171
+ console.log(`${indent}${a.name} (${kb})${saved}`);
103
172
  }
104
173
  }
174
+ if (task !== undefined && message.attachments.some((a) => a.name.startsWith('voice-')))
175
+ console.log(`${indent}${ME} voice ${task} (speech in every clip), ${ME} transcribe ${task} (the words)`);
105
176
  }
106
177
 
107
178
  /** The other open tasks about the same page, of the same project: left a minute apart, they're often one change. */
package/src/cli/voice.ts CHANGED
@@ -4,9 +4,9 @@
4
4
  * it too. `--wav` writes each clip as 16 kHz mono WAV, what speech-to-text tools take.
5
5
  */
6
6
  import { mkdirSync } from 'node:fs';
7
- import { join, resolve } from 'node:path';
7
+ import { join, relative, resolve } from 'node:path';
8
8
 
9
- import { clock } from './board.ts';
9
+ import { clock, ME } from './board.ts';
10
10
  import { ffmpeg, voiceClips } from './find.ts';
11
11
 
12
12
  export async function run(ref: string, values: { noise: string; gap: string; wav?: string; json?: boolean }): Promise<void> {
@@ -42,9 +42,14 @@ export async function run(ref: string, values: { noise: string; gap: string; wav
42
42
  }
43
43
  for (const r of results) {
44
44
  const where = r.recording === undefined ? 'a voice note' : `in recording ${r.recording}, from ${clock(r.at)}`;
45
- console.log(`clip ${r.id} (${where}), ${clock(r.length)} long: ${r.file}`);
45
+ console.log(`clip ${r.id} (${where}), ${clock(r.length)} long: ${relative(process.cwd(), r.file)}`);
46
46
  if (r.speech.length === 0) console.log(' no speech found: try a lower --noise, like -45');
47
47
  for (const s of r.speech) console.log(` ${clock(s.from).padStart(6)} – ${clock(s.to).padStart(6)} speech`);
48
- if (wav !== undefined) console.log(` wav: ${join(wav, `${r.id}.wav`)}`);
48
+ if (wav !== undefined) console.log(` wav: ${relative(process.cwd(), join(wav, `${r.id}.wav`))}`);
49
49
  }
50
+ // Speech in a recording points at the page: "this one" is what was on screen as it was said.
51
+ if (!results.some((r) => r.recording !== undefined && r.speech.length > 0)) return;
52
+ console.log(
53
+ `\nWhat was on screen as they spoke is what they mean: ${ME} frame ${ref} --at <seconds>. The words: ${ME} transcribe ${ref}.`,
54
+ );
50
55
  }
package/src/cli/watch.ts CHANGED
@@ -16,7 +16,7 @@ import { createInterface } from 'node:readline';
16
16
 
17
17
  import { watcherAt } from '#src/plugins/tasks/watchers.ts';
18
18
 
19
- import { answers, boardIn, boardUrl, deicticDirs, duration, ME, vb, vbCommand, vbJson, whoami } from './board.ts';
19
+ import { answers, boardIn, boardUrl, deicticDirs, duration, ME, type Message, vbCommand, vbJson, whoami } from './board.ts';
20
20
 
21
21
  /** What `vb tail --json` prints, one per line. */
22
22
  interface Tailed {
@@ -98,6 +98,14 @@ export function run(channel: string, values: { idle: string; once?: boolean; lab
98
98
  const idle = duration(values.idle);
99
99
  const say = (line: string) => console.log(line.replace(/\s+/g, ' ').trim());
100
100
  const first = (text: string) => (text.split('\n---')[0] ?? '').trim().slice(0, 160);
101
+ // A task in a line: its words and where, not its labels, which `task` reads out.
102
+ const about = (text: string, labels: Record<string, string> | undefined) => {
103
+ const label = (key: string) => labels?.[key];
104
+ const at = label('deictic.at');
105
+ const page = label('deictic.page');
106
+ const project = label('deictic.project');
107
+ return `"${first(text)}"${at ? ` at ${at}` : ''}${page ? ` on ${page}` : ''}${project ? ` in ${project}` : ''}`;
108
+ };
101
109
 
102
110
  // A board nothing has posted to yet has no channel, and won't list or follow one it hasn't: made here, as the first
103
111
  // task would make it. One that's there stays as it is; where the board won't let this make one, `vb tasks` says so.
@@ -109,7 +117,7 @@ export function run(channel: string, values: { idle: string; once?: boolean; lab
109
117
  // Where the channel is now, taken before what's ready is: followed from here, nothing posted between is missed, and
110
118
  // a tail started again after the board went away follows on from what this one heard, never from a list taken earlier.
111
119
  let cursor = vbJson<{ cursor: string }>(['read', channel, '--limit', '1']).cursor;
112
- const ready = vb(['tasks', channel, '--state', 'ready', ...labels]).trim();
120
+ const ready = vbJson<{ tasks: { message: Message }[] }>(['tasks', channel, '--state', 'ready', ...labels]).tasks.map((t) => t.message);
113
121
  const me = whoami();
114
122
  // In the `.deictic/` whose board this is, or in each one near here where the board is the environment's.
115
123
  const url = boardUrl();
@@ -143,11 +151,10 @@ export function run(channel: string, values: { idle: string; once?: boolean; lab
143
151
  `you write as ${me.handle ?? me.actor}, the person's own identity, as nothing here says which agent you are: set BOARD_PROFILE=<your name> (claude, codex) on every command, this watch too, and start it again`,
144
152
  );
145
153
  }
146
- const waiting = (ready ? ready.split('\n') : []).filter((line) => /^#\d+/.test(line));
147
154
  // The tasks said, by ID: one made after the cursor above and listed as ready is said once.
148
- const told = new Set(waiting.map((line) => /^#(\d+)/.exec(line)?.[1]));
149
- for (const line of waiting) say(`ready: ${line}`);
150
- if (values.once && waiting.length > 0) end(0);
155
+ const told = new Set(ready.map((m) => String(m.id)));
156
+ for (const m of ready) say(`ready: #${m.id} ${about(m.text, m.labels)}. Read it: ${ME} task ${m.id}`);
157
+ if (values.once && ready.length > 0) end(0);
151
158
 
152
159
  /** One thing to act on: all `--once` waits for. */
153
160
  const event = (line: string) => {
@@ -181,13 +188,7 @@ export function run(channel: string, values: { idle: string; once?: boolean; lab
181
188
  if (e.cursor !== undefined) cursor = e.cursor;
182
189
  heard();
183
190
  const p = e.payload ?? {};
184
- const label = (key: string) => p.labels?.[key];
185
- if (e.type === 'message.posted' && p.re === null && p.thread !== undefined) {
186
- const at = label('deictic.at');
187
- const page = label('deictic.page');
188
- const project = label('deictic.project');
189
- roots.set(p.thread, `"${first(p.text ?? '')}"${at ? ` at ${at}` : ''}${page ? ` on ${page}` : ''}${project ? ` in ${project}` : ''}`);
190
- }
191
+ if (e.type === 'message.posted' && p.re === null && p.thread !== undefined) roots.set(p.thread, about(p.text ?? '', p.labels));
191
192
  if (e.type === 'task.created' && !told.has(String(p.id)))
192
193
  event(`new task #${p.id}: ${roots.get(p.thread ?? -1) ?? ''}. Read it: ${ME} task ${p.id}`);
193
194
  if (e.type === 'message.posted' && p.re !== null && p.re !== undefined) {
@@ -5,12 +5,14 @@
5
5
  * The state may hold what JSON can't (a drawn screenshot is a `Blob`), so it's in IndexedDB, which is the
6
6
  * origin's: the tab's session storage holds the key, so each tab comes back to its own.
7
7
  */
8
- import type { Target } from '#src/index.ts';
8
+ import type { Point, Target } from '#src/index.ts';
9
9
 
10
10
  /** What the next page needs to come back: which tab, on what, with what. */
11
11
  export interface Away {
12
12
  tab: string;
13
13
  target: Target;
14
+ /** The spot in the element the popup was on, where it was on one. */
15
+ at?: Point;
14
16
  state: unknown;
15
17
  }
16
18
 
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The component that wrote an element, where the page can say: with React in development, which keeps who wrote
3
+ * each element on its fiber. Anything else (another framework, a production build) says nothing, and an element is
4
+ * then known by its tag alone.
5
+ */
6
+
7
+ /**
8
+ * What React keeps, in development, of who wrote an element: a fiber (its `type` the component), or for a server
9
+ * component its `name`. Each has the one that wrote it in turn. A fiber has what it rendered under it, too.
10
+ */
11
+ export interface Owner {
12
+ name?: unknown;
13
+ type?: unknown;
14
+ alternate?: Owner | null;
15
+ owner?: Owner | null;
16
+ _debugOwner?: Owner | null;
17
+ child?: Owner | null;
18
+ sibling?: Owner | null;
19
+ return?: Owner | null;
20
+ }
21
+
22
+ /** React's fiber of an element it rendered, which it keeps on the element under a key of its own. */
23
+ export const fiberOf = (el: Element): Owner | undefined => {
24
+ const key = Object.keys(el).find((k) => k.startsWith('__reactFiber$'));
25
+ return key === undefined ? undefined : (el as unknown as Record<string, Owner>)[key];
26
+ };
27
+
28
+ export const ownerOf = (of: Owner | undefined): Owner | undefined => of?._debugOwner ?? of?.owner ?? undefined;
29
+
30
+ /** A component's name, through `memo` and `forwardRef`, or nothing for one written without. */
31
+ export function componentOf(owner: Owner): string | undefined {
32
+ if (typeof owner.name === 'string') return owner.name === '' ? undefined : owner.name;
33
+ let type = owner.type as { displayName?: unknown; name?: unknown; render?: unknown; type?: unknown } | null | undefined;
34
+ for (let depth = 0; depth < 4 && type !== null && type !== undefined; depth++) {
35
+ // A function's own name, where it has no `displayName`; a `memo` or `forwardRef` object has neither.
36
+ const name = type.displayName ?? type.name;
37
+ if (typeof name === 'string' && name !== '') return name;
38
+ type = (type.render ?? type.type) as typeof type;
39
+ }
40
+ return undefined;
41
+ }
42
+
43
+ /** How an element is told to a person: its tag, and the component that wrote it where the page says. */
44
+ export interface Named {
45
+ tag: string;
46
+ /** The component whose JSX has the element: `PlanCard`. */
47
+ component?: string;
48
+ /** Whether the element is the only one that component wrote: then the component's name says it all. */
49
+ sole: boolean;
50
+ }
51
+
52
+ /** How far under a component its elements are counted: past that it's taken to have several. */
53
+ const LOOKED = 400;
54
+
55
+ /** Whether `owner` wrote no element but the one: read off what it rendered, which holds what it passed down as children too. */
56
+ function wroteOne(owner: Owner): boolean {
57
+ // A component's fiber is one of two, by turns: an element may name either.
58
+ const its = (fiber: Owner | null | undefined) => fiber !== null && fiber !== undefined && (fiber === owner || fiber === owner.alternate);
59
+ let wrote = 0;
60
+ let looked = 0;
61
+ // Down, then across, then back up to the next across: every fiber under it, without a stack.
62
+ for (let at = owner.child; at !== null && at !== undefined;) {
63
+ if (++looked > LOOKED) return false;
64
+ if (typeof at.type === 'string' && its(ownerOf(at)) && ++wrote > 1) return false;
65
+ if (at.child !== null && at.child !== undefined) {
66
+ at = at.child;
67
+ continue;
68
+ }
69
+ while (at.sibling === null || at.sibling === undefined) {
70
+ const up: Owner | null | undefined = at.return;
71
+ // Back at the component: that was all of it.
72
+ if (up === null || up === undefined || its(up)) return wrote === 1;
73
+ at = up;
74
+ }
75
+ at = at.sibling;
76
+ }
77
+ return wrote === 1;
78
+ }
79
+
80
+ // Asked each frame while it's pointed at: an element's answer is kept while the element is.
81
+ const known = new WeakMap<Element, Named>();
82
+
83
+ export function named(el: Element): Named {
84
+ const kept = known.get(el);
85
+ if (kept !== undefined) return kept;
86
+ const owner = ownerOf(fiberOf(el));
87
+ const component = owner === undefined ? undefined : componentOf(owner);
88
+ const answer: Named =
89
+ owner === undefined || component === undefined
90
+ ? { tag: el.localName, sole: false }
91
+ : { tag: el.localName, component, sole: wroteOne(owner) };
92
+ known.set(el, answer);
93
+ return answer;
94
+ }
95
+
96
+ /** `<PlanCard>` for the only element of one, `<PlanCard> <li>` for one of several, `<li>` where no component is known. */
97
+ export const tell = ({ tag, component, sole }: Named) =>
98
+ component === undefined ? `<${tag}>` : sole ? `<${component}>` : `<${component}> <${tag}>`;
@@ -0,0 +1,70 @@
1
+ /** The little the overlay's parts all draw with. */
2
+ import type { Target } from '#src/index.ts';
3
+
4
+ /** The attribute the transform marks an element with: `file:line:column`. */
5
+ export const ATTRIBUTE = 'data-deictic';
6
+
7
+ /** An element's place in the source, as its mark has it, or nothing for one with none. */
8
+ export function targetOf(el: Element): Target | undefined {
9
+ const at = el.getAttribute(ATTRIBUTE);
10
+ const match = at === null ? null : /^(.*):(\d+):(\d+)$/.exec(at);
11
+ if (match === null) return undefined;
12
+ return { loc: { file: match[1]!, line: Number(match[2]), column: Number(match[3]) }, tag: el.localName };
13
+ }
14
+
15
+ /** Every element on the page from the same place in the source as `el`. */
16
+ export const sameAs = (el: Element) => [...document.querySelectorAll(`[${ATTRIBUTE}="${CSS.escape(el.getAttribute(ATTRIBUTE) ?? '')}"]`)];
17
+
18
+ export function div(className: string): HTMLDivElement {
19
+ const el = document.createElement('div');
20
+ el.className = className;
21
+ return el;
22
+ }
23
+
24
+ /** Puts a fixed box over `r`. */
25
+ export function place(el: HTMLElement, r: DOMRect): void {
26
+ Object.assign(el.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
27
+ }
28
+
29
+ /** `button.tab`: the element as a selector, its own classes only, for a person to tell it by. */
30
+ export const nameOf = (el: Element) => `${el.localName}${[...el.classList].map((c) => `.${c}`).join('')}`;
31
+
32
+ export const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
33
+
34
+ /**
35
+ * A button for the tool panel: an icon (its strokes, on a 24-pixel grid), named by its tooltip and for a screen
36
+ * reader, with the keys that press it (`B`, `Control+Z`), which the tooltip shows and the panel hears.
37
+ */
38
+ export function toolButton(strokes: string, name: string, keys: string | undefined, run: () => void): HTMLButtonElement {
39
+ const el = Object.assign(document.createElement('button'), { type: 'button', className: 'icon', title: name });
40
+ el.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${strokes}</svg>`;
41
+ el.setAttribute('aria-label', name);
42
+ if (keys !== undefined) el.setAttribute('aria-keyshortcuts', keys);
43
+ el.addEventListener('click', run);
44
+ return el;
45
+ }
46
+
47
+ /**
48
+ * The control in `within` that a key is for, by its `aria-keyshortcuts`: a key alone, or with the keys it names.
49
+ * `loose` takes a key alone whatever is held with it, for while a shortcut's keys are held to point.
50
+ */
51
+ export function controlFor(within: ParentNode, e: KeyboardEvent, loose = false): HTMLElement | undefined {
52
+ // By the letter typed, and by where the key is where it types no Latin letter (another layout, or Alt held).
53
+ const key = /^[a-z]$/i.test(e.key) ? e.key.toUpperCase() : e.code.startsWith('Key') ? e.code.slice(3) : e.key;
54
+ const held = [e.ctrlKey && 'Control', e.metaKey && 'Meta', e.shiftKey && 'Shift'].filter((m) => m !== false);
55
+ for (const el of within.querySelectorAll<HTMLElement>('[aria-keyshortcuts]')) {
56
+ if (el instanceof HTMLButtonElement && el.disabled) continue;
57
+ // One that isn't shown now: a recording's Stop while none is going.
58
+ if (el.offsetParent === null) continue;
59
+ for (const keys of (el.getAttribute('aria-keyshortcuts') ?? '').split(' ')) {
60
+ const named = keys.split('+');
61
+ if (named.at(-1) !== key) continue;
62
+ const mods = named.slice(0, -1);
63
+ if (mods.length === 0 ? loose || held.length === 0 : mods.length === held.length && mods.every((m) => held.includes(m))) return el;
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ /** The key held with a letter for a command, as the platform has it, by the name `aria-keyshortcuts` gives it. */
70
+ export const MOD = typeof navigator !== 'undefined' && /Mac|iP(?:hone|ad)/.test(navigator.platform) ? 'Meta' : 'Control';