Repository navigation
Expand file tree
/
Copy pathhelp.test.mjs
More file actions
2220 lines (2102 loc) · 109 KB
/
Copy pathhelp.test.mjs
File metadata and controls
2220 lines (2102 loc) · 109 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The help add-in, add-in/, increments 1 to 3 of Stage 4 in WIP.HelpAddin.md:
// F1 shows the page for the selection or for the name under the cursor in the
// help pane, whose search box and results list find any page of the index;
// for the name under the cursor, the compiler's hover says where it is
// declared.
//
// The add-in is built as committed, with its copy of the symbol index,
// add-in/Resources/SYMBOLS/symbols.json, embedded as a resource. This file
// serves the built site, docs/_site, on localhost and gives the add-in it as
// TB_DOCS_HELP_SITE, which Open in browser opens. The lane named help builds
// the add-in without the help archive, so the pane's frame loads that site
// too; the lane named help-offline builds it with an archive of the built
// offline tree (lib/help-archive.mjs, the writer a build uses too), so the frame
// loads the add-in's own server. Either way every page a case reaches is a page of the
// build, and nothing comes from the network. Run build.bat first.
// Each case is a line and column in helphost/Sources/Cases.twin, so a change to
// that file is a change to this table.
//
// The last cases are the Detach button, which moves the pane into a window of
// the add-in's own, a Form holding a WebView2 control. The window's page is
// read and operated over DevTools: the add-in starts the control with the
// debugging port in TB_DOCS_HELP_WINDOW_PORT, which only the test switch
// allows, and prints "window page <src>" when the frame in it has loaded.
//
// Run it with addin-test.bat, which gives it a lane; on its own it is skipped.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { before, test } from "node:test";
import { fileURLToPath } from "node:url";
import { helpArchiveSkips } from "../../builder/help-archive-step.mjs";
import { createStaticHandler } from "../../builder/static-files.mjs";
import { writeHelpArchive } from "../../lib/help-archive.mjs";
import { attach } from "../../scripts/lib/tb-cdp.mjs";
import { leaseSlot, 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 { fixPageSize, PAGE } from "../../scripts/lib/tb-lane.mjs";
import {
click,
clickAt,
elementRect,
listViewItems,
notifications,
openedUrls,
openFile,
pressKey,
select,
setCursor,
toolWindow,
typeText,
waitFor,
} from "../../scripts/lib/tb-operate.mjs";
import { hoverLink, hoverText, mouseAway, restMouse } from "./hover.mjs";
import { frameEval, frameOf, serveLoopback } from "./pages.mjs";
import { scenario } from "./scenario.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "..", "..");
const ADDIN = path.join(ROOT, "add-in");
const INDEX = path.join(ADDIN, "Resources", "SYMBOLS", "symbols.json");
const BUILT = path.join(ROOT, "docs", "_site");
const BUILT_OFFLINE = path.join(ROOT, "docs", "_site-offline");
const FRESH_GATE = path.join(ROOT, "scripts", "check_tree_fresh.mjs");
// "serving site.zip, <n> files, at <origin>", which the add-in prints when it
// has the archive.
const SERVING = /^serving site\.zip, \d+ files, at (http:\/\/localhost:\d+)$/;
const HOST = path.join(HERE, "helphost");
const FILE = "/HelpHost/Sources/Cases.twin";
const PANE = "tbDocsHelpPane";
// The page height the hover test emulates, so that a hover reaches past the editor.
const SHORT_PAGE = 480;
// A page as small as a user's IDE window makes it: 1200 by 900 at 150%.
const SMALL_PAGE = { width: 800, height: 600 };
const addinLines = async (c, mark) => linesSince(c, mark, { prefix: "[tbDocsHelp] " });
// An expression on the pane's shadow root, `root`.
const inPane = (c, body) =>
c.evaluate(`(() => {
const w = toolWindowsById[${JSON.stringify(PANE)}];
if (!w) return null;
const root = w.bodyElement.getRootNode();
${body}
})()`);
const frameSrc = (c) => inPane(c, `return root.querySelector("#helpPage")?.getAttribute("src") ?? null;`);
// "dark" or "light", from the IDE theme's panel colour rather than from the
// API the add-in asks (Themes.ActiveThemeNameGroup).
const themeGroup = (c) =>
c.evaluate(`(() => {
const probe = document.createElement("div");
probe.style.background = "var(--themeGeneralPanelBackColor)";
document.body.appendChild(probe);
const [r, g, b] = getComputedStyle(probe).backgroundColor.match(/\\d+/g).map(Number);
probe.remove();
return 0.299 * r + 0.587 * g + 0.114 * b < 128 ? "dark" : "light";
})()`);
const focusedId = (c) => inPane(c, "return root.activeElement?.id ?? null;");
const searchValue = (c) => inPane(c, `return root.querySelector("#helpSearch")?.value ?? null;`);
const results = async (c) => (await listViewItems(c, { toolWindow: PANE, css: "#helpResults" })).map((i) => i.text);
// The results list's height, one drawn row's, the whole pane's,
// and whether the list's scrollbar shows; null while the list is hidden. The
// list view keeps a hidden copy of a row to measure with, so the row is the
// first one with a height.
const resultsBox = (c) =>
inPane(
c,
`const l = root.querySelector("#helpResults");
if (!l || l.style.display === "none") return null;
const heights = [...l.querySelectorAll(".hit, .none")].map((e) => e.getBoundingClientRect().height);
return {
height: l.getBoundingClientRect().height,
row: heights.find((h) => h > 0) ?? null,
pane: root.querySelector("#helpWrap").getBoundingClientRect().height,
scrollbar: getComputedStyle(l.querySelector(".scrollBackV")).display !== "none",
};`,
);
// The line between the results list and what is under it, in the pane (`root`
// is its shadow root) or in the window's page (`root` is the document): the
// top border of the frame and of the summary, the theme's text colour at 40%
// as a probe element has it, the list's own bottom border, which has to
// stay none (its height is its rows), and whether the list shows.
const SEPARATOR_LOOK = `(() => {
const look = (e) => { const s = getComputedStyle(e); return { width: s.borderTopWidth, style: s.borderTopStyle, color: s.borderTopColor }; };
const probe = document.createElement("div");
probe.style.cssText = "border: 2px solid color-mix(in srgb, var(--themeToolWindowBodyForeColor) 40%, transparent)";
(root.querySelector("#helpWrap") ?? root.body).appendChild(probe);
const want = look(probe);
probe.remove();
const list = root.querySelector("#helpResults");
return {
want,
page: look(root.querySelector("#helpPage")),
summary: look(root.querySelector("#helpSummary")),
listBottom: getComputedStyle(list).borderBottomWidth,
listShown: list.style.display !== "none",
};
})()`;
const paneSeparator = (c) => inPane(c, `return ${SEPARATOR_LOOK};`);
const windowSeparator = (conn) => conn.evaluate(`(() => { const root = document; return ${SEPARATOR_LOOK}; })()`);
const NO_LINE = { width: "0px", style: "none" };
// Whether `got`, from SEPARATOR_LOOK, has the line under a shown list and
// none under a hidden one; "" when it has, else what was wrong.
function separatorFault(got) {
const line = got.listShown ? got.want : NO_LINE;
if (got.want.style === "none" || got.want.width === "0px")
return "the probe has no border: color-mix is not supported, or the theme has no text colour";
for (const name of ["page", "summary"]) {
for (const key of Object.keys(line)) {
if (got[name][key] !== line[key]) return `${name} ${key} is ${got[name][key]}, not ${line[key]}`;
}
}
return got.listBottom === "0px" ? "" : "the list has a border of its own";
}
// What shows in place of the page for a name with none: null while the page shows.
const summary = (c) =>
inPane(
c,
`const s = root.querySelector("#helpSummary");
if (!s || s.style.display === "none") return null;
const text = (css) => s.querySelector(css)?.textContent ?? null;
return {
declaration: text(".declaration"),
description: text(".description"),
where: text(".where"),
frameHidden: root.querySelector("#helpPage").style.display === "none",
browserDisabled: root.querySelector("#helpBrowser").disabled,
};`,
);
// Whether the frame shows, rather than a summary, with Open in browser enabled.
const pageState = (c) =>
inPane(
c,
`return {
summary: root.querySelector("#helpSummary")?.style.display ?? null,
frame: root.querySelector("#helpPage")?.style.display ?? null,
browserDisabled: root.querySelector("#helpBrowser")?.disabled ?? null,
};`,
);
// What a frame's page shows of the theme, read in that page: its path and
// query, whether it has loaded and is the document marked earlier
// (tbDocsTestMark), its data-theme and data-pane, whether its background is
// dark or light, the choice theme-toggle.js shows on the site's theme button,
// the colour scheme the frame prefers, and, to say why when the
// theme is wrong, what its two storages hold for the theme and its window.name.
const DOCS_STATE = `(() => {
const stored = (name) => { try { const v = window[name].getItem("theme"); return v === null ? "empty" : v; } catch (e) { return "throws " + e.name; } };
const [r, g, b] = getComputedStyle(document.body).backgroundColor.match(/\\d+/g).map(Number);
return {
url: location.pathname + location.search,
ready: document.readyState === "complete",
marked: !!window.tbDocsTestMark,
theme: document.documentElement.getAttribute("data-theme"),
pane: document.documentElement.hasAttribute("data-pane"),
toggle: document.getElementById("theme-toggle")?.getAttribute("data-theme-choice") ?? null,
background: 0.299 * r + 0.587 * g + 0.114 * b < 128 ? "dark" : "light",
prefers: matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light",
sessionStorage: stored("sessionStorage"),
localStorage: stored("localStorage"),
name: window.name,
};
})()`;
const otherScheme = (group) => (group === "dark" ? "light" : "dark");
// The frame is told to prefer the other colour scheme than the IDE's group,
// so that a page left to follow its colour scheme shows the wrong theme.
const preferOther = (conn, group) =>
conn.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: otherScheme(group) }] });
// Whether a DOCS_STATE read under preferOther has the IDE's theme: the
// attribute, the background it gives, and the pane's layout. "" when it has,
// else what is wrong, so that a case can go on to the next page and report
// every one.
function docsThemeFault(state, group, where) {
if (!state) return `${where}: no page`;
if (state.prefers !== otherScheme(group)) return `${where}: the frame does not prefer the other scheme`;
const got = { theme: state.theme, background: state.background, pane: state.pane };
const want = { theme: group, background: group, pane: true };
return JSON.stringify(got) === JSON.stringify(want) ? "" : `${where}: ${JSON.stringify(state)}`;
}
// The floating panel that holds the pane, as a box in the page, with the page's
// size; null while the pane is docked or has no panel.
const floatingBox = (c) =>
c.evaluate(`(() => {
const w = toolWindowsById[${JSON.stringify(PANE)}];
const p = w?.shadowDom.host.closest(".floatingPanel");
if (!p) return null;
const r = p.getBoundingClientRect();
return { left: r.left, top: r.top, width: r.width, height: r.height, page: [innerWidth, innerHeight] };
})()`);
// Whether a floatingBox is wholly inside its page: "" when it is.
const boxFault = (b) =>
b.left >= 0 && b.top >= 0 && b.left + b.width <= b.page[0] && b.top + b.height <= b.page[1]
? ""
: "the pane's floating panel is not inside the page";
async function at(c, line, column) {
await setCursor(c, line, column);
await sleep(100);
}
async function emptySearch(c) {
await click(c, { toolWindow: PANE, css: "#helpSearch" });
await pressKey(c, "End");
for (let n = (await searchValue(c)).length; n > 0; n--) await pressKey(c, "Backspace");
}
scenario("the help add-in: F1 and the help pane", (lane) => {
let c;
let entries;
let origin; // the site this file serves
let pages; // where the frame's pages come from: origin, or the add-in's server
let server;
let windowPort; // the detached window's DevTools port
const offline = lane.name === "help-offline";
// What the IDE is started with: the site this file serves, the window's
// debugging port, and the window's frame, which the IDE's own option
// "Show real OS titlebar" would otherwise decide: 0 the frame the page draws
// a title bar for, 1 the Windows one. The option is never changed.
const ideEnv = (realTitlebar) => ({
TB_DOCS_HELP_SITE: origin,
TB_DOCS_HELP_WINDOW_PORT: String(windowPort),
TB_DOCS_HELP_REAL_TITLEBAR: String(realTitlebar),
});
// The frame shows `url` from the built site in the IDE's theme: the add-in
// gave it that src with ?theme= and ?pane=1, the page it loaded is the
// build's, not a 404, and the page applied the theme and hid the site's
// navigation and header. With `fresh`, the page is a new document: not the
// one markFrame marked.
async function showsPage(url, { fresh = false } = {}) {
const group = await themeGroup(c);
const [pagePath, fragment] = url.split("#");
const want = `${pages}${pagePath}?theme=${group}&pane=1${fragment ? `#${fragment}` : ""}`;
// The frame can have this src already, hidden behind a summary, so the
// page showing again is waited for too.
const shown = { summary: "none", frame: "", browserDisabled: false };
const src = await waitFor(c, async (c) => {
const s = await frameSrc(c);
return s === want && JSON.stringify(await pageState(c)) === JSON.stringify(shown) && s;
});
assert.equal(src ?? (await frameSrc(c)), want, "the frame's src");
assert.ok((await toolWindow(c, PANE))?.visible, "the pane is not showing");
assert.deepEqual(await pageState(c), shown);
const loaded = await waitFor(c, async (c) => {
const f = await frameOf(c, pages);
const loadedUrl = `${pages}${pagePath.replace(/\/$/, "")}?theme=${group}&pane=1`;
if (!f || f.url.replace(/\/\?/, "?") !== loadedUrl) return false;
// A src set to the URL the frame already has reloads it, and a question
// put to the page being replaced fails: that is not loaded yet.
const ready = `document.readyState === "complete"${fresh ? " && !window.tbDocsTestMark" : ""}`;
return (await frameEval(c, pages, ready).catch(() => false)) === true;
});
if (!loaded) {
const frames = (await c.send("Page.getFrameTree")).frameTree.childFrames ?? [];
assert.fail(
`the frame did not load ${want}; the page's frames: ${JSON.stringify(frames.map((f) => f.frame.url))}`,
);
}
if (fragment) assert.equal((await frameOf(c, pages)).urlFragment, `#${fragment}`);
// The status the page itself came with, after any redirect to its folder.
const status = await frameEval(c, pages, `performance.getEntriesByType("navigation")[0]?.responseStatus`);
assert.equal(status, 200, `${url} as served`);
assert.equal(
await frameEval(c, pages, `document.documentElement.getAttribute("data-theme")`),
group,
"the page's theme",
);
assert.deepEqual(await paneChrome(), PANE_CHROME, "the site's chrome in the pane");
}
// What the frame's page shows of the site's chrome: the pane hides the
// sidebar and the header, and keeps the breadcrumbs and the footer.
const PANE_CHROME = { sidebar: "none", header: "none", breadcrumbs: "block", footer: "block" };
const paneChrome = () =>
frameEval(
c,
pages,
`(() => {
const shown = (s) => { const e = document.querySelector(s); return e ? getComputedStyle(e).display : "missing"; };
return { sidebar: shown(".side-bar"), header: shown(".main-header"), breadcrumbs: shown(".breadcrumb-nav"), footer: shown("footer[role=contentinfo]") };
})()`,
);
// Marks the page the frame shows now, so that showsPage can tell a page F1
// loaded from it: F1 on the name whose page shows already loads it again,
// and the page before the reload looks loaded until the reload begins.
const markFrame = () => frameEval(c, pages, "window.tbDocsTestMark = true").catch(() => {});
// The IDE's theme, switched with the IDE's own commands for its theme menu.
const switchTheme = (group) =>
c.evaluate(
`executeIdeCommand(${JSON.stringify(group === "dark" ? "tbTheme_SwitchToDarkMode" : "tbTheme_SwitchToLightMode")})`,
);
// The frame's origin once the add-in has loaded after `mark`: the add-in's
// server, whose port changes with every start, or the site this file serves.
async function pagesOrigin(mark) {
const loaded = await waitFor(c, async (c) => (await addinLines(c, mark)).some((l) => l.startsWith("loaded")));
assert.ok(loaded, "the add-in never printed its loaded line");
const serving = (await addinLines(c, mark)).filter((l) => l.startsWith("serving") || l.startsWith("not serving"));
if (!offline) {
assert.deepEqual(serving, [], "the add-in built without the archive serves it");
return origin;
}
assert.equal(serving.length, 1, `the add-in's lines about the archive: ${JSON.stringify(serving)}`);
const m = serving[0].match(SERVING);
assert.ok(m, `the add-in does not serve the archive: ${serving[0]}`);
return m[1];
}
// Press F1 at line:column, and expect `want` in place of the page, the frame
// hidden, Open in browser disabled, and nothing printed.
async function f1Summary(line, column, want) {
await at(c, line, column);
const mark = await consoleMark(c);
await pressKey(c, "F1");
const got = await waitFor(c, async (c) => {
const s = await summary(c);
return s?.declaration === want.declaration && s;
});
assert.deepEqual(got || (await summary(c)), { ...want, frameHidden: true, browserDisabled: true });
assert.ok((await toolWindow(c, PANE))?.visible, "the pane is not showing");
assert.deepEqual(await addinLines(c, mark), [], "the add-in printed something");
}
// Press F1 (or run `act`), and expect `url` in the pane and nothing printed.
async function f1Shows(url, act = () => pressKey(c, "F1")) {
const mark = await consoleMark(c);
await markFrame();
await act();
await showsPage(url, { fresh: true });
assert.deepEqual(await addinLines(c, mark), [], "the add-in printed something");
}
before(async () => {
assert.ok(fs.existsSync(path.join(BUILT, "tB", "symbols.json")), `no built site in ${BUILT}: run build.bat`);
entries = JSON.parse(fs.readFileSync(INDEX, "utf8")).symbols.length;
server = await serveLoopback(createStaticHandler(BUILT));
origin = `http://localhost:${server.port}`;
// The add-in as committed, with the archive only in the offline lane,
// whatever add-in/Resources/HELP holds in this working tree.
const src = path.join(lane.work, "help-src");
fs.rmSync(src, { recursive: true, force: true });
const skip = [path.join(ADDIN, "Build"), path.join(ADDIN, "Resources", "HELP")];
fs.cpSync(ADDIN, src, { recursive: true, filter: (f) => !skip.includes(f) });
if (offline) {
// A tree older than its sources is refused, so the lane never tests
// a previous build's pages.
const fresh = spawnSync(process.execPath, [FRESH_GATE, "--tree", BUILT_OFFLINE], { encoding: "utf8" });
assert.equal(fresh.status, 0, `${BUILT_OFFLINE} is stale or missing; run build.bat first:\n${fresh.stderr}`);
try {
await writeHelpArchive({
src: BUILT_OFFLINE,
out: path.join(src, "Resources", "HELP", "site.zip"),
skip: helpArchiveSkips,
});
} catch (err) {
assert.fail(`writeHelpArchive failed: ${err.message}${err.problems ? `\n${err.problems.join("\n")}` : ""}`);
}
}
await lane.addAddin(src);
// A port the add-in is told before it binds it, so one the broker hands out
// (WIP.Broker.md); held, with its slot, until this process ends.
({ port: windowPort } = await leaseSlot({ tag: "help.test detached window", port: true }));
// The lane gives the page 1600 by 1000 (PAGE): in a page as small as the
// user's IDE window can make it, the pane, which first floats at 480 by 640,
// covers the toolbar's buttons and the editor.
c = await lane.open(HOST, { env: ideEnv(0) });
pages = await pagesOrigin(null);
await openFile(c, FILE, { line: 5, column: 9 });
});
test("it loads with the whole index and the test switch on, and makes its pane", async () => {
assert.ok((await loadedAddins(c)).some((a) => a.name === "twinBASIC Documentation Help"));
const loaded = await waitFor(c, async (c) => (await addinLines(c, null)).find((l) => l.startsWith("loaded")));
// Checked before any key is pressed: with the switch off, the add-in would
// ignore TB_DOCS_HELP_SITE, and "Open in browser" would start a browser.
const m = /^loaded, index (\d+) entries, packages ([^,]*), test switch on$/.exec(loaded);
assert.ok(m, `the loaded line: ${loaded}`);
assert.equal(Number(m[1]), entries);
// The packages the host project references, and the ones those reference,
// in the order the IDE lists them.
assert.deepEqual(m[2].split(" ").sort(), ["VB", "VBA", "VBRUN", "tbIDE"], loaded);
const pane = await toolWindow(c, PANE);
assert.equal(pane?.title, "TWINBASIC HELP");
assert.equal(pane.visible, false);
assert.equal(await frameSrc(c), null, "a page in the frame before any was asked for");
});
// Asked from here, not from the pane: the server finds a path as GitHub
// Pages does, and sends each file as the offline tree has it.
test("the add-in's server answers as GitHub Pages does", { skip: !offline && "the help lane" }, async () => {
const get = (p, o = {}) => fetch(`${pages}${p}`, { redirect: "manual", signal: AbortSignal.timeout(10000), ...o });
const tree = (rel) => fs.readFileSync(path.join(BUILT_OFFLINE, rel));
let r = await get("/tB/Modules/Interaction/MsgBox?theme=dark&pane=1");
assert.equal(r.status, 200);
assert.equal(r.headers.get("content-type"), "text/html; charset=utf-8");
assert.equal(r.headers.get("content-encoding"), "gzip");
assert.ok(Buffer.from(await r.arrayBuffer()).equals(tree("tB/Modules/Interaction/MsgBox.html")));
r = await get("/favicon.png");
assert.equal(r.status, 200);
assert.equal(r.headers.get("content-type"), "image/png");
assert.equal(r.headers.get("content-encoding"), null);
assert.ok(Buffer.from(await r.arrayBuffer()).equals(tree("favicon.png")));
r = await get("/Features/Advanced?pane=1");
assert.equal(r.status, 301);
assert.equal(r.headers.get("location"), "/Features/Advanced/?pane=1");
await r.body?.cancel();
r = await get("/Features/Advanced/");
assert.ok(Buffer.from(await r.arrayBuffer()).equals(tree("Features/Advanced/index.html")));
// A file the archive lacks, a page or a download, is on the site, the one
// the lane serves.
assert.ok(fs.existsSync(path.join(BUILT_OFFLINE, "Documentation/Development/Building.html")));
r = await get("/Documentation/Development/Building?pane=1");
assert.equal(r.status, 302);
assert.equal(r.headers.get("location"), `${origin}/Documentation/Development/Building?pane=1`);
await r.body?.cancel();
r = await get("/Videos/");
assert.equal(r.status, 302);
assert.equal(r.headers.get("location"), `${origin}/Videos/`);
await r.body?.cancel();
r = await get("/no/such/page.html");
assert.equal(r.status, 302);
assert.equal(r.headers.get("location"), `${origin}/no/such/page.html`);
await r.body?.cancel();
assert.ok(fs.existsSync(path.join(BUILT_OFFLINE, "Features/Packages/downloads/impexp.py")));
r = await get("/Features/Packages/downloads/impexp.py");
assert.equal(r.status, 302);
assert.equal(r.headers.get("location"), `${origin}/Features/Packages/downloads/impexp.py`);
await r.body?.cancel();
r = await get("/no/such/picture.png");
assert.equal(r.status, 302);
await r.body?.cancel();
// A path the server refuses is not sent on.
r = await get("/tB%5Cindex.html");
assert.equal(r.status, 404);
await r.body?.cancel();
r = await get("/tB/Modules/Interaction/MsgBox", { method: "HEAD" });
assert.equal(r.status, 200);
assert.ok(Number(r.headers.get("content-length")) > 0);
});
// [line, column, URL] in Cases.twin; the comment says what the cursor is on.
// The compiler's hover says where most of these are declared; the ones it
// says nothing about (Debug.Print, a statement, a comment) take the index's
// lookup alone.
const CASES = [
[5, 9, "/tB/Modules/Interaction/MsgBox", "the first letter of a name"],
[5, 15, "/tB/Modules/Interaction/MsgBox", "just after a name"],
[6, 27, "/tB/Modules/Interaction/MsgBox", "VBA.Interaction.MsgBox: Container.Name"],
[6, 15, "/tB/Modules/Interaction/", "VBA.Interaction: Package.Name"],
[7, 15, "/tB/Modules/Debug#print", "Debug.Print: the member, not the statement"],
[7, 21, "/tB/Modules/Strings/Len", "a function inside a call"],
[8, 9, "/tB/Core/Dim", "a statement"],
[9, 9, "/tB/Core/Close", "a bare name: the statement wins over twelve methods"],
[10, 28, "/tB/Packages/tbIDE/ToolWindows#add", "a chain in a comment: ToolWindows.Add"],
[4, 12, "/tB/Modules/Collection/Add", "c.Add, c a Collection: VBA._Collection's"],
[21, 15, "/tB/Modules/Collection/Add", ".Add inside With on a Collection"],
[16, 35, "/tB/Packages/tbIDE/ToolWindows#add", "Host.ToolWindows.Add: tbIDE.IToolWindowsV1's"],
[14, 25, "/tB/Packages/VB/CheckBox/#value", "a CheckBox's Value: VB._CheckBox's"],
[14, 42, "/tB/Modules/Constants/VbMsgBoxStyle", "an enumeration's value"],
[14, 52, "/tB/Modules/Constants/", "a constant"],
// Hover names another procedure for these, GetAppPath and GetErrNumber,
// but its package still picks VB's App from AppGlobalClassObject's, and
// ErrObject.Number from every other Number.
[14, 36, "/tB/Packages/VB/App/#path", "App.Path"],
[14, 64, "/tB/Modules/ErrObject/Number", "Err.Number"],
// A data type is the language's, at its section of the Data Types page;
// the function or property of the same name is picked by the hover's
// package, which names VBA for String( and Date, and nothing for a type.
// No two of the page's cases are next to each other: a change of
// fragment alone does not load the page again.
[8, 29, "/Reference/Data-Types#long", "a data type: Long"],
[42, 27, "/tB/Modules/Strings/String", 'String(5, "x"): the function, not the type'],
[42, 18, "/Reference/Data-Types#string", "As String: the type, not the function"],
[43, 25, "/tB/Modules/DateTime/Date", "= Date: the property, not the type"],
[43, 18, "/Reference/Data-Types#date", "As Date: the type, not the property"],
];
for (const [line, column, url, what] of CASES) {
test(`F1 on ${what} (${line}:${column})`, async () => {
await at(c, line, column);
await f1Shows(url);
});
}
test("in a page of 1600 by 1000 the pane first floats at 480 by 640, inside the page", async () => {
const box = await floatingBox(c);
assert.ok(box, "the pane is not floating");
assert.deepEqual([box.width, box.height], [480, 640], JSON.stringify(box));
assert.equal(boxFault(box), "", JSON.stringify(box));
});
test("a selection is looked up as selected", async () => {
// "Print" alone is the bare name, where the cursor would give Debug.Print.
await select(c, { startLine: 7, startColumn: 15, endLine: 7, endColumn: 20 });
await sleep(100);
await f1Shows("/tB/Core/Print");
});
test("a name with no page says so and leaves the page", async () => {
const was = await frameSrc(c);
await at(c, 8, 13);
await pressKey(c, "F1");
const text = "No help for 'zzqHelpProbe'";
const shown = await waitFor(c, async (c) => (await notifications(c)).find((t) => t.trim() === text));
assert.ok(shown, `notifications: ${JSON.stringify(await notifications(c))}`);
await sleep(300);
assert.equal(await frameSrc(c), was);
});
test("F1 with no name at the cursor puts the focus in the search box", async () => {
await at(c, 3, 3);
await pressKey(c, "F1");
assert.equal(await waitFor(c, async (c) => (await focusedId(c)) === "helpSearch" && "helpSearch"), "helpSearch");
});
// P15: the compiler's hover gives a name's [Description]. A name declared
// where the documentation has no page shows that in place of the page.
test("a name the project declares shows its declaration and description, though a package has a page for it", async () => {
// Cases.Beep, not VBA.Interaction.Beep.
await f1Summary(18, 10, {
declaration: "Sub Beep ( )",
description: "Sounds the project's own tone.",
where: "Declared in HelpHost.Cases",
});
});
test("a procedure of the project with no [Description] shows its declaration", async () => {
await f1Summary(36, 22, {
declaration: "Function Plain ( ) As Long",
description: "No description.",
where: "Declared in HelpHost.Cases",
});
});
test("a class of the project shows its description, without its members", async () => {
await f1Summary(35, 24, {
declaration: "class Gadget",
description: "A gadget of the project's own.",
where: "Declared in HelpHost",
});
});
test("F1 on a procedure's own name where it is declared says so, and leaves the pane", async () => {
const was = await summary(c);
await at(c, 27, 17);
await pressKey(c, "F1");
const text = "No help for 'Beep': it is declared here";
const shown = await waitFor(c, async (c) => (await notifications(c)).find((t) => t.trim() === text));
assert.ok(shown, `notifications: ${JSON.stringify(await notifications(c))}`);
await sleep(300);
assert.deepEqual(await summary(c), was);
});
test("a member of a late-bound object lists its pages, and a click shows one", async () => {
// o.Add, o As Object: the compiler cannot tell either, so every page of an
// Add is listed.
await at(c, 17, 12);
const was = await frameSrc(c);
await pressKey(c, "F1");
// A list read as soon as it had items once held 3 of the 12, so wait until
// it has stopped changing for a second.
let list = "";
let since = 0;
const items = await waitFor(c, async (c) => {
const r = await results(c);
if (JSON.stringify(r) !== list) [list, since] = [JSON.stringify(r), Date.now()];
return r.length > 0 && Date.now() - since >= 1000 && r;
});
// The index has 12 Add pages; those of the packages the project does not
// reference are not offered.
assert.equal(items?.length, 6, JSON.stringify(items));
assert.ok(items.includes("Collection.Addmethod") && items.includes("ToolWindows.Addmethod"), JSON.stringify(items));
assert.equal(await searchValue(c), "o.Add");
assert.equal(await frameSrc(c), was, "a list must not change the page");
await f1Shows("/tB/Modules/Collection/Add", () =>
click(c, { toolWindow: PANE, css: "#helpResults .hit .label", text: "Collection.Add" }),
);
});
test("the search box finds names as typed, and Enter shows the first", async () => {
await emptySearch(c);
await typeText(c, "msgbo");
const items = await waitFor(c, async (c) => {
const r = await results(c);
return r[0] === "Interaction.MsgBoxfunction" && r;
});
assert.ok(items, JSON.stringify(await results(c)));
await f1Shows("/tB/Modules/Interaction/MsgBox", () => pressKey(c, "Enter"));
});
test("a search that matches nothing says so", async () => {
await emptySearch(c);
await typeText(c, "zzqq");
assert.ok(
await waitFor(c, async (c) => (await results(c)).join() === "No matches"),
JSON.stringify(await results(c)),
);
// The list draws its rows a moment after it has them: no row has a height yet.
const box = await waitFor(c, async (c) => (await resultsBox(c))?.row > 0 && (await resultsBox(c)));
assert.ok(box && Math.abs(box.height - box.row) < 1 && !box.scrollbar, JSON.stringify(await resultsBox(c)));
});
test("the results list is as tall as its rows, up to 35% of the pane", async () => {
await emptySearch(c);
await typeText(c, "msgbo");
// The add-in fills the list before it shows it, so wait for both.
const few = await waitFor(c, async (c) => {
const r = await results(c);
return r.length > 0 && r[0] === "Interaction.MsgBoxfunction" && (await resultsBox(c))?.row > 0 && r.length;
});
let box = await resultsBox(c);
assert.ok(
box.height < 0.3 * box.pane && Math.abs(box.height - few * box.row) < 1 && !box.scrollbar,
JSON.stringify({ few, box }),
);
// "a" finds the search's limit of 100, far more than 35% of the pane holds.
await emptySearch(c);
await typeText(c, "a");
box = await waitFor(c, async (c) => {
const b = await resultsBox(c);
return b && (await results(c)).length > 0 && b.scrollbar && b;
});
assert.ok(box && Math.abs(box.height - 0.35 * box.pane) < 1, JSON.stringify(box));
});
// The list's own height is its rows (the two tests before), so the line
// between it and the page is the page's top border, and only while it shows.
test("the page is under a line in the theme's text colour at 40% while the list shows, and the line goes with the list", async () => {
await emptySearch(c);
await typeText(c, "msgbo");
assert.ok(await waitFor(c, async (c) => (await resultsBox(c))?.row > 0), "the list did not show");
let got = await paneSeparator(c);
assert.ok(got.listShown, JSON.stringify(got));
assert.equal(separatorFault(got), "", JSON.stringify(got));
await emptySearch(c);
assert.ok(await waitFor(c, async (c) => (await resultsBox(c)) === null), "the list did not hide");
got = await paneSeparator(c);
assert.ok(!got.listShown, JSON.stringify(got));
assert.equal(separatorFault(got), "", JSON.stringify(got));
});
test("the search box's clear button hides the results", async () => {
await emptySearch(c);
await typeText(c, "zzqq");
assert.ok(await waitFor(c, async (c) => (await results(c)).join() === "No matches"));
// The clear button is drawn at the box's right end, inside its padding.
const r = await elementRect(c, { toolWindow: PANE, css: "#helpSearch" });
await clickAt(c, r.x + r.width - 14, r.y + r.height / 2);
assert.equal(await searchValue(c), "", "the click missed the clear button");
assert.ok(await waitFor(c, async (c) => (await resultsBox(c)) === null), JSON.stringify(await resultsBox(c)));
});
test("the toolbar's Help button puts the focus in the search box", async () => {
await at(c, 7, 21);
await click(c, "addinButton-tbDocsHelp");
assert.equal(await waitFor(c, async (c) => (await focusedId(c)) === "helpSearch" && "helpSearch"), "helpSearch");
});
// The IDE draws the pane's header, the tool-window header the detached
// window's title bar copies; what a copy has to match is read here, while the
// pane shows.
let paneHeader;
test("the pane's header is the IDE's tool-window header", async () => {
paneHeader = await c.evaluate(`(() => {
const h = [...document.querySelectorAll("#ADDIN_${PANE} .sectionHeader")]
.find((e) => e.textContent.trim() === "TWINBASIC HELP");
if (!h) return null;
const s = getComputedStyle(h);
return {
height: h.getBoundingClientRect().height,
look: { backgroundColor: s.backgroundColor, color: s.color, fontSize: s.fontSize, fontWeight: s.fontWeight, paddingTop: s.paddingTop, paddingBottom: s.paddingBottom },
};
})()`);
assert.ok(paneHeader, "no header for the pane");
});
test("Open in browser opens the page the pane shows", async () => {
const mark = await consoleMark(c);
await click(c, { toolWindow: PANE, css: "#helpBrowser" });
const urls = await waitFor(c, async (c) => {
const u = await openedUrls(c, { since: mark });
return u.length > 0 && u;
});
assert.deepEqual(urls, [`${origin}/tB/Modules/Interaction/MsgBox`]);
});
// The background, since it is not inherited: the IDE gives the tool window
// the theme's text colour already, so the pane's would match with no CSS.
test("the pane's colours are the IDE theme's", async () => {
const colours = await inPane(
c,
`const probe = document.createElement("div");
probe.style.background = "var(--themeGeneralPanelBackColor)";
document.body.appendChild(probe);
const theme = getComputedStyle(probe).backgroundColor;
probe.remove();
return { theme, pane: getComputedStyle(root.querySelector("#helpWrap")).backgroundColor };`,
);
assert.ok(colours.theme && colours.theme !== "rgba(0, 0, 0, 0)", JSON.stringify(colours));
assert.equal(colours.pane, colours.theme);
});
// Through the IDE's own commands for its theme menu, which tell the compiler,
// and so the add-in, of the change (OnChangedTheme). The IDE's save of the
// theme, where the user's own IDE reads it, is guarded by the
// --no-save-ide-settings every harness IDE has (IDE_FLAGS in
// scripts/lib/tb-ide.mjs), so the registry keeps the user's theme. The test
// switches it back at the end for the tests after it.
test("a theme change loads the page again in the new theme", async () => {
const page = "/tB/Modules/Interaction/MsgBox";
const was = await themeGroup(c);
const other = was === "dark" ? "light" : "dark";
const switchTo = (group) =>
c.evaluate(
`executeIdeCommand(${JSON.stringify(group === "dark" ? "tbTheme_SwitchToDarkMode" : "tbTheme_SwitchToLightMode")})`,
);
try {
await switchTo(other);
assert.equal(await themeGroup(c), other, "the IDE's theme did not change");
await showsPage(page);
} finally {
await switchTo(was);
}
await showsPage(page);
});
test("a compiler restart empties the pane, and the add-in puts its page back", async () => {
// The old frame is marked, so that the frame found after is the new pane's.
await inPane(c, `root.querySelector("#helpPage").dataset.beforeRestart = "1";`);
const mark = await consoleMark(c);
await lane.restartCompiler();
pages = await pagesOrigin(mark);
const src = await waitFor(c, (c) =>
inPane(
c,
`const f = root.querySelector("#helpPage"); return f && !f.dataset.beforeRestart && f.getAttribute("src");`,
),
);
assert.equal(src, `${pages}/tB/Modules/Interaction/MsgBox?theme=${await themeGroup(c)}&pane=1`);
});
// A page reached from the pane's page has no parameters of its own; the site
// keeps both for the tab.
test("a page reached by a link keeps the IDE's theme and the pane's layout", async () => {
await f1Shows("/tB/Modules/Interaction/MsgBox", () => at(c, 5, 9).then(() => pressKey(c, "F1")));
const next = "/tB/Modules/Strings/Len";
await frameEval(c, pages, `location.href = ${JSON.stringify(next)}`);
const loaded = await waitFor(c, async (c) => {
const f = await frameOf(c, pages);
if (f?.url !== `${pages}${next}`) return false;
return (await frameEval(c, pages, `document.readyState === "complete"`).catch(() => false)) === true;
});
assert.ok(loaded, `the frame did not load ${next}: ${JSON.stringify(await frameOf(c, pages))}`);
assert.equal(
await frameEval(c, pages, `document.documentElement.getAttribute("data-theme")`),
await themeGroup(c),
"the page's theme",
);
assert.deepEqual(await paneChrome(), PANE_CHROME, "the site's chrome in the pane");
});
// In both of the IDE's groups, with the frame preferring the other colour
// scheme: the page F1 shows, the same page given again by a theme change,
// and a page reached by a link from either. The pane's frame is on the IDE
// page's own site, so it is in the IDE page's frame tree, and the scheme is
// emulated on the IDE's page.
test("the pane's page has the IDE's theme in Light and Dark, after a link too, whatever the frame's colour scheme", async () => {
const was = await themeGroup(c);
const page = "/tB/Modules/Interaction/MsgBox";
const next = "/tB/Modules/Strings/Len";
const paneDocs = async (group) => {
await preferOther(c, group);
return frameEval(c, pages, DOCS_STATE).catch(() => null);
};
const faults = [];
try {
for (const group of [was, otherScheme(was)]) {
if (group === was) {
await f1Shows(page, () => at(c, 5, 9).then(() => pressKey(c, "F1")));
} else {
await markFrame();
await switchTheme(group);
assert.equal(await themeGroup(c), group, "the IDE's theme did not change");
await showsPage(page, { fresh: true });
}
faults.push(docsThemeFault(await paneDocs(group), group, `${group}, the page given`));
await frameEval(c, pages, `location.href = ${JSON.stringify(next)}`);
const linked = await waitFor(c, async () => {
const s = await paneDocs(group);
return s?.url === next && s.ready && s;
});
faults.push(docsThemeFault(linked || (await paneDocs(group)), group, `${group}, after a link`));
}
assert.deepEqual(faults.filter(Boolean), []);
} finally {
await c.send("Emulation.setEmulatedMedia", { features: [] });
await switchTheme(was);
}
await showsPage(page);
});
// Hover help: links in the IDE's own hover under the mouse, while the pane's
// box is ticked.
const hoverBox = () => inPane(c, `return root.querySelector("#helpHover")?.checked ?? null;`);
// The settings panel, in the pane (inPane) and in the window's page (its
// `root` is the document): what the gear says, and whether the panel and the
// shade under it show.
const SETTINGS_STATE = `const g = root.querySelector("#helpSettings");
const p = root.querySelector("#helpSettingsPanel");
const s = root.querySelector("#helpSettingsShade");
if (!g || !p || !s) return null;
return {
expanded: g.getAttribute("aria-expanded"),
panel: getComputedStyle(p).display !== "none",
shade: getComputedStyle(s).display !== "none",
};`;
const SETTINGS_OPEN = { expanded: "true", panel: true, shade: true };
const SETTINGS_CLOSED = { expanded: "false", panel: false, shade: false };
const paneSettings = () => inPane(c, SETTINGS_STATE);
const windowSettings = () => win.evaluate(`(() => { const root = document; ${SETTINGS_STATE} })()`);
// Waits for a view's panel to be in `want`, which the add-in sets a moment
// after the click, and fails with what it was.
async function settingsBecome(read, want, what) {
await waitFor(c, async () => JSON.stringify(await read()) === JSON.stringify(want));
assert.deepEqual(await read(), want, what);
}
// The look the panel has to have, in the pane (`root`) or in the window's
// page: the theme's panel colours and border, read from elements the theme's
// own properties are applied to.
const PANEL_LOOK = `(() => {
const look = (e) => { const s = getComputedStyle(e); return { background: s.backgroundColor, color: s.color, border: s.borderTopColor, borderStyle: s.borderTopStyle, borderWidth: s.borderTopWidth }; };
const probe = document.createElement("div");
probe.style.cssText = "background: var(--themeGeneralPanelBackColor); color: var(--themeToolWindowBodyForeColor); border: var(--themePropertySheetValueBorderColor)";
(root.querySelector("#helpWrap") ?? root.body).appendChild(probe);
const want = look(probe);
probe.remove();
return { want, got: look(root.querySelector("#helpSettingsPanel")) };
})()`;
const paneLook = () => inPane(c, `return ${PANEL_LOOK};`);
const windowLook = () => win.evaluate(`(() => { const root = document; return ${PANEL_LOOK}; })()`);
// Where the panel, the gear and the shade are, and what a click at the
// panel's centre and at the page's would reach: the panel's own element, or
// the shade.
const SETTINGS_PLACE = `const box = (e) => { const r = e.getBoundingClientRect(); return [r.left, r.top, r.right, r.bottom].map(Math.round); };
const g = root.querySelector("#helpSettings");
const p = root.querySelector("#helpSettingsPanel");
const page = root.querySelector("#helpPage").getBoundingClientRect();
const hitAt = (x, y) => { const e = root.elementFromPoint(x, y); return e?.closest("#helpSettingsPanel") ? "panel" : e?.id ?? null; };
const r = p.getBoundingClientRect();
return {
gear: box(g),
panel: box(p),
wrap: box(root.querySelector("#helpWrap")),
row: p.contains(root.querySelector("#helpHoverLabel")),
panelHit: hitAt(r.left + r.width / 2, r.top + r.height / 2),
pageHit: hitAt(page.left + page.width / 2, page.top + page.height / 2),
};`;
const panePlace = () => inPane(c, SETTINGS_PLACE);
const windowPlace = () => win.evaluate(`(() => { const root = document; ${SETTINGS_PLACE} })()`);
// What a view's panel has to look like open: right-aligned with the gear
// and under it, inside the view, on top of everything else; and the shade
// over the page.
function assertPlace(place, what) {
const [gl, gt, gr, gb] = place.gear;
const [pl, pt, pr, pb] = place.panel;
const [wl, wt, wr, wb] = place.wrap;
assert.equal(pr, gr, `${what}: the panel is not right-aligned with the gear`);
assert.ok(pt >= gb, `${what}: the panel is not under the gear: ${JSON.stringify(place)}`);
assert.ok(
pl >= wl && pr <= wr && pb <= wb && gt >= wt && gl >= wl,
`${what}: the panel is cut off: ${JSON.stringify(place)}`,
);
assert.ok(place.row, `${what}: the Hover help row is not in the panel`);
assert.equal(place.panelHit, "panel", `${what}: something is over the panel`);
assert.equal(place.pageHit, "helpSettingsShade", `${what}: the shade is not over the page`);
}
// Ticks or unticks one of the pane's boxes, which are in the settings
// panel: opens the panel, clicks the box, checks the panel is still open,
// and closes it with the gear.
async function clickSettingBox(css) {
await click(c, { toolWindow: PANE, css: "#helpSettings" });
await settingsBecome(paneSettings, SETTINGS_OPEN, "the gear did not open the panel");
await click(c, { toolWindow: PANE, css });
assert.deepEqual(await paneSettings(), SETTINGS_OPEN, "the panel closed when the box was clicked");
await click(c, { toolWindow: PANE, css: "#helpSettings" });
await settingsBecome(paneSettings, SETTINGS_CLOSED, "the gear did not close the panel");
}
const clickHoverBox = () => clickSettingBox("#helpHover");
const clickAllBox = () => clickSettingBox("#helpAllPackages");
// The All packages box in the pane, and in the window's page.
const allBox = () => inPane(c, `return root.querySelector("#helpAllPackages")?.checked ?? null;`);
const windowAllBox = () => win.evaluate(`document.getElementById("helpAllPackages").checked`);
// The two page-side fixes: a box each in the settings panel, and what the
// fix's script leaves on the IDE's page while it is on.
const FIXES = [
{ box: "helpKeysOn", global: "tbDocsAddinKeys", label: "Ctrl and Alt shortcuts of add-ins" },
{ box: "helpFindOn", global: "tbDocsTextFind", label: "Find in the shortcut editors" },
];
const paneFixBox = (id) => inPane(c, `return root.querySelector("#helpSettingsPanel #${id}")?.checked ?? null;`);
const windowFixBox = (id) => win.evaluate(`document.getElementById(${JSON.stringify(id)}).checked`);
const fixInstalled = (name) => c.evaluate(`!!window.${name}`);
// Waits for the results to be `want`, a function of the rows, and fails with the rows.
async function resultsBecome(want, what) {
const rows = await waitFor(c, async (c) => {
const r = await results(c);
return want(r) && r;
});
assert.ok(rows, `${what}: ${JSON.stringify(await results(c))}`);
return rows;
}
const NO_MATCHES = (r) => r.join() === "No matches";
// The eight Waynes... controls are in CustomControls, and no other name has
// "Waynes" in it.
const HAS_WAYNES = (r) => r.some((t) => t.startsWith("CustomControlsPackage.Waynes"));
// A class's hover lists its members, and is taller than the room below it.
const COLLECTION_LINK = "Help: Collection class (VBA)";
const LEN_LINK = "Help: Len function (VBA.Strings)";
// The pane floats over the middle of the code editor, where the mouse has to
// rest and click: move it against the window's right edge.
const paneAside = () =>
c.evaluate(`(() => {
const s = toolWindowsById[${JSON.stringify(PANE)}].shadowDom.host.closest(".floatingPanel");
if (!s) return null;
s.style.left = (innerWidth - s.getBoundingClientRect().width - 4) + "px";
return s.getBoundingClientRect().left;
})()`);
// The hover under the mouse at a place, once the IDE's own text is in it.
// The first hover after a compiler restart can come back empty, while the
// compiler is still starting, and stays empty however long the mouse rests;
// the mouse then rests again, once.
async function mouseHover(line, column, want = "in VBA.") {
await paneAside();
for (let attempt = 0; ; attempt++) {
await restMouse(c, line, column);
const t = await waitFor(c, async (c) => {
const t = await hoverText(c);
return t?.includes(want) && t;
});
if (t || attempt === 1) return t;
}
}
// The settings gear at the bar's right end opens a panel of rows under it.
test("the bar ends in a gear, drawn in the text colour, as tall and bordered as the other buttons", async () => {
const bar = await inPane(
c,
`const el = (id) => root.querySelector("#" + id);
const g = el("helpSettings"), d = el("helpDetach");
const gs = getComputedStyle(g), ds = getComputedStyle(d);