@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/kanban.js ADDED
@@ -0,0 +1,319 @@
1
+ /* Kanban board: columns of cards you drag from one column to another or up and down.
2
+ A picked-up card lifts off the board and hangs from where you hold it, swinging a little with
3
+ the speed you move it. A dashed gap opens where it will land and the other cards slide aside to
4
+ make room. Let go and it flies into the gap and settles. Columns can have a limit: the count turns
5
+ amber when full and, if strict, the column refuses more cards (it tints red, the gap stays put).
6
+ On a phone, hold a card for a moment to pick it up; a plain swipe still scrolls the board.
7
+ Keyboard: Space picks a focused card up, the arrow keys move it, Space drops it, Escape puts it back. */
8
+ import * as M from '@gecko-ui-kit/motion';
9
+ import { icon } from '@gecko-ui-kit/icons';
10
+ import { esc, tag } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
14
+ const WORDS = {
15
+ empty: 'Nothing here yet',
16
+ add: 'Add card',
17
+ hint: 'Space picks up, arrow keys move, Space drops, Escape cancels.',
18
+ grabbed: (title, col, pos, total) => `Picked up ${title}. ${col}, ${pos} of ${total}.`,
19
+ moving: (col, pos, total) => `${col}, ${pos} of ${total}.`,
20
+ dropped: (title, col, pos) => `${title} dropped in ${col} at ${pos}.`,
21
+ cancelled: (title) => `${title} put back.`,
22
+ refused: (col) => `${col} can't take this card.`,
23
+ full: (col) => `${col} is full`,
24
+ };
25
+
26
+ /** The card a board shows when you don't give it your own render(): tags, a title, a line of text, a footer. */
27
+ const defaultCard = (c) => `${c.tags?.length ? `<div class="kb__tags">${c.tags.map((t) => (typeof t === 'string' ? tag(t, 'plain', false) : tag(t.label, t.tone || 'plain', false))).join('')}</div>` : ''}`
28
+ + `<b class="kb__title">${esc(c.title ?? '')}</b>${c.text ? `<p class="kb__text">${esc(c.text)}</p>` : ''}${c.meta ? `<div class="kb__meta">${c.meta}</div>` : ''}`;
29
+
30
+ let uid = 0;
31
+ /**
32
+ * const kb = kanban(el, {
33
+ * columns: [{ id, title, color, limit }], // limit: how many cards it should hold
34
+ * cards: [{ id, column, title, text, tags: ['Bug' | { label, tone }], meta: '<html>', color }],
35
+ * render: (card) => '<html>', // your own card inside the frame (default: tags, title, text, meta)
36
+ * strictLimit: false, // true: a full column takes no more cards
37
+ * canDrop: (card, columnId) => true, // your own rules, e.g. only reviewed work goes to Done
38
+ * onMove(card, { from, to, index, fromIndex }, kb) // after a drop; return false to put it back
39
+ * onOpen(card, el, kb), // a click or Enter on a card
40
+ * onAdd(columnId, kb), // shows an "Add card" button under each column
41
+ * words: { … } // every text, for another language
42
+ * })
43
+ * kb.cards() · kb.add(card, index?) · kb.update(id, patch) · kb.remove(id) · kb.move(id, column, index) · kb.destroy()
44
+ * Column width: --kb-col (280px; most of the screen on phones).
45
+ */
46
+ export const kanban = (el, opts = {}) => {
47
+ el = $$(el)[0];
48
+ if (!el) return null;
49
+ const W = { ...WORDS, ...opts.words };
50
+ const o = { strictLimit: false, render: defaultCard, ...opts };
51
+ const hintId = `kb-hint-${++uid}`;
52
+ let columns = (o.columns || []).map((c) => ({ ...c }));
53
+ const data = new Map((o.cards || []).map((c) => [String(c.id), { ...c }]));
54
+
55
+ const root = document.createElement('div');
56
+ root.className = 'kb';
57
+ el.innerHTML = ''; el.append(root);
58
+
59
+ const cardHTML = (c) => `<div class="kb__card${c.color ? ' has-c' : ''}" role="listitem" tabindex="0" data-id="${esc(c.id)}" aria-describedby="${hintId}"${c.color ? ` style="--kb-c:${esc(c.color)}"` : ''}>${o.render(c)}</div>`;
60
+ const colHTML = (col) => `<section class="kb__col" data-col="${esc(col.id)}"${col.color ? ` style="--kb-c:${esc(col.color)}"` : ''}>`
61
+ + `<header class="kb__head"><i class="kb__dot" aria-hidden="true"></i><h3>${esc(col.title)}</h3><span class="kb__count"></span></header>`
62
+ + `<div class="kb__list" role="list" aria-label="${esc(col.title)}" data-empty="${esc(W.empty)}">${[...data.values()].filter((c) => String(c.column) === String(col.id)).map(cardHTML).join('')}</div>`
63
+ + `${o.onAdd ? `<button type="button" class="kb__add">${icon('plus')}<span>${esc(W.add)}</span></button>` : ''}</section>`;
64
+
65
+ const render = () => {
66
+ root.innerHTML = columns.map(colHTML).join('') + `<p class="kb__sr" id="${hintId}">${esc(W.hint)}</p><p class="kb__sr" role="status"></p>`;
67
+ counts(true);
68
+ };
69
+
70
+ const colEl = (id) => root.querySelector(`.kb__col[data-col="${CSS.escape(String(id))}"]`);
71
+ const listOf = (id) => colEl(id)?.querySelector('.kb__list');
72
+ const colOf = (cardEl) => cardEl.closest('.kb__col')?.dataset.col;
73
+ const colData = (id) => columns.find((c) => String(c.id) === String(id));
74
+ const cardsIn = (list) => [...list.children].filter((x) => x.classList.contains('kb__card') && !x.classList.contains('is-src'));
75
+ const elOf = (id) => root.querySelector(`.kb__card[data-id="${CSS.escape(String(id))}"]`);
76
+ const pub = (id) => ({ ...data.get(String(id)) });
77
+ const say = (t) => { const s = root.querySelector('.kb__sr[role="status"]'); if (s) s.textContent = t; };
78
+ const titleOf = (id) => data.get(String(id))?.title ?? String(id);
79
+
80
+ /** Update the count beside each column title (and its full / over-the-limit look). */
81
+ const counts = (quiet) => columns.forEach((col) => {
82
+ const c = colEl(col.id); if (!c) return;
83
+ const n = cardsIn(c.querySelector('.kb__list')).length + (c.querySelector('.kb__ph') ? 1 : 0); // the gap counts where the card will land
84
+ const span = c.querySelector('.kb__count'), text = col.limit ? `${n}/${col.limit}` : String(n);
85
+ if (span.textContent !== text) { span.textContent = text; if (!quiet && !RM()) M.pop(span); }
86
+ c.classList.toggle('is-full', !!col.limit && n >= col.limit); c.classList.toggle('is-over', !!col.limit && n > col.limit);
87
+ span.title = col.limit && n >= col.limit ? W.full(col.title) : '';
88
+ });
89
+
90
+ /** Move things in the DOM, then slide every card from where it was to where it is now. */
91
+ const flip = (mutate, skip) => {
92
+ const els = [...root.querySelectorAll('.kb__card:not(.is-src), .kb__ph')];
93
+ const before = new Map(els.map((x) => [x, x.getBoundingClientRect()]));
94
+ mutate();
95
+ if (RM()) return;
96
+ before.forEach((r, x) => {
97
+ if (x === skip || !x.isConnected) return;
98
+ const n = x.getBoundingClientRect(), dx = r.left - n.left, dy = r.top - n.top;
99
+ if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) g.fromTo(x, { x: dx, y: dy }, { x: 0, y: 0, duration: 0.3, ease: 'power3.out', overwrite: 'auto', clearProps: 'transform' });
100
+ });
101
+ };
102
+
103
+ const allowed = (id, to, from) => {
104
+ if (o.canDrop && o.canDrop(pub(id), to) === false) return false;
105
+ const col = colData(to);
106
+ if (o.strictLimit && col?.limit && String(to) !== String(from) && cardsIn(listOf(to)).length >= col.limit) return false;
107
+ return true;
108
+ };
109
+
110
+ /* ---------- pointer dragging ---------- */
111
+ let drag = null, eatClick = false, raf = 0;
112
+ const lift = (d) => {
113
+ d.live = true; eatClick = true;
114
+ const { card } = d, r = card.getBoundingClientRect();
115
+ d.ox = d.x - r.left; d.oy = d.y - r.top; d.w = r.width; d.h = r.height;
116
+ d.from = colOf(card); d.fromIndex = cardsIn(card.parentElement).indexOf(card);
117
+ d.ph = document.createElement('div'); d.ph.className = 'kb__ph'; d.ph.style.height = `${r.height}px`;
118
+ card.before(d.ph);
119
+ d.ghost = card.cloneNode(true); d.ghost.classList.add('is-ghost'); d.ghost.removeAttribute('tabindex'); d.ghost.setAttribute('aria-hidden', 'true');
120
+ Object.assign(d.ghost.style, { width: `${r.width}px`, height: `${r.height}px`, left: `${r.left}px`, top: `${r.top}px` });
121
+ document.body.append(d.ghost);
122
+ card.classList.add('is-src'); // stays in the page (hidden), so the touch keeps reaching it
123
+ root.classList.add('is-dragging'); colEl(d.from)?.classList.add('is-from');
124
+ d.rot = RM() ? null : g.quickTo(d.ghost, 'rotation', { duration: 0.35, ease: 'power3.out' });
125
+ if (!RM()) g.fromTo(d.ghost, { scale: 1 }, { scale: 1.04, duration: 0.2, ease: 'back.out(3)', transformOrigin: `${d.ox}px ${d.oy}px` });
126
+ if (d.touch) navigator.vibrate?.(8);
127
+ d.lastX = d.x; d.lastT = performance.now(); d.moved = d.lastT;
128
+ say(W.grabbed(titleOf(card.dataset.id), colData(d.from)?.title ?? '', d.fromIndex + 1, cardsIn(card.parentElement).length + 1));
129
+ loop();
130
+ };
131
+ /** Where the card would land under the pointer: { list, index } (null over nothing). */
132
+ const target = (d) => {
133
+ const hit = document.elementFromPoint(d.x, d.y)?.closest('.kb__col');
134
+ if (!hit || !root.contains(hit)) return null;
135
+ const list = hit.querySelector('.kb__list');
136
+ const items = cardsIn(list);
137
+ let index = items.length;
138
+ for (let i = 0; i < items.length; i++) { const r = items[i].getBoundingClientRect(); if (d.y < r.top + r.height / 2) { index = i; break; } }
139
+ return { list, col: hit.dataset.col, index };
140
+ };
141
+ const follow = (d) => {
142
+ d.ghost.style.left = `${d.x - d.ox}px`; d.ghost.style.top = `${d.y - d.oy}px`;
143
+ const t = target(d);
144
+ root.querySelectorAll('.kb__col.is-no, .kb__col.is-over-t').forEach((c) => c.classList.remove('is-no', 'is-over-t'));
145
+ if (!t) return;
146
+ if (!allowed(d.card.dataset.id, t.col, d.from)) { colEl(t.col)?.classList.add('is-no'); return; }
147
+ colEl(t.col)?.classList.add('is-over-t');
148
+ const items = cardsIn(t.list), ref = items[t.index] || null;
149
+ if (d.ph.parentElement === t.list && (d.ph.nextElementSibling === ref || (ref == null && !d.ph.nextElementSibling))) return;
150
+ flip(() => { t.list.insertBefore(d.ph, ref); }, d.ph);
151
+ counts();
152
+ };
153
+ /** Each frame while dragging: swing back to upright when still, scroll near the edges. */
154
+ const loop = () => {
155
+ cancelAnimationFrame(raf);
156
+ raf = requestAnimationFrame(function step() {
157
+ const d = drag; if (!d?.live) return;
158
+ const now = performance.now();
159
+ if (d.rot && now - d.moved > 70) d.rot(0);
160
+ let scrolled = false;
161
+ const br = root.getBoundingClientRect(), E = 56;
162
+ if (d.x > br.right - E) { root.scrollLeft += Math.ceil((d.x - (br.right - E)) / 4); scrolled = true; } else if (d.x < br.left + E) { root.scrollLeft -= Math.ceil((br.left + E - d.x) / 4); scrolled = true; }
163
+ const list = document.elementFromPoint(d.x, d.y)?.closest('.kb__list');
164
+ if (list && root.contains(list)) { const lr = list.getBoundingClientRect(); if (d.y > lr.bottom - 40) { list.scrollTop += 6; scrolled = true; } else if (d.y < lr.top + 40) { list.scrollTop -= 6; scrolled = true; } }
165
+ if (scrolled) follow(d);
166
+ raf = requestAnimationFrame(step);
167
+ });
168
+ };
169
+ const end = (d, cancel) => {
170
+ cancelAnimationFrame(raf);
171
+ root.querySelectorAll('.kb__col.is-no, .kb__col.is-over-t, .kb__col.is-from').forEach((c) => c.classList.remove('is-no', 'is-over-t', 'is-from'));
172
+ const { card, ghost, ph } = d;
173
+ if (cancel) flip(() => { const list = listOf(d.from); list.insertBefore(ph, cardsIn(list)[d.fromIndex] || null); }, ph);
174
+ const finish = () => {
175
+ ph.replaceWith(card); card.classList.remove('is-src'); ghost.remove(); root.classList.remove('is-dragging');
176
+ counts();
177
+ if (!RM()) g.fromTo(card, { scaleY: 0.94, scaleX: 1.02 }, { scaleY: 1, scaleX: 1, duration: 0.4, ease: 'back.out(3)', clearProps: 'transform' });
178
+ if (cancel) { say(W.cancelled(titleOf(card.dataset.id))); return; }
179
+ commit(card, d.from, d.fromIndex);
180
+ };
181
+ if (RM()) { finish(); return; }
182
+ const r = ph.getBoundingClientRect();
183
+ g.killTweensOf(ghost);
184
+ g.to(ghost, { left: r.left, top: r.top, rotation: 0, scale: 1, duration: 0.32, ease: 'power3.out', onComplete: finish });
185
+ };
186
+ /** After a card has landed: tell the app, or put it back if the app says no. */
187
+ const commit = (card, from, fromIndex) => {
188
+ const id = card.dataset.id, to = colOf(card), index = cardsIn(card.parentElement).indexOf(card);
189
+ if (String(to) === String(from) && index === fromIndex) return;
190
+ const it = data.get(String(id)); const before = it.column; it.column = to;
191
+ say(W.dropped(titleOf(id), colData(to)?.title ?? '', index + 1));
192
+ if (o.onMove?.(pub(id), { from, to, index, fromIndex }, api) === false) {
193
+ it.column = before;
194
+ flip(() => { const list = listOf(from); list.insertBefore(card, cardsIn(list).filter((x) => x !== card)[fromIndex] || null); });
195
+ counts();
196
+ }
197
+ };
198
+
199
+ const ac = new AbortController(), on = { signal: ac.signal };
200
+ root.addEventListener('pointerdown', (e) => {
201
+ if (e.button > 0 || keyGrab) return;
202
+ const card = e.target.closest('.kb__card'); if (!card || !root.contains(card)) return;
203
+ if (e.target.closest('a, button, input, select, textarea, [data-no-drag]')) return;
204
+ drag = { card, x: e.clientX, y: e.clientY, x0: e.clientX, y0: e.clientY, pid: e.pointerId, touch: e.pointerType === 'touch', live: false };
205
+ eatClick = false;
206
+ if (drag.touch) { const st = drag; st.timer = setTimeout(() => { if (drag === st) lift(st); }, 320); }
207
+ }, on);
208
+ addEventListener('pointermove', (e) => {
209
+ const d = drag; if (!d || e.pointerId !== d.pid) return;
210
+ d.x = e.clientX; d.y = e.clientY;
211
+ if (!d.live) {
212
+ const far = Math.hypot(d.x - d.x0, d.y - d.y0);
213
+ if (d.touch) { if (far > 8) { clearTimeout(d.timer); drag = null; } return; } // a swipe: let the board scroll
214
+ if (far < 5) return;
215
+ lift(d);
216
+ }
217
+ const now = performance.now(), dt = Math.max(1, now - d.lastT), vx = (d.x - d.lastX) / dt;
218
+ d.lastX = d.x; d.lastT = now; d.moved = now;
219
+ d.rot?.(clamp(vx * 14, -9, 9)); // it swings with the speed you move it
220
+ follow(d);
221
+ }, on);
222
+ const up = (cancel) => (e) => {
223
+ const d = drag; if (!d || e.pointerId !== d.pid) return;
224
+ clearTimeout(d.timer); drag = null;
225
+ if (d.live) { end(d, cancel); setTimeout(() => { eatClick = false; }, 0); }
226
+ };
227
+ addEventListener('pointerup', up(false), on);
228
+ addEventListener('pointercancel', up(true), on);
229
+ document.addEventListener('touchmove', (e) => { if (drag?.live) e.preventDefault(); }, { passive: false, signal: ac.signal });
230
+ root.addEventListener('contextmenu', (e) => { if (e.target.closest('.kb__card')) e.preventDefault(); }, on);
231
+ root.addEventListener('click', (e) => {
232
+ if (eatClick) { eatClick = false; e.stopPropagation(); return; }
233
+ const add = e.target.closest('.kb__add'); if (add) { o.onAdd?.(colOf(add), api); return; }
234
+ const card = e.target.closest('.kb__card');
235
+ if (card && !keyGrab && !e.target.closest('a, button, input, select, textarea')) o.onOpen?.(pub(card.dataset.id), card, api);
236
+ }, on);
237
+
238
+ /* ---------- keyboard: pick up, move, drop ---------- */
239
+ let keyGrab = null;
240
+ const place = (card, col, index) => flip(() => { const list = listOf(col); list.insertBefore(card, cardsIn(list).filter((x) => x !== card)[index] || null); });
241
+ const where = (card) => { const col = colOf(card), list = card.parentElement; return { col, index: cardsIn(list).indexOf(card), total: cardsIn(list).length }; };
242
+ root.addEventListener('keydown', (e) => {
243
+ const card = e.target.closest('.kb__card'); if (!card || !root.contains(card)) return;
244
+ const id = card.dataset.id;
245
+ if (!keyGrab) {
246
+ if (e.key === ' ') { e.preventDefault(); const w = where(card); keyGrab = { card, from: w.col, fromIndex: w.index }; card.classList.add('is-grabbed'); root.classList.add('is-dragging'); say(W.grabbed(titleOf(id), colData(w.col)?.title ?? '', w.index + 1, w.total)); if (!RM()) g.fromTo(card, { scale: 1 }, { scale: 1.03, duration: 0.2, ease: 'back.out(3)' }); }
247
+ else if (e.key === 'Enter') { e.preventDefault(); o.onOpen?.(pub(id), card, api); }
248
+ return;
249
+ }
250
+ if (keyGrab.card !== card) return;
251
+ const w = where(card), ci = columns.findIndex((c) => String(c.id) === String(w.col));
252
+ const done = (cancel) => {
253
+ e.preventDefault(); const k = keyGrab; keyGrab = null;
254
+ card.classList.remove('is-grabbed'); root.classList.remove('is-dragging');
255
+ if (!RM()) g.to(card, { scale: 1, duration: 0.2, clearProps: 'transform' });
256
+ if (cancel) { place(card, k.from, k.fromIndex); counts(); say(W.cancelled(titleOf(id))); }
257
+ else commit(card, k.from, k.fromIndex);
258
+ card.focus();
259
+ };
260
+ if (e.key === ' ' || e.key === 'Enter') return done(false);
261
+ if (e.key === 'Escape') return done(true);
262
+ let to = null;
263
+ if (e.key === 'ArrowUp' && w.index > 0) to = [w.col, w.index - 1];
264
+ else if (e.key === 'ArrowDown' && w.index < w.total - 1) to = [w.col, w.index + 1];
265
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
266
+ const step = e.key === 'ArrowLeft' ? -1 : 1;
267
+ for (let k = ci + step; k >= 0 && k < columns.length; k += step) {
268
+ if (allowed(id, columns[k].id, keyGrab.from)) { to = [columns[k].id, Math.min(w.index, cardsIn(listOf(columns[k].id)).length)]; break; }
269
+ say(W.refused(columns[k].title));
270
+ }
271
+ }
272
+ if (!to) { if (e.key.startsWith('Arrow')) e.preventDefault(); return; }
273
+ e.preventDefault();
274
+ place(card, to[0], to[1]); counts(); card.focus({ preventScroll: false });
275
+ card.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
276
+ const nw = where(card); say(W.moving(colData(nw.col)?.title ?? '', nw.index + 1, nw.total));
277
+ }, on);
278
+
279
+ const api = {
280
+ el: root, opts: o,
281
+ /** Every card with the column it is in, in board order. */
282
+ cards: () => columns.flatMap((col) => cardsIn(listOf(col.id)).map((x) => ({ ...pub(x.dataset.id), column: col.id }))),
283
+ /** Add a card (it grows into its column). index: where in the column (default: the end). */
284
+ add(card, index) {
285
+ const c = { ...card }; data.set(String(c.id), c);
286
+ const list = listOf(c.column); if (!list) return null;
287
+ const t = document.createElement('template'); t.innerHTML = cardHTML(c).trim(); const x = t.content.firstElementChild;
288
+ flip(() => list.insertBefore(x, index != null ? cardsIn(list)[index] || null : null), x);
289
+ counts();
290
+ if (!RM()) g.fromTo(x, { opacity: 0, scale: 0.9, y: -6 }, { opacity: 1, scale: 1, y: 0, duration: 0.4, ease: 'back.out(2)', clearProps: 'all' });
291
+ return pub(c.id);
292
+ },
293
+ /** Change a card's fields; it is drawn again in place (a new column moves it there). */
294
+ update(id, patch) {
295
+ const it = data.get(String(id)); if (!it) return null;
296
+ const col = patch.column ?? it.column; Object.assign(it, patch, { column: it.column });
297
+ const x = elOf(id); if (x) { const t = document.createElement('template'); t.innerHTML = cardHTML(it).trim(); x.innerHTML = t.content.firstElementChild.innerHTML; x.style.cssText = t.content.firstElementChild.style.cssText; x.classList.toggle('has-c', !!it.color); }
298
+ if (String(col) !== String(it.column)) api.move(id, col);
299
+ return pub(id);
300
+ },
301
+ remove(id) {
302
+ const x = elOf(id); data.delete(String(id));
303
+ if (!x) return api;
304
+ if (RM()) { x.remove(); counts(); return api; }
305
+ g.to(x, { opacity: 0, scale: 0.92, duration: 0.2, ease: 'power2.in', onComplete: () => { flip(() => x.remove()); counts(); } });
306
+ return api;
307
+ },
308
+ /** Move a card from code (it slides there). */
309
+ move(id, column, index) {
310
+ const x = elOf(id), it = data.get(String(id)); if (!x || !it || !listOf(column)) return api;
311
+ it.column = column; place(x, column, index ?? cardsIn(listOf(column)).filter((y) => y !== x).length); counts();
312
+ return api;
313
+ },
314
+ setCards(list) { data.clear(); (list || []).forEach((c) => data.set(String(c.id), { ...c })); render(); return api; },
315
+ destroy() { ac.abort(); cancelAnimationFrame(raf); drag?.ghost?.remove(); el.innerHTML = ''; },
316
+ };
317
+ render();
318
+ return api;
319
+ };
@@ -0,0 +1,201 @@
1
+ /* Leaderboard: a ranked list — best sellers, top of the team, busiest rooms — with a bar under each
2
+ row that shows its value against the leader. Optional medals on the top three and avatars.
3
+ How it moves: on first show the rows rise in one after another, the bars stretch out and the
4
+ numbers count up. set(items) works out the new order and every row glides to its new place
5
+ (FLIP: measured before and after, then slid with GSAP). Bars stretch or shrink, numbers count to
6
+ the new value, rows that climbed flash and show “▲2” (rows that fell show a quiet “▼1”), rows that
7
+ are new to the list slide in with a “New” mark and rows that leave fade away where they stood.
8
+ The list's height follows. A polite live region sums up what changed (“Malee moved up to 1st”). */
9
+ import * as M from '@gecko-ui-kit/motion';
10
+ import { esc, av } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const ord = (n) => { const s = ['th', 'st', 'nd', 'rd'], v = n % 100; return `${n}${s[(v - 20) % 10] || s[v] || s[0]}`; };
14
+ const WORDS = {
15
+ label: 'Leaderboard',
16
+ place: (n) => ord(n), // “1st”, used in the announcements
17
+ rank: (n) => `${ord(n)} place:`, // read before each row (hidden)
18
+ up: (n) => `up ${n}`, down: (n) => `down ${n}`, // hidden text next to ▲2 / ▼1
19
+ fresh: 'New', freshSr: 'new', // the mark on a row that just joined (visible / read)
20
+ movedUp: (label, place) => `${label} moved up to ${place}`,
21
+ joined: (label, place) => `${label} joined at ${place}`,
22
+ dropped: (label) => `${label} dropped off the list`,
23
+ more: (n) => `${n} more ${n === 1 ? 'change' : 'changes'}`,
24
+ };
25
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
26
+ const decs = (v) => Math.min(4, (String(v).split('.')[1] || '').length);
27
+
28
+ /**
29
+ * const lb = leaderboard(el, {
30
+ * items: [{ id, label, value, sub, avatar }], // avatar: a person for av() — { name, ini, tone }
31
+ * max: 0, // rows shown (0 = all); a row that climbs into view slides in
32
+ * format: (v) => string, // the number on each row (gets in-between values while it counts)
33
+ * bars: true, // a bar under each row, the leader = full width
34
+ * medals: true, // gold, silver and bronze marks on the top three ranks
35
+ * label: '', // name for screen readers (default words.label)
36
+ * words: { label, place, rank, up, down, fresh, freshSr, movedUp, joined, dropped, more },
37
+ * })
38
+ * lb.set(items) // rows glide to their new ranks, bars stretch, numbers count
39
+ * lb.items // [{ …item, rank }] in rank order · lb.destroy()
40
+ */
41
+ export const leaderboard = (el, opts = {}) => {
42
+ el = $$(el)[0];
43
+ if (!el) return null;
44
+ const o = { items: [], max: 0, format: null, bars: true, medals: true, label: '', words: null, ...opts };
45
+ const W = { ...WORDS, ...o.words };
46
+ const max = +o.max > 0 ? Math.round(+o.max) : Infinity;
47
+ const fmt = (v) => (o.format ? String(o.format(v)) : Number(v).toLocaleString());
48
+ const shown = (to) => { const d = decs(to); return (v) => fmt(d ? +v.toFixed(d) : Math.round(v)); };
49
+
50
+ el.innerHTML = `<div class="lbd${o.bars ? '' : ' lbd--nobar'}"><ol class="lbd__list" role="list" aria-label="${esc(o.label || W.label)}"></ol>`
51
+ + '<span class="lbd__sr" role="status" aria-live="polite"></span></div>';
52
+ const root = el.firstElementChild, list = root.querySelector('.lbd__list'), live = root.querySelector('.lbd__sr[role="status"]');
53
+ const say = (t) => { live.textContent = ''; if (t) live.textContent = t; };
54
+
55
+ /* ---------- model ---------- */
56
+ let all = []; // every item, in rank order
57
+ const rows = new Map(); // id → row on show
58
+ const norm = (list) => {
59
+ const seen = new Set();
60
+ return (list || []).filter(Boolean).map((it, i) => {
61
+ let id = String(it.id ?? it.label ?? i);
62
+ while (seen.has(id)) id += '~';
63
+ seen.add(id);
64
+ const v = +it.value;
65
+ return { id, label: String(it.label ?? ''), value: Number.isFinite(v) ? v : 0, sub: it.sub == null ? '' : String(it.sub), avatar: it.avatar || null, raw: it, i };
66
+ });
67
+ };
68
+ const rankOf = (list) => new Map(list.map((it, i) => [it.id, i + 1]));
69
+ const sortAll = (list, prev) => list.sort((a, b) => b.value - a.value || (prev.get(a.id) ?? 1e9) - (prev.get(b.id) ?? 1e9) || a.i - b.i);
70
+
71
+ /* ---------- rows ---------- */
72
+ const make = (it) => {
73
+ const li = document.createElement('li');
74
+ li.className = 'lbd__row'; li.dataset.id = it.id;
75
+ li.innerHTML = '<span class="lbd__flash" aria-hidden="true"></span>'
76
+ + '<span class="lbd__rank"><span class="lbd__n" aria-hidden="true"></span><span class="lbd__sr"></span></span>'
77
+ + '<span class="lbd__av"></span>'
78
+ + '<span class="lbd__body"><span class="lbd__main"><span class="lbd__name"></span><small class="lbd__sub"></small></span>'
79
+ + `<span class="lbd__chg"></span><b class="lbd__val">${esc(fmt(0))}</b>${o.bars ? '<span class="lbd__bar" aria-hidden="true"><i></i></span>' : ''}</span>`;
80
+ const q = (s) => li.querySelector(s);
81
+ const r = { id: it.id, li, rank: 0, n: q('.lbd__n'), rsr: q('.lbd__rank .lbd__sr'), rankEl: q('.lbd__rank'), avEl: q('.lbd__av'), name: q('.lbd__name'), sub: q('.lbd__sub'),
82
+ chg: q('.lbd__chg'), val: q('.lbd__val'), bar: q('.lbd__bar i'), flash: q('.lbd__flash'), avKey: '' };
83
+ rows.set(it.id, r);
84
+ return r;
85
+ };
86
+ const fill = (r, it, rank) => {
87
+ r.name.textContent = it.label;
88
+ r.sub.textContent = it.sub;
89
+ const key = it.avatar ? JSON.stringify([it.avatar.name, it.avatar.ini, it.avatar.tone]) : '';
90
+ if (key !== r.avKey) { r.avKey = key; r.avEl.innerHTML = it.avatar ? av(it.avatar, 'sm') : ''; }
91
+ r.n.textContent = String(rank);
92
+ r.rsr.textContent = `${W.rank(rank)} `;
93
+ r.rankEl.className = `lbd__rank${o.medals && rank <= 3 ? ` is-m${rank}` : ''}`;
94
+ r.rank = rank;
95
+ };
96
+ const mark = (r, kind, d) => {
97
+ r.chg.className = `lbd__chg${kind ? ` is-${kind}` : ''}`;
98
+ r.chg.innerHTML = !kind ? ''
99
+ : kind === 'new' ? `<span aria-hidden="true">${esc(W.fresh)}</span><span class="lbd__sr">${esc(W.freshSr)}</span>`
100
+ : `<span aria-hidden="true">${kind === 'up' ? '▲' : '▼'}${d}</span><span class="lbd__sr">${esc(kind === 'up' ? W.up(d) : W.down(d))}</span>`;
101
+ };
102
+ const leave = (r, lr) => {
103
+ rows.delete(r.id);
104
+ const li = r.li, b = li.getBoundingClientRect();
105
+ g.killTweensOf([li, r.bar, r.flash, r.chg]);
106
+ if (RM()) { li.remove(); return; }
107
+ li.classList.add('is-leaving'); li.setAttribute('aria-hidden', 'true');
108
+ g.set(li, { clearProps: 'transform' });
109
+ Object.assign(li.style, { position: 'absolute', top: `${b.top - lr.top}px`, left: `${b.left - lr.left}px`, width: `${b.width}px`, margin: '0' });
110
+ g.to(li, { opacity: 0, x: -14, duration: 0.32, ease: 'power2.in', onComplete: () => li.remove() });
111
+ };
112
+
113
+ /* ---------- show a list: first time, or a change ---------- */
114
+ let firstDone = false;
115
+ const sync = (items) => {
116
+ const first = !firstDone;
117
+ firstDone = true;
118
+ const prevAll = rankOf(all); // ranks before this change (rows beyond max included)
119
+ all = sortAll(norm(items), prevAll);
120
+ const next = all.slice(0, max === Infinity ? all.length : max);
121
+ const topV = Math.max(0, ...all.map((it) => it.value));
122
+ root.classList.toggle('lbd--av', next.some((it) => it.avatar));
123
+
124
+ // First: where every row is now (as seen, mid-glide included)
125
+ const lr = list.getBoundingClientRect(), h0 = list.offsetHeight, before = new Map();
126
+ rows.forEach((r) => before.set(r.id, r.li.getBoundingClientRect().top));
127
+ const keep = new Set(next.map((it) => it.id)), dropped = [];
128
+ rows.forEach((r) => { if (!keep.has(r.id)) { dropped.push(r.name.textContent); leave(r, lr); } });
129
+
130
+ // Last: the new order in the DOM
131
+ const fresh = [];
132
+ next.forEach((it, i) => {
133
+ const rank = i + 1, was = prevAll.get(it.id);
134
+ let r = rows.get(it.id);
135
+ if (r) { g.killTweensOf([r.li, r.n, r.chg, r.flash]); g.set([r.li, r.n, r.chg], { clearProps: 'transform,opacity,zIndex' }); g.set(r.flash, { opacity: 0 }); } else { r = make(it); fresh.push(r.li); }
136
+ fill(r, it, rank);
137
+ if (first) mark(r, '');
138
+ else if (was == null) mark(r, 'new');
139
+ else if (was > rank) mark(r, 'up', was - rank);
140
+ else if (was < rank) mark(r, 'down', rank - was);
141
+ else mark(r, '');
142
+ list.append(r.li);
143
+ });
144
+
145
+ // Invert + play
146
+ const animate = !RM();
147
+ const h1 = list.offsetHeight;
148
+ if (animate && !first && h0 !== h1) g.fromTo(list, { height: h0 }, { height: h1, duration: 0.5, ease: 'power3.inOut', clearProps: 'height' });
149
+ if (animate && first) g.fromTo(fresh, { opacity: 0, y: 12 }, { opacity: 1, y: 0, duration: 0.5, ease: 'power3.out', stagger: 0.06, clearProps: 'opacity,transform' });
150
+ next.forEach((it, i) => {
151
+ const r = rows.get(it.id), was = prevAll.get(it.id), climbed = !first && was != null && was > r.rank;
152
+ const delay = first ? 0.1 + i * 0.06 : 0;
153
+ // the number and the bar
154
+ if (r.bar) g.killTweensOf(r.bar);
155
+ M.count(r.val, it.value, shown(it.value), { duration: first ? 1.1 : 0.8, delay });
156
+ if (r.bar) {
157
+ const w = `${topV > 0 ? clamp((it.value / topV) * 100, 0, 100) : 0}%`;
158
+ if (animate) g.to(r.bar, { width: w, duration: first ? 0.9 : 0.7, delay, ease: 'power3.out' }); else r.bar.style.width = w;
159
+ }
160
+ if (first || !animate) return;
161
+ // the glide
162
+ if (before.has(it.id)) {
163
+ const dy = before.get(it.id) - r.li.getBoundingClientRect().top;
164
+ if (Math.abs(dy) > 0.5) g.fromTo(r.li, { y: dy, zIndex: climbed ? 3 : 2 }, { y: 0, duration: 0.65, ease: 'back.out(1.1)', clearProps: 'transform,zIndex' });
165
+ } else g.fromTo(r.li, { opacity: 0, x: 28 }, { opacity: 1, x: 0, duration: 0.5, delay: 0.18, ease: 'power3.out', clearProps: 'opacity,transform' });
166
+ // climbers flash, marks pop in
167
+ if (climbed) {
168
+ g.fromTo(r.flash, { opacity: 0 }, { keyframes: { opacity: [0, 1, 1, 0] }, duration: 1.5, delay: 0.25, ease: 'none' });
169
+ M.flash(r.val);
170
+ }
171
+ if (r.chg.firstChild) g.fromTo(r.chg, { scale: 0.3, opacity: 0 }, { scale: 1, opacity: 1, duration: 0.45, delay: 0.4, ease: 'back.out(3)', clearProps: 'transform,opacity' });
172
+ if (was != null && was !== r.rank) g.fromTo(r.n, { yPercent: was > r.rank ? 70 : -70, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.4, delay: 0.2, ease: 'power3.out', clearProps: 'transform,opacity' });
173
+ });
174
+
175
+ // Tell screen readers what changed
176
+ if (first) return;
177
+ const msgs = [];
178
+ next.forEach((it, i) => {
179
+ const was = prevAll.get(it.id), place = W.place(i + 1);
180
+ if (was == null) msgs.push(W.joined(it.label, place));
181
+ else if (was > i + 1) msgs.push(W.movedUp(it.label, place));
182
+ });
183
+ dropped.forEach((label) => msgs.push(W.dropped(label)));
184
+ say(msgs.length ? `${msgs.slice(0, 3).join('. ')}${msgs.length > 3 ? `. ${W.more(msgs.length - 3)}` : ''}.` : '');
185
+ };
186
+
187
+ sync(o.items);
188
+
189
+ const api = {
190
+ root,
191
+ /** Every item in rank order, with its rank. */
192
+ get items() { return all.map((it, i) => ({ ...it.raw, rank: i + 1 })); },
193
+ set(items) { sync(items); return api; },
194
+ destroy() {
195
+ rows.forEach((r) => M.count(r.val, 0, String, { duration: 0 })); // stops any count still running
196
+ g.killTweensOf([root, list, ...root.querySelectorAll('*')]);
197
+ el.innerHTML = '';
198
+ },
199
+ };
200
+ return api;
201
+ };