// test/elements/keep.test.ts
//
// The capture and restore of src/elements/keep.ts on plain shadow roots in a
// JSDOM document: what is noted, what is refused, and that nothing captured
// outlives the task. JSDOM lays nothing out, so a control is made to look
// rendered where the code asks; scripts/check-upgrade-focus.ts runs the real
// elements in real browsers.
import { describe, test, expect, beforeEach } from "bun:test";
import { JSDOM } from "jsdom";
const dom = new JSDOM("
", { url: "http://localhost/" });
const g = globalThis as any;
g.window = dom.window;
g.document = dom.window.document;
g.HTMLElement = dom.window.HTMLElement;
g.Element = dom.window.Element;
g.Node = dom.window.Node;
g.FocusEvent = dom.window.FocusEvent;
import { keeping, type KeepSpec } from "../../src/elements/keep";
const keep: KeepSpec = {
focus: (node) => (node.localName === "button" ? ((node as HTMLElement).dataset.id ?? null) : null),
scroll: (root) => ({ list: root.querySelector(".list") }),
};
// A host with an open shadow root holding buttons with these ids.
const host = (ids: string[]): { root: ShadowRoot; button: (id: string) => HTMLButtonElement } => {
const element = document.createElement("div");
document.body.append(element);
const root = element.attachShadow({ mode: "open" });
root.innerHTML = `
${ids.map((id) => ``).join("")}
`;
// JSDOM has no layout: every button counts as rendered.
root.querySelectorAll("button").forEach((button) => {
(button as any).getClientRects = () => [{}];
});
return { root, button: (id) => root.querySelector(`[data-id="${id}"]`) as HTMLButtonElement };
};
// The build: the old tree goes, a new one with these ids comes.
const rebuild = (root: ShadowRoot, ids: string[], disabled: string[] = []): void => {
root.innerHTML = `
${ids.map((id) => ``).join("")}
`;
root.querySelectorAll("button").forEach((button) => {
(button as any).getClientRects = () => [{}];
});
};
beforeEach(() => document.body.replaceChildren());
const keeper = keeping(keep);
const capture = (root: ShadowRoot) => keeper.capture(root, () => {});
describe("capture", () => {
test("nothing focused and nothing scrolled: nothing is kept", () => {
const { root } = host(["a", "b"]);
expect(capture(root)).toBeNull();
});
test("a focused control with a key is noted by its key, tag and role", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const withAnyTag = keeping({ focus: node => node.getAttribute("data-id") });
const kept = withAnyTag.capture(root, () => {});
expect(kept).not.toBeNull();
root.innerHTML = 'Other kind';
kept!(root);
expect(root.activeElement).toBeNull();
});
test("a focused control with no key is not noted", () => {
const { root, button } = host(["a", "b"]);
button("b").removeAttribute("data-id");
button("a"); // still keyed, not focused
(root.querySelector("button:not([data-id])") as HTMLElement).focus();
expect(capture(root)).toBeNull();
});
test("a key two controls share names neither", () => {
const { root, button } = host(["a", "b", "c"]);
button("c").dataset.id = "b";
(root.querySelector('[data-id="b"]') as HTMLElement).focus();
expect(capture(root)).toBeNull();
});
test("nothing captured outlives the task", async () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
(root.querySelector(".list") as HTMLElement).scrollTop = 40;
let expired = false;
const kept = keeper.capture(root, () => { expired = true; });
expect(kept).not.toBeNull();
await Promise.resolve();
expect(expired).toBe(true);
rebuild(root, ["a", "b"]);
const list = root.querySelector(".list") as HTMLElement;
Object.defineProperty(list, "scrollHeight", { value: 100 });
Object.defineProperty(list, "clientHeight", { value: 20 });
kept!(root);
expect(root.activeElement).toBeNull();
expect(list.scrollTop).toBe(0);
});
});
describe("restore", () => {
test("focus goes back to the control with the same key", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
kept(root);
expect(root.activeElement).toBe(button("b"));
});
test("by key, not by position", () => {
const { root, button } = host(["a", "b", "c"]);
button("a").focus();
const kept = capture(root)!;
rebuild(root, ["b", "c", "a"]);
kept(root);
expect(root.activeElement).toBe(button("a"));
});
test("a key the new tree does not have, or has twice, restores nothing", () => {
for (const next of [["a", "c"], ["a", "b", "b"]]) {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, next);
kept(root);
expect(root.activeElement).toBeNull();
}
});
test("a control whose role changed is another control", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
button("b").setAttribute("role", "link");
kept(root);
expect(root.activeElement).toBeNull();
});
test("a control disabled for assistive technology does not take focus back", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
button("b").setAttribute("aria-disabled", "true");
kept(root);
expect(root.activeElement).toBeNull();
});
test("a focusin a script made up does not drop the handoff", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
window.dispatchEvent(new FocusEvent("focusin"));
kept(root);
expect(root.activeElement).toBe(button("b"));
});
test("a focus taken in between is honoured, even one that is gone again", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
const field = document.createElement("input");
document.body.append(field);
field.focus();
field.remove();
expect(document.activeElement).toBe(document.body);
kept(root);
expect(root.activeElement).toBeNull();
});
test("focus held elsewhere is not taken", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
const field = document.createElement("input");
document.body.append(field);
field.focus();
kept(root);
expect(document.activeElement).toBe(field);
});
test("a built control keeps focus even if the arrival event did not reach the handoff", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const stop = (event: Event) => event.stopImmediatePropagation();
window.addEventListener("focusin", stop, true);
try {
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
button("a").focus();
kept(root);
expect(root.activeElement).toBe(button("a"));
} finally {
window.removeEventListener("focusin", stop, true);
}
});
test("after the restore nothing listens for focus any more", () => {
const { root, button } = host(["a", "b"]);
button("b").focus();
const removed: string[] = [];
const original = window.removeEventListener;
window.removeEventListener = function (type, listener, options) {
removed.push(type);
original.call(this, type, listener, options);
};
try {
const kept = capture(root)!;
rebuild(root, ["a", "b"]);
kept(root);
expect(removed).toContain("focusin");
expect(root.activeElement).toBe(button("b"));
} finally {
window.removeEventListener = original;
}
});
test("a scroller that cannot scroll that far is left alone", () => {
const { root } = host(["a"]);
const list = root.querySelector(".list") as HTMLElement;
list.scrollTop = 40;
const kept = capture(root);
// JSDOM keeps the assigned offset; the rebuilt scroller has no range.
expect(kept).not.toBeNull();
rebuild(root, ["a"]);
kept!(root);
expect((root.querySelector(".list") as HTMLElement).scrollTop).toBe(0);
});
});