@arraypress/extension-kit 1.10.0 → 1.11.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 (68) hide show
  1. package/README.md +97 -20
  2. package/bin/extension-kit.js +2 -1
  3. package/package.json +1 -1
  4. package/src/ai/host.d.ts +183 -0
  5. package/src/ai/host.js +225 -0
  6. package/src/ai/model.d.ts +2 -1
  7. package/src/ai/model.js +10 -2
  8. package/src/build/vendor.d.ts +29 -8
  9. package/src/build/vendor.js +136 -40
  10. package/src/content/highlight.d.ts +15 -6
  11. package/src/content/highlight.js +42 -17
  12. package/src/content/overlay.d.ts +19 -4
  13. package/src/content/overlay.js +44 -6
  14. package/src/content/slices.d.ts +3 -1
  15. package/src/content/slices.js +29 -14
  16. package/src/content/watch.d.ts +4 -2
  17. package/src/content/watch.js +17 -3
  18. package/src/dom/focus.d.ts +11 -0
  19. package/src/dom/focus.js +15 -0
  20. package/src/frame/window.d.ts +1 -1
  21. package/src/frame/window.js +8 -7
  22. package/src/index.d.ts +10 -3
  23. package/src/index.js +8 -3
  24. package/src/panel/show-on-page.d.ts +82 -0
  25. package/src/panel/show-on-page.js +83 -0
  26. package/src/scripting/call.d.ts +29 -9
  27. package/src/scripting/call.js +35 -11
  28. package/src/scripting/context-menus.d.ts +45 -0
  29. package/src/scripting/context-menus.js +53 -0
  30. package/src/scripting/registration.d.ts +2 -1
  31. package/src/scripting/registration.js +2 -1
  32. package/src/scripting/tab.d.ts +17 -5
  33. package/src/scripting/tab.js +15 -7
  34. package/src/settings/saver.js +16 -6
  35. package/src/settings/storage.d.ts +33 -2
  36. package/src/settings/storage.js +73 -3
  37. package/src/settings/store.d.ts +17 -0
  38. package/src/settings/store.js +87 -20
  39. package/src/sites/sites.d.ts +6 -1
  40. package/src/sites/sites.js +20 -3
  41. package/src/styles/chrome-ui.css +56 -30
  42. package/src/testing/e2e.d.ts +35 -4
  43. package/src/testing/e2e.js +67 -5
  44. package/src/testing/fake-model.d.ts +9 -1
  45. package/src/testing/fake-model.js +44 -23
  46. package/src/testing/fake-storage.d.ts +41 -13
  47. package/src/testing/fake-storage.js +163 -51
  48. package/src/testing/index.d.ts +3 -3
  49. package/src/testing/index.js +5 -3
  50. package/src/testing/live-run.d.ts +23 -2
  51. package/src/testing/live-run.js +64 -18
  52. package/src/testing/messages.d.ts +7 -3
  53. package/src/testing/messages.js +50 -9
  54. package/src/testing/package.d.ts +56 -7
  55. package/src/testing/package.js +57 -18
  56. package/src/testing/prompt.d.ts +4 -2
  57. package/src/testing/prompt.js +7 -3
  58. package/src/time/pool.d.ts +2 -1
  59. package/src/time/pool.js +4 -2
  60. package/src/toolbar/theme.d.ts +10 -2
  61. package/src/toolbar/theme.js +12 -4
  62. package/src/ui/menu.d.ts +13 -3
  63. package/src/ui/menu.js +31 -11
  64. package/src/ui/model-row.js +5 -1
  65. package/src/ui/site-list.js +12 -3
  66. package/src/ui/text-dialog.d.ts +3 -2
  67. package/src/ui/text-dialog.js +10 -3
  68. package/src/ui/toast.js +2 -0
package/src/ai/model.d.ts CHANGED
@@ -9,7 +9,8 @@
9
9
  * only downloads from a user gesture) and which reports progress;
10
10
  * - one base session, with the instructions and examples, is made once and
11
11
  * kept; each question goes to a `clone()` of it, so answers don't leak into
12
- * each other;
12
+ * each other; a base session Chrome has let go since (it can't be cloned)
13
+ * is made again;
13
14
  * - each answer has a time limit: an `AbortSignal` stops the answer once
14
15
  * it's late, and the caller gets a reason instead of a hang;
15
16
  * - the first session after Chrome starts can take ~18 s while the model
package/src/ai/model.js CHANGED
@@ -9,7 +9,8 @@
9
9
  * only downloads from a user gesture) and which reports progress;
10
10
  * - one base session, with the instructions and examples, is made once and
11
11
  * kept; each question goes to a `clone()` of it, so answers don't leak into
