@gecko-ui-kit/components 0.0.0-stage → 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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +904 -2
  3. package/index.js +225 -0
  4. package/package.json +42 -4
  5. package/src/accordion.js +208 -0
  6. package/src/activity.js +218 -0
  7. package/src/alert.js +205 -0
  8. package/src/authform.js +285 -0
  9. package/src/beforeafter.js +141 -0
  10. package/src/bell.js +137 -0
  11. package/src/breadcrumbs.js +204 -0
  12. package/src/calendar.js +523 -0
  13. package/src/carousel.js +266 -0
  14. package/src/combobox.js +421 -0
  15. package/src/daterange.js +311 -0
  16. package/src/donut.js +346 -0
  17. package/src/filedrop.js +378 -0
  18. package/src/gauge.js +169 -0
  19. package/src/grid.js +298 -0
  20. package/src/heatmap.js +332 -0
  21. package/src/kanban.js +319 -0
  22. package/src/leaderboard.js +201 -0
  23. package/src/like.js +208 -0
  24. package/src/linechart.js +550 -0
  25. package/src/multiselect.js +324 -0
  26. package/src/notifications.js +393 -0
  27. package/src/otp.js +112 -0
  28. package/src/pagination.js +242 -0
  29. package/src/password.js +245 -0
  30. package/src/pay.js +162 -0
  31. package/src/pricing.js +189 -0
  32. package/src/radiocards.js +101 -0
  33. package/src/rangeslider.js +266 -0
  34. package/src/rating.js +171 -0
  35. package/src/signature.js +213 -0
  36. package/src/skeleton.js +254 -0
  37. package/src/speeddial.js +128 -0
  38. package/src/spinner.js +38 -0
  39. package/src/stepper.js +211 -0
  40. package/src/subscribe.js +173 -0
  41. package/src/swipe.js +280 -0
  42. package/src/tagsinput.js +369 -0
  43. package/src/timeline.js +340 -0
  44. package/src/timepicker.js +290 -0
  45. package/src/tree.js +490 -0
  46. package/src/typing.js +93 -0
  47. package/src/upload.js +416 -0
  48. package/src/virtuallist.js +373 -0
  49. package/src/wizard.js +392 -0
  50. package/style.css +2092 -0
