@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,128 @@
1
+ /* Speed dial: a round floating action button (+) that fans out a few labelled actions. Pressing it turns the
2
+ + a little more than a quarter turn into an ×, and the actions spring out one after another, the nearest
3
+ first, each icon with its label chip sliding in a beat later. Closing folds them back the other way,
4
+ farthest first, quicker. Escape, a click outside, or tabbing away closes it; picking an action closes it
5
+ and gives the focus back to the button. Opened from the keyboard, the focus moves to the nearest action;
6
+ the arrow keys walk along the actions and back to the button. The button has aria-expanded and
7
+ aria-controls; the closed list is hidden, so nobody tabs into actions they cannot see. */
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 WORDS = { label: 'Create new', actions: 'Actions' };
14
+ let uid = 0;
15
+ const ico = (v) => (!v ? '' : String(v).trim().startsWith('<') ? v : icon(v));
16
+
17
+ /**
18
+ * const dial = speedDial(el, {
19
+ * actions: [{ id: 'photo', label: 'Photo', icon: 'image' }, …], // icon: an icon name or an <svg> string
20
+ * direction: 'up' | 'down', // where the actions fan out (down for a button near the top)
21
+ * side: 'right' | 'left', // which edge the button sits on; labels point inwards
22
+ * labels: true, // false = icons only (the label still names each button)
23
+ * fixed: false, // true = pinned to the corner of the screen (--sd-x / --sd-y set the gap)
24
+ * icon: 'plus', // the main button's icon (it turns into an ×)
25
+ * words: { label, actions }, // label names the main button; actions names the list
26
+ * onSelect(action, dial), onToggle(open, dial),
27
+ * })
28
+ * dial.isOpen · dial.open({ focus }) · dial.close({ focus }) · dial.toggle() · dial.setActions(list) · dial.destroy()
29
+ */
30
+ export const speedDial = (el, opts = {}) => {
31
+ el = $$(el)[0];
32
+ if (!el) return null;
33
+ el.__sdial?.destroy();
34
+ const o = { actions: [], direction: 'up', side: 'right', labels: true, fixed: false, icon: 'plus', onSelect: null, onToggle: null, ...opts };
35
+ const W = { ...WORDS, ...o.words };
36
+ const id = `sdial-${++uid}`, down = o.direction === 'down', left = o.side === 'left';
37
+ el.innerHTML = `<div class="sdial${down ? ' sdial--down' : ''}${left ? ' sdial--left' : ''}${o.fixed ? ' sdial--fixed' : ''}${o.labels ? '' : ' sdial--bare'}">`
38
+ + `<button type="button" class="sdial__fab" aria-expanded="false" aria-controls="${id}" aria-label="${esc(W.label)}"><span class="sdial__plus">${ico(o.icon)}</span></button>`
39
+ + `<ul class="sdial__list" id="${id}" aria-label="${esc(W.actions)}" hidden></ul></div>`;
40
+ const root = el.firstElementChild, fab = root.querySelector('.sdial__fab'), plus = root.querySelector('.sdial__plus'), list = root.querySelector('.sdial__list');
41
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
42
+ let actions = [], items = [], open = false, tl = null;
43
+
44
+ const render = (list0) => {
45
+ actions = (list0 || []).map((a, i) => ({ id: a.id ?? String(i), ...a }));
46
+ list.innerHTML = actions.map((a, i) => `<li><button type="button" class="sdial__act" data-i="${i}"${o.labels ? '' : ` aria-label="${esc(a.label)}"`}>`
47
+ + `${o.labels ? `<span class="sdial__label">${esc(a.label)}</span>` : ''}<span class="sdial__ic" aria-hidden="true">${ico(a.icon)}</span></button></li>`).join('');
48
+ items = [...list.querySelectorAll('.sdial__act')];
49
+ };
50
+ render(o.actions);
51
+
52
+ const parts = (b) => [b.querySelector('.sdial__ic'), b.querySelector('.sdial__label')].filter(Boolean);
53
+ const show = () => {
54
+ tl?.kill();
55
+ list.hidden = false; root.classList.add('is-open');
56
+ if (RM()) { g.set(plus, { rotation: 135 }); g.set(items.flatMap(parts), { clearProps: 'all' }); return; }
57
+ const dy = down ? -16 : 16, sx = left ? -10 : 10;
58
+ tl = g.timeline();
59
+ tl.to(plus, { rotation: 135, duration: 0.45, ease: 'back.out(2.2)' }, 0);
60
+ items.forEach((b, i) => {
61
+ const [ic, lab] = parts(b);
62
+ tl.fromTo(ic, { y: dy, scale: 0.4, opacity: 0 }, { y: 0, scale: 1, opacity: 1, duration: 0.4, ease: 'back.out(2)' }, 0.03 + i * 0.055);
63
+ if (lab) tl.fromTo(lab, { x: sx, opacity: 0 }, { x: 0, opacity: 1, duration: 0.3, ease: 'power3.out' }, 0.1 + i * 0.055);
64
+ });
65
+ };
66
+ const hide = () => {
67
+ tl?.kill();
68
+ root.classList.remove('is-open');
69
+ if (RM()) { g.set(plus, { rotation: 0 }); list.hidden = true; return; }
70
+ const dy = down ? -10 : 10;
71
+ tl = g.timeline({ onComplete: () => { list.hidden = true; g.set(items.flatMap(parts), { clearProps: 'all' }); } });
72
+ tl.to(plus, { rotation: 0, duration: 0.35, ease: 'power3.out' }, 0);
73
+ [...items].reverse().forEach((b, i) => tl.to(parts(b), { y: dy, scale: 0.6, opacity: 0, duration: 0.18, ease: 'power2.in' }, i * 0.03));
74
+ };
75
+
76
+ const api = {
77
+ el: root,
78
+ get isOpen() { return open; },
79
+ get actions() { return actions; },
80
+ /** Fan the actions out. focus: true moves the focus to the nearest action. */
81
+ open({ focus = false } = {}) {
82
+ if (!open) { open = true; fab.setAttribute('aria-expanded', 'true'); show(); o.onToggle?.(true, api); }
83
+ if (focus) items[0]?.focus();
84
+ return api;
85
+ },
86
+ /** Fold them away. focus: true gives the focus back to the main button. */
87
+ close({ focus = false } = {}) {
88
+ if (open) { open = false; fab.setAttribute('aria-expanded', 'false'); hide(); o.onToggle?.(false, api); }
89
+ if (focus) fab.focus();
90
+ return api;
91
+ },
92
+ toggle() { return open ? api.close() : api.open(); },
93
+ /** New actions (closes first). */
94
+ setActions(list0) { api.close(); tl?.progress(1); render(list0); return api; },
95
+ destroy() {
96
+ ac.abort(); tl?.kill(); g.killTweensOf([plus, ...items.flatMap(parts)]);
97
+ delete el.__sdial; el.innerHTML = '';
98
+ },
99
+ };
100
+
101
+ on(fab, 'click', (e) => (open ? api.close() : api.open({ focus: e.detail === 0 }))); // detail 0 = Enter / Space
102
+ on(list, 'click', (e) => {
103
+ const b = e.target.closest('.sdial__act'); if (!b) return;
104
+ const a = actions[+b.dataset.i];
105
+ api.close({ focus: true });
106
+ a?.onClick?.(a, api);
107
+ o.onSelect?.(a, api);
108
+ });
109
+ on(root, 'keydown', (e) => {
110
+ if (e.key === 'Escape' && open) { e.preventDefault(); e.stopPropagation(); api.close({ focus: true }); return; }
111
+ if (!open || !['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) return;
112
+ const ring = [fab, ...items], i = ring.indexOf(document.activeElement);
113
+ if (i < 0) return;
114
+ e.preventDefault();
115
+ const away = down ? 'ArrowDown' : 'ArrowUp', back = down ? 'ArrowUp' : 'ArrowDown';
116
+ let n = i;
117
+ if (e.key === away) n = Math.min(ring.length - 1, i + 1);
118
+ else if (e.key === back) n = Math.max(0, i - 1);
119
+ else if (e.key === 'Home') n = 1;
120
+ else if (e.key === 'End') n = ring.length - 1;
121
+ ring[n]?.focus();
122
+ });
123
+ on(root, 'focusout', (e) => { if (open && e.relatedTarget && !root.contains(e.relatedTarget)) api.close(); });
124
+ on(document, 'pointerdown', (e) => { if (open && !root.contains(e.target)) api.close(); });
125
+
126
+ el.__sdial = api;
127
+ return api;
128
+ };
package/src/spinner.js ADDED
@@ -0,0 +1,38 @@
1
+ /* Spinner (orbit loader): a comet sweeps round a faint ring. Its tail fades from nothing to the
2
+ full tone colour and a small glowing head leads it, so it reads as one object circling rather
3
+ than a ring that rotates. Tail and head turn together in one CSS rotation (it keeps going while
4
+ the page is busy with scripts, and needs no JavaScript once it is on the page). Size it with
5
+ font-size: the ring is 1em across. With reduced motion (the OS setting, or reduceMotion(true)
6
+ before you build it) the comet stops turning and the ring breathes slowly instead. */
7
+ import * as M from '@gecko-ui-kit/motion';
8
+ import { esc } from '../index.js';
9
+
10
+ const { RM } = M;
11
+ const WORDS = { loading: 'Loading…' };
12
+ const TONES = ['accent', 'ink', 'muted', 'good', 'warn', 'bad', 'current'];
13
+ const len = (v) => (typeof v === 'number' ? `${v}px` : String(v).replace(/[^\w.%()+\-*/ ]/g, ''));
14
+
15
+ /**
16
+ * spinner({
17
+ * size: 28, // px, or any CSS length ('1.2em' to match the text around it)
18
+ * tone: 'accent' | 'ink' | 'muted' | 'good' | 'warn' | 'bad' | 'current', // current = the text colour
19
+ * speed: 1, // seconds per lap
20
+ * track: true, // the faint full ring behind the comet
21
+ * label: '', // text shown next to it ('' = a hidden "Loading…" for screen readers only)
22
+ * stack: false, // the label under the ring instead of beside it
23
+ * words: { loading: 'Loading…' },
24
+ * decorative: false, // true: hidden from screen readers (no role, no text), e.g. inside a button whose text already says "Saving…"
25
+ * cls: '', // extra classes
26
+ * }) → HTML string: <span class="orb" role="status">…</span>
27
+ * Remove the element (or replace it with the content) when loading is done.
28
+ */
29
+ export const spinner = (opts = {}) => {
30
+ const o = { size: '', tone: 'accent', speed: 1, track: true, label: '', stack: false, words: null, decorative: false, cls: '', ...opts };
31
+ const W = { ...WORDS, ...o.words };
32
+ const tone = TONES.includes(o.tone) ? o.tone : 'accent';
33
+ const style = [o.size !== '' && o.size !== null && o.size !== undefined ? `font-size:${len(o.size)}` : '', +o.speed && +o.speed !== 1 ? `--orb-speed:${+o.speed}s` : ''].filter(Boolean).join(';');
34
+ const cls = ['orb', `orb--${tone}`, o.track === false ? 'orb--bare' : '', o.stack && o.label ? 'orb--stack' : '', RM() ? 'orb--still' : '', o.cls].filter(Boolean).join(' ');
35
+ const text = o.label ? `<span class="orb__label">${esc(o.label)}</span>` : o.decorative ? '' : `<span class="orb__sr">${esc(W.loading)}</span>`;
36
+ const role = o.decorative ? ' aria-hidden="true"' : ' role="status"';
37
+ return `<span class="${esc(cls)}"${role}${style ? ` style="${style}"` : ''}><span class="orb__dial" aria-hidden="true"><span class="orb__spin"></span></span>${text}</span>`;
38
+ };
package/src/stepper.js ADDED
@@ -0,0 +1,211 @@
1
+ /* Number stepper: − and + round a number whose digits roll like an odometer — up when it goes up,
2
+ down when it goes down, and only the digits that change. Hold a button and it keeps counting,
3
+ faster and faster. At the limit the number gives a small elastic nudge instead of moving.
4
+ Click (or start typing on) the number to type a value straight in. */
5
+ import * as M from '@gecko-ui-kit/motion';
6
+ import { icon } from '@gecko-ui-kit/icons';
7
+ import { esc } from '../index.js';
8
+
9
+ const { g, RM, $$ } = M;
10
+ const WORDS = { label: 'Amount', less: 'Decrease', more: 'Increase', min: (n) => `The least is ${n}`, max: (n) => `The most is ${n}` };
11
+ const STRIP = Array.from({ length: 20 }, (_, i) => `<i>${i % 10}</i>`).join('');
12
+
13
+ /**
14
+ * const st = stepper(el, {
15
+ * value: 1, min: 0, max: 99, step: 1, // step 0.5 shows one decimal, 0.25 two
16
+ * unit: 'days' | (n) => (n === 1 ? 'day' : 'days'), // after the number
17
+ * prefix: '฿', // before the number
18
+ * format: (n) => string, // default: grouped digits for the locale (1,250)
19
+ * locale: undefined,
20
+ * size: '' | 'sm' | 'lg',
21
+ * name: 'days', // a hidden input, so a plain <form> sends the value
22
+ * disabled: false,
23
+ * words: { label, less, more, min, max },
24
+ * onChange(value, st)
25
+ * })
26
+ * st.value · st.set(n) · st.stepBy(±1) · st.setRange({ min, max }) · st.destroy()
27
+ */
28
+ export const stepper = (el, opts = {}) => {
29
+ el = $$(el)[0];
30
+ if (!el) return null;
31
+ const o = { value: 0, min: -Infinity, max: Infinity, step: 1, unit: '', prefix: '', format: null, locale: undefined, size: '', name: '', disabled: false, onChange: null, ...opts };
32
+ const W = { ...WORDS, ...o.words };
33
+ const dec = () => (String(o.step).split('.')[1] || '').length;
34
+ const nf = () => new Intl.NumberFormat(o.locale, { minimumFractionDigits: dec(), maximumFractionDigits: dec() });
35
+ const fmt = (n) => (o.format ? String(o.format(n)) : nf().format(n));
36
+ const unitOf = (n) => (typeof o.unit === 'function' ? o.unit(n) : o.unit) || '';
37
+ const snap = (n) => { const base = Number.isFinite(o.min) ? o.min : 0; const s = +o.step || 1; return +(base + Math.round((n - base) / s) * s).toFixed(dec()); };
38
+ const clamp = (n) => Math.min(o.max, Math.max(o.min, n));
39
+
40
+ el.innerHTML = `<div class="st${o.size ? ` st--${esc(o.size)}` : ''}${o.disabled ? ' is-disabled' : ''}">`
41
+ + `<button type="button" class="st__btn" data-d="-1" aria-label="${esc(W.less)}"${o.disabled ? ' disabled' : ''}>${icon('minus')}</button>`
42
+ + `<div class="st__val" role="spinbutton" tabindex="${o.disabled ? -1 : 0}" aria-label="${esc(W.label)}"${o.disabled ? ' aria-disabled="true"' : ''}>`
43
+ + `<span class="st__face" aria-hidden="true">${o.prefix ? `<span class="st__pre">${esc(o.prefix)}</span>` : ''}<span class="st__odo"></span><span class="st__unit"></span></span>`
44
+ + `<input class="st__input" type="text" inputmode="${dec() ? 'decimal' : 'numeric'}" tabindex="-1" aria-hidden="true" autocomplete="off"></div>`
45
+ + `<button type="button" class="st__btn" data-d="1" aria-label="${esc(W.more)}"${o.disabled ? ' disabled' : ''}>${icon('plus')}</button>`
46
+ + `${o.name ? `<input type="hidden" name="${esc(o.name)}">` : ''}<span class="st__sr" role="status"></span></div>`;
47
+ const root = el.firstElementChild, val = root.querySelector('.st__val'), odo = root.querySelector('.st__odo'), unitEl = root.querySelector('.st__unit');
48
+ const input = root.querySelector('.st__input'), [less, more] = root.querySelectorAll('.st__btn');
49
+ const say = (t) => { root.querySelector('.st__sr').textContent = t; };
50
+
51
+ let value = clamp(snap(+o.value || 0)), shown = '';
52
+
53
+ /* ---------- the odometer ---------- */
54
+ const isDigit = (c) => c >= '0' && c <= '9';
55
+ const cell = (c) => {
56
+ const s = document.createElement('span');
57
+ if (isDigit(c)) { s.className = 'st__d'; s.innerHTML = `<span class="st__strip">${STRIP}</span>`; g.set(s.firstChild, { yPercent: -(+c) * 5 }); }
58
+ else { s.className = 'st__c'; s.textContent = c; }
59
+ s.dataset.c = c;
60
+ return s;
61
+ };
62
+ /** Roll one digit strip to c, the short way round in the direction the number moved. */
63
+ const roll = (span, c, dir, delay) => {
64
+ const strip = span.firstChild, n = +c;
65
+ let p = -g.getProperty(strip, 'yPercent') / 5; // where it shows now (0…20)
66
+ p = ((p % 10) + 10) % 10; g.killTweensOf(strip); g.set(strip, { yPercent: -p * 5 });
67
+ span.dataset.c = c;
68
+ if (RM()) { g.set(strip, { yPercent: -n * 5 }); return; }
69
+ let to = n;
70
+ if (dir > 0) { if (n < p - 0.001) to = n + 10; }
71
+ else if (n > p + 0.001) { g.set(strip, { yPercent: -(p + 10) * 5 }); }
72
+ g.to(strip, { yPercent: -to * 5, duration: 0.45, delay, ease: 'power3.out', onComplete: () => g.set(strip, { yPercent: -n * 5 }) });
73
+ };
74
+ const draw = (text, dir, animate) => {
75
+ const leaving = [...odo.children].filter((x) => x.classList.contains('is-gone')); // still on their way out
76
+ const old = [...odo.children].filter((x) => !x.classList.contains('is-gone'));
77
+ const chars = [...text], seq = [], fresh = [], gone = [];
78
+ const w0 = odo.offsetWidth;
79
+ // line the two up from the right, so units stay units and tens stay tens
80
+ for (let k = 1; k <= Math.max(old.length, chars.length); k++) {
81
+ const span = old[old.length - k], c = chars[chars.length - k];
82
+ if (span && c != null && isDigit(c) && span.classList.contains('st__d')) {
83
+ if (span.dataset.c !== c) roll(span, c, dir, animate ? (k - 1) * 0.03 : 0);
84
+ seq.unshift(span);
85
+ } else if (span && c != null && span.dataset.c === c) seq.unshift(span);
86
+ else {
87
+ if (c != null) { const n = cell(c); fresh.push(n); seq.unshift(n); }
88
+ if (span) { span.classList.add('is-gone'); gone.push(span); seq.unshift(span); }
89
+ }
90
+ }
91
+ odo.replaceChildren(...leaving, ...seq);
92
+ if (!animate || RM()) { gone.forEach((x) => x.remove()); return; }
93
+ gone.forEach((x) => g.to(x, { yPercent: dir > 0 ? 70 : -70, opacity: 0, width: 0, duration: 0.3, ease: 'power2.in', onComplete: () => x.remove() }));
94
+ fresh.forEach((x) => { const w = x.offsetWidth; g.fromTo(x, { yPercent: dir > 0 ? -70 : 70, opacity: 0, width: 0 }, { yPercent: 0, opacity: 1, width: w, duration: 0.38, ease: 'power3.out', clearProps: 'width,opacity,transform' }); });
95
+ const w1 = odo.offsetWidth;
96
+ if (Math.abs(w1 - w0) > 1 && !fresh.length && !gone.length) g.fromTo(odo, { width: w0 }, { width: w1, duration: 0.3, ease: 'power3.out', clearProps: 'width' });
97
+ };
98
+
99
+ const paint = (dir = 1, animate = true) => {
100
+ const text = fmt(value);
101
+ if (text !== shown) { draw(text, dir, animate && !!shown); shown = text; }
102
+ const u = unitOf(value);
103
+ if (unitEl.textContent !== u) {
104
+ unitEl.textContent = u; unitEl.hidden = !u;
105
+ if (animate && !RM() && u) g.fromTo(unitEl, { y: dir > 0 ? -6 : 6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.3, ease: 'power2.out', clearProps: 'transform,opacity' });
106
+ }
107
+ const full = `${o.prefix || ''}${text}${u ? ` ${u}` : ''}`;
108
+ val.setAttribute('aria-valuenow', String(value)); val.setAttribute('aria-valuetext', full);
109
+ if (Number.isFinite(o.min)) val.setAttribute('aria-valuemin', String(o.min)); else val.removeAttribute('aria-valuemin');
110
+ if (Number.isFinite(o.max)) val.setAttribute('aria-valuemax', String(o.max)); else val.removeAttribute('aria-valuemax');
111
+ less.classList.toggle('is-end', value <= o.min); more.classList.toggle('is-end', value >= o.max);
112
+ less.setAttribute('aria-disabled', String(value <= o.min || o.disabled)); more.setAttribute('aria-disabled', String(value >= o.max || o.disabled));
113
+ const h = root.querySelector('input[type="hidden"]'); if (h) h.value = String(value);
114
+ };
115
+
116
+ /** Pushing past the limit: the number leans that way and springs back. */
117
+ const bump = (dir) => {
118
+ say(dir > 0 ? W.max(fmt(o.max)) : W.min(fmt(o.min)));
119
+ if (RM()) return;
120
+ const face = root.querySelector('.st__face');
121
+ g.fromTo(face, { y: 0 }, { keyframes: { y: [0, -dir * 5, 0] }, duration: 0.42, ease: 'power2.out', overwrite: true, clearProps: 'transform' });
122
+ const b = dir > 0 ? more : less;
123
+ g.fromTo(b, { x: 0 }, { keyframes: { x: [0, dir * 3, -dir * 2, 0] }, duration: 0.3, ease: 'power2.out', clearProps: 'transform' });
124
+ };
125
+
126
+ const set = (n, { silent = false, animate = true } = {}) => {
127
+ if (!Number.isFinite(n)) return false;
128
+ const next = clamp(snap(n));
129
+ if (next === value) return false;
130
+ const dir = next > value ? 1 : -1;
131
+ value = next; paint(dir, animate);
132
+ if (!silent) o.onChange?.(value, api);
133
+ return true;
134
+ };
135
+ const stepBy = (dir) => {
136
+ if (o.disabled) return false;
137
+ const moved = set(value + dir * (+o.step || 1));
138
+ if (!moved) bump(dir);
139
+ return moved;
140
+ };
141
+
142
+ /* ---------- typing a value in ---------- */
143
+ const edit = (seed) => {
144
+ if (o.disabled || root.classList.contains('is-editing')) return;
145
+ root.classList.add('is-editing');
146
+ input.value = seed ?? String(value); input.tabIndex = 0;
147
+ input.focus(); if (seed == null) input.select(); else input.setSelectionRange(input.value.length, input.value.length);
148
+ };
149
+ const endEdit = (keep) => {
150
+ if (!root.classList.contains('is-editing')) return;
151
+ root.classList.remove('is-editing'); input.tabIndex = -1;
152
+ if (keep) {
153
+ const raw = input.value.replace(/[^\d.,-]/g, '').replace(/,(?=\d{3}\b)/g, '').replace(',', '.');
154
+ const n = parseFloat(raw);
155
+ if (Number.isFinite(n)) { const want = snap(n); if (!set(n) && want !== value) bump(want > value ? 1 : -1); }
156
+ }
157
+ val.focus({ preventScroll: true });
158
+ };
159
+
160
+ /* ---------- events ---------- */
161
+ const ac = new AbortController(), on = { signal: ac.signal };
162
+ let timer = null, pressed = false;
163
+ const stopRepeat = () => { clearTimeout(timer); timer = null; };
164
+ [less, more].forEach((b) => {
165
+ const dir = +b.dataset.d;
166
+ b.addEventListener('pointerdown', (e) => {
167
+ if (e.button > 0 || o.disabled) return;
168
+ e.preventDefault(); pressed = true; // keep the focus where it is
169
+ stepBy(dir);
170
+ let gap = 380; // hold: wait, then repeat faster and faster
171
+ const again = () => { if (!stepBy(dir)) { stopRepeat(); return; } gap = Math.max(40, gap * 0.82); timer = setTimeout(again, gap); };
172
+ timer = setTimeout(again, 420);
173
+ try { b.setPointerCapture(e.pointerId); } catch { /* fine */ }
174
+ }, on);
175
+ ['pointerup', 'pointercancel', 'lostpointercapture'].forEach((t) => b.addEventListener(t, stopRepeat, on));
176
+ b.addEventListener('click', () => { if (pressed) { pressed = false; return; } stepBy(dir); }, on); // keyboard Enter/Space
177
+ });
178
+ val.addEventListener('keydown', (e) => {
179
+ if (e.target === input || root.classList.contains('is-editing')) return; // keys typed into the box are the box's
180
+ const big = (+o.step || 1) * 10;
181
+ const map = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 };
182
+ if (map[e.key]) { e.preventDefault(); stepBy(map[e.key]); }
183
+ else if (e.key === 'PageUp' || e.key === 'PageDown') { e.preventDefault(); const d = e.key === 'PageUp' ? 1 : -1; if (!set(value + d * big)) bump(d); }
184
+ else if (e.key === 'Home' && Number.isFinite(o.min)) { e.preventDefault(); if (!set(o.min)) bump(-1); }
185
+ else if (e.key === 'End' && Number.isFinite(o.max)) { e.preventDefault(); if (!set(o.max)) bump(1); }
186
+ else if (e.key === 'Enter') { e.preventDefault(); edit(); }
187
+ else if (/^[\d.,-]$/.test(e.key) && !e.ctrlKey && !e.metaKey) { e.preventDefault(); edit(e.key); }
188
+ }, on);
189
+ val.addEventListener('click', (e) => { if (e.target !== input) edit(); }, on);
190
+ input.addEventListener('keydown', (e) => {
191
+ if (e.key === 'Enter') { e.preventDefault(); endEdit(true); }
192
+ else if (e.key === 'Escape') { e.preventDefault(); endEdit(false); }
193
+ else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { e.preventDefault(); endEdit(true); stepBy(e.key === 'ArrowUp' ? 1 : -1); }
194
+ }, on);
195
+ input.addEventListener('blur', () => endEdit(true), on);
196
+ ac.signal.addEventListener('abort', stopRepeat);
197
+
198
+ const api = {
199
+ el: root, opts: o,
200
+ get value() { return value; },
201
+ /** Go to a number (clamped and snapped to the step). */
202
+ set(n, { silent = false } = {}) { set(+n, { silent }); return api; },
203
+ /** One step up (1) or down (-1); returns false at the limit (after the nudge). */
204
+ stepBy,
205
+ /** Change the limits; the value is pulled inside them if needed. */
206
+ setRange({ min = o.min, max = o.max } = {}) { o.min = min; o.max = max; if (!set(value)) paint(1, false); return api; },
207
+ destroy() { ac.abort(); g.killTweensOf(root.querySelectorAll('*')); el.innerHTML = ''; },
208
+ };
209
+ paint(1, false);
210
+ return api;
211
+ };
@@ -0,0 +1,173 @@
1
+ /* Email subscribe: one email field and a button, for a newsletter or a waitlist. The label sits
2
+ inside the field and floats up when you type; a small tick draws itself at the end of the field
3
+ once the address looks complete. Sending an address that is empty or wrong turns the field red,
4
+ says why under it and gives a small shake; leaving the field with a half-typed address says so
5
+ too. A good address makes the button busy (a spinner) while your onSubmit runs, and when it
6
+ succeeds the button grows across the whole row and turns into the thank-you message, with a
7
+ tick drawn in a circle. If onSubmit fails, its message shows under the field and the button
8
+ comes back. Everything that changes is read out by a polite live region. Nothing is sent
9
+ anywhere by this file: call your mailing list in onSubmit. With reduced motion the message
10
+ simply appears and nothing shakes. */
11
+ import * as M from '@gecko-ui-kit/motion';
12
+ import { icon } from '@gecko-ui-kit/icons';
13
+ import { esc } from '../index.js';
14
+ import { spinner } from './spinner.js';
15
+
16
+ const { g, RM, $$ } = M;
17
+ const WORDS = {
18
+ label: 'Email address', button: 'Subscribe', hint: 'One email a month. No spam.',
19
+ missing: 'Enter your email first.', bad: 'That email looks incomplete.',
20
+ busy: 'Subscribing…', done: 'You’re subscribed!', doneText: 'Check your inbox to confirm.',
21
+ failed: 'Something went wrong. Please try again.',
22
+ };
23
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; // the same check as authForm
24
+ let uid = 0;
25
+
26
+ /**
27
+ * const sub = subscribeForm(el, {
28
+ * value: '', // fill the field in to start with
29
+ * name: 'email', // the input's name
30
+ * icon: '', // an icon inside the field on the left, e.g. 'mail'
31
+ * layout: 'row' | 'stack', // button beside the field (wraps under it when narrow) or always under it
32
+ * validate: (email) => '', // your own extra check: return a message to refuse the address
33
+ * resetAfter: 0, // ms after success before the empty form comes back (0 = stay thanked)
34
+ * words: { label, button, hint, missing, bad, busy, done, doneText, failed },
35
+ * onSubmit: async (email, sub) => {}, // resolve (a string replaces doneText); reject or throw to show the error
36
+ * })
37
+ * sub.value · sub.state ('idle' | 'bad' | 'busy' | 'done') · sub.setError('…') · sub.reset() · sub.destroy()
38
+ */
39
+ export const subscribeForm = (el, opts = {}) => {
40
+ el = $$(el)[0];
41
+ if (!el) return null;
42
+ const o = { value: '', name: 'email', icon: '', layout: 'row', validate: null, resetAfter: 0, words: null, onSubmit: null, ...opts };
43
+ const W = { ...WORDS, ...o.words };
44
+ const id = `sub${++uid}`;
45
+ const ac = new AbortController(), on = (t, ev, fn) => t.addEventListener(ev, fn, { signal: ac.signal });
46
+
47
+ el.innerHTML = `<form class="subscribe subscribe--${o.layout === 'stack' ? 'stack' : 'row'}${o.icon ? ' subscribe--icon' : ''}" novalidate>`
48
+ + '<div class="subscribe__stage"><div class="subscribe__row">'
49
+ + `<div class="subscribe__box">${o.icon ? `<span class="subscribe__ic" aria-hidden="true">${icon(o.icon)}</span>` : ''}`
50
+ + `<input class="input subscribe__input" id="${id}-in" type="email" name="${esc(o.name)}" value="${esc(o.value)}" placeholder=" " autocomplete="email" inputmode="email" autocapitalize="off" spellcheck="false" aria-describedby="${id}-hint">`
51
+ + `<label class="subscribe__label" for="${id}-in">${esc(W.label)}</label>`
52
+ + '<svg class="subscribe__ok" viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10.5 3.2 3.2L15 6.5"/></svg></div>'
53
+ + `<button type="submit" class="btn btn--primary subscribe__go"><span class="subscribe__go-text">${esc(W.button)}</span>`
54
+ + `<span class="subscribe__spin">${spinner({ size: 18, tone: 'current', decorative: true })}</span></button></div>`
55
+ + '<div class="subscribe__done" tabindex="-1" hidden><svg class="subscribe__tick" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="m7.5 12.4 3 3 6-6.4"/></svg>'
56
+ + `<span class="subscribe__done-text">${esc(W.done)}</span></div></div>`
57
+ + `<p class="subscribe__hint" id="${id}-hint">${esc(W.hint)}</p>`
58
+ + '<p class="subscribe__sr" role="status" aria-live="polite"></p></form>';
59
+
60
+ const form = el.firstElementChild, q = (s) => form.querySelector(s);
61
+ const input = q('.subscribe__input'), go = q('.subscribe__go'), row = q('.subscribe__row'), box = q('.subscribe__box');
62
+ const done = q('.subscribe__done'), doneText = q('.subscribe__done-text'), hint = q('.subscribe__hint'), sr = q('.subscribe__sr');
63
+ let state = 'idle', timer = 0;
64
+
65
+ const say = (t) => { sr.textContent = ''; if (t) requestAnimationFrame(() => { sr.textContent = t; }); };
66
+ const setHint = (t, tone = '') => {
67
+ const same = hint.textContent === t;
68
+ hint.textContent = t; hint.className = `subscribe__hint${tone ? ` is-${tone}` : ''}`;
69
+ if (!same && !RM() && tone) g.fromTo(hint, { opacity: 0, y: -4 }, { opacity: 1, y: 0, duration: 0.3, ease: 'power2.out', clearProps: 'opacity,transform' });
70
+ };
71
+ const problem = (v) => (!v ? W.missing : !EMAIL.test(v) ? W.bad : o.validate?.(v) || '');
72
+ const looksOk = () => { const ok = EMAIL.test(input.value.trim()); form.classList.toggle('is-valid', ok); return ok; };
73
+ const setState = (s) => { state = s; form.dataset.state = s; };
74
+ const showError = (text, { loud = true, announce = false } = {}) => {
75
+ setState('bad'); form.classList.add('is-bad');
76
+ input.setAttribute('aria-invalid', 'true');
77
+ setHint(text, 'bad');
78
+ if (announce) say(text);
79
+ if (loud) M.shake(box);
80
+ };
81
+ const clearError = () => {
82
+ if (state !== 'bad') return;
83
+ setState('idle'); form.classList.remove('is-bad');
84
+ input.removeAttribute('aria-invalid');
85
+ setHint(W.hint);
86
+ };
87
+ const setBusy = (v) => {
88
+ form.classList.toggle('is-busy', v); form.classList.toggle('subscribe--still', RM());
89
+ v ? form.setAttribute('aria-busy', 'true') : form.removeAttribute('aria-busy');
90
+ v ? go.setAttribute('aria-disabled', 'true') : go.removeAttribute('aria-disabled');
91
+ input.readOnly = v;
92
+ };
93
+
94
+ /* The button grows over the field and becomes the message: a panel laid over the row starts
95
+ clipped to the button's own box and colour, then opens to the full row and fades to green. */
96
+ const morph = (text) => {
97
+ doneText.textContent = text || W.done;
98
+ const r = row.getBoundingClientRect(), b = go.getBoundingClientRect();
99
+ const radius = getComputedStyle(go).borderTopLeftRadius;
100
+ done.hidden = false;
101
+ row.inert = true;
102
+ done.focus({ preventScroll: true });
103
+ if (RM()) { row.style.visibility = 'hidden'; return; }
104
+ const ins = (t, rt, bt, l) => `inset(${t}px ${rt}px ${bt}px ${l}px round ${radius})`;
105
+ const from = ins(b.top - r.top, r.right - b.right, r.bottom - b.bottom, b.left - r.left);
106
+ const bg = getComputedStyle(go).backgroundColor;
107
+ g.timeline({ onComplete: () => { row.style.visibility = 'hidden'; g.set(row, { clearProps: 'opacity' }); } })
108
+ .to(row, { opacity: 0, duration: 0.3, ease: 'power1.in' }, 0.12)
109
+ .fromTo(done, { clipPath: from, backgroundColor: bg }, { clipPath: ins(0, 0, 0, 0), duration: 0.55, ease: 'power3.inOut', clearProps: 'clipPath' }, 0)
110
+ .to(done, { backgroundColor: getComputedStyle(done).backgroundColor, duration: 0.45, ease: 'power1.out', clearProps: 'backgroundColor' }, 0.2)
111
+ .fromTo(done.children, { opacity: 0, y: 8 }, { opacity: 1, y: 0, duration: 0.45, stagger: 0.06, ease: 'back.out(1.8)', clearProps: 'opacity,transform' }, 0.3)
112
+ .fromTo(done.querySelector('circle'), { strokeDashoffset: 63 }, { strokeDashoffset: 0, duration: 0.5, ease: 'power2.out', clearProps: 'strokeDashoffset' }, 0.35)
113
+ .fromTo(done.querySelector('path'), { strokeDashoffset: 14 }, { strokeDashoffset: 0, duration: 0.35, ease: 'power2.out', clearProps: 'strokeDashoffset' }, 0.7);
114
+ };
115
+ const succeed = (text) => {
116
+ setState('done'); form.classList.add('is-done');
117
+ morph(typeof text === 'string' && text ? text : W.done);
118
+ setHint(W.doneText, 'good');
119
+ say(`${typeof text === 'string' && text ? text : W.done} ${W.doneText}`);
120
+ if (o.resetAfter > 0) timer = setTimeout(() => api.reset(), o.resetAfter);
121
+ };
122
+
123
+ on(input, 'input', () => { looksOk(); if (state === 'bad' && !problem(input.value.trim())) clearError(); });
124
+ on(input, 'blur', () => {
125
+ const v = input.value.trim();
126
+ if (state === 'idle' && v && !EMAIL.test(v)) showError(W.bad, { loud: false, announce: true });
127
+ });
128
+ on(form, 'submit', async (e) => {
129
+ e.preventDefault();
130
+ if (state === 'busy' || state === 'done') return;
131
+ const v = input.value.trim(), bad = problem(v);
132
+ if (bad) { showError(bad); input.focus(); return; }
133
+ clearError();
134
+ if (!o.onSubmit) { succeed(); return; }
135
+ setState('busy'); setBusy(true); say(W.busy);
136
+ try {
137
+ const r = await o.onSubmit(v, api);
138
+ if (ac.signal.aborted) return;
139
+ setBusy(false);
140
+ if (r === false) throw new Error('');
141
+ succeed(r);
142
+ } catch (err) {
143
+ if (ac.signal.aborted) return;
144
+ setBusy(false); setState('idle');
145
+ showError((typeof err === 'string' ? err : err?.message) || W.failed, { announce: true });
146
+ }
147
+ });
148
+
149
+ const api = {
150
+ root: form,
151
+ get value() { return input.value.trim(); },
152
+ get state() { return state; },
153
+ /** Show a message of your own under the field (red); '' clears it. */
154
+ setError(text) { if (state === 'busy' || state === 'done') return; text ? showError(text, { announce: true }) : clearError(); },
155
+ /** Back to an empty field (also after success). */
156
+ reset() {
157
+ clearTimeout(timer);
158
+ if (state === 'busy') return;
159
+ const wasDone = state === 'done', refocus = wasDone && done.contains(document.activeElement);
160
+ g.killTweensOf([done, ...done.querySelectorAll('*'), row]);
161
+ setState('idle'); form.classList.remove('is-done', 'is-bad', 'is-valid');
162
+ input.removeAttribute('aria-invalid'); input.value = '';
163
+ setHint(W.hint); say('');
164
+ done.hidden = true; row.inert = false; row.style.visibility = ''; g.set(row, { clearProps: 'opacity,transform' });
165
+ if (wasDone && !RM()) g.fromTo(row, { opacity: 0, y: 6 }, { opacity: 1, y: 0, duration: 0.4, ease: 'power3.out', clearProps: 'opacity,transform' });
166
+ if (refocus) input.focus({ preventScroll: true });
167
+ },
168
+ destroy() { clearTimeout(timer); ac.abort(); g.killTweensOf([form, ...form.querySelectorAll('*')]); el.innerHTML = ''; },
169
+ };
170
+ setState('idle');
171
+ looksOk();
172
+ return api;
173
+ };