12
- * each other;
12
+ * each other; a base session Chrome has let go since (it can't be cloned)
13
+ * is made again;
13
14
  * - each answer has a time limit: an `AbortSignal` stops the answer once
14
15
  * it's late, and the caller gets a reason instead of a hang;
15
16
  * - the first session after Chrome starts can take ~18 s while the model
@@ -265,7 +266,14 @@ export function createModelSession({ model, options, initialPrompts = [] }) {
265
266
  * @returns {Promise<string>} The answer.
266
267
  */
267
268
  async function ask(api, prompt, signal, responseConstraint) {
268
- const session = await (await baseSession(api)).clone({ signal });
269
+ const made = baseSession(api);
270
+ const kept = await made;
271
+ const session = await kept.clone({ signal }).catch(async (error) => {
272
+ if (signal.aborted) throw error;
273
+ // Chrome let the base session go (the model was updated, or its process ended): a new one, once.
274
+ if (base === made) base = null;
275
+ return (await baseSession(api)).clone({ signal });
276
+ });
269
277
  try {
270
278
  return await session.prompt(prompt, { signal, ...(responseConstraint && { responseConstraint }) });
271
279
  } finally {
@@ -5,11 +5,13 @@
5
5
  * `extension/vendor/`; the copy is made from the installed package on
6
6
  * `npm install` (`postinstall`) and is never committed.
7
7
  *
8
- * Each copy is stamped with the package's name and version
9
- * ({@link VENDOR_STAMP}), so {@link checkVendored} can say when a copy no
10
- * longer matches what's installed: `npm install some-package` installs
11
- * without running the extension's own `postinstall`, and the copy goes stale
12
- * without a word.
8
+ * Each copy is stamped with the package's name and version, what was copied
9
+ * and a hash of it ({@link VENDOR_STAMP}), so {@link checkVendored} can say
10
+ * when a copy no longer matches what's installed: `npm install some-package`
11
+ * installs without running the extension's own `postinstall`, and the copy
12
+ * goes stale without a word; so does a copy edited by hand, or a package
13
+ * whose files changed under the same version (a library copied into
14
+ * `node_modules` to try it before it's published).
13
15
  *
14
16
  * An extension with a bundler imports the package instead and copies only
15
17
  * the stylesheet ({@link STYLESHEET}).
@@ -31,6 +33,14 @@ export type VendorStamp = {
31
33
  * Its version when copied.
32
34
  */
33
35
  version: string;
36
+ /**
37
+ * The paths copied, as {@link vendorPackage} took them (the kit's own copy has none).
38
+ */
39
+ files?: string[];
40
+ /**
41
+ * A hash of every file copied ({@link treeHash}); a copy from before 1.11 has none.
42
+ */
43
+ hash?: string;
34
44
  };
35
45
  /**
36
46
  * Where a vendored copy came from.
@@ -38,6 +48,8 @@ export type VendorStamp = {
38
48
  * @typedef {object} VendorStamp
39
49
  * @property {string} package The package's name.
40
50
  * @property {string} version Its version when copied.
51
+ * @property {string[]} [files] The paths copied, as {@link vendorPackage} took them (the kit's own copy has none).
52
+ * @property {string} [hash] A hash of every file copied ({@link treeHash}); a copy from before 1.11 has none.
41
53
  */
42
54
  /**
43
55
  * The folder of an installed package, found as Node finds it (the nearest
@@ -55,6 +67,8 @@ export declare function packageDir(name: string, from?: string): Promise<string>
55
67
  *
56
68
  * @param {string} dest - The folder to fill, e.g. `extension/vendor/extension-kit`. Removed first.
57
69
  * @returns {Promise<string[]>} The entries copied, relative to `dest`.
70
+ * @throws {Error} When `dest` holds an extension or a project (`manifest.json`, `package.json`, `.git`).
71
+ *
58
72
  * @example
59
73
  * await vendorKit('extension/vendor/extension-kit');
60
74
  * // extension/vendor/extension-kit/index.js, …/styles/chrome-ui.css, …, vendored.json
@@ -71,7 +85,9 @@ export declare function vendorKit(dest: string): Promise<string[]>;
71
85
  * @param {string} dest - The folder to fill, e.g. `extension/vendor/clean-link`. Removed first.
72
86
  * @param {{from?: string}} [options] - `from`: where to look for `node_modules` from. Default the current folder.
73
87
  * @returns {Promise<string[]>} The files and folders written, relative to `dest`.
74
- * @throws {Error} When the package isn't installed, or a path isn't in it.
88
+ * @throws {Error} When the package isn't installed, a path isn't in it, two paths would land in
89
+ * the same place (`dist/index.js` and `rules/index.js`), or `dest` holds an extension or a project.
90
+ *
75
91
  * @example
76
92
  * await vendorPackage('@duckduckgo/autoconsent', ['dist/autoconsent.esm.js', 'rules/compact-rules.json', 'LICENSE'], 'extension/vendor/autoconsent');
77
93
  * // or, from postinstall: extension-kit vendor extension/vendor/clean-link @arraypress/clean-link src/
@@ -82,11 +98,16 @@ export declare function vendorPackage(name: string, files: readonly string[], de
82
98
  /**
83
99
  * Every vendored copy under `dir` (a folder with a {@link VENDOR_STAMP},
84
100
  * searched to any depth) that no longer matches the package installed now:
85
- * copied from another version, or from a package that's gone.
101
+ * copied from another version, from a package that's gone, edited since (a
102
+ * file a script wrote beside the copied ones afterwards doesn't count), or
103
+ * from files the installed package no longer has as they were. A folder with
104
+ * no vendored copy at all (a mistyped path, `postinstall` never run) is
105
+ * reported too.
86
106
  *
87
107
  * @param {string} dir - The vendor folder, e.g. `extension/vendor`.
88
108
  * @param {{from?: string}} [options] - `from`: where to look for `node_modules` from. Default the current folder.
89
- * @returns {Promise<string[]>} One line per stale copy; empty when all match (or there are none).
109
+ * @returns {Promise<string[]>} One line per stale copy; empty when all match.
110
+ *
90
111
  * @example
91
112
  * const stale = await checkVendored('extension/vendor');
92
113
  * // ['extension/vendor/extension-kit is @arraypress/extension-kit 1.2.0; 1.3.0 is installed']
@@ -5,11 +5,13 @@
5
5
  * `extension/vendor/`; the copy is made from the installed package on
6
6
  * `npm install` (`postinstall`) and is never committed.
7
7
  *
8
- * Each copy is stamped with the package's name and version
9
- * ({@link VENDOR_STAMP}), so {@link checkVendored} can say when a copy no
10
- * longer matches what's installed: `npm install some-package` installs
11
- * without running the extension's own `postinstall`, and the copy goes stale
12
- * without a word.
8
+ * Each copy is stamped with the package's name and version, what was copied
9
+ * and a hash of it ({@link VENDOR_STAMP}), so {@link checkVendored} can say
10
+ * when a copy no longer matches what's installed: `npm install some-package`
11
+ * installs without running the extension's own `postinstall`, and the copy
12
+ * goes stale without a word; so does a copy edited by hand, or a package
13
+ * whose files changed under the same version (a library copied into
14
+ * `node_modules` to try it before it's published).
13
15
  *
14
16
  * An extension with a bundler imports the package instead and copies only
15
17
  * the stylesheet ({@link STYLESHEET}).
@@ -17,7 +19,8 @@
17
19
  * @module build/vendor
18
20
  */
19
21
 
20
- import { access, cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
22
+ import { createHash } from 'node:crypto';
23
+ import { access, copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
21
24
  import { fileURLToPath } from 'node:url';
22
25
  import path from 'node:path';
23
26
 
@@ -42,6 +45,8 @@ export const VENDOR_STAMP = 'vendored.json';
42
45
  * @typedef {object} VendorStamp
43
46
  * @property {string} package The package's name.
44
47
  * @property {string} version Its version when copied.
48
+ * @property {string[]} [files] The paths copied, as {@link vendorPackage} took them (the kit's own copy has none).
49
+ * @property {string} [hash] A hash of every file copied ({@link treeHash}); a copy from before 1.11 has none.
45
50
  */
46
51
 
47
52
  /**
@@ -73,14 +78,90 @@ async function versionOf(dir) {
73
78
  }
74
79
 
75
80
  /**
76
- * Write a folder's {@link VENDOR_STAMP}.
81
+ * Every file under a file or folder.
77
82
  *
78
- * @param {string} dest - The vendored folder.
79
- * @param {VendorStamp} source - Where the copy came from.
83
+ * @param {string} source - A file or a folder.
84
+ * @returns {Promise<string[]>} Paths from `source`, forward slashes ('' for a file itself).
85
+ */
86
+ async function filesOf(source) {
87
+ if (!(await stat(source)).isDirectory()) return [''];
88
+ const entries = await readdir(source, { recursive: true, withFileTypes: true });
89
+ return entries.filter((entry) => entry.isFile()).map((entry) => path.relative(source, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'));
90
+ }
91
+
92
+ /**
93
+ * What a copy holds: each file's place in the vendored folder and the file it comes from. A
94
+ * path lands under its own name (`dist/lib.esm.js` → `lib.esm.js`); a path ending in `/` has its
95
+ * contents copied instead (`src/` → `index.js`, …).
96
+ *
97
+ * @param {string} dir - The folder the paths are in (a package's, or the kit's `src/`).
98
+ * @param {readonly string[]} files - The paths.
99
+ * @returns {Promise<Map<string, string>>} Place in the copy (forward slashes) → source file.
100
+ * @throws {Error} When a path isn't there, or two files would land in the same place.
101
+ */
102
+ async function copyPlan(dir, files) {
103
+ /** @type {Map<string, string>} */
104
+ const plan = new Map();
105
+ for (const file of files) {
106
+ const source = path.join(dir, file);
107
+ const under = file.endsWith('/') ? '' : path.basename(file);
108
+ for (const inner of await filesOf(source)) {
109
+ const place = [under, inner].filter(Boolean).join('/');
110
+ const taken = plan.get(place);
111
+ if (taken) throw new Error(`${path.relative(dir, taken)} and ${path.relative(dir, path.join(source, inner))} would both be copied to ${place}`);
112
+ plan.set(place, path.join(source, inner));
113
+ }
114
+ }
115
+ return plan;
116
+ }
117
+
118
+ /**
119
+ * A hash of a set of files: their places and contents, in order of place.
120
+ *
121
+ * @param {Iterable<[string, string]>} files - Place (forward slashes) → the file to read.
122
+ * @returns {Promise<string>} SHA-256, hex.
123
+ */
124
+ async function treeHash(files) {
125
+ const hash = createHash('sha256');
126
+ for (const [place, file] of [...files].sort(([a], [b]) => (a < b ? -1 : 1))) {
127
+ hash.update(`${place}\0`).update(await readFile(file)).update('\0');
128
+ }
129
+ return hash.digest('hex');
130
+ }
131
+
132
+ /**
133
+ * Whether a folder is somewhere a copy mustn't go: it would be deleted first, and it holds an
134
+ * extension or a project (`manifest.json`, `package.json`, a `.git`) rather than an older copy.
135
+ *
136
+ * @param {string} dest - The folder to fill.
137
+ * @returns {Promise<void>}
138
+ * @throws {Error} When it does.
139
+ */
140
+ async function refuseSource(dest) {
141
+ for (const sign of ['manifest.json', 'package.json', '.git']) {
142
+ if (await access(path.join(dest, sign)).then(() => true, () => false)) {
143
+ throw new Error(`${dest} holds a ${sign}: it isn't a vendor folder, and copying into it would delete it first`);
144
+ }
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Replace `dest` with the files of a plan, stamped.
150
+ *
151
+ * @param {string} dest - The vendored folder. Removed first.
152
+ * @param {Map<string, string>} plan - From {@link copyPlan}.
153
+ * @param {Omit<VendorStamp, 'hash'>} source - Where the copy comes from.
80
154
  * @returns {Promise<void>}
81
155
  */
82
- async function stamp(dest, source) {
83
- await writeFile(path.join(dest, VENDOR_STAMP), `${JSON.stringify(source, null, 2)}\n`);
156
+ async function copyStamped(dest, plan, source) {
157
+ await refuseSource(dest);
158
+ await rm(dest, { recursive: true, force: true });
159
+ await mkdir(dest, { recursive: true });
160
+ for (const [place, file] of plan) {
161
+ await mkdir(path.dirname(path.join(dest, place)), { recursive: true });
162
+ await copyFile(file, path.join(dest, place));
163
+ }
164
+ await writeFile(path.join(dest, VENDOR_STAMP), `${JSON.stringify({ ...source, hash: await treeHash(plan) }, null, 2)}\n`);
84
165
  }
85
166
 
86
167
  /**
@@ -88,17 +169,14 @@ async function stamp(dest, source) {
88
169
  *
89
170
  * @param {string} dest - The folder to fill, e.g. `extension/vendor/extension-kit`. Removed first.
90
171
  * @returns {Promise<string[]>} The entries copied, relative to `dest`.
172
+ * @throws {Error} When `dest` holds an extension or a project (`manifest.json`, `package.json`, `.git`).
173
+ *
91
174
  * @example
92
175
  * await vendorKit('extension/vendor/extension-kit');
93
176
  * // extension/vendor/extension-kit/index.js, …/styles/chrome-ui.css, …, vendored.json
94
177
  */
95
178
  export async function vendorKit(dest) {
96
- await rm(dest, { recursive: true, force: true });
97
- await mkdir(dest, { recursive: true });
98
- for (const entry of RUNTIME_ENTRIES) {
99
- await cp(path.join(SOURCE, entry), path.join(dest, entry), { recursive: true });
100
- }
101
- await stamp(dest, { package: KIT, version: await versionOf(path.dirname(SOURCE)) });
179
+ await copyStamped(dest, await copyPlan(SOURCE, RUNTIME_ENTRIES), { package: KIT, version: await versionOf(path.dirname(SOURCE)) });
102
180
  return [...RUNTIME_ENTRIES];
103
181
  }
104
182
 
@@ -113,54 +191,72 @@ export async function vendorKit(dest) {
113
191
  * @param {string} dest - The folder to fill, e.g. `extension/vendor/clean-link`. Removed first.
114
192
  * @param {{from?: string}} [options] - `from`: where to look for `node_modules` from. Default the current folder.
115
193
  * @returns {Promise<string[]>} The files and folders written, relative to `dest`.
116
- * @throws {Error} When the package isn't installed, or a path isn't in it.
194
+ * @throws {Error} When the package isn't installed, a path isn't in it, two paths would land in
195
+ * the same place (`dist/index.js` and `rules/index.js`), or `dest` holds an extension or a project.
196
+ *
117
197
  * @example
118
198
  * await vendorPackage('@duckduckgo/autoconsent', ['dist/autoconsent.esm.js', 'rules/compact-rules.json', 'LICENSE'], 'extension/vendor/autoconsent');
119
199
  * // or, from postinstall: extension-kit vendor extension/vendor/clean-link @arraypress/clean-link src/
120
200
  */
121
201
  export async function vendorPackage(name, files, dest, { from } = {}) {
122
202
  const dir = await packageDir(name, from);
123
- await rm(dest, { recursive: true, force: true });
124
- await mkdir(dest, { recursive: true });
125
- /** @type {string[]} */
126
- const written = [];
127
- for (const file of files) {
128
- const source = path.join(dir, file);
129
- if (file.endsWith('/')) {
130
- await cp(source, dest, { recursive: true });
131
- written.push(...await readdir(source));
132
- } else {
133
- await cp(source, path.join(dest, path.basename(file)), { recursive: true });
134
- written.push(path.basename(file));
135
- }
203
+ const plan = await copyPlan(dir, files);
204
+ await copyStamped(dest, plan, { package: name, version: await versionOf(dir), files: [...files] });
205
+ return [...new Set([...plan.keys()].map((place) => place.split('/')[0]))];
206
+ }
207
+
208
+ /**
209
+ * Why a stamped copy no longer matches the package installed now, if it doesn't.
210
+ *
211
+ * @param {string} folder - The vendored folder.
212
+ * @param {VendorStamp} copied - Its stamp.
213
+ * @param {string | undefined} from - Where to look for `node_modules` from.
214
+ * @returns {Promise<string | null>} The line to print, or null when it matches.
215
+ */
216
+ async function staleness(folder, copied, from) {
217
+ const dir = await packageDir(copied.package, from).catch(() => null);
218
+ if (dir === null) return `${folder} is ${copied.package} ${copied.version}, which isn't installed`;
219
+ const installed = await versionOf(dir);
220
+ if (installed !== copied.version) return `${folder} is ${copied.package} ${copied.version}; ${installed} is installed`;
221
+ if (!copied.hash) return null;
222
+ const plan = await (copied.files ? copyPlan(dir, copied.files) : copyPlan(path.join(dir, 'src'), RUNTIME_ENTRIES)).catch(() => null);
223
+ if (plan === null || await treeHash(plan) !== copied.hash) {
224
+ return `${folder} is ${copied.package} ${copied.version}, but the installed ${copied.version}'s files are different`;
136
225
  }
137
- await stamp(dest, { package: name, version: await versionOf(dir) });
138
- return written;
226
+ // The copied files as they are now; files a script wrote beside them afterwards aren't the package's.
227
+ const here = await treeHash([...plan.keys()].map((place) => [place, path.join(folder, place)])).catch(() => null);
228
+ if (here !== copied.hash) return `${folder} has changed since it was copied from ${copied.package} ${copied.version}`;
229
+ return null;
139
230
  }
140
231
 
141
232
  /**
142
233
  * Every vendored copy under `dir` (a folder with a {@link VENDOR_STAMP},
143
234
  * searched to any depth) that no longer matches the package installed now:
144
- * copied from another version, or from a package that's gone.
235
+ * copied from another version, from a package that's gone, edited since (a
236
+ * file a script wrote beside the copied ones afterwards doesn't count), or
237
+ * from files the installed package no longer has as they were. A folder with
238
+ * no vendored copy at all (a mistyped path, `postinstall` never run) is
239
+ * reported too.
145
240
  *
146
241
  * @param {string} dir - The vendor folder, e.g. `extension/vendor`.
147
242
  * @param {{from?: string}} [options] - `from`: where to look for `node_modules` from. Default the current folder.
148
- * @returns {Promise<string[]>} One line per stale copy; empty when all match (or there are none).
243
+ * @returns {Promise<string[]>} One line per stale copy; empty when all match.
244
+ *
149
245
  * @example
150
246
  * const stale = await checkVendored('extension/vendor');
151
247
  * // ['extension/vendor/extension-kit is @arraypress/extension-kit 1.2.0; 1.3.0 is installed']
152
248
  */
153
249
  export async function checkVendored(dir, { from } = {}) {
154
250
  const entries = await readdir(dir, { recursive: true }).catch(() => /** @type {string[]} */ ([]));
251
+ const stamps = entries.filter((file) => path.basename(file) === VENDOR_STAMP).sort();
252
+ if (!stamps.length) return [`${dir} has no vendored copies (no ${VENDOR_STAMP} in it)`];
155
253
  /** @type {string[]} */
156
254
  const stale = [];
157
- for (const entry of entries.filter((file) => path.basename(file) === VENDOR_STAMP).sort()) {
158
- const folder = path.join(dir, path.dirname(entry));
255
+ for (const entry of stamps) {
159
256
  /** @type {VendorStamp} */
160
257
  const copied = JSON.parse(await readFile(path.join(dir, entry), 'utf8'));
161
- const installed = await packageDir(copied.package, from).then(versionOf, () => null);
162
- if (installed === null) stale.push(`${folder} is ${copied.package} ${copied.version}, which isn't installed`);
163
- else if (installed !== copied.version) stale.push(`${folder} is ${copied.package} ${copied.version}; ${installed} is installed`);
258
+ const line = await staleness(path.join(dir, path.dirname(entry)), copied, from);
259
+ if (line) stale.push(line);
164
260
  }
165
261
  return stale;
166
262
  }
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * “Show on page”: boxes in Chrome's blue (DevTools' highlight) around a set of
3
3
  * elements, kept on them as the page scrolls or resizes, until cleared (the
4
- * extension's button again, another set, or Esc). The first can be scrolled
5
- * into view. The boxes go in the extension's own overlay (`pageOverlay`), so
4
+ * extension's button again, another set, Esc, or the page being left) and
5
+ * `onClear` is told which, so a panel's pressed button can follow an Esc on
6
+ * the page. The first can be scrolled into view. The boxes go in the extension's own overlay (`pageOverlay`), so
6
7
  * the page's styles can't touch them.
7
8
  *
8
9
  * @module content/highlight
@@ -21,10 +22,11 @@ export type Highlighter = {
21
22
  reveal?: boolean;
22
23
  }) => number;
23
24
  /**
24
- * Take the boxes away.
25
+ * Take the boxes away (`onClear('asked')`).
25
26
  */
26
27
  clear: () => void;
27
28
  };
29
+ export type ClearReason = 'escape' | 'replaced' | 'asked' | 'pagehide';
28
30
  /**
29
31
  * A page's highlight: one set of elements boxed at a time.
30
32
  *
@@ -32,7 +34,13 @@ export type Highlighter = {
32
34
  * @property {(elements: Element[], options?: {reveal?: boolean}) => number} show Box elements (the
33
35
  * ones still in the page, the first {@link MAX_BOXES}), clearing any boxed before; `reveal`
34
36
  * scrolls the first into view. Returns how many are boxed.
35
- * @property {() => void} clear Take the boxes away.
37
+ * @property {() => void} clear Take the boxes away (`onClear('asked')`).
38
+ */
39
+ /**
40
+ * Why the boxes went: Esc on the page, another set shown in their place, `clear()` called, or
41
+ * the page left (`pagehide`: a page kept for Back would come back with stale boxes).
42
+ *
43
+ * @typedef {'escape' | 'replaced' | 'asked' | 'pagehide'} ClearReason
36
44
  */
37
45
  /**
38
46
  * A highlighter for a page.
@@ -40,7 +48,8 @@ export type Highlighter = {
40
48
  * @param {Document} doc - The page.
41
49
  * @param {object} options
42
50
  * @param {() => ParentNode} options.root - Where boxes go: the overlay's shadow root, made when first needed.
43
- * @param {() => void} [options.onClear] - After the boxes go (take an empty overlay away).
51
+ * @param {(reason: ClearReason) => void} [options.onClear] - After the boxes go, and why (take an empty
52
+ * overlay away; tell the panel when it's `'escape'` or `'pagehide'`, which it didn't ask for).
44
53
  * @param {number} [options.max] - The most elements boxed. Default {@link MAX_BOXES}.
45
54
  * @returns {Highlighter} It.
46
55
  * @example
@@ -49,6 +58,6 @@ export type Highlighter = {
49
58
  */
50
59
  export declare function createHighlighter(doc: Document, { root, onClear, max }: {
51
60
  root: () => ParentNode;
52
- onClear?: () => void;
61
+ onClear?: (reason: ClearReason) => void;
53
62
  max?: number;
54
63
  }): Highlighter;
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * “Show on page”: boxes in Chrome's blue (DevTools' highlight) around a set of
3
3
  * elements, kept on them as the page scrolls or resizes, until cleared (the
4
- * extension's button again, another set, or Esc). The first can be scrolled
5
- * into view. The boxes go in the extension's own overlay (`pageOverlay`), so
4
+ * extension's button again, another set, Esc, or the page being left) and
5
+ * `onClear` is told which, so a panel's pressed button can follow an Esc on
6
+ * the page. The first can be scrolled into view. The boxes go in the extension's own overlay (`pageOverlay`), so
6
7
  * the page's styles can't touch them.
7
8
  *
8
9
  * @module content/highlight
@@ -21,7 +22,14 @@ export const HIGHLIGHT_CSS = '.box { position: fixed; box-sizing: border-box; bo
21
22
  * @property {(elements: Element[], options?: {reveal?: boolean}) => number} show Box elements (the
22
23
  * ones still in the page, the first {@link MAX_BOXES}), clearing any boxed before; `reveal`
23
24
  * scrolls the first into view. Returns how many are boxed.
24
- * @property {() => void} clear Take the boxes away.
25
+ * @property {() => void} clear Take the boxes away (`onClear('asked')`).
26
+ */
27
+
28
+ /**
29
+ * Why the boxes went: Esc on the page, another set shown in their place, `clear()` called, or
30
+ * the page left (`pagehide`: a page kept for Back would come back with stale boxes).
31
+ *
32
+ * @typedef {'escape' | 'replaced' | 'asked' | 'pagehide'} ClearReason
25
33
  */
26
34
 
27
35
  /**
@@ -30,7 +38,8 @@ export const HIGHLIGHT_CSS = '.box { position: fixed; box-sizing: border-box; bo
30
38
  * @param {Document} doc - The page.
31
39
  * @param {object} options
32
40
  * @param {() => ParentNode} options.root - Where boxes go: the overlay's shadow root, made when first needed.
33
- * @param {() => void} [options.onClear] - After the boxes go (take an empty overlay away).
41
+ * @param {(reason: ClearReason) => void} [options.onClear] - After the boxes go, and why (take an empty
42
+ * overlay away; tell the panel when it's `'escape'` or `'pagehide'`, which it didn't ask for).
34
43
  * @param {number} [options.max] - The most elements boxed. Default {@link MAX_BOXES}.
35
44
  * @returns {Highlighter} It.
36
45
  * @example
@@ -43,40 +52,54 @@ export function createHighlighter(doc, { root, onClear = () => {}, max = MAX_BOX
43
52
  let shown = null;
44
53
  let pending = 0;
45
54
 
55
+ /** Put a box on each rectangle in the window, reusing the boxes there are: nothing is made or removed while scrolling. */
46
56
  const draw = () => {
47
57
  pending = 0;
48
58
  if (!shown) return;
49
- for (const box of shown.boxes) box.remove();
50
- shown.boxes = shown.elements.flatMap((element) => [...element.getClientRects()].filter((rect) => rect.width && rect.height
51
- && rect.bottom > 0 && rect.top < view.innerHeight && rect.right > 0 && rect.left < view.innerWidth).map((rect) => {
52
- const box = doc.createElement('div');
53
- box.className = 'box';
59
+ const rects = shown.elements.flatMap((element) => [...element.getClientRects()].filter((rect) => rect.width && rect.height
60
+ && rect.bottom > 0 && rect.top < view.innerHeight && rect.right > 0 && rect.left < view.innerWidth));
61
+ const { boxes } = shown;
62
+ for (const box of boxes.splice(rects.length)) box.remove();
63
+ /** @type {HTMLElement[]} */
64
+ const added = [];
65
+ rects.forEach((rect, index) => {
66
+ let box = boxes[index];
67
+ if (!box) {
68
+ box = doc.createElement('div');
69
+ box.className = 'box';
70
+ boxes.push(box);
71
+ added.push(box);
72
+ }
54
73
  Object.assign(box.style, { left: `${rect.left - 2}px`, top: `${rect.top - 2}px`, width: `${rect.width + 4}px`, height: `${rect.height + 4}px` });
55
- return box;
56
- }));
57
- root().append(...shown.boxes);
74
+ });
75
+ if (added.length) root().append(...added);
58
76
  };
59
77
  const update = () => {
60
78
  if (!pending) pending = view.requestAnimationFrame(draw);
61
79
  };
62
80
  /** @param {KeyboardEvent} event */
63
81
  const key = (event) => {
64
- if (event.key === 'Escape') clear();
82
+ if (event.key === 'Escape') end('escape');
65
83
  };
84
+ const left = () => end('pagehide');
66
85
 
67
- function clear() {
86
+ /** @param {ClearReason} reason */
87
+ function end(reason) {
68
88
  if (!shown) return;
69
89
  view.removeEventListener('scroll', update, true);
70
90
  view.removeEventListener('resize', update);
71
91
  view.removeEventListener('keydown', key, true);
92
+ view.removeEventListener('pagehide', left);
93
+ if (pending) view.cancelAnimationFrame(pending);
94
+ pending = 0;
72
95
  for (const box of shown.boxes) box.remove();
73
96
  shown = null;
74
- onClear();
97
+ onClear(reason);
75
98
  }
76
99
 
77
100
  /** @type {Highlighter['show']} */
78
101
  function show(elements, { reveal = false } = {}) {
79
- clear();
102
+ end('replaced');
80
103
  const some = elements.filter((element) => element.isConnected).slice(0, max);
81
104
  if (!some.length) return 0;
82
105
  if (reveal) some[0].scrollIntoView({ block: 'center', inline: 'nearest' });
@@ -84,9 +107,11 @@ export function createHighlighter(doc, { root, onClear = () => {}, max = MAX_BOX
84
107
  view.addEventListener('scroll', update, { capture: true, passive: true });
85
108
  view.addEventListener('resize', update, { passive: true });
86
109
  view.addEventListener('keydown', key, true);
110
+ view.addEventListener('pagehide', left);
87
111
  draw();
88
112
  return some.length;
89
113
  }
90
114
 
91
- return { show, clear };
115
+ return { show, clear: () => end('asked') };
116
+
92
117
  }
@@ -19,6 +19,10 @@ export type PageOverlay = {
19
19
  * Take it off the page.
20
20
  */
21
21
  remove: () => void;
22
+ /**
23
+ * With `topLayer`: put it over whatever entered the top layer since.
24
+ */
25
+ raise: () => void;
22
26
  };
23
27
  /**
24
28
  * A page overlay.
@@ -27,6 +31,7 @@ export type PageOverlay = {
27
31
  * @property {HTMLElement} host The host element, on the page's root element.
28
32
  * @property {ShadowRoot} root Its closed shadow root, the styles first: append to it.
29
33
  * @property {() => void} remove Take it off the page.
34
+ * @property {() => void} raise With `topLayer`: put it over whatever entered the top layer since.
30
35
  */
31
36
  /**
32
37
  * Put an overlay on the page, replacing one of the same name a run before left.
@@ -37,10 +42,19 @@ export type PageOverlay = {
37
42
  * with `!important` after the reset. `css` styles what's inside (and `:host` custom properties,
38
43
  * which the reset doesn't touch).
39
44
  *
45
+ * With `topLayer` the host is a manual popover, shown: it draws in the top layer, over the page's
46
+ * modal dialogs, popovers and fullscreen element, which no `z-index` reaches. The top layer
47
+ * paints in the order things entered it, so the overlay goes back on top (`raise`) whenever the
48
+ * page opens a dialog or a popover or goes fullscreen after it. What a modal dialog makes inert
49
+ * stays inert, the overlay with it: it shows over the dialog, but can't be clicked while the
50
+ * dialog is open. The popover's own backdrop is taken away (first in the overlay's styles), so a
51
+ * page's `::backdrop` rule can't tint the window through it.
52
+ *
40
53
  * @param {Document} doc - The page.
41
- * @param {{name: string, css: string, hostStyle?: Record<string, string>}} options - `name`: the
42
- * host's element name, with a hyphen (never registered: a plain element); `css`: the overlay's
43
- * styles; `hostStyle`: the host's own styles by CSS property name (`'z-index'`), each `!important`.
54
+ * @param {{name: string, css: string, hostStyle?: Record<string, string>, topLayer?: boolean}} options -
55
+ * `name`: the host's element name, with a hyphen (never registered: a plain element); `css`: the
56
+ * overlay's styles; `hostStyle`: the host's own styles by CSS property name (`'z-index'`), each
57
+ * `!important`; `topLayer`: draw over the page's dialogs and fullscreen element. Default false.
44
58
  * @returns {PageOverlay} The overlay.
45
59
  * @example
46
60
  * const { root, remove } = pageOverlay(document, {
@@ -50,8 +64,9 @@ export type PageOverlay = {
50
64
  * });
51
65
  * root.append(card);
52
66
  */
53
- export declare function pageOverlay(doc: Document, { name, css, hostStyle }: {
67
+ export declare function pageOverlay(doc: Document, { name, css, hostStyle, topLayer }: {
54
68
  name: string;
55
69
  css: string;
56
70
  hostStyle?: Record<string, string>;
71
+ topLayer?: boolean;
57
72
  }): PageOverlay;