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>
This commit is contained in:
WolfandClaude committed 2026-09-29 21:58:34 +02:00
1 parent 64f367cc18
commit bd7b20a0a8
3 files changed
+811

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
/* The chip input, static/chips.js: a box drawn as the rail's text fields
* (`.rail-fields input[type="text"]` in app.css), with the picks inside it
* as the rail's pressed tags and the suggestions in a list under it, as wide
* as the box, so it stays inside the rail. Only app.css's custom properties,
* so light and dark come with them.
*
* The rail styles every button with `#rail button:not(.linky)`, an id's
* weight, which would square the chips and clear their colour. `:not(#_)`
* matches everything and gives the chip rules an id's weight too, so they
* hold in the rail and anywhere else without naming it.
*/
.chip-input { position: relative; margin: 0 .3rem; }
.chip-box {
display: flex; flex-wrap: wrap; align-items: center; gap: .25rem;
min-height: 2rem; padding: .2rem .3rem;
border: 1px solid var(--line); border-radius: 3px;
background: var(--panel); color: var(--fg);
cursor: text;
}
/* The field's focus ring, on the box, since the box is what looks like the
field. Not `:focus-within`: a focused chip draws its own. */
.chip-box:has(.chip-text:focus) { outline: 2px solid var(--accent); outline-offset: 1px; }
/* Three classes to outweigh `.rail-fields input[type="text"]`, which would
give the text its own border and margin inside the box. */
.chip-input .chip-box input.chip-text {
flex: 1 1 4rem; width: auto; min-width: 3rem; min-height: 1.5rem;
margin: 0; padding: 0 .15rem;
border: 0; outline: none; background: none; color: inherit;
font: inherit; font-size: .84rem; line-height: normal;
}
/* A pick: the pressed tag of app.css's `#rail .tag[aria-pressed="true"]`,
the × in the colour of its count. The whole chip is the remove button,
as on the agent form's chips. */
.chip-input:not(#_) .chip-box button.chip {
display: inline-flex; align-items: center; gap: .3rem;
max-width: 100%; min-width: 0; min-height: 0;
padding: .06rem .55rem; margin: 0;
font: inherit; font-size: .8rem; line-height: 1.45;
color: var(--panel); background: var(--accent);
border: 1px solid var(--accent); border-radius: 999px;
cursor: pointer;
}
.chip .chip-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip .chip-x { flex: none; color: var(--accent-weak); }
@media (hover: hover) {
.chip-input:not(#_) .chip-box button.chip:hover { color: var(--panel); background: var(--accent); }
.chip:hover .chip-x { color: var(--panel); }
}
.chip-list {
position: absolute; z-index: 3; left: 0; right: 0; top: calc(100% + 2px);
margin: 0; padding: .2rem 0; list-style: none;
max-height: min(16rem, 50vh); overflow-y: auto; overscroll-behavior: contain;
background: var(--panel); color: var(--fg);
border: 1px solid var(--line); border-radius: 3px;
box-shadow: 0 8px 24px rgb(0 0 0 / 18%);
}
.chip-option {
display: flex; align-items: baseline; gap: .5rem;
padding: .3rem .55rem; font-size: .84rem; line-height: 1.35;
cursor: pointer;
}
.chip-option-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.chip-option-hint {
flex: none; margin-left: auto;
font-size: .76rem; color: var(--faint); font-variant-numeric: tabular-nums;
}
/* The highlighted option: the rail's pressed row. */
.chip-option[aria-selected="true"] {
background: color-mix(in srgb, var(--accent) 14%, transparent);
color: var(--accent); box-shadow: inset 3px 0 0 var(--accent);
}
/* Sizes for a finger, after app.css's own coarse block. 16px text so iOS
does not zoom in on focus. */
@media (pointer: coarse) {
.chip-box { min-height: 2.75rem; }
.chip-input .chip-box input.chip-text { font-size: 16px; min-height: 2.25rem; }
.chip-input:not(#_) .chip-box button.chip { min-height: 2.25rem; padding: .2rem .8rem; font-size: .88rem; }
.chip-option { align-items: center; min-height: 2.75rem; padding-block: .4rem; font-size: .92rem; }
}
+317
View File
@@ -0,0 +1,317 @@
/* A text field whose picks from a suggestion list become chips, several per
* field: the rail's Company and Place filters.
*
* const places = chipInput($("#f-place"), {
* suggest: (q) => api(`/api/suggest/places?q=${encodeURIComponent(q)}`)
* .then((rows) => rows.map((r) => ({ value: r.token, label: r.label, hint: r.count }))),
* onChange: (items) => setFilter({ places: items.map((i) => i.value) }),
* placeholder: "Place", label: "Place",
* });
* places.set([{ value: "country:DK", label: "Denmark" }]);
*
* `root` is an empty element; the field, its chips and the list are built in
* it. `suggest(q)` resolves to `[{value, label, hint}]` and is only asked for
* text that is not blank. Only a suggestion becomes a chip: a filter value has
* to be something the database holds, so text that matches nothing stays text
* and filters nothing.
*
* `suggest` is asked 150 ms after the last keystroke, and an answer is used
* only if nothing was typed since it was asked, so a slow answer to "ska"
* cannot replace the list for "skane". Enter before the answer for the text
* in the field has come asks at once and picks the first of that answer, so a
* fast typist gets what they typed and not what the list showed a letter ago.
*
* `onChange(items)` runs after the person adds or removes a chip. `set` and
* `clear` are the page's own changes (reading the address, the `c` key) and
* do not call it, so a page that reloads on `onChange` does not reload twice.
*
* The field is an `<input>`, which is what `roles.js` looks for to leave the
* page's letter keys alone. Escape that shuts the list stops there, so it does
* not also leave the field; with the list shut it goes on to the page.
*
* The keys are `keyAction`, a function of the field's state and the key with
* no DOM in it, so `tests/js/chips.test.mjs` can walk it without a browser.
*/
(function () {
"use strict";
const WAIT_MS = 150;
let made = 0;
/** The suggestions not already chips, each value once. */
function unpicked(suggestions, items) {
const taken = new Set(items.map((i) => String(i.value)));
const left = [];
for (const s of suggestions || []) {
const value = String(s.value);
if (taken.has(value)) continue;
taken.add(value);
left.push(s);
}
return left;
}
/* What a key does, from the field's state:
open the list is showing
active the highlighted option, -1 for none
count options in the list
fresh the list answers the text now in the field
text the field's text
chips how many chips there are
The answer is `null` for a key left to the browser, or `{ act, prevent,
stop }`: `prevent` is preventDefault and `stop` keeps the key from the
page's own shortcuts. `act` is one of
move highlight option `to`
pick make option `to` a chip
ask ask now and pick the first answer: Enter before the answer to
the text, or on a list that was shut
open show the list for the text (ArrowDown on a shut list)
shut hide the list
unchip remove the last chip */
function keyAction(s, key) {
const text = s.text.trim();
switch (key) {
case "ArrowDown":
if (s.open && s.count) return { act: "move", to: (s.active + 1) % s.count, prevent: true };
if (!s.open && text) return { act: "open", prevent: true };
return null;
case "ArrowUp":
if (s.open && s.count) {
return { act: "move", to: s.active <= 0 ? s.count - 1 : s.active - 1, prevent: true };
}
return null;
case "Enter":
if (!text) return null;
if (s.open && s.fresh && s.count) return { act: "pick", to: Math.max(s.active, 0), prevent: true };
return { act: "ask", prevent: true };
case "Escape":
return s.open ? { act: "shut", prevent: true, stop: true } : null;
case "Tab":
return s.open ? { act: "shut" } : null;
case "Backspace":
return !s.text && s.chips ? { act: "unchip" } : null;
default:
return null;
}
}
function el(tag, cls, text) {
const node = document.createElement(tag);
if (cls) node.className = cls;
if (text != null) node.textContent = text;
return node;
}
function hintText(hint) {
if (hint == null || hint === "") return "";
return typeof hint === "number" ? hint.toLocaleString("en-GB") : String(hint);
}
function chipInput(root, { suggest, onChange = () => {}, placeholder = "", label = "" } = {}) {
const id = `chip-input-${++made}`;
root.classList.add("chip-input");
const box = el("div", "chip-box");
const input = el("input", "chip-text");
input.type = "text";
input.autocomplete = "off";
input.spellcheck = false;
input.placeholder = placeholder;
input.setAttribute("autocapitalize", "off");
input.setAttribute("role", "combobox");
input.setAttribute("aria-autocomplete", "list");
input.setAttribute("aria-expanded", "false");
input.setAttribute("aria-controls", `${id}-list`);
if (label) input.setAttribute("aria-label", label);
box.appendChild(input);
const list = el("ul", "chip-list");
list.id = `${id}-list`;
list.setAttribute("role", "listbox");
if (label) list.setAttribute("aria-label", label);
list.hidden = true;
root.append(box, list);
/** @type {{value: string, label: string}[]} */
let items = [];
let shown = []; // the options in the list
let shownFor = null; // the text they answer
let active = -1;
let open = false;
let timer = null;
let asked = 0; // bumped by every change of text, so older answers are dropped
let pickFirst = false; // Enter came before the answer
const values = () => items.map((i) => ({ value: i.value, label: i.label }));
const changed = () => onChange(values());
function drawChips() {
for (const old of [...box.children]) if (old !== input) old.remove();
for (const item of items) {
const chip = el("button", "tag chip");
chip.type = "button";
chip.title = item.label;
chip.setAttribute("aria-label", `Remove ${item.label}`);
chip.append(el("span", "chip-label", item.label), el("span", "chip-x", "×"));
chip.lastChild.setAttribute("aria-hidden", "true");
chip.addEventListener("click", () => {
items = items.filter((i) => i !== item);
drawChips();
input.focus();
changed();
});
box.insertBefore(chip, input);
}
}
function highlight(i) {
active = i;
[...list.children].forEach((option, n) => option.setAttribute("aria-selected", String(n === i)));
const option = list.children[i];
if (option) {
input.setAttribute("aria-activedescendant", option.id);
if (option.scrollIntoView) option.scrollIntoView({ block: "nearest" });
} else {
input.removeAttribute("aria-activedescendant");
}
}
function shut() {
open = false;
list.hidden = true;
input.setAttribute("aria-expanded", "false");
highlight(-1);
}
function show() {
if (!shown.length) { shut(); return; }
list.replaceChildren(...shown.map((s, i) => {
const option = el("li", "chip-option");
option.id = `${id}-option-${i}`;
option.setAttribute("role", "option");
option.append(el("span", "chip-option-label", s.label));
const hint = hintText(s.hint);
if (hint) option.append(el("span", "chip-option-hint", hint));
// mousedown, not click, is where the field would lose focus and the
// list shut before the click arrives; a finger's tap sends one too.
option.addEventListener("mousedown", (e) => e.preventDefault());
option.addEventListener("click", () => pick(i));
option.addEventListener("mousemove", () => { if (active !== i) highlight(i); });
return option;
}));
const opening = !open;
open = true;
list.hidden = false;
input.setAttribute("aria-expanded", "true");
highlight(0);
// The rail scrolls; a list opened near its foot is brought into view.
if (opening && list.scrollIntoView) list.scrollIntoView({ block: "nearest" });
}
function ask(q) {
const mine = ++asked;
new Promise((resolve) => resolve(suggest(q))).then((answer) => {
if (mine !== asked) return;
shown = unpicked(answer, items).map((s) => ({
value: String(s.value), label: s.label == null ? String(s.value) : String(s.label), hint: s.hint,
}));
shownFor = q;
if (pickFirst) {
pickFirst = false;
if (shown.length) { pick(0); return; }
}
show();
}, () => {
// `api()` has toasted the failure already.
if (mine !== asked) return;
pickFirst = false;
shut();
});
}
function forget() {
clearTimeout(timer);
asked++;
pickFirst = false;
}
function pick(i) {
const s = shown[i];
if (!s) return;
forget();
items.push({ value: s.value, label: s.label });
input.value = "";
shown = [];
shownFor = null;
shut();
drawChips();
input.focus();
changed();
}
input.addEventListener("input", () => {
forget();
const q = input.value.trim();
if (!q) { shownFor = null; shut(); return; }
timer = setTimeout(() => ask(q), WAIT_MS);
});
input.addEventListener("keydown", (e) => {
if (e.isComposing) return;
const q = input.value.trim();
const what = keyAction({
open, active, count: shown.length, fresh: shownFor === q, text: input.value, chips: items.length,
}, e.key);
if (!what) return;
if (what.prevent) e.preventDefault();
if (what.stop) e.stopPropagation();
switch (what.act) {
case "move": highlight(what.to); break;
case "pick": pick(what.to); break;
case "ask": forget(); pickFirst = true; ask(q); break;
case "open":
if (shownFor === q && shown.length) show();
else { forget(); ask(q); }
break;
case "shut": shut(); break;
case "unchip":
items = items.slice(0, -1);
drawChips();
changed();
break;
}
});
// A late answer must not open the list under a field that was left.
input.addEventListener("blur", () => { forget(); shut(); });
// The box looks like the field, so a tap anywhere in it is a tap in it.
box.addEventListener("click", (e) => { if (e.target === box) input.focus(); });
return {
values,
set(next) {
items = unpicked((next || []).map((i) => ({
value: String(i.value), label: i.label == null ? String(i.value) : String(i.label),
})), []);
drawChips();
},
clear() {
forget();
items = [];
input.value = "";
shown = [];
shownFor = null;
shut();
drawChips();
},
};
}
// For the tests, which walk the keys without a DOM.
chipInput.keyAction = keyAction;
chipInput.unpicked = unpicked;
window.chipInput = chipInput;
})();
+409
View File
@@ -0,0 +1,409 @@
// 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);
});