Merge branch 'wp-d-chips'

This commit is contained in:
Wolf committed 2026-09-29 22:01:07 +02:00
commit 7a282a181d
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;
})();