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>
318 lines
11 KiB
JavaScript
318 lines
11 KiB
JavaScript
/* 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;
|
||
})();
|