@gecko-ui-kit/components 0.20.0 → 0.21.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/bell.js ADDED
@@ -0,0 +1,137 @@
1
+ /* Notification bell: an on / off switch for notifications that shows its state with the bell itself.
2
+ Turning it on fills the circle with colour and rings the bell: it swings from the top a few times,
3
+ each swing smaller, the clapper following a beat later, and two small sound waves flash beside it.
4
+ Turning it off draws a slash across the bell from corner to corner (a thin gap in the background colour
5
+ cuts the bell where the slash crosses it). The small line under the label rolls to "On" / "Off".
6
+ It is a real <button role="switch"> with aria-checked, named by its label; the state line is for the eyes
7
+ (screen readers already hear "on" / "off"). If your onChange returns a promise that fails, it switches
8
+ back and shakes. bellBtn() writes the HTML; bellSwitch() wires one up; bindAll(root) wires every
9
+ .nbell inside root for you. */
10
+ import * as M from '@gecko-ui-kit/motion';
11
+ import { esc } from '../index.js';
12
+
13
+ const { g, RM, $$ } = M;
14
+ const WORDS = { label: 'Notifications', on: 'On', off: 'Off' };
15
+ const TONES = { accent: 'var(--accent)', good: 'var(--good)', warn: 'var(--warn)', bad: 'var(--bad)' };
16
+ const HUES = ['indigo', 'teal', 'rose', 'amber', 'violet', 'green', 'slate', 'sky'];
17
+ const toColor = (t) => (!t ? '' : TONES[t] || (HUES.includes(t) ? `var(--hue-${t})` : String(t)));
18
+ let uid = 0;
19
+
20
+ const SVG = (on) => '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">'
21
+ + '<g class="nbell__waves"><path d="M3.6 6.2a8.6 8.6 0 0 0-1 4.3"/><path d="M20.4 6.2a8.6 8.6 0 0 1 1 4.3"/></g>'
22
+ + '<g class="nbell__body"><path d="M6 9.5a6 6 0 1 1 12 0c0 5.6 2.4 7.2 2.4 7.2H3.6S6 15.1 6 9.5"/>'
23
+ + '<path class="nbell__clap" d="M10 20.2a2.2 2.2 0 0 0 4 0"/></g>'
24
+ + `<path class="nbell__halo" d="M4 3.5 20 19.5" pathLength="1" stroke-dasharray="1 2" stroke-dashoffset="${on ? 1 : 0}"/>`
25
+ + `<path class="nbell__slash" d="M4 3.5 20 19.5" pathLength="1" stroke-dasharray="1 2" stroke-dashoffset="${on ? 1 : 0}"/></svg>`;
26
+
27
+ /**
28
+ * bellBtn({ on, label, iconOnly, tone, words, cls, attrs }) → HTML string
29
+ * label: the visible name (default words.label, "Notifications"). iconOnly: just the round bell (label
30
+ * becomes its aria-label). tone: 'accent' | 'good' | a palette name | any CSS colour.
31
+ */
32
+ export const bellBtn = (opts = {}) => {
33
+ const W = { ...WORDS, ...opts.words }, on = !!opts.on, label = opts.label || W.label;
34
+ const id = `nbell-${++uid}`, c = toColor(opts.tone);
35
+ return `<button type="button" class="nbell${opts.iconOnly ? ' nbell--icon' : ''}${opts.cls ? ` ${esc(opts.cls)}` : ''}" role="switch" aria-checked="${on}"`
36
+ + (opts.iconOnly ? ` aria-label="${esc(label)}"` : ` aria-labelledby="${id}"`)
37
+ + ` data-on-text="${esc(W.on)}" data-off-text="${esc(W.off)}"${c ? ` style="--nb-c:${esc(c)}"` : ''}${opts.attrs ? ' ' + opts.attrs : ''}>`
38
+ + `<span class="nbell__icon">${SVG(on)}</span>`
39
+ + (opts.iconOnly ? '' : `<span class="nbell__text"><b class="nbell__label" id="${id}">${esc(label)}</b><small class="nbell__state" aria-hidden="true"><span>${esc(on ? W.on : W.off)}</span></small></span>`)
40
+ + '</button>';
41
+ };
42
+
43
+ /**
44
+ * const bell = bellSwitch(el, {
45
+ * on: false, label: 'Notifications', iconOnly: false, tone: '',
46
+ * words: { label, on, off },
47
+ * onChange(on, bell), // return a promise: if it fails, the switch goes back
48
+ * })
49
+ * bell.on · bell.set(on, { silent, animate }) · bell.toggle() · bell.ring() · bell.destroy()
50
+ *
51
+ * el is a .nbell button from bellBtn() (its state is read from the markup) or an empty element to build one in.
52
+ * Calling it again on the same button returns the same handle with the new options merged in.
53
+ */
54
+ export const bellSwitch = (el, opts = {}) => {
55
+ el = $$(el)[0];
56
+ if (!el) return null;
57
+ if (el.__nbell) { Object.assign(el.__nbell.opts, opts); return el.__nbell; }
58
+ let b = el, built = false;
59
+ if (!el.matches('.nbell')) { el.innerHTML = bellBtn(opts); b = el.firstElementChild; built = true; }
60
+ const o = { onChange: null, ...opts };
61
+ const W = { ...WORDS, ...o.words };
62
+ const onText = b.dataset.onText || W.on, offText = b.dataset.offText || W.off;
63
+ const $ = (s) => b.querySelector(s);
64
+ const body = $('.nbell__body'), clap = $('.nbell__clap'), waves = [...b.querySelectorAll('.nbell__waves path')];
65
+ const lines = [$('.nbell__halo'), $('.nbell__slash')], stateEl = $('.nbell__state > span');
66
+ const ac = new AbortController();
67
+ let on = b.getAttribute('aria-checked') === 'true';
68
+
69
+ /** Ring the bell: big swing first, each one smaller, the clapper a beat behind. */
70
+ const ring = () => {
71
+ g.killTweensOf([body, clap, ...waves]);
72
+ if (RM()) return g.timeline();
73
+ const swing = [0, 22, -18, 12, -8, 4, 0];
74
+ const tl = g.timeline();
75
+ tl.to(body, { keyframes: { rotation: swing }, svgOrigin: '12 3.5', duration: 0.9, ease: 'power1.out' }, 0)
76
+ .to(clap, { keyframes: { rotation: swing.map((r) => r * 0.6) }, svgOrigin: '12 3.5', duration: 0.9, ease: 'power1.out' }, 0.06);
77
+ waves.forEach((w, i) => tl.fromTo(w, { opacity: 0, x: i ? -2 : 2 }, { keyframes: { opacity: [0, 1, 1, 0] }, x: 0, duration: 0.55, ease: 'power1.out' }, 0.05 + i * 0.08));
78
+ return tl;
79
+ };
80
+ const draw = (animate) => {
81
+ b.setAttribute('aria-checked', String(on));
82
+ g.killTweensOf(lines);
83
+ const off = on ? 1 : 0;
84
+ if (!animate || RM()) lines.forEach((l) => l.setAttribute('stroke-dashoffset', String(off)));
85
+ else g.to(lines, { attr: { 'stroke-dashoffset': off }, duration: on ? 0.2 : 0.38, ease: on ? 'power2.in' : 'power2.out', delay: on ? 0 : 0.05 });
86
+ if (stateEl) {
87
+ const t = on ? onText : offText;
88
+ if (stateEl.textContent !== t) {
89
+ stateEl.textContent = t;
90
+ if (animate && !RM()) g.fromTo(stateEl, { yPercent: on ? 80 : -80, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.3, ease: 'back.out(2)', clearProps: 'all' });
91
+ }
92
+ }
93
+ if (on && animate) ring();
94
+ else if (!on) { g.killTweensOf([body, clap, ...waves]); g.set([body, clap], { rotation: 0, svgOrigin: '12 3.5' }); g.set(waves, { opacity: 0 }); }
95
+ };
96
+
97
+ const api = {
98
+ el: b, opts: o,
99
+ get on() { return on; },
100
+ /** Switch it on or off. silent (default) skips onChange. */
101
+ set(next, { silent = true, animate = true } = {}) {
102
+ next = !!next;
103
+ if (next === on) return api;
104
+ on = next; draw(animate);
105
+ if (!silent) changed();
106
+ return api;
107
+ },
108
+ toggle() { return api.set(!on, { silent: false }); },
109
+ /** Ring it again (for example when a new notification comes in). */
110
+ ring,
111
+ destroy() {
112
+ ac.abort();
113
+ g.killTweensOf([body, clap, stateEl, ...waves, ...lines].filter(Boolean));
114
+ delete b.__nbell;
115
+ if (built) { delete el.__nbell; el.innerHTML = ''; }
116
+ },
117
+ };
118
+ const changed = () => {
119
+ const was = on;
120
+ let r;
121
+ try { r = api.opts.onChange?.(on, api); } catch { r = Promise.reject(); }
122
+ if (r && typeof r.then === 'function') {
123
+ Promise.resolve(r).catch(() => {
124
+ if (!b.isConnected || on !== was) return;
125
+ on = !was; draw(false); M.shake(b);
126
+ });
127
+ }
128
+ };
129
+ b.addEventListener('click', () => api.toggle(), { signal: ac.signal });
130
+ b.__nbell = api;
131
+ if (built) el.__nbell = api;
132
+ return api;
133
+ };
134
+
135
+ /** Wires every .nbell switch inside root (bindAll does this for you). Returns the handles. */
136
+ export const bindBells = (root = document) =>
137
+ $$(root.matches?.('.nbell') ? [root] : $$('.nbell', root)).map((b) => b.__nbell || bellSwitch(b));
package/src/like.js ADDED
@@ -0,0 +1,208 @@
1
+ /* Like & bookmark: an on / off icon button that celebrates when it turns on. Three looks share one API:
2
+ - heart (Like): the heart pops in from small with a little overshoot, a ring bursts out and thins away,
3
+ and eight dots fly out in a circle (two colours, a random twist each time).
4
+ - star: the same pop and burst with a star.
5
+ - bookmark (Save): the ribbon fills with colour from the top, dips down a little and throws four sparks
6
+ up and out. It can say "Save" / "Saved".
7
+ An optional count rolls up (or down when the like is taken back). Turning it off is quiet: a small dip.
8
+ It is a real <button> with aria-pressed. If your onChange returns a promise that fails (the server said
9
+ no), the button goes back to how it was and gives a small shake. likeBtn() writes the HTML; likeButton()
10
+ wires one up; bindAll(root) wires every .lk button inside root for you. */
11
+ import * as M from '@gecko-ui-kit/motion';
12
+ import { esc } from '../index.js';
13
+
14
+ const { g, RM, $$ } = M;
15
+ const WORDS = { like: 'Like', star: 'Star', save: 'Save', saved: 'Saved', withCount: (label, count) => `${label}, ${count}` };
16
+
17
+ /* the outline shapes (24 × 24) */
18
+ const SHAPES = {
19
+ heart: 'M20.4 5.6a5 5 0 0 0-7.1 0L12 6.9l-1.3-1.3a5 5 0 0 0-7.1 7.1L12 21l8.4-8.3a5 5 0 0 0 0-7.1z',
20
+ star: 'm12 3 2.7 5.6 6.1.8-4.5 4.2 1.1 6.1L12 16.8l-5.4 2.9 1.1-6.1-4.5-4.2 6.1-.8z',
21
+ bookmark: 'M6.5 4.6c0-.9.7-1.6 1.6-1.6h7.8c.9 0 1.6.7 1.6 1.6V21L12 17.2 6.5 21z',
22
+ };
23
+ const KINDS = Object.keys(SHAPES);
24
+ const TONES = { accent: 'var(--accent)', good: 'var(--good)', warn: 'var(--warn)', bad: 'var(--bad)' };
25
+ const HUES = ['indigo', 'teal', 'rose', 'amber', 'violet', 'green', 'slate', 'sky'];
26
+ const toColor = (t) => (!t ? '' : TONES[t] || (HUES.includes(t) ? `var(--hue-${t})` : String(t)));
27
+ const kindOf = (k) => (KINDS.includes(k) ? k : 'heart');
28
+ const defaults = (kind, W) => (kind === 'bookmark' ? [W.save, W.saved] : [kind === 'star' ? W.star : W.like, '']);
29
+ const svg = (kind) => `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${SHAPES[kind]}"/></svg>`;
30
+
31
+ /**
32
+ * likeBtn({ kind, pressed, count, label, onLabel, iconOnly, size, tone, format, words, cls, attrs }) → HTML string
33
+ * kind: 'heart' (default) | 'star' | 'bookmark'. count: a number shows a rolling count (null = none).
34
+ * label / onLabel: the text (onLabel replaces it while on, e.g. Save → Saved). size: '' | 'sm' | 'lg'.
35
+ * iconOnly: a round icon button (the label becomes its aria-label). tone: 'accent' | 'rose' | any CSS colour.
36
+ */
37
+ export const likeBtn = (opts = {}) => {
38
+ const kind = kindOf(opts.kind), W = { ...WORDS, ...opts.words };
39
+ const [l0, on0] = defaults(kind, W);
40
+ const label = opts.label ?? l0, onLabel = opts.onLabel ?? on0;
41
+ const pressed = !!opts.pressed, hasCount = opts.count != null && opts.count !== '';
42
+ const count = hasCount ? Math.max(0, Math.round(+opts.count || 0)) : null;
43
+ const fmt = (n) => (opts.format ? String(opts.format(n)) : n.toLocaleString());
44
+ const c = toColor(opts.tone);
45
+ const swap = !opts.iconOnly && onLabel && onLabel !== label;
46
+ const name = opts.iconOnly ? ` aria-label="${esc(hasCount ? W.withCount(label, fmt(count)) : label)}"` : '';
47
+ const bits = '<i></i>'.repeat(kind === 'bookmark' ? 4 : 8);
48
+ return `<button type="button" class="lk lk--${kind}${opts.iconOnly ? ' lk--icon' : ''}${opts.size ? ` lk--${esc(opts.size)}` : ''}${opts.cls ? ` ${esc(opts.cls)}` : ''}"`
49
+ + ` aria-pressed="${pressed}" data-kind="${kind}" data-label="${esc(label)}"${onLabel ? ` data-on-label="${esc(onLabel)}"` : ''}${hasCount ? ` data-count="${count}"` : ''}`
50
+ + `${c ? ` style="--lk-c:${esc(c)}"` : ''}${name}${opts.attrs ? ' ' + opts.attrs : ''}>`
51
+ + `<span class="lk__icon" aria-hidden="true">${kind === 'bookmark' ? '' : '<span class="lk__ring"></span>'}<span class="lk__bits">${bits}</span>`
52
+ + `<span class="lk__glyph"><span class="lk__line">${svg(kind)}</span><span class="lk__solid">${svg(kind)}</span></span></span>`
53
+ + (opts.iconOnly ? '' : `${swap ? `<span class="lk__sr">${esc(label)}</span>` : ''}<span class="lk__label"${swap ? ' aria-hidden="true"' : ''}>${esc(pressed && swap ? onLabel : label)}</span>`
54
+ + (hasCount ? `<span class="lk__count"><span class="lk__num">${esc(fmt(count))}</span></span>` : ''))
55
+ + '</button>';
56
+ };
57
+
58
+ /**
59
+ * const like = likeButton(el, {
60
+ * kind: 'heart' | 'star' | 'bookmark',
61
+ * pressed: false, count: 128, // count: null = no number
62
+ * label: 'Like', onLabel: '', // bookmark defaults: 'Save' / 'Saved'
63
+ * iconOnly: false, size: '', tone: '',
64
+ * format: (n) => n.toLocaleString(),
65
+ * words: { like, star, save, saved, withCount },
66
+ * onChange(pressed, count, like), // return a promise: if it fails, the button goes back
67
+ * })
68
+ * like.pressed · like.count · like.set(pressed, { silent }) · like.toggle() · like.setCount(n) · like.destroy()
69
+ *
70
+ * el is a .lk button from likeBtn() (its state is read from the markup) or an empty element to build one in.
71
+ * Calling it again on the same button returns the same handle with the new options merged in.
72
+ */
73
+ export const likeButton = (el, opts = {}) => {
74
+ el = $$(el)[0];
75
+ if (!el) return null;
76
+ if (el.__lk) { Object.assign(el.__lk.opts, opts); return el.__lk; }
77
+ let b = el, built = false;
78
+ if (!el.matches('.lk')) { el.innerHTML = likeBtn(opts); b = el.firstElementChild; built = true; }
79
+ const o = { onChange: null, format: null, ...opts };
80
+ const W = { ...WORDS, ...o.words };
81
+ const kind = kindOf(b.dataset.kind || o.kind);
82
+ const label = b.dataset.label ?? defaults(kind, W)[0], onLabel = b.dataset.onLabel || '';
83
+ const icon = b.querySelector('.lk__icon'), glyph = b.querySelector('.lk__glyph'), solid = b.querySelector('.lk__solid');
84
+ const ring = b.querySelector('.lk__ring'), bits = [...b.querySelectorAll('.lk__bits i')];
85
+ const labelEl = b.querySelector('.lk__label'), num = b.querySelector('.lk__num');
86
+ const iconOnly = b.classList.contains('lk--icon');
87
+ const ac = new AbortController();
88
+ let pressed = b.getAttribute('aria-pressed') === 'true';
89
+ let count = b.dataset.count != null ? Math.max(0, +b.dataset.count || 0) : null;
90
+ const fmt = (n) => (api.opts.format ? String(api.opts.format(n)) : n.toLocaleString());
91
+
92
+ /* ---------- the little shows ---------- */
93
+ const burst = () => {
94
+ const s = icon.offsetWidth || 20, tl = g.timeline();
95
+ tl.fromTo(glyph, { scale: 0.2 }, { scale: 1, duration: 0.55, ease: 'back.out(2.8)', clearProps: 'transform' }, 0);
96
+ if (ring) {
97
+ const d = s + 16;
98
+ tl.fromTo(ring, { scale: 0.2, opacity: 1, borderWidth: d / 2 }, { scale: 1.15, borderWidth: 0, duration: 0.45, ease: 'power2.out' }, 0)
99
+ .set(ring, { opacity: 0 });
100
+ }
101
+ const twist = Math.random() * 40 - 20;
102
+ bits.forEach((dot, i) => {
103
+ const a = ((i * 360) / bits.length + twist) * (Math.PI / 180);
104
+ const r0 = s * 0.45, r1 = s * (i % 2 ? 1 : 1.25);
105
+ tl.fromTo(dot, { x: Math.sin(a) * r0, y: -Math.cos(a) * r0, scale: 1, opacity: 1 },
106
+ { x: Math.sin(a) * r1, y: -Math.cos(a) * r1, scale: 0.3, opacity: 0, duration: 0.6, ease: 'power2.out' }, 0.12);
107
+ });
108
+ return tl;
109
+ };
110
+ const fill = () => {
111
+ const s = icon.offsetWidth || 20, tl = g.timeline();
112
+ tl.fromTo(solid, { clipPath: 'inset(0% 0% 100% 0%)' }, { clipPath: 'inset(0% 0% 0% 0%)', duration: 0.35, ease: 'power2.inOut', clearProps: 'clipPath' }, 0)
113
+ .to(glyph, { keyframes: { y: [0, s * 0.18, 0], scaleY: [1, 1.12, 1] }, transformOrigin: '50% 0%', duration: 0.55, ease: 'power1.out', clearProps: 'transform' }, 0.2);
114
+ [-55, -20, 20, 55].forEach((deg, i) => {
115
+ const a = deg * (Math.PI / 180), x0 = (i < 2 ? -1 : 1) * s * (i % 3 ? 0.18 : 0.42);
116
+ tl.fromTo(bits[i], { x: x0, y: 0, rotation: deg, scaleY: 1, opacity: 1 },
117
+ { x: x0 + Math.sin(a) * s * 0.55, y: -Math.cos(a) * s * 0.55, scaleY: 0.3, opacity: 0, duration: 0.5, ease: 'power2.out' }, 0.3);
118
+ });
119
+ return tl;
120
+ };
121
+ const quiet = () => {
122
+ const tl = g.timeline();
123
+ tl.fromTo(glyph, { scale: 1 }, { keyframes: { scale: [1, 0.75, 1] }, duration: 0.35, ease: 'power1.inOut', clearProps: 'transform' }, 0);
124
+ if (kind === 'bookmark' && !pressed) tl.fromTo(solid, { clipPath: 'inset(0% 0% 0% 0%)' }, { clipPath: 'inset(0% 0% 100% 0%)', duration: 0.25, ease: 'power2.in', clearProps: 'clipPath' }, 0);
125
+ return tl;
126
+ };
127
+ const roll = (n, up, animate) => {
128
+ if (!num) return;
129
+ g.killTweensOf(num);
130
+ const t = fmt(n);
131
+ if (!animate || RM()) { num.textContent = t; g.set(num, { clearProps: 'all' }); return; }
132
+ const d = up ? -1 : 1;
133
+ g.timeline()
134
+ .to(num, { yPercent: d * 100, opacity: 0, duration: 0.16, ease: 'power2.in' })
135
+ .add(() => { num.textContent = t; })
136
+ .fromTo(num, { yPercent: -d * 100, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.3, ease: 'back.out(2.2)', clearProps: 'all' });
137
+ };
138
+ const relabel = (animate) => {
139
+ if (!labelEl || !onLabel || onLabel === label) return;
140
+ const t = pressed ? onLabel : label;
141
+ if (labelEl.textContent === t) return;
142
+ labelEl.textContent = t;
143
+ if (animate && !RM()) g.fromTo(labelEl, { y: pressed ? 6 : -6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.28, ease: 'power2.out', clearProps: 'all' });
144
+ };
145
+ const draw = (animate, up, cheer = true) => {
146
+ b.setAttribute('aria-pressed', String(pressed));
147
+ if (count != null) b.dataset.count = String(count);
148
+ if (iconOnly) b.setAttribute('aria-label', count != null ? W.withCount(label, fmt(count)) : label);
149
+ relabel(animate);
150
+ g.killTweensOf([glyph, solid, ring, ...bits].filter(Boolean));
151
+ g.set([glyph, solid, ring, ...bits].filter(Boolean), { clearProps: 'all' });
152
+ if (animate && !RM()) (pressed && cheer ? (kind === 'bookmark' ? fill() : burst()) : quiet());
153
+ if (count != null) roll(count, up, animate);
154
+ };
155
+
156
+ const api = {
157
+ el: b, opts: o,
158
+ get pressed() { return pressed; },
159
+ get count() { return count; },
160
+ /** Turn it on or off (counts ±1 like a click). silent: true skips onChange. */
161
+ set(on, { silent = true, animate = true } = {}) {
162
+ on = !!on;
163
+ if (on === pressed) return api;
164
+ pressed = on;
165
+ if (count != null) count = Math.max(0, count + (on ? 1 : -1));
166
+ draw(animate, on);
167
+ if (!silent) changed();
168
+ return api;
169
+ },
170
+ toggle() { return api.set(!pressed, { silent: false }); },
171
+ /** Set the number (rolls up or down to it). */
172
+ setCount(n, animate = true) {
173
+ if (count == null || !num) return api;
174
+ const next = Math.max(0, Math.round(+n || 0)), up = next > count;
175
+ count = next; b.dataset.count = String(count);
176
+ if (iconOnly) b.setAttribute('aria-label', W.withCount(label, fmt(count)));
177
+ roll(count, up, animate);
178
+ return api;
179
+ },
180
+ destroy() {
181
+ ac.abort();
182
+ g.killTweensOf([glyph, solid, ring, num, labelEl, ...bits].filter(Boolean));
183
+ delete b.__lk;
184
+ if (built) { delete el.__lk; el.innerHTML = ''; }
185
+ },
186
+ };
187
+ const changed = () => {
188
+ const was = pressed, wasCount = count;
189
+ let r;
190
+ try { r = api.opts.onChange?.(pressed, count, api); } catch { r = Promise.reject(); }
191
+ if (r && typeof r.then === 'function') {
192
+ Promise.resolve(r).catch(() => {
193
+ if (!b.isConnected || pressed !== was) return; // already changed again: leave it
194
+ pressed = !was; count = wasCount == null ? null : Math.max(0, wasCount + (was ? -1 : 1));
195
+ draw(true, !was, false); // back without the celebration
196
+ M.shake(b);
197
+ });
198
+ }
199
+ };
200
+ b.addEventListener('click', () => api.toggle(), { signal: ac.signal });
201
+ b.__lk = api;
202
+ if (built) el.__lk = api;
203
+ return api;
204
+ };
205
+
206
+ /** Wires every .lk button inside root (bindAll does this for you). Returns the handles. */
207
+ export const bindLikes = (root = document) =>
208
+ $$(root.matches?.('.lk') ? [root] : $$('.lk', root)).map((b) => b.__lk || likeButton(b));
package/src/pay.js ADDED
@@ -0,0 +1,162 @@
1
+ /* Pay button: the busy-state button (a .btn that locks while it works, then says how it went) made for
2
+ checkout. Press it and the label slides up and away, a thin card-reader slot opens in the middle, a small
3
+ card swipes through it (the slot glows as it passes) and "Processing" slides in with three bouncing dots.
4
+ Your onPay() runs meanwhile. When it resolves, the button turns green, "Paid" springs in with a tick that
5
+ draws itself and the button gives a small happy bounce; after a few seconds it goes back to the start.
6
+ When it fails (throws, rejects or returns false), the button turns red, shakes and offers "Try again".
7
+ A polite live region says "Processing payment…", then "Payment complete" or the failure, and the button
8
+ has aria-busy while it works. It never takes the focus away: while busy it is aria-disabled and ignores
9
+ presses instead of being disabled. Under reduced motion the faces simply swap and nothing slides. */
10
+ import * as M from '@gecko-ui-kit/motion';
11
+ import { icon } from '@gecko-ui-kit/icons';
12
+ import { esc } from '../index.js';
13
+
14
+ const { g, RM, $$ } = M;
15
+ const WORDS = {
16
+ label: 'Pay now', busy: 'Processing', done: 'Paid', retry: 'Try again',
17
+ sayBusy: 'Processing payment…', sayDone: 'Payment complete', sayFail: (error) => 'Payment failed. Try again.',
18
+ };
19
+ const TICK = '<svg class="pay__tick" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m5 12.5 4.5 4.5L19 7.5" pathLength="1" stroke-dasharray="1 2" stroke-dashoffset="1"/></svg>';
20
+
21
+ /**
22
+ * payBtn({ label, variant, size, block, icon, words, cls, attrs }) → HTML string
23
+ * label: 'Pay $49.00' (default words.label). variant: 'dark' (default) | 'primary'. size: 'lg' (default) | '' | 'sm'.
24
+ * block: fill the row. icon: an icon name before the label ('card' by default, '' = none).
25
+ */
26
+ export const payBtn = (opts = {}) => {
27
+ const W = { ...WORDS, ...opts.words };
28
+ const variant = opts.variant ?? 'dark', size = opts.size ?? 'lg', ic = opts.icon ?? 'card';
29
+ return `<button type="button" class="btn${variant ? ` btn--${esc(variant)}` : ''}${size ? ` btn--${esc(size)}` : ''}${opts.block ? ' btn--block' : ''} pay${opts.cls ? ` ${esc(opts.cls)}` : ''}"${opts.attrs ? ' ' + opts.attrs : ''}>`
30
+ + `<span class="pay__face pay__idle">${ic ? icon(ic) : ''}<span class="pay__label">${esc(opts.label || W.label)}</span></span>`
31
+ + `<span class="pay__face pay__busy" aria-hidden="true"><span>${esc(W.busy)}</span><span class="pay__dots"><i></i><i></i><i></i></span></span>`
32
+ + `<span class="pay__face pay__done" aria-hidden="true">${TICK}<span>${esc(W.done)}</span></span>`
33
+ + `<span class="pay__face pay__fail" aria-hidden="true">${icon('alert')}<span>${esc(W.retry)}</span></span>`
34
+ + '<span class="pay__slot" aria-hidden="true"><i></i></span><span class="pay__card" aria-hidden="true"></span>'
35
+ + '</button>';
36
+ };
37
+
38
+ /**
39
+ * const pay = payButton(el, {
40
+ * onPay: async (pay) => { … }, // resolve = paid; throw / reject / return false = failed
41
+ * label: 'Pay $49.00', variant: 'dark', size: 'lg', block: false, icon: 'card', // when it builds the button
42
+ * card: true, // the card swiping through the slot
43
+ * minBusy: 1.4, // seconds "Processing" shows at least, so the swipe is seen
44
+ * back: 3, // seconds before it returns to the start after paying (0 = stays "Paid")
45
+ * words: { label, busy, done, retry, sayBusy, sayDone, sayFail(error) },
46
+ * onDone(result, pay), onFail(error, pay),
47
+ * })
48
+ * pay.state ('idle' | 'busy' | 'done' | 'failed') · pay.pay() · pay.reset() · pay.setLabel(text) · pay.destroy()
49
+ *
50
+ * el is a .pay button from payBtn() or an empty element to build one in.
51
+ */
52
+ export const payButton = (el, opts = {}) => {
53
+ el = $$(el)[0];
54
+ if (!el) return null;
55
+ if (el.__pay) { Object.assign(el.__pay.opts, opts); return el.__pay; }
56
+ let b = el, built = false;
57
+ if (!el.matches('.pay')) { el.innerHTML = payBtn(opts); b = el.firstElementChild; built = true; }
58
+ const o = { onPay: null, card: true, minBusy: 1.4, back: 3, onDone: null, onFail: null, ...opts };
59
+ const W = { ...WORDS, ...o.words };
60
+ const $ = (s) => b.querySelector(s);
61
+ const faces = { idle: $('.pay__idle'), busy: $('.pay__busy'), done: $('.pay__done'), failed: $('.pay__fail') };
62
+ const slot = $('.pay__slot'), glow = $('.pay__slot i'), card = $('.pay__card'), tick = $('.pay__tick path'), label = $('.pay__label');
63
+ const sr = document.createElement('span');
64
+ sr.className = 'pay__sr'; sr.setAttribute('role', 'status');
65
+ b.after(sr);
66
+ const say = (t) => { sr.textContent = ''; requestAnimationFrame(() => { sr.textContent = t; }); };
67
+ const ac = new AbortController();
68
+ let state = 'idle', shown = faces.idle, tl = null, backCall = null, run = 0;
69
+
70
+ /** Slide the face that shows now up and away, and the next one in from below. */
71
+ const swapTo = (next, t, at = 0, inAt = '>-0.02') => {
72
+ const from = shown; shown = next;
73
+ if (from === next) return;
74
+ g.set(Object.values(faces).filter((f) => f !== from && f !== next), { autoAlpha: 0, yPercent: 0 });
75
+ if (RM()) { g.set(from, { autoAlpha: 0, yPercent: 0 }); g.set(next, { autoAlpha: 1, yPercent: 0 }); return; }
76
+ t.to(from, { yPercent: -70, autoAlpha: 0, duration: 0.22, ease: 'power2.in' }, at)
77
+ .fromTo(next, { yPercent: 70, autoAlpha: 0 }, { yPercent: 0, autoAlpha: 1, duration: 0.38, ease: 'back.out(2)' }, inAt);
78
+ };
79
+ const fresh = () => { tl?.kill(); tl = g.timeline(); return tl; };
80
+ const setBusy = (on) => {
81
+ if (on) { b.setAttribute('aria-busy', 'true'); b.setAttribute('aria-disabled', 'true'); }
82
+ else b.removeAttribute('aria-busy');
83
+ };
84
+
85
+ const api = {
86
+ el: b, opts: o,
87
+ get state() { return state; },
88
+ /** Start paying, as if pressed. Resolves with true (paid) or false (failed). */
89
+ async pay() {
90
+ if (state === 'busy' || state === 'done') return false;
91
+ const me = ++run;
92
+ backCall?.kill();
93
+ state = 'busy'; setBusy(true);
94
+ b.classList.remove('is-done', 'is-failed'); b.classList.add('is-busy'); b.classList.toggle('is-still', RM());
95
+ say(W.sayBusy);
96
+ const w = b.offsetWidth, t = fresh();
97
+ if (!RM() && api.opts.card) {
98
+ t.fromTo(slot, { scaleY: 0, autoAlpha: 1 }, { scaleY: 1, duration: 0.2, ease: 'power2.out' }, 0.12)
99
+ .fromTo(card, { x: -w / 2 - 30, rotation: -10, autoAlpha: 1 }, { x: w / 2 + 30, rotation: 5, duration: 0.8, ease: 'power2.inOut' }, 0.22)
100
+ .fromTo(glow, { opacity: 0 }, { keyframes: { opacity: [0, 1, 1, 0] }, duration: 0.5, ease: 'none' }, 0.42)
101
+ .to(slot, { scaleY: 0, duration: 0.2, ease: 'power2.in' }, 0.98)
102
+ .set([slot, card], { autoAlpha: 0 });
103
+ swapTo(faces.busy, t, 0, 0.95); // the label leaves first; "Processing" comes after the swipe
104
+ } else swapTo(faces.busy, t, 0);
105
+ const wait = new Promise((r) => setTimeout(r, (+api.opts.minBusy || 0) * 1000));
106
+ const intro = t.duration() ? new Promise((r) => t.eventCallback('onComplete', r)) : null; // GSAP time: also right when the page's speed is changed
107
+ const [res] = await Promise.allSettled([Promise.resolve().then(() => api.opts.onPay?.(api)), wait, intro]);
108
+ if (me !== run || !b.isConnected) return false;
109
+ const ok = res.status === 'fulfilled' && res.value !== false;
110
+ return ok ? finish(res.value) : fail(res.status === 'rejected' ? res.reason : null);
111
+ },
112
+ /** Back to the start (the label you set). */
113
+ reset() {
114
+ run++; backCall?.kill();
115
+ if (state === 'idle') return api;
116
+ state = 'idle'; setBusy(false); b.removeAttribute('aria-disabled');
117
+ b.classList.remove('is-busy', 'is-done', 'is-failed');
118
+ const t = fresh(); swapTo(faces.idle, t, 0);
119
+ t.add(() => tick?.setAttribute('stroke-dashoffset', '1'));
120
+ return api;
121
+ },
122
+ /** Change the label (for example a new total). */
123
+ setLabel(text) { if (label) label.textContent = text; return api; },
124
+ destroy() {
125
+ run++; ac.abort(); tl?.kill(); backCall?.kill();
126
+ g.killTweensOf([b, slot, glow, card, tick, ...Object.values(faces)].filter(Boolean));
127
+ sr.remove(); delete b.__pay;
128
+ if (built) { delete el.__pay; el.innerHTML = ''; }
129
+ },
130
+ };
131
+
132
+ const finish = (result) => {
133
+ state = 'done'; setBusy(false);
134
+ b.classList.remove('is-busy'); b.classList.add('is-done');
135
+ say(W.sayDone);
136
+ const t = fresh();
137
+ swapTo(faces.done, t, 0);
138
+ if (RM()) tick?.setAttribute('stroke-dashoffset', '0');
139
+ else {
140
+ t.fromTo(tick, { attr: { 'stroke-dashoffset': 1 } }, { attr: { 'stroke-dashoffset': 0 }, duration: 0.4, ease: 'power2.out' }, 0.3)
141
+ .fromTo(b, { scale: 1 }, { keyframes: { scale: [1, 1.05, 1] }, duration: 0.45, ease: 'power2.out', clearProps: 'transform' }, 0.2);
142
+ }
143
+ api.opts.onDone?.(result, api);
144
+ if (+api.opts.back > 0) backCall = g.delayedCall(+api.opts.back, () => api.reset());
145
+ return true;
146
+ };
147
+ const fail = (error) => {
148
+ state = 'failed'; setBusy(false); b.removeAttribute('aria-disabled');
149
+ b.classList.remove('is-busy'); b.classList.add('is-failed');
150
+ say(typeof W.sayFail === 'function' ? W.sayFail(error) : W.sayFail);
151
+ const t = fresh();
152
+ swapTo(faces.failed, t, 0);
153
+ if (!RM()) t.add(() => M.shake(b), 0.15);
154
+ api.opts.onFail?.(error, api);
155
+ return false;
156
+ };
157
+
158
+ b.addEventListener('click', () => { if (state !== 'busy' && state !== 'done') api.pay(); }, { signal: ac.signal });
159
+ b.__pay = api;
160
+ if (built) el.__pay = api;
161
+ return api;
162
+ };