Repository navigation
Expand file tree
/
Copy pathpanes.test.mjs
More file actions
293 lines (267 loc) · 13.4 KB
/
Copy pathpanes.test.mjs
File metadata and controls
293 lines (267 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// P3, P4 and P12 in WIP.HelpAddin.md, measured rather than read off the IDE's
// code: a web page in a tool window, HTML set through innerHTML with inline
// handlers in it, and raiseEvent from plain tool-window HTML. The PanesProbe
// add-in (probes/panes) builds the tool window and points its iframe at
// TB_PANES_URL. This file serves that page, and the two it leads to, from a
// server of its own on localhost: the IDE's own page is on localhost too, so
// the frame is on the same site, in the page's own process, where CDP can read
// it through Page.getFrameTree. A frame on another site gets a process and a
// DevTools target of its own (P3 in WIP.HelpAddin.md).
//
// The last test is what ToolWindows.Add does with windows given no id, which
// P9 turned up.
//
// Each test states what BETA 1034 does. If one fails after an IDE update, the
// IDE has changed: update P3, P4 and P12 in WIP.HelpAddin.md and the tbIDE
// pages that rest on them (HtmlElement, HtmlElementProperties, HtmlElements,
// ToolWindow, ToolWindows), and then this file.
//
// Run it with addin-test.bat, which gives it a lane; on its own it is skipped.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import path from "node:path";
import { before, test } from "node:test";
import { fileURLToPath } from "node:url";
import { sleep } from "../../scripts/lib/tb-ide.mjs";
import { loadedAddins } from "../../scripts/lib/tb-ide-addins.mjs";
import { consoleMark, linesSince } from "../../scripts/lib/tb-ide-console.mjs";
import { click, clickAt, pressKey, toolWindow, waitFor } from "../../scripts/lib/tb-operate.mjs";
import { frameEval, frameOf, serveLoopback } from "./pages.mjs";
import { scenario } from "./scenario.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const HOST = path.join(HERE, "host");
const PROBE = path.join(HERE, "probes", "panes");
const W = "PanesProbeData"; // the id the probe gives ToolWindows.Add
// ------------------------------------------------------------------ the pages
const page = (title, body) => `<!doctype html><html><head><meta charset="utf-8">
<meta name="color-scheme" content="light dark"><title>${title}</title>
<style>body{font:14px sans-serif;margin:8px}@media (prefers-color-scheme: dark){body{background:#111;color:#eee}}</style>
</head><body><h1>${title}</h1>${body}</body></html>`;
const PAGES = {
"/a.html": page(
"Fixture A",
`<p><a id="toB" href="b.html">to page B</a></p>` +
Array.from({ length: 200 }, (_, i) => `<p>line ${i + 1}</p>`).join(""),
),
"/b.html": page("Fixture B", `<p><a id="toA" href="a.html">to page A</a></p>`),
"/c.html": page("Fixture C", "<p>page C</p>"),
};
// Serve PAGES on localhost, recording every request.
async function servePages() {
const requests = [];
const server = await serveLoopback((req, res) => {
requests.push({ url: req.url, dest: req.headers["sec-fetch-dest"] });
const body = PAGES[req.url.split("?")[0]];
res.writeHead(body ? 200 : 404, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
res.end(body ?? "");
});
return { ...server, requests };
}
// ------------------------------------------------------------------ reading
// The probe's lines in the DEBUG CONSOLE since a mark, without the prefix.
const probeLines = (c, mark) => linesSince(c, mark, { prefix: "[PanesProbe] " });
// An element of the tool window, as a rectangle in the page's coordinates.
const rectOf = (c, css) =>
c.evaluate(`(() => {
const e = toolWindowsById[${JSON.stringify(W)}].bodyElement.querySelector(${JSON.stringify(css)});
if (!e) return null;
const r = e.getBoundingClientRect();
return { x: r.x, y: r.y, width: r.width, height: r.height };
})()`);
// Click an element of the page in the frame, at its centre, as a person would.
async function clickInFrame(c, origin, css) {
const f = await rectOf(c, "#p3frame");
const e = await frameEval(
c,
origin,
`(() => { const r = document.querySelector(${JSON.stringify(css)})
.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`,
);
await clickAt(c, f.x + e.x, f.y + e.y);
}
// Windows' app mode, which a WebView2 page's prefers-color-scheme follows
// unless its host says otherwise: AppsUseLightTheme 0 is dark.
function windowsAppModeDark() {
try {
const out = execFileSync(
"reg",
["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "/v", "AppsUseLightTheme"],
{ encoding: "utf8", windowsHide: true },
);
return /AppsUseLightTheme\s+REG_DWORD\s+0x0\b/.test(out);
} catch {
return false; // no value: Windows' default, light
}
}
// ------------------------------------------------------------------ the tests
scenario("P3, P4 and P12: HTML and a web page in a tool window", (lane) => {
let c, pages, origin;
const exceptions = [];
before(async () => {
pages = await servePages();
origin = `http://localhost:${pages.port}/`;
await lane.addAddin(PROBE);
// The lane gives the page 1600 by 1000: in a page as small as the user's IDE
// window can make it, the tool window floats over the probe's toolbar buttons.
c = await lane.open(HOST, { env: { TB_PANES_URL: `${origin}a.html` } });
await c.send("Runtime.enable");
c.on((m) => {
if (m.method !== "Runtime.exceptionThrown") return;
const d = m.params.exceptionDetails;
exceptions.push((d.exception?.description ?? d.text ?? "").split("\n")[0]);
});
});
test("the add-in loads, and its button opens its tool window", async () => {
const names = (await loadedAddins(c)).map((a) => a.name);
assert.ok(names.includes("PanesProbe AddIn"), `loaded: ${JSON.stringify(names)}`);
const mark = await consoleMark(c);
await click(c, "addinButton-PanesProbeShow");
assert.ok(await waitFor(c, async (c) => (await toolWindow(c, W))?.visible), "the tool window did not appear");
assert.ok(
await waitFor(c, async (c) => (await probeLines(c, mark)).includes("shown")),
"the add-in did not finish building its tool window",
);
});
test("P4: innerHTML renders, and its inline handlers run as the IDE page's own script", async () => {
assert.equal(
await c.evaluate(`toolWindowsById[${JSON.stringify(W)}].bodyElement.querySelector("#p4bold")?.tagName`),
"B",
);
// The <img>'s onerror ran with nothing clicked, and saw the page's internals.
assert.equal(await waitFor(c, (c) => c.evaluate("window.__p4error")), "object");
await click(c, { toolWindow: W, css: "#p4click" });
assert.equal(await waitFor(c, (c) => c.evaluate("window.__p4click")), "object");
});
test('P4: a property whose name starts with "on" is dropped, and the add-in is told nothing', async () => {
assert.ok((await probeLines(c, null)).includes("onclick property set, error 0"));
assert.deepEqual(
await c.evaluate(`(() => { const e = toolWindowsById[${JSON.stringify(W)}].bodyElement
.querySelector("#p4onprop"); return [e.onclick, e.getAttribute("onclick")]; })()`),
[null, null],
);
});
test("P12: raiseEvent from plain tool-window HTML throws, and the add-in hears nothing", async () => {
const mark = await consoleMark(c);
const n = exceptions.length;
await click(c, { toolWindow: W, css: "#p12raise" });
assert.ok(await waitFor(c, () => exceptions.length > n), "raiseEvent threw nothing");
assert.match(exceptions[n], /^TypeError: Cannot read properties of null \(reading 'rootEventHandler'\)/);
await sleep(1500);
assert.deepEqual(
(await probeLines(c, mark)).filter((l) => l.startsWith("p12Event")),
[],
);
});
test("P12: an inline handler that calls the listener AddEventListener put on its parent reaches the add-in", async () => {
const mark = await consoleMark(c);
const n = exceptions.length;
await click(c, { toolWindow: W, css: "#p12direct" });
assert.ok(
await waitFor(c, async (c) => (await probeLines(c, mark)).includes("p12Event from p12direct")),
`the add-in's listener was not called: ${JSON.stringify(await probeLines(c, mark))}`,
);
assert.deepEqual(exceptions.slice(n), []);
});
test("P3: Visible = True sets the root's display to block, and a wrapper keeps the frame filling the window", async () => {
assert.equal(await c.evaluate(`toolWindowsById[${JSON.stringify(W)}].bodyElement.style.display`), "block");
const body = await c.evaluate(`(() => { const r = toolWindowsById[${JSON.stringify(W)}].bodyElement
.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`);
const frame = await rectOf(c, "#p3frame");
assert.ok(Math.abs(frame.width - body.width) < 2, `frame ${JSON.stringify(frame)} in body ${JSON.stringify(body)}`);
assert.ok(
Math.abs(frame.y + frame.height - (body.y + body.height)) < 2,
`the frame does not reach the bottom: frame ${JSON.stringify(frame)}, body ${JSON.stringify(body)}`,
);
assert.ok(frame.height > 150, `the frame kept its default height: ${JSON.stringify(frame)}`);
});
test("P3: the frame loads the page, and the add-in hears its load event", async () => {
const loaded = await waitFor(
c,
async (c) =>
(await frameOf(c, origin))?.url === `${origin}a.html` &&
(await frameEval(c, origin, "document.readyState")) === "complete",
);
assert.ok(loaded, `the frame did not load ${origin}a.html`);
assert.equal(await frameEval(c, origin, "document.title"), "Fixture A");
assert.deepEqual(pages.requests[0], { url: "/a.html", dest: "iframe" });
assert.ok(
await waitFor(c, async (c) => (await probeLines(c, null)).includes("frame load")),
"the add-in's load listener was not called",
);
});
test("P3: the mouse wheel scrolls the page in the frame", async () => {
const f = await rectOf(c, "#p3frame");
const x = f.x + f.width / 2,
y = f.y + f.height / 2;
await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
await c.send("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: 0, deltaY: 400 });
assert.ok(await waitFor(c, async (c) => (await frameEval(c, origin, "scrollY")) > 0), "the page did not scroll");
await frameEval(c, origin, "scrollTo(0, 0)");
});
test("P3: keys pressed with the focus in the frame go to the page, not to the add-in's shortcuts", async () => {
await clickInFrame(c, origin, "h1");
assert.equal(await waitFor(c, (c) => frameEval(c, origin, "document.hasFocus()")), true);
let mark = await consoleMark(c);
await pressKey(c, "F1");
await sleep(1500);
assert.deepEqual(
(await probeLines(c, mark)).filter((l) => l === "fired f1"),
[],
);
// The control: back in the IDE's own document, F1 fires.
await click(c, { toolWindow: W, css: "#p4bold" });
mark = await consoleMark(c);
await pressKey(c, "F1");
assert.ok(
await waitFor(c, async (c) => (await probeLines(c, mark)).includes("fired f1")),
"F1 did not fire outside the frame either",
);
});
test("P3: a link in the page navigates the frame", async () => {
const mark = await consoleMark(c);
await clickInFrame(c, origin, "#toB");
assert.ok(
await waitFor(c, async (c) => (await frameOf(c, origin))?.url === `${origin}b.html`),
`the frame is at ${(await frameOf(c, origin))?.url}`,
);
assert.ok(await waitFor(c, async (c) => (await probeLines(c, mark)).includes("frame load")));
assert.ok(pages.requests.some((r) => r.url === "/b.html" && r.dest === "iframe"));
});
test("P3: the add-in moves the frame to another page by setting its src", async () => {
const mark = await consoleMark(c);
await click(c, "addinButton-PanesProbeNavigate");
assert.ok(
await waitFor(c, async (c) => (await frameOf(c, origin))?.url === `${origin}c.html`),
`the frame is at ${(await frameOf(c, origin))?.url}`,
);
assert.ok(await waitFor(c, async (c) => (await probeLines(c, mark)).includes("frame load")));
assert.equal(await waitFor(c, (c) => frameEval(c, origin, "document.title")), "Fixture C");
});
test("P3: the page's colour scheme is Windows' app mode", async (t) => {
const dark = await frameEval(c, origin, `matchMedia("(prefers-color-scheme: dark)").matches`);
t.diagnostic(
`frame dark: ${dark}; Windows app mode dark: ${windowsAppModeDark()}; ` +
`IDE theme: ${await c.evaluate("getBaseThemeName()")}`,
);
assert.equal(dark, windowsAppModeDark());
});
// Found by P9 (reload.test.mjs): the page files a window given no id under
// the id "", and ToolWindows.Add of an id it already has empties that window
// and returns it (createToolWindowById in main.js).
test("ToolWindows.Add: two windows given no id are one window, emptied by the second Add", async () => {
const mark = await consoleMark(c);
await click(c, "addinButton-PanesProbeNoId");
assert.ok(
await waitFor(c, async (c) => (await probeLines(c, mark)).includes("no id windows")),
"the add-in did not finish opening its windows",
);
assert.deepEqual(
await c.evaluate(`Object.entries(toolWindowsById).filter(([id]) => id !== ${JSON.stringify(W)})
.map(([id, w]) => ({ id, title: w.titleElement.textContent,
divs: [...w.bodyElement.querySelectorAll("div[id^='noid']")].map((d) => d.id) }))`),
[{ id: "", title: "NO ID 2", divs: ["noid2", "noid1again"] }],
);
});
// After the lane is closed, even when closing it fails.
return () => pages?.close();
});