@gecko-ui-kit/motion 0.0.0-stage → 0.8.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,166 @@
1
+ /* Confetti: a burst of paper shoots up from a button (or any point), slows in the air, then
2
+ flutters down over the page: every piece spins, sways from side to side and flips over like
3
+ real paper, then fades out. It draws on one fixed canvas laid over the page that ignores the
4
+ mouse; the canvas and its animation frame are removed as soon as the last piece is gone, and
5
+ several bursts at once share the same canvas. With reduced motion nothing flies: a few soft
6
+ sparkles twinkle at the origin for half a second (or nothing at all with reduced: 'none'). */
7
+ import { RM, $$ } from './core.js';
8
+
9
+ const FALLBACK = ['#5b4cf0', '#e39a14', '#0f9f9a', '#e25577', '#2b8fd6', '#9b51e0', '#16a36a'];
10
+ const TOKENS = ['--accent', '--hue-amber', '--hue-teal', '--hue-rose', '--hue-sky', '--hue-violet', '--good'];
11
+ const SHAPES = ['rect', 'circle', 'strip', 'star'];
12
+ const MAX = 600;
13
+
14
+ /* one shared layer for every burst */
15
+ let layer = null, ctx = null, frame = 0, last = 0, W = 0, H = 0;
16
+ const pieces = new Set(), bursts = new Set();
17
+ const size = () => {
18
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
19
+ W = innerWidth; H = innerHeight;
20
+ layer.width = Math.round(W * dpr); layer.height = Math.round(H * dpr);
21
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
22
+ };
23
+ const open = (z) => {
24
+ if (!layer) {
25
+ layer = document.createElement('canvas');
26
+ layer.className = 'confetti-layer';
27
+ layer.setAttribute('aria-hidden', 'true');
28
+ Object.assign(layer.style, { position: 'fixed', inset: '0', width: '100%', height: '100%', pointerEvents: 'none' });
29
+ document.body.append(layer);
30
+ ctx = layer.getContext('2d');
31
+ size();
32
+ addEventListener('resize', size);
33
+ }
34
+ layer.style.zIndex = String(Math.max(z, +layer.style.zIndex || 0));
35
+ if (!frame) { last = performance.now(); frame = requestAnimationFrame(tick); }
36
+ };
37
+ const close = () => {
38
+ cancelAnimationFrame(frame); frame = 0;
39
+ removeEventListener('resize', size);
40
+ layer?.remove(); layer = null; ctx = null;
41
+ };
42
+
43
+ const star = (r) => {
44
+ ctx.beginPath();
45
+ for (let k = 0; k < 10; k++) { const a = (k * Math.PI) / 5 - Math.PI / 2, rr = k % 2 ? r * 0.45 : r; ctx.lineTo(Math.cos(a) * rr, Math.sin(a) * rr); }
46
+ ctx.closePath(); ctx.fill();
47
+ };
48
+ const draw = (p) => {
49
+ ctx.save();
50
+ ctx.globalAlpha = p.alpha;
51
+ ctx.translate(p.x, p.y);
52
+ ctx.rotate(p.rot);
53
+ ctx.fillStyle = p.color;
54
+ if (p.shape === 'spark') { // reduced motion: a soft four-point twinkle, no movement
55
+ const r = p.s * (0.6 + 0.4 * p.alpha);
56
+ ctx.beginPath(); ctx.moveTo(0, -r); ctx.quadraticCurveTo(0, 0, r, 0); ctx.quadraticCurveTo(0, 0, 0, r); ctx.quadraticCurveTo(0, 0, -r, 0); ctx.quadraticCurveTo(0, 0, 0, -r); ctx.fill();
57
+ } else {
58
+ ctx.scale(1, Math.cos(p.flip)); // turning over: the piece looks thinner, then thicker
59
+ if (p.shape === 'circle') { ctx.beginPath(); ctx.arc(0, 0, p.s / 2.4, 0, Math.PI * 2); ctx.fill(); }
60
+ else if (p.shape === 'strip') ctx.fillRect(-p.s * 0.16, -p.s * 0.8, p.s * 0.32, p.s * 1.6);
61
+ else if (p.shape === 'star') star(p.s / 1.7);
62
+ else ctx.fillRect(-p.s / 2, -p.s / 3.2, p.s, p.s / 1.6);
63
+ }
64
+ ctx.restore();
65
+ };
66
+
67
+ function tick(now) {
68
+ const dt = Math.min(0.05, (now - last) / 1000); last = now; // a hidden tab must not make pieces jump
69
+ ctx.clearRect(0, 0, W, H);
70
+ for (const p of pieces) {
71
+ p.t += dt;
72
+ if (p.t < 0) continue; // waiting for its delay
73
+ if (p.shape === 'spark') p.alpha = Math.sin(Math.PI * Math.min(1, p.t / p.life)) * 0.9;
74
+ else {
75
+ const drag = Math.exp(-p.k * dt); // air slows the piece; gravity pulls it towards a gentle falling speed
76
+ p.vx *= drag; p.vy = p.vy * drag + p.g * dt;
77
+ p.wob += p.ws * dt;
78
+ p.x += (p.vx + Math.sin(p.wob) * p.sway) * dt; p.y += p.vy * dt;
79
+ p.rot += p.spin * dt; p.flip += p.fs * dt;
80
+ const left = p.life - p.t;
81
+ p.alpha = left < 0.6 ? Math.max(0, left / 0.6) : 1;
82
+ }
83
+ if (p.t >= p.life || p.y > H + 60) { pieces.delete(p); p.b.left--; if (!p.b.left) p.b.end(); continue; }
84
+ draw(p);
85
+ }
86
+ if (pieces.size) frame = requestAnimationFrame(tick);
87
+ else close();
88
+ }
89
+
90
+ /** Colours from the theme: the accent plus the palette hues, read where the burst starts. */
91
+ const themeColors = (el) => {
92
+ const cs = getComputedStyle(el || document.documentElement);
93
+ const out = TOKENS.map((t) => cs.getPropertyValue(t).trim()).filter(Boolean);
94
+ return out.length > 2 ? out : FALLBACK;
95
+ };
96
+ const pointOf = (origin) => {
97
+ if (origin && typeof origin.x === 'number' && typeof origin.y === 'number' && !origin.nodeType) return [origin, null];
98
+ const el = $$(origin)[0];
99
+ if (!el) return [{ x: innerWidth / 2, y: innerHeight * 0.6 }, null];
100
+ const r = el.getBoundingClientRect();
101
+ return [{ x: r.left + r.width / 2, y: r.top + r.height / 2 }, el];
102
+ };
103
+ const rnd = (a, b) => a + Math.random() * (b - a);
104
+
105
+ /**
106
+ * const party = confetti(buttonOrPoint, {
107
+ * count: 120, // pieces of paper (at most 600)
108
+ * spread: 100, // width of the burst, in degrees
109
+ * angle: 90, // which way it shoots: 90 = straight up, 45 = up and right, 135 = up and left
110
+ * velocity: 1, // how hard it shoots (1 = normal; it also scales with the window height)
111
+ * colors: ['#…', 'var(--accent)'], // default: --accent and the theme hues
112
+ * shapes: ['rect', 'circle', 'strip', 'star'], // picked at random for each piece
113
+ * gravity: 1, // how fast it falls (0.5 = floats, 2 = drops)
114
+ * duration: 3, // seconds a piece lives at most (it fades out at the end)
115
+ * zIndex: 9999,
116
+ * reduced: 'sparkle' | 'none', // what happens with reduced motion
117
+ * })
118
+ * origin: an element or selector (its centre), or { x, y } in viewport pixels (default: the middle of the screen).
119
+ * Returns a promise that resolves when the last piece is gone, with party.stop() to clear this burst now.
120
+ * confetti.clear() stops every burst.
121
+ */
122
+ export const confetti = (origin, opts = {}) => {
123
+ const o = { count: 120, spread: 100, angle: 90, velocity: 1, colors: null, shapes: ['rect', 'circle', 'strip'], gravity: 1, duration: 3, zIndex: 9999, reduced: 'sparkle', ...opts };
124
+ let done;
125
+ const promise = new Promise((res) => { done = res; });
126
+ const b = { left: 0, end: () => { bursts.delete(b); done(); } };
127
+ promise.stop = () => { for (const p of pieces) if (p.b === b) pieces.delete(p); if (bursts.has(b)) b.end(); if (!pieces.size && layer) close(); };
128
+ if (typeof document === 'undefined') { done(); return promise; }
129
+
130
+ const [pt, el] = pointOf(origin);
131
+ const cs = getComputedStyle(el || document.documentElement);
132
+ const colors = (Array.isArray(o.colors) && o.colors.length ? o.colors : themeColors(el))
133
+ .map((c) => { const m = /^var\((--[\w-]+)\)$/.exec(String(c).trim()); return m ? cs.getPropertyValue(m[1]).trim() || '#888' : c; });
134
+ const shapes = (Array.isArray(o.shapes) ? o.shapes : [o.shapes]).filter((s) => SHAPES.includes(s));
135
+ if (!shapes.length) shapes.push('rect');
136
+ const reduced = RM();
137
+ if (reduced && o.reduced === 'none') { done(); return promise; }
138
+
139
+ const add = (p) => { p.b = b; b.left++; pieces.add(p); };
140
+ if (reduced) {
141
+ for (let i = 0; i < 9; i++) {
142
+ const a = (i / 9) * Math.PI * 2 + rnd(-0.3, 0.3), r = rnd(12, 40);
143
+ add({ shape: 'spark', x: pt.x + Math.cos(a) * r, y: pt.y + Math.sin(a) * r * 0.8, s: rnd(4, 8), rot: 0, alpha: 0, t: -rnd(0, 0.2), life: rnd(0.45, 0.7), color: colors[i % colors.length] });
144
+ }
145
+ } else {
146
+ const n = Math.max(0, Math.min(MAX, Math.round(o.count))), base = Math.PI * (o.angle / 180), half = (Math.PI * Math.max(0, Math.min(360, o.spread)) / 180) / 2;
147
+ const v0 = 1500 * o.velocity * Math.max(0.6, Math.min(1.15, innerHeight / 850));
148
+ for (let i = 0; i < n; i++) {
149
+ const a = base + rnd(-half, half), v = v0 * rnd(0.45, 1), k = rnd(2.6, 4.2);
150
+ add({
151
+ shape: shapes[(Math.random() * shapes.length) | 0], color: colors[i % colors.length],
152
+ x: pt.x + rnd(-6, 6), y: pt.y + rnd(-4, 4), vx: Math.cos(a) * v, vy: -Math.sin(a) * v,
153
+ k, g: 900 * o.gravity, s: rnd(7, 13), rot: rnd(0, Math.PI * 2), spin: rnd(2, 7) * (Math.random() < 0.5 ? -1 : 1),
154
+ flip: rnd(0, Math.PI * 2), fs: rnd(5, 12), wob: rnd(0, Math.PI * 2), ws: rnd(3, 7), sway: rnd(20, 55),
155
+ t: -rnd(0, 0.06), life: o.duration * rnd(0.7, 1), alpha: 1,
156
+ });
157
+ }
158
+ }
159
+ if (!b.left) { done(); return promise; }
160
+ bursts.add(b);
161
+ open(o.zIndex);
162
+ return promise;
163
+ };
164
+
165
+ /** Stop every burst and remove the canvas. */
166
+ confetti.clear = () => { [...bursts].forEach((b) => b.end()); pieces.clear(); if (layer) close(); };
package/src/core.js ADDED
@@ -0,0 +1,26 @@
1
+ /* core: GSAP instance, reduced-motion helpers, small utils */
2
+ import { gsap } from 'gsap';
3
+
4
+ export const g = gsap;
5
+ export { gsap };
6
+ const rmq = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : { matches: false };
7
+ /** Pointer can hover precisely (mouse/trackpad). Magnetic + lift only run when this matches. */
8
+ export const fine = typeof matchMedia === 'function' ? matchMedia('(hover: hover) and (pointer: fine)') : { matches: false };
9
+
10
+ let forceReduced = null;
11
+ /** true when motion should be skipped (OS setting, or forced with reduceMotion(true)). */
12
+ export const RM = () => (forceReduced ?? rmq.matches);
13
+ /** A duration/delay that collapses to 0 under reduced motion. */
14
+ export const D = (v) => (RM() ? 0 : v);
15
+ /** Force reduced motion on/off (null = follow the OS). */
16
+ export const reduceMotion = (v) => { forceReduced = v; };
17
+ /** Play every animation faster/slower: speed(0.5) = half speed, speed(1) = normal. */
18
+ export const speed = (v) => { gsap.globalTimeline.timeScale(v); };
19
+
20
+ /** Elements from a selector, NodeList, array or single element. */
21
+ export const $$ = (sel, root = document) =>
22
+ typeof sel === 'string' ? [...root.querySelectorAll(sel)] : !sel ? [] : sel.nodeType ? [sel] : [...sel];
23
+ export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
24
+
25
+ /** Hover effects wait for this (set true after your intro animation). */
26
+ export const ready = { v: true };
package/src/count.js ADDED
@@ -0,0 +1,21 @@
1
+ /* Count-up numbers */
2
+ import { g, RM, $$ } from './core.js';
3
+
4
+ const state = new WeakMap();
5
+ /** count(el, 1234, v => '฿' + Math.round(v), { duration, delay, from }) */
6
+ export const count = (el, to, fmt = (v) => Math.round(v), { duration = 1.2, delay = 0, from } = {}) => {
7
+ if (!el) return;
8
+ let s = state.get(el); if (!s) state.set(el, (s = { v: from ?? 0 }));
9
+ if (from !== undefined) s.v = from;
10
+ g.killTweensOf(s);
11
+ if (RM() || !duration || s.v === to) { s.v = to; el.textContent = fmt(to); return; }
12
+ el.textContent = fmt(s.v);
13
+ return g.to(s, { v: to, duration, delay, ease: 'power3.out', onUpdate: () => (el.textContent = fmt(s.v)), onComplete: () => (el.textContent = fmt(to)) });
14
+ };
15
+
16
+ /** Every [data-count="1234" data-pre="฿" data-suf="h" data-dec="1"] inside root counts up from 0. */
17
+ export const countAll = (root = document, sel = '[data-count]') => $$(sel, root).forEach((el, i) => {
18
+ const to = parseFloat(el.dataset.count); const dec = +(el.dataset.dec || 0);
19
+ const pre = el.dataset.pre || ''; const suf = el.dataset.suf || '';
20
+ count(el, to, (v) => pre + Number(v).toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec }) + suf, { delay: 0.15 + i * 0.05, from: 0 });
21
+ });
package/src/drag.js ADDED
@@ -0,0 +1,71 @@
1
+ /* Drag & drop: pointer drag (mouse immediate, touch long-press) + elastic landing */
2
+ import { g, RM } from './core.js';
3
+
4
+ /** Animate el from an old rect to where it is now, then squash like it landed. */
5
+ export const landFrom = (el, rect, { squash = true, rotate = 0 } = {}) => {
6
+ if (!el || !rect || RM()) return;
7
+ const n = el.getBoundingClientRect();
8
+ const tl = g.timeline();
9
+ tl.fromTo(el, { x: rect.left - n.left, y: rect.top - n.top, rotation: rotate }, { x: 0, y: 0, rotation: 0, duration: 0.42, ease: 'power3.out' });
10
+ if (squash) tl.fromTo(el, { scaleY: 0.8, scaleX: 1.05 }, { scaleY: 1, scaleX: 1, duration: 0.5, ease: 'elastic.out(1, 0.45)', clearProps: 'transform' });
11
+ else tl.fromTo(el, { scale: 1.04 }, { scale: 1, duration: 0.5, ease: 'power3.out', clearProps: 'transform' }, 0);
12
+ return tl;
13
+ };
14
+
15
+ /**
16
+ * Start a drag from a pointerdown event.
17
+ * el.addEventListener('pointerdown', e => drag(el, e, {
18
+ * targets: '.lane', // drop zones (get .is-target while hovered)
19
+ * onDrop: (zone, rect) => { zone.append(el); landFrom(el, rect); }, // return false to snap back
20
+ * onClick: () => openDetails(), // a press without moving
21
+ * }))
22
+ */
23
+ export const drag = (el, e, { lift = { scale: 1.04, rotation: 1.5 }, targets = '.drop', onStart, onMove, onDrop, onCancel, onClick } = {}) => {
24
+ if (e.button > 0) return;
25
+ const sx = e.clientX, sy = e.clientY, touch = e.pointerType === 'touch';
26
+ let started = false, armed = !touch, over = null, dx = 0, dy = 0;
27
+ const start = () => {
28
+ if (started) return; started = true;
29
+ el.classList.add('is-drag'); document.body.classList.add('is-dragging');
30
+ if (touch && navigator.vibrate) navigator.vibrate(8);
31
+ g.to(el, { ...lift, duration: 0.22, ease: 'power2.out' }); onStart?.();
32
+ };
33
+ const lp = touch ? g.delayedCall(0.32, () => { armed = true; start(); }) : null;
34
+ const move = (ev) => {
35
+ dx = ev.clientX - sx; dy = ev.clientY - sy;
36
+ if (!started) { if (!armed) { if (Math.hypot(dx, dy) > 8) { lp?.kill(); end(); } return; } if (Math.hypot(dx, dy) < 5) return; start(); }
37
+ ev.preventDefault();
38
+ g.set(el, { x: dx, y: dy });
39
+ el.style.pointerEvents = 'none';
40
+ const t = document.elementFromPoint(ev.clientX, ev.clientY)?.closest(targets) ?? null;
41
+ el.style.pointerEvents = '';
42
+ if (t !== over) { over?.classList.remove('is-target'); over = t; over?.classList.add('is-target'); }
43
+ onMove?.(dx, dy, over, ev);
44
+ };
45
+ const back = () => g.to(el, { x: 0, y: 0, rotation: 0, scale: 1, duration: 0.45, ease: 'back.out(1.8)', clearProps: 'transform' });
46
+ const end = () => {
47
+ removeEventListener('pointermove', move); removeEventListener('pointerup', up); removeEventListener('pointercancel', cancel);
48
+ el.classList.remove('is-drag'); document.body.classList.remove('is-dragging'); over?.classList.remove('is-target');
49
+ };
50
+ const up = () => {
51
+ lp?.kill(); end();
52
+ if (!started) { if (Math.hypot(dx, dy) < 6) onClick?.(); return; }
53
+ const rect = el.getBoundingClientRect();
54
+ const ok = over ? onDrop?.(over, rect, { dx, dy }) : false;
55
+ if (ok === false || !over) { back(); onCancel?.(); }
56
+ };
57
+ const cancel = () => { lp?.kill(); end(); back(); onCancel?.(); };
58
+ addEventListener('pointermove', move, { passive: false }); addEventListener('pointerup', up); addEventListener('pointercancel', cancel);
59
+ return { back };
60
+ };
61
+
62
+ /** Make every child matching `items` inside `root` draggable between `zones`. Moves the DOM node. */
63
+ export const sortable = (root, { items = '[data-drag]', zones = '[data-drop]', onChange } = {}) => {
64
+ root.addEventListener('pointerdown', (e) => {
65
+ const el = e.target.closest(items); if (!el || !root.contains(el) || e.target.closest('button, input, a')) return;
66
+ drag(el, e, { targets: zones, onDrop: (zone, rect) => {
67
+ if (zone === el.parentElement) return false;
68
+ g.set(el, { clearProps: 'transform' }); zone.appendChild(el); landFrom(el, rect); onChange?.(el, zone); return true;
69
+ } });
70
+ });
71
+ };
package/src/edge.js ADDED
@@ -0,0 +1,127 @@
1
+ /* Download: the button's own outline is the progress bar. A line grows around the edge from
2
+ the top centre as the file arrives, the label counts the percent and the arrow bobs. When it
3
+ finishes the outline glows, the button fills, the arrow drops into the tray and a tick draws
4
+ itself. Unknown size? A short segment chases round the edge until the first real number. */
5
+ import { g, RM, $$ } from './core.js';
6
+
7
+ const ICON = `<svg class="dl" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
8
+ <g class="dl__arrow"><path d="M12 3.8v10"/><path d="M7.6 9.6 12 14l4.4-4.4"/></g>
9
+ <path class="dl__tray" d="M4.5 15.5v2.4a2.1 2.1 0 0 0 2.1 2.1h10.8a2.1 2.1 0 0 0 2.1-2.1v-2.4"/>
10
+ <path class="dl__tick" d="M7.6 10.6l3.1 3.1 5.9-6.2" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/></svg>`;
11
+ /** The two-part download icon edgeProgress() animates (arrow, tray, tick). */
12
+ export const downloadIcon = ICON;
13
+
14
+ /** A rounded-rectangle path that starts at the top centre and runs clockwise. */
15
+ const outline = (w, h, r, s) => {
16
+ const x = s / 2, y = s / 2, W = w - s, H = h - s; r = Math.max(0, Math.min(r - s / 2, W / 2, H / 2));
17
+ return `M${x + W / 2} ${y}H${x + W - r}A${r} ${r} 0 0 1 ${x + W} ${y + r}V${y + H - r}A${r} ${r} 0 0 1 ${x + W - r} ${y + H}H${x + r}A${r} ${r} 0 0 1 ${x} ${y + H - r}V${y + r}A${r} ${r} 0 0 1 ${x + r} ${y}Z`;
18
+ };
19
+
20
+ const pct = (p) => `${Math.round(p * 100)}%`;
21
+
22
+ /**
23
+ * const dl = edgeProgress(button, { label: (p) => '40%', wait: 'Preparing…', done: 'Done', fail: 'Try again', back: 0, width: 2.5 })
24
+ * dl.set(0.4) — grow the outline to 40% (null = unknown size: a segment chases round the edge)
25
+ * dl.done() — finish: glow, fill, tick. dl.fail() — red outline and a shake. dl.reset() — back to normal.
26
+ * The button needs a <span> label; its icon is swapped for an arrow-and-tray that can turn into a tick.
27
+ */
28
+ export const edgeProgress = (btn, opts = {}) => {
29
+ btn = $$(btn)[0];
30
+ if (!btn) return null;
31
+ if (btn.__edge) { Object.assign(btn.__edge.opts, opts); return btn.__edge; } // same button: update options, keep state
32
+ const o = { label: pct, wait: 'Preparing…', done: 'Done', fail: 'Try again', back: 0, width: 2.5, ...opts };
33
+
34
+ let icon = btn.querySelector(':scope > svg');
35
+ if (!icon?.querySelector('.dl__arrow')) { const t = document.createElement('template'); t.innerHTML = ICON.trim(); const fresh = t.content.firstElementChild; icon ? icon.replaceWith(fresh) : btn.prepend(fresh); icon = fresh; }
36
+ const arrow = icon.querySelector('.dl__arrow'), tray = icon.querySelector('.dl__tray'), tick = icon.querySelector('.dl__tick');
37
+ const label = btn.querySelector(':scope > span:not(.edge__sr)');
38
+ const text0 = label?.textContent ?? '';
39
+ const sr = document.createElement('span'); sr.className = 'edge__sr'; sr.setAttribute('role', 'status'); btn.append(sr);
40
+
41
+ let ring = null, line = null, state = 'idle', bob = null, chase = null, lastSaid = -1;
42
+ const p = { v: 0 };
43
+ const say = (t) => { sr.textContent = t; };
44
+ const setLabel = (t) => { if (label) label.textContent = t; };
45
+ const draw = () => { line?.setAttribute('stroke-dashoffset', String(100 - p.v * 100)); };
46
+
47
+ const build = () => {
48
+ btn.classList.add('edge'); btn.setAttribute('aria-busy', 'true');
49
+ const w = btn.offsetWidth, h = btn.offsetHeight, r = parseFloat(getComputedStyle(btn).borderTopLeftRadius) || 0, s = o.width;
50
+ btn.style.width = w + 'px'; // hold the width while the label changes
51
+ ring?.remove();
52
+ ring = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
53
+ ring.setAttribute('class', 'edge__ring'); ring.setAttribute('viewBox', `0 0 ${w} ${h}`); ring.setAttribute('aria-hidden', 'true');
54
+ const d = outline(w, h, r, s);
55
+ ring.innerHTML = `<path class="edge__track" d="${d}" stroke-width="${s}"/><path class="edge__line" d="${d}" stroke-width="${s}" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100"/>`;
56
+ btn.append(ring); line = ring.querySelector('.edge__line');
57
+ if (!RM()) { g.fromTo(ring, { opacity: 0 }, { opacity: 1, duration: 0.25 }); bob = g.to(arrow, { y: 2.5, duration: 0.45, ease: 'sine.inOut', yoyo: true, repeat: -1 }); }
58
+ };
59
+ const stopChase = () => { chase?.kill(); chase = null; ring?.classList.remove('is-chasing'); line?.setAttribute('stroke-dasharray', '100'); draw(); };
60
+
61
+ const api = {
62
+ el: btn, opts: o,
63
+ get progress() { return p.v; },
64
+ get state() { return state; },
65
+ /** Grow the outline to p (0–1). null = size unknown: a segment chases round the edge. */
66
+ set(v) {
67
+ if (state === 'done') return api;
68
+ if (state !== 'loading') { if (state === 'failed') api.reset(true); state = 'loading'; build(); }
69
+ if (v == null) {
70
+ setLabel(api.opts.wait); say(api.opts.wait);
71
+ if (!chase && !RM()) { ring.classList.add('is-chasing'); line.setAttribute('stroke-dasharray', '22 78'); chase = g.fromTo(line, { attr: { 'stroke-dashoffset': 0 } }, { attr: { 'stroke-dashoffset': -100 }, duration: 1.1, ease: 'none', repeat: -1 }); }
72
+ return api;
73
+ }
74
+ if (chase) stopChase();
75
+ v = Math.max(0, Math.min(1, +v));
76
+ const show = () => { setLabel(api.opts.label(p.v)); draw(); };
77
+ if (RM()) { p.v = v; show(); } else g.to(p, { v, duration: 0.45, ease: 'power2.out', overwrite: true, onUpdate: show });
78
+ const ten = Math.floor(v * 10); if (ten !== lastSaid) { lastSaid = ten; say(`Downloading ${Math.round(v * 100)}%`); }
79
+ return api;
80
+ },
81
+ /** Finish: the outline closes and glows, the button fills, the arrow drops into the tray, a tick draws. */
82
+ done(text = api.opts.done) {
83
+ if (state === 'idle') { state = 'loading'; build(); }
84
+ if (state === 'done') return g.timeline();
85
+ state = 'done'; stopChase(); bob?.kill(); g.killTweensOf(p);
86
+ btn.removeAttribute('aria-busy'); say(text);
87
+ const tl = g.timeline({ onComplete: () => { if (api.opts.back > 0) g.delayedCall(api.opts.back, () => api.reset()); } });
88
+ if (RM()) { p.v = 1; draw(); btn.classList.add('is-done'); setLabel(text); g.set(arrow, { opacity: 0 }); g.set(tick, { attr: { 'stroke-dashoffset': 0 } }); return tl; }
89
+ tl.to(p, { v: 1, duration: 0.3, ease: 'power2.out', onUpdate: () => { setLabel(api.opts.label(p.v)); draw(); } })
90
+ .to(ring, { scale: 1.06, opacity: 0, duration: 0.5, ease: 'power2.out', transformOrigin: '50% 50%' })
91
+ .add(() => btn.classList.add('is-done'), '<')
92
+ .to(btn, { keyframes: { scale: [1, 1.04, 1] }, duration: 0.45, ease: 'power2.out' }, '<')
93
+ .to(arrow, { y: 7, opacity: 0, duration: 0.25, ease: 'power2.in' }, '<')
94
+ .to(tray, { keyframes: { scaleY: [1, 0.7, 1] }, svgOrigin: '12 20', duration: 0.35, ease: 'power2.out' }, '<0.15')
95
+ .to(tick, { attr: { 'stroke-dashoffset': 0 }, duration: 0.4, ease: 'power2.out' }, '<0.1')
96
+ .add(() => { setLabel(text); if (label) g.fromTo(label, { y: 8, opacity: 0 }, { y: 0, opacity: 1, duration: 0.4, ease: 'back.out(2)', clearProps: 'transform,opacity' }); }, '<');
97
+ return tl;
98
+ },
99
+ /** Stop with an error: the outline turns red, the button shakes, the label asks to try again. */
100
+ fail(text = api.opts.fail) {
101
+ if (state !== 'loading') return g.timeline();
102
+ state = 'failed'; stopChase(); bob?.kill(); g.killTweensOf(p); g.to(arrow, { y: 0, duration: 0.2 });
103
+ btn.removeAttribute('aria-busy'); btn.classList.add('is-failed'); setLabel(text); say(text);
104
+ return RM() ? g.timeline() : g.timeline().fromTo(btn, { x: 0 }, { keyframes: { x: [0, -7, 6, -4, 2, 0] }, duration: 0.42, ease: 'power2.out', clearProps: 'x' });
105
+ },
106
+ /** Back to the start: outline gone, label and arrow back. */
107
+ reset(quick = false) {
108
+ stopChase(); bob?.kill(); g.killTweensOf([p, ring, arrow, tick, label]);
109
+ state = 'idle'; p.v = 0; lastSaid = -1;
110
+ btn.classList.remove('is-done', 'is-failed'); btn.removeAttribute('aria-busy');
111
+ const old = ring; ring = null; line = null;
112
+ const restore = () => {
113
+ const w0 = btn.offsetWidth; btn.style.width = ''; setLabel(text0); const w1 = btn.offsetWidth;
114
+ if (!RM() && !quick && Math.abs(w1 - w0) > 1) g.fromTo(btn, { width: w0 }, { width: w1, duration: 0.35, ease: 'power3.out', clearProps: 'width' });
115
+ g.set(tick, { attr: { 'stroke-dashoffset': 1 } });
116
+ if (RM() || quick) { g.set(arrow, { clearProps: 'all' }); return; }
117
+ g.fromTo(arrow, { y: -8, opacity: 0 }, { y: 0, opacity: 1, duration: 0.45, ease: 'back.out(2)', clearProps: 'all' });
118
+ if (label) g.fromTo(label, { y: 8, opacity: 0 }, { y: 0, opacity: 1, duration: 0.35, ease: 'power3.out', clearProps: 'transform,opacity' });
119
+ };
120
+ if (old && !RM() && !quick) g.to(old, { opacity: 0, duration: 0.2, onComplete: () => old.remove() }); else old?.remove();
121
+ restore(); say('');
122
+ return api;
123
+ },
124
+ };
125
+ btn.__edge = api;
126
+ return api;
127
+ };
package/src/enter.js ADDED
@@ -0,0 +1,24 @@
1
+ /* Entrances: rise (cards), slide (rows), deal (tilted cards) */
2
+ import { g, D, $$ } from './core.js';
3
+
4
+ export const rise = (els, { y = 26, stagger = 0.06, delay = 0, duration = 0.8 } = {}) => {
5
+ els = $$(els); const tl = g.timeline({ delay: D(delay) });
6
+ if (els.length) tl.fromTo(els, { opacity: 0, y, scale: 0.985 },
7
+ { opacity: 1, y: 0, scale: 1, duration: D(duration), ease: 'expo.out', stagger: D(stagger), clearProps: 'transform,opacity' });
8
+ return tl;
9
+ };
10
+
11
+ export const slide = (els, { x = 0, y = 12, stagger = 0.04, delay = 0, duration = 0.55 } = {}) => {
12
+ els = $$(els); if (!els.length) return g.timeline();
13
+ return g.fromTo(els, { opacity: 0, x, y },
14
+ { opacity: 1, x: 0, y: 0, duration: D(duration), ease: 'power3.out', stagger: D(stagger), delay: D(delay), clearProps: 'transform,opacity' });
15
+ };
16
+
17
+ export const deal = (els, { delay = 0, stagger = 0.07, tilt = 2.5 } = {}) => {
18
+ els = $$(els); if (!els.length) return g.timeline();
19
+ return g.fromTo(els, { opacity: 0, y: 40, rotation: (i) => (i % 2 ? tilt : -tilt), scale: 0.95 },
20
+ { opacity: 1, y: 0, rotation: 0, scale: 1, duration: D(0.85), ease: 'back.out(1.4)', stagger: D(stagger), delay: D(delay), clearProps: 'transform,opacity' });
21
+ };
22
+
23
+ /** Small fade-down used for accordion bodies. */
24
+ export const reveal = (el, y = -4) => { if (el) g.fromTo(el, { opacity: 0, y }, { opacity: 1, y: 0, duration: D(0.3), ease: 'power3.out', clearProps: 'transform,opacity' }); };
@@ -0,0 +1,25 @@
1
+ /* Feedback: flash (value changed), tick up/down, pop (press), shake (no), wiggle (bell) */
2
+ import { g, RM } from './core.js';
3
+
4
+ export const flash = (el) => {
5
+ if (!el) return;
6
+ el.classList.remove('is-flash'); void el.offsetWidth; el.classList.add('is-flash');
7
+ if (!RM()) g.fromTo(el, { y: -4, scale: 1.08 }, { y: 0, scale: 1, duration: 0.55, ease: 'back.out(2.4)', overwrite: 'auto', clearProps: 'transform' });
8
+ };
9
+ export const tick = (el, up) => { if (!el) return; el.classList.remove('tick-up', 'tick-down'); void el.offsetWidth; el.classList.add(up ? 'tick-up' : 'tick-down'); };
10
+
11
+ /** Springs the icon (or the element) back after a press. */
12
+ export const pop = (el) => {
13
+ if (!el || RM()) return;
14
+ const t = el.querySelector?.('svg') ?? el;
15
+ return g.fromTo(t, { scale: 0.7 }, { scale: 1, duration: 0.55, ease: 'back.out(3)', overwrite: true });
16
+ };
17
+ export const shake = (el) => {
18
+ if (!el || RM()) return;
19
+ return g.fromTo(el, { x: 0 }, { keyframes: { x: [0, -8, 7, -5, 3, 0] }, duration: 0.42, ease: 'power2.out', clearProps: 'transform' });
20
+ };
21
+ /** Bell-style wiggle, swinging from the top. */
22
+ export const wiggle = (el) => {
23
+ if (!el || RM()) return;
24
+ return g.fromTo(el, { rotation: 0 }, { keyframes: { rotation: [0, 16, -14, 10, -6, 0] }, duration: 0.8, ease: 'power2.out', transformOrigin: '50% 10%' });
25
+ };
package/src/fly.js ADDED
@@ -0,0 +1,88 @@
1
+ /* Send: the button's plane icon winds back, then flies off along a path (it turns to face the
2
+ way it is going), leaving a short dotted trail. The label lifts away, the button turns green
3
+ and "Sent" rolls in with a tick that draws itself. After a moment it all comes back. */
4
+ import { g, RM, $$ } from './core.js';
5
+
6
+ const TICK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5.5 12.5l4 4L18.5 7.5"/></svg>';
7
+
8
+ /** Flight paths: t 0→1 gives a point; d is how far right the plane must go to leave the button. */
9
+ const PATHS = {
10
+ up: (t, d) => ({ x: d * t ** 1.5, y: -46 * t ** 2 }),
11
+ straight: (t, d) => ({ x: d * t ** 1.8, y: -6 * t }),
12
+ loop: (t, d) => {
13
+ const a = 0.6; // the first 60% is a loop-the-loop, then it heads off
14
+ if (t < a) { const s = t / a, R = 17; return { x: 34 * s + R * Math.sin(2 * Math.PI * s), y: -R * (1 - Math.cos(2 * Math.PI * s)) }; }
15
+ const s = (t - a) / (1 - a);
16
+ return { x: 34 + (d - 34) * s ** 1.4, y: -26 * s ** 1.6 };
17
+ },
18
+ };
19
+ const HEADING = -45; // the send icon points up-right
20
+
21
+ /**
22
+ * sendOff(button, { done: 'Sent', path: 'up'|'straight'|'loop', trail: true, back: 2.4, duration, onDone })
23
+ * The button needs an <svg> (the plane) and a <span> label, like btn('Send', { icon: 'send' }).
24
+ * back: seconds before it resets (0 = stay sent; call sendOff.reset(button) yourself).
25
+ */
26
+ export const sendOff = (btn, { done = 'Sent', path = 'up', trail = true, back = 2.4, duration, onDone } = {}) => {
27
+ btn = $$(btn)[0];
28
+ if (!btn || btn.__flying) return g.timeline();
29
+ const ic = btn.querySelector(':scope > svg'), label = [...btn.querySelectorAll(':scope > span:not(.fly__done)')]; // [] for an icon-only button
30
+ btn.__flying = true; btn.classList.add('fly'); btn.setAttribute('aria-disabled', 'true');
31
+ let msg = btn.querySelector('.fly__done');
32
+ if (!msg) { msg = document.createElement('span'); msg.className = 'fly__done'; msg.setAttribute('role', 'status'); btn.append(msg); }
33
+ msg.innerHTML = `${TICK}<b>${String(done).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)}</b>`;
34
+ const tick = msg.querySelector('path');
35
+ const finish = () => { onDone?.(btn); if (back > 0) g.delayedCall(back, () => reset(btn)); };
36
+
37
+ if (RM()) {
38
+ btn.classList.add('is-sent'); g.set([ic, ...label], { opacity: 0 }); g.set(msg, { opacity: 1, y: 0 }); g.set(tick, { strokeDashoffset: 0 });
39
+ finish(); return g.timeline();
40
+ }
41
+
42
+ const fn = PATHS[path] || PATHS.up;
43
+ const b = btn.getBoundingClientRect(), r = ic ? ic.getBoundingClientRect() : b;
44
+ const d = b.right - r.left + 70; // fly well past the right edge
45
+ const flight = duration ?? (path === 'loop' ? 1.15 : 0.75);
46
+ const p = { t: 0 }; let n = 0;
47
+ const place = () => {
48
+ const t = p.t, a = fn(t, d), z = fn(Math.min(1, t + 0.01), d);
49
+ const turn = Math.min(1, t * 7); // ease from resting angle into facing the path
50
+ const ang = Math.atan2(z.y - a.y, z.x - a.x) * 180 / Math.PI - HEADING;
51
+ // start from the wound-back pose (x -6, -14°) and blend into the path
52
+ g.set(ic, { x: a.x - 6 * (1 - turn), y: a.y, rotation: -14 + turn * (ang + 14), scale: 1 - 0.35 * t, opacity: t > 0.78 ? 1 - (t - 0.78) / 0.22 : 1 });
53
+ if (trail && ++n % 3 === 0 && t < 0.85) dot(btn, r.left - b.left + r.width / 2 + a.x, r.top - b.top + r.height / 2 + a.y);
54
+ };
55
+
56
+ const tl = g.timeline({ onComplete: finish });
57
+ tl.to(btn, { scale: 0.95, duration: 0.12, ease: 'power2.out' })
58
+ .to(btn, { scale: 1, duration: 0.6, ease: 'back.out(3)' })
59
+ .to(label, { y: -12, opacity: 0, duration: 0.25, ease: 'power2.in' }, 0.04)
60
+ .to(ic, { x: -6, rotation: -14, duration: 0.2, ease: 'power2.out' }, 0.04)
61
+ .to(p, { t: 1, duration: flight, ease: 'power1.in', onUpdate: place }, 0.24)
62
+ .add(() => btn.classList.add('is-sent'), 0.24 + flight * 0.55)
63
+ .fromTo(msg, { opacity: 0, y: 12 }, { opacity: 1, y: 0, duration: 0.45, ease: 'back.out(2)' }, 0.24 + flight * 0.6)
64
+ .fromTo(tick, { strokeDashoffset: 22 }, { strokeDashoffset: 0, duration: 0.4, ease: 'power2.out' }, '<0.12');
65
+ return tl;
66
+ };
67
+
68
+ /** Little dots left behind the plane; each fades and drifts down. */
69
+ const dot = (btn, x, y) => {
70
+ const s = document.createElement('i'); s.className = 'fly__dot';
71
+ s.style.left = x + 'px'; s.style.top = y + 'px'; btn.append(s);
72
+ g.fromTo(s, { scale: 1, opacity: 0.9 }, { scale: 0.2, opacity: 0, y: 6, duration: 0.6, ease: 'power1.out', onComplete: () => s.remove() });
73
+ };
74
+
75
+ /** Put the button back: "Sent" drops away, the plane glides in from the left, the label returns. */
76
+ export const reset = (btn) => {
77
+ btn = $$(btn)[0]; if (!btn) return g.timeline();
78
+ const ic = btn.querySelector(':scope > svg'), label = [...btn.querySelectorAll(':scope > span:not(.fly__done)')], msg = btn.querySelector('.fly__done');
79
+ g.killTweensOf([ic, ...label, msg]);
80
+ const end = () => { btn.__flying = false; btn.removeAttribute('aria-disabled'); };
81
+ if (RM()) { btn.classList.remove('is-sent'); g.set([ic, ...label, msg], { clearProps: 'all' }); end(); return g.timeline(); }
82
+ return g.timeline({ onComplete: end })
83
+ .to(msg, { opacity: 0, y: -10, duration: 0.25, ease: 'power2.in' })
84
+ .add(() => btn.classList.remove('is-sent'))
85
+ .fromTo(ic, { x: -26, y: 8, rotation: 20, scale: 0.6, opacity: 0 }, { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, duration: 0.6, ease: 'expo.out', clearProps: 'all' })
86
+ .fromTo(label, { y: 12, opacity: 0 }, { y: 0, opacity: 1, duration: 0.45, ease: 'power3.out', clearProps: 'all' }, '<0.08');
87
+ };
88
+ sendOff.reset = reset;