@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.
package/src/tree.js ADDED
@@ -0,0 +1,490 @@
1
+ /* Tree view: nested items that open and close, like folders in a file browser or a list of
2
+ categories. A branch grows open while its rows drop in, the chevron turns with a small overshoot
3
+ and a folder icon opens. The selection highlight stretches from row to row (the same motion as the
4
+ sidebar pill). Checkboxes can tick a whole branch and show “some” on the branches above it.
5
+ A branch can load its children the first time it opens. filter(text) keeps the matches and the
6
+ branches that lead to them. Full keyboard support (the ARIA tree pattern) with type-to-jump. */
7
+ import * as M from '@gecko-ui-kit/motion';
8
+ import { icon } from '@gecko-ui-kit/icons';
9
+ import { esc } from '../index.js';
10
+
11
+ const { g, RM, $$ } = M;
12
+ const WORDS = { label: 'Tree', loading: 'Loading…', empty: 'Empty', error: 'Couldn’t load this', retry: 'Try again', loaded: (n) => `${n} items loaded` };
13
+ let uid = 0;
14
+
15
+ /**
16
+ * const t = tree(el, {
17
+ * items: [{ id, label, icon, iconOpen, badge, children: [...] | true, open, selected, checked, disabled }],
18
+ * // children: true → loaded with load() the first time the branch opens
19
+ * select: 'single' | 'multiple' | 'none',
20
+ * checkable: false, // checkboxes; a branch ticks everything inside it
21
+ * lines: true, // guide lines down each open branch
22
+ * icons: true, // folder / open folder / file when an item has no icon
23
+ * openOnClick: true, // clicking a branch's row opens or closes it (the chevron always does)
24
+ * indent: 18,
25
+ * value, checked, // ids to start with (or use selected / checked on items)
26
+ * load: async (item, t) => [...children],
27
+ * label: 'Files', // name for screen readers
28
+ * words: { label, loading, empty, error, retry, loaded },
29
+ * onSelect(ids, item, t), onCheck(ids, t), onToggle(id, open, t), onActivate(item, t)
30
+ * })
31
+ * t.value · t.checked · t.checkedLeaves · t.get(id) · t.select(id | ids) · t.check(id, on)
32
+ * t.open(id) · t.close(id) · t.toggle(id) · t.expandAll() · t.collapseAll() · t.reveal(id)
33
+ * t.filter(text) → matches · t.add(parentId, item, index) · t.remove(id) · t.rename(id, label) · t.destroy()
34
+ */
35
+ export const tree = (el, opts = {}) => {
36
+ el = $$(el)[0];
37
+ if (!el) return null;
38
+ const o = { items: [], select: 'single', checkable: false, lines: true, icons: true, openOnClick: true, indent: null, value: null, checked: null, load: null, label: '', words: null, onSelect: null, onCheck: null, onToggle: null, onActivate: null, ...opts };
39
+ const W = { ...WORDS, ...o.words };
40
+ const multi = o.select === 'multiple', single = o.select === 'single', none = !multi && !single;
41
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
42
+ const base = `tv${++uid}`;
43
+ let seq = 0;
44
+
45
+ el.innerHTML = `<div class="tv${o.lines ? ' tv--lines' : ''}${o.checkable ? ' tv--check' : ''}${multi ? ' tv--multi' : ''}"${o.indent != null ? ` style="--tv-indent:${+o.indent}px"` : ''}>`
46
+ + `${single ? '<span class="tv__pill" aria-hidden="true"></span>' : ''}`
47
+ + `<ul class="tv__list" role="tree" aria-label="${esc(o.label || W.label)}"${multi ? ' aria-multiselectable="true"' : ''}></ul>`
48
+ + '<span class="tv__sr" role="status"></span></div>';
49
+ const root = el.firstElementChild, list = root.querySelector('.tv__list'), pill = root.querySelector('.tv__pill');
50
+ const say = (t) => { root.querySelector('.tv__sr').textContent = t; };
51
+
52
+ /* ---------- the model: one node per item ---------- */
53
+ const byId = new Map(), sel = new Set();
54
+ const top = { root: true, id: null, depth: -1, kids: [], open: true, group: list };
55
+ const branch = (n) => n.lazy || Array.isArray(n.kids);
56
+ const icName = (n) => {
57
+ const it = n.item;
58
+ if (branch(n) && n.open) return it.iconOpen ?? it.icon ?? (o.icons ? 'folderOpen' : null);
59
+ return it.icon ?? (o.icons ? (branch(n) ? 'folder' : 'file') : null);
60
+ };
61
+ const rowHtml = (n) => `<div class="tv__row" style="--d:${n.depth}">`
62
+ + `<span class="tv__tw">${branch(n) ? icon('chevR') : ''}</span>`
63
+ + `${o.checkable ? `<span class="check tv__ck" aria-checked="false" aria-hidden="true">${icon('check')}</span>` : ''}`
64
+ + `<span class="tv__ic"></span><span class="tv__lb">${esc(n.label)}</span>`
65
+ + `${n.item.badge != null && n.item.badge !== '' ? `<span class="tv__bd">${esc(n.item.badge)}</span>` : ''}</div>`;
66
+
67
+ const addGroup = (n) => {
68
+ const ul = document.createElement('ul');
69
+ ul.className = 'tv__group'; ul.setAttribute('role', 'group'); ul.style.setProperty('--d', n.depth); ul.hidden = true;
70
+ n.li.append(ul); n.group = ul;
71
+ n.tw.innerHTML = icon('chevR');
72
+ };
73
+ const setStatus = (n, kind) => { // kind: null | 'empty' | 'loading' | 'error'
74
+ n.group.querySelector(':scope > .tv__status')?.remove();
75
+ if (!kind) return;
76
+ const li = document.createElement('li');
77
+ li.className = `tv__status tv__status--${kind}`; li.setAttribute('role', 'none'); li.style.setProperty('--d', n.depth + 1);
78
+ li.innerHTML = kind === 'loading' ? `<span class="tv__spin"></span><span>${esc(W.loading)}</span>`
79
+ : kind === 'error' ? `${icon('alert')}<span>${esc(W.error)}</span><button type="button" class="tv__retry">${esc(W.retry)}</button>`
80
+ : `<span>${esc(W.empty)}</span>`;
81
+ n.group.append(li);
82
+ };
83
+ const paintIcon = (n, animate) => {
84
+ const name = icName(n);
85
+ if ((n.ic.dataset.i || '') === (name || '')) return;
86
+ n.ic.dataset.i = name || ''; n.ic.innerHTML = name ? icon(name) : ''; n.ic.hidden = !name;
87
+ if (animate && name && !RM()) g.fromTo(n.ic, { scale: 0.75 }, { scale: 1, duration: 0.42, ease: 'back.out(3)', clearProps: 'transform' });
88
+ };
89
+ const paintSel = (n) => {
90
+ if (none) return;
91
+ const s = sel.has(n.id);
92
+ n.li.setAttribute('aria-selected', String(s)); n.li.classList.toggle('is-sel', s);
93
+ };
94
+ const paintCheck = (n, pop = false, delay = 0) => {
95
+ if (!o.checkable) return;
96
+ n.li.setAttribute('aria-checked', n.checked); n.ck.setAttribute('aria-checked', n.checked);
97
+ if (pop && !RM()) g.fromTo(n.ck, { scale: 0.7 }, { scale: 1, duration: 0.4, delay, ease: 'back.out(3)', clearProps: 'transform' });
98
+ };
99
+
100
+ const make = (it, parent, i) => {
101
+ let id = String(it.id ?? `${parent.root ? '' : parent.id + '/'}${i + 1}`);
102
+ if (byId.has(id)) id = `${id}~${++seq}`;
103
+ const n = { id, item: it, label: String(it.label ?? it.title ?? id), parent, depth: parent.depth + 1,
104
+ kids: Array.isArray(it.children) ? [] : null, lazy: it.children === true, loading: false, open: false,
105
+ disabled: !!it.disabled, checked: 'false', out: false };
106
+ byId.set(id, n);
107
+ const li = document.createElement('li');
108
+ li.className = 'tv__item'; li.id = `${base}-${++seq}`; li.dataset.id = id;
109
+ li.setAttribute('role', 'treeitem'); li.tabIndex = -1;
110
+ if (n.disabled) li.setAttribute('aria-disabled', 'true');
111
+ li.innerHTML = rowHtml(n);
112
+ Object.assign(n, { li, row: li.firstElementChild });
113
+ n.tw = n.row.querySelector('.tv__tw'); n.ic = n.row.querySelector('.tv__ic'); n.lb = n.row.querySelector('.tv__lb'); n.ck = n.row.querySelector('.tv__ck');
114
+ paintIcon(n, false); paintCheck(n); paintSel(n);
115
+ if (branch(n)) { addGroup(n); li.setAttribute('aria-expanded', 'false'); }
116
+ if (n.kids) {
117
+ it.children.forEach((c, k) => { const ch = make(c, n, k); n.kids.push(ch); n.group.append(ch.li); });
118
+ if (!n.kids.length) setStatus(n, 'empty');
119
+ }
120
+ return n;
121
+ };
122
+ const walk = (n, fn) => (n.kids || []).forEach((k) => { fn(k); walk(k, fn); });
123
+ const all = (from = top) => { const a = []; walk(from, (n) => a.push(n)); return a; };
124
+ const shown = (n) => { if (!n || n.out) return false; for (let p = n.parent; !p.root; p = p.parent) if (!p.open || p.out) return false; return true; };
125
+ const visible = () => { const a = []; const rec = (n) => (n.kids || []).forEach((k) => { if (k.out) return; a.push(k); if (k.open) rec(k); }); rec(top); return a; };
126
+
127
+ /* ---------- the stretchy selection pill (single select) ---------- */
128
+ const selRow = () => { if (!pill || !sel.size) return null; const n = byId.get([...sel][0]); return shown(n) ? n.row : null; };
129
+ const place = (animate) => {
130
+ if (!pill) return;
131
+ const row = selRow(), was = Number(g.getProperty(pill, 'opacity'));
132
+ M.indicator(pill, row, { animate, radius: 9 });
133
+ if (row && !was && !RM()) g.fromTo(pill, { opacity: 0 }, { opacity: 1, duration: 0.25 });
134
+ };
135
+ const place0 = () => place(false);
136
+
137
+ /* ---------- focus (one item in the tab order) ---------- */
138
+ let cur = null;
139
+ const focusNode = (n, { focus = true } = {}) => {
140
+ if (!n) return;
141
+ if (cur && cur !== n && cur.li.isConnected) cur.li.tabIndex = -1;
142
+ cur = n; n.li.tabIndex = 0;
143
+ if (focus) { n.li.focus({ preventScroll: true }); n.row.scrollIntoView({ block: 'nearest' }); }
144
+ };
145
+
146
+ /* ---------- open / close ---------- */
147
+ const chev = (n, animate) => {
148
+ const s = n.tw.querySelector('svg'); if (!s) return;
149
+ g.killTweensOf(s);
150
+ if (!animate || RM()) g.set(s, { rotation: n.open ? 90 : 0 });
151
+ else g.to(s, { rotation: n.open ? 90 : 0, duration: 0.42, ease: n.open ? 'back.out(2.6)' : 'power2.out' });
152
+ };
153
+ const grow = (n, animate, from) => {
154
+ const ul = n.group;
155
+ g.killTweensOf(ul);
156
+ if (!animate || RM()) { g.set(ul, { clearProps: 'height,opacity' }); place0(); return; }
157
+ g.fromTo(ul, { height: from, opacity: 1 }, { height: 'auto', duration: 0.4, ease: 'power3.out', clearProps: 'height,opacity', onUpdate: place0 });
158
+ };
159
+ const dropIn = (lis) => {
160
+ lis = lis.filter((l) => !l.hidden).slice(0, 14);
161
+ if (RM() || !lis.length) return;
162
+ g.fromTo(lis, { y: -6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.36, delay: 0.04, stagger: 0.03, ease: 'power3.out', clearProps: 'transform,opacity' });
163
+ };
164
+ const show = (n, animate = true) => {
165
+ if (!branch(n) || n.open) return false;
166
+ const ul = n.group, was = ul.hidden, h0 = was ? 0 : ul.offsetHeight;
167
+ n.open = true; n.li.setAttribute('aria-expanded', 'true');
168
+ chev(n, animate); paintIcon(n, animate);
169
+ ul.hidden = false;
170
+ if (n.lazy && !n.loading) fetchKids(n);
171
+ grow(n, animate, h0);
172
+ if (was && animate) dropIn([...ul.children]);
173
+ return true;
174
+ };
175
+ const hide = (n, animate = true) => {
176
+ if (!n.open) return false;
177
+ n.open = false; n.li.setAttribute('aria-expanded', 'false');
178
+ chev(n, animate); paintIcon(n, animate);
179
+ if (cur && cur !== n && n.li.contains(cur.li)) focusNode(n, { focus: root.contains(document.activeElement) });
180
+ const ul = n.group;
181
+ g.killTweensOf(ul);
182
+ place0();
183
+ if (!animate || RM() || ul.hidden) { ul.hidden = true; g.set(ul, { clearProps: 'height,opacity' }); return true; }
184
+ g.fromTo(ul, { height: ul.offsetHeight, opacity: 1 }, { height: 0, opacity: 0.2, duration: 0.3, ease: 'power2.inOut', onUpdate: place0,
185
+ onComplete: () => { if (!n.open) ul.hidden = true; g.set(ul, { clearProps: 'height,opacity' }); } });
186
+ return true;
187
+ };
188
+ const setOpen = (n, open, { animate = true, tell = true } = {}) => {
189
+ if (!n || n.root) return false;
190
+ const done = open ? show(n, animate) : hide(n, animate);
191
+ if (done && tell) o.onToggle?.(n.id, open, api);
192
+ return done;
193
+ };
194
+
195
+ /* ---------- children loaded on first open ---------- */
196
+ const settle = (n) => { // starting state of a node (and what's below it) from its item
197
+ if (o.checkable && n.item.checked && n.checked !== 'true') setCheck(n, 'true');
198
+ if (!none && n.item.selected && !n.disabled && (multi || !sel.size)) { sel.add(n.id); paintSel(n); }
199
+ (n.kids || []).forEach(settle);
200
+ if (n.item.open) show(n, false);
201
+ };
202
+ const fetchKids = async (n) => {
203
+ if (!o.load) { n.lazy = false; n.kids = []; setStatus(n, 'empty'); return; }
204
+ n.loading = true; n.li.setAttribute('aria-busy', 'true'); setStatus(n, 'loading');
205
+ let items = null;
206
+ try { items = await o.load(n.item, api); } catch { items = null; }
207
+ if (ac.signal.aborted || !byId.has(n.id)) return;
208
+ n.loading = false; n.li.removeAttribute('aria-busy');
209
+ if (!Array.isArray(items)) { setStatus(n, 'error'); say(W.error); return; }
210
+ const h0 = n.group.hidden ? 0 : n.group.offsetHeight;
211
+ n.lazy = false; n.kids = [];
212
+ setStatus(n, null);
213
+ items.forEach((it, k) => { const c = make(it, n, k); n.kids.push(c); n.group.append(c.li); });
214
+ if (!n.kids.length) setStatus(n, 'empty');
215
+ if (o.checkable && n.checked === 'true') { n.kids.forEach((c) => { if (!c.disabled) down(c, 'true', []); }); all(n).forEach((x) => paintCheck(x)); }
216
+ n.kids.forEach(settle);
217
+ if (o.checkable) { const ch = []; up(n, ch); ch.forEach((x) => paintCheck(x)); }
218
+ if (query) filter(query);
219
+ if (n.open && !n.group.hidden) { grow(n, true, h0); dropIn(n.kids.map((c) => c.li)); }
220
+ say(W.loaded(n.kids.length));
221
+ };
222
+
223
+ /* ---------- checkboxes ---------- */
224
+ const down = (x, v, changed) => {
225
+ if (x.checked !== v) { x.checked = v; changed.push(x); }
226
+ (x.kids || []).forEach((k) => { if (!k.disabled) down(k, v, changed); });
227
+ };
228
+ const up = (n, changed) => {
229
+ for (let p = n.root ? null : n; p && !p.root; p = p.parent) {
230
+ if (!p.kids?.length) continue;
231
+ const s = p.kids.every((k) => k.checked === 'true') ? 'true' : p.kids.every((k) => k.checked === 'false') ? 'false' : 'mixed';
232
+ if (p.checked !== s) { p.checked = s; changed.push(p); }
233
+ }
234
+ };
235
+ const setCheck = (n, v, animate = false) => {
236
+ const changed = [];
237
+ down(n, v, changed); up(n, changed); // n itself too: a locked item below keeps it at “some”
238
+ const v2 = visible();
239
+ changed.sort((a, b) => v2.indexOf(a) - v2.indexOf(b));
240
+ let k = 0;
241
+ changed.forEach((x) => paintCheck(x, animate && shown(x), shown(x) ? Math.min(k++, 12) * 0.025 : 0));
242
+ return changed.length > 0;
243
+ };
244
+ const toggleCheck = (n) => {
245
+ if (!o.checkable || n.disabled) return;
246
+ const free = all(n).filter((x) => !x.disabled && !x.kids?.length); // what a click can change below
247
+ const full = n.checked === 'true' || (n.checked === 'mixed' && free.length > 0 && free.every((x) => x.checked === 'true'));
248
+ if (setCheck(n, full ? 'false' : 'true', true)) o.onCheck?.(api.checked, api);
249
+ };
250
+
251
+ /* ---------- selection ---------- */
252
+ let anchor = null;
253
+ const ordered = () => all().filter((n) => sel.has(n.id)).map((n) => n.id);
254
+ const selectOnly = (n) => {
255
+ const old = [...sel]; sel.clear();
256
+ old.forEach((id) => byId.get(id) && paintSel(byId.get(id)));
257
+ if (n) { sel.add(n.id); paintSel(n); }
258
+ };
259
+ const choose = (n, { add = false, range = false, tell = true, animate = true } = {}) => {
260
+ if (none || !n || n.disabled) return false;
261
+ const before = ordered().join('\n');
262
+ if (multi && range && anchor && byId.has(anchor.id)) {
263
+ const v = visible(), a = v.indexOf(anchor), b = v.indexOf(n);
264
+ if (a < 0 || b < 0) { selectOnly(n); anchor = n; }
265
+ else {
266
+ if (!add) selectOnly(null);
267
+ v.slice(Math.min(a, b), Math.max(a, b) + 1).forEach((m) => { if (!m.disabled) { sel.add(m.id); paintSel(m); } });
268
+ }
269
+ } else if (multi && add) { if (sel.has(n.id)) sel.delete(n.id); else sel.add(n.id); paintSel(n); anchor = n; }
270
+ else { selectOnly(n); anchor = n; }
271
+ place(animate);
272
+ const changed = ordered().join('\n') !== before;
273
+ if (changed && tell) o.onSelect?.(api.value, n.item, api);
274
+ return changed;
275
+ };
276
+ const activate = (n) => {
277
+ if (branch(n)) { setOpen(n, !n.open); return; }
278
+ if (!n.disabled) o.onActivate?.(n.item, api);
279
+ };
280
+
281
+ /* ---------- filter ---------- */
282
+ let query = '', pre = null;
283
+ const paintLabel = (n, q) => {
284
+ if (!q) { n.lb.textContent = n.label; return; }
285
+ const s = n.label, sl = s.toLowerCase(), ql = q.toLowerCase();
286
+ let i = 0, j, h = '';
287
+ while ((j = sl.indexOf(ql, i)) >= 0) { h += `${esc(s.slice(i, j))}<mark class="tv__hit">${esc(s.slice(j, j + q.length))}</mark>`; i = j + q.length; }
288
+ n.lb.innerHTML = h + esc(s.slice(i));
289
+ };
290
+ const filter = (text = '') => {
291
+ const q = String(text).trim(), ql = q.toLowerCase();
292
+ if (q && !pre) pre = new Set(all().filter((n) => n.open).map((n) => n.id));
293
+ let count = 0;
294
+ const rec = (n, inside) => {
295
+ const hit = !!q && n.label.toLowerCase().includes(ql);
296
+ if (hit) count++;
297
+ let below = false;
298
+ (n.kids || []).forEach((k) => { if (rec(k, inside || hit)) below = true; });
299
+ const keep = !q || hit || below || inside;
300
+ n.out = !keep; n.li.hidden = !keep;
301
+ paintLabel(n, hit ? q : '');
302
+ if (branch(n)) {
303
+ const want = q ? below : pre ? pre.has(n.id) : n.open;
304
+ if (want && !n.open && !(n.lazy && !q)) show(n, false); else if (!want && n.open) hide(n, false);
305
+ }
306
+ return hit || below;
307
+ };
308
+ top.kids.forEach((k) => rec(k, false));
309
+ if (!q) pre = null;
310
+ query = q;
311
+ root.classList.toggle('is-filtered', !!q);
312
+ if (cur && !shown(cur)) { const f = visible()[0]; if (f) focusNode(f, { focus: false }); }
313
+ place0();
314
+ return count;
315
+ };
316
+
317
+ /* ---------- events ---------- */
318
+ const nodeOf = (t) => { const li = t.closest?.('.tv__item'); return li && li.closest('.tv') === root ? byId.get(li.dataset.id) : null; };
319
+ on(list, 'click', (e) => {
320
+ const retry = e.target.closest('.tv__retry');
321
+ if (retry) { const p = nodeOf(retry); if (p && !p.loading) { p.lazy = true; fetchKids(p); } return; }
322
+ if (!e.target.closest('.tv__row')) return;
323
+ const n = nodeOf(e.target); if (!n) return;
324
+ focusNode(n);
325
+ if (e.target.closest('.tv__tw')) { if (branch(n)) setOpen(n, !n.open); return; }
326
+ if (o.checkable && (e.target.closest('.tv__ck') || none)) { toggleCheck(n); return; }
327
+ const mod = multi && (e.metaKey || e.ctrlKey || e.shiftKey);
328
+ if (!n.disabled) choose(n, { add: multi && (e.metaKey || e.ctrlKey), range: multi && e.shiftKey });
329
+ if (branch(n) && o.openOnClick && !mod) setOpen(n, !n.open);
330
+ });
331
+ on(list, 'dblclick', (e) => { if (!e.target.closest('.tv__row') || e.target.closest('.tv__tw, .tv__ck')) return; const n = nodeOf(e.target); if (n && !branch(n) && !n.disabled) o.onActivate?.(n.item, api); });
332
+ on(list, 'mousedown', (e) => { if (multi && e.shiftKey) e.preventDefault(); });
333
+ on(list, 'focusin', (e) => { const n = nodeOf(e.target); if (n && e.target === n.li && cur !== n) focusNode(n, { focus: false }); });
334
+
335
+ let buf = '', bufT = 0;
336
+ on(list, 'keydown', (e) => {
337
+ const n = nodeOf(e.target); if (!n || e.target !== n.li) return;
338
+ const v = visible(), i = v.indexOf(n), k = e.key;
339
+ const go = (m) => {
340
+ e.preventDefault(); if (!m) return;
341
+ focusNode(m);
342
+ if (single) choose(m);
343
+ else if (multi && e.shiftKey) choose(m, { range: true });
344
+ };
345
+ if (k === 'ArrowDown') go(v[i + 1]);
346
+ else if (k === 'ArrowUp') go(v[i - 1]);
347
+ else if (k === 'Home') go(v[0]);
348
+ else if (k === 'End') go(v[v.length - 1]);
349
+ else if (k === 'ArrowRight') {
350
+ e.preventDefault();
351
+ if (branch(n) && !n.open) setOpen(n, true);
352
+ else if (n.open) { const f = (n.kids || []).find((c) => !c.out); if (f) go(f); }
353
+ } else if (k === 'ArrowLeft') {
354
+ e.preventDefault();
355
+ if (n.open) setOpen(n, false); else if (!n.parent.root) go(n.parent);
356
+ } else if (k === 'Enter') { e.preventDefault(); if (!none) choose(n); activate(n); }
357
+ else if (k === ' ') { e.preventDefault(); if (o.checkable) toggleCheck(n); else choose(n, { add: multi }); }
358
+ else if (k === '*') { e.preventDefault(); n.parent.kids.forEach((s) => { if (!s.out && !(s.lazy && s !== n)) setOpen(s, true); }); }
359
+ else if (multi && (e.ctrlKey || e.metaKey) && k.toLowerCase() === 'a') {
360
+ e.preventDefault(); selectOnly(null);
361
+ v.forEach((m) => { if (!m.disabled) { sel.add(m.id); paintSel(m); } });
362
+ o.onSelect?.(api.value, n.item, api);
363
+ } else if (k.length === 1 && /\S/.test(k) && !e.ctrlKey && !e.metaKey && !e.altKey) {
364
+ clearTimeout(bufT); buf += k.toLowerCase(); bufT = setTimeout(() => { buf = ''; }, 650);
365
+ const from = buf.length === 1 ? i + 1 : i;
366
+ const m = [...v.slice(from), ...v.slice(0, from)].find((x) => x.label.toLowerCase().startsWith(buf));
367
+ if (m) go(m);
368
+ }
369
+ });
370
+
371
+ /* keep the pill on its row when the layout changes */
372
+ let raf = 0;
373
+ const ro = new ResizeObserver(() => { cancelAnimationFrame(raf); raf = requestAnimationFrame(place0); });
374
+ ro.observe(list);
375
+
376
+ /* ---------- build ---------- */
377
+ (o.items || []).forEach((it, i) => { const n = make(it, top, i); top.kids.push(n); list.append(n.li); });
378
+ top.kids.forEach(settle);
379
+ if (o.checkable && o.checked) [].concat(o.checked).forEach((id) => { const n = byId.get(String(id)); if (n) setCheck(n, 'true'); });
380
+ if (!none && o.value != null) { selectOnly(null); [].concat(o.value).slice(0, multi ? Infinity : 1).forEach((id) => { const n = byId.get(String(id)); if (n && !n.disabled) { sel.add(n.id); paintSel(n); } }); }
381
+ focusNode((sel.size && byId.get([...sel][0])) || top.kids[0], { focus: false });
382
+ place0();
383
+ document.fonts?.ready.then(() => { if (!ac.signal.aborted) place0(); });
384
+
385
+ /* ---------- add / remove / rename ---------- */
386
+ const add = (parentId, item, index) => {
387
+ const p = parentId == null ? top : byId.get(String(parentId));
388
+ if (!p || !item || (p.lazy && !p.root)) return null;
389
+ if (!p.root && !branch(p)) { p.kids = []; addGroup(p); p.li.setAttribute('aria-expanded', 'false'); paintIcon(p, false); }
390
+ const n = make(item, p, p.kids.length);
391
+ const at = index == null ? p.kids.length : Math.max(0, Math.min(p.kids.length, +index || 0));
392
+ const next = p.kids[at];
393
+ p.kids.splice(at, 0, n);
394
+ if (!p.root) setStatus(p, null);
395
+ p.group.insertBefore(n.li, next ? next.li : null);
396
+ settle(n);
397
+ if (o.checkable) { if (!p.root && p.checked === 'true') down(n, 'true', []); paintCheck(n); all(n).forEach((x) => paintCheck(x)); const ch = []; up(p, ch); ch.forEach((x) => paintCheck(x)); }
398
+ if (query) filter(query);
399
+ if (!p.root && !p.open) setOpen(p, true);
400
+ if (!RM() && shown(n)) {
401
+ g.fromTo(n.li, { height: 0, opacity: 0, overflow: 'hidden' }, { height: 'auto', opacity: 1, duration: 0.36, ease: 'power3.out', clearProps: 'height,opacity,overflow', onUpdate: place0 });
402
+ n.row.classList.remove('is-new'); void n.row.offsetWidth; n.row.classList.add('is-new');
403
+ on(n.row, 'animationend', () => n.row.classList.remove('is-new'), { once: true });
404
+ }
405
+ return n.id;
406
+ };
407
+ const remove = (id) => {
408
+ const n = byId.get(String(id)); if (!n) return false;
409
+ const p = n.parent, v = visible(), had = n.li.contains(document.activeElement);
410
+ if (cur && (cur === n || n.li.contains(cur.li))) {
411
+ const i = v.indexOf(n);
412
+ const m = v.slice(i + 1).find((x) => !n.li.contains(x.li)) ?? v.slice(0, Math.max(0, i)).reverse().find((x) => !n.li.contains(x.li)) ?? null;
413
+ cur = null;
414
+ if (m) focusNode(m, { focus: had });
415
+ }
416
+ let lost = false;
417
+ [n, ...all(n)].forEach((x) => { byId.delete(x.id); if (sel.delete(x.id)) lost = true; if (anchor === x) anchor = null; });
418
+ p.kids.splice(p.kids.indexOf(n), 1);
419
+ if (o.checkable && !p.root) { const ch = []; up(p, ch); ch.forEach((x) => paintCheck(x, true)); }
420
+ const li = n.li;
421
+ const end = () => { li.remove(); if (!p.root && !p.kids.length) setStatus(p, 'empty'); place0(); };
422
+ place0();
423
+ if (RM() || !shown(n)) end();
424
+ else g.to(li, { height: 0, opacity: 0, overflow: 'hidden', duration: 0.28, ease: 'power2.inOut', onUpdate: place0, onComplete: end });
425
+ if (lost) o.onSelect?.(api.value, null, api);
426
+ return true;
427
+ };
428
+ const rename = (id, label) => {
429
+ const n = byId.get(String(id)); if (!n) return false;
430
+ n.label = String(label ?? '');
431
+ paintLabel(n, query && n.label.toLowerCase().includes(query.toLowerCase()) ? query : '');
432
+ if (!RM() && shown(n)) g.fromTo(n.lb, { y: 5, opacity: 0 }, { y: 0, opacity: 1, duration: 0.3, ease: 'power2.out', clearProps: 'transform,opacity' });
433
+ return true;
434
+ };
435
+ const reveal = (id, { select = true, focus = true } = {}) => {
436
+ const n = byId.get(String(id)); if (!n || n.out) return false;
437
+ const chain = []; for (let p = n.parent; !p.root; p = p.parent) chain.unshift(p);
438
+ chain.forEach((p) => setOpen(p, true));
439
+ if (select && !n.disabled) choose(n);
440
+ focusNode(n, { focus: false });
441
+ g.delayedCall(RM() ? 0 : 0.42, () => {
442
+ if (ac.signal.aborted || !n.li.isConnected) return;
443
+ if (focus) n.li.focus({ preventScroll: true });
444
+ n.row.scrollIntoView({ block: 'nearest', behavior: RM() ? 'auto' : 'smooth' });
445
+ });
446
+ return true;
447
+ };
448
+
449
+ const info = (n) => n && { id: n.id, label: n.label, item: n.item, depth: n.depth, parent: n.parent.root ? null : n.parent.id,
450
+ open: n.open, selected: sel.has(n.id), checked: n.checked === 'mixed' ? 'mixed' : n.checked === 'true', branch: branch(n), loaded: !n.lazy };
451
+
452
+ const api = {
453
+ root,
454
+ get value() { return ordered(); },
455
+ get checked() { return all().filter((n) => n.checked === 'true').map((n) => n.id); },
456
+ get checkedLeaves() { return all().filter((n) => n.checked === 'true' && !n.kids?.length && !n.lazy).map((n) => n.id); },
457
+ get: (id) => info(byId.get(String(id))),
458
+ select(ids) {
459
+ if (none) return false;
460
+ const want = ids == null ? [] : [].concat(ids).map(String).filter((id) => byId.has(id) && !byId.get(id).disabled);
461
+ const before = ordered().join('\n');
462
+ selectOnly(null);
463
+ (multi ? want : want.slice(0, 1)).forEach((id) => { sel.add(id); paintSel(byId.get(id)); });
464
+ place(true);
465
+ return ordered().join('\n') !== before;
466
+ },
467
+ check(id, onOff = true) { const n = byId.get(String(id)); return !!n && o.checkable && setCheck(n, onOff ? 'true' : 'false', true); },
468
+ open: (id) => setOpen(byId.get(String(id)), true),
469
+ close: (id) => setOpen(byId.get(String(id)), false),
470
+ toggle: (id) => { const n = byId.get(String(id)); return n ? setOpen(n, !n.open) : false; },
471
+ expandAll() {
472
+ const todo = all().filter((n) => branch(n) && !n.open && !n.out && !n.lazy);
473
+ const now = todo.filter(shown);
474
+ todo.filter((n) => !now.includes(n)).forEach((n) => setOpen(n, true, { animate: false }));
475
+ now.forEach((n) => setOpen(n, true));
476
+ },
477
+ collapseAll() {
478
+ const open = all().filter((n) => n.open);
479
+ open.filter((n) => n.parent.root).forEach((n) => setOpen(n, false));
480
+ open.filter((n) => !n.parent.root).forEach((n) => setOpen(n, false, { animate: false }));
481
+ },
482
+ reveal, filter, add, remove, rename,
483
+ destroy() {
484
+ ac.abort(); ro.disconnect(); cancelAnimationFrame(raf); clearTimeout(bufT);
485
+ g.killTweensOf(root.querySelectorAll('*')); if (pill) g.killTweensOf(pill.__st ?? {});
486
+ el.innerHTML = '';
487
+ },
488
+ };
489
+ return api;
490
+ };