@gecko-ui-kit/components 0.0.0-stage → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,421 @@
1
+ /* Combobox: a text field you type into to find one option in a list (a country, a customer, a
2
+ product). The list opens with a quick scale and fade from the field and the matching letters
3
+ are marked. The highlight on the active row stretches from row to row as you move with the
4
+ arrows or the mouse (the sidebar motion), and the option you pick settles from its row into
5
+ the field. Options can come from a list or from your server (`source`), with a spinner while
6
+ it searches, older requests cancelled, and a “Try again” row when it fails. With `allowCustom`,
7
+ Enter keeps what was typed. ARIA 1.2 combobox with a listbox popup. */
8
+ import * as M from '@gecko-ui-kit/motion';
9
+ import { icon } from '@gecko-ui-kit/icons';
10
+ import { esc } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const WORDS = {
14
+ placeholder: 'Search…',
15
+ empty: 'No matches',
16
+ loading: 'Searching…',
17
+ error: 'Couldn’t load results',
18
+ retry: 'Try again',
19
+ clear: 'Clear',
20
+ toggle: 'Show options',
21
+ custom: (t) => `Use “${t}”`,
22
+ min: (n) => `Type at least ${n} ${n === 1 ? 'letter' : 'letters'}`,
23
+ results: (n) => (n === 1 ? '1 result' : `${n} results`),
24
+ chosen: (l) => `${l} selected`,
25
+ cleared: 'Cleared',
26
+ };
27
+ let seq = 0;
28
+
29
+ /** Lower case without accents, for matching. */
30
+ const fold = (s) => String(s ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
31
+ /** Options can be strings or objects; make them all objects. */
32
+ const normal = (list) => (list || []).map((x) => (x && typeof x === 'object' ? { ...x, value: String(x.value ?? x.label), label: String(x.label ?? x.value) } : { value: String(x), label: String(x) }));
33
+ /** The text with the first match of q wrapped in <mark> (ignores case and accents). */
34
+ const mark = (text, q) => {
35
+ text = String(text ?? '');
36
+ const fq = fold(q);
37
+ if (!fq) return esc(text);
38
+ let f = '';
39
+ const at = [];
40
+ for (let i = 0; i < text.length; i++) { const c = fold(text[i]); f += c; for (let k = 0; k < c.length; k++) at.push(i); }
41
+ const i = f.indexOf(fq);
42
+ if (i < 0) return esc(text);
43
+ const s = at[i], e = at[i + fq.length - 1] + 1;
44
+ return `${esc(text.slice(0, s))}<mark>${esc(text.slice(s, e))}</mark>${esc(text.slice(e))}`;
45
+ };
46
+
47
+ /**
48
+ * const cb = combobox(el, {
49
+ * options: ['Thailand', …] | [{ value, label, sub, icon, group, disabled }],
50
+ * source: async (query, { signal }) => options, // instead of options: ask your server
51
+ * value: 'th' | { value, label }, // the starting pick (use the object form with a source)
52
+ * placeholder: 'Search…',
53
+ * clearable: true, // an × button; Escape on a closed list clears
54
+ * allowCustom: false, // Enter (or leaving the field) keeps the typed text as the value
55
+ * minChars: 0, // letters needed before the list (or the source) is asked
56
+ * debounce: 150, // ms to wait after typing before calling source
57
+ * maxResults: 50, // rows shown at most (0 = all)
58
+ * name: 'country', // adds a hidden input so a plain <form> sends the value
59
+ * disabled: false,
60
+ * label: 'Country', // a visible label (else the placeholder names the field)
61
+ * words: { placeholder, empty, loading, error, retry, clear, toggle, custom, min, results, chosen, cleared },
62
+ * onChange(value, option, cb), onInput(text, cb)
63
+ * })
64
+ * cb.value · cb.option · cb.isOpen · cb.set(value) · cb.clear() · cb.open() · cb.close() · cb.focus()
65
+ * cb.setOptions(list) · cb.destroy()
66
+ * List height: --cb-list-h (300px).
67
+ */
68
+ export const combobox = (el, opts = {}) => {
69
+ el = $$(el)[0];
70
+ if (!el) return null;
71
+ const o = { options: [], source: null, value: null, placeholder: null, clearable: true, allowCustom: false, minChars: 0, debounce: 150, maxResults: 50, name: '', disabled: false, label: '', words: null, onChange: null, onInput: null, ...opts };
72
+ const W = { ...WORDS, ...o.words };
73
+ if (o.placeholder != null) W.placeholder = o.placeholder;
74
+ const id = `cb${++seq}`;
75
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
76
+
77
+ el.innerHTML = `<div class="cb${o.disabled ? ' is-disabled' : ''}">`
78
+ + (o.label ? `<label class="cb__label" id="${id}-lb" for="${id}-in">${esc(o.label)}</label>` : '')
79
+ + `<div class="cb__field"><span class="cb__lead" aria-hidden="true"></span>`
80
+ + `<input class="cb__input" id="${id}-in" type="text" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="${id}-list" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="${esc(W.placeholder)}"${o.label ? '' : ` aria-label="${esc(W.placeholder)}"`}${o.disabled ? ' disabled' : ''}>`
81
+ + `<span class="cb__side"><span class="cb__spin" aria-hidden="true"></span>`
82
+ + (o.clearable ? `<button type="button" class="cb__clear" tabindex="-1" aria-label="${esc(W.clear)}" title="${esc(W.clear)}">${icon('close')}</button>` : '')
83
+ + `<button type="button" class="cb__chev" tabindex="-1" aria-label="${esc(W.toggle)}" aria-controls="${id}-list" aria-expanded="false"${o.disabled ? ' disabled' : ''}>${icon('down')}</button></span></div>`
84
+ + `<div class="cb__pop" hidden><span class="cb__pill" aria-hidden="true"></span>`
85
+ + `<div class="cb__list" id="${id}-list" role="listbox"${o.label ? ` aria-labelledby="${id}-lb"` : ` aria-label="${esc(W.placeholder)}"`}></div>`
86
+ + '<div class="cb__note" hidden></div></div>'
87
+ + `${o.name ? `<input type="hidden" name="${esc(o.name)}">` : ''}<span class="cb__sr" role="status"></span></div>`;
88
+ const root = el.firstElementChild, field = root.querySelector('.cb__field'), input = root.querySelector('.cb__input');
89
+ const pop = root.querySelector('.cb__pop'), list = root.querySelector('.cb__list'), note = root.querySelector('.cb__note');
90
+ const pill = root.querySelector('.cb__pill'), lead = root.querySelector('.cb__lead'), chev = root.querySelector('.cb__chev');
91
+ const hidden = root.querySelector('input[type="hidden"]'), sr = root.querySelector('.cb__sr');
92
+
93
+ let options = normal(o.options);
94
+ let chosen = null; // the picked option
95
+ let rows = [], active = -1, isOpen = false, typed = false, focusedByPointer = false;
96
+ let state = 'idle', results = [], lastQ = null, req = null; // source: 'idle' | 'loading' | 'ready' | 'error'
97
+ let askT = 0, sayT = 0, ghost = null;
98
+
99
+ const say = (t, wait = 0) => { clearTimeout(sayT); if (wait) sayT = setTimeout(() => { sr.textContent = t; }, wait); else sr.textContent = t; };
100
+ const query = () => (typed ? input.value.trim() : '');
101
+ const short = () => query().length < o.minChars;
102
+ const pool = () => (o.source ? results : options);
103
+ const exact = (t) => pool().find((x) => !x.disabled && fold(x.label) === fold(t));
104
+ const resolve = (v) => {
105
+ if (v == null || v === '') return null;
106
+ if (typeof v === 'object') return normal([v])[0];
107
+ return pool().find((x) => x.value === String(v)) || options.find((x) => x.value === String(v))
108
+ || (o.source || o.allowCustom ? { value: String(v), label: String(v), custom: !o.source } : null);
109
+ };
110
+
111
+ /** Show the picked option in the field (and the hidden input). */
112
+ const sync = () => {
113
+ endGhost();
114
+ root.classList.toggle('has-value', !!chosen);
115
+ input.value = chosen ? chosen.label : '';
116
+ lead.innerHTML = chosen?.icon ? icon(chosen.icon) : '';
117
+ root.classList.toggle('has-lead', !!chosen?.icon);
118
+ if (hidden) hidden.value = chosen ? chosen.value : '';
119
+ typed = false;
120
+ };
121
+
122
+ /* ---------- the list ---------- */
123
+ const optHTML = (x, i, q) => {
124
+ const on = !!chosen && !chosen.custom && x.value === chosen.value;
125
+ return `<div class="cb__opt${on ? ' is-on' : ''}${x.disabled ? ' is-off' : ''}" role="option" id="${id}-o${i}" data-i="${i}" aria-selected="${on}"${x.disabled ? ' aria-disabled="true"' : ''}>`
126
+ + (x.icon ? `<span class="cb__ic">${icon(x.icon)}</span>` : '')
127
+ + `<span class="cb__text"><span class="cb__name">${mark(x.label, q)}</span>${x.sub ? `<small>${mark(x.sub, q)}</small>` : ''}</span>`
128
+ + `<span class="cb__tick">${icon('check')}</span></div>`;
129
+ };
130
+ const render = () => {
131
+ const q = query(), few = short(), fq = fold(q);
132
+ let hits = o.source ? results : few ? [] : options.filter((x) => !fq || fold(x.label).includes(fq) || fold(x.sub).includes(fq) || fold(x.value).includes(fq));
133
+ if (o.maxResults > 0) hits = hits.slice(0, o.maxResults);
134
+ const was = rows[active];
135
+ rows = [];
136
+ let html = '', grp = null, gi = 0;
137
+ hits.forEach((x) => {
138
+ if ((x.group || null) !== grp) {
139
+ if (grp) html += '</div>';
140
+ grp = x.group || null;
141
+ if (grp) { gi++; html += `<div class="cb__grp" role="group" aria-labelledby="${id}-g${gi}"><div class="cb__group" id="${id}-g${gi}">${esc(grp)}</div>`; }
142
+ }
143
+ html += optHTML(x, rows.length, q);
144
+ rows.push({ x, off: !!x.disabled });
145
+ });
146
+ if (grp) html += '</div>';
147
+ if (o.allowCustom && q && !few && !hits.some((x) => fold(x.label) === fq)) {
148
+ html += `<div class="cb__opt cb__opt--custom" role="option" id="${id}-o${rows.length}" data-i="${rows.length}" aria-selected="false"><span class="cb__ic">${icon('plus')}</span><span class="cb__text"><span class="cb__name">${esc(W.custom(q))}</span></span></div>`;
149
+ rows.push({ custom: q, off: false });
150
+ }
151
+ list.innerHTML = html;
152
+
153
+ // the line under the rows: searching / failed / type more / nothing found
154
+ const busy = !!o.source && state === 'loading';
155
+ let kind = '', text = '';
156
+ if (o.source && state === 'error' && !few) { kind = 'error'; text = `${icon('alert')}<span>${esc(W.error)}</span><button type="button" class="cb__retry">${esc(W.retry)}</button>`; }
157
+ else if (busy && !rows.length) { kind = 'loading'; text = `<span class="cb__spin"></span><span>${esc(W.loading)}</span>`; }
158
+ else if (few && o.minChars) { kind = 'min'; text = `<span>${esc(W.min(o.minChars))}</span>`; }
159
+ else if (!rows.length && !busy) { kind = 'empty'; text = `<span>${esc(W.empty)}</span>`; }
160
+ note.className = `cb__note${kind ? ` cb__note--${kind}` : ''}`;
161
+ note.innerHTML = text; note.hidden = !kind;
162
+ root.classList.toggle('is-busy', busy);
163
+ list.classList.toggle('is-stale', busy && rows.length > 0);
164
+
165
+ // which row is active: the same one as before, else the first match, else the picked one
166
+ const keep = was ? rows.findIndex((r) => (was.custom != null ? r.custom != null : r.x && r.x.value === was.x?.value)) : -1;
167
+ if (keep >= 0) active = keep;
168
+ else if (q) active = rows.findIndex((r) => !r.off);
169
+ else active = chosen ? rows.findIndex((r) => r.x && r.x.value === chosen.value) : -1;
170
+ paint(false);
171
+ };
172
+
173
+ /** Scroll the list (not the page) so the row shows. */
174
+ const ensure = (row) => {
175
+ const t = row.offsetTop, b = t + row.offsetHeight;
176
+ if (t < pop.scrollTop + 4) pop.scrollTop = t - 4;
177
+ else if (b > pop.scrollTop + pop.clientHeight - 4) pop.scrollTop = b - pop.clientHeight + 4;
178
+ };
179
+ /** Mark the active row; the pill stretches to it (animate) or jumps there. */
180
+ const paint = (animate = true, scroll = true) => {
181
+ const els = list.querySelectorAll('.cb__opt');
182
+ els.forEach((r, i) => r.classList.toggle('is-active', i === active));
183
+ const row = els[active] || null;
184
+ if (row) { input.setAttribute('aria-activedescendant', row.id); if (scroll) ensure(row); }
185
+ else input.removeAttribute('aria-activedescendant');
186
+ if (!pop.hidden) M.indicator(pill, row, { animate, radius: 9 });
187
+ };
188
+ const step = (dir) => {
189
+ if (!rows.length) return;
190
+ let i = active < 0 ? (dir > 0 ? -1 : 0) : active;
191
+ for (let n = 0; n < rows.length; n++) { i = (i + dir + rows.length) % rows.length; if (!rows[i].off) break; }
192
+ if (rows[i].off) return;
193
+ active = i; paint();
194
+ };
195
+ const edge = (last) => {
196
+ const order = rows.map((r, i) => i).filter((i) => !rows[i].off);
197
+ if (!order.length) return;
198
+ active = last ? order[order.length - 1] : order[0]; paint();
199
+ };
200
+
201
+ /* ---------- asking the source ---------- */
202
+ const fetchNow = (q) => {
203
+ req?.abort();
204
+ const c = new AbortController(); req = c;
205
+ state = 'loading';
206
+ let p;
207
+ try { p = Promise.resolve(o.source(q, { signal: c.signal })); } catch (err) { p = Promise.reject(err); }
208
+ p.then((found) => {
209
+ if (req !== c) return;
210
+ req = null; results = normal(found); lastQ = q; state = 'ready';
211
+ if (isOpen) { rows = []; active = -1; render(); say(rows.length ? W.results(rows.length) : W.empty, 300); }
212
+ }, () => {
213
+ if (req !== c || c.signal.aborted) return;
214
+ req = null; state = 'error'; lastQ = null;
215
+ if (isOpen) { render(); say(W.error); }
216
+ });
217
+ };
218
+ /** Ask for the current text, after the debounce (or now). */
219
+ const ask = (now = false) => {
220
+ clearTimeout(askT);
221
+ if (!o.source) return;
222
+ const q = query();
223
+ if (q.length < o.minChars) { req?.abort(); req = null; state = 'idle'; results = []; lastQ = null; return; }
224
+ state = 'loading';
225
+ if (now || !o.debounce) fetchNow(q); else askT = setTimeout(() => fetchNow(q), o.debounce);
226
+ };
227
+
228
+ /* ---------- open / close ---------- */
229
+ /** Open down or up, whichever has room, inside the screen and any box that clips around it. */
230
+ const place = () => {
231
+ let top = 0, bottom = innerHeight;
232
+ for (let p = root.parentElement; p && p !== document.body; p = p.parentElement) {
233
+ const s = getComputedStyle(p);
234
+ if (/(hidden|auto|scroll|clip)/.test(s.overflowY + s.overflow)) { const r = p.getBoundingClientRect(); top = Math.max(top, r.top); bottom = Math.min(bottom, r.bottom); }
235
+ }
236
+ const r = field.getBoundingClientRect(), below = bottom - r.bottom - 12, above = r.top - top - 12;
237
+ const up = below < 220 && above > below;
238
+ root.classList.toggle('is-up', up);
239
+ pop.style.maxHeight = `min(var(--cb-list-h, 300px), ${Math.max(120, Math.floor(up ? above : below))}px)`;
240
+ };
241
+ const open = () => {
242
+ if (isOpen || o.disabled) return;
243
+ isOpen = true; root.classList.add('is-open');
244
+ input.setAttribute('aria-expanded', 'true'); chev.setAttribute('aria-expanded', 'true');
245
+ place(); pop.hidden = false;
246
+ if (o.source && !short() && (state === 'idle' || state === 'error' || (state === 'ready' && lastQ !== query()))) ask(true);
247
+ rows = []; active = -1;
248
+ render();
249
+ if (RM()) return;
250
+ const up = root.classList.contains('is-up');
251
+ g.fromTo(pop, { opacity: 0, y: up ? 6 : -6, scale: 0.97 }, { opacity: 1, y: 0, scale: 1, duration: 0.22, ease: 'power3.out', overwrite: true, clearProps: 'transform,opacity' });
252
+ g.fromTo([...list.querySelectorAll('.cb__opt')].slice(0, 8), { opacity: 0, y: up ? 4 : -4 }, { opacity: 1, y: 0, duration: 0.24, stagger: 0.018, ease: 'power2.out', clearProps: 'transform,opacity' });
253
+ };
254
+ /** Leaving the field: keep typed text (allowCustom), clear on empty text, or put the pick back. */
255
+ const settleText = () => {
256
+ if (!typed) return;
257
+ const t = input.value.trim();
258
+ if (!t) { if (chosen && o.clearable) commit(null); else sync(); return; }
259
+ const hit = exact(t);
260
+ if (hit) { if (hit.value !== chosen?.value) commit(hit); else sync(); return; }
261
+ if (o.allowCustom && t !== chosen?.label) commit({ value: t, label: t, custom: true });
262
+ else sync();
263
+ };
264
+ /** how: 'pick' (a row was chosen), 'revert' (Escape: put the pick back), 'blur' (left the field). */
265
+ const close = (how = 'revert') => {
266
+ clearTimeout(askT);
267
+ if (how === 'blur') settleText();
268
+ else if (how === 'revert' && typed) sync();
269
+ if (!isOpen) return;
270
+ isOpen = false; active = -1; root.classList.remove('is-open', 'is-busy');
271
+ input.setAttribute('aria-expanded', 'false'); chev.setAttribute('aria-expanded', 'false'); input.removeAttribute('aria-activedescendant');
272
+ if (state === 'loading') { req?.abort(); req = null; state = lastQ == null ? 'idle' : 'ready'; } // no one is looking any more
273
+ const done = () => { if (!isOpen) { pop.hidden = true; g.set(pop, { clearProps: 'transform,opacity' }); } };
274
+ if (RM()) { done(); return; }
275
+ g.to(pop, { opacity: 0, y: root.classList.contains('is-up') ? 4 : -4, duration: 0.13, ease: 'power2.in', overwrite: true, onComplete: done });
276
+ };
277
+
278
+ /* ---------- picking ---------- */
279
+ const endGhost = () => {
280
+ if (!ghost) return;
281
+ g.killTweensOf(ghost); ghost.remove(); ghost = null;
282
+ root.classList.remove('is-settling');
283
+ };
284
+ /** The picked label travels from its row into the field. */
285
+ const settleIn = (from) => {
286
+ if (RM() || !from || !input.value) return;
287
+ const rr = root.getBoundingClientRect(), ir = input.getBoundingClientRect(), pl = parseFloat(getComputedStyle(input).paddingLeft) || 0;
288
+ const gh = document.createElement('span');
289
+ gh.className = 'cb__ghost'; gh.setAttribute('aria-hidden', 'true'); gh.textContent = input.value;
290
+ root.append(gh); ghost = gh;
291
+ root.classList.add('is-settling');
292
+ const h = gh.offsetHeight;
293
+ g.fromTo(gh, { x: from.left - rr.left, y: from.top - rr.top + (from.height - h) / 2 },
294
+ { x: ir.left - rr.left + pl, y: ir.top - rr.top + (ir.height - h) / 2, duration: 0.42, ease: 'power3.inOut', onComplete: endGhost });
295
+ };
296
+ const commit = (x, from = null) => {
297
+ const prev = chosen;
298
+ chosen = x; sync();
299
+ if (isOpen) close('pick');
300
+ settleIn(from);
301
+ if (x?.icon && !RM()) M.pop(lead);
302
+ if (document.activeElement === input) input.setSelectionRange(input.value.length, input.value.length);
303
+ say(x ? W.chosen(x.label) : W.cleared);
304
+ if ((prev?.value ?? null) !== (x?.value ?? null)) o.onChange?.(x ? x.value : null, x, api);
305
+ };
306
+ const choose = (i) => {
307
+ const r = rows[i];
308
+ if (!r || r.off) return;
309
+ const row = list.querySelectorAll('.cb__opt')[i];
310
+ const from = row?.querySelector('.cb__name')?.getBoundingClientRect() || null;
311
+ if (r.custom != null) commit(exact(r.custom) || { value: r.custom, label: r.custom, custom: true }, from);
312
+ else commit(r.x, from);
313
+ };
314
+
315
+ /* ---------- events ---------- */
316
+ on(field, 'pointerdown', (e) => {
317
+ if (o.disabled || e.button > 0) return;
318
+ if (e.target.closest('.cb__clear')) { e.preventDefault(); api.clear(); input.focus(); return; }
319
+ if (e.target !== input) e.preventDefault();
320
+ focusedByPointer = document.activeElement !== input;
321
+ input.focus();
322
+ if (e.target.closest('.cb__chev')) { isOpen ? close('revert') : open(); return; }
323
+ if (!isOpen) open();
324
+ });
325
+ on(input, 'focus', () => {
326
+ root.classList.add('is-focus');
327
+ if (chosen && !typed && !focusedByPointer) input.select(); // Tab in: typing replaces the pick
328
+ });
329
+ on(input, 'click', () => { if (focusedByPointer && chosen && !typed) input.select(); focusedByPointer = false; });
330
+ on(input, 'input', () => {
331
+ typed = true; endGhost();
332
+ o.onInput?.(input.value, api);
333
+ rows = []; active = -1;
334
+ ask();
335
+ if (isOpen) render(); else open();
336
+ if (!o.source && isOpen) say(rows.length ? W.results(rows.filter((r) => r.x).length) : W.empty, 600);
337
+ });
338
+ on(input, 'keydown', (e) => {
339
+ if (o.disabled || e.isComposing) return;
340
+ switch (e.key) {
341
+ case 'ArrowDown':
342
+ e.preventDefault();
343
+ if (!isOpen) { open(); if (!e.altKey && active < 0) edge(false); } else step(1);
344
+ break;
345
+ case 'ArrowUp':
346
+ e.preventDefault();
347
+ if (!isOpen) { open(); if (!e.altKey && active < 0) edge(true); } else if (e.altKey) close('revert'); else step(-1);
348
+ break;
349
+ case 'Home': case 'End':
350
+ if (isOpen && rows.length) { e.preventDefault(); edge(e.key === 'End'); }
351
+ break;
352
+ case 'Enter':
353
+ if (isOpen) {
354
+ e.preventDefault();
355
+ if (active >= 0) choose(active);
356
+ else if (o.allowCustom && query()) commit(exact(query()) || { value: query(), label: query(), custom: true });
357
+ } else if (typed) { e.preventDefault(); settleText(); }
358
+ break;
359
+ case 'Escape':
360
+ if (isOpen) { e.preventDefault(); e.stopPropagation(); close('revert'); }
361
+ else if (typed) { e.preventDefault(); e.stopPropagation(); sync(); }
362
+ else if (o.clearable && chosen) { e.preventDefault(); e.stopPropagation(); commit(null); }
363
+ break;
364
+ case 'Tab': if (isOpen) close('blur'); break;
365
+ default:
366
+ }
367
+ });
368
+ on(pop, 'pointerdown', (e) => e.preventDefault()); // keep the focus in the field
369
+ on(pop, 'click', (e) => {
370
+ if (e.target.closest('.cb__retry')) { ask(true); render(); return; }
371
+ const r = e.target.closest('.cb__opt');
372
+ if (!r) return;
373
+ active = +r.dataset.i; paint(false, false); choose(active);
374
+ });
375
+ on(pop, 'pointermove', (e) => {
376
+ if (e.pointerType === 'touch') return;
377
+ const r = e.target.closest('.cb__opt');
378
+ if (!r || +r.dataset.i === active || r.classList.contains('is-off')) return;
379
+ active = +r.dataset.i; paint(true, false);
380
+ });
381
+ on(root, 'focusout', (e) => {
382
+ if (root.contains(e.relatedTarget)) return;
383
+ root.classList.remove('is-focus');
384
+ focusedByPointer = false;
385
+ close('blur');
386
+ });
387
+ on(document, 'pointerdown', (e) => { if (isOpen && !root.contains(e.target)) close('blur'); });
388
+ on(window, 'resize', () => { if (isOpen) { place(); paint(false, false); } });
389
+
390
+ const api = {
391
+ el: root, opts: o,
392
+ /** The picked value (a string), or null. */
393
+ get value() { return chosen ? chosen.value : null; },
394
+ /** The picked option ({ value, label, … }; custom text has custom: true), or null. */
395
+ get option() { return chosen ? { ...chosen } : null; },
396
+ get isOpen() { return isOpen; },
397
+ /** Pick a value (or { value, label }) without calling onChange. null clears. */
398
+ set(v) { chosen = resolve(v); sync(); if (isOpen) { rows = []; active = -1; render(); } return api; },
399
+ clear() {
400
+ if (!chosen && !input.value) return api;
401
+ if (chosen) commit(null); else sync();
402
+ if (isOpen) { rows = []; active = -1; render(); }
403
+ return api;
404
+ },
405
+ open() { input.focus(); open(); return api; },
406
+ close() { close('revert'); return api; },
407
+ focus() { input.focus(); return api; },
408
+ /** Swap the list (e.g. after loading it); the pick stays. */
409
+ setOptions(next) { options = normal(next); if (isOpen) { rows = []; active = -1; render(); } return api; },
410
+ destroy() {
411
+ ac.abort(); req?.abort(); req = null;
412
+ clearTimeout(askT); clearTimeout(sayT);
413
+ endGhost(); g.killTweensOf([pop, lead, pill, ...list.querySelectorAll('.cb__opt')]);
414
+ el.innerHTML = '';
415
+ },
416
+ };
417
+
418
+ chosen = resolve(o.value);
419
+ sync();
420
+ return api;
421
+ };