Files
jobboard/tests/js/chips.test.mjs
T
WolfandClaude bd7b20a0a8 Add the chip input for the rail's Company and Place fields
window.chipInput(root, {suggest, onChange, placeholder, label}) to the
contract in docs/plan-feed-filters.md: a combobox whose picks become
chips, suggest debounced and late answers dropped, Enter before the
answer picks its first, Escape that shuts the list stops there. Not
wired into the page yet; package G does that.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-29 21:58:34 +02:00

410 lines
15 KiB
JavaScript

// The chip input, static/chips.js, without a browser: `keyAction` and
// `unpicked` as functions, then the widget on a DOM stub just large enough
// for it, with the clock mocked for the 150 ms wait.
//
// node --test tests/js/*.test.mjs
//
// Node 22 takes files or globs, not a directory: `node --test tests/js/`
// fails with MODULE_NOT_FOUND.
import { test, beforeEach, afterEach, mock } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import vm from "node:vm";
// ------------------------------------------------------------ the DOM stub
class Node {
constructor(tag) {
this.tagName = tag.toUpperCase();
this.children = [];
this.parentNode = null;
this.attributes = new Map();
this.listeners = new Map();
this.hidden = false;
this.id = "";
this.value = "";
this._text = "";
this.classList = {
add: (c) => { const s = new Set(this.className.split(" ").filter(Boolean)); s.add(c); this.className = [...s].join(" "); },
contains: (c) => this.className.split(" ").includes(c),
};
this.className = "";
}
get textContent() { return this._text + this.children.map((c) => c.textContent).join(""); }
set textContent(t) { this.children = []; this._text = String(t); }
get lastChild() { return this.children[this.children.length - 1] || null; }
setAttribute(k, v) { this.attributes.set(k, String(v)); }
getAttribute(k) { return this.attributes.has(k) ? this.attributes.get(k) : null; }
removeAttribute(k) { this.attributes.delete(k); }
appendChild(c) { c.remove(); c.parentNode = this; this.children.push(c); return c; }
append(...cs) { for (const c of cs) this.appendChild(c); }
insertBefore(c, ref) {
c.remove();
c.parentNode = this;
const at = this.children.indexOf(ref);
this.children.splice(at < 0 ? this.children.length : at, 0, c);
}
replaceChildren(...cs) { for (const c of [...this.children]) c.remove(); this.append(...cs); }
remove() {
if (!this.parentNode) return;
const siblings = this.parentNode.children;
siblings.splice(siblings.indexOf(this), 1);
this.parentNode = null;
}
addEventListener(type, fn) {
if (!this.listeners.has(type)) this.listeners.set(type, []);
this.listeners.get(type).push(fn);
}
dispatchEvent(event) {
event.target ??= this;
for (let node = this; node && !event.stopped; node = node.parentNode) {
for (const fn of node.listeners.get(event.type) || []) fn(event);
}
return !event.defaultPrevented;
}
focus() {
const was = document.activeElement;
if (was === this) return;
document.activeElement = this;
if (was) was.dispatchEvent(new Event("blur"));
}
blur() { if (document.activeElement === this) { document.activeElement = null; this.dispatchEvent(new Event("blur")); } }
click() { this.dispatchEvent(new Event("click")); }
find(pred) {
for (const c of this.children) {
if (pred(c)) return c;
const deeper = c.find(pred);
if (deeper) return deeper;
}
return null;
}
findAll(pred, out = []) {
for (const c of this.children) { if (pred(c)) out.push(c); c.findAll(pred, out); }
return out;
}
}
class Event {
constructor(type, init = {}) { Object.assign(this, init); this.type = type; this.defaultPrevented = false; this.stopped = false; }
preventDefault() { this.defaultPrevented = true; }
stopPropagation() { this.stopped = true; }
}
const document = { activeElement: null, createElement: (tag) => new Node(tag) };
const window = {};
Object.assign(globalThis, { document, window });
vm.runInThisContext(readFileSync(new URL("../../app/static/chips.js", import.meta.url), "utf8"));
const { chipInput } = window;
const { keyAction, unpicked } = chipInput;
// ------------------------------------------------------------- keyAction
const state = (s) => ({ open: false, active: -1, count: 0, fresh: false, text: "", chips: 0, ...s });
test("arrows move through an open list and wrap at both ends", () => {
const open = state({ open: true, active: 0, count: 3, fresh: true, text: "ma" });
assert.deepEqual(keyAction(open, "ArrowDown"), { act: "move", to: 1, prevent: true });
assert.equal(keyAction({ ...open, active: 2 }, "ArrowDown").to, 0);
assert.equal(keyAction(open, "ArrowUp").to, 2);
assert.equal(keyAction({ ...open, active: 2 }, "ArrowUp").to, 1);
});
test("ArrowDown on a shut list opens it, if there is text to ask about", () => {
assert.equal(keyAction(state({ text: "ma" }), "ArrowDown").act, "open");
assert.equal(keyAction(state({ text: " " }), "ArrowDown"), null);
assert.equal(keyAction(state({ text: "ma" }), "ArrowUp"), null);
});
test("Enter picks the highlighted option, the first when none is", () => {
const open = state({ open: true, active: 2, count: 3, fresh: true, text: "ma" });
assert.deepEqual(keyAction(open, "Enter"), { act: "pick", to: 2, prevent: true });
assert.equal(keyAction({ ...open, active: -1 }, "Enter").to, 0);
});
test("Enter before the answer to the text asks now, and Enter on nothing is the browser's", () => {
assert.equal(keyAction(state({ open: true, count: 3, active: 0, text: "mal" }), "Enter").act, "ask");
assert.equal(keyAction(state({ fresh: true, text: "mal" }), "Enter").act, "ask");
assert.equal(keyAction(state({ text: "" }), "Enter"), null);
});
test("Escape shuts an open list and stops there; on a shut list it is the page's", () => {
assert.deepEqual(keyAction(state({ open: true, count: 1 }), "Escape"), { act: "shut", prevent: true, stop: true });
assert.equal(keyAction(state({}), "Escape"), null);
});
test("Backspace removes the last chip only from an empty field", () => {
assert.equal(keyAction(state({ chips: 2 }), "Backspace").act, "unchip");
assert.equal(keyAction(state({ chips: 2, text: "m" }), "Backspace"), null);
assert.equal(keyAction(state({ chips: 0 }), "Backspace"), null);
});
test("Tab shuts the list without picking, and letters are left alone", () => {
assert.deepEqual(keyAction(state({ open: true, count: 1 }), "Tab"), { act: "shut" });
assert.equal(keyAction(state({ open: true, count: 1 }), "j"), null);
});
test("unpicked drops what is a chip already and repeats of one value", () => {
const got = unpicked(
[{ value: "country:DK" }, { value: "region:skane" }, { value: "region:skane" }, { value: 7 }],
[{ value: "country:DK", label: "Denmark" }, { value: "7", label: "Seven" }],
);
assert.deepEqual(got.map((s) => s.value), ["region:skane"]);
assert.deepEqual(unpicked(null, []), []);
});
// ------------------------------------------------------------ the widget
let root, field, changes, asked, answers;
// `suggest` answers from `answers`, and a query in `slow` only when released.
function make(extra = {}) {
root = new Node("div");
changes = [];
asked = [];
const widget = chipInput(root, {
suggest: (q) => { asked.push(q); return answers(q); },
onChange: (items) => changes.push(items.map((i) => i.value)),
placeholder: "Place",
label: "Place",
...extra,
});
field = root.find((n) => n.tagName === "INPUT");
return widget;
}
const PLACES = [
{ value: "region:skane", label: "Skåne", hint: "region" },
{ value: "place:malmo", label: "Malmö", hint: 203 },
{ value: "place:lund", label: "Lund", hint: 88 },
];
const settle = () => new Promise((resolve) => setImmediate(resolve));
const list = () => root.find((n) => n.getAttribute("role") === "listbox");
const options = () => list().children;
const chips = () => root.findAll((n) => n.classList.contains("chip"));
function type(text) {
field.value = text;
field.dispatchEvent(new Event("input"));
}
function key(k) {
const e = new Event("keydown", { key: k });
field.dispatchEvent(e);
return e;
}
async function typeAndWait(text) {
type(text);
mock.timers.tick(150);
await settle();
}
beforeEach(() => {
mock.timers.enable({ apis: ["setTimeout"] });
document.activeElement = null;
answers = () => Promise.resolve(PLACES);
});
afterEach(() => mock.timers.reset());
test("the field is a combobox that controls a listbox", () => {
make();
assert.equal(field.getAttribute("role"), "combobox");
assert.equal(field.getAttribute("aria-expanded"), "false");
assert.equal(field.getAttribute("aria-controls"), list().id);
assert.equal(field.getAttribute("aria-label"), "Place");
assert.equal(field.placeholder, "Place");
assert.ok(root.classList.contains("chip-input"));
assert.equal(list().hidden, true);
});
test("suggest waits 150 ms after the last keystroke and is not asked for blank text", async () => {
make();
type("m");
mock.timers.tick(100);
type("ma");
mock.timers.tick(149);
assert.deepEqual(asked, []);
mock.timers.tick(1);
assert.deepEqual(asked, ["ma"]);
type(" ");
mock.timers.tick(500);
assert.deepEqual(asked, ["ma"]);
});
test("an answer shows the options with label and hint, the first highlighted", async () => {
make();
await typeAndWait("s");
assert.equal(field.getAttribute("aria-expanded"), "true");
assert.equal(list().hidden, false);
assert.equal(options().length, 3);
const [first, second] = options();
assert.equal(first.getAttribute("role"), "option");
assert.equal(first.textContent, "Skåneregion");
assert.equal(second.children[1].className, "chip-option-hint");
assert.equal(second.children[1].textContent, "203");
assert.equal(first.getAttribute("aria-selected"), "true");
assert.equal(field.getAttribute("aria-activedescendant"), first.id);
});
test("a late answer to an older query is dropped", async () => {
const release = {};
answers = (q) => new Promise((resolve) => { release[q] = () => resolve(q === "s" ? PLACES : [PLACES[0]]); });
make();
type("s");
mock.timers.tick(150);
type("sk");
mock.timers.tick(150);
release.sk();
await settle();
release.s();
await settle();
assert.deepEqual([...options()].map((o) => o.children[0].textContent), ["Skåne"]);
});
test("arrows move the highlight and Enter picks it", async () => {
make();
await typeAndWait("s");
key("ArrowDown");
key("ArrowDown");
assert.equal(field.getAttribute("aria-activedescendant"), options()[2].id);
assert.equal(key("Enter").defaultPrevented, true);
assert.deepEqual(changes, [["place:lund"]]);
});
test("Enter picks the first suggestion, empties the field and keeps focus", async () => {
const widget = make();
field.focus();
await typeAndWait("s");
key("Enter");
assert.deepEqual(widget.values(), [{ value: "region:skane", label: "Skåne" }]);
assert.equal(field.value, "");
assert.equal(document.activeElement, field);
assert.equal(list().hidden, true);
assert.equal(field.getAttribute("aria-expanded"), "false");
assert.equal(chips().length, 1);
assert.equal(chips()[0].getAttribute("aria-label"), "Remove Skåne");
assert.deepEqual(changes, [["region:skane"]]);
});
test("a suggestion already a chip is not offered again", async () => {
make();
await typeAndWait("s");
key("Enter");
await typeAndWait("s");
assert.deepEqual([...options()].map((o) => o.children[0].textContent), ["Malmö", "Lund"]);
});
test("Enter before the answer waits for it and picks its first", async () => {
const widget = make();
type("lund");
answers = () => Promise.resolve([PLACES[2]]);
key("Enter");
assert.deepEqual(asked, ["lund"]);
await settle();
assert.deepEqual(widget.values().map((i) => i.value), ["place:lund"]);
mock.timers.tick(500);
assert.deepEqual(asked, ["lund"], "the waiting query was not asked a second time");
});
test("text that matches no suggestion becomes no chip", async () => {
const widget = make();
answers = () => Promise.resolve([]);
await typeAndWait("zzz");
key("Enter");
await settle();
assert.deepEqual(widget.values(), []);
assert.equal(field.value, "zzz");
assert.deepEqual(changes, []);
assert.equal(list().hidden, true);
});
test("Escape shuts the list and keeps the key from the page; shut, it passes", async () => {
make();
await typeAndWait("s");
const e = key("Escape");
assert.equal(e.stopped, true);
assert.equal(list().hidden, true);
assert.equal(field.getAttribute("aria-activedescendant"), null);
assert.equal(key("Escape").stopped, false);
key("ArrowDown");
assert.equal(list().hidden, false, "ArrowDown brings the same list back");
});
test("Backspace in an empty field removes the last chip", async () => {
const widget = make();
widget.set([{ value: "country:DK", label: "Denmark" }, { value: "region:skane", label: "Skåne" }]);
key("Backspace");
assert.deepEqual(widget.values().map((i) => i.value), ["country:DK"]);
assert.deepEqual(changes, [["country:DK"]]);
field.value = "d";
key("Backspace");
assert.equal(widget.values().length, 1);
});
test("a chip's button removes it and gives the field focus", () => {
const widget = make();
widget.set([{ value: "country:DK", label: "Denmark" }, { value: "region:skane", label: "Skåne" }]);
chips()[0].click();
assert.deepEqual(widget.values().map((i) => i.value), ["region:skane"]);
assert.deepEqual(changes, [["region:skane"]]);
assert.equal(document.activeElement, field);
});
test("a click on an option picks it, and its mousedown keeps the field's focus", async () => {
const widget = make();
await typeAndWait("s");
const down = new Event("mousedown");
options()[1].dispatchEvent(down);
assert.equal(down.defaultPrevented, true);
options()[1].click();
assert.deepEqual(widget.values().map((i) => i.value), ["place:malmo"]);
});
test("leaving the field shuts the list, and a late answer does not open it", async () => {
let release;
answers = () => new Promise((resolve) => { release = () => resolve(PLACES); });
make();
field.focus();
type("s");
mock.timers.tick(150);
field.blur();
release();
await settle();
assert.equal(list().hidden, true);
assert.equal(field.getAttribute("aria-expanded"), "false");
});
test("a failed suggest shuts the list and makes no chip", async () => {
const widget = make();
answers = () => Promise.reject(new Error("down"));
await typeAndWait("s");
key("Enter");
await settle();
assert.equal(list().hidden, true);
assert.deepEqual(widget.values(), []);
});
test("set and clear do not call onChange, and values is a copy", () => {
const widget = make();
widget.set([{ value: "country:DK", label: "Denmark" }, { value: "country:DK", label: "Denmark" }, { value: "x" }]);
assert.deepEqual(widget.values(), [{ value: "country:DK", label: "Denmark" }, { value: "x", label: "x" }]);
assert.equal(chips().length, 2);
widget.values()[0].label = "changed";
assert.equal(widget.values()[0].label, "Denmark");
field.value = "left over";
widget.clear();
assert.deepEqual(widget.values(), []);
assert.equal(field.value, "");
assert.equal(chips().length, 0);
assert.deepEqual(changes, []);
});
test("two fields on one page have their own ids", () => {
make();
const first = list().id;
make();
assert.notEqual(list().id, first);
});