@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,373 @@
1
+ /* Virtual list: thousands of rows, but only the ones you can see (plus a few either side) are in the
2
+ page. Row elements are reused as you scroll, so 10,000 rows scroll as smoothly as 20. Rows can have
3
+ one fixed height, or 'auto': each row is measured the first time it shows and the list keeps a
4
+ running index of where every row starts, keeping what you are looking at still while sizes settle.
5
+ On first paint the rows on screen rise in with a short stagger. scrollTo() glides to any row.
6
+ With selectable: true it is a listbox: ↑ ↓ PageUp PageDown Home End move the active row (the
7
+ highlight slides to it and it is kept in view), Enter or Space picks it. */
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 = { label: 'List', empty: 'Nothing to show', count: (n) => `${n.toLocaleString()} items` };
14
+ let uid = 0;
15
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
16
+
17
+ /**
18
+ * const list = virtualList(el, {
19
+ * items: [...] | 10000, // an array, or just a count (render gets the index as the item)
20
+ * rowHeight: 48, // px for every row, or 'auto' (measured as rows show)
21
+ * estimate: 48, // with 'auto': the guess for rows not measured yet
22
+ * height: 400, // viewport height (px or any CSS length); leave out to fill el
23
+ * overscan: 6, // extra rows kept above and below the view
24
+ * render: (item, index) => '<b>…</b>' | Node,
25
+ * key: (item, index) => item.id, // keeps measured heights, selection and scroll place across update()
26
+ * selectable: false, // a listbox with an active row and one picked row
27
+ * value, // key of the row picked at the start (selectable)
28
+ * label: 'Contacts', // name for screen readers
29
+ * words: { label, empty, count },
30
+ * onSelect(item, index, list), onRange({ start, end, rendered, count }, list)
31
+ * })
32
+ * list.update(items) · list.scrollTo(index, { align: 'start'|'center'|'end'|'auto', smooth }) → Promise
33
+ * list.select(index) · list.selected · list.refresh() · list.range · list.count · list.destroy()
34
+ */
35
+ export const virtualList = (el, opts = {}) => {
36
+ el = $$(el)[0];
37
+ if (!el) return null;
38
+ const o = { items: [], count: null, rowHeight: 48, estimate: null, height: null, overscan: 6, render: null, key: null,
39
+ selectable: false, value: undefined, label: '', words: null, onSelect: null, onRange: null, ...opts };
40
+ const W = { ...WORDS, ...o.words };
41
+ const auto = o.rowHeight === 'auto', fixed = auto ? 0 : Math.max(1, +o.rowHeight || 48);
42
+ const est = Math.max(8, +o.estimate || (auto ? 48 : fixed));
43
+ const over = Math.max(0, o.overscan | 0), sel = !!o.selectable;
44
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
45
+ const base = `vl${++uid}`;
46
+ const css = [o.height != null ? `--vl-h:${typeof o.height === 'number' ? `${o.height}px` : o.height}` : '', auto ? '' : `--vl-row:${fixed}px`].filter(Boolean).join(';');
47
+
48
+ el.innerHTML = `<div class="vl${auto ? ' vl--auto' : ''}${sel ? ' vl--select' : ''}"${css ? ` style="${css}"` : ''}>`
49
+ + `<div class="vl__vp" tabindex="0" role="${sel ? 'listbox' : 'list'}" aria-label="${esc(o.label || W.label)}">`
50
+ + `<div class="vl__sizer">${sel ? '<span class="vl__hl" aria-hidden="true"></span>' : ''}</div></div>`
51
+ + `<div class="vl__empty" hidden><span>${icon('search')}</span><b></b></div>`
52
+ + '<span class="vl__sr" role="status"></span></div>';
53
+ const root = el.firstElementChild, vp = root.querySelector('.vl__vp'), sizer = root.querySelector('.vl__sizer');
54
+ const hl = root.querySelector('.vl__hl'), emptyEl = root.querySelector('.vl__empty'), live = root.querySelector('.vl__sr');
55
+ const say = (t) => { live.textContent = t; };
56
+
57
+ /* ---------- items + keys ---------- */
58
+ let items = null, n = 0, kIdx = null;
59
+ const setItems = (v) => {
60
+ if (typeof v === 'number') { items = null; n = Math.max(0, v | 0); }
61
+ else { items = Array.isArray(v) ? v : []; n = items.length; }
62
+ kIdx = null;
63
+ };
64
+ const itemAt = (i) => (items ? items[i] : i);
65
+ const keyAt = (i) => {
66
+ const it = itemAt(i);
67
+ if (o.key) return o.key(it, i);
68
+ if (it != null && typeof it === 'object') return it.id ?? it.key ?? i;
69
+ return items ? it : i;
70
+ };
71
+ const indexOfKey = (k) => {
72
+ if (!kIdx) { kIdx = new Map(); for (let i = 0; i < n; i++) if (!kIdx.has(keyAt(i))) kIdx.set(keyAt(i), i); }
73
+ return kIdx.has(k) ? kIdx.get(k) : -1;
74
+ };
75
+
76
+ /* ---------- sizes: one height for all, or measured heights + running offsets ---------- */
77
+ const hByKey = new Map();
78
+ let sizes = null, offs = null;
79
+ const rebuild = () => {
80
+ if (!auto) return;
81
+ sizes = new Float64Array(n); offs = new Float64Array(n + 1);
82
+ for (let i = 0; i < n; i++) { const h = hByKey.get(keyAt(i)) ?? est; sizes[i] = h; offs[i + 1] = offs[i] + h; }
83
+ };
84
+ const fromIdx = (i) => { for (let k = i; k < n; k++) offs[k + 1] = offs[k] + sizes[k]; };
85
+ const sizeOf = (i) => (auto ? sizes[i] : fixed);
86
+ const offOf = (i) => (auto ? offs[i] : i * fixed);
87
+ const total = () => (auto ? offs[n] : n * fixed);
88
+ const indexAt = (y) => {
89
+ if (n <= 0) return 0;
90
+ if (!auto) return clamp(Math.floor(y / fixed), 0, n - 1);
91
+ let a = 0, b = n - 1;
92
+ while (a < b) { const m = (a + b + 1) >> 1; if (offs[m] <= y) a = m; else b = m - 1; }
93
+ return a;
94
+ };
95
+
96
+ /* ---------- rows: a small pool of elements, reused as you scroll ---------- */
97
+ const rows = new Map(); // index → element
98
+ const pool = [];
99
+ let active = -1, selKey, vs = 0, ve = -1, painted = false, stw = null;
100
+ if (o.value !== undefined) selKey = o.value;
101
+ const makeRow = () => {
102
+ const r = document.createElement('div');
103
+ r.className = 'vl__row';
104
+ r.setAttribute('role', sel ? 'option' : 'listitem');
105
+ return r;
106
+ };
107
+ const release = (r) => {
108
+ g.killTweensOf(r);
109
+ r.style.removeProperty('opacity'); r.style.removeProperty('--vl-rise');
110
+ r.remove();
111
+ if (pool.length < 64) pool.push(r);
112
+ };
113
+ const fill = (r, i, force) => {
114
+ const k = keyAt(i);
115
+ if (force || r.__k !== k || r.__n !== n) {
116
+ if (force || r.__k !== k) {
117
+ const out = o.render ? o.render(itemAt(i), i) : esc(itemAt(i));
118
+ if (out instanceof Node) r.replaceChildren(out); else r.innerHTML = out ?? '';
119
+ r.__k = k;
120
+ }
121
+ r.__n = n;
122
+ r.setAttribute('aria-setsize', n);
123
+ }
124
+ if (r.__i !== i) { r.__i = i; r.id = `${base}-${i}`; r.dataset.i = i; r.setAttribute('aria-posinset', i + 1); }
125
+ if (sel) {
126
+ const s = selKey !== undefined && k === selKey;
127
+ if (r.__s !== s) { r.__s = s; r.setAttribute('aria-selected', String(s)); r.classList.toggle('is-sel', s); }
128
+ r.classList.toggle('is-active', i === active);
129
+ }
130
+ const y = offOf(i);
131
+ if (r.__y !== y) { r.__y = y; r.style.transform = `translateY(${y}px)`; }
132
+ };
133
+
134
+ const paint = (force = false) => {
135
+ emptyEl.hidden = n > 0;
136
+ if (!n) {
137
+ rows.forEach(release); rows.clear();
138
+ sizer.style.height = '0px'; vs = 0; ve = -1;
139
+ vp.removeAttribute('aria-activedescendant'); placeHl(false); report();
140
+ return;
141
+ }
142
+ for (let pass = 0; pass < 4; pass++) {
143
+ const top = vp.scrollTop, h = vp.clientHeight || est * 8;
144
+ const a = indexAt(top), b = indexAt(top + h - 1);
145
+ const s = Math.max(0, a - over), e = Math.min(n - 1, b + over);
146
+ rows.forEach((r, i) => { if (i < s || i > e) { rows.delete(i); release(r); } });
147
+ let prev = hl || null;
148
+ for (let i = s; i <= e; i++) {
149
+ let r = rows.get(i);
150
+ if (!r) { r = pool.pop() || makeRow(); r.__i = -1; r.__y = null; rows.set(i, r); }
151
+ fill(r, i, force);
152
+ const want = prev ? prev.nextSibling : sizer.firstChild; // keep page order = row order
153
+ if (r !== want) sizer.insertBefore(r, want);
154
+ prev = r;
155
+ }
156
+ vs = a; ve = b;
157
+ if (!auto) break;
158
+ // measure what was just drawn; rows above the view that change size move the scroll so nothing jumps
159
+ let first = n, shift = 0;
160
+ rows.forEach((r, i) => {
161
+ const hh = r.offsetHeight;
162
+ if (!hh || Math.abs(hh - sizes[i]) < 0.5) return;
163
+ if (i < a) shift += hh - sizes[i];
164
+ sizes[i] = hh; hByKey.set(r.__k, hh); first = Math.min(first, i);
165
+ });
166
+ if (first === n) break;
167
+ fromIdx(first);
168
+ sizer.style.height = `${total()}px`;
169
+ if (shift && !stw) vp.scrollTop = top + shift;
170
+ force = false;
171
+ }
172
+ sizer.style.height = `${total()}px`;
173
+ if (sel) {
174
+ if (active >= 0 && rows.has(active)) vp.setAttribute('aria-activedescendant', `${base}-${active}`);
175
+ else vp.removeAttribute('aria-activedescendant');
176
+ placeHl(false);
177
+ }
178
+ report();
179
+ };
180
+
181
+ /* ---------- first paint: the rows on screen rise in ---------- */
182
+ const rise = () => {
183
+ if (RM()) return;
184
+ const list = [];
185
+ for (let i = vs; i <= ve; i++) if (rows.get(i)) list.push(rows.get(i));
186
+ if (!list.length) return;
187
+ g.fromTo(list, { opacity: 0, '--vl-rise': '14px' }, { opacity: 1, '--vl-rise': '0px', duration: 0.5, ease: 'power3.out', stagger: Math.min(0.04, 0.5 / list.length),
188
+ onComplete: () => list.forEach((r) => { r.style.removeProperty('opacity'); r.style.removeProperty('--vl-rise'); }) });
189
+ };
190
+
191
+ /* ---------- the active-row highlight slides from row to row ---------- */
192
+ let hlY = null, hlH = null;
193
+ const placeHl = (animate) => {
194
+ if (!hl) return;
195
+ if (active < 0 || active >= n) { if (hlY !== null) { g.killTweensOf(hl); g.to(hl, { opacity: 0, duration: RM() ? 0 : 0.15 }); hlY = hlH = null; } return; }
196
+ const y = offOf(active), h = sizeOf(active);
197
+ if (y === hlY && h === hlH) return;
198
+ const first = hlY === null;
199
+ hlY = y; hlH = h;
200
+ if (first || RM() || (!animate && !g.isTweening(hl))) { g.killTweensOf(hl); g.set(hl, { y, height: h, opacity: 1 }); return; }
201
+ g.to(hl, { y, height: h, opacity: 1, duration: 0.24, ease: 'power3.out', overwrite: 'auto' });
202
+ };
203
+ const setActive = (i, { scroll = true, animate = true } = {}) => {
204
+ if (!n) return;
205
+ i = clamp(i, 0, n - 1);
206
+ active = i;
207
+ rows.forEach((r, j) => r.classList.toggle('is-active', j === i));
208
+ placeHl(animate); // before paint(), which would place it at once
209
+ if (scroll) jump(i, 'auto');
210
+ paint();
211
+ };
212
+ const choose = (i, tell = true) => {
213
+ if (!sel || i < 0 || i >= n) return;
214
+ selKey = keyAt(i);
215
+ rows.forEach((r, j) => fill(r, j));
216
+ if (tell) o.onSelect?.(itemAt(i), i, api);
217
+ };
218
+ const selIndex = () => (selKey === undefined ? -1 : indexOfKey(selKey));
219
+
220
+ /* ---------- scrolling to a row ---------- */
221
+ const targetFor = (i, align) => {
222
+ const top = offOf(i), h = sizeOf(i), vh = vp.clientHeight, cur = vp.scrollTop;
223
+ let y;
224
+ if (align === 'center') y = top - (vh - h) / 2;
225
+ else if (align === 'end') y = top + h - vh;
226
+ else if (align === 'start') y = top;
227
+ else y = top < cur ? top : top + h > cur + vh ? top + h - vh : cur;
228
+ return clamp(y, 0, Math.max(0, total() - vh));
229
+ };
230
+ const jump = (i, align) => { const y = targetFor(i, align); if (Math.abs(y - vp.scrollTop) >= 1) { vp.scrollTop = y; paint(); } };
231
+ const scrollTo = (index, { align = 'auto', smooth = false } = {}) => new Promise((done) => {
232
+ if (!n) { done(false); return; }
233
+ const i = clamp(index | 0, 0, n - 1);
234
+ stw?.kill(); stw = null;
235
+ const land = () => { // with measured rows, sizes near the target are now known: land exactly
236
+ paint();
237
+ if (auto) { jump(i, align); jump(i, align); }
238
+ done(true);
239
+ };
240
+ const y = targetFor(i, align), from = vp.scrollTop;
241
+ if (!smooth || RM() || Math.abs(y - from) < 1) { vp.scrollTop = y; land(); return; }
242
+ const st = { y: from };
243
+ stw = g.to(st, { y, duration: Math.min(1.1, 0.35 + Math.abs(y - from) / 5000), ease: 'power3.inOut',
244
+ onUpdate: () => { vp.scrollTop = st.y; },
245
+ onComplete: () => { stw = null; land(); },
246
+ onInterrupt: () => done(false) });
247
+ });
248
+
249
+ /* ---------- events ---------- */
250
+ on(vp, 'scroll', () => paint(), { passive: true });
251
+ const stop = () => { if (stw) { stw.kill(); stw = null; } };
252
+ on(vp, 'wheel', stop, { passive: true });
253
+ on(vp, 'touchstart', stop, { passive: true });
254
+ if (sel) {
255
+ on(vp, 'click', (e) => {
256
+ const r = e.target.closest('.vl__row');
257
+ ptr = false;
258
+ if (!r || !sizer.contains(r)) return;
259
+ const i = +r.dataset.i;
260
+ setActive(i);
261
+ choose(i);
262
+ });
263
+ let ptr = false; // focus from a press: the click picks the row
264
+ on(vp, 'pointerdown', () => { ptr = true; });
265
+ on(vp, 'focus', () => {
266
+ if (ptr) { ptr = false; return; }
267
+ if (active >= 0 || !n) return;
268
+ const si = selIndex();
269
+ setActive(si >= 0 ? si : vs, { scroll: si >= 0, animate: false });
270
+ });
271
+ on(vp, 'keydown', (e) => {
272
+ if (!n || e.target !== vp) return;
273
+ stop();
274
+ const k = e.key, page = Math.max(1, ve - vs);
275
+ const cur = active >= 0 ? active : vs;
276
+ let i;
277
+ if (k === 'ArrowDown') i = active < 0 ? cur : cur + 1;
278
+ else if (k === 'ArrowUp') i = active < 0 ? cur : cur - 1;
279
+ else if (k === 'PageDown') i = cur + page;
280
+ else if (k === 'PageUp') i = cur - page;
281
+ else if (k === 'Home') i = 0;
282
+ else if (k === 'End') i = n - 1;
283
+ else if ((k === 'Enter' || k === ' ') && active >= 0) { e.preventDefault(); choose(active); return; }
284
+ else return;
285
+ e.preventDefault();
286
+ setActive(i);
287
+ });
288
+ }
289
+
290
+ let raf = 0, lastW = 0, lastH = 0;
291
+ const ro = new ResizeObserver(() => {
292
+ cancelAnimationFrame(raf);
293
+ raf = requestAnimationFrame(() => {
294
+ const w = vp.clientWidth, h = vp.clientHeight;
295
+ if (w === lastW && h === lastH) return;
296
+ const wide = auto && w !== lastW && lastW !== 0;
297
+ lastW = w; lastH = h;
298
+ if (wide && n) { // new width: wrapped rows change height; keep the top row in place
299
+ const ai = vs, aOff = offOf(vs) - vp.scrollTop;
300
+ hByKey.clear(); rebuild();
301
+ sizer.style.height = `${total()}px`;
302
+ vp.scrollTop = Math.max(0, offOf(ai) - aOff);
303
+ }
304
+ paint();
305
+ if (!painted && n) { painted = true; rise(); }
306
+ });
307
+ });
308
+
309
+ /* ---------- report what is drawn ---------- */
310
+ let lastR = '';
311
+ const range = () => ({ start: n ? vs : 0, end: n ? ve : -1, rendered: rows.size, count: n });
312
+ const report = () => {
313
+ const r = range(), k = `${r.start},${r.end},${r.rendered},${r.count}`;
314
+ if (k === lastR) return;
315
+ lastR = k;
316
+ o.onRange?.(r, api);
317
+ };
318
+
319
+ const api = {
320
+ root,
321
+ get range() { return range(); },
322
+ get count() { return n; },
323
+ get selected() { return selIndex(); },
324
+ get active() { return active; },
325
+ item: (i) => itemAt(i),
326
+ update(next) {
327
+ const had = n;
328
+ // remember the first row in view and how far it sits from the top, by key
329
+ const aKey = n ? keyAt(vs) : undefined, aOff = n ? offOf(vs) - vp.scrollTop : 0;
330
+ const actKey = active >= 0 && active < n ? keyAt(active) : undefined;
331
+ stop();
332
+ setItems(next);
333
+ rebuild();
334
+ const ai = aKey === undefined ? -1 : indexOfKey(aKey);
335
+ active = actKey === undefined ? -1 : indexOfKey(actKey);
336
+ sizer.style.height = `${total()}px`;
337
+ vp.scrollTop = ai >= 0 ? clamp(offOf(ai) - aOff, 0, Math.max(0, total() - vp.clientHeight)) : 0;
338
+ rows.forEach((r) => { r.__k = undefined; }); // same index may now hold another item
339
+ paint();
340
+ if (n !== had) say(n ? W.count(n) : W.empty);
341
+ if (!had && n && vp.clientHeight) rise();
342
+ else if (!n && !RM()) g.fromTo(emptyEl, { opacity: 0, y: 8 }, { opacity: 1, y: 0, duration: 0.4, ease: 'power3.out', clearProps: 'opacity,transform' });
343
+ return api;
344
+ },
345
+ scrollTo,
346
+ select(index, { scroll = true } = {}) {
347
+ if (!sel || !n) return false;
348
+ const i = clamp(index | 0, 0, n - 1);
349
+ setActive(i, { scroll });
350
+ choose(i, false);
351
+ return true;
352
+ },
353
+ refresh() { rows.forEach((r, i) => fill(r, i, true)); paint(); return api; },
354
+ destroy() {
355
+ ac.abort(); ro.disconnect(); cancelAnimationFrame(raf);
356
+ stw?.kill();
357
+ g.killTweensOf([...rows.values(), hl, emptyEl].filter(Boolean));
358
+ rows.clear(); pool.length = 0;
359
+ el.innerHTML = '';
360
+ },
361
+ };
362
+
363
+ /* ---------- build ---------- */
364
+ emptyEl.querySelector('b').textContent = W.empty;
365
+ setItems(o.count != null ? o.count : o.items);
366
+ rebuild();
367
+ if (sel && selKey !== undefined) { const si = selIndex(); if (si >= 0) { active = si; } }
368
+ paint();
369
+ if (sel && active >= 0) { jump(active, 'center'); paint(); }
370
+ if (vp.clientHeight && n) { painted = true; rise(); }
371
+ ro.observe(vp);
372
+ return api;
373
+ };