Files
pipelines/web/test/modal.test.mjs
T

449 lines
15 KiB
JavaScript

// Focused unit tests for the shared modal controller. A tiny DOM stub gives the
// controller the same surface it uses in the browser (attributes, children,
// focus and document listeners) without a test dependency or a live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
createModalController,
focusableElements,
initialFocusIndex,
isFocusable,
wrapFocusIndex,
} from "../src/modal.js";
class FakeElement {
constructor(tag = "div", document_ = null) {
this.tagName = tag.toUpperCase();
this.ownerDocument = document_;
this.nodeType = 1;
this.attributes = new Map();
this.children = [];
this.parentElement = null;
this.isConnected = false;
this.hidden = false;
this.disabled = false;
this.textContent = "";
}
getAttribute(name) {
return this.attributes.has(name) ? this.attributes.get(name) : null;
}
setAttribute(name, value) {
this.attributes.set(name, String(value));
}
hasAttribute(name) {
return this.attributes.has(name);
}
removeAttribute(name) {
this.attributes.delete(name);
}
append(...nodes) {
for (const node of nodes) {
if (node.parentElement) node.remove();
node.parentElement = this;
node.isConnected = true;
this.children.push(node);
}
}
replaceChildren(...nodes) {
for (const child of this.children) {
child.parentElement = null;
child.isConnected = false;
}
this.children = [];
this.append(...nodes);
}
replaceWith(next) {
const parent = this.parentElement;
if (!parent) return;
const index = parent.children.indexOf(this);
if (index === -1) return;
parent.children[index] = next;
next.parentElement = parent;
next.isConnected = true;
this.parentElement = null;
this.isConnected = false;
}
remove() {
const parent = this.parentElement;
if (!parent) return;
const index = parent.children.indexOf(this);
if (index !== -1) parent.children.splice(index, 1);
this.parentElement = null;
this.isConnected = false;
}
contains(node) {
if (node === this) return true;
return this.children.some((child) => child.contains(node));
}
querySelectorAll() {
const found = [];
const walk = (element) => {
for (const child of element.children) {
found.push(child);
walk(child);
}
};
walk(this);
return found;
}
querySelector(selector) {
return this.querySelectorAll(selector)[0] ?? null;
}
matches(selector) {
if (selector === "a[href]") return this.tagName === "A" && this.hasAttribute("href");
if (selector === "button") return this.tagName === "BUTTON";
if (selector === "[tabindex]") return this.hasAttribute("tabindex");
return false;
}
focus() {
this.ownerDocument.activeElement = this;
}
}
class FakeDocument {
constructor() {
this.body = new FakeElement("body", this);
this.body.isConnected = true;
this.activeElement = this.body;
this.byId = new Map();
this.bySelector = new Map();
this.listeners = new Map();
this.defaultView = { getComputedStyle: () => ({ display: "block", visibility: "visible" }) };
}
createElement(tag) {
return new FakeElement(tag, this);
}
register(selector, element) {
if (selector.startsWith("#")) this.byId.set(selector.slice(1), element);
this.bySelector.set(selector, element);
return element;
}
getElementById(id) {
return this.byId.get(id) ?? null;
}
querySelector(selector) {
return this.bySelector.get(selector) ?? null;
}
querySelectorAll(selector) {
const element = this.bySelector.get(selector);
return element ? [element] : [];
}
addEventListener(type, listener, capture = false) {
const key = `${type}:${capture ? "capture" : "bubble"}`;
const list = this.listeners.get(key) ?? [];
list.push(listener);
this.listeners.set(key, list);
}
removeEventListener(type, listener, capture = false) {
const key = `${type}:${capture ? "capture" : "bubble"}`;
const list = this.listeners.get(key) ?? [];
this.listeners.set(
key,
list.filter((candidate) => candidate !== listener),
);
}
listenerCount(type, capture = false) {
return (this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? []).length;
}
dispatch(type, event, capture = false) {
for (const listener of [...(this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? [])]) {
listener(event);
}
}
}
function harness({ fallback = false } = {}) {
const document_ = new FakeDocument();
const root = document_.register(".app-root", new FakeElement("div", document_));
document_.body.append(root);
const skip = document_.register(".skip-link", new FakeElement("a", document_));
skip.setAttribute("href", "#main");
document_.body.append(skip);
const layer = new FakeElement("div", document_);
document_.body.append(layer);
const title = document_.register("#detailTitle", new FakeElement("h1", document_));
title.setAttribute("tabindex", "-1");
root.append(title);
const pane = document_.register("#pane-main", new FakeElement("div", document_));
pane.setAttribute("tabindex", "-1");
root.append(pane);
const controller = createModalController({
document: document_,
layer,
background: root,
skipLinks: [skip],
supportsInert: () => !fallback,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return { document_, root, skip, layer, title, controller };
}
function button(document_, text, props = {}) {
const node = new FakeElement("button", document_);
node.textContent = text;
node.tagName = "BUTTON";
for (const [key, value] of Object.entries(props)) {
if (key === "disabled") node.disabled = value;
else if (key === "hidden") node.hidden = value;
else node.setAttribute(key, value);
}
return node;
}
function panelWith(document_, ...controls) {
const panel = new FakeElement("div", document_);
panel.setAttribute("role", "dialog");
panel.append(...controls);
return panel;
}
test("modal lifecycle cleanup runs once for direct close, closeAll and render-managed disappearance", () => {
const {document_,controller}=harness();
const closed=[];
controller.open("info",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("info")});
assert.equal(controller.close("info"),true);
assert.equal(controller.close("info"),false);
controller.open("again",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("again")});
controller.closeAll();
controller.stage("rendered",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("rendered")});
controller.reconcile();controller.reconcile();
assert.deepEqual(closed,["info","again","rendered"]);
assert.deepEqual(controller.stackIds(),[]);
});
test("focusable discovery keeps DOM order and excludes every unreachable form", () => {
const document_ = new FakeDocument();
const panel = new FakeElement("div", document_);
const first = button(document_, "first");
const disabled = button(document_, "disabled", { disabled: true });
const hidden = button(document_, "hidden", { hidden: true });
const ariaHidden = button(document_, "aria hidden", { "aria-hidden": "true" });
const inert = button(document_, "inert", { inert: "" });
const negative = button(document_, "negative", { tabindex: "-1" });
const nested = new FakeElement("div", document_);
nested.setAttribute("aria-hidden", "true");
nested.append(button(document_, "nested"));
const last = button(document_, "last");
panel.append(first, disabled, hidden, ariaHidden, inert, negative, nested, last);
assert.deepEqual(
focusableElements(panel).map((node) => node.textContent),
["first", "last"],
);
assert.equal(isFocusable(first, { root: panel }), true);
assert.equal(isFocusable(disabled, { root: panel }), false);
assert.equal(isFocusable(negative, { root: panel }), false);
});
test("Tab and Shift+Tab arithmetic wraps in both directions", () => {
assert.equal(wrapFocusIndex(2, 1, 3), 0);
assert.equal(wrapFocusIndex(0, -1, 3), 2);
assert.equal(wrapFocusIndex(1, 1, 3), 2);
assert.equal(wrapFocusIndex(1, -1, 3), 0);
assert.equal(wrapFocusIndex(-1, 1, 3), 0);
assert.equal(wrapFocusIndex(-1, -1, 3), 2);
assert.equal(wrapFocusIndex(0, 1, 0), -1);
assert.equal(initialFocusIndex(0), -1);
assert.equal(initialFocusIndex(2), 0);
});
test("a panel with no focusable control focuses the panel itself", () => {
const { document_, layer, controller } = harness();
const panel = panelWith(document_, button(document_, "disabled", { disabled: true }));
controller.open("empty", panel);
assert.equal(document_.activeElement, panel);
assert.equal(panel.getAttribute("tabindex"), "-1");
assert.equal(layer.children.includes(panel), true);
controller.close("empty");
assert.equal(document_.activeElement, document_.getElementById("detailTitle"));
});
test("opening the same id twice keeps one trigger and one set of listeners", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "open");
title.append(trigger);
trigger.focus();
const first = panelWith(document_, button(document_, "a"));
controller.open("same", first, { onClose: () => {} });
assert.equal(document_.listenerCount("keydown"), 1);
const second = panelWith(document_, button(document_, "b"));
const other = button(document_, "other");
title.append(other);
other.focus();
controller.open("same", second, { onClose: () => {} });
assert.equal(document_.listenerCount("keydown"), 1);
assert.equal(controller.stackIds().length, 1);
controller.close("same");
assert.equal(document_.activeElement, trigger, "the original opener is still the return target");
assert.equal(controller.listenerState().keydown, false);
});
test("a same-id re-render replaces the panel and keeps the focused control", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
const firstPanel = panelWith(document_, button(document_, "one"), button(document_, "two"));
controller.open("same", firstPanel, { onClose: () => {} });
const second = firstPanel.children[1];
second.focus();
const replacement = panelWith(document_, button(document_, "one again"), button(document_, "two again"));
controller.open("same", replacement, { onClose: () => {} });
assert.equal(controller.stackIds().length, 1);
assert.equal(document_.activeElement.textContent, "two again");
controller.close("same");
assert.equal(document_.activeElement, trigger);
});
test("a second overlay inerts the first and closing it restores the first", () => {
const { document_, root, skip, title, controller } = harness();
const firstTrigger = button(document_, "first trigger");
title.append(firstTrigger);
firstTrigger.focus();
const first = panelWith(document_, button(document_, "first control"));
controller.open("first", first);
assert.equal(root.getAttribute("inert"), "");
assert.equal(skip.getAttribute("aria-hidden"), "true");
const secondTrigger = button(document_, "second trigger");
title.append(secondTrigger);
secondTrigger.focus();
const second = panelWith(document_, button(document_, "second control"));
controller.open("second", second);
assert.equal(first.getAttribute("inert"), "");
assert.equal(second.hasAttribute("inert"), false);
assert.deepEqual(controller.stackIds(), ["first", "second"]);
controller.close("second");
assert.equal(first.hasAttribute("inert"), false, "the lower panel is interactive again");
assert.equal(root.getAttribute("inert"), "");
assert.equal(controller.isOpen("first"), true);
controller.close("first");
assert.equal(root.hasAttribute("inert"), false);
assert.equal(skip.hasAttribute("aria-hidden"), false);
assert.equal(controller.listenerState().keydown, false);
});
test("native inert and aria-hidden/tabindex restore the exact prior values", () => {
const { document_, root, skip, controller } = harness();
root.setAttribute("inert", "kept");
skip.setAttribute("aria-hidden", "false");
const trigger = button(document_, "trigger");
root.append(trigger);
trigger.focus();
controller.open("exact", panelWith(document_, button(document_, "ok")));
controller.close("exact");
assert.equal(root.getAttribute("inert"), "kept");
assert.equal(skip.getAttribute("aria-hidden"), "false");
});
test("the no-inert fallback hides the background, removes its tab stops and restores them", () => {
const { document_, root, skip, controller } = harness({ fallback: true });
const first = button(document_, "one", { tabindex: "3" });
const second = button(document_, "two");
const trigger = button(document_, "trigger");
root.append(first, second, trigger);
trigger.focus();
controller.open("fallback", panelWith(document_, button(document_, "inside")));
assert.equal(root.getAttribute("aria-hidden"), "true");
assert.equal(skip.getAttribute("aria-hidden"), "true");
assert.equal(first.getAttribute("tabindex"), "-1");
assert.equal(second.getAttribute("tabindex"), "-1");
assert.equal(document_.listenerCount("keydown"), 1);
assert.equal(document_.listenerCount("focusin", true), 1);
controller.close("fallback");
assert.equal(root.hasAttribute("aria-hidden"), false);
assert.equal(skip.hasAttribute("aria-hidden"), false);
assert.equal(first.getAttribute("tabindex"), "3");
assert.equal(second.hasAttribute("tabindex"), false);
assert.equal(document_.listenerCount("keydown"), 0);
assert.equal(document_.listenerCount("focusin", true), 0);
});
test("Tab from the last control wraps to the first; Shift+Tab wraps back", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
const first = button(document_, "first");
const last = button(document_, "last");
controller.open("trap", panelWith(document_, first, last));
last.focus();
const tab = {
key: "Tab",
shiftKey: false,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {},
};
document_.dispatch("keydown", tab);
assert.equal(document_.activeElement, first);
const shiftTab = {
key: "Tab",
shiftKey: true,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {},
};
document_.dispatch("keydown", shiftTab);
assert.equal(document_.activeElement, last);
});
test("Escape closes through the supplied callback and returns focus", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
let closed = 0;
controller.open("escape", panelWith(document_, button(document_, "ok")), {
onClose: () => {
closed += 1;
controller.close("escape");
},
});
const escape = {
key: "Escape",
defaultPrevented: false,
preventDefault() {},
stopPropagation() {},
};
document_.dispatch("keydown", escape);
assert.equal(closed, 1);
assert.equal(controller.isOpen("escape"), false);
assert.equal(document_.activeElement, trigger);
});