Number 7: Several services in one field
Specification
- Catalogue
- No. 7 of 110
- Section
- Forms and inputs
- Interaction
- Press, Type
- Element
- Input, Form
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
Pick several services for one enquiry; each shows as a token you can remove by name.
An enquiry often covers more than one thing. The choices stay readable in the field, a typed word filters the list, and each remove button says what it removes.
Tokens enter in 150ms. Combobox: arrows move, Enter toggles, Backspace in an empty field removes the last token. Options in short groups in the client's own words.
The names, figures and pictures in the demo are sample content; a real build uses the client's own.
Code
React and plain CSS"use client";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { layoutScale } from "@/components/pieces/motion-helpers";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./multi-selector.css";
const SERVICES = [
{ group: "Personal", items: ["Self Assessment return", "Selling a property", "Inheritance planning"] },
{ group: "Business", items: ["Bookkeeping", "VAT returns", "Payroll", "Year-end accounts"] },
];
const ALL = SERVICES.flatMap((g) => g.items);
function MultiSelectorDemo() {
const [picked, setPicked] = useState<string[]>(["VAT returns"]);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const input = useRef<HTMLInputElement>(null);
const uid = useId();
const q = query.trim().toLowerCase();
const shown = ALL.filter((s) => s.toLowerCase().includes(q));
const toggle = (s: string) => setPicked((p) => (p.includes(s) ? p.filter((x) => x !== s) : [...p, s]));
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const n = shown.length;
if (n) setActive((a) => (a + (e.key === "ArrowDown" ? 1 : -1) + n) % n);
} else if (e.key === "Enter") {
e.preventDefault();
if (shown[active]) toggle(shown[active]);
} else if (e.key === "Backspace" && !query && picked.length) {
setPicked((p) => p.slice(0, -1));
}
};
// Keep the option the arrow keys reach inside the list's scroll box.
const list = useRef<HTMLUListElement>(null);
const activeId = shown[active] ? `${uid}-o${ALL.indexOf(shown[active])}` : null;
useEffect(() => {
const l = list.current;
const o = activeId ? document.getElementById(activeId) : null;
if (!l || !o) return;
const lr = l.getBoundingClientRect();
const or = o.getBoundingClientRect();
// Rects are on-screen sizes; scrollTop is in the list's own units.
const s = layoutScale(l);
if (or.top < lr.top) l.scrollTop -= (lr.top - or.top) / s + 4;
else if (or.bottom > lr.bottom) l.scrollTop += (or.bottom - lr.bottom) / s + 4;
}, [activeId]);
return (
<div className="dm">
<div className="ms">
<label className="ms-label" htmlFor={`${uid}-in`}>
What do you need help with?
</label>
<div className="ms-field" onPointerDown={(e) => e.target === e.currentTarget && input.current?.focus()}>
{picked.map((p) => (
<span key={p} className="ms-token">
{p}
<button type="button" aria-label={`Remove ${p}`} onClick={() => toggle(p)}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" />
</svg>
</button>
</span>
))}
<input
ref={input}
id={`${uid}-in`}
role="combobox"
aria-expanded={true}
aria-controls={`${uid}-list`}
aria-autocomplete="list"
aria-activedescendant={activeId ?? undefined}
value={query}
placeholder={picked.length ? "Add more" : "Type to filter"}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={onKey}
/>
</div>
<ul ref={list} className="ms-list" id={`${uid}-list`} role="listbox" aria-multiselectable="true" aria-label="Services">
{shown.length === 0 && <li className="ms-empty">Nothing matches. Describe it in your message instead.</li>}
{SERVICES.map((g) => {
const items = g.items.filter((s) => shown.includes(s));
if (!items.length) return null;
return (
<li key={g.group} role="presentation">
<span className="ms-group" aria-hidden="true">
{g.group}
</span>
<ul role="group" aria-label={g.group}>
{items.map((s) => (
<li
key={s}
id={`${uid}-o${ALL.indexOf(s)}`}
role="option"
aria-selected={picked.includes(s)}
data-active={shown[active] === s || undefined}
className="ms-opt"
onPointerDown={(e) => {
e.preventDefault();
toggle(s);
setActive(shown.indexOf(s));
input.current?.focus();
}}
>
<span className="ms-check" aria-hidden="true" />
{s}
</li>
))}
</ul>
</li>
);
})}
</ul>
</div>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
{ input: 'input[role="combobox"]', value: "pay", wait: 900 },
{ key: "Enter", on: 'input[role="combobox"]', wait: 700 },
{ input: 'input[role="combobox"]', value: "", wait: 900 },
];
export default function MultiSelectorEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Several services in one field" sample tour={TOUR}>
<MultiSelectorDemo />
</PieceStage>
);
}