@@ -0,0 +1,242 @@
1
+ /* Pagination: page numbers (or “Page 3 of 24”) with previous / next arrows, an optional
2
+ “21–30 of 240” line and a page-size list.
3
+ How it moves: the highlight on the current page stretches from number to number (the same
4
+ motion as the sidebar pill). When the window of numbers shifts (the “…” moves), the numbers
5
+ that stay glide to their new place, new ones slide in from the side you are heading to and the
6
+ ones that leave slide out the other way. The info line and “Page 3 of 24” roll up or down.
7
+ At narrow widths it turns compact on its own (fewer numbers, smaller buttons). */
8
+ import * as M from '@gecko-ui-kit/motion';
9
+ import { icon } from '@gecko-ui-kit/icons';
10
+ import { esc } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const fmt = (n) => Number(n).toLocaleString('en-US');
14
+ const WORDS = {
15
+ label: 'Pagination', prev: 'Previous page', next: 'Next page', perPage: 'Per page', none: 'No results',
16
+ page: (n) => `Page ${n}`,
17
+ pageOf: (n, pages) => `Page ${n} of ${pages}`,
18
+ info: (from, to, total) => `${from}–${to} of ${total}`,
19
+ num: fmt,
20
+ };
21
+
22
+ /** The numbers to show: page numbers and 'gap-l' / 'gap-r' for the “…”. Always the same count once
23
+ there are enough pages, so the bar keeps its width while you move through it. */
24
+ export const pageWindow = (pages, page, siblings = 1, boundaries = 1) => {
25
+ const s = Math.max(0, siblings | 0), b = Math.max(0, boundaries | 0);
26
+ const range = (a, z) => (z < a ? [] : Array.from({ length: z - a + 1 }, (_, i) => a + i));
27
+ if (pages <= 2 * b + 2 * s + 3) return range(1, pages);
28
+ const lo = Math.max(Math.min(page - s, pages - b - 2 * s - 1), b + 2);
29
+ const hi = Math.min(Math.max(page + s, b + 2 * s + 2), pages - b - 1);
30
+ return [
31
+ ...range(1, b),
32
+ ...(lo > b + 2 ? ['gap-l'] : [b + 1]),
33
+ ...range(lo, hi),
34
+ ...(hi < pages - b - 1 ? ['gap-r'] : [pages - b]),
35
+ ...range(pages - b + 1, pages),
36
+ ];
37
+ };
38
+
39
+ /**
40
+ * const p = pagination(el, {
41
+ * total: 240, // number of items
42
+ * pageSize: 10, page: 1,
43
+ * siblings: 1, // numbers either side of the current one
44
+ * boundaries: 1, // numbers always shown at each end
45
+ * sizes: [10, 20, 50], // a page-size list (a plain <select class="input">); null for none
46
+ * info: true, // “21–30 of 240”
47
+ * look: 'numbers' | 'simple', // simple: arrows + “Page 3 of 24”
48
+ * compact: 'auto', // true | false | 'auto' (below compactAt px wide: no siblings, smaller buttons)
49
+ * compactAt: 480,
50
+ * words: { label, prev, next, perPage, none, page(n), pageOf(n, pages), info(from, to, total), num(n) },
51
+ * onChange(page, pageSize, p),
52
+ * })
53
+ * p.page · p.pageSize · p.pages · p.total · p.go(n) · p.next() · p.prev() · p.setTotal(n) · p.destroy()
54
+ */
55
+ export const pagination = (el, opts = {}) => {
56
+ el = $$(el)[0];
57
+ if (!el) return null;
58
+ const o = { total: 0, pageSize: 10, page: 1, siblings: 1, boundaries: 1, sizes: [10, 20, 50], info: true, look: 'numbers', compact: 'auto', compactAt: 480, words: null, onChange: null, ...opts };
59
+ const W = { ...WORDS, ...o.words };
60
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
61
+ const numbers = o.look !== 'simple';
62
+ const sizes = Array.isArray(o.sizes) && o.sizes.length ? [...new Set([...o.sizes, +o.pageSize].map(Number).filter((n) => n > 0))].sort((a, b) => a - b) : null;
63
+ let total = Math.max(0, +o.total || 0), size = Math.max(1, +o.pageSize || 10), page = 1, compact = false;
64
+ const count = () => Math.max(1, Math.ceil(total / size));
65
+ page = Math.min(count(), Math.max(1, Math.round(+o.page || 1)));
66
+
67
+ el.innerHTML = `<nav class="pgn pgn--${numbers ? 'numbers' : 'simple'}${!o.info && !sizes ? ' pgn--bare' : ''}" aria-label="${esc(W.label)}">`
68
+ + `${o.info ? '<p class="pgn__info"><span class="pgn__roll"></span></p>' : ''}`
69
+ + `${sizes ? `<div class="pgn__size"><span class="pgn__size-lb" aria-hidden="true">${esc(W.perPage)}</span><span class="pgn__sel"><select class="input input--sm" aria-label="${esc(W.perPage)}">${sizes.map((n) => `<option value="${n}"${n === size ? ' selected' : ''}>${esc(W.num(n))}</option>`).join('')}</select></span></div>` : ''}`
70
+ + '<div class="pgn__bar">'
71
+ + `<button type="button" class="pgn__arrow pgn__prev" aria-label="${esc(W.prev)}">${icon('chevL')}</button>`
72
+ + (numbers ? '<div class="pgn__nums"><span class="pgn__pill" aria-hidden="true"></span><ul class="pgn__list"></ul><span class="pgn__ghosts" aria-hidden="true"></span></div>'
73
+ : '<span class="pgn__of"><span class="pgn__roll"></span></span>')
74
+ + `<button type="button" class="pgn__arrow pgn__next" aria-label="${esc(W.next)}">${icon('chevR')}</button>`
75
+ + '</div><span class="pgn__sr" role="status"></span></nav>';
76
+ const root = el.firstElementChild;
77
+ const $ = (s) => root.querySelector(s);
78
+ const prevB = $('.pgn__prev'), nextB = $('.pgn__next'), nums = $('.pgn__nums'), list = $('.pgn__list'), pill = $('.pgn__pill'), ghosts = $('.pgn__ghosts');
79
+ const infoBox = $('.pgn__info .pgn__roll'), ofBox = $('.pgn__of .pgn__roll'), sel = $('.pgn__size select'), sr = $('.pgn__sr');
80
+ const say = (t) => { sr.textContent = t; };
81
+
82
+ /* ---------- text that rolls up (forward) or down (back) ---------- */
83
+ const roll = (box, text, dir, animate) => {
84
+ if (!box) return;
85
+ const old = box.querySelector(':scope > span:not(.is-out)');
86
+ if (old && old.textContent === text) return;
87
+ const nu = document.createElement('span'); nu.textContent = text;
88
+ if (!animate || RM() || !old || !dir) { g.killTweensOf(box.children); box.replaceChildren(nu); return; }
89
+ old.classList.add('is-out'); old.setAttribute('aria-hidden', 'true');
90
+ box.append(nu);
91
+ g.to(old, { yPercent: -80 * dir, opacity: 0, duration: 0.2, ease: 'power2.in', onComplete: () => old.remove() });
92
+ g.fromTo(nu, { yPercent: 80 * dir, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.42, delay: 0.05, ease: 'power3.out', clearProps: 'transform,opacity' });
93
+ };
94
+
95
+ /* ---------- the numbers ---------- */
96
+ const lis = new Map(); // key ('p4', 'gap-l', 'gap-r') → <li>
97
+ const keyOf = (x) => (typeof x === 'number' ? `p${x}` : x);
98
+ const makeLi = (x) => {
99
+ const li = document.createElement('li');
100
+ if (typeof x === 'number') {
101
+ li.className = 'pgn__item';
102
+ li.innerHTML = `<button type="button" class="pgn__num" data-p="${x}" aria-label="${esc(W.page(x))}">${esc(W.num(x))}</button>`;
103
+ } else { li.className = 'pgn__item pgn__gap'; li.setAttribute('aria-hidden', 'true'); li.textContent = '…'; }
104
+ return li;
105
+ };
106
+ const curBtn = () => list?.querySelector('[aria-current="page"]') ?? null;
107
+ const place = (animate) => { if (pill) M.indicator(pill, curBtn(), { animate, radius: 10 }); };
108
+
109
+ const renderNums = (animate, dir) => {
110
+ const want = pageWindow(count(), page, compact ? 0 : o.siblings, o.boundaries);
111
+ const keys = want.map(keyOf);
112
+ const anim = animate && !RM() && lis.size > 0;
113
+ const hadFocus = list.contains(document.activeElement);
114
+ const box = list.getBoundingClientRect();
115
+ const before = new Map();
116
+ if (anim) lis.forEach((li, k) => before.set(k, li.getBoundingClientRect().left));
117
+ // the ones leaving: lift them out of the row and let them slide away
118
+ lis.forEach((li, k) => {
119
+ if (keys.includes(k)) return;
120
+ const r = li.getBoundingClientRect(); // where it is on screen now, mid-glide included
121
+ lis.delete(k); g.killTweensOf(li);
122
+ if (!anim) { li.remove(); return; }
123
+ g.set(li, { x: 0, opacity: 1 });
124
+ li.classList.add('is-out'); li.querySelector('button')?.setAttribute('tabindex', '-1');
125
+ li.style.left = `${r.left - box.left + list.offsetLeft}px`; li.style.top = `${r.top - box.top + list.offsetTop}px`;
126
+ ghosts.append(li);
127
+ g.to(li, { x: -dir * 16, opacity: 0, duration: 0.24, ease: 'power2.in', onComplete: () => li.remove() });
128
+ });
129
+ // put the row in order; the ones that stay keep their relative order, so only new ones are inserted
130
+ const fresh = [];
131
+ keys.forEach((k, i) => {
132
+ let li = lis.get(k);
133
+ if (!li) { li = makeLi(want[i]); lis.set(k, li); fresh.push(li); }
134
+ if (list.children[i] !== li) list.insertBefore(li, list.children[i] ?? null);
135
+ });
136
+ lis.forEach((li) => {
137
+ const b = li.querySelector('button'); if (!b) return;
138
+ if (+b.dataset.p === page) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current');
139
+ });
140
+ if (anim) {
141
+ lis.forEach((li, k) => {
142
+ if (!before.has(k)) return;
143
+ g.killTweensOf(li); g.set(li, { x: 0 });
144
+ const dx = before.get(k) - li.getBoundingClientRect().left;
145
+ if (Math.abs(dx) > 0.5) g.fromTo(li, { x: dx }, { x: 0, duration: 0.46, ease: 'power3.out', clearProps: 'transform' });
146
+ });
147
+ if (fresh.length) g.fromTo(fresh, { x: dir * 16, opacity: 0 }, { x: 0, opacity: 1, duration: 0.42, delay: 0.06, stagger: { each: 0.03, from: dir < 0 ? 'end' : 'start' }, ease: 'power3.out', clearProps: 'transform,opacity' });
148
+ }
149
+ if (hadFocus && !list.contains(document.activeElement)) curBtn()?.focus({ preventScroll: true });
150
+ place(animate);
151
+ };
152
+
153
+ /* ---------- paint everything for the current page ---------- */
154
+ const paint = (animate, dir) => {
155
+ const pages = count();
156
+ prevB.setAttribute('aria-disabled', String(page <= 1));
157
+ nextB.setAttribute('aria-disabled', String(page >= pages));
158
+ if (numbers) renderNums(animate, dir);
159
+ else roll(ofBox, W.pageOf(W.num(page), W.num(pages)), dir, animate);
160
+ if (infoBox) {
161
+ const from = total ? (page - 1) * size + 1 : 0, to = Math.min(page * size, total);
162
+ roll(infoBox, total ? W.info(W.num(from), W.num(to), W.num(total)) : W.none, dir, animate);
163
+ }
164
+ };
165
+
166
+ const change = (n, { tell = true, focus = false } = {}) => {
167
+ const pages = count(), was = page;
168
+ n = Math.min(pages, Math.max(1, Math.round(+n) || 1));
169
+ if (n === was) return false;
170
+ page = n;
171
+ paint(true, Math.sign(n - was));
172
+ if (focus) curBtn()?.focus({ preventScroll: true });
173
+ say(W.pageOf(W.num(page), W.num(pages)));
174
+ if (tell) o.onChange?.(page, size, api);
175
+ return true;
176
+ };
177
+
178
+ /* ---------- events ---------- */
179
+ on(root, 'click', (e) => {
180
+ const b = e.target.closest('button'); if (!b || !root.contains(b)) return;
181
+ if (b === prevB || b === nextB) {
182
+ if (b.getAttribute('aria-disabled') === 'true') return;
183
+ change(page + (b === nextB ? 1 : -1));
184
+ if (!RM()) g.fromTo(b.querySelector('svg'), { x: b === nextB ? 3 : -3 }, { x: 0, duration: 0.4, ease: 'back.out(3)', clearProps: 'transform' });
185
+ } else if (b.classList.contains('pgn__num')) change(+b.dataset.p);
186
+ });
187
+ on(root, 'keydown', (e) => {
188
+ if (!e.target.closest?.('.pgn__num, .pgn__arrow') || e.altKey || e.ctrlKey || e.metaKey) return;
189
+ if (e.key === 'Home') { e.preventDefault(); change(1, { focus: numbers }); }
190
+ else if (e.key === 'End') { e.preventDefault(); change(count(), { focus: numbers }); }
191
+ });
192
+ if (sel) on(sel, 'change', () => {
193
+ const n = Math.max(1, +sel.value || size);
194
+ if (n === size) return;
195
+ const first = (page - 1) * size, was = page;
196
+ size = n; page = Math.min(count(), Math.floor(first / size) + 1);
197
+ paint(true, Math.sign(page - was) || 1);
198
+ say(W.pageOf(W.num(page), W.num(count())));
199
+ o.onChange?.(page, size, api);
200
+ });
201
+
202
+ /* compact at narrow widths; keep the highlight glued to its number when the layout moves */
203
+ let raf = 0;
204
+ const fit = () => {
205
+ const c = o.compact === 'auto' ? el.clientWidth > 0 && el.clientWidth < o.compactAt : !!o.compact;
206
+ if (c !== compact) { compact = c; root.classList.toggle('is-compact', c); if (numbers) renderNums(false, 0); }
207
+ else place(false);
208
+ };
209
+ const ro = new ResizeObserver(() => { cancelAnimationFrame(raf); raf = requestAnimationFrame(fit); });
210
+ ro.observe(el);
211
+ if (numbers) ro.observe(list);
212
+
213
+ compact = o.compact === 'auto' ? el.clientWidth > 0 && el.clientWidth < o.compactAt : !!o.compact;
214
+ root.classList.toggle('is-compact', compact);
215
+ paint(false, 0);
216
+ document.fonts?.ready.then(() => { if (!ac.signal.aborted) place(false); });
217
+
218
+ const api = {
219
+ root,
220
+ get page() { return page; },
221
+ get pageSize() { return size; },
222
+ get pages() { return count(); },
223
+ get total() { return total; },
224
+ go: (n) => change(n),
225
+ next: () => change(page + 1),
226
+ prev: () => change(page - 1),
227
+ setTotal(n) {
228
+ total = Math.max(0, +n || 0);
229
+ const was = page;
230
+ page = Math.min(count(), page);
231
+ paint(true, page < was ? -1 : 0);
232
+ if (page !== was) { say(W.pageOf(W.num(page), W.num(count()))); o.onChange?.(page, size, api); }
233
+ return count();
234
+ },
235
+ destroy() {
236
+ ac.abort(); ro.disconnect(); cancelAnimationFrame(raf);
237
+ g.killTweensOf(root.querySelectorAll('*')); if (pill) g.killTweensOf(pill.__st ?? {});
238
+ el.innerHTML = '';
239
+ },
240
+ };
241
+ return api;
242
+ };
@@ -0,0 +1,245 @@
1
+ /* Password strength: attach it to a password field and it shows how strong the password is while
2
+ it is typed. Four bars fill one after another and change colour together (red → amber → green),
3
+ the word beside them rolls to the new level, and each rule in the checklist ticks itself off:
4
+ its circle fills and the tick is drawn with a pen stroke. When the password is strong, a small
5
+ padlock swings its shackle down and clicks shut. Screen readers hear the new level (politely,
6
+ only when it changes) and the rules are linked to the field as its description.
7
+ passwordToggle() is the show / hide eye on its own: the slash is drawn across the eye while the
8
+ letters are visible. passwordMeter(…, { reveal: true }) adds it for you. */
9
+ import * as M from '@gecko-ui-kit/motion';
10
+ import { esc } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const WORDS = {
14
+ empty: 'Type a password', tooWeak: 'Too weak', weak: 'Weak', okay: 'Okay', strong: 'Strong',
15
+ strength: (level) => `Password strength: ${level}`,
16
+ needs: 'Your password needs:',
17
+ length: (n) => `${n} or more characters`, case: 'Upper and lower case letters', number: 'At least one number', symbol: 'At least one symbol, like ! or #',
18
+ met: 'done', unmet: 'not yet',
19
+ show: 'Show password', hide: 'Hide password',
20
+ };
21
+ const LEVELS = ['tooWeak', 'weak', 'okay', 'strong'];
22
+ const EYE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
23
+ + '<path d="M2.5 12C4.7 8.1 8 6.2 12 6.2s7.3 1.9 9.5 5.8c-2.2 3.9-5.5 5.8-9.5 5.8S4.7 15.9 2.5 12z"/><circle cx="12" cy="12" r="2.9"/>'
24
+ + '<path class="pwm__cut" pathLength="1" d="M4.6 4.2l15.2 15.6"/><path class="pwm__slash" pathLength="1" d="M4.6 4.2l15.2 15.6"/></svg>';
25
+ const LOCK = '<svg class="pwm__lock" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
26
+ + '<path class="pwm__shackle" d="M8.2 11V8.1a3.8 3.8 0 0 1 7.6 0V11"/><rect x="5" y="11" width="14" height="10" rx="2.6"/><circle cx="12" cy="16" r="1.35" fill="currentColor" stroke="none"/></svg>';
27
+ const TICK = '<svg class="pwm__tick" viewBox="0 0 20 20" aria-hidden="true"><circle class="pwm__ring" cx="10" cy="10" r="8.2"/><path class="pwm__mark" pathLength="1" d="M6.3 10.3l2.6 2.6 4.9-5.3"/></svg>';
28
+ let uid = 0;
29
+
30
+ const txt = (w, ...a) => (typeof w === 'function' ? w(...a) : w);
31
+ /** Add or remove ids in an aria-describedby list. */
32
+ const describe = (el, ids, add) => {
33
+ const now = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean).filter((x) => !ids.includes(x));
34
+ const next = add ? [...now, ...ids] : now;
35
+ next.length ? el.setAttribute('aria-describedby', next.join(' ')) : el.removeAttribute('aria-describedby');
36
+ };
37
+ /** The four rules used when none are given. */
38
+ const defaultRules = (min, W) => [
39
+ { id: 'length', test: (v) => [...v].length >= min, label: txt(W.length, min) },
40
+ { id: 'case', test: (v) => /\p{Ll}/u.test(v) && /\p{Lu}/u.test(v), label: W.case },
41
+ { id: 'number', test: (v) => /\p{Nd}/u.test(v), label: W.number },
42
+ { id: 'symbol', test: (v) => /[^\p{L}\p{M}\p{N}\s]/u.test(v), label: W.symbol },
43
+ ];
44
+ /** Default score 0–4: the share of rules passed, but never more than 1 while the first rule (length) fails. */
45
+ const defaultScore = (v, met) => {
46
+ const s = Math.round((met.filter(Boolean).length / (met.length || 1)) * 4);
47
+ return met[0] === false ? Math.min(s, 1) : s;
48
+ };
49
+
50
+ /**
51
+ * const eye = passwordToggle(input, { words: { show, hide }, onToggle(shown) })
52
+ * Wraps the input and puts a show / hide button inside its right edge.
53
+ * eye.shown · eye.show(true | false) · eye.button · eye.destroy()
54
+ */
55
+ export const passwordToggle = (input, opts = {}) => {
56
+ input = $$(input)[0];
57
+ if (!input) return null;
58
+ const W = { show: WORDS.show, hide: WORDS.hide, ...opts.words };
59
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
60
+ const type0 = input.type, madeId = !input.id;
61
+ if (madeId) input.id = `pwm${++uid}-input`;
62
+ const wrap = document.createElement('span');
63
+ wrap.className = 'pwm__wrap';
64
+ input.before(wrap); wrap.append(input);
65
+ const button = document.createElement('button');
66
+ button.type = 'button'; button.className = 'pwm__eye';
67
+ button.setAttribute('aria-controls', input.id);
68
+ button.innerHTML = EYE;
69
+ wrap.append(button);
70
+ const lines = button.querySelectorAll('.pwm__cut, .pwm__slash');
71
+ let shown = false;
72
+ const show = (v, animate = true) => {
73
+ shown = !!v;
74
+ input.type = shown ? 'text' : 'password';
75
+ button.setAttribute('aria-label', shown ? W.hide : W.show);
76
+ button.classList.toggle('is-on', shown);
77
+ g.killTweensOf(lines);
78
+ if (RM() || !animate) g.set(lines, { strokeDashoffset: shown ? 0 : 1 });
79
+ else g.to(lines, { strokeDashoffset: shown ? 0 : 1, duration: shown ? 0.34 : 0.22, ease: shown ? 'power2.out' : 'power2.in' });
80
+ };
81
+ show(false, false);
82
+ on(button, 'mousedown', (e) => e.preventDefault()); // a mouse click keeps the caret in the field
83
+ on(button, 'click', () => { show(!shown); M.pop(button); opts.onToggle?.(shown); });
84
+ return {
85
+ button, wrap,
86
+ get shown() { return shown; },
87
+ show: (v) => show(v),
88
+ destroy() {
89
+ ac.abort(); g.killTweensOf([...lines, button.firstElementChild]);
90
+ input.type = type0;
91
+ if (wrap.isConnected) { wrap.before(input); wrap.remove(); }
92
+ if (madeId) input.removeAttribute('id');
93
+ },
94
+ };
95
+ };
96
+
97
+ /**
98
+ * const pw = passwordMeter(input, {
99
+ * rules: [{ id, test: (value) => true | false, label }], // default: length (min), upper + lower, number, symbol
100
+ * min: 8, // length for the default first rule
101
+ * minScore: 3, // pw.valid needs this score (0–4): 3 = “okay”
102
+ * score: (value, met) => 0–4, // your own scoring; met = [true, false, …] in rule order
103
+ * reveal: false, // a show / hide eye inside the field
104
+ * list: true, // the rules checklist
105
+ * lock: true, // the padlock that clicks shut when strong
106
+ * panel: null, // element to put the meter in (default: right after the field / its <label>)
107
+ * words: { empty, tooWeak, weak, okay, strong, strength(level), needs, length(n), case, number, symbol, met, unmet, show, hide },
108
+ * onChange({ score, level, valid, rules }, pw),
109
+ * })
110
+ * pw.score (0–4) · pw.level ('empty' | 'tooWeak' | 'weak' | 'okay' | 'strong') · pw.valid · pw.rules ({ id: true | false })
111
+ * pw.check() → state (after setting input.value yourself) · pw.reveal(true | false) · pw.destroy()
112
+ */
113
+ export const passwordMeter = (input, opts = {}) => {
114
+ input = $$(input)[0];
115
+ if (!input) return null;
116
+ const o = { rules: null, min: 8, minScore: 3, score: null, reveal: false, list: true, lock: true, panel: null, words: null, onChange: null, ...opts };
117
+ const W = { ...WORDS, ...o.words };
118
+ const rules = (o.rules?.length ? o.rules : defaultRules(o.min, W)).map((r, i) => ({ id: r.id ?? `r${i}`, test: r.test, label: r.label ?? '' }));
119
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
120
+ const id = `pwm${++uid}`;
121
+ const eye = o.reveal ? passwordToggle(input, { words: { show: W.show, hide: W.hide } }) : null;
122
+
123
+ const root = document.createElement('div');
124
+ root.className = `pwm${o.lock ? '' : ' pwm--nolock'}`;
125
+ root.dataset.level = 'empty';
126
+ root.innerHTML = `<div class="pwm__status">${o.lock ? LOCK : ''}`
127
+ + `<span class="pwm__bars" aria-hidden="true">${'<span class="pwm__bar"><i></i></span>'.repeat(4)}</span>`
128
+ + `<span class="pwm__word" id="${id}-word"><span>${esc(W.empty)}</span></span></div>`
129
+ + (o.list && rules.length ? `<p class="pwm__sr" id="${id}-needs">${esc(W.needs)}</p><ul class="pwm__rules" id="${id}-rules">${rules.map((r) => `<li class="pwm__rule" data-id="${esc(r.id)}">${TICK}<span class="pwm__label">${esc(r.label)}</span><span class="pwm__sr">, ${esc(W.unmet)}</span></li>`).join('')}</ul>` : '')
130
+ + '<span class="pwm__sr" role="status" aria-live="polite"></span>';
131
+ const panel = o.panel ? $$(o.panel)[0] : null;
132
+ if (panel) panel.append(root);
133
+ else (input.closest('label') || eye?.wrap || input).after(root);
134
+
135
+ const fills = $$('.pwm__bar > i', root), word = root.querySelector('.pwm__word'), sr = root.querySelector('[role="status"]');
136
+ const lock = root.querySelector('.pwm__lock'), shackle = root.querySelector('.pwm__shackle');
137
+ const items = $$('.pwm__rule', root);
138
+ const descIds = [`${id}-word`, ...(items.length ? [`${id}-needs`, `${id}-rules`] : [])];
139
+ describe(input, descIds, true);
140
+
141
+ const OPEN = { rotation: 24, y: -2.6, transformOrigin: '100% 100%' };
142
+ if (shackle) g.set(shackle, OPEN);
143
+ g.set(fills, { scaleX: 0, transformOrigin: '0% 50%' });
144
+ g.set(root.querySelectorAll('.pwm__mark'), { strokeDashoffset: 1 });
145
+
146
+ let state = { score: 0, level: 'empty', valid: false, rules: {} }, bars = 0, shut = false, said = '', sayT = 0, first = true;
147
+ const label = (level) => (level === 'empty' ? W.empty : W[level]);
148
+
149
+ const rollWord = (text, up) => {
150
+ const old = [...word.children], neu = document.createElement('span');
151
+ neu.textContent = text; word.append(neu);
152
+ g.killTweensOf(old);
153
+ if (RM() || first) { old.forEach((s) => s.remove()); return; }
154
+ g.to(old, { yPercent: up ? -100 : 100, opacity: 0, duration: 0.22, ease: 'power2.in', onComplete: () => old.forEach((s) => s.remove()) });
155
+ g.fromTo(neu, { yPercent: up ? 100 : -100, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.42, ease: 'back.out(1.8)', clearProps: 'transform,opacity' });
156
+ };
157
+ const fillBars = (n) => {
158
+ const before = bars; bars = n;
159
+ fills.forEach((f, i) => {
160
+ const want = i < n ? 1 : 0;
161
+ if (f.__on === want && !first) return;
162
+ f.__on = want;
163
+ g.killTweensOf(f);
164
+ if (RM() || first) { g.set(f, { scaleX: want }); return; }
165
+ const delay = want ? Math.max(0, i - before) * 0.07 : Math.max(0, before - 1 - i) * 0.05;
166
+ g.to(f, { scaleX: want, duration: want ? 0.42 : 0.24, delay, ease: want ? 'power3.out' : 'power2.in' });
167
+ });
168
+ };
169
+ const setLock = (v) => {
170
+ if (!shackle || v === shut) return;
171
+ shut = v; root.classList.toggle('is-shut', v);
172
+ g.killTweensOf([shackle, lock]);
173
+ if (RM() || first) { g.set(shackle, v ? { rotation: 0, y: 0 } : OPEN); return; }
174
+ if (v) {
175
+ g.timeline()
176
+ .to(shackle, { rotation: 0, y: -1.2, duration: 0.24, ease: 'power2.in' })
177
+ .to(shackle, { y: 0, duration: 0.32, ease: 'back.out(4)' }) // the click
178
+ .fromTo(lock, { scale: 1 }, { keyframes: { scale: [1, 1.16, 0.96, 1] }, duration: 0.42, ease: 'power1.out', transformOrigin: '50% 60%', clearProps: 'transform' }, '<');
179
+ } else g.to(shackle, { ...OPEN, duration: 0.3, ease: 'power2.out' });
180
+ };
181
+ const tickRule = (li, met) => {
182
+ if (li.classList.contains('is-met') === met && !first) return;
183
+ li.classList.toggle('is-met', met);
184
+ li.querySelector('.pwm__sr').textContent = `, ${met ? W.met : W.unmet}`;
185
+ const mark = li.querySelector('.pwm__mark'), svg = li.querySelector('.pwm__tick');
186
+ g.killTweensOf([mark, svg]);
187
+ if (RM() || first) { g.set(mark, { strokeDashoffset: met ? 0 : 1 }); return; }
188
+ if (met) {
189
+ g.fromTo(svg, { scale: 0.6 }, { scale: 1, duration: 0.5, ease: 'back.out(3)', transformOrigin: '50% 50%', clearProps: 'transform' });
190
+ g.fromTo(mark, { strokeDashoffset: 1 }, { strokeDashoffset: 0, duration: 0.36, delay: 0.08, ease: 'power2.out' });
191
+ } else g.to(mark, { strokeDashoffset: 1, duration: 0.18, ease: 'power2.in' });
192
+ };
193
+ const announce = (level) => {
194
+ clearTimeout(sayT);
195
+ if (level === 'empty') { said = ''; return; }
196
+ sayT = setTimeout(() => { if (level !== said) { said = level; sr.textContent = txt(W.strength, label(level)); } }, 450);
197
+ };
198
+
199
+ const check = () => {
200
+ const v = input.value, wasFirst = first;
201
+ const met = rules.map((r) => { try { return !!r.test(v); } catch { return false; } });
202
+ let score = v ? (o.score ? +o.score(v, met) : defaultScore(v, met)) : 0;
203
+ score = Math.max(0, Math.min(4, Math.round(score) || 0));
204
+ const level = v ? LEVELS[Math.max(score, 1) - 1] : 'empty';
205
+ const next = { score, level, valid: !!v && score >= o.minScore, rules: Object.fromEntries(rules.map((r, i) => [r.id, met[i]])) };
206
+ const changed = level !== state.level || score !== state.score || met.some((m, i) => m !== state.rules[rules[i].id]);
207
+ root.classList.toggle('pwm--still', RM());
208
+ if (first || level !== state.level) {
209
+ const up = LEVELS.indexOf(level) >= LEVELS.indexOf(state.level);
210
+ root.dataset.level = level;
211
+ rollWord(label(level), up);
212
+ if (!first) announce(level);
213
+ }
214
+ fillBars(v ? Math.max(1, score) : 0);
215
+ items.forEach((li, i) => tickRule(li, met[i]));
216
+ setLock(level === 'strong');
217
+ root.classList.toggle('is-valid', next.valid);
218
+ state = next; first = false;
219
+ if (changed && !wasFirst) o.onChange?.({ ...state }, api);
220
+ return { ...state };
221
+ };
222
+
223
+ on(input, 'input', check);
224
+ on(input, 'change', check);
225
+ if (input.form) on(input.form, 'reset', () => setTimeout(() => { if (!ac.signal.aborted) check(); }));
226
+
227
+ const api = {
228
+ root, input,
229
+ get score() { return state.score; },
230
+ get level() { return state.level; },
231
+ get valid() { return state.valid; },
232
+ get rules() { return { ...state.rules }; },
233
+ check,
234
+ reveal: (v) => eye?.show(v),
235
+ destroy() {
236
+ ac.abort(); clearTimeout(sayT);
237
+ g.killTweensOf([root, ...root.querySelectorAll('*')]);
238
+ describe(input, descIds, false);
239
+ root.remove();
240
+ eye?.destroy();
241
+ },
242
+ };
243
+ check();
244
+ return api;
245
+ };
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
+ };