@jskit-ai/shell-web 0.2.38 → 0.2.40

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.
@@ -0,0 +1,262 @@
1
+ import assert from "node:assert/strict";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+ import test from "node:test";
6
+ import { fileURLToPath } from "node:url";
7
+ import { expect } from "@playwright/test";
8
+ import { sharedBrowserFixture } from "../../../tooling/testUtils/browserFixture.mjs";
9
+
10
+ // The page behind an open modal dialog is inert, as the WAI-ARIA dialog pattern has it and as the scrim already has it
11
+ // for the pointer: ShellLayout's app bar, navigation, main and FAB take no focus and are left out of the accessibility
12
+ // tree and of axe's checks, while Vuetify's overlay layer (the dialog, a menu opened in it, a second dialog, a
13
+ // snackbar) stays live. When the dialog closes the page is live again and focus is back on the element that opened it.
14
+ const SKIP = process.env.JSKIT_SHELL_WEB_BROWSER_INTEGRATION === "1"
15
+ ? false
16
+ : "set JSKIT_SHELL_WEB_BROWSER_INTEGRATION=1 to check the page behind a dialog is inert";
17
+ const FIXTURE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../fixtures/adaptive-shell");
18
+ // axe-core as the page runs it, with every WCAG 2.2 A and AA rule, target-size included, and the best practices.
19
+ const AXE_PATH = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
20
+ const STRICT_AXE_TAGS = Object.freeze(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa", "best-practice"]);
21
+ const open = sharedBrowserFixture({ fixtureRoot: FIXTURE_ROOT, configFile: "vite.config.mjs" });
22
+ const COMPACT = Object.freeze({ width: 390, height: 844 });
23
+ const EXPANDED = Object.freeze({ width: 1280, height: 900 });
24
+
25
+ async function openNotes(t, viewport) {
26
+ const { vite, browser } = await open(t);
27
+ const page = await browser.newPage({ baseURL: vite.baseURL, viewport, reducedMotion: "reduce" });
28
+ await page.goto("/home/notes");
29
+ await expect(page.getByTestId("fixture-note-edit")).toBeVisible();
30
+ return page;
31
+ }
32
+
33
+ // The button inside `locator` when it wraps one (a FAB), else the element itself.
34
+ function buttonOf(locator) {
35
+ return locator.locator("xpath=self::button | self::a | .//button | .//a").first();
36
+ }
37
+
38
+ // Focuses an element and presses Enter on it, as a keyboard user activates it.
39
+ async function activate(locator) {
40
+ await locator.focus();
41
+ await expect(locator).toBeFocused();
42
+ await locator.press("Enter");
43
+ }
44
+
45
+ // The parts of the page ShellLayout makes inert, and whether each is.
46
+ function readPageParts(page) {
47
+ return page.evaluate(() => [...document.querySelectorAll("[data-shell-page]")].map((part) => part.inert));
48
+ }
49
+
50
+ // Every part of the page, the app bar, the navigation and main at least, inert or else live.
51
+ async function expectPageInert(page, inert, message) {
52
+ await expect.poll(async () => {
53
+ const parts = await readPageParts(page);
54
+ return parts.length >= 3 && parts.every((part) => part === inert);
55
+ }, { message: `${message}: every part of the page ${inert ? "inert" : "live"}` }).toBe(true);
56
+ }
57
+
58
+ // Whether `locator`'s element takes focus when asked, as a keyboard and assistive technology ask.
59
+ function takesFocus(locator) {
60
+ return locator.evaluate((element) => {
61
+ element.focus();
62
+ return document.activeElement === element;
63
+ });
64
+ }
65
+
66
+ // The accessible names of the nodes assistive technology reaches, from Chromium's accessibility tree.
67
+ async function readAccessibleNames(page) {
68
+ const session = await page.context().newCDPSession(page);
69
+ try {
70
+ const { nodes } = await session.send("Accessibility.getFullAXTree");
71
+ return new Set(nodes.filter((node) => !node.ignored && node.name?.value).map((node) => node.name.value));
72
+ } finally {
73
+ await session.detach();
74
+ }
75
+ }
76
+
77
+ // axe over the whole document, strict: each result's node, and whether it lies behind the dialogs (anywhere but
78
+ // Vuetify's overlay layer, the document itself aside). `targets` are the nodes target-size judged as targets.
79
+ async function runStrictAxe(page) {
80
+ if (!(await page.evaluate(() => Boolean(globalThis.axe)))) {
81
+ await page.addScriptTag({ path: AXE_PATH });
82
+ }
83
+ return page.evaluate(async (tags) => {
84
+ const results = await globalThis.axe.run(document, { runOnly: { type: "tag", values: tags } });
85
+ const behind = (selector) => {
86
+ const element = document.querySelector(selector);
87
+ return Boolean(element) && element !== document.documentElement && element !== document.body &&
88
+ !element.closest(".v-overlay-container");
89
+ };
90
+ const nodesOf = (rules) => rules.flatMap((rule) => rule.nodes.map((node) => ({
91
+ rule: rule.id,
92
+ target: node.target.join(" "),
93
+ behind: behind(String(node.target[0]))
94
+ })));
95
+ return {
96
+ violations: nodesOf(results.violations),
97
+ incompleteBehind: nodesOf(results.incomplete).filter((node) => node.behind),
98
+ targets: nodesOf([...results.passes, ...results.violations, ...results.incomplete].filter((rule) => rule.id === "target-size"))
99
+ };
100
+ }, STRICT_AXE_TAGS);
101
+ }
102
+
103
+ // Waits for a dialog to finish opening: shown, with focus moved into it.
104
+ async function expectDialogOpen(page, dialog) {
105
+ await expect(dialog).toBeVisible();
106
+ await expect.poll(() => dialog.evaluate((element) => element.closest(".v-overlay")?.contains(document.activeElement)))
107
+ .toBe(true);
108
+ }
109
+
110
+ test("the page behind a dialog takes no focus and is skipped by assistive technology and strict axe, target-size included; closing it gives focus back to the FAB", {
111
+ skip: SKIP,
112
+ timeout: 120_000
113
+ }, async (t) => {
114
+ const page = await openNotes(t, COMPACT);
115
+ const fab = buttonOf(page.getByTestId("fixture-invite"));
116
+ const noteEdit = page.getByTestId("fixture-note-edit");
117
+ const behind = [
118
+ ["the note's Edit", noteEdit],
119
+ ["the note's link", page.getByTestId("fixture-note-link")],
120
+ ["the FAB", fab],
121
+ ["a navigation bar destination", page.getByTestId("jskit-shell-bottom-nav").getByRole("link").first()]
122
+ ];
123
+
124
+ // The FAB opens the dialog from v-model, so it has no activator for Vuetify to give focus back to.
125
+ await activate(fab);
126
+ const dialog = page.getByTestId("fixture-invite-dialog");
127
+ await expectDialogOpen(page, dialog);
128
+ for (const [name, element] of behind) {
129
+ assert.equal(await takesFocus(element), false, `${name} takes no focus behind the dialog`);
130
+ }
131
+ await expectDialogOpen(page, dialog);
132
+
133
+ const names = await readAccessibleNames(page);
134
+ for (const name of ["Edit note", "Supplier contacts", "Invite"]) {
135
+ assert.equal(names.has(name), false, `assistive technology reaches no "${name}" behind the dialog`);
136
+ }
137
+ assert.ok(names.has("Send invitation"), "assistive technology reaches the dialog's actions");
138
+
139
+ // The dialog's "Send invitation" sits where the FAB is: it is on top, and axe judges only the dialog's targets.
140
+ const send = page.getByTestId("fixture-invite-send");
141
+ assert.equal(
142
+ await send.evaluate((element) => {
143
+ const box = element.getBoundingClientRect();
144
+ return element.contains(document.elementFromPoint(box.right - 4, box.bottom - 4));
145
+ }),
146
+ true,
147
+ "the dialog's button is on top of the FAB"
148
+ );
149
+ const axe = await runStrictAxe(page);
150
+ assert.deepEqual(axe.violations, [], "strict axe finds no violation");
151
+ assert.deepEqual(axe.incompleteBehind, [], "strict axe has nothing to review behind the dialog");
152
+ assert.deepEqual(axe.targets.filter((node) => node.behind), [], "target-size judges no target behind the dialog");
153
+ assert.ok(axe.targets.some((node) => node.target.includes("fixture-invite-send")), "target-size judges the dialog's buttons");
154
+ await expectPageInert(page, true, "with the dialog open");
155
+ assert.deepEqual(
156
+ await page.evaluate(() => [...document.querySelectorAll(".v-overlay-container, .v-overlay--active")].map((element) => element.inert)),
157
+ [false, false],
158
+ "the overlay layer and the dialog stay live"
159
+ );
160
+
161
+ await activate(page.getByTestId("fixture-invite-cancel"));
162
+ await expect(dialog).toBeHidden();
163
+ await expectPageInert(page, false, "after the dialog closes");
164
+ await expect(fab).toBeFocused();
165
+ assert.equal(await takesFocus(noteEdit), true, "the note's Edit takes focus again");
166
+ await noteEdit.press("Enter");
167
+ await expect(page.getByTestId("fixture-notes-presses")).toHaveText("edit");
168
+ await page.close();
169
+ });
170
+
171
+ test("in a dialog, a select's menu works, a snackbar is announced and a second dialog leaves the first inert until it closes, focus going back to each opener", {
172
+ skip: SKIP,
173
+ timeout: 120_000
174
+ }, async (t) => {
175
+ const page = await openNotes(t, EXPANDED);
176
+ // On an expanded window the screen's primary action is the app bar's button.
177
+ const invite = page.getByTestId("fixture-invite");
178
+ await activate(invite);
179
+ const inviteDialog = page.getByTestId("fixture-invite-dialog");
180
+ await expectDialogOpen(page, inviteDialog);
181
+ await expectPageInert(page, true, "with the dialog open");
182
+
183
+ await page.getByTestId("fixture-invite-role").click();
184
+ const options = page.getByRole("listbox");
185
+ await expect(options).toBeVisible();
186
+ await options.getByRole("option", { name: "Editor" }).click();
187
+ await expect(options).toBeHidden();
188
+ await expect(page.getByTestId("fixture-invite-role")).toContainText("Editor");
189
+
190
+ await activate(page.getByTestId("fixture-invite-copy"));
191
+ const message = page.getByRole("status").filter({ hasText: "Invitation link copied." });
192
+ await expect(message).toBeVisible();
193
+ assert.equal(await message.evaluate((element) => Boolean(element.closest("[inert]"))), false, "the snackbar is live");
194
+ assert.ok((await readAccessibleNames(page)).has("Invitation link copied."), "assistive technology reaches the message");
195
+ await expectPageInert(page, true, "with a message over the dialog");
196
+
197
+ const remove = page.getByTestId("fixture-invite-remove");
198
+ await activate(remove);
199
+ const removeDialog = page.getByTestId("fixture-remove-dialog");
200
+ await expectDialogOpen(page, removeDialog);
201
+ const inertOf = (locator) => locator.evaluate((element) => element.closest(".v-overlay").inert);
202
+ assert.equal(await inertOf(inviteDialog), true, "the first dialog is inert under the second");
203
+ assert.equal(await inertOf(removeDialog), false, "the second dialog is live");
204
+ assert.equal(await takesFocus(page.getByTestId("fixture-invite-copy")), false, "the first dialog takes no focus");
205
+ const names = await readAccessibleNames(page);
206
+ assert.equal(names.has("Copy link"), false, "assistive technology skips the first dialog");
207
+ assert.ok(names.has("Keep"), "assistive technology reaches the second dialog");
208
+ await expectPageInert(page, true, "with two dialogs open");
209
+
210
+ await activate(page.getByTestId("fixture-remove-keep"));
211
+ await expect(removeDialog).toBeHidden();
212
+ assert.equal(await inertOf(inviteDialog), false, "the first dialog is live again");
213
+ await expect(remove).toBeFocused();
214
+ await expectPageInert(page, true, "with the first dialog still open");
215
+
216
+ await page.keyboard.press("Escape");
217
+ await expect(inviteDialog).toBeHidden();
218
+ await expectPageInert(page, false, "after both dialogs close");
219
+ await expect(invite).toBeFocused();
220
+ await page.close();
221
+ });
222
+
223
+ test("Vuetify's activator gets focus back, the shell's own error dialog makes the page inert too, and leaving the page with a dialog open leaves the next page live", {
224
+ skip: SKIP,
225
+ timeout: 120_000
226
+ }, async (t) => {
227
+ const page = await openNotes(t, COMPACT);
228
+
229
+ const details = page.getByTestId("fixture-note-details");
230
+ await activate(details);
231
+ const detailsDialog = page.getByTestId("fixture-details-dialog");
232
+ await expectDialogOpen(page, detailsDialog);
233
+ await expectPageInert(page, true, "with a dialog opened from its activator");
234
+ await page.keyboard.press("Escape");
235
+ await expect(detailsDialog).toBeHidden();
236
+ await expectPageInert(page, false, "after Escape");
237
+ await expect(details).toBeFocused();
238
+
239
+ // ShellErrorHost's dialog: one of JSKIT's own, rendered beside the layout rather than in the page.
240
+ const report = page.getByTestId("fixture-report-problem");
241
+ await activate(report);
242
+ const errorDialog = page.getByRole("dialog", { name: "Attention required" });
243
+ await expectDialogOpen(page, errorDialog);
244
+ await expectPageInert(page, true, "with the shell's error dialog open");
245
+ assert.equal(await takesFocus(page.getByTestId("fixture-note-edit")), false, "the note's Edit takes no focus");
246
+ assert.deepEqual((await runStrictAxe(page)).violations, [], "strict axe finds no violation");
247
+ await activate(errorDialog.getByRole("button", { name: "Close" }));
248
+ await expect(errorDialog).toBeHidden();
249
+ await expectPageInert(page, false, "after the error dialog closes");
250
+ await expect(report).toBeFocused();
251
+
252
+ await activate(buttonOf(page.getByTestId("fixture-invite")));
253
+ await expectDialogOpen(page, page.getByTestId("fixture-invite-dialog"));
254
+ await expectPageInert(page, true, "with the dialog open");
255
+ await activate(page.getByTestId("fixture-invite-contacts"));
256
+ await expect(page).toHaveURL(/\/home\/contacts$/u);
257
+ await expect(page.getByTestId("fixture-invite-dialog")).toHaveCount(0);
258
+ await expectPageInert(page, false, "on the page the dialog's link opened");
259
+ assert.equal(await page.locator(".v-overlay[inert]").count(), 0, "no dialog is left inert");
260
+ assert.equal(await takesFocus(page.locator("main a[href]").first()), true, "the next page takes focus");
261
+ await page.close();
262
+ });
@@ -0,0 +1,182 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import test from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+ import { expect } from "@playwright/test";
7
+ import { sharedBrowserFixture } from "../../../tooling/testUtils/browserFixture.mjs";
8
+
9
+ // A command button keeps keyboard focus while its action runs: ShellPageAction and ShellPrimaryAction with `pending`
10
+ // or `loading`, and any button with v-pending, read as unavailable, ignore a second activation and never hand focus to
11
+ // the page body, which is where a focused button that becomes `disabled` sends it in Chromium. Each test reaches the
12
+ // button with Tab, presses Enter, holds the action, then settles it.
13
+ const SKIP = process.env.JSKIT_SHELL_WEB_BROWSER_INTEGRATION === "1"
14
+ ? false
15
+ : "set JSKIT_SHELL_WEB_BROWSER_INTEGRATION=1 to check that pending actions keep keyboard focus";
16
+ const FIXTURE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../fixtures/adaptive-shell");
17
+ const open = sharedBrowserFixture({ fixtureRoot: FIXTURE_ROOT, configFile: "vite.config.mjs" });
18
+ const COMPACT = Object.freeze({ width: 390, height: 844 });
19
+ const EXPANDED = Object.freeze({ width: 1280, height: 900 });
20
+
21
+ async function openPage(t, viewport, url) {
22
+ const { vite, browser } = await open(t);
23
+ const page = await browser.newPage({ baseURL: vite.baseURL, viewport, reducedMotion: "reduce" });
24
+ await page.goto(url);
25
+ return page;
26
+ }
27
+
28
+ // Records, at every frame until read, each time focus is on the page body (or nowhere).
29
+ async function watchFocus(page) {
30
+ await page.evaluate(() => {
31
+ const lost = [];
32
+ let watching = true;
33
+ const sample = () => {
34
+ const active = document.activeElement;
35
+ if (!active || active === document.body || active === document.documentElement) {
36
+ lost.push(performance.now());
37
+ }
38
+ if (watching) {
39
+ requestAnimationFrame(sample);
40
+ }
41
+ };
42
+ requestAnimationFrame(sample);
43
+ globalThis.jskitPendingFocusWatch = () => {
44
+ watching = false;
45
+ return lost.length;
46
+ };
47
+ });
48
+ return () => page.evaluate(() => globalThis.jskitPendingFocusWatch());
49
+ }
50
+
51
+ // The button inside `locator` when it wraps one (a FAB), else the element itself.
52
+ function buttonOf(locator) {
53
+ return locator.locator("xpath=self::button | self::a | .//button | .//a").first();
54
+ }
55
+
56
+ // Presses Tab until `locator` has focus, as a keyboard user reaches it.
57
+ async function tabTo(page, locator, { max = 80 } = {}) {
58
+ await locator.waitFor({ state: "visible", timeout: 10_000 });
59
+ for (let presses = 0; presses <= max; presses += 1) {
60
+ if (await locator.evaluate((element) => element === document.activeElement)) {
61
+ return;
62
+ }
63
+ await page.keyboard.press("Tab");
64
+ }
65
+ throw new Error(`Tab never reached ${locator}`);
66
+ }
67
+
68
+ const presses = (page) => page.getByTestId("fixture-pending-presses");
69
+
70
+ // Tab to the action's button, press Enter, and check it while it runs: focused, unavailable, a second Enter ignored;
71
+ // then settle it and check focus stayed on it throughout.
72
+ async function checkPendingAction(page, { testId, name, running, idle }) {
73
+ const button = buttonOf(page.getByTestId(testId));
74
+ await tabTo(page, button);
75
+ const framesOnBody = await watchFocus(page);
76
+ await page.keyboard.press("Enter");
77
+ await expect(presses(page)).toContainText(`${name}=1`);
78
+ if (running) {
79
+ await expect(button).toContainText(running);
80
+ }
81
+ await expect(button).toBeFocused();
82
+ await expect(button).toHaveAttribute("aria-disabled", "true");
83
+ await expect(button).not.toHaveAttribute("disabled");
84
+ await page.keyboard.press("Enter");
85
+ await page.keyboard.press(" ");
86
+ await page.waitForTimeout(200);
87
+ await expect(presses(page)).toContainText(`${name}=1`);
88
+ await expect(button).toBeFocused();
89
+
90
+ await page.evaluate((action) => globalThis.settleFixtureAction(action), name);
91
+ if (idle) {
92
+ await expect(button).toContainText(idle);
93
+ }
94
+ await expect(button).not.toHaveAttribute("aria-disabled", "true");
95
+ await expect(button).toBeFocused();
96
+ assert.equal(await framesOnBody(), 0, `focus fell to the page body while ${name} was pending`);
97
+ }
98
+
99
+ test("page actions keep focus while they run: `pending`, and the primary one with `loading`", {
100
+ skip: SKIP,
101
+ timeout: 120_000
102
+ }, async (t) => {
103
+ const page = await openPage(t, EXPANDED, "/home/pending");
104
+ await expect(page.getByTestId("fixture-pending-sync")).toBeVisible();
105
+ await checkPendingAction(page, { testId: "fixture-pending-sync", name: "sync", running: "Syncing…", idle: "Sync" });
106
+ await checkPendingAction(page, { testId: "fixture-pending-save", name: "save" });
107
+ });
108
+
109
+ test("the screen's primary action keeps focus while it runs, as a FAB and as the bar's primary action", {
110
+ skip: SKIP,
111
+ timeout: 120_000
112
+ }, async (t) => {
113
+ for (const viewport of [COMPACT, EXPANDED]) {
114
+ const page = await openPage(t, viewport, "/home/pending");
115
+ await expect(page.getByTestId("fixture-pending-send")).toBeVisible();
116
+ await checkPendingAction(page, { testId: "fixture-pending-send", name: "send", running: "Sending…", idle: "Send" });
117
+ await page.close();
118
+ }
119
+ });
120
+
121
+ test("a dialog's v-pending action keeps focus, ignores a second press and focuses the field a refusal marks", {
122
+ skip: SKIP,
123
+ timeout: 120_000
124
+ }, async (t) => {
125
+ const page = await openPage(t, EXPANDED, "/home/pending-dialog");
126
+ await tabTo(page, page.getByTestId("fixture-open-invite"));
127
+ await page.keyboard.press("Enter");
128
+ const dialog = page.getByRole("dialog");
129
+ await expect(dialog).toBeVisible();
130
+ const send = page.getByTestId("fixture-send-invite");
131
+ await tabTo(page, send, { max: 8 });
132
+ const framesOnBody = await watchFocus(page);
133
+ await page.keyboard.press("Enter");
134
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("1");
135
+ await expect(send).toHaveText("Sending…");
136
+ await expect(send).toBeFocused();
137
+ await expect(send).toHaveAttribute("aria-disabled", "true");
138
+ await page.keyboard.press("Enter");
139
+ await page.waitForTimeout(200);
140
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("1");
141
+
142
+ await page.evaluate(() => globalThis.settleFixtureInvite("Already invited."));
143
+ await expect(dialog.getByText("Already invited.")).toBeVisible();
144
+ await expect(dialog.getByRole("textbox", { name: "Email" })).toBeFocused();
145
+ assert.equal(await framesOnBody(), 0, "focus fell to the page body while Send invite was pending");
146
+
147
+ // Accepted, focus stays on the button.
148
+ await tabTo(page, send, { max: 8 });
149
+ await page.keyboard.press("Enter");
150
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("2");
151
+ await page.evaluate(() => globalThis.settleFixtureInvite());
152
+ await expect(send).toHaveText("Send invite");
153
+ await page.waitForTimeout(100);
154
+ await expect(send).toBeFocused();
155
+
156
+ // A refusal that marks a radio group whose first choice is disabled focuses its first enabled choice.
157
+ await page.keyboard.press("Enter");
158
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("3");
159
+ await page.evaluate(() => globalThis.settleFixtureInvite("Choose a larger plan.", "plan"));
160
+ await expect(dialog.getByText("Choose a larger plan.")).toBeVisible();
161
+ await expect(dialog.getByRole("radio", { name: "Larger plan" })).toBeFocused();
162
+ });
163
+
164
+ test("a form's implicit submission does nothing while its v-pending submit button runs", {
165
+ skip: SKIP,
166
+ timeout: 120_000
167
+ }, async (t) => {
168
+ const page = await openPage(t, EXPANDED, "/home/pending-dialog");
169
+ await page.getByTestId("fixture-open-invite").click();
170
+ const name = page.getByRole("dialog").getByRole("textbox", { name: "Name" });
171
+ await name.fill("Ada");
172
+ await name.press("Enter");
173
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("1");
174
+ await expect(page.getByTestId("fixture-send-invite")).toHaveText("Sending…");
175
+ await name.press("Enter");
176
+ await page.waitForTimeout(200);
177
+ await expect(page.getByTestId("fixture-invite-presses")).toHaveText("1");
178
+ await page.evaluate(() => globalThis.settleFixtureInvite());
179
+ await expect(page.getByTestId("fixture-send-invite")).toHaveText("Send invite");
180
+ // Focus was never on the button, so the settled action leaves it in the field.
181
+ await expect(name).toBeFocused();
182
+ });
@@ -0,0 +1,151 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { vPending } from "../src/client/directives/vPending.js";
4
+
5
+ // The browser behaviour (focus kept, Enter ignored, a marked field focused) is in pendingAction.browser.test.js; these
6
+ // check the directive's own steps on stand-in elements.
7
+
8
+ function createDocument() {
9
+ return { activeElement: null };
10
+ }
11
+
12
+ // A field the refusal marked; the directive's selector for a focusable control leaves out a disabled one.
13
+ function createField(document, { visible = true, disabled = false } = {}) {
14
+ const field = {
15
+ matches: () => !disabled,
16
+ querySelector: () => null,
17
+ getClientRects: () => (visible ? [{}] : []),
18
+ focus() {
19
+ document.activeElement = field;
20
+ }
21
+ };
22
+ return field;
23
+ }
24
+
25
+ function createButton(document, { form = null, dialog = null } = {}) {
26
+ const attributes = new Map();
27
+ const listeners = [];
28
+ const button = {
29
+ ownerDocument: document,
30
+ form,
31
+ matches: () => true,
32
+ querySelector: () => null,
33
+ closest: () => dialog,
34
+ contains: (other) => other === button,
35
+ setAttribute: (name, value) => attributes.set(name, String(value)),
36
+ removeAttribute: (name) => attributes.delete(name),
37
+ getAttribute: (name) => attributes.get(name) ?? null,
38
+ addEventListener: (type, handler, capture) => listeners.push({ type, handler, capture }),
39
+ removeEventListener: (type, handler, capture) => {
40
+ const index = listeners.findIndex((entry) => entry.type === type && entry.handler === handler && entry.capture === capture);
41
+ if (index >= 0) listeners.splice(index, 1);
42
+ },
43
+ listeners,
44
+ click() {
45
+ const calls = [];
46
+ const event = {
47
+ currentTarget: button,
48
+ preventDefault: () => calls.push("preventDefault"),
49
+ stopImmediatePropagation: () => calls.push("stopImmediatePropagation")
50
+ };
51
+ for (const { handler } of listeners.filter((entry) => entry.type === "click")) handler(event);
52
+ return calls;
53
+ },
54
+ focus() {
55
+ document.activeElement = button;
56
+ }
57
+ };
58
+ return button;
59
+ }
60
+
61
+ function scope(fields) {
62
+ return { querySelectorAll: () => fields };
63
+ }
64
+
65
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 5));
66
+
67
+ test("a pending button reads as unavailable and cancels its activation until it settles", () => {
68
+ const document = createDocument();
69
+ const button = createButton(document);
70
+ vPending.mounted(button, { value: false });
71
+ assert.deepEqual(button.listeners.map(({ type, capture }) => [type, capture]), [["click", true]]);
72
+ assert.equal(button.getAttribute("aria-disabled"), null);
73
+ assert.deepEqual(button.click(), [], "an idle button's click goes through");
74
+
75
+ vPending.updated(button, { value: true, oldValue: false });
76
+ assert.equal(button.getAttribute("aria-disabled"), "true");
77
+ assert.deepEqual(button.click(), ["preventDefault", "stopImmediatePropagation"]);
78
+
79
+ vPending.updated(button, { value: false, oldValue: true });
80
+ assert.equal(button.getAttribute("aria-disabled"), null);
81
+ assert.deepEqual(button.click(), []);
82
+
83
+ vPending.beforeUnmount(button);
84
+ assert.equal(button.listeners.length, 0);
85
+ });
86
+
87
+ test("settling with focus on the button focuses the first visible, enabled field the refusal marked in its form", async () => {
88
+ const document = createDocument();
89
+ const hidden = createField(document, { visible: false });
90
+ const disabled = createField(document, { disabled: true });
91
+ const email = createField(document);
92
+ const button = createButton(document, { form: scope([hidden, disabled, email]) });
93
+ vPending.mounted(button, { value: true });
94
+ button.focus();
95
+ vPending.updated(button, { value: false, oldValue: true });
96
+ assert.equal(document.activeElement, button, "focus moves only once the refusal's errors have drawn");
97
+ await settled();
98
+ assert.equal(document.activeElement, email);
99
+ vPending.beforeUnmount(button);
100
+ });
101
+
102
+ test("outside a form the button's dialog, then the page, holds the marked fields", async () => {
103
+ const document = createDocument();
104
+ const inDialog = createField(document);
105
+ const dialogButton = createButton(document, { dialog: scope([inDialog]) });
106
+ vPending.mounted(dialogButton, { value: true });
107
+ dialogButton.focus();
108
+ vPending.updated(dialogButton, { value: false, oldValue: true });
109
+ await settled();
110
+ assert.equal(document.activeElement, inDialog);
111
+ vPending.beforeUnmount(dialogButton);
112
+
113
+ const onPage = createField(document);
114
+ Object.assign(document, scope([onPage]));
115
+ const barButton = createButton(document);
116
+ vPending.mounted(barButton, { value: true });
117
+ barButton.focus();
118
+ vPending.updated(barButton, { value: false, oldValue: true });
119
+ await settled();
120
+ assert.equal(document.activeElement, onPage);
121
+ vPending.beforeUnmount(barButton);
122
+ });
123
+
124
+ test("focus stays where it is when nothing is marked, when it left the button, or when the button goes", async () => {
125
+ const document = createDocument();
126
+ const accepted = createButton(document, { form: scope([]) });
127
+ vPending.mounted(accepted, { value: true });
128
+ accepted.focus();
129
+ vPending.updated(accepted, { value: false, oldValue: true });
130
+ await settled();
131
+ assert.equal(document.activeElement, accepted);
132
+ vPending.beforeUnmount(accepted);
133
+
134
+ const marked = createField(document);
135
+ const left = createButton(document, { form: scope([marked]) });
136
+ const elsewhere = createField(document);
137
+ vPending.mounted(left, { value: true });
138
+ elsewhere.focus();
139
+ vPending.updated(left, { value: false, oldValue: true });
140
+ await settled();
141
+ assert.equal(document.activeElement, elsewhere);
142
+ vPending.beforeUnmount(left);
143
+
144
+ const gone = createButton(document, { form: scope([marked]) });
145
+ vPending.mounted(gone, { value: true });
146
+ gone.focus();
147
+ vPending.updated(gone, { value: false, oldValue: true });
148
+ vPending.beforeUnmount(gone);
149
+ await settled();
150
+ assert.equal(document.activeElement, gone);
151
+ });