@gecko-ui-kit/motion 0.0.0-stage → 0.8.1

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/hold.js ADDED
@@ -0,0 +1,169 @@
1
+ /* Hold to confirm: for actions that should not happen by accident (delete, end, pay, sign out).
2
+ Press and hold: colour floods the button from the left (the label turns white where it has
3
+ passed), the button sinks in a little and the icon starts to tremble harder as it nears the end.
4
+ Let go too early and the colour drains away, the button gives a small shake and says "Hold to
5
+ confirm" for a moment. Hold to the end and it bursts: a ring flies out, the icon turns into a
6
+ tick that draws itself and the label changes. The 'ring' look draws the progress as a circle
7
+ round a round icon button instead. Space or Enter held down works the same. */
8
+ import { g, RM, $$ } from './core.js';
9
+
10
+ const TICK = '<svg class="hold__tick" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/></svg>';
11
+ const RING = '<svg class="hold__ring" viewBox="0 0 100 100" aria-hidden="true"><circle class="hold__track" cx="50" cy="50" r="47" pathLength="1"/><circle class="hold__arc" cx="50" cy="50" r="47" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/></svg>';
12
+ const TONES = new Set(['accent', 'bad', 'good', 'warn']);
13
+
14
+ /**
15
+ * const h = holdConfirm(button, {
16
+ * duration: 1.2, // seconds to hold
17
+ * look: 'fill' | 'ring', // colour floods the button, or a circle fills round it (round icon buttons)
18
+ * tone: 'bad' | 'accent' | 'good' | 'warn',
19
+ * hint: 'Hold to confirm', // shown for a moment after letting go too early ('' = none)
20
+ * done: 'Done', // the label afterwards
21
+ * back: 0, // seconds until it resets by itself (0 = stays done until h.reset())
22
+ * haptic: true, // small buzzes on phones that support it
23
+ * onConfirm(button, h), onCancel(button, h, progress)
24
+ * })
25
+ * Use onConfirm instead of a click listener: a normal click does nothing on its own.
26
+ * h.progress · h.state ('idle' | 'holding' | 'done') · h.confirm() · h.reset() · h.destroy()
27
+ */
28
+ export const holdConfirm = (btn, opts = {}) => {
29
+ btn = $$(btn)[0];
30
+ if (!btn) return null;
31
+ if (btn.__hold) { Object.assign(btn.__hold.opts, opts); return btn.__hold; }
32
+ const o = { duration: 1.2, look: 'fill', tone: 'bad', hint: 'Hold to confirm', done: 'Done', back: 0, haptic: true, onConfirm: null, onCancel: null, ...opts };
33
+ const ring = o.look === 'ring';
34
+
35
+ const label0 = btn.querySelector(':scope > span')?.textContent ?? '';
36
+ const icon0 = btn.querySelector(':scope > svg')?.outerHTML ?? '';
37
+ const aria0 = btn.getAttribute('aria-label');
38
+ btn.classList.add('hold', `hold--${ring ? 'ring' : 'fill'}`, `hold--${TONES.has(o.tone) ? o.tone : 'bad'}`);
39
+
40
+ // the coloured copy of the button's face that floods in (fill look), or the circle (ring look)
41
+ let fill = null;
42
+ if (ring) btn.insertAdjacentHTML('beforeend', RING);
43
+ else { fill = document.createElement('span'); fill.className = 'hold__fill'; fill.setAttribute('aria-hidden', 'true'); fill.innerHTML = `<span class="hold__face">${btn.innerHTML}</span>`; btn.append(fill); }
44
+ const arc = btn.querySelector(':scope > .hold__ring .hold__arc');
45
+ const sr = document.createElement('span'); sr.className = 'hold__sr'; sr.setAttribute('role', 'status'); btn.append(sr);
46
+ if (o.hint && !btn.title) { btn.dataset.holdTitle = '1'; btn.title = o.hint; }
47
+
48
+ const faces = () => [btn, fill?.firstChild].filter(Boolean);
49
+ const icons = () => faces().map((f) => f.querySelector(':scope > svg:not(.hold__ring)')).filter(Boolean);
50
+ const labels = () => faces().map((f) => f.querySelector(':scope > span:not(.hold__fill):not(.hold__sr)')).filter(Boolean);
51
+
52
+ const p = { v: 0 };
53
+ let state = 'idle', run = null, hintT = null, backT = null, pid = null;
54
+ const draw = () => {
55
+ const v = p.v;
56
+ if (fill) fill.style.clipPath = `inset(0 ${(100 - v * 100).toFixed(2)}% 0 0)`;
57
+ if (arc) arc.setAttribute('stroke-dashoffset', String(1 - v));
58
+ if (!RM() && state === 'holding') { // the icon trembles harder as it nears the end
59
+ const a = v * v * 1.8;
60
+ icons().forEach((i) => g.set(i, { x: (Math.random() - 0.5) * 2 * a, y: (Math.random() - 0.5) * 2 * a, rotation: (Math.random() - 0.5) * a * 4 }));
61
+ }
62
+ };
63
+ const settleIcons = () => icons().forEach((i) => g.to(i, { x: 0, y: 0, rotation: 0, duration: 0.2, overwrite: true }));
64
+
65
+ /** Change the label on both faces; the button glides to its new width. */
66
+ const setLabel = (t) => {
67
+ const ls = labels(); if (!ls.length || ls[0].textContent === t) return;
68
+ const w0 = btn.offsetWidth; btn.style.width = '';
69
+ ls.forEach((l) => { l.textContent = t; });
70
+ const w1 = btn.offsetWidth;
71
+ if (!RM() && Math.abs(w1 - w0) > 1) g.fromTo(btn, { width: w0 }, { width: w1, duration: 0.3, ease: 'power3.out', clearProps: 'width' });
72
+ if (!RM()) g.fromTo(ls, { y: 6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.28, ease: 'power2.out', clearProps: 'transform,opacity' });
73
+ };
74
+ const buzz = (pattern) => { if (o.haptic) navigator.vibrate?.(pattern); };
75
+
76
+ const start = () => {
77
+ if (state === 'done' || state === 'holding' || btn.disabled) return;
78
+ clearTimeout(hintT); state = 'holding';
79
+ if (labels()[0]?.textContent !== label0) setLabel(label0);
80
+ run?.kill();
81
+ run = g.to(p, { v: 1, duration: o.duration * (1 - p.v), ease: 'none', onUpdate: draw, onComplete: () => api.confirm() });
82
+ if (!RM()) g.to(btn, { scale: 0.965, duration: 0.18, ease: 'power2.out' });
83
+ buzz(6);
84
+ };
85
+ const stop = () => {
86
+ if (state !== 'holding') return;
87
+ state = 'idle'; run?.kill();
88
+ const left = p.v;
89
+ if (!RM()) { g.to(btn, { scale: 1, duration: 0.4, ease: 'back.out(2.5)' }); settleIcons(); }
90
+ run = g.to(p, { v: 0, duration: RM() ? 0 : 0.18 + left * 0.3, ease: 'power2.out', onUpdate: draw });
91
+ if (!RM()) g.fromTo(btn, { x: 0 }, { keyframes: { x: [0, -4, 3, -2, 0] }, duration: 0.32, ease: 'power2.out', clearProps: 'x' });
92
+ if (o.hint) {
93
+ setLabel(o.hint); sr.textContent = o.hint;
94
+ hintT = setTimeout(() => { if (state === 'idle') setLabel(label0); }, 1400);
95
+ }
96
+ o.onCancel?.(btn, api, left);
97
+ };
98
+
99
+ const api = {
100
+ el: btn, opts: o,
101
+ get progress() { return p.v; },
102
+ get state() { return state; },
103
+ /** Finish straight away (also what holding to the end does). */
104
+ confirm() {
105
+ if (state === 'done') return api;
106
+ state = 'done'; run?.kill(); clearTimeout(hintT); p.v = 1; draw();
107
+ btn.classList.add('is-done'); btn.setAttribute('aria-disabled', 'true');
108
+ if (aria0) btn.setAttribute('aria-label', o.done);
109
+ // the icon becomes a tick that draws itself
110
+ faces().forEach((f) => { const i = f.querySelector(':scope > svg:not(.hold__ring)'); const t = document.createElement('template'); t.innerHTML = TICK; const tick = t.content.firstElementChild; i ? i.replaceWith(tick) : f.prepend(tick); });
111
+ const paths = faces().map((f) => f.querySelector(':scope > .hold__tick path'));
112
+ setLabel(o.done); sr.textContent = o.done; buzz([12, 50, 18]);
113
+ if (RM()) paths.forEach((x) => x.setAttribute('stroke-dashoffset', '0'));
114
+ else {
115
+ g.to(paths, { attr: { 'stroke-dashoffset': 0 }, duration: 0.4, ease: 'power2.out', delay: 0.08 });
116
+ g.fromTo(btn, { scale: 0.96 }, { keyframes: { scale: [0.96, 1.06, 1] }, duration: 0.5, ease: 'power2.out', clearProps: 'scale' });
117
+ const burst = document.createElement('span'); burst.className = 'hold__burst'; burst.setAttribute('aria-hidden', 'true'); btn.append(burst);
118
+ g.fromTo(burst, { scale: 1, opacity: 0.55 }, { scale: ring ? 1.7 : 1.25, opacity: 0, duration: 0.6, ease: 'power2.out', onComplete: () => burst.remove() });
119
+ }
120
+ o.onConfirm?.(btn, api);
121
+ if (o.back > 0) backT = setTimeout(() => api.reset(), o.back * 1000);
122
+ return api;
123
+ },
124
+ /** Back to the start: the colour drains, the icon and label come back. */
125
+ reset() {
126
+ clearTimeout(backT); clearTimeout(hintT); run?.kill();
127
+ state = 'idle'; btn.classList.remove('is-done'); btn.removeAttribute('aria-disabled');
128
+ if (aria0) btn.setAttribute('aria-label', aria0);
129
+ faces().forEach((f) => { const t = f.querySelector(':scope > .hold__tick'); if (t) { if (icon0) { const x = document.createElement('template'); x.innerHTML = icon0; t.replaceWith(x.content.firstElementChild); } else t.remove(); } });
130
+ setLabel(label0); sr.textContent = '';
131
+ if (RM()) { p.v = 0; draw(); } else run = g.to(p, { v: 0, duration: 0.4, ease: 'power2.inOut', onUpdate: draw });
132
+ return api;
133
+ },
134
+ destroy() {
135
+ clearTimeout(backT); clearTimeout(hintT); run?.kill(); ac.abort();
136
+ fill?.remove(); btn.querySelector(':scope > .hold__ring')?.remove(); sr.remove();
137
+ if (btn.dataset.holdTitle) { btn.removeAttribute('title'); delete btn.dataset.holdTitle; }
138
+ btn.classList.remove('hold', 'hold--ring', 'hold--fill', 'is-done', ...[...TONES].map((t) => `hold--${t}`));
139
+ delete btn.__hold;
140
+ },
141
+ };
142
+
143
+ const ac = new AbortController(), on = { signal: ac.signal };
144
+ btn.addEventListener('pointerdown', (e) => {
145
+ if (e.button > 0) return;
146
+ pid = e.pointerId; try { btn.setPointerCapture(pid); } catch { /* fine */ }
147
+ start();
148
+ }, on);
149
+ const end = (e) => { if (e.pointerId === pid) { pid = null; stop(); } };
150
+ btn.addEventListener('pointerup', end, on);
151
+ btn.addEventListener('pointercancel', end, on);
152
+ btn.addEventListener('pointermove', (e) => { // sliding the finger off the button lets go
153
+ if (e.pointerId !== pid || state !== 'holding') return;
154
+ const r = btn.getBoundingClientRect(), m = 16;
155
+ if (e.clientX < r.left - m || e.clientX > r.right + m || e.clientY < r.top - m || e.clientY > r.bottom + m) { pid = null; stop(); }
156
+ }, on);
157
+ btn.addEventListener('keydown', (e) => {
158
+ if (e.key !== ' ' && e.key !== 'Enter') return;
159
+ e.preventDefault(); if (!e.repeat) start();
160
+ }, on);
161
+ btn.addEventListener('keyup', (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); stop(); } }, on);
162
+ btn.addEventListener('blur', stop, on);
163
+ btn.addEventListener('contextmenu', (e) => e.preventDefault(), on);
164
+ btn.addEventListener('click', (e) => { if (state !== 'done') e.preventDefault(); }, on);
165
+
166
+ draw();
167
+ btn.__hold = api;
168
+ return api;
169
+ };
package/src/hover.js ADDED
@@ -0,0 +1,26 @@
1
+ /* Hover: magnetic buttons (.magnetic) and lift ([data-lift]) */
2
+ import { g, RM, fine, ready, $$ } from './core.js';
3
+
4
+ export const magnetic = (root = document, { strength = 0.2, strengthY = 0.28 } = {}) => {
5
+ if (!fine.matches) return;
6
+ $$(root.matches?.('.magnetic') ? [root] : $$('.magnetic', root)).forEach((el) => {
7
+ if (el.__mag) return; el.__mag = true;
8
+ const qx = g.quickTo(el, 'x', { duration: 0.5, ease: 'power3.out' });
9
+ const qy = g.quickTo(el, 'y', { duration: 0.5, ease: 'power3.out' });
10
+ el.addEventListener('pointermove', (e) => {
11
+ if (RM()) return; const r = el.getBoundingClientRect();
12
+ const k = +(el.dataset.magnet || 1);
13
+ qx((e.clientX - r.left - r.width / 2) * strength * k); qy((e.clientY - r.top - r.height / 2) * strengthY * k);
14
+ });
15
+ el.addEventListener('pointerleave', () => { qx(0); qy(0); });
16
+ });
17
+ };
18
+
19
+ export const lift = (root = document, y = -4) => {
20
+ if (!fine.matches) return;
21
+ $$(root.matches?.('[data-lift]') ? [root] : $$('[data-lift]', root)).forEach((el) => {
22
+ if (el.__lift) return; el.__lift = true;
23
+ el.addEventListener('pointerenter', () => { if (!RM() && ready.v) g.to(el, { y: +(el.dataset.lift || y), duration: 0.45, ease: 'power3.out', overwrite: 'auto' }); });
24
+ el.addEventListener('pointerleave', () => { if (ready.v) g.to(el, { y: 0, duration: 0.5, ease: 'power3.out', overwrite: 'auto', clearProps: 'transform' }); });
25
+ });
26
+ };
@@ -0,0 +1,57 @@
1
+ /* Stretchy indicator.
2
+ One element covers its whole parent; clip-path cuts it down to the active child.
3
+ On change the leading edge travels first (fast) and the trailing edge follows (slower),
4
+ so the highlight stretches, then snaps into place. Used for sidebar pills, tab lines,
5
+ segmented thumbs, list selections.
6
+
7
+ <nav class="x"><span class="x__pill"></span><a>…</a><a aria-current="page">…</a></nav>
8
+ indicator(pill, activeLink) → animate to it
9
+ indicator(pill, activeLink, { animate:false })→ jump
10
+ trackIndicator(pill, () => nav.querySelector('[aria-current]')) → keep glued on resize */
11
+ import { g, RM } from './core.js';
12
+
13
+ export const indicatorTiming = { lead: 0.36, trail: 0.55, cross: 0.45 };
14
+
15
+ export const indicator = (ind, target, { animate = true, radius = 13, line = false, lead = indicatorTiming.lead, trail = indicatorTiming.trail, cross = indicatorTiming.cross } = {}) => {
16
+ if (!ind) return;
17
+ const par = ind.parentElement;
18
+ if (!target || !target.offsetWidth) { g.set(ind, { opacity: 0 }); return; }
19
+ const cs = getComputedStyle(par);
20
+ const W = /auto|scroll/.test(cs.overflowX) && par.scrollWidth > par.clientWidth ? par.scrollWidth : par.offsetWidth;
21
+ const H = /auto|scroll/.test(cs.overflowY) && par.scrollHeight > par.clientHeight ? par.scrollHeight : par.offsetHeight;
22
+ // offsets relative to the indicator's parent, even through positioned wrappers
23
+ let ox = 0, oy = 0, n = target;
24
+ while (n && n !== par) { ox += n.offsetLeft; oy += n.offsetTop; const op = n.offsetParent; if (!op || (!par.contains(op) && op !== par)) break; n = op; }
25
+ if (n !== par) { const a = target.getBoundingClientRect(), b = par.getBoundingClientRect(); ox = a.left - b.left + par.scrollLeft; oy = a.top - b.top + par.scrollTop; }
26
+ const to = line
27
+ ? { l: ox, r: W - (ox + target.offsetWidth), t: 0, b: 0 }
28
+ : { l: ox, r: W - (ox + target.offsetWidth), t: oy, b: H - (oy + target.offsetHeight) };
29
+ W === par.offsetWidth ? ind.style.removeProperty('width') : (ind.style.width = W + 'px');
30
+ !line && H !== par.offsetHeight ? (ind.style.height = H + 'px') : ind.style.removeProperty('height');
31
+ const clip = (e) => `inset(${e.t}px ${e.r}px ${e.b}px ${e.l}px round ${radius}px)`;
32
+ const prev = ind.__e;
33
+ const same = (a, b) => Math.abs(a.l - b.l) < 1 && Math.abs(a.r - b.r) < 1 && Math.abs(a.t - b.t) < 1 && Math.abs(a.b - b.b) < 1;
34
+ if (!animate && prev && same(prev, to) && ind.__st && g.isTweening(ind.__st)) return;
35
+ ind.__e = to;
36
+ if (!animate || RM() || !prev || Number(g.getProperty(ind, 'opacity')) === 0) {
37
+ g.killTweensOf(ind.__st ?? {}); ind.__st = { ...to }; g.set(ind, { clipPath: clip(to), opacity: 1 }); return;
38
+ }
39
+ const st = ind.__st ?? { ...prev }; ind.__st = st; g.killTweensOf(st);
40
+ const vertical = Math.abs(to.t - prev.t) > Math.abs(to.l - prev.l);
41
+ const forward = vertical ? to.t > prev.t : to.l > prev.l;
42
+ const [L, T] = vertical ? (forward ? ['b', 't'] : ['t', 'b']) : (forward ? ['r', 'l'] : ['l', 'r']);
43
+ const C = vertical ? ['l', 'r'] : ['t', 'b'];
44
+ const upd = () => g.set(ind, { clipPath: clip(st) });
45
+ g.to(st, { [L]: to[L], duration: lead, ease: 'power3.out', onUpdate: upd });
46
+ g.to(st, { [T]: to[T], duration: trail, ease: 'power3.inOut', onUpdate: upd });
47
+ g.to(st, { [C[0]]: to[C[0]], [C[1]]: to[C[1]], duration: cross, ease: 'power3.inOut', onUpdate: upd });
48
+ };
49
+
50
+ /** Keep an indicator on its target while the layout resizes. Returns a stop() function. */
51
+ export const trackIndicator = (ind, getTarget, opts) => {
52
+ const fix = () => indicator(ind, getTarget(), { ...opts, animate: false });
53
+ let raf = 0; const ro = new ResizeObserver(() => { cancelAnimationFrame(raf); raf = requestAnimationFrame(fix); });
54
+ ro.observe(ind.parentElement); [...ind.parentElement.children].forEach((c) => ro.observe(c));
55
+ document.fonts?.ready.then(fix);
56
+ return () => { cancelAnimationFrame(raf); ro.disconnect(); };
57
+ };
package/src/liquid.js ADDED
@@ -0,0 +1,130 @@
1
+ /* Liquid tab bar. The bar and a bubble above the active tab are drawn as one liquid (an SVG
2
+ "goo" filter melts shapes that touch into one smooth surface). Picking another tab:
3
+ 'dip' the bubble shrinks back into the bar's top edge, runs along it as a small wave with a
4
+ coloured bead on top, and swells up again at the new tab with a wobble and a splash;
5
+ 'glide' the bubble stays up and slides, stretching sideways with droplets trailing behind.
6
+ The active icon rides up into the bubble and turns white. */
7
+ import { g, RM, $$, esc } from './core.js';
8
+
9
+ let uid = 0;
10
+ /**
11
+ * liquidBar(items, { active: 0, label: 'Main', labels: true, goo: true }) → HTML
12
+ * items: [{ label, icon: '<svg…>', href? }] (an href makes the tab a link, otherwise a button).
13
+ * labels: false shows icons only (labels stay for screen readers). goo: false shows the plain shapes.
14
+ */
15
+ export const liquidBar = (items, { active = 0, label = 'Main', labels = true, goo = true } = {}) => {
16
+ const id = `lq-goo-${++uid}`;
17
+ const tabs = items.map((it, i) => {
18
+ const tag = it.href ? 'a' : 'button', attrs = it.href ? `href="${esc(it.href)}"` : 'type="button"';
19
+ return `<${tag} class="lq__tab${i === active ? ' is-on' : ''}" ${attrs}${i === active ? ' aria-current="page"' : ''}><span class="lq__ic" aria-hidden="true">${it.icon || ''}</span><span class="lq__lb">${esc(it.label)}</span></${tag}>`;
20
+ }).join('');
21
+ const cls = ['lq', labels ? '' : 'lq--icons', goo ? '' : 'lq--plain'].filter(Boolean).join(' ');
22
+ return `<nav class="${cls}" aria-label="${esc(label)}" style="--lq-goo: url(#${id})">`
23
+ + `<svg class="lq__defs" width="0" height="0" aria-hidden="true" focusable="false"><filter id="${id}" x="-10%" y="-90%" width="120%" height="280%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceGraphic" stdDeviation="7"/><feColorMatrix values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 24 -11"/></filter></svg>`
24
+ + '<span class="lq__goo" aria-hidden="true"><span class="lq__body"></span><span class="lq__drop"></span><span class="lq__drop"></span><span class="lq__bub"></span></span>'
25
+ + `<span class="lq__dot" aria-hidden="true"></span>${tabs}</nav>`;
26
+ };
27
+
28
+ /**
29
+ * const bar = liquidTabs(el, { mode: 'dip'|'glide', splash: true, onChange(index, tab) })
30
+ * el: a .lq nav from liquidBar(), or a box that holds one.
31
+ * Clicks and the arrow keys pick a tab. Links still navigate; onChange runs first.
32
+ * Returns { el, opts, index, select(i, { animate }), place(), destroy() }.
33
+ */
34
+ export const liquidTabs = (el, opts = {}) => {
35
+ el = $$(el)[0];
36
+ const nav = el?.matches('.lq') ? el : el?.querySelector('.lq');
37
+ if (!nav) return null;
38
+ if (nav.__lq) { Object.assign(nav.__lq.opts, opts); return nav.__lq; }
39
+ const o = { mode: 'dip', splash: true, onChange: null, ...opts };
40
+ const tabs = [...nav.querySelectorAll('.lq__tab')];
41
+ const bub = nav.querySelector('.lq__bub'), dot = nav.querySelector('.lq__dot'), drops = [...nav.querySelectorAll('.lq__drop')];
42
+ let index = Math.max(0, tabs.findIndex((t) => t.hasAttribute('aria-current'))), tl = null;
43
+
44
+ const icon = (t) => t.querySelector('.lq__ic');
45
+ const cx = (t) => t.offsetLeft + t.offsetWidth / 2;
46
+ /** How far the icon must move up so it sits in the middle of the bubble's coloured dot. */
47
+ const rise = (t) => { const ic = icon(t); return dot.offsetTop + dot.offsetHeight / 2 - (t.offsetTop + ic.offsetTop + ic.offsetHeight / 2); };
48
+ const at = (t, e) => cx(t) - e.offsetWidth / 2;
49
+
50
+ /** Put everything on the active tab with no animation (also used on resize). */
51
+ const place = () => {
52
+ const t = tabs[index]; if (!t) return;
53
+ g.set(bub, { x: at(t, bub), y: 0, scale: 1 }); g.set(dot, { x: at(t, dot), y: 0, scale: 1 });
54
+ g.set(drops, { x: at(t, drops[0]), y: 0, scale: 0 });
55
+ tabs.forEach((tb, k) => { tb.classList.toggle('is-on', k === index); g.set(icon(tb), { y: k === index ? rise(tb) : 0 }); });
56
+ };
57
+
58
+ const splashAt = (tl, t, time) => {
59
+ if (!o.splash || drops.length < 2) return;
60
+ const x = at(t, drops[0]);
61
+ drops.forEach((d, k) => {
62
+ const side = k ? 1 : -1;
63
+ tl.fromTo(d, { x, y: 4, scale: 0.4 }, { keyframes: { '0%': { x, y: 4, scale: 0.4 }, '45%': { x: x + side * 26, y: -16, scale: 1 }, '100%': { x: x + side * 36, y: 2, scale: 0 }, easeEach: 'sine.inOut' }, duration: 0.6, ease: 'power1.out' }, time + k * 0.03);
64
+ });
65
+ };
66
+
67
+ const api = {
68
+ el: nav, opts: o,
69
+ get index() { return index; },
70
+ /** Make tab i the active one and play the liquid move. */
71
+ select(i, { animate = true } = {}) {
72
+ i = Math.max(0, Math.min(tabs.length - 1, i));
73
+ if (i === index) return g.timeline();
74
+ const from = tabs[index], to = tabs[i]; index = i;
75
+ from.removeAttribute('aria-current'); to.setAttribute('aria-current', 'page');
76
+ o.onChange?.(i, to, api);
77
+ tl?.kill(); g.killTweensOf([bub, dot, ...drops, ...tabs.map(icon)]);
78
+ if (!animate || RM()) { place(); return g.timeline(); }
79
+
80
+ const dist = Math.abs(cx(to) - cx(from)), travel = Math.min(0.6, 0.3 + dist / 900);
81
+ tl = g.timeline();
82
+ from.classList.remove('is-on');
83
+ tl.to(icon(from), { y: 0, duration: 0.35, ease: 'back.out(2)' }, 0);
84
+ let land;
85
+ if (o.mode === 'glide') {
86
+ // stays up and slides; stretches with the speed, droplets trail and get pulled back in
87
+ tl.to(bub, { x: at(to, bub), duration: travel, ease: 'power3.inOut' }, 0)
88
+ .to(dot, { x: at(to, dot), duration: travel, ease: 'power3.inOut' }, 0)
89
+ .to([bub, dot], { keyframes: { scaleX: [1, 1.3, 0.92, 1], scaleY: [1, 0.82, 1.06, 1] }, duration: travel + 0.3, ease: 'sine.inOut' }, 0);
90
+ drops.forEach((d, k) => {
91
+ tl.fromTo(d, { x: at(from, d), y: 0, scale: 0 }, { x: at(to, d), duration: travel, ease: 'power3.inOut' }, 0.05 + k * 0.06)
92
+ .to(d, { keyframes: { scale: [0, 1 - k * 0.25, 0] }, duration: travel + 0.1, ease: 'none' }, 0.05 + k * 0.06);
93
+ });
94
+ land = travel * 0.75;
95
+ } else {
96
+ // dip: shrink back into the bar's top edge, run along it as a small wave with a bead on top
97
+ // (above the icons, so it never crosses them), then swell up at the new tab
98
+ const surf = 2 - (dot.offsetTop + dot.offsetHeight / 2), B = 0.42, Dt = 0.36;
99
+ tl.to(bub, { y: surf, scale: B, duration: 0.22, ease: 'power2.in' }, 0)
100
+ .to(dot, { y: surf, scale: Dt, duration: 0.22, ease: 'power2.in' }, 0);
101
+ splashAt(tl, from, 0.02);
102
+ tl.to(bub, { x: at(to, bub), duration: travel, ease: 'power2.inOut' }, 0.14)
103
+ .to(dot, { x: at(to, dot), duration: travel, ease: 'power2.inOut' }, 0.14);
104
+ land = 0.14 + travel * 0.8;
105
+ tl.to([bub, dot], { y: 0, duration: 0.55, ease: 'back.out(2.2)' }, land);
106
+ [[bub, B], [dot, Dt]].forEach(([e, s]) => tl.fromTo(e, { scaleX: s, scaleY: s }, { keyframes: { scaleX: [s, 1.14, 0.95, 1], scaleY: [s, 0.86, 1.05, 1] }, duration: 0.6, ease: 'power1.out', immediateRender: false }, land));
107
+ splashAt(tl, to, land + 0.08);
108
+ }
109
+ tl.add(() => to.classList.add('is-on'), land + 0.1)
110
+ .to(icon(to), { y: rise(to), duration: 0.5, ease: 'back.out(2.4)' }, land);
111
+ return tl;
112
+ },
113
+ place,
114
+ destroy() { tl?.kill(); ro.disconnect(); ac.abort(); delete nav.__lq; },
115
+ };
116
+
117
+ const ac = new AbortController(), on = { signal: ac.signal };
118
+ tabs.forEach((t, i) => t.addEventListener('click', () => api.select(i), on));
119
+ nav.addEventListener('keydown', (e) => {
120
+ const k = tabs.indexOf(document.activeElement); if (k < 0) return;
121
+ const n = { ArrowLeft: k - 1, ArrowRight: k + 1, Home: 0, End: tabs.length - 1 }[e.key];
122
+ if (n == null) return;
123
+ e.preventDefault(); const j = (n + tabs.length) % tabs.length; tabs[j].focus(); api.select(j);
124
+ }, on);
125
+ const ro = new ResizeObserver(() => { if (!tl?.isActive()) place(); });
126
+ ro.observe(nav);
127
+ place();
128
+ nav.__lq = api;
129
+ return api;
130
+ };
@@ -0,0 +1,169 @@
1
+ /* Odometer: a number that rolls digit by digit, like a meter in a car. Every digit is a little
2
+ column (a reel of 0–9) that spins to its new digit; the columns start one after the other from
3
+ the right, the way a real meter carries over. Digits that stay the same do not move. When the
4
+ number gets longer or shorter the new columns grow in (or the old ones shrink away) so the width
5
+ glides instead of jumping. Commas, currency signs and suffixes stay where they are; if they
6
+ change (say "$" becomes "฿") they swap with a small fade. Screen readers only get the final
7
+ text, never the columns. With reduced motion the new number simply appears. */
8
+ import { g, RM, $$ } from './core.js';
9
+
10
+ const state = new WeakMap();
11
+ const LAPS = 3; // each reel holds 0–9 three times so it can roll past 9 → 0
12
+ const DIGIT = /[0-9]/;
13
+ const reelHTML = (() => { let s = ''; for (let k = 0; k < 10 * LAPS; k++) s += `<span>${k % 10}</span>`; return `<span class="odo__reel">${s}</span>`; })();
14
+ const toY = (idx) => -(idx / (10 * LAPS)) * 100; // reel index → yPercent
15
+ const fromY = (y) => (-y / 100) * 10 * LAPS;
16
+
17
+ /** The text for a value, from opts.format (Intl options or a function) and opts.locale. */
18
+ const textOf = (v, o) => {
19
+ if (typeof v === 'string') return v;
20
+ if (typeof o.format === 'function') return String(o.format(v));
21
+ try { return new Intl.NumberFormat(o.locale, o.format || undefined).format(v); } catch { return String(v); }
22
+ };
23
+
24
+ /** Split text into keyed slots: digits keyed by place from the right (d0 = last digit), the text
25
+ before the first digit (p…), after the last digit (x…) and between digits (i<place>…). */
26
+ const slotsOf = (text) => {
27
+ const chars = [...text], idx = chars.map((c, i) => (DIGIT.test(c) ? i : -1)).filter((i) => i >= 0);
28
+ const first = idx[0] ?? chars.length, last = idx.length ? idx[idx.length - 1] : -1;
29
+ let right = idx.length, inner = {};
30
+ return chars.map((c, i) => {
31
+ if (DIGIT.test(c)) { right--; return { key: 'd' + right, ch: c, digit: +c }; }
32
+ if (i < first) return { key: 'p' + i, ch: c };
33
+ if (i > last) return { key: 'x' + (i - last), ch: c };
34
+ const k = 'i' + right + c; inner[k] = (inner[k] || 0) + 1;
35
+ return { key: k + '#' + inner[k], ch: c };
36
+ });
37
+ };
38
+
39
+ const makeCell = (slot) => {
40
+ const el = document.createElement('span');
41
+ if (slot.digit !== undefined) { el.className = 'odo__cell odo__col'; el.innerHTML = reelHTML; }
42
+ else { el.className = 'odo__cell odo__ch'; el.textContent = slot.ch === ' ' ? ' ' : slot.ch; }
43
+ el.dataset.key = slot.key;
44
+ return el;
45
+ };
46
+
47
+ /**
48
+ * odometer(el, value, {
49
+ * format: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } | (v) => '$' + v,
50
+ * // Intl.NumberFormat options, or a function that returns the text (default: grouped digits)
51
+ * locale: 'en-US', // for Intl (default: the browser's)
52
+ * duration: 0.9, // seconds one column takes to roll
53
+ * stagger: 0.06, // seconds between columns, starting from the right
54
+ * direction: 'auto' | 'up' | 'down', // auto: up when the number grows, down when it shrinks
55
+ * ease: 'back.out(1.15)', // a touch of overshoot, like a real reel settling
56
+ * from: 0, // first call only: roll in from this value instead of just showing
57
+ * })
58
+ * value: a number, or a ready-made string (rolled as it is). Returns the GSAP timeline.
59
+ * Later calls remember format / locale / duration … from earlier calls, so odometer(el, 42) is enough.
60
+ * odometer.value(el) → the last value · odometer.clear(el) → plain text again, state forgotten.
61
+ */
62
+ export const odometer = (el, value, opts = {}) => {
63
+ el = $$(el)[0];
64
+ if (!el) return g.timeline();
65
+ let s = state.get(el);
66
+ const first = !s;
67
+ if (first) {
68
+ s = { o: { duration: 0.9, stagger: 0.06, direction: 'auto', ease: 'back.out(1.15)' }, value: null, text: null, tl: null };
69
+ state.set(el, s);
70
+ el.classList.add('odo');
71
+ el.textContent = '';
72
+ s.sr = document.createElement('span'); s.sr.className = 'odo__sr';
73
+ s.vis = document.createElement('span'); s.vis.className = 'odo__vis'; s.vis.setAttribute('aria-hidden', 'true');
74
+ el.append(s.sr, s.vis);
75
+ }
76
+ const { from, ...keep } = opts;
77
+ Object.assign(s.o, keep);
78
+ const o = s.o;
79
+ if (first && from !== undefined && from !== null && !RM()) { place(s, textOf(from, o)); s.value = from; }
80
+
81
+ const text = textOf(value, o);
82
+ s.sr.textContent = text;
83
+ const old = s.value; s.value = value;
84
+ s.tl?.progress(1).kill(); // finish a roll in progress so the reels start from real digits
85
+ const tl = g.timeline();
86
+ s.tl = tl;
87
+ if (text === s.text) return tl;
88
+
89
+ if (RM() || s.text === null) { place(s, text); return tl; }
90
+
91
+ const dir = o.direction === 'up' ? 1 : o.direction === 'down' ? -1
92
+ : typeof value === 'number' && typeof old === 'number' && value < old ? -1 : 1;
93
+ const slots = slotsOf(text), byKey = new Map([...s.vis.children].map((c) => [c.dataset.key, c]));
94
+ const before = [...s.vis.children], keepKeys = new Set(slots.map((x) => x.key));
95
+ const moves = [], enters = [];
96
+
97
+ // put the cells for the new text in order (reuse a cell when its key is still there)
98
+ slots.forEach((slot) => {
99
+ let cell = byKey.get(slot.key);
100
+ if (cell && !cell.classList.contains('is-leaving')) {
101
+ if (slot.digit !== undefined) moves.push([cell, slot.digit, false]);
102
+ else if (cell.textContent !== slot.ch) swapChar(tl, cell, slot.ch, dir, o);
103
+ } else {
104
+ cell = makeCell(slot);
105
+ enters.push(cell);
106
+ if (slot.digit !== undefined) moves.push([cell, slot.digit, true]);
107
+ }
108
+ s.vis.append(cell);
109
+ });
110
+ // cells that are no longer needed stay where they were and shrink away
111
+ let anchor = null;
112
+ for (let i = before.length - 1; i >= 0; i--) {
113
+ const c = before[i];
114
+ if (keepKeys.has(c.dataset.key) && !c.classList.contains('is-leaving')) { anchor = c; continue; }
115
+ s.vis.insertBefore(c, anchor); anchor = c;
116
+ if (!c.classList.contains('is-leaving')) {
117
+ c.classList.add('is-leaving');
118
+ tl.to(c, { width: 0, opacity: 0, duration: o.duration * 0.6, ease: 'power2.inOut', onComplete: () => c.remove() }, 0);
119
+ }
120
+ }
121
+ // new cells grow from nothing to their own width
122
+ enters.forEach((c) => {
123
+ const w = c.offsetWidth;
124
+ tl.fromTo(c, { width: 0, opacity: 0 }, { width: w, opacity: 1, duration: o.duration * 0.6, ease: 'power2.out', clearProps: 'width,opacity' }, 0);
125
+ });
126
+ // roll the columns that change, one after the other from the right
127
+ let k = 0;
128
+ moves.reverse().forEach(([cell, d, isNew]) => {
129
+ const reel = cell.firstChild;
130
+ // a new column starts from 0 (rolling up) or 9 (rolling down); an old one from where it shows
131
+ let f = isNew ? (dir > 0 ? 10 : 19) : fromY(+g.getProperty(reel, 'yPercent') || 0);
132
+ f = (((f % 10) + 10) % 10) + 10; // the same digit on the middle lap: no visible jump
133
+ g.set(reel, { yPercent: toY(f) });
134
+ let to = 10 + d;
135
+ if (Math.abs(to - f) < 0.01) { g.set(reel, { yPercent: toY(to) }); return; }
136
+ if (dir > 0 && to < f) to += 10;
137
+ if (dir < 0 && to > f) to -= 10;
138
+ tl.to(reel, { yPercent: toY(to), duration: o.duration, ease: o.ease, onComplete: () => g.set(reel, { yPercent: toY(10 + d) }) }, k * o.stagger);
139
+ k++;
140
+ });
141
+ s.text = text;
142
+ return tl;
143
+ };
144
+
145
+ /** A prefix / suffix / separator that changed: the old one slips out, the new one slips in. */
146
+ const swapChar = (tl, cell, ch, dir, o) => {
147
+ const w0 = cell.offsetWidth;
148
+ cell.textContent = ch === ' ' ? ' ' : ch;
149
+ const w1 = cell.offsetWidth;
150
+ tl.fromTo(cell, { yPercent: 60 * dir, opacity: 0, width: w0 }, { yPercent: 0, opacity: 1, width: w1, duration: o.duration * 0.5, ease: 'power2.out', clearProps: 'transform,opacity,width' }, 0);
151
+ };
152
+
153
+ /** Draw text straight away (first render, reduced motion). */
154
+ function place(s, text) {
155
+ g.killTweensOf(s.vis.querySelectorAll('*'));
156
+ s.vis.textContent = '';
157
+ slotsOf(text).forEach((slot) => {
158
+ const c = makeCell(slot); s.vis.append(c);
159
+ if (slot.digit !== undefined) g.set(c.firstChild, { yPercent: toY(10 + slot.digit) });
160
+ });
161
+ s.text = text;
162
+ }
163
+
164
+ odometer.value = (el) => state.get($$(el)[0])?.value;
165
+ odometer.clear = (el) => {
166
+ el = $$(el)[0]; const s = el && state.get(el); if (!s) return;
167
+ s.tl?.kill(); g.killTweensOf(s.vis.querySelectorAll('*'));
168
+ el.classList.remove('odo'); el.textContent = s.text ?? ''; state.delete(el);
169
+ };
package/src/overlay.js ADDED
@@ -0,0 +1,12 @@
1
+ /* Shared motions for things that pop over the page */
2
+ import { g, D, RM } from './core.js';
3
+
4
+ export const popIn = (el, origin = '50% 0%') => g.fromTo(el, { scale: 0.92, opacity: 0, y: -6, transformOrigin: origin }, { scale: 1, opacity: 1, y: 0, duration: D(0.4), ease: 'back.out(2)', clearProps: 'transform,opacity' });
5
+ export const popOut = (el, done) => { if (RM()) return done?.(); return g.to(el, { scale: 0.96, opacity: 0, duration: 0.15, ease: 'power2.in', onComplete: done }); };
6
+ /** Zoom in from an anchor element (used by modal). */
7
+ export const zoomFrom = (el, anchor) => {
8
+ const a = anchor?.getBoundingClientRect(), r = el.getBoundingClientRect();
9
+ const ox = a && a.width ? a.left + a.width / 2 - r.left : r.width / 2, oy = a && a.width ? a.top + a.height / 2 - r.top : r.height / 2;
10
+ return g.fromTo(el, { scale: 0.86, opacity: 0, transformOrigin: `${ox}px ${oy}px` }, { scale: 1, opacity: 1, duration: D(0.5), ease: 'back.out(1.5)', clearProps: 'transform,opacity' });
11
+ };
12
+ export const fadeIn = (el, d = 0.3) => g.fromTo(el, { opacity: 0 }, { opacity: 1, duration: D(d) });