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
@@ -0,0 +1,797 @@
1
+ /**
2
+ * The composer: a field as a chat has, shared by the Task tab (a new task) and a task's thread in the drawer (a
3
+ * reply). What's attached is chips over the words, and under them the buttons that attach, each an icon named by its
4
+ * tooltip, and the arrow that sends. Enter sends, and Shift+Enter starts a new line.
5
+ *
6
+ * Two buttons are on or off. With the screenshots plugin, a shot of the page goes as it's sent, the elements
7
+ * outlined in it (or the spot circled): nothing else says which of two rows alike was meant. And, for a task, the
8
+ * element's HTML as it rendered, as a file. The rest make something: Draw takes a shot and opens it to draw on, in the
9
+ * annotations plugin's editor; Record is the caller's (the Task tab leaves the popup to record the page); Voice
10
+ * records the mic here, its time and waveform beside it.
11
+ *
12
+ * A task's elements are chips too: the one the popup is on to begin with, and any other the element button's next
13
+ * press on the page picks. A reply has none.
14
+ *
15
+ * A picture pasted in, or dropped on it, is a screenshot of its own, in the tray, to draw on as one drawn here is.
16
+ *
17
+ * What they make, and what the tool panel's tools made since (the tray), is this one's to attach. Each is a chip,
18
+ * which opens it; removing one takes it out of the tray. Once it's sent, they're gone from the tray, and the page's
19
+ * marks with them.
20
+ */
21
+ import { named, tell } from '#src/client/component.ts';
22
+ import { place, targetOf, toolButton } from '#src/client/dom.ts';
23
+ import { liveWaveform } from '#src/client/waveform.ts';
24
+ import type { ClientContext, LightboxItem, Point, Target } from '#src/index.ts';
25
+
26
+ // For `use()`'s types: the plugins may not be loaded, and nothing of them runs here.
27
+ import type { Annotation, Annotations, Picture } from '#src/plugins/annotations/index.ts';
28
+ import type { Recording } from '#src/plugins/recordings/index.ts';
29
+ import type { Shot } from '#src/plugins/screenshots/index.ts';
30
+ import type { Clip, Take } from '#src/plugins/voice/index.ts';
31
+
32
+ import type { Marks, Op } from './index.ts';
33
+
34
+ /** Scoped to the composer: the drawer and the Task tab share the overlay's root, and a field of theirs is their own. */
35
+ export const COMPOSER_STYLE = `
36
+ /* One box for what's attached, the words and the buttons, lit as a field is while it's typed in. */
37
+ .composer { border: 1px solid var(--deictic-line); border-radius: 12px; background: rgb(0 0 0 / 0.35); }
38
+ .composer:focus-within, .composer.dropping { border-color: var(--deictic-accent); box-shadow: 0 0 0 1px var(--deictic-accent); }
39
+ .composer textarea { display: block; box-sizing: border-box; width: 100%; min-height: 0; padding: 10px 12px 4px; border: 0; resize: none; background: none; font: 13px/1.45 system-ui, sans-serif; }
40
+ .composer textarea:focus { outline: none; }
41
+ .composer .chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 0; padding: 8px 8px 0; font-size: 12px; }
42
+ .composer .attach { display: flex; align-items: center; gap: 2px; padding: 4px 6px 6px; }
43
+ .composer .attach button.icon { width: 28px; height: 28px; border-radius: 8px; }
44
+ .composer .attach button.icon svg { width: 16px; height: 16px; }
45
+ .composer .attach button[aria-pressed='true'] { color: var(--deictic-accent); background: rgb(18 179 88 / 0.14); }
46
+ .composer .attach .gap { width: 1px; height: 16px; margin: 0 4px; background: var(--deictic-line); }
47
+ .composer .attach .mic[aria-pressed='true'], .composer .attach .mic[aria-pressed='true']:hover { color: #fff; background: #ef4444; }
48
+ .composer .hearing { display: inline-flex; align-items: center; gap: 6px; padding-left: 4px; font: 12px ui-monospace, monospace; color: var(--deictic-muted); }
49
+ .composer .hearing canvas { width: 56px; height: 18px; }
50
+ .composer .doing { margin-left: auto; padding-right: 6px; font-size: 12px; color: var(--deictic-muted); }
51
+ .composer .attach button.send { border-radius: 50%; color: var(--deictic-on-accent); }
52
+ .composer .attach button.send:hover:not(:disabled) { color: var(--deictic-on-accent); background: var(--deictic-accent); filter: brightness(1.1); }
53
+ .composer [hidden] { display: none; }
54
+ /* Every chip one height, and a picture's thumbnail one size whatever its shape or whether it has loaded yet: nothing
55
+ moves as one is attached, or as its picture comes. */
56
+ .chip { box-sizing: border-box; display: inline-flex; align-items: center; height: 30px; border: 1px solid var(--deictic-line); border-radius: 6px; }
57
+ .chip button { height: 100%; border: 0; }
58
+ .chip .open { display: inline-flex; align-items: center; gap: 6px; padding: 0 4px 0 2px; }
59
+ .chip img { display: block; width: 36px; height: 24px; object-fit: cover; border-radius: 4px; background: var(--deictic-line); }
60
+ .chip .play { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 4px; background: var(--deictic-line); }
61
+ .chip .play svg { width: 12px; height: 12px; }
62
+ .chip .play.drawn svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
63
+ .chip .remove { padding: 0 6px; color: var(--deictic-muted); }
64
+ .chip .remove:hover { color: var(--deictic-fg); }
65
+ /* An element the task is about: named as the caption names it, in the overlay's own green. */
66
+ .chip.about .open { padding: 0 4px 0 8px; font: 12px ui-monospace, monospace; color: var(--deictic-accent); }
67
+ .chip.about .open span { color: var(--deictic-muted); }
68
+ .compose .shot-problem { margin-top: 4px; font-size: 12px; color: var(--deictic-problem); }
69
+ .compose .shot-problem:empty { display: none; }
70
+ .compose .shot-note { margin-top: 4px; font-size: 12px; color: var(--deictic-muted); }
71
+ .compose .shot-note:empty { display: none; }
72
+ `;
73
+
74
+ export const PLAY = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z" fill="currentColor"/></svg>';
75
+ /** The composer's buttons, each its strokes on a 24-pixel grid. */
76
+ const CAMERA = '<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>';
77
+ const CODE = '<path d="M8 7l-5 5 5 5M16 7l5 5-5 5M13.5 5l-3 14"/>';
78
+ export const PEN = '<path d="M4 20l1-4L16 5a2.1 2.1 0 0 1 3 3L8 19z"/>';
79
+ const RECORD = '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3" fill="currentColor"/>';
80
+ const MIC = '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/>';
81
+ const SEND = '<path d="M12 19V5M6 11l6-6 6 6"/>';
82
+ const TARGET = '<circle cx="12" cy="12" r="7"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/>';
83
+ /** How tall the field grows with what's typed, in pixels, before it scrolls. */
84
+ const GROWN = 200;
85
+
86
+ /** The overlay's own green, as its ring on the element while the popup is open. */
87
+ const OUTLINE = '#12b358';
88
+ /** CSS pixels between the element and its outline, so the dashes are on nothing of the element's. */
89
+ const ROOM = 3;
90
+ /** How far around a spot its circle is drawn in a shot, in CSS pixels. */
91
+ const SPOT = 16;
92
+
93
+ /** The tray's kinds a composer attaches. */
94
+ const KINDS = ['screenshots', 'recordings', 'voice'];
95
+
96
+ export function element<K extends keyof HTMLElementTagNameMap>(
97
+ tag: K,
98
+ props: Partial<HTMLElementTagNameMap[K]> = {},
99
+ ): HTMLElementTagNameMap[K] {
100
+ return Object.assign(document.createElement(tag), props);
101
+ }
102
+
103
+ export const atOf = ({ loc }: Target) => `${loc.file}:${loc.line}:${loc.column}`;
104
+
105
+ export const clock = (ms: number) => {
106
+ const s = Math.round(ms / 1000);
107
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
108
+ };
109
+
110
+ export const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e));
111
+
112
+ /** Marks as a task tells of them: how many, and what the notes say. */
113
+ function marksOf(list: readonly Annotation[]): Marks {
114
+ return { count: list.length, notes: list.flatMap(({ shape }) => (shape.kind === 'note' ? [shape.text] : [])) };
115
+ }
116
+
117
+ /** The page's annotations, where there are any. */
118
+ function annotationsOf(marks: Annotations | undefined): Marks | undefined {
119
+ const list = marks?.list() ?? [];
120
+ return list.length === 0 ? undefined : marksOf(list);
121
+ }
122
+
123
+ /**
124
+ * A shot as the tray has it: the window's, from the tool panel, or one that was drawn on here. That one's PNG has the
125
+ * marks in it, and it keeps what it was made of, to draw on it again: the shot as taken, the marks, and the element it
126
+ * was taken of (`file:line:column`), as only a task about that element can say where the element is in it.
127
+ */
128
+ type Pictured = Shot & { drawn?: { shot: Shot; marks: Annotation[]; about: string } };
129
+
130
+ /** A shot as it's attached, and where it is, for the page to hear of; what's sent goes without that. */
131
+ export type Sent = NonNullable<Op['screenshots']>[number] & { url: string };
132
+
133
+ /** What a task says of an element that only the page with it on knows. */
134
+ export interface Seen extends Pick<Op, 'point' | 'pointed' | 'count' | 'chain'> {
135
+ /** The element's HTML, as it would be attached. */
136
+ html: string;
137
+ }
138
+
139
+ /**
140
+ * An element the task is about, a chip in the composer: its place, the element where this page has it, and what
141
+ * the page said of it as the panel left for a recording, for a page that no longer has it. `own` is the popup's.
142
+ */
143
+ export interface About {
144
+ target: Target;
145
+ own: boolean;
146
+ el?: Element;
147
+ seen?: Seen;
148
+ }
149
+
150
+ export const onPage = (a: About | undefined): Element | undefined => (a?.el?.isConnected === true ? a.el : undefined);
151
+
152
+ /** What's sent: the words, and all that's attached, as the composer has it. */
153
+ export interface Gathered {
154
+ text: string;
155
+ /** The elements attached, in order: none for a reply, or for a task about the page. */
156
+ about: About[];
157
+ /** Whether the elements' HTML goes too. */
158
+ html: boolean;
159
+ screenshots?: Sent[];
160
+ recordings: Recording[];
161
+ voices: Clip[];
162
+ /** What's drawn on the page, where something is. */
163
+ annotations?: Marks;
164
+ }
165
+
166
+ /** What's attached, as a task's op or a reply sends it: each shot, each recording with where it replays, each voice note, the marks. */
167
+ export function attachedOf({
168
+ screenshots,
169
+ recordings,
170
+ voices,
171
+ annotations,
172
+ }: Gathered): Pick<Op, 'screenshots' | 'recordings' | 'voice' | 'annotations'> {
173
+ return {
174
+ ...(screenshots === undefined ? {} : { screenshots: screenshots.map(({ url: _, ...shot }) => shot) }),
175
+ ...(recordings.length === 0
176
+ ? {}
177
+ : {
178
+ recordings: recordings.map(({ id, duration, url, voice: clips }) => ({
179
+ id,
180
+ duration,
181
+ replay: new URL(url, location.href).href,
182
+ ...(clips === undefined ? {} : { voice: clips.map((c) => c.id) }),
183
+ })),
184
+ }),
185
+ ...(voices.length === 0 ? {} : { voice: voices.map(({ id, duration }) => ({ id, duration })) }),
186
+ ...(annotations === undefined ? {} : { annotations }),
187
+ };
188
+ }
189
+
190
+ /** What's typed and asked for, to keep while the composer is away and give back to one made again. */
191
+ export interface Draft {
192
+ text: string;
193
+ /** Whether a shot was asked for, or asked not to be, where either was. */
194
+ shot?: boolean;
195
+ html: boolean;
196
+ about: About[];
197
+ }
198
+
199
+ export interface ComposerOptions {
200
+ placeholder: string;
201
+ /** What the arrow does, as its tooltip says: `Add task`, `Reply`. */
202
+ sendLabel: string;
203
+ /**
204
+ * The elements attached to begin with, and again once it's sent: a task's. With them come their chips, the element
205
+ * button and HTML snapshot; a reply has none of them.
206
+ */
207
+ about?: () => About[];
208
+ /** Whether the HTML snapshot button is there, for a task with elements: the tasks plugin's `html` option. */
209
+ html?: boolean;
210
+ /** The spot in the popup's own element, circled in a shot of it. */
211
+ at?: Point;
212
+ /** Whether a shot is taken as it's sent, while nothing else is attached and none was asked for or not: a task's. */
213
+ shoot?: boolean;
214
+ /** Whether this page has what's shot and drawn on: not for a task back from a recording on a page without it. */
215
+ here?: boolean;
216
+ /** Whether it's over the page, in the overlay's root: a press on the page picks an element, and attached ones are outlined. */
217
+ over: boolean;
218
+ /** What Record does, where it's there at all: the Task tab leaves the popup to record the page. */
219
+ record?: () => void;
220
+ /** Sends it; answers whether it's taken, which empties the composer. A refusal thrown is said under it. */
221
+ submit: (gathered: Gathered) => Promise<boolean>;
222
+ /** Hears a change to what leaving would lose: what's typed, or a take going. */
223
+ changed?: () => void;
224
+ }
225
+
226
+ export interface Composer {
227
+ /** The composer, and under it what went wrong and what was done. */
228
+ el: HTMLElement;
229
+ /** The arrow: what an unsaved change keeps a popup open with. */
230
+ send: HTMLButtonElement;
231
+ problem: HTMLElement;
232
+ note: HTMLElement;
233
+ /** Whether leaving now loses something: words typed, or a take going. */
234
+ pending: () => boolean;
235
+ draft: () => Draft;
236
+ restore: (draft: Partial<Draft>) => void;
237
+ /** Ends a take going, keeping its clip in the tray. */
238
+ stopTake: () => Promise<void>;
239
+ focus: () => void;
240
+ /** Lets it go: a take going is kept, in the tray. */
241
+ destroy: () => void;
242
+ }
243
+
244
+ /**
245
+ * A shot's PNG with what the task is about outlined in it: dashes around each box, with nothing between them, and a
246
+ * circle around `spot`. The shot may have more pixels than its size in CSS ones, which the boxes are in.
247
+ */
248
+ async function outlined(png: string, size: Shot['size'], boxes: Shot['box'][], spot?: Point): Promise<Blob> {
249
+ const image = new Image();
250
+ image.src = png;
251
+ await image.decode();
252
+ const canvas = element('canvas', { width: image.naturalWidth, height: image.naturalHeight });
253
+ const ctx = canvas.getContext('2d');
254
+ if (ctx === null) throw new Error("tasks: this browser won't draw to a canvas");
255
+ ctx.drawImage(image, 0, 0);
256
+ const k = image.naturalWidth / size.width;
257
+ ctx.lineWidth = 2 * k;
258
+ ctx.strokeStyle = OUTLINE;
259
+ ctx.setLineDash([6 * k, 4 * k]);
260
+ for (const box of boxes) ctx.strokeRect((box.x - ROOM) * k, (box.y - ROOM) * k, (box.width + 2 * ROOM) * k, (box.height + 2 * ROOM) * k);
261
+ if (spot !== undefined) {
262
+ ctx.beginPath();
263
+ ctx.arc(spot.x * k, spot.y * k, SPOT * k, 0, 2 * Math.PI);
264
+ ctx.stroke();
265
+ }
266
+ return await new Promise<Blob>((done, fail) =>
267
+ canvas.toBlob((blob) => (blob === null ? fail(new Error('tasks: the screenshot drew nothing')) : done(blob)), 'image/png'),
268
+ );
269
+ }
270
+
271
+ /** A picture as a PNG, and its size: the screenshots plugin keeps PNGs, and a pasted one may be a JPEG or a GIF. */
272
+ async function pngOf(picture: Blob): Promise<{ png: Blob; width: number; height: number }> {
273
+ const url = URL.createObjectURL(picture);
274
+ try {
275
+ const image = new Image();
276
+ image.src = url;
277
+ await image.decode();
278
+ const { naturalWidth: width, naturalHeight: height } = image;
279
+ if (picture.type === 'image/png') return { png: picture, width, height };
280
+ const canvas = element('canvas', { width, height });
281
+ const ctx = canvas.getContext('2d');
282
+ if (ctx === null) throw new Error("tasks: this browser won't draw to a canvas");
283
+ ctx.drawImage(image, 0, 0);
284
+ const png = await new Promise<Blob>((done, fail) =>
285
+ canvas.toBlob((blob) => (blob === null ? fail(new Error('tasks: the picture drew nothing')) : done(blob)), 'image/png'),
286
+ );
287
+ return { png, width, height };
288
+ } finally {
289
+ URL.revokeObjectURL(url);
290
+ }
291
+ }
292
+
293
+ export function composerIn(context: ClientContext, options: ComposerOptions): Composer {
294
+ const shots = context.use('screenshots');
295
+ const notes = context.use('annotations');
296
+ const recorder = context.use('recordings');
297
+ const voice = context.use('voice');
298
+ const { tray } = context;
299
+ const here = options.here ?? true;
300
+ const withElements = options.about !== undefined;
301
+
302
+ // What it's about, in the order attached.
303
+ let about: About[] = options.about?.() ?? [];
304
+
305
+ // A shot as it goes: said (on, or off), or else, where it's wanted at all, only while nothing else is attached.
306
+ let wanted: boolean | undefined;
307
+ const shooting = () => shots !== undefined && here && (wanted ?? (options.shoot === true && attachedCount() === 0));
308
+ let withHtml = true;
309
+
310
+ const text = element('textarea', { placeholder: options.placeholder, rows: 1 });
311
+ const chipsEl = element('div', { className: 'chips' });
312
+ const camera = toolButton(CAMERA, `Attach a screenshot, taken as it's sent`, undefined, () => {
313
+ wanted = !shooting();
314
+ showChips();
315
+ });
316
+ camera.hidden = shots === undefined || !here;
317
+ const code = toolButton(CODE, 'Attach an HTML snapshot: the element as the page has it now, as a file', undefined, () => {
318
+ withHtml = !withHtml;
319
+ showChips();
320
+ });
321
+ code.hidden = !withElements || options.html === false;
322
+ const picker = toolButton(TARGET, 'Attach another element: press it on the page', undefined, () => void pick());
323
+ picker.setAttribute('aria-pressed', 'false');
324
+ // Not where there's no page under it to press on.
325
+ picker.hidden = !withElements || !options.over;
326
+ const pen = toolButton(PEN, 'Draw on a screenshot', undefined, () => void draw());
327
+ pen.hidden = shots === undefined || notes === undefined || !here;
328
+ const record = toolButton(RECORD, 'Record the page', undefined, () => {
329
+ if (!sending) options.record?.();
330
+ });
331
+ record.hidden = recorder === undefined || options.record === undefined;
332
+ const mic = toolButton(MIC, 'Record your voice', undefined, () => void (take === undefined ? speakOn() : speakOff()));
333
+ mic.classList.add('mic');
334
+ mic.hidden = voice === undefined;
335
+ // Between what's on or off and what makes something, where there's some of both.
336
+ const gap = element('span', {
337
+ className: 'gap',
338
+ hidden: (camera.hidden && code.hidden) || (picker.hidden && pen.hidden && record.hidden && mic.hidden),
339
+ });
340
+ // The time and the mic's live waveform while a take goes, so it's plain it hears.
341
+ const time = element('span');
342
+ const wave = element('canvas');
343
+ const hearing = element('span', { className: 'hearing', hidden: true });
344
+ hearing.append(time, wave);
345
+ // What the arrow waits on, while it does: a shot being taken.
346
+ const doing = element('span', { className: 'doing' });
347
+ const send = toolButton(SEND, options.sendLabel, 'Enter', () => void sendIt());
348
+ send.classList.add('send', 'primary');
349
+ const attach = element('div', { className: 'attach' });
350
+ attach.append(camera, code, gap, picker, pen, record, mic, hearing, doing, send);
351
+ const box = element('div', { className: 'composer' });
352
+ box.append(chipsEl, text, attach);
353
+ const problem = element('div', { className: 'shot-problem' });
354
+ const note = element('div', { className: 'shot-note' });
355
+ const el = element('div', { className: 'compose' });
356
+ el.append(box, problem, note);
357
+ // As tall as what's typed, to a point.
358
+ const grow = () => {
359
+ text.style.height = 'auto';
360
+ text.style.height = `${Math.min(text.scrollHeight, GROWN)}px`;
361
+ };
362
+
363
+ // What the tool panel's tools made and nothing has taken: this one's to attach, as each plugin said it.
364
+ const inTray = <T>(plugin: string) => tray.list(plugin).map((item) => item.value as T);
365
+ const taken = () => ({
366
+ pictures: inTray<Pictured>('screenshots'),
367
+ recordings: inTray<Recording>('recordings'),
368
+ voices: inTray<Clip>('voice'),
369
+ });
370
+ const attachedCount = () => KINDS.reduce((n, plugin) => n + tray.list(plugin).length, 0);
371
+ // It goes with words, or with something attached that says it; not while it's going.
372
+ let sending = false;
373
+ let take: Take | undefined;
374
+ const able = () => (send.disabled = sending || (text.value.trim() === '' && attachedCount() === 0 && take === undefined));
375
+ const changed = () => options.changed?.();
376
+
377
+ const chip = (content: (string | Node)[], title: string, at: number, remove: string, drop: () => void) => {
378
+ const opener = element('button', { type: 'button', className: 'open', title });
379
+ opener.append(...content);
380
+ // Every attachment in one lightbox, opened at this one, growing out of its chip.
381
+ opener.addEventListener('click', () => context.lightbox(viewed(), { at, from: it }));
382
+ const remover = element('button', { type: 'button', className: 'remove', textContent: '×', title: remove });
383
+ remover.addEventListener('click', drop);
384
+ const it = element('span', { className: 'chip' });
385
+ it.append(opener, remover);
386
+ return it;
387
+ };
388
+ const numbered = (name: string, i: number, of: number) => (of === 1 ? name : `${name} ${i + 1}`);
389
+ /** What's attached, as the lightbox shows it, in the chips' order. */
390
+ const viewed = (): LightboxItem[] => {
391
+ const { pictures, recordings, voices } = taken();
392
+ return [
393
+ ...pictures.map((s, i) => ({
394
+ kind: 'image' as const,
395
+ url: s.url,
396
+ title: numbered('Screenshot', i, pictures.length),
397
+ ...(s.drawn === undefined
398
+ ? {}
399
+ : {
400
+ actions: [
401
+ s.drawn.marks.length === 0
402
+ ? { label: 'Draw on it', title: 'Draw boxes, arrows and notes on it', run: () => void draw(s) }
403
+ : { label: 'Change marks', title: 'Draw on it again', run: () => void draw(s) },
404
+ ],
405
+ }),
406
+ })),
407
+ ...recordings.map((r, i) => ({
408
+ kind: 'page' as const,
409
+ // The replay filling the frame, without a header of its own: the lightbox names it.
410
+ url: `${r.url}${r.url.includes('?') ? '&' : '?'}embed`,
411
+ title: `${numbered('Recording', i, recordings.length)} · ${clock(r.duration)}`,
412
+ actions: [
413
+ { label: 'New tab', title: 'Play it back in a tab of its own', run: () => void window.open(r.url, '_blank', 'noopener') },
414
+ ],
415
+ })),
416
+ ...voices.map((v, i) => ({
417
+ kind: 'audio' as const,
418
+ url: v.url,
419
+ title: `${numbered('Voice', i, voices.length)} · ${clock(v.duration)}`,
420
+ })),
421
+ ];
422
+ };
423
+ /** Takes one out of the tray. A shot that was the last thing attached leaves none asked for: taking it out said so. */
424
+ const drop = (plugin: string, id: string) => () => {
425
+ tray.remove(plugin, id);
426
+ if (plugin === 'screenshots' && attachedCount() === 0) wanted = false;
427
+ showChips();
428
+ };
429
+ /** An element the task is about: named as the caption names it, with its place for a tip. Its chip shows it, and its × leaves it out. */
430
+ const aboutChip = (a: About) => {
431
+ const it = onPage(a);
432
+ const { file, line } = a.target.loc;
433
+ const { component, sole, tag } = it === undefined ? { component: undefined, sole: false, tag: a.target.tag } : named(it);
434
+ const opener = element('button', { type: 'button', className: 'open', title: `${file}:${line}` });
435
+ opener.append(`<${component ?? tag}>`, ...(component === undefined || sole ? [] : [element('span', { textContent: ` <${tag}>` })]));
436
+ opener.addEventListener('click', () => it?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }));
437
+ const name = it === undefined ? `<${tag}>` : tell(named(it));
438
+ const remover = element('button', { type: 'button', className: 'remove', textContent: '×', title: `Leave ${name} out` });
439
+ remover.addEventListener('click', () => {
440
+ about = about.filter((x) => x !== a);
441
+ showChips();
442
+ });
443
+ const chipEl = element('span', { className: 'chip about' });
444
+ chipEl.append(opener, remover);
445
+ return chipEl;
446
+ };
447
+ /** What's drawn on the page, which goes with it: its chip draws more, and its × clears it. */
448
+ const marksChip = (marked: number) => {
449
+ const opener = element('button', { type: 'button', className: 'open', title: 'Draw more on the page' });
450
+ const icon = element('span', { className: 'play drawn', innerHTML: `<svg viewBox="0 0 24 24" aria-hidden="true">${PEN}</svg>` });
451
+ opener.append(icon, `${marked} mark${marked === 1 ? '' : 's'}`);
452
+ opener.addEventListener('click', () => notes?.draw());
453
+ const remover = element('button', { type: 'button', className: 'remove', textContent: '×', title: 'Clear the marks' });
454
+ remover.addEventListener('click', () => notes?.clear());
455
+ const it = element('span', { className: 'chip' });
456
+ it.append(opener, remover);
457
+ return it;
458
+ };
459
+ const showChips = () => {
460
+ const { pictures, recordings, voices } = taken();
461
+ const marked = notes?.list().length ?? 0;
462
+ camera.setAttribute('aria-pressed', String(shooting()));
463
+ code.setAttribute('aria-pressed', String(withHtml));
464
+ chipsEl.hidden = about.length === 0 && attachedCount() === 0 && marked === 0;
465
+ chipsEl.replaceChildren(
466
+ ...about.map(aboutChip),
467
+ ...pictures.map((s, i) => {
468
+ const name = numbered('Screenshot', i, pictures.length);
469
+ const thumb = element('img', { src: s.url, alt: '' });
470
+ return chip([thumb, name], `Open ${name.toLowerCase()}`, i, `Remove ${name.toLowerCase()}`, drop('screenshots', s.id));
471
+ }),
472
+ ...recordings.map((r, i) => {
473
+ const name = numbered('Recording', i, recordings.length);
474
+ const play = element('span', { className: 'play', innerHTML: PLAY });
475
+ return chip(
476
+ [play, `${name} ${clock(r.duration)}${r.voice === undefined ? '' : ' · voice'}`],
477
+ `Play ${name.toLowerCase()} back`,
478
+ pictures.length + i,
479
+ `Remove ${name.toLowerCase()}`,
480
+ drop('recordings', r.id),
481
+ );
482
+ }),
483
+ ...voices.map((v, i) => {
484
+ const name = numbered('Voice', i, voices.length);
485
+ const play = element('span', { className: 'play', innerHTML: PLAY });
486
+ return chip(
487
+ [play, `${name} ${clock(v.duration)}`],
488
+ `Play ${name.toLowerCase()}`,
489
+ pictures.length + recordings.length + i,
490
+ `Remove ${name.toLowerCase()}`,
491
+ drop('voice', v.id),
492
+ );
493
+ }),
494
+ ...(marked === 0 ? [] : [marksChip(marked)]),
495
+ );
496
+ able();
497
+ };
498
+ // As the tray changes: a shot taken from the panel while this is open is a chip at once. The marks too.
499
+ const unsubscribe = [tray.subscribe(showChips), notes?.subscribe(showChips)];
500
+
501
+ // The element button: the next press on the page attaches the marked element under it.
502
+ let picking = false;
503
+ const pick = async () => {
504
+ if (picking) return;
505
+ picking = true;
506
+ picker.setAttribute('aria-pressed', 'true');
507
+ const spot = await context.tools.pick();
508
+ picking = false;
509
+ picker.setAttribute('aria-pressed', 'false');
510
+ const target = spot === undefined ? undefined : targetOf(spot.element);
511
+ if (spot === undefined || target === undefined) return;
512
+ // Only what the press was on: the element nearest to a press on none isn't what was meant.
513
+ const r = spot.element.getBoundingClientRect();
514
+ if (spot.at.x < 0 || spot.at.y < 0 || spot.at.x > r.width || spot.at.y > r.height) return;
515
+ if (about.some((a) => a.el === spot.element)) return;
516
+ about = [...about, { target, own: false, el: spot.element }];
517
+ showChips();
518
+ };
519
+ // Each attached element on the page, outlined where it is, but the popup's own: that one has the light.
520
+ const outlines = withElements && options.over ? element('div') : undefined;
521
+ if (outlines !== undefined) context.root.append(outlines);
522
+ let following = 0;
523
+ const follow = () => {
524
+ following = requestAnimationFrame(follow);
525
+ if (outlines === undefined) return;
526
+ const others = about.flatMap((a) => (a.own || onPage(a) === undefined ? [] : [onPage(a)!]));
527
+ while (outlines.childElementCount > others.length) outlines.lastElementChild!.remove();
528
+ while (outlines.childElementCount < others.length) outlines.append(element('div', { className: 'task-about' }));
529
+ for (const [i, it] of others.entries()) place(outlines.children[i] as HTMLElement, it.getBoundingClientRect());
530
+ };
531
+ if (outlines !== undefined) follow();
532
+
533
+ // Draw: a shot is taken and opened to draw on, or a chip's opened again. Saved, the PNG of both is kept as a
534
+ // shot of its own, in the tray, so it's a chip as any other is.
535
+ const firstAt = () => (about[0] === undefined ? '' : atOf(about[0].target));
536
+ const aborts = new AbortController();
537
+ let drawing = false;
538
+ const draw = async (old?: Pictured) => {
539
+ if (shots === undefined || notes === undefined || drawing || sending) return;
540
+ drawing = true;
541
+ problem.textContent = '';
542
+ try {
543
+ if (old === undefined) doing.textContent = 'Capturing…';
544
+ const shot = old?.drawn?.shot ?? (await shots.capture(onPage(about[0]) ?? document.documentElement));
545
+ doing.textContent = '';
546
+ const picture: Picture = { url: shot.url, ...shot.size };
547
+ const marks = await notes.edit(picture, old?.drawn?.marks ?? [], { signal: aborts.signal });
548
+ if (marks === undefined) return;
549
+ doing.textContent = 'Saving…';
550
+ const kept = await shots.upload(await notes.flatten(picture, marks), shot);
551
+ if (old !== undefined) tray.remove('screenshots', old.id);
552
+ const pictured: Pictured = { ...kept, drawn: { shot, marks, about: old?.drawn?.about ?? firstAt() } };
553
+ tray.add('screenshots', kept.id, pictured);
554
+ } catch (e) {
555
+ problem.textContent = messageOf(e);
556
+ } finally {
557
+ doing.textContent = '';
558
+ drawing = false;
559
+ // Back to the words: the editor gave the focus to the button that opened it.
560
+ text.focus();
561
+ }
562
+ };
563
+
564
+ /**
565
+ * Pictures pasted in or dropped on it: each kept as a shot of its own (a PNG, as the screenshots plugin keeps them)
566
+ * and put in the tray, so it's a chip as any other is, to draw on. Anything else is said, not attached.
567
+ */
568
+ const paste = async (files: File[]) => {
569
+ const pictures = files.filter((file) => file.type.startsWith('image/'));
570
+ const others = files.length - pictures.length;
571
+ problem.textContent = '';
572
+ if (pictures.length > 0 && shots === undefined)
573
+ problem.textContent = 'Attaching a picture needs the screenshots plugin: add it to deictic';
574
+ else if (others > 0)
575
+ problem.textContent = `Only pictures can be attached here: ${others === 1 ? 'that file was' : `${others} files were`} left out`;
576
+ if (shots === undefined || pictures.length === 0) return;
577
+ doing.textContent = 'Attaching…';
578
+ try {
579
+ for (const picture of pictures) {
580
+ const { png, width, height } = await pngOf(picture);
581
+ const size = { width, height };
582
+ const kept = await shots.upload(png, { box: { x: 0, y: 0, ...size }, size });
583
+ // Drawn on with no marks yet: its lightbox offers to draw on it, as one drawn here does.
584
+ const pictured: Pictured = { ...kept, drawn: { shot: kept, marks: [], about: '' } };
585
+ tray.add('screenshots', kept.id, pictured);
586
+ }
587
+ } catch (e) {
588
+ problem.textContent = messageOf(e);
589
+ } finally {
590
+ doing.textContent = '';
591
+ }
592
+ };
593
+ box.addEventListener('paste', (e) => {
594
+ const files = [...(e.clipboardData?.files ?? [])];
595
+ if (files.length === 0) return;
596
+ // A picture isn't text: nothing goes in the field for it.
597
+ e.preventDefault();
598
+ void paste(files);
599
+ });
600
+ box.addEventListener('dragover', (e) => {
601
+ if (!e.dataTransfer?.types.includes('Files')) return;
602
+ e.preventDefault();
603
+ box.classList.add('dropping');
604
+ });
605
+ box.addEventListener('dragleave', () => box.classList.remove('dropping'));
606
+ box.addEventListener('drop', (e) => {
607
+ box.classList.remove('dropping');
608
+ const files = [...(e.dataTransfer?.files ?? [])];
609
+ if (files.length === 0) return;
610
+ e.preventDefault();
611
+ void paste(files);
612
+ });
613
+
614
+ // The mic, here: its button starts a take, and stops it, and it's a chip.
615
+ let ticking: ReturnType<typeof setInterval> | undefined;
616
+ let stopWave: (() => void) | undefined;
617
+ const speakOn = async () => {
618
+ if (voice === undefined) return;
619
+ problem.textContent = '';
620
+ mic.disabled = true;
621
+ try {
622
+ take = await voice.start();
623
+ } catch (e) {
624
+ problem.textContent = messageOf(e);
625
+ return;
626
+ } finally {
627
+ mic.disabled = false;
628
+ }
629
+ const { started, stream } = take;
630
+ stopWave = liveWaveform(wave, stream, { played: '#ef4444', rest: '#52525b' });
631
+ const tick = () => (time.textContent = clock(Date.now() - started));
632
+ tick();
633
+ ticking = setInterval(tick, 250);
634
+ hearing.hidden = false;
635
+ mic.setAttribute('aria-pressed', 'true');
636
+ mic.title = 'Stop, and attach it';
637
+ able();
638
+ changed();
639
+ };
640
+ const speakOff = async () => {
641
+ const ending = take;
642
+ if (ending === undefined) return;
643
+ take = undefined;
644
+ clearInterval(ticking);
645
+ stopWave?.();
646
+ stopWave = undefined;
647
+ hearing.hidden = true;
648
+ mic.setAttribute('aria-pressed', 'false');
649
+ mic.title = 'Record your voice';
650
+ try {
651
+ const clip = await ending.stop();
652
+ tray.add('voice', clip.id, clip);
653
+ } catch (e) {
654
+ problem.textContent = messageOf(e);
655
+ }
656
+ able();
657
+ changed();
658
+ };
659
+
660
+ /**
661
+ * The shots to attach: one taken now, where that's on, and those in the tray, each the window as it was taken.
662
+ * Only the first has the elements outlined in it, and its spot circled (or is as it was taken, where that can't be
663
+ * drawn), so it's first: nothing else in a shot says what it's about.
664
+ */
665
+ const screenshotsOf = async (): Promise<Sent[] | undefined> => {
666
+ if (shots === undefined) return undefined;
667
+ // One drawn on says its notes, and where the element is in it, where it's the first one it was taken of.
668
+ const kept: Sent[] = taken().pictures.map(({ id, url, drawn }) => ({
669
+ id,
670
+ url,
671
+ ...(drawn !== undefined && drawn.about !== '' && drawn.about === firstAt() ? { box: drawn.shot.box } : {}),
672
+ ...(drawn === undefined || drawn.marks.length === 0 ? {} : { marks: marksOf(drawn.marks) }),
673
+ }));
674
+ if (!shooting()) return kept.length === 0 ? undefined : kept;
675
+ doing.textContent = 'Capturing…';
676
+ // Of the first element, which the shot then says the place of; of the page, with none on it.
677
+ const first = onPage(about[0]);
678
+ const of = first ?? document.documentElement;
679
+ const now = await shots.capture(of);
680
+ const where = first === undefined ? {} : { box: now.box };
681
+ // The others as the page has them, moved by as much as the shot has the first off where the page has it.
682
+ const live = of.getBoundingClientRect();
683
+ const boxes = about.flatMap((a) => {
684
+ const it = onPage(a);
685
+ if (it === undefined) return [];
686
+ if (it === first) return a.own && options.at !== undefined ? [] : [now.box];
687
+ const r = it.getBoundingClientRect();
688
+ return [{ x: r.left + now.box.x - live.left, y: r.top + now.box.y - live.top, width: r.width, height: r.height }];
689
+ });
690
+ const spot = first !== undefined && about[0]?.own === true ? options.at : undefined;
691
+ const circled = spot === undefined ? undefined : { x: now.box.x + spot.x, y: now.box.y + spot.y };
692
+ if (boxes.length === 0 && circled === undefined) return [{ id: now.id, url: now.url }, ...kept];
693
+ try {
694
+ const { id, url } = await shots.upload(await outlined(now.url, now.size, boxes, circled), now);
695
+ return [{ id, url, ...where, outlined: true }, ...kept];
696
+ } catch {
697
+ return [{ id: now.id, url: now.url, ...where }, ...kept];
698
+ }
699
+ };
700
+
701
+ const sendIt = async () => {
702
+ if (sending) return;
703
+ sending = true;
704
+ // A take still going is kept first: it may be all there is to send.
705
+ await speakOff();
706
+ if (text.value.trim() === '' && attachedCount() === 0) {
707
+ sending = false;
708
+ able();
709
+ return;
710
+ }
711
+ able();
712
+ problem.textContent = '';
713
+ note.textContent = '';
714
+ let screenshots: Sent[] | undefined;
715
+ try {
716
+ screenshots = await screenshotsOf();
717
+ } catch (e) {
718
+ // Said under the field, which stays as it is: turn the screenshot off to send without.
719
+ problem.textContent = messageOf(e);
720
+ doing.textContent = '';
721
+ sending = false;
722
+ able();
723
+ return;
724
+ }
725
+ doing.textContent = '';
726
+ const { recordings, voices } = taken();
727
+ const annotations = annotationsOf(notes);
728
+ let done = false;
729
+ try {
730
+ done = await options.submit({
731
+ text: text.value,
732
+ about,
733
+ html: withHtml,
734
+ ...(screenshots === undefined ? {} : { screenshots }),
735
+ recordings,
736
+ voices,
737
+ ...(annotations === undefined ? {} : { annotations }),
738
+ });
739
+ } catch (e) {
740
+ problem.textContent = messageOf(e);
741
+ }
742
+ if (done) {
743
+ text.value = '';
744
+ grow();
745
+ // It has them now: what was made for it, and what was drawn on the page for it.
746
+ for (const plugin of KINDS) tray.remove(plugin);
747
+ notes?.clear();
748
+ wanted = undefined;
749
+ about = options.about?.() ?? [];
750
+ showChips();
751
+ changed();
752
+ }
753
+ sending = false;
754
+ able();
755
+ };
756
+
757
+ text.addEventListener('input', () => {
758
+ grow();
759
+ able();
760
+ changed();
761
+ });
762
+ // Enter sends, as a chat's field does; Shift+Enter is a new line. Not while an IME is composing a word.
763
+ text.addEventListener('keydown', (e) => {
764
+ if (e.key !== 'Enter' || e.shiftKey || e.isComposing) return;
765
+ e.preventDefault();
766
+ void sendIt();
767
+ });
768
+ showChips();
769
+ requestAnimationFrame(grow);
770
+
771
+ return {
772
+ el,
773
+ send,
774
+ problem,
775
+ note,
776
+ pending: () => text.value.trim() !== '' || take !== undefined,
777
+ draft: () => ({ text: text.value, ...(wanted === undefined ? {} : { shot: wanted }), html: withHtml, about }),
778
+ restore: (draft) => {
779
+ if (draft.text !== undefined) text.value = draft.text;
780
+ if (draft.shot !== undefined) wanted = draft.shot;
781
+ if (draft.html !== undefined) withHtml = draft.html;
782
+ if (draft.about !== undefined) about = draft.about;
783
+ showChips();
784
+ grow();
785
+ },
786
+ stopTake: speakOff,
787
+ focus: () => text.focus(),
788
+ destroy: () => {
789
+ for (const stop of unsubscribe) stop?.();
790
+ aborts.abort();
791
+ cancelAnimationFrame(following);
792
+ outlines?.remove();
793
+ // A take it closes on is kept, in the tray: the next one's.
794
+ void speakOff();
795
+ },
796
+ };
797
+ }