deictic 0.0.1 → 0.1.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -0
  3. package/dist/annotations/client.d.ts +4 -0
  4. package/dist/annotations/client.d.ts.map +1 -0
  5. package/dist/annotations/client.js +497 -0
  6. package/dist/annotations/client.js.map +1 -0
  7. package/dist/annotations/index.d.ts +110 -0
  8. package/dist/annotations/index.d.ts.map +1 -0
  9. package/dist/annotations/index.js +22 -0
  10. package/dist/annotations/index.js.map +1 -0
  11. package/dist/astro.d.ts +29 -0
  12. package/dist/astro.d.ts.map +1 -0
  13. package/dist/astro.js +24 -0
  14. package/dist/astro.js.map +1 -0
  15. package/dist/bun.d.ts +12 -0
  16. package/dist/bun.d.ts.map +1 -0
  17. package/dist/bun.js +67 -0
  18. package/dist/bun.js.map +1 -0
  19. package/dist/client/index.d.ts +93 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1329 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/endpoints.js +354 -0
  24. package/dist/endpoints.js.map +1 -0
  25. package/dist/index.d.ts +220 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +10 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/index2.d.ts +23 -0
  30. package/dist/index3.d.ts +98 -0
  31. package/dist/index3.d.ts.map +1 -0
  32. package/dist/index4.d.ts +74 -0
  33. package/dist/index4.d.ts.map +1 -0
  34. package/dist/index5.d.ts +70 -0
  35. package/dist/index5.d.ts.map +1 -0
  36. package/dist/integration.d.ts +19 -0
  37. package/dist/integration.d.ts.map +1 -0
  38. package/dist/integration.js +277 -0
  39. package/dist/integration.js.map +1 -0
  40. package/dist/kept.js +23 -0
  41. package/dist/kept.js.map +1 -0
  42. package/dist/loader.d.ts +15 -0
  43. package/dist/loader.d.ts.map +1 -0
  44. package/dist/loader.js +17 -0
  45. package/dist/loader.js.map +1 -0
  46. package/dist/marks.js +14 -0
  47. package/dist/marks.js.map +1 -0
  48. package/dist/next.d.ts +17 -0
  49. package/dist/next.d.ts.map +1 -0
  50. package/dist/next.js +150 -0
  51. package/dist/next.js.map +1 -0
  52. package/dist/playwright.js +105 -0
  53. package/dist/playwright.js.map +1 -0
  54. package/dist/recommended/index.d.ts +25 -0
  55. package/dist/recommended/index.d.ts.map +1 -0
  56. package/dist/recommended/index.js +19 -0
  57. package/dist/recommended/index.js.map +1 -0
  58. package/dist/recordings/client.d.ts +4 -0
  59. package/dist/recordings/client.d.ts.map +1 -0
  60. package/dist/recordings/client.js +376 -0
  61. package/dist/recordings/client.js.map +1 -0
  62. package/dist/recordings/index.d.ts +2 -0
  63. package/dist/recordings/index.js +3 -0
  64. package/dist/recordings.js +235 -0
  65. package/dist/recordings.js.map +1 -0
  66. package/dist/screenshots/client.d.ts +23 -0
  67. package/dist/screenshots/client.d.ts.map +1 -0
  68. package/dist/screenshots/client.js +76 -0
  69. package/dist/screenshots/client.js.map +1 -0
  70. package/dist/screenshots/dom.d.ts +4 -0
  71. package/dist/screenshots/dom.d.ts.map +1 -0
  72. package/dist/screenshots/dom.js +92 -0
  73. package/dist/screenshots/dom.js.map +1 -0
  74. package/dist/screenshots/index.d.ts +2 -0
  75. package/dist/screenshots/index.js +98 -0
  76. package/dist/screenshots/index.js.map +1 -0
  77. package/dist/screenshots/rrweb.d.ts +9 -0
  78. package/dist/screenshots/rrweb.d.ts.map +1 -0
  79. package/dist/screenshots/rrweb.js +60 -0
  80. package/dist/screenshots/rrweb.js.map +1 -0
  81. package/dist/shortcut.js +63 -0
  82. package/dist/shortcut.js.map +1 -0
  83. package/dist/tailwind/client.d.ts +4 -0
  84. package/dist/tailwind/client.d.ts.map +1 -0
  85. package/dist/tailwind/client.js +613 -0
  86. package/dist/tailwind/client.js.map +1 -0
  87. package/dist/tailwind/index.d.ts +2 -0
  88. package/dist/tailwind/index.js +557 -0
  89. package/dist/tailwind/index.js.map +1 -0
  90. package/dist/tasks/client.d.ts +6 -0
  91. package/dist/tasks/client.d.ts.map +1 -0
  92. package/dist/tasks/client.js +642 -0
  93. package/dist/tasks/client.js.map +1 -0
  94. package/dist/tasks/index.d.ts +159 -0
  95. package/dist/tasks/index.d.ts.map +1 -0
  96. package/dist/tasks/index.js +348 -0
  97. package/dist/tasks/index.js.map +1 -0
  98. package/dist/vite.d.ts +17 -0
  99. package/dist/vite.d.ts.map +1 -0
  100. package/dist/vite.js +44 -0
  101. package/dist/vite.js.map +1 -0
  102. package/dist/voice/client.d.ts +4 -0
  103. package/dist/voice/client.d.ts.map +1 -0
  104. package/dist/voice/client.js +66 -0
  105. package/dist/voice/client.js.map +1 -0
  106. package/dist/voice/index.d.ts +47 -0
  107. package/dist/voice/index.d.ts.map +1 -0
  108. package/dist/voice/index.js +74 -0
  109. package/dist/voice/index.js.map +1 -0
  110. package/dist/waveform.js +93 -0
  111. package/dist/waveform.js.map +1 -0
  112. package/dist/webpack.d.ts +50 -0
  113. package/dist/webpack.d.ts.map +1 -0
  114. package/dist/webpack.js +78 -0
  115. package/dist/webpack.js.map +1 -0
  116. package/package.json +307 -7
  117. package/skills/deictic/SKILL.md +47 -0
  118. package/skills/deictic/references/install.md +81 -0
  119. package/skills/deictic/references/recordings.md +83 -0
  120. package/skills/deictic/references/tasks.md +79 -0
  121. package/skills/deictic/references/watch.md +43 -0
  122. package/skills/deictic/scripts/frame.mjs +62 -0
  123. package/skills/deictic/scripts/lib.mjs +193 -0
  124. package/skills/deictic/scripts/recording.mjs +186 -0
  125. package/skills/deictic/scripts/task.mjs +84 -0
  126. package/skills/deictic/scripts/transcribe.mjs +93 -0
  127. package/skills/deictic/scripts/voice.mjs +50 -0
  128. package/skills/deictic/scripts/watch.mjs +51 -0
  129. package/src/astro.ts +34 -0
  130. package/src/bun.ts +79 -0
  131. package/src/client/index.ts +833 -0
  132. package/src/client/lightbox.ts +256 -0
  133. package/src/client/style.ts +243 -0
  134. package/src/client/tooltip.ts +78 -0
  135. package/src/client/waveform.ts +98 -0
  136. package/src/index.ts +240 -0
  137. package/src/loader.ts +28 -0
  138. package/src/next.ts +133 -0
  139. package/src/plugins/annotations/client.ts +301 -0
  140. package/src/plugins/annotations/draw.ts +169 -0
  141. package/src/plugins/annotations/index.ts +105 -0
  142. package/src/plugins/annotations/svg.ts +61 -0
  143. package/src/plugins/recommended/index.ts +35 -0
  144. package/src/plugins/recordings/client.ts +315 -0
  145. package/src/plugins/recordings/index.ts +174 -0
  146. package/src/plugins/recordings/marks.ts +11 -0
  147. package/src/plugins/recordings/ours.ts +70 -0
  148. package/src/plugins/recordings/replay.ts +139 -0
  149. package/src/plugins/screenshots/client.ts +63 -0
  150. package/src/plugins/screenshots/dom.ts +79 -0
  151. package/src/plugins/screenshots/index.ts +194 -0
  152. package/src/plugins/screenshots/playwright.ts +119 -0
  153. package/src/plugins/screenshots/rrweb.ts +45 -0
  154. package/src/plugins/tailwind/catalog.ts +396 -0
  155. package/src/plugins/tailwind/client.ts +669 -0
  156. package/src/plugins/tailwind/index.ts +267 -0
  157. package/src/plugins/tasks/client.ts +622 -0
  158. package/src/plugins/tasks/index.ts +513 -0
  159. package/src/plugins/voice/client.ts +57 -0
  160. package/src/plugins/voice/index.ts +114 -0
  161. package/src/shortcut.ts +83 -0
  162. package/src/tools/astro.ts +81 -0
  163. package/src/tools/editor.ts +22 -0
  164. package/src/tools/endpoints.ts +163 -0
  165. package/src/tools/history.ts +203 -0
  166. package/src/tools/integration.ts +106 -0
  167. package/src/tools/kept.ts +21 -0
  168. package/src/tools/locate.ts +94 -0
  169. package/src/tools/plugins.ts +41 -0
  170. package/src/tools/source.ts +72 -0
  171. package/src/vite.ts +62 -0
  172. package/src/webpack.ts +107 -0
  173. package/index.js +0 -1
@@ -0,0 +1,833 @@
1
+ /**
2
+ * `deictic/client`: the overlay the page loads in dev. Hold a shortcut's keys (Alt, deictic's own,
3
+ * by default) and point: the element under the pointer that the source marked (`tools/locate.ts`) is
4
+ * outlined, with its tag, its place and how many elements share it. Press the shortcut's button to open
5
+ * the popup there: a tab for each plugin with a panel, at the one used last, or at a plugin's own where
6
+ * its shortcut was pressed.
7
+ *
8
+ * Everything drawn sits in one shadow root, so neither the page's styles nor ours cross over. A
9
+ * panel's undo and redo are its tab's on its element: the latest change that plugin made there.
10
+ */
11
+ import type { ClientContext, ClientPlugin, LightboxItem, PanelContext, Resumed, Target } from '#src/index.ts';
12
+ import { gestureOf, type Shortcut } from '#src/shortcut.ts';
13
+
14
+ import { openLightbox } from './lightbox.ts';
15
+ import { STYLE } from './style.ts';
16
+ import { tooltips } from './tooltip.ts';
17
+
18
+ // For a plugin's page half that records the mic, or shows a clip: the waveforms the lightbox draws.
19
+ export { drawBars, liveWaveform, peaksOf, type Colors } from './waveform.ts';
20
+
21
+ export interface StartOptions {
22
+ /** The dev server's base URL, ending in `/`. */
23
+ base: string;
24
+ /** deictic's own shortcut, checked: it opens the popup at the tab used last. None where it's turned off. */
25
+ shortcut?: Required<Shortcut>;
26
+ /** Each plugin with a half in the page, and its own shortcut as the bundler's plugin checked it, where it has one. */
27
+ plugins: { plugin: ClientPlugin; shortcut?: Required<Shortcut>; options?: unknown }[];
28
+ }
29
+
30
+ type Mount = (panel: HTMLElement, context: PanelContext<unknown, unknown>) => (() => void) | void;
31
+
32
+ /** A plugin with a panel: a tab in the popup. */
33
+ interface Tab {
34
+ plugin: ClientPlugin;
35
+ mount: Mount;
36
+ }
37
+
38
+ const ATTRIBUTE = 'data-deictic';
39
+ /** An arrow pointing up and out: the link leaves the page for the editor. */
40
+ const OUT = icon('M7 17 17 7M8 7h9v9', 2.25);
41
+ // Drawn, as the arrows and the cross of a system's font differ in size and weight from one to the next.
42
+ const UNDO = icon('M9 14 4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11');
43
+ const REDO = icon('m15 14 5-5-5-5M20 9H9.5a5.5 5.5 0 0 0 0 11H13');
44
+ const CLOSE = icon('M18 6 6 18M6 6l12 12');
45
+ /** Where the tab used last is kept, for deictic's own shortcut to open it again. */
46
+ const LAST = 'deictic:tab';
47
+ /** How long a read may take, in milliseconds, before the popup says it's reading. */
48
+ const SLOW = 200;
49
+ const STARTED = Symbol.for('deictic');
50
+
51
+ export function targetOf(el: Element): Target | undefined {
52
+ const at = el.getAttribute(ATTRIBUTE);
53
+ const match = at === null ? null : /^(.*):(\d+):(\d+)$/.exec(at);
54
+ if (match === null) return undefined;
55
+ return { loc: { file: match[1]!, line: Number(match[2]), column: Number(match[3]) }, tag: el.localName };
56
+ }
57
+
58
+ const sameAs = (el: Element) => [...document.querySelectorAll(`[${ATTRIBUTE}="${CSS.escape(el.getAttribute(ATTRIBUTE) ?? '')}"]`)];
59
+
60
+ /** The nearest marked element around `el`, out through shadow roots to their hosts. */
61
+ function markedAround(el: Element): Element | undefined {
62
+ for (let at: Element | undefined = el; at !== undefined;) {
63
+ const marked = at.closest(`[${ATTRIBUTE}]`);
64
+ if (marked !== null) return marked;
65
+ const root = at.getRootNode();
66
+ at = root instanceof ShadowRoot ? root.host : undefined;
67
+ }
68
+ return undefined;
69
+ }
70
+
71
+ /** `div.panel > button.tab`: the element as a selector, the deepest classes only, for a person to tell it by. */
72
+ function icon(path: string, width = 2): string {
73
+ return `<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="${width}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${path}"/></svg>`;
74
+ }
75
+
76
+ const nameOf = (el: Element) => `${el.localName}${[...el.classList].map((c) => `.${c}`).join('')}`;
77
+
78
+ /** What the overlay keeps once started, for `popupIn` to show the popup with. */
79
+ interface Started {
80
+ base: string;
81
+ contextOf: (name: string) => ClientContext;
82
+ tabs: Tab[];
83
+ /** Opens the popup over the page on an element, at a tab or the one used last: `openPopup`. */
84
+ open: (element: Element, tab?: string) => boolean;
85
+ }
86
+
87
+ let started: Started | undefined;
88
+
89
+ /**
90
+ * What the page hears on `window` as the popup opens over it on an element (its `detail` a `PopupOpened`) and as
91
+ * it closes: for a page that moves on its own to hold still meanwhile, as deictic's site does. Not for one pinned.
92
+ */
93
+ export const POPUP_OPENED = 'deictic:open';
94
+ export const POPUP_CLOSED = 'deictic:close';
95
+
96
+ export interface PopupOpened {
97
+ /** The element it's open on. */
98
+ element: Element;
99
+ /** The plugin whose tab it opened at. */
100
+ tab: string;
101
+ }
102
+
103
+ /**
104
+ * Opens the popup over the page on `element`, as deictic's own shortcut does: at `tab` (a plugin's name), or at the
105
+ * tab used last. For a page that opens it from a gesture of its own, as deictic's site does on a plain click.
106
+ * Answers whether it opened: not where no plugin has a tab, or `element` has no mark. The overlay must have started.
107
+ */
108
+ export function openPopup(element: Element, { tab }: { tab?: string } = {}): boolean {
109
+ if (started === undefined) throw new Error('deictic: the overlay has not started, so there is no popup to open');
110
+ return started.open(element, tab);
111
+ }
112
+
113
+ /**
114
+ * Shows the popup in `container`, open at a tab (`tab`, a plugin's name, or the first) on `element`, where
115
+ * the page puts it rather than over the page: a page of the popup's states, to point at and fix, as deictic's
116
+ * own site does. It's the real popup, its tabs and plugins working. Closing it, or a tab's `away`, opens it
117
+ * again in place. It draws in `container`'s shadow root, made if there isn't one. Answers what removes it.
118
+ * The overlay must have started (the dev server's client module starts it), and `element` be marked.
119
+ */
120
+ export function popupIn(container: Element, { tab: name, element }: { tab?: string; element: Element }): () => void {
121
+ if (started === undefined) throw new Error('deictic: the overlay has not started, so there is no popup to show');
122
+ const target = targetOf(element);
123
+ if (target === undefined) throw new Error(`deictic: ${nameOf(element)} has no ${ATTRIBUTE} mark to open the popup on`);
124
+ const { base, contextOf, tabs } = started;
125
+ // A tab shown here isn't one a person chose: the popup over the page keeps opening at theirs.
126
+ const remember = () => {};
127
+ const tab = tabs.find((t) => t.plugin.name === name) ?? tabs[0];
128
+ if (tab === undefined) throw new Error('deictic: no plugin has a tab to show');
129
+ const root = container.shadowRoot ?? container.attachShadow({ mode: 'open' });
130
+ const style = document.createElement('style');
131
+ style.textContent = `${STYLE}:host { display: block; }`;
132
+ root.replaceChildren(style);
133
+ tooltips(root);
134
+ let panel: { close: () => void } | undefined;
135
+ let gone = false;
136
+ const open = (at: Tab, resumed?: Resumed) => {
137
+ panel = openPanel({
138
+ base,
139
+ root,
140
+ contextOf,
141
+ tabs,
142
+ tab: at,
143
+ remember,
144
+ element,
145
+ target,
146
+ pinned: true,
147
+ onClose: (shown, leaving) => {
148
+ panel = undefined;
149
+ // Closed by its own × or Esc: open again, as the page is there to show it. Leaving for `away` comes back by `reopen`.
150
+ if (!gone && !leaving) open(shown);
151
+ },
152
+ ...(resumed === undefined ? {} : { resumed }),
153
+ reopen: (again, _, kept) => open(again, kept),
154
+ });
155
+ };
156
+ open(tab);
157
+ return () => {
158
+ gone = true;
159
+ panel?.close();
160
+ style.remove();
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Shows the lightbox in `container`, at `at`, where the page puts it rather than over everything: as `popupIn`
166
+ * does the popup, for a page of deictic's own states. Its items step with its arrows; there's no backdrop, close
167
+ * or keys, and an item's actions run without closing it. Answers what removes it.
168
+ */
169
+ export function lightboxIn(container: Element, items: LightboxItem[], { at }: { at?: number } = {}): () => void {
170
+ const root = container.shadowRoot ?? container.attachShadow({ mode: 'open' });
171
+ const style = document.createElement('style');
172
+ style.textContent = `${STYLE}:host { display: block; }`;
173
+ root.replaceChildren(style);
174
+ tooltips(root);
175
+ const { close } = openLightbox(root, items, { ...(at === undefined ? {} : { at }), pinned: true });
176
+ return () => {
177
+ close();
178
+ style.remove();
179
+ };
180
+ }
181
+
182
+ /** Starts the overlay, once per page: the client module runs again when a module importing it is replaced. */
183
+ export function start({ base, shortcut: own, plugins: given }: StartOptions): void {
184
+ const page = globalThis as { [STARTED]?: true };
185
+ if (page[STARTED] === true) return;
186
+ page[STARTED] = true;
187
+
188
+ const host = document.createElement('deictic-overlay');
189
+ const root = host.attachShadow({ mode: 'open' });
190
+ const style = document.createElement('style');
191
+ style.textContent = STYLE;
192
+ const box = div('box');
193
+ const label = div('label');
194
+ box.append(label);
195
+ // What's under the pointer, outlined inside the marked element around it when they differ.
196
+ const inner = div('box inner');
197
+ root.append(style, box, inner);
198
+ tooltips(root);
199
+ // What's typed in the popup is the popup's: the page hears a key from in here as one on the host, not in a field,
200
+ // so its own shortcuts (a "/" to search, a "j" to step) would run on a task's words. Ours listen while capturing.
201
+ for (const type of ['keydown', 'keypress', 'keyup'] as const) host.addEventListener(type, (e) => e.stopPropagation());
202
+ document.documentElement.append(host);
203
+
204
+ // Each plugin's API, set up before any panel opens. `use` reads it when asked, so a setup may keep
205
+ // `use` for later, not call it: the plugin it asks for may not be set up yet.
206
+ const apis = new Map<string, unknown>();
207
+ const optionsOf = new Map(given.map(({ plugin, options }) => [plugin.name, options]));
208
+ const contextOf = (name: string): ClientContext => ({
209
+ base,
210
+ root,
211
+ options: optionsOf.get(name),
212
+ use: (other) => apis.get(other) as never,
213
+ request: (route, init) => fetch(`${base}__deictic/plugins/${name}/${route}`, init),
214
+ open: (plugin, element) => openAt(plugin, element),
215
+ lightbox: (items, options) => openLightbox(root, items, options),
216
+ });
217
+ for (const { plugin } of given) {
218
+ if (plugin.setup === undefined) continue;
219
+ try {
220
+ apis.set(plugin.name, plugin.setup(contextOf(plugin.name)));
221
+ } catch (e) {
222
+ // One plugin's failure is no reason to take the others down with it.
223
+ console.error(`deictic: ${plugin.name} failed to set up`, e);
224
+ }
225
+ }
226
+ const tabs: Tab[] = given.flatMap(({ plugin }) => (plugin.mount === undefined ? [] : [{ plugin, mount: plugin.mount }]));
227
+ started = {
228
+ base,
229
+ contextOf,
230
+ tabs,
231
+ // Not over a popup holding something unsaved: the press that asked shook its button (`openPanel`).
232
+ open: (element, tab) => tabs.length > 0 && panel?.unsaved() !== true && openAt(tab ?? last().plugin.name, element),
233
+ };
234
+ const last = () => {
235
+ let name: string | null = null;
236
+ try {
237
+ name = localStorage.getItem(LAST);
238
+ } catch {
239
+ // Storage can be off: the first tab, then.
240
+ }
241
+ return tabs.find((t) => t.plugin.name === name) ?? tabs[0]!;
242
+ };
243
+ const remember = (tab: Tab) => {
244
+ try {
245
+ localStorage.setItem(LAST, tab.plugin.name);
246
+ } catch {
247
+ // Not kept, then: the next open starts at the first tab.
248
+ }
249
+ };
250
+ // What opens the popup, and at which tab: deictic's own shortcut at the one used last, each
251
+ // plugin's at its own.
252
+ const plugins = [
253
+ ...(own === undefined || tabs.length === 0 ? [] : [{ shortcut: own, gesture: gestureOf(own), tab: last }]),
254
+ ...given.flatMap(({ plugin, shortcut }) => {
255
+ if (shortcut === undefined) return [];
256
+ const tab = tabs.find((t) => t.plugin === plugin);
257
+ if (tab !== undefined) return [{ shortcut, gesture: gestureOf(shortcut), tab: () => tab }];
258
+ console.error(`deictic: ${plugin.name} has a shortcut, but its page half has no \`mount\` to draw a tab with`);
259
+ return [];
260
+ }),
261
+ ];
262
+
263
+ let pointer: { x: number; y: number } | undefined;
264
+ let frame = 0;
265
+ let panel: { close: () => void; unsaved: () => boolean } | undefined;
266
+
267
+ /** The plugins whose keys are held: several, where they share keys and differ by button. */
268
+ const heldBy = (e: MouseEvent | KeyboardEvent) => plugins.filter((p) => p.gesture.held(e));
269
+ /** The plugin a press opens. */
270
+ const pressedBy = (e: MouseEvent) => plugins.find((p) => p.gesture.held(e) && e.button === p.gesture.button);
271
+ /**
272
+ * The marked element at a point, and what's under the pointer inside it where that differs: down through
273
+ * open shadow roots but the overlay's own, as a page showing the popup (`popupIn`) has it in one.
274
+ */
275
+ const hitAt = (x: number, y: number) => {
276
+ let under = document.elementFromPoint(x, y) ?? undefined;
277
+ while (under !== undefined && under !== host && under.shadowRoot !== null) {
278
+ const inside = under.shadowRoot.elementFromPoint(x, y);
279
+ if (inside === null || inside === under) break;
280
+ under = inside;
281
+ }
282
+ const el = under === undefined || under === host ? undefined : markedAround(under);
283
+ return el === undefined ? undefined : { el, pointed: under === el ? undefined : under };
284
+ };
285
+ const hide = () => {
286
+ box.classList.remove('shown');
287
+ inner.classList.remove('shown');
288
+ };
289
+ const show = (held: typeof plugins) => {
290
+ frame = 0;
291
+ const hit = pointer === undefined ? undefined : hitAt(pointer.x, pointer.y);
292
+ const el = hit?.el;
293
+ const target = el === undefined ? undefined : targetOf(el);
294
+ if (el === undefined || target === undefined) return hide();
295
+ place(box, el.getBoundingClientRect());
296
+ if (hit?.pointed === undefined) {
297
+ inner.classList.remove('shown');
298
+ } else {
299
+ place(inner, hit.pointed.getBoundingClientRect());
300
+ inner.classList.add('shown');
301
+ }
302
+ const count = sameAs(el).length;
303
+ // The button, where it isn't the left: what the keys alone don't tell apart.
304
+ const names = held.map(({ tab, shortcut }) => {
305
+ const { plugin } = tab();
306
+ const name = plugin.label ?? plugin.name;
307
+ return shortcut.button === 'left' ? name : `${name} (${shortcut.button})`;
308
+ });
309
+ const within = hit?.pointed === undefined ? '' : ` › ${nameOf(hit.pointed)}`;
310
+ label.textContent = `${names.join(' / ')} · <${target.tag}> ${target.loc.file}:${target.loc.line}${count > 1 ? ` · ×${count}` : ''}${within}`;
311
+ label.classList.toggle('below', el.getBoundingClientRect().top < 24);
312
+ box.classList.add('shown');
313
+ };
314
+ const update = (e: MouseEvent | KeyboardEvent) => {
315
+ const held = heldBy(e);
316
+ if (held.length === 0) return hide();
317
+ if (frame === 0) frame = requestAnimationFrame(() => show(held));
318
+ };
319
+
320
+ window.addEventListener(
321
+ 'mousemove',
322
+ (e) => {
323
+ pointer = { x: e.clientX, y: e.clientY };
324
+ update(e);
325
+ },
326
+ { capture: true, passive: true },
327
+ );
328
+ window.addEventListener('keydown', update, true);
329
+ window.addEventListener('keyup', update, true);
330
+ window.addEventListener('blur', hide);
331
+ let press = {};
332
+ let opened: object | undefined;
333
+ // Alt-click on a link would otherwise download it, and on a field focus it.
334
+ window.addEventListener(
335
+ 'mousedown',
336
+ (e) => {
337
+ press = {};
338
+ if (e.composedPath().includes(host)) return;
339
+ if (pressedBy(e) !== undefined && hitAt(e.clientX, e.clientY) !== undefined) e.preventDefault();
340
+ },
341
+ true,
342
+ );
343
+ // A press ends in `click`, `auxclick` or `contextmenu` by its button, and a right one in two of
344
+ // them, in an order that varies by platform; on macOS Control-click is a left `contextmenu`. Each
345
+ // is kept from the page, and the first opens the panel.
346
+ const pressed = (e: MouseEvent) => {
347
+ if (e.composedPath().includes(host)) return;
348
+ const found = pressedBy(e);
349
+ const hit = found === undefined ? undefined : hitAt(e.clientX, e.clientY);
350
+ const target = hit === undefined ? undefined : targetOf(hit.el);
351
+ if (found === undefined || hit === undefined || target === undefined) return;
352
+ e.preventDefault();
353
+ e.stopPropagation();
354
+ if (opened === press) return;
355
+ opened = press;
356
+ // Still open after this press's pointerdown, outside it: it holds something unsaved, and shook its button.
357
+ if (panel?.unsaved() === true) return;
358
+ openTab(found.tab(), hit.el, target, undefined, hit.pointed);
359
+ };
360
+ const openTab = (tab: Tab, el: Element, target: Target, resumed?: Resumed, pointed?: Element) => {
361
+ hide();
362
+ panel?.close();
363
+ panel = openPanel({
364
+ base,
365
+ root,
366
+ contextOf,
367
+ tabs,
368
+ tab,
369
+ remember,
370
+ element: el,
371
+ ...(pointed === undefined ? {} : { pointed }),
372
+ target,
373
+ onClose: () => (panel = undefined),
374
+ ...(resumed === undefined ? {} : { resumed }),
375
+ reopen: (again, element, kept) => {
376
+ const found = element.isConnected ? element : sameAs(element)[0];
377
+ const at = found === undefined ? undefined : targetOf(found);
378
+ // Gone from the page while away: there's nothing to come back to.
379
+ if (found === undefined || at === undefined)
380
+ return console.warn('deictic: the element is no longer on the page, so the popup stays closed');
381
+ openTab(again, found, at, kept, pointed?.isConnected === true && found === element ? pointed : undefined);
382
+ },
383
+ });
384
+ };
385
+ function openAt(name: string, given: Element): boolean {
386
+ const tab = tabs.find((t) => t.plugin.name === name);
387
+ const el = given.isConnected ? given : (sameAs(given)[0] ?? undefined);
388
+ const target = el === undefined ? undefined : targetOf(el);
389
+ if (tab === undefined || el === undefined || target === undefined) return false;
390
+ openTab(tab, el, target);
391
+ return true;
392
+ }
393
+ for (const type of ['click', 'auxclick', 'contextmenu'] as const) window.addEventListener(type, pressed, true);
394
+ }
395
+
396
+ interface PanelOptions {
397
+ base: string;
398
+ root: ShadowRoot;
399
+ contextOf: (name: string) => ClientContext;
400
+ tabs: Tab[];
401
+ /** The tab it opens at. */
402
+ tab: Tab;
403
+ /** Keeps the tab shown, for deictic's own shortcut to open at next. */
404
+ remember: (tab: Tab) => void;
405
+ element: Element;
406
+ /** What was under the pointer inside `element`, where that differs. */
407
+ pointed?: Element;
408
+ target: Target;
409
+ /** Shown where the page put it (`popupIn`), not over the page beside the element; Esc leaves it alone. */
410
+ pinned?: boolean;
411
+ /** Called as it closes: the tab it showed, and whether it's leaving for a tab's `away`, to come back by `reopen`. */
412
+ onClose: (shown: Tab, leaving: boolean) => void;
413
+ /** What the first tab's mount gets, coming back from `away`. */
414
+ resumed?: Resumed;
415
+ /** Opens the popup again, at a tab on an element, coming back from `away`. */
416
+ reopen: (tab: Tab, element: Element, resumed: Resumed) => void;
417
+ }
418
+
419
+ function openPanel({
420
+ base,
421
+ root,
422
+ contextOf,
423
+ tabs,
424
+ tab: first,
425
+ remember,
426
+ element,
427
+ pointed,
428
+ target,
429
+ pinned = false,
430
+ onClose,
431
+ resumed: coming,
432
+ reopen,
433
+ }: PanelOptions): { close: () => void; unsaved: () => boolean } {
434
+ // Given to the first tab's first mount only: another tab, or a remount after an undo, starts afresh.
435
+ let resumed = coming;
436
+ const panel = div('panel');
437
+ // The tabs, then the element's place and undo and redo, which are the shown tab's on this element.
438
+ const head = div('head');
439
+ head.setAttribute('role', 'tablist');
440
+ const bar = div('bar');
441
+ const where = document.createElement('a');
442
+ where.className = 'where';
443
+ const file = document.createElement('span');
444
+ file.textContent = `${target.loc.file}:${target.loc.line}`;
445
+ // An arrow out, as it leaves the page for the editor; its title is the overlay's tooltip (`tooltip.ts`).
446
+ where.append(file);
447
+ where.insertAdjacentHTML('beforeend', OUT);
448
+ where.title = 'Open in editor';
449
+ where.setAttribute('aria-label', `Open ${file.textContent} in the editor`);
450
+ // The element's place, as a request's query names it.
451
+ const at = { file: target.loc.file, line: String(target.loc.line), column: String(target.loc.column) };
452
+ where.href = `${base}__deictic/open?${new URLSearchParams(at)}`;
453
+ where.addEventListener('click', (e) => {
454
+ e.preventDefault();
455
+ void fetch(where.href);
456
+ });
457
+ // Off until the tab's history is read: there's nothing to take back on most elements.
458
+ const undo = iconButton(UNDO, 'Undo', 'Nothing to undo');
459
+ const redo = iconButton(REDO, 'Redo', 'Nothing to redo');
460
+ undo.disabled = redo.disabled = true;
461
+ const close = iconButton(CLOSE, 'Close', pinned ? 'Close' : 'Close (Esc)');
462
+ const buttons = tabs.map((tab) => {
463
+ const el = button(tab.plugin.label ?? tab.plugin.name, '');
464
+ el.className = 'tab';
465
+ el.setAttribute('role', 'tab');
466
+ el.addEventListener('click', () => show(tab));
467
+ return { tab, el };
468
+ });
469
+ close.classList.add('close');
470
+ head.append(...buttons.map((b) => b.el), close);
471
+ bar.append(where, undo, redo);
472
+ const body = div('body');
473
+ body.setAttribute('role', 'tabpanel');
474
+ const status = div('status');
475
+ panel.append(head, bar, body, status);
476
+ root.append(panel);
477
+ if (pinned) panel.classList.add('pinned');
478
+ const release = pinned ? undefined : keepInView(panel, body, head, element);
479
+ const unmark = pinned ? undefined : outline(root, element);
480
+ if (!pinned) window.dispatchEvent(new CustomEvent<PopupOpened>(POPUP_OPENED, { detail: { element, tab: first.plugin.name } }));
481
+
482
+ let cleanup: (() => void) | void;
483
+ // The button that keeps what the shown tab would lose, while there's something: `unsaved`, from the panel.
484
+ let holding: HTMLElement | undefined;
485
+ const say = (text: string, problem = false) => {
486
+ status.textContent = text;
487
+ status.classList.toggle('problem', problem);
488
+ };
489
+ const post = async <T>(route: string, body?: unknown): Promise<T> => {
490
+ const res = await fetch(`${base}__deictic/${route}`, {
491
+ method: 'POST',
492
+ headers: { 'content-type': 'application/json' },
493
+ body: JSON.stringify(body ?? {}),
494
+ });
495
+ const json = (await res.json()) as T & { problem?: string };
496
+ if (!res.ok) throw new Error(json.problem ?? res.statusText);
497
+ return json;
498
+ };
499
+ const unmount = () => {
500
+ cleanup?.();
501
+ cleanup = undefined;
502
+ holding = undefined;
503
+ body.replaceChildren();
504
+ };
505
+ // The change undone may be this tab's from before the panel opened: the panel reads its model again.
506
+ const step = (route: 'undo' | 'redo') =>
507
+ post<{ change: { label: string } }>(route, { plugin: current.plugin.name, target })
508
+ .then(
509
+ async ({ change }) => {
510
+ await load();
511
+ say(`${route === 'undo' ? 'Undid' : 'Redid'} ${change.label}`);
512
+ },
513
+ (e: unknown) => say(messageOf(e), true),
514
+ )
515
+ .finally(() => void steps());
516
+ // Undo and redo as the tab's history on this element stands: off with nothing to take back or do again, else
517
+ // saying what they would. Read as a tab shows, after each change made here, and as the pointer comes back, for a
518
+ // change made elsewhere. One a later read overtook (another tab's) sets nothing.
519
+ let asked = 0;
520
+ const steps = async () => {
521
+ const ask = ++asked;
522
+ let history: { done: { label: string }[]; undone: { label: string }[] };
523
+ try {
524
+ const res = await fetch(`${base}__deictic/history?${new URLSearchParams({ plugin: current.plugin.name, ...at })}`);
525
+ if (!res.ok || ask !== asked) return;
526
+ history = (await res.json()) as typeof history;
527
+ } catch {
528
+ return;
529
+ }
530
+ const last = history.done.at(-1);
531
+ const next = history.undone.at(-1);
532
+ undo.disabled = last === undefined;
533
+ undo.title = last === undefined ? 'Nothing to undo' : `Undo ${last.label}`;
534
+ redo.disabled = next === undefined;
535
+ redo.title = next === undefined ? 'Nothing to redo' : `Redo ${next.label}`;
536
+ };
537
+ panel.addEventListener('pointerenter', () => void steps());
538
+
539
+ const done = (leaving = false) => {
540
+ unmount();
541
+ release?.();
542
+ unmark?.();
543
+ panel.remove();
544
+ window.removeEventListener('keydown', onKey, true);
545
+ window.removeEventListener('pointerdown', onOutside, true);
546
+ if (!pinned) window.dispatchEvent(new CustomEvent(POPUP_CLOSED));
547
+ onClose(current, leaving);
548
+ };
549
+ const onKey = (e: KeyboardEvent) => {
550
+ // A plugin's modal over the popup (one marked `data-deictic-modal`) takes Esc for itself.
551
+ if (e.key !== 'Escape' || root.querySelector('[data-deictic-modal]') !== null) return;
552
+ // Esc is the popup's while it's open: a dialog of the page's that it's open in stays open.
553
+ e.preventDefault();
554
+ e.stopPropagation();
555
+ done();
556
+ };
557
+ // A press on the page closes the popup, as it would a menu, unless that loses something: then the button that
558
+ // keeps it shakes. Anything in the overlay is the popup's own: a modal, the lightbox, the surface marks are drawn on.
559
+ const onOutside = (e: PointerEvent) => {
560
+ if (e.composedPath().includes(root.host)) return;
561
+ if (holding === undefined) return done();
562
+ shake(holding);
563
+ };
564
+ if (!pinned) {
565
+ window.addEventListener('keydown', onKey, true);
566
+ window.addEventListener('pointerdown', onOutside, true);
567
+ }
568
+ undo.addEventListener('click', () => void step('undo'));
569
+ redo.addEventListener('click', () => void step('redo'));
570
+ close.addEventListener('click', () => done());
571
+
572
+ let current = first;
573
+ // A read that a later one overtook (another tab, or the same after an undo) mounts nothing.
574
+ let reads = 0;
575
+ const load = async () => {
576
+ const { plugin, mount } = current;
577
+ const read = ++reads;
578
+ // The body keeps its height while it's empty, and "Reading…" waits for a read that takes long: one answered
579
+ // at once, as most are, would otherwise fold the popup and open it again in a blink.
580
+ body.style.minHeight = `${body.offsetHeight}px`;
581
+ unmount();
582
+ say('');
583
+ const slow = setTimeout(() => read === reads && say('Reading…'), SLOW);
584
+ let model: unknown;
585
+ try {
586
+ ({ model } = await post<{ model: unknown }>('read', { plugin: plugin.name, target }));
587
+ } catch (e) {
588
+ if (read !== reads) return;
589
+ body.style.minHeight = '';
590
+ say(messageOf(e), true);
591
+ return;
592
+ } finally {
593
+ clearTimeout(slow);
594
+ }
595
+ if (read !== reads) return;
596
+ body.style.minHeight = '';
597
+ say('');
598
+ const back = current === first ? resumed : undefined;
599
+ resumed = undefined;
600
+ cleanup = mount(body, {
601
+ ...contextOf(plugin.name),
602
+ ...(back === undefined ? {} : { resumed: back }),
603
+ away: (state, task) => {
604
+ const tab = current;
605
+ done(true);
606
+ void task().then(
607
+ (result) => reopen(tab, element, { state, result }),
608
+ (e: unknown) => reopen(tab, element, { state, problem: messageOf(e) }),
609
+ );
610
+ },
611
+ element,
612
+ ...(pointed === undefined ? {} : { pointed }),
613
+ elements: sameAs(element),
614
+ target,
615
+ model,
616
+ apply: async (op) => {
617
+ say('Writing…');
618
+ try {
619
+ const result = await post<{ model: unknown }>('apply', { plugin: plugin.name, target, op });
620
+ say('');
621
+ void steps();
622
+ return result.model;
623
+ } catch (e) {
624
+ say(messageOf(e), true);
625
+ throw e;
626
+ }
627
+ },
628
+ close: () => done(),
629
+ unsaved: (action) => {
630
+ if (read === reads) holding = action;
631
+ },
632
+ });
633
+ };
634
+ const show = (tab: Tab) => {
635
+ current = tab;
636
+ for (const b of buttons) b.el.setAttribute('aria-selected', String(b.tab === tab));
637
+ remember(tab);
638
+ void steps();
639
+ void load();
640
+ };
641
+ show(first);
642
+ return { close: done, unsaved: () => holding !== undefined };
643
+ }
644
+
645
+ /** Shakes a panel's button, in view: what a press outside does where closing would lose something. A blink where motion is reduced. */
646
+ function shake(el: HTMLElement): void {
647
+ el.scrollIntoView({ block: 'nearest' });
648
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return void el.animate({ opacity: [1, 0.3, 1, 0.3, 1] }, 400);
649
+ el.animate({ translate: ['0', '-5px', '5px', '-4px', '4px', '-2px', '0'] }, { duration: 360, easing: 'ease-out' });
650
+ }
651
+
652
+ /** Puts an outline over `r`. */
653
+ function place(el: HTMLElement, r: DOMRect): void {
654
+ Object.assign(el.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
655
+ }
656
+
657
+ /** How far from the element the popup's outline is drawn, in pixels. */
658
+ const ROOM = 4;
659
+
660
+ /**
661
+ * Outlines the element the popup is open on, for as long as it is: which one it's about, where several look alike
662
+ * or the popup covers it. Dashed, with no fill and a little room around the element, so nothing of it is drawn on:
663
+ * a border, a ring or a colour tried on it shows as it is. Read each frame, as the element moves with the page's
664
+ * scrolling, its layout and what a panel previews on it. Answers what removes it.
665
+ */
666
+ function outline(root: ShadowRoot, element: Element): () => void {
667
+ const box = div('box on');
668
+ root.append(box);
669
+ let frame = 0;
670
+ let was = '';
671
+ const follow = () => {
672
+ frame = requestAnimationFrame(follow);
673
+ const r = element.getBoundingClientRect();
674
+ const now = element.isConnected ? `${r.left},${r.top},${r.width},${r.height}` : '';
675
+ if (now === was) return;
676
+ was = now;
677
+ box.classList.toggle('shown', now !== '');
678
+ place(box, new DOMRect(r.left - ROOM, r.top - ROOM, r.width + 2 * ROOM, r.height + 2 * ROOM));
679
+ };
680
+ follow();
681
+ return () => {
682
+ cancelAnimationFrame(frame);
683
+ box.remove();
684
+ };
685
+ }
686
+
687
+ const MARGIN = 8;
688
+ // Under this much room on either side, the panel overlaps the element rather than shrink to a sliver beside it.
689
+ const LEAST = 160;
690
+
691
+ /** How far a press on the head moves, in pixels, before it's a drag: a click there leaves the popup following. */
692
+ const SLACK = 3;
693
+
694
+ /**
695
+ * Keeps a panel beside `element` and inside the viewport, as its tabs fill it, the window resizes and the element
696
+ * moves with the page: below, or above where it fits better, its height capped to the room there, so the body
697
+ * scrolls rather than the panel leaving the window. Dragged by `handle`, it stays where it's put, in the window,
698
+ * and follows the element no more. Fixed, so it never changes the page's own scrolling. Answers a release.
699
+ */
700
+ function keepInView(panel: HTMLElement, body: HTMLElement, handle: HTMLElement, element: Element): () => void {
701
+ let frame = 0;
702
+ let timer: ReturnType<typeof setTimeout> | undefined;
703
+ // Where the element was last seen: one gone from the page leaves the popup where it was.
704
+ let r = element.getBoundingClientRect();
705
+ let moved: { left: number; top: number } | undefined;
706
+ const fit = () => {
707
+ cancelAnimationFrame(frame);
708
+ clearTimeout(timer);
709
+ frame = 0;
710
+ timer = undefined;
711
+ // The viewport without the page's scrollbars.
712
+ const width = document.documentElement.clientWidth;
713
+ const height = document.documentElement.clientHeight;
714
+ // What the panel would take with no cap: its frame, and all of its body.
715
+ const wanted = panel.offsetHeight - body.clientHeight + body.scrollHeight;
716
+ if (moved !== undefined) {
717
+ const room = Math.max(0, height - 2 * MARGIN);
718
+ Object.assign(panel.style, {
719
+ left: `${Math.max(MARGIN, Math.min(moved.left, width - MARGIN - panel.offsetWidth))}px`,
720
+ top: `${Math.max(MARGIN, Math.min(moved.top, height - MARGIN - Math.min(wanted, room)))}px`,
721
+ maxHeight: `${room}px`,
722
+ });
723
+ return;
724
+ }
725
+ const top = Math.min(Math.max(r.top, 0), height);
726
+ const bottom = Math.min(Math.max(r.bottom, 0), height);
727
+ const below = height - bottom - 2 * MARGIN;
728
+ const above = top - 2 * MARGIN;
729
+ const cap = Math.max(0, Math.min(height * 0.6, height - 2 * MARGIN));
730
+ let at: number;
731
+ let room: number;
732
+ if (Math.max(below, above) < LEAST) {
733
+ room = height - 2 * MARGIN;
734
+ at = Math.min(Math.max(bottom + MARGIN, MARGIN), height - MARGIN - Math.min(wanted, room));
735
+ } else if (wanted <= below || below >= above) {
736
+ room = Math.min(below, cap);
737
+ at = bottom + MARGIN;
738
+ } else {
739
+ room = Math.min(above, cap);
740
+ at = top - MARGIN - Math.min(wanted, room);
741
+ }
742
+ Object.assign(panel.style, {
743
+ left: `${Math.max(MARGIN, Math.min(r.left, width - MARGIN - panel.offsetWidth))}px`,
744
+ top: `${at}px`,
745
+ bottom: '',
746
+ maxHeight: `${room}px`,
747
+ });
748
+ };
749
+ // Not in the observers' callbacks, where a change of size is a "ResizeObserver loop" error on the page. The next
750
+ // frame, or a moment later where there's none: a hidden tab draws no frames, and its popup still fits when shown.
751
+ const later = () => {
752
+ frame ||= requestAnimationFrame(fit);
753
+ timer ??= setTimeout(fit, 50);
754
+ };
755
+ fit();
756
+ // Read each frame, as nothing tells of an element moving: the page scrolls, its layout shifts, a panel previews.
757
+ let watching = requestAnimationFrame(function watch() {
758
+ if (moved !== undefined) return;
759
+ watching = requestAnimationFrame(watch);
760
+ if (!element.isConnected) return;
761
+ const now = element.getBoundingClientRect();
762
+ if (now.left === r.left && now.top === r.top && now.width === r.width && now.height === r.height) return;
763
+ r = now;
764
+ fit();
765
+ });
766
+ // A drag starts on the head itself, not on a tab or the close in it.
767
+ let from: { x: number; y: number; left: number; top: number } | undefined;
768
+ const down = (e: PointerEvent) => {
769
+ if (e.button !== 0 || (e.target as Element).closest('button') !== null) return;
770
+ // Kept from the browser: no text selected along the way, and the field being typed in keeps its focus.
771
+ e.preventDefault();
772
+ const at = panel.getBoundingClientRect();
773
+ from = { x: e.clientX, y: e.clientY, left: at.left, top: at.top };
774
+ handle.setPointerCapture(e.pointerId);
775
+ };
776
+ const move = (e: PointerEvent) => {
777
+ if (from === undefined) return;
778
+ const x = e.clientX - from.x;
779
+ const y = e.clientY - from.y;
780
+ if (moved === undefined && Math.hypot(x, y) < SLACK) return;
781
+ moved = { left: from.left + x, top: from.top + y };
782
+ panel.classList.add('dragging');
783
+ fit();
784
+ };
785
+ const up = () => {
786
+ from = undefined;
787
+ panel.classList.remove('dragging');
788
+ };
789
+ handle.addEventListener('pointerdown', down);
790
+ handle.addEventListener('pointermove', move);
791
+ handle.addEventListener('pointerup', up);
792
+ handle.addEventListener('pointercancel', up);
793
+ // A tab's content arrives after the panel opens, and changes as it's used, as does the status line. Both, as a
794
+ // resize observer reports only while the page renders: a hidden tab's popup would keep its first place.
795
+ const resized = new ResizeObserver(later);
796
+ resized.observe(panel);
797
+ const changed = new MutationObserver(later);
798
+ changed.observe(panel, { childList: true, subtree: true, characterData: true });
799
+ window.addEventListener('resize', later);
800
+ return () => {
801
+ cancelAnimationFrame(frame);
802
+ cancelAnimationFrame(watching);
803
+ clearTimeout(timer);
804
+ resized.disconnect();
805
+ changed.disconnect();
806
+ window.removeEventListener('resize', later);
807
+ };
808
+ }
809
+
810
+ function div(className: string): HTMLDivElement {
811
+ const el = document.createElement('div');
812
+ el.className = className;
813
+ return el;
814
+ }
815
+
816
+ /** A button that is a drawing: named for what it does, as its title, the tooltip, changes with what it would do. */
817
+ function iconButton(svg: string, name: string, title: string): HTMLButtonElement {
818
+ const el = button('', title);
819
+ el.className = 'icon';
820
+ el.innerHTML = svg;
821
+ el.setAttribute('aria-label', name);
822
+ return el;
823
+ }
824
+
825
+ function button(text: string, title: string): HTMLButtonElement {
826
+ const el = document.createElement('button');
827
+ el.type = 'button';
828
+ el.textContent = text;
829
+ el.title = title;
830
+ return el;
831
+ }
832
+
833
+ const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e));