@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.
- package/LICENSE +21 -0
- package/README.md +904 -2
- package/index.js +225 -0
- package/package.json +42 -4
- package/src/accordion.js +208 -0
- package/src/activity.js +218 -0
- package/src/alert.js +205 -0
- package/src/authform.js +285 -0
- package/src/beforeafter.js +141 -0
- package/src/bell.js +137 -0
- package/src/breadcrumbs.js +204 -0
- package/src/calendar.js +523 -0
- package/src/carousel.js +266 -0
- package/src/combobox.js +421 -0
- package/src/daterange.js +311 -0
- package/src/donut.js +346 -0
- package/src/filedrop.js +378 -0
- package/src/gauge.js +169 -0
- package/src/grid.js +298 -0
- package/src/heatmap.js +332 -0
- package/src/kanban.js +319 -0
- package/src/leaderboard.js +201 -0
- package/src/like.js +208 -0
- package/src/linechart.js +550 -0
- package/src/multiselect.js +324 -0
- package/src/notifications.js +393 -0
- package/src/otp.js +112 -0
- package/src/pagination.js +242 -0
- package/src/password.js +245 -0
- package/src/pay.js +162 -0
- package/src/pricing.js +189 -0
- package/src/radiocards.js +101 -0
- package/src/rangeslider.js +266 -0
- package/src/rating.js +171 -0
- package/src/signature.js +213 -0
- package/src/skeleton.js +254 -0
- package/src/speeddial.js +128 -0
- package/src/spinner.js +38 -0
- package/src/stepper.js +211 -0
- package/src/subscribe.js +173 -0
- package/src/swipe.js +280 -0
- package/src/tagsinput.js +369 -0
- package/src/timeline.js +340 -0
- package/src/timepicker.js +290 -0
- package/src/tree.js +490 -0
- package/src/typing.js +93 -0
- package/src/upload.js +416 -0
- package/src/virtuallist.js +373 -0
- package/src/wizard.js +392 -0
- package/style.css +2092 -0
package/src/pricing.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/* Pricing toggle: a set of plan cards with a billing-period switch above them (monthly / yearly,
|
|
2
|
+
or any periods you like). Picking another period slides the switch’s stretchy thumb across and
|
|
3
|
+
every price rolls to its new number digit by digit, like a meter (odometer from
|
|
4
|
+
@gecko-ui-kit/motion; or counts to it with count, if you prefer). The cards follow one after the
|
|
5
|
+
other, the line under each price swaps with a small slide, the old price can show crossed out
|
|
6
|
+
beside the new one, and a “Save 20%” badge on a period gives a little pop when you pick it.
|
|
7
|
+
Plans, periods, the money format and every word come from options, so it fits any shop or
|
|
8
|
+
language. Screen readers hear each price as plain text and a short “Showing yearly prices”
|
|
9
|
+
when the period changes. With reduced motion the new prices simply appear. */
|
|
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: 'Billing period', // the switch's name for screen readers
|
|
17
|
+
showing: (period) => `Showing ${period.toLowerCase()} prices`, // announced after a change
|
|
18
|
+
was: 'Was', // read before the crossed-out price
|
|
19
|
+
features: (plan) => `${plan} includes`, // the feature list's name for screen readers
|
|
20
|
+
};
|
|
21
|
+
const PERIODS = [{ id: 'month', label: 'Monthly', per: '/mo' }, { id: 'year', label: 'Yearly', per: '/mo', badge: 'Save 20%' }];
|
|
22
|
+
let uid = 0;
|
|
23
|
+
|
|
24
|
+
const txt = (w, ...a) => (typeof w === 'function' ? w(...a) : w);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* const prices = pricingToggle(el, {
|
|
28
|
+
* periods: [ // the switch; per = the small text after the price
|
|
29
|
+
* { id: 'month', label: 'Monthly', per: '/mo' },
|
|
30
|
+
* { id: 'year', label: 'Yearly', per: '/mo', badge: 'Save 20%' },
|
|
31
|
+
* ],
|
|
32
|
+
* plans: [
|
|
33
|
+
* { id: 'starter', name: 'Starter', desc: 'For one shop', price: { month: 12, year: 9 },
|
|
34
|
+
* note: { month: 'Billed monthly', year: '$108 billed yearly' }, // or (periodId, plan) => text
|
|
35
|
+
* features: ['1 location', 'Email support'], action: 'Choose Starter' },
|
|
36
|
+
* { id: 'pro', name: 'Pro', price: { month: 29, year: 23 }, featured: true, tag: 'Popular', action: 'Start free trial' },
|
|
37
|
+
* ],
|
|
38
|
+
* value: 'month', // the period shown first (default: the first one)
|
|
39
|
+
* format: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }, // Intl options, or (value, periodId, plan) => text
|
|
40
|
+
* locale: 'en-US', // for Intl (default: the browser's)
|
|
41
|
+
* motion: 'roll' | 'count', // roll digit by digit (odometer) or count to the new number
|
|
42
|
+
* strike: true, // on a later period, show the first period's price crossed out when it was higher
|
|
43
|
+
* words: { label, showing(periodLabel), was, features(planName) },
|
|
44
|
+
* onChange: (periodId, prices) => {},
|
|
45
|
+
* onSelect: (plan, periodId, prices) => {}, // the plan's action button was pressed
|
|
46
|
+
* })
|
|
47
|
+
* prices.period · prices.set('year') · prices.destroy()
|
|
48
|
+
* A price may also be a string ('Custom', 'Free'): it is shown as it is.
|
|
49
|
+
*/
|
|
50
|
+
export const pricingToggle = (el, opts = {}) => {
|
|
51
|
+
el = $$(el)[0];
|
|
52
|
+
if (!el) return null;
|
|
53
|
+
const o = { periods: PERIODS, plans: [], value: '', format: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }, locale: undefined,
|
|
54
|
+
motion: 'roll', strike: true, words: null, onChange: null, onSelect: null, ...opts };
|
|
55
|
+
const W = { ...WORDS, ...o.words };
|
|
56
|
+
const periods = o.periods.length ? o.periods : PERIODS;
|
|
57
|
+
const id = `price${++uid}`;
|
|
58
|
+
const ac = new AbortController(), on = (t, ev, fn) => t.addEventListener(ev, fn, { signal: ac.signal });
|
|
59
|
+
const fmt = (v, p, plan) => {
|
|
60
|
+
if (v === null || v === undefined) return '';
|
|
61
|
+
if (typeof v === 'string') return v;
|
|
62
|
+
if (typeof o.format === 'function') return String(o.format(v, p, plan));
|
|
63
|
+
try { return new Intl.NumberFormat(o.locale, o.format || undefined).format(v); } catch { return String(v); }
|
|
64
|
+
};
|
|
65
|
+
const priceOf = (plan, p) => (plan.price && typeof plan.price === 'object' ? plan.price[p] : plan.price);
|
|
66
|
+
const noteOf = (plan, p) => txt(plan.note && typeof plan.note === 'object' ? plan.note[p] : plan.note, p, plan) ?? '';
|
|
67
|
+
const per = (p) => periods.find((x) => x.id === p) || periods[0];
|
|
68
|
+
|
|
69
|
+
const planHTML = (plan, i) => {
|
|
70
|
+
const k = `${id}-${i}`;
|
|
71
|
+
return `<section class="pricing__plan${plan.featured ? ' is-featured' : ''}" aria-labelledby="${k}">`
|
|
72
|
+
+ `<header class="pricing__head"><h3 class="pricing__name" id="${k}">${esc(plan.name ?? '')}</h3>${plan.tag ? `<span class="pricing__tag">${esc(plan.tag)}</span>` : ''}</header>`
|
|
73
|
+
+ (plan.desc ? `<p class="pricing__desc">${esc(plan.desc)}</p>` : '')
|
|
74
|
+
+ '<div class="pricing__price"><s class="pricing__was" hidden></s><span class="pricing__amount"></span><span class="pricing__per"></span></div>'
|
|
75
|
+
+ '<p class="pricing__note"></p>'
|
|
76
|
+
+ (plan.features?.length ? `<ul class="pricing__features" aria-label="${esc(txt(W.features, plan.name ?? ''))}">${plan.features.map((f) => `<li>${icon('check')}<span>${esc(f)}</span></li>`).join('')}</ul>` : '')
|
|
77
|
+
+ (plan.action ? `<button type="button" class="btn ${plan.featured ? 'btn--primary' : ''} btn--block pricing__go" data-plan="${i}">${esc(plan.action)}</button>` : '')
|
|
78
|
+
+ '</section>';
|
|
79
|
+
};
|
|
80
|
+
el.innerHTML = `<div class="pricing${RM() ? ' pricing--still' : ''}">`
|
|
81
|
+
+ `<div class="seg pricing__switch" role="group" aria-label="${esc(W.label)}"><span class="seg__thumb"></span>`
|
|
82
|
+
+ periods.map((p) => `<button type="button" data-v="${esc(p.id)}" aria-pressed="false"><span>${esc(p.label)}</span>${p.badge ? `<span class="pricing__save">${esc(p.badge)}</span>` : ''}</button>`).join('')
|
|
83
|
+
+ `</div><div class="pricing__plans">${o.plans.map(planHTML).join('')}</div>`
|
|
84
|
+
+ '<p class="pricing__sr" role="status" aria-live="polite"></p></div>';
|
|
85
|
+
|
|
86
|
+
const root = el.firstElementChild;
|
|
87
|
+
const sw = root.querySelector('.pricing__switch'), thumb = sw.querySelector('.seg__thumb'), btns = $$('button[data-v]', sw);
|
|
88
|
+
const sr = root.querySelector('.pricing__sr');
|
|
89
|
+
const cards = $$('.pricing__plan', root).map((c, i) => ({
|
|
90
|
+
plan: o.plans[i], el: c, amount: c.querySelector('.pricing__amount'), per: c.querySelector('.pricing__per'),
|
|
91
|
+
was: c.querySelector('.pricing__was'), note: c.querySelector('.pricing__note'),
|
|
92
|
+
}));
|
|
93
|
+
const current = () => sw.querySelector('[aria-pressed="true"]');
|
|
94
|
+
const thumbOpts = { radius: 99 };
|
|
95
|
+
const rad = () => parseFloat(getComputedStyle(btns[0]).borderTopLeftRadius) || 99; // the thumb takes the buttons' rounding
|
|
96
|
+
const stopTrack = M.trackIndicator(thumb, () => { thumbOpts.radius = rad(); return current(); }, thumbOpts);
|
|
97
|
+
let period = '', first = true;
|
|
98
|
+
|
|
99
|
+
/* a short text that changes: the old one slips up and out, the new one comes up from below */
|
|
100
|
+
const swapText = (node, text, delay) => {
|
|
101
|
+
if (node.textContent === text) return;
|
|
102
|
+
g.killTweensOf(node);
|
|
103
|
+
if (first || RM()) { node.textContent = text; g.set(node, { clearProps: 'opacity,transform' }); return; }
|
|
104
|
+
g.timeline({ delay })
|
|
105
|
+
.to(node, { opacity: 0, y: -6, duration: 0.16, ease: 'power2.in' })
|
|
106
|
+
.add(() => { node.textContent = text; })
|
|
107
|
+
.fromTo(node, { opacity: 0, y: 8 }, { opacity: 1, y: 0, duration: 0.36, ease: 'power3.out', clearProps: 'opacity,transform' });
|
|
108
|
+
};
|
|
109
|
+
const setWas = (c, text, delay) => {
|
|
110
|
+
const show = !!text;
|
|
111
|
+
g.killTweensOf(c.was);
|
|
112
|
+
if (show) c.was.innerHTML = `<span class="pricing__vh">${esc(W.was)} </span>${esc(text)}`;
|
|
113
|
+
if (first || RM()) { c.was.hidden = !show; g.set(c.was, { clearProps: 'opacity,transform,width' }); return; }
|
|
114
|
+
if (show && c.was.hidden) {
|
|
115
|
+
c.was.hidden = false;
|
|
116
|
+
g.fromTo(c.was, { opacity: 0, x: 6 }, { opacity: 1, x: 0, duration: 0.4, delay: delay + 0.15, ease: 'power3.out', clearProps: 'opacity,transform' });
|
|
117
|
+
} else if (!show && !c.was.hidden) {
|
|
118
|
+
g.to(c.was, { opacity: 0, x: 6, duration: 0.2, ease: 'power2.in', onComplete: () => { c.was.hidden = true; g.set(c.was, { clearProps: 'opacity,transform' }); } });
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const setAmount = (c, value, p, delay) => {
|
|
122
|
+
const text = fmt(value, p, c.plan);
|
|
123
|
+
if (typeof value !== 'number') { M.odometer.clear(c.amount); g.killTweensOf(c.amount); swapText(c.amount, text, delay); return; }
|
|
124
|
+
if (o.motion === 'count') {
|
|
125
|
+
const f = (v) => fmt(Math.abs(value % 1) > 0 ? Math.round(v * 100) / 100 : Math.round(v), p, c.plan);
|
|
126
|
+
M.count(c.amount, value, f, { duration: first ? 0 : 0.8, delay, from: c.__v ?? value });
|
|
127
|
+
} else {
|
|
128
|
+
const tl = M.odometer(c.amount, value, { format: (v) => fmt(v, p, c.plan), stagger: 0.05 });
|
|
129
|
+
if (!first && delay) tl.delay(delay);
|
|
130
|
+
}
|
|
131
|
+
c.__v = value;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const set = (p, { silent = false } = {}) => {
|
|
135
|
+
const P = per(p);
|
|
136
|
+
if (P.id === period) return false;
|
|
137
|
+
period = P.id;
|
|
138
|
+
btns.forEach((b) => b.setAttribute('aria-pressed', b.dataset.v === P.id));
|
|
139
|
+
const b = current();
|
|
140
|
+
M.indicator(thumb, b, { radius: rad(), animate: !first });
|
|
141
|
+
const badge = b.querySelector('.pricing__save');
|
|
142
|
+
if (!first && badge && !RM()) g.fromTo(badge, { scale: 0.6 }, { scale: 1, duration: 0.6, ease: 'back.out(3)', clearProps: 'transform' });
|
|
143
|
+
const base = periods[0].id;
|
|
144
|
+
cards.forEach((c, k) => {
|
|
145
|
+
const d = first ? 0 : k * 0.07, v = priceOf(c.plan, P.id), v0 = priceOf(c.plan, base);
|
|
146
|
+
setAmount(c, v, P.id, d);
|
|
147
|
+
swapText(c.per, v === null || v === undefined || typeof v === 'string' ? '' : P.per ?? '', d);
|
|
148
|
+
setWas(c, o.strike && P.id !== base && typeof v === 'number' && typeof v0 === 'number' && v0 > v ? fmt(v0, base, c.plan) : '', d);
|
|
149
|
+
swapText(c.note, noteOf(c.plan, P.id), d);
|
|
150
|
+
});
|
|
151
|
+
if (!first) {
|
|
152
|
+
sr.textContent = txt(W.showing, P.label);
|
|
153
|
+
if (!silent) o.onChange?.(P.id, api);
|
|
154
|
+
}
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
on(sw, 'click', (e) => { const b = e.target.closest('button[data-v]'); if (b && set(b.dataset.v)) M.pop(b); });
|
|
159
|
+
on(sw, 'keydown', (e) => {
|
|
160
|
+
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
|
|
161
|
+
e.preventDefault();
|
|
162
|
+
const rtl = getComputedStyle(root).direction === 'rtl';
|
|
163
|
+
const i = btns.indexOf(current()), n = btns.length;
|
|
164
|
+
const fwd = (e.key === 'ArrowRight') !== rtl;
|
|
165
|
+
const j = e.key === 'Home' ? 0 : e.key === 'End' ? n - 1 : (i + (fwd ? 1 : -1) + n) % n;
|
|
166
|
+
set(btns[j].dataset.v); btns[j].focus();
|
|
167
|
+
});
|
|
168
|
+
on(root, 'click', (e) => {
|
|
169
|
+
const b = e.target.closest('.pricing__go'); if (!b) return;
|
|
170
|
+
M.pop(b);
|
|
171
|
+
o.onSelect?.(o.plans[+b.dataset.plan], period, api);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const api = {
|
|
175
|
+
root,
|
|
176
|
+
get period() { return period; },
|
|
177
|
+
/** Show another period's prices (rolls them). onChange runs unless { silent: true }. */
|
|
178
|
+
set: (p, x) => set(p, x),
|
|
179
|
+
destroy() {
|
|
180
|
+
ac.abort(); stopTrack();
|
|
181
|
+
cards.forEach((c) => M.odometer.clear(c.amount));
|
|
182
|
+
g.killTweensOf([root, ...root.querySelectorAll('*')]);
|
|
183
|
+
el.innerHTML = '';
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
set(o.value || periods[0].id, { silent: true });
|
|
187
|
+
first = false;
|
|
188
|
+
return api;
|
|
189
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/* Radio cards: a group of choices where exactly one is picked, drawn as cards instead of small
|
|
2
|
+
round dots. Each card can have a title, a short description, a price (or any short text on the
|
|
3
|
+
right), an icon and a small badge such as “Popular”. The picked card gets an accent ring and a
|
|
4
|
+
soft tint, and the round mark in its corner fills and a tick draws in with a little overshoot.
|
|
5
|
+
Underneath they are real radio buttons in a <fieldset>, so the browser does the work: arrow keys
|
|
6
|
+
move between the cards and pick them, Tab enters and leaves the group, forms send the value, and
|
|
7
|
+
screen readers hear “radio button, 2 of 3, checked”. With reduced motion the mark simply
|
|
8
|
+
appears and the cards do not bounce. */
|
|
9
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
10
|
+
import { icon } from '@gecko-ui-kit/icons';
|
|
11
|
+
import { esc } from '../index.js';
|
|
12
|
+
|
|
13
|
+
const { g, RM, $$ } = M;
|
|
14
|
+
const WORDS = { group: 'Options' }; // the group's name for screen readers when there is no label
|
|
15
|
+
let uid = 0;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* const plan = radioCards(el, {
|
|
19
|
+
* label: 'Delivery', // the group name (a <legend>); hideLabel: true keeps it for screen readers only
|
|
20
|
+
* options: [
|
|
21
|
+
* { value: 'standard', title: 'Standard', desc: '3–5 working days', price: 'Free' },
|
|
22
|
+
* { value: 'express', title: 'Express', desc: 'Arrives tomorrow', price: '$9', icon: 'zap', badge: 'Popular' },
|
|
23
|
+
* { value: 'pickup', title: 'Pick up in store', desc: 'Ready in 2 hours', price: 'Free', disabled: true },
|
|
24
|
+
* ],
|
|
25
|
+
* value: 'standard', // picked at the start ('' = none picked yet)
|
|
26
|
+
* layout: 'list' | 'grid', // list: one card per row; grid: cards side by side (min width: min)
|
|
27
|
+
* min: 160, // grid only: the narrowest a card gets, in px
|
|
28
|
+
* name: 'delivery', // the radios' name (sent with a form); made up if left out
|
|
29
|
+
* required: false, // the browser asks for a pick before the form is sent
|
|
30
|
+
* disabled: false, // the whole group
|
|
31
|
+
* words: { group: 'Options' }, // read out as the group name when label is empty
|
|
32
|
+
* onChange: (value, option, plan) => {},
|
|
33
|
+
* })
|
|
34
|
+
* plan.value · plan.set('express') · plan.focus() · plan.destroy()
|
|
35
|
+
*/
|
|
36
|
+
export const radioCards = (el, opts = {}) => {
|
|
37
|
+
el = $$(el)[0];
|
|
38
|
+
if (!el) return null;
|
|
39
|
+
const o = { label: '', hideLabel: false, options: [], value: '', layout: 'list', min: 160, name: '', required: false, disabled: false, words: null, onChange: null, ...opts };
|
|
40
|
+
const W = { ...WORDS, ...o.words };
|
|
41
|
+
const id = `rcard${++uid}`, name = o.name || id;
|
|
42
|
+
const ac = new AbortController();
|
|
43
|
+
const opt = (x) => (typeof x === 'object' && x ? x : { value: String(x), title: String(x) });
|
|
44
|
+
const options = o.options.map(opt);
|
|
45
|
+
|
|
46
|
+
const card = (x, i) => {
|
|
47
|
+
const k = `${id}-${i}`, v = String(x.value ?? i);
|
|
48
|
+
const desc = [x.desc ? `${k}-d` : '', x.price !== undefined && x.price !== '' ? `${k}-p` : ''].filter(Boolean).join(' ');
|
|
49
|
+
return `<label class="rcard${x.icon ? ' rcard--icon' : ''}">`
|
|
50
|
+
+ `<input class="rcard__input" type="radio" name="${esc(name)}" value="${esc(v)}" aria-labelledby="${k}-t"${desc ? ` aria-describedby="${desc}"` : ''}`
|
|
51
|
+
+ `${v === String(o.value) ? ' checked' : ''}${x.disabled ? ' disabled' : ''}${o.required ? ' required' : ''}>`
|
|
52
|
+
+ '<span class="rcard__mark" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="m4.2 8.4 2.5 2.5 5.1-5.3"/></svg></span>'
|
|
53
|
+
+ (x.icon ? `<span class="rcard__icon" aria-hidden="true">${icon(x.icon)}</span>` : '')
|
|
54
|
+
+ `<span class="rcard__text"><span class="rcard__title" id="${k}-t">${esc(x.title ?? v)}${x.badge ? ` <span class="rcard__badge">${esc(x.badge)}</span>` : ''}</span>`
|
|
55
|
+
+ (x.desc ? `<span class="rcard__desc" id="${k}-d">${esc(x.desc)}</span>` : '') + '</span>'
|
|
56
|
+
+ (desc.includes('-p') ? `<span class="rcard__price" id="${k}-p">${esc(x.price)}</span>` : '')
|
|
57
|
+
+ '</label>';
|
|
58
|
+
};
|
|
59
|
+
const grid = o.layout === 'grid';
|
|
60
|
+
el.innerHTML = `<fieldset class="rcards rcards--${grid ? 'grid' : 'list'}${RM() ? ' rcards--still' : ''}" role="radiogroup"${o.disabled ? ' disabled' : ''}`
|
|
61
|
+
+ `${grid ? ` style="--rc-min:${Math.max(80, +o.min || 160)}px"` : ''}${!o.label ? ` aria-label="${esc(W.group)}"` : ''}>`
|
|
62
|
+
+ (o.label ? `<legend class="rcards__legend${o.hideLabel ? ' rcards__vh' : ''}">${esc(o.label)}</legend>` : '')
|
|
63
|
+
+ `<div class="rcards__list">${options.map(card).join('')}</div></fieldset>`;
|
|
64
|
+
|
|
65
|
+
const root = el.firstElementChild;
|
|
66
|
+
const inputs = $$('.rcard__input', root);
|
|
67
|
+
const picked = () => inputs.find((i) => i.checked);
|
|
68
|
+
const optionOf = (input) => options[inputs.indexOf(input)];
|
|
69
|
+
|
|
70
|
+
/* The mark is drawn by CSS (:checked); this adds the springy press on the card that was picked. */
|
|
71
|
+
const bounce = (input) => {
|
|
72
|
+
const c = input.closest('.rcard');
|
|
73
|
+
if (RM() || !c) return;
|
|
74
|
+
g.fromTo(c, { scale: 0.97 }, { scale: 1, duration: 0.5, ease: 'back.out(3)', overwrite: true, clearProps: 'transform' });
|
|
75
|
+
const ic = c.querySelector('.rcard__icon svg');
|
|
76
|
+
if (ic) g.fromTo(ic, { scale: 0.6, rotation: -12 }, { scale: 1, rotation: 0, duration: 0.55, ease: 'back.out(2.6)', clearProps: 'transform' });
|
|
77
|
+
};
|
|
78
|
+
root.addEventListener('change', (e) => {
|
|
79
|
+
const i = e.target;
|
|
80
|
+
if (!inputs.includes(i) || !i.checked) return;
|
|
81
|
+
bounce(i);
|
|
82
|
+
o.onChange?.(i.value, optionOf(i), api);
|
|
83
|
+
}, { signal: ac.signal });
|
|
84
|
+
|
|
85
|
+
const api = {
|
|
86
|
+
root,
|
|
87
|
+
get value() { return picked()?.value ?? ''; },
|
|
88
|
+
/** Pick a value from code (no onChange unless { silent: false }); '' clears the pick. */
|
|
89
|
+
set(v, { silent = true } = {}) {
|
|
90
|
+
const i = inputs.find((x) => x.value === String(v));
|
|
91
|
+
if (!i) { inputs.forEach((x) => { x.checked = false; }); return api; }
|
|
92
|
+
if (i.checked || i.disabled) return api;
|
|
93
|
+
i.checked = true; bounce(i);
|
|
94
|
+
if (!silent) o.onChange?.(i.value, optionOf(i), api);
|
|
95
|
+
return api;
|
|
96
|
+
},
|
|
97
|
+
focus() { (picked() || inputs.find((x) => !x.disabled))?.focus(); },
|
|
98
|
+
destroy() { ac.abort(); g.killTweensOf(root.querySelectorAll('*')); el.innerHTML = ''; },
|
|
99
|
+
};
|
|
100
|
+
return api;
|
|
101
|
+
};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/* Range slider with two thumbs: pick a low and a high value on one track (a price filter, opening
|
|
2
|
+
hours). Drag a thumb, press the track to send the nearest thumb there, or drag the filled middle to
|
|
3
|
+
move both at once. The thumbs never cross and keep `minGap` apart; when they sit on top of each
|
|
4
|
+
other, the way you drag decides which one moves.
|
|
5
|
+
How it moves: a grabbed thumb grows with a spring and a bubble with the value pops up above it;
|
|
6
|
+
pressing the track or calling set() glides the thumbs over; bars of an optional histogram behind
|
|
7
|
+
the track light up as they come inside the range and fade as they leave it, and grow up from the
|
|
8
|
+
track when it first shows. With reduced motion everything jumps straight to its place. */
|
|
9
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
10
|
+
import { esc } from '../index.js';
|
|
11
|
+
|
|
12
|
+
const { g, RM, $$ } = M;
|
|
13
|
+
const WORDS = { min: 'Minimum', max: 'Maximum', to: 'to', range: (a, b) => `${a} – ${b}` };
|
|
14
|
+
let seq = 0;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* const rs = rangeSlider(el, {
|
|
18
|
+
* min: 0, max: 100, step: 1,
|
|
19
|
+
* value: [20, 80], // [low, high]; default: the whole range
|
|
20
|
+
* minGap: 0, // the least the two may be apart
|
|
21
|
+
* format: (v) => string, // bubble, aria-valuetext, marks, inputs (default: grouped digits)
|
|
22
|
+
* parse: (text) => number, // reads the number inputs (default: the digits in the text)
|
|
23
|
+
* marks: [0, 50, 100] | 25, // ticks + labels under the track (a number: every n)
|
|
24
|
+
* histogram: [3, 8, 12, …], // bars behind the track, spread evenly from min to max;
|
|
25
|
+
* // a bar whose middle is inside the range lights up
|
|
26
|
+
* inputs: false, // two number boxes under the track (commit on blur / Enter)
|
|
27
|
+
* name: 'price', // two hidden inputs: price_min and price_max
|
|
28
|
+
* label: 'Price', // a heading with the range written out next to it
|
|
29
|
+
* disabled: false,
|
|
30
|
+
* words: { min, max, to, range },
|
|
31
|
+
* onInput(value, rs), // every change while dragging
|
|
32
|
+
* onChange(value, rs), // when a drag ends, a key is pressed, a box is committed
|
|
33
|
+
* })
|
|
34
|
+
* rs.value → [low, high] · rs.set([low, high], { silent }) · rs.destroy()
|
|
35
|
+
*/
|
|
36
|
+
export const rangeSlider = (el, opts = {}) => {
|
|
37
|
+
el = $$(el)[0];
|
|
38
|
+
if (!el) return null;
|
|
39
|
+
const o = { min: 0, max: 100, step: 1, value: null, minGap: 0, format: null, parse: null, marks: null, histogram: null, inputs: false, name: '', label: '', disabled: false, onInput: null, onChange: null, ...opts };
|
|
40
|
+
const W = { ...WORDS, ...o.words };
|
|
41
|
+
const id = `rs${++seq}`;
|
|
42
|
+
const min = +o.min, max = Math.max(+o.max, min + 1e-9), span = max - min, step = Math.abs(+o.step) || 1;
|
|
43
|
+
const gap = Math.max(0, +o.minGap || 0);
|
|
44
|
+
const dec = (String(step).split('.')[1] || '').length;
|
|
45
|
+
const nf = new Intl.NumberFormat(undefined, { minimumFractionDigits: dec, maximumFractionDigits: dec });
|
|
46
|
+
const fmt = (v) => (o.format ? String(o.format(v)) : nf.format(v));
|
|
47
|
+
const parse = (t) => (o.parse ? +o.parse(t) : parseFloat(String(t).replace(/[^\d.-]/g, '')));
|
|
48
|
+
const snap = (v) => +(min + Math.round((v - min) / step) * step).toFixed(dec);
|
|
49
|
+
const clamp = (v, a = min, b = max) => Math.min(b, Math.max(a, v));
|
|
50
|
+
const pct = (v) => ((v - min) / span) * 100;
|
|
51
|
+
|
|
52
|
+
/* ---------- the first value ---------- */
|
|
53
|
+
const start = Array.isArray(o.value) ? o.value : [min, max];
|
|
54
|
+
let lo = clamp(snap(+start[0])), hi = clamp(snap(+start[1]));
|
|
55
|
+
if (!Number.isFinite(lo)) lo = min;
|
|
56
|
+
if (!Number.isFinite(hi)) hi = max;
|
|
57
|
+
if (lo > hi) [lo, hi] = [hi, lo];
|
|
58
|
+
if (hi - lo < gap) { hi = Math.min(max, lo + gap); lo = Math.max(min, hi - gap); }
|
|
59
|
+
let val = [lo, hi];
|
|
60
|
+
|
|
61
|
+
/* ---------- markup ---------- */
|
|
62
|
+
const hist = Array.isArray(o.histogram) && o.histogram.length ? o.histogram.map((n) => Math.max(0, +n || 0)) : null;
|
|
63
|
+
const top = hist ? Math.max(...hist) || 1 : 1;
|
|
64
|
+
const marks = (typeof o.marks === 'number' && o.marks > 0
|
|
65
|
+
? Array.from({ length: Math.floor(span / o.marks + 1e-9) + 1 }, (_, i) => min + i * o.marks)
|
|
66
|
+
: Array.isArray(o.marks) ? o.marks.map(Number) : []).filter((v) => Number.isFinite(v) && v >= min && v <= max);
|
|
67
|
+
const thumb = (i) => `<div class="rs__thumb" data-i="${i}" role="slider" tabindex="${o.disabled ? -1 : 0}" aria-label="${esc(i ? W.max : W.min)}" aria-orientation="horizontal"${o.disabled ? ' aria-disabled="true"' : ''}><span class="rs__knob"></span><span class="rs__bubble" aria-hidden="true"></span></div>`;
|
|
68
|
+
const box = (i) => `<label class="rs__in"><small>${esc(i ? W.max : W.min)}</small><input class="input input--sm rs__num" data-i="${i}" type="text" inputmode="decimal" autocomplete="off"${o.disabled ? ' disabled' : ''}></label>`;
|
|
69
|
+
el.innerHTML = `<div class="rs${hist ? ' has-hist' : ''}${marks.length ? ' has-marks' : ''}${o.disabled ? ' is-disabled' : ''}${RM() ? ' is-still' : ''}" role="group"${o.label ? ` aria-labelledby="${id}-l"` : ''}>`
|
|
70
|
+
+ (o.label ? `<div class="rs__head"><span class="rs__label" id="${id}-l">${esc(o.label)}</span><output class="rs__out" aria-hidden="true"></output></div>` : '')
|
|
71
|
+
+ '<div class="rs__body">'
|
|
72
|
+
+ (hist ? `<div class="rs__hist" aria-hidden="true">${hist.map((n) => `<i class="rs__bar" style="height:${Math.max(4, (n / top) * 100)}%"></i>`).join('')}</div>` : '')
|
|
73
|
+
+ `<div class="rs__rail"><div class="rs__track"><div class="rs__fill"></div></div>${thumb(0)}${thumb(1)}</div>`
|
|
74
|
+
+ (marks.length ? `<div class="rs__marks" aria-hidden="true">${marks.map((v) => `<button type="button" class="rs__mark${v === min ? ' is-start' : v === max ? ' is-end' : ''}" tabindex="-1" data-v="${v}" style="left:${pct(v)}%"${o.disabled ? ' disabled' : ''}><i></i><small>${esc(fmt(v))}</small></button>`).join('')}</div>` : '')
|
|
75
|
+
+ '</div>'
|
|
76
|
+
+ (o.inputs ? `<div class="rs__inputs">${box(0)}<span class="rs__to">${esc(W.to)}</span>${box(1)}</div>` : '')
|
|
77
|
+
+ (o.name ? `<input type="hidden" name="${esc(o.name)}_min"><input type="hidden" name="${esc(o.name)}_max">` : '')
|
|
78
|
+
+ '</div>';
|
|
79
|
+
const root = el.firstElementChild, rail = root.querySelector('.rs__rail');
|
|
80
|
+
const thumbs = [...root.querySelectorAll('.rs__thumb')], knobs = thumbs.map((t) => t.querySelector('.rs__knob')), bubbles = thumbs.map((t) => t.querySelector('.rs__bubble'));
|
|
81
|
+
const nums = [...root.querySelectorAll('.rs__num')], bars = [...root.querySelectorAll('.rs__bar')], markEls = [...root.querySelectorAll('.rs__mark')];
|
|
82
|
+
const hidden = [...root.querySelectorAll('input[type="hidden"]')], out = root.querySelector('.rs__out');
|
|
83
|
+
|
|
84
|
+
/* ---------- drawing ---------- */
|
|
85
|
+
const pos = { a: pct(lo), b: pct(hi) }; // what is on screen (tweened), in %
|
|
86
|
+
const place = () => {
|
|
87
|
+
const w = rail.clientWidth, near = ((pos.b - pos.a) / 100) * w < (bubbles[0].offsetWidth + bubbles[1].offsetWidth) / 2 + 6;
|
|
88
|
+
root.style.setProperty('--a', `${pos.a}%`); root.style.setProperty('--b', `${pos.b}%`);
|
|
89
|
+
root.classList.toggle('is-near', near);
|
|
90
|
+
};
|
|
91
|
+
const glide = (animate) => {
|
|
92
|
+
g.killTweensOf(pos);
|
|
93
|
+
const a = pct(val[0]), b = pct(val[1]);
|
|
94
|
+
if (!animate || RM()) { pos.a = a; pos.b = b; place(); return; }
|
|
95
|
+
g.to(pos, { a, b, duration: 0.34, ease: 'power3.out', onUpdate: place });
|
|
96
|
+
};
|
|
97
|
+
const paint = (animate = false) => {
|
|
98
|
+
const [a, b] = val;
|
|
99
|
+
thumbs.forEach((t, i) => {
|
|
100
|
+
const v = val[i];
|
|
101
|
+
t.setAttribute('aria-valuemin', String(i ? Math.min(max, a + gap) : min));
|
|
102
|
+
t.setAttribute('aria-valuemax', String(i ? max : Math.max(min, b - gap)));
|
|
103
|
+
t.setAttribute('aria-valuenow', String(v));
|
|
104
|
+
t.setAttribute('aria-valuetext', fmt(v));
|
|
105
|
+
bubbles[i].textContent = fmt(v);
|
|
106
|
+
});
|
|
107
|
+
if (out) out.textContent = W.range(fmt(a), fmt(b));
|
|
108
|
+
nums.forEach((n, i) => { if (document.activeElement !== n) n.value = fmt(val[i]); });
|
|
109
|
+
if (hidden.length) { hidden[0].value = String(a); hidden[1].value = String(b); }
|
|
110
|
+
const w = span / (bars.length || 1);
|
|
111
|
+
bars.forEach((x, k) => { const mid = min + (k + 0.5) * w; x.classList.toggle('is-in', mid >= a && mid <= b); });
|
|
112
|
+
markEls.forEach((m) => { const v = +m.dataset.v; m.classList.toggle('is-in', v >= a && v <= b); });
|
|
113
|
+
glide(animate);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/* ---------- changing the value ---------- */
|
|
117
|
+
const same = (x, y) => x[0] === y[0] && x[1] === y[1];
|
|
118
|
+
/** Where thumb i may go: inside the track and minGap away from the other one. */
|
|
119
|
+
const fit = (i, v) => (i ? clamp(snap(v), Math.min(max, val[0] + gap), max) : clamp(snap(v), min, Math.max(min, val[1] - gap)));
|
|
120
|
+
/** Set a new pair; returns true when it changed. input: call onInput. */
|
|
121
|
+
const put = (next, { animate = false, silent = false } = {}) => {
|
|
122
|
+
if (same(next, val)) return false;
|
|
123
|
+
val = next; paint(animate);
|
|
124
|
+
if (!silent) o.onInput?.([...val], api);
|
|
125
|
+
return true;
|
|
126
|
+
};
|
|
127
|
+
const changed = () => o.onChange?.([...val], api);
|
|
128
|
+
const moveThumb = (i, v, how) => { const next = [...val]; next[i] = fit(i, v); return put(next, how); };
|
|
129
|
+
const valueAt = (x) => { const r = rail.getBoundingClientRect(); return min + clamp((x - r.left) / (r.width || 1), 0, 1) * span; };
|
|
130
|
+
const nearest = (v) => (v <= val[0] ? 0 : v >= val[1] ? 1 : v - val[0] <= val[1] - v ? 0 : 1);
|
|
131
|
+
const front = (i) => thumbs.forEach((t, k) => t.classList.toggle('is-top', k === i));
|
|
132
|
+
|
|
133
|
+
/* ---------- grab motion ---------- */
|
|
134
|
+
const grab = (i, on) => {
|
|
135
|
+
thumbs[i].classList.toggle('is-drag', on);
|
|
136
|
+
if (RM()) return;
|
|
137
|
+
g.to(knobs[i], on ? { scale: 1.32, duration: 0.55, ease: 'elastic.out(1, 0.45)', overwrite: true } : { scale: 1, duration: 0.35, ease: 'back.out(2.2)', overwrite: true, clearProps: 'transform' });
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/* ---------- pointer ---------- */
|
|
141
|
+
const ac = new AbortController();
|
|
142
|
+
const on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
|
|
143
|
+
let drag = null; // { mode: 'thumb' | 'middle' | 'pick', i, x0, v0, from, id }
|
|
144
|
+
const begin = (i) => { drag.mode = 'thumb'; drag.i = i; front(i); grab(i, true); thumbs[i].focus({ preventScroll: true }); };
|
|
145
|
+
on(rail, 'pointerdown', (e) => {
|
|
146
|
+
if (o.disabled || e.button > 0 || drag) return;
|
|
147
|
+
e.preventDefault();
|
|
148
|
+
const v = valueAt(e.clientX), t = e.target.closest('.rs__thumb');
|
|
149
|
+
drag = { mode: '', i: -1, x0: e.clientX, v0: v, from: [...val], id: e.pointerId };
|
|
150
|
+
try { rail.setPointerCapture(e.pointerId); } catch { /* fine */ }
|
|
151
|
+
if (t) {
|
|
152
|
+
const w = rail.clientWidth, overlap = ((pos.b - pos.a) / 100) * w < knobs[0].offsetWidth;
|
|
153
|
+
if (overlap) { drag.mode = 'pick'; thumbs[+t.dataset.i].focus({ preventScroll: true }); thumbs.forEach((x, k) => grab(k, true)); return; } // the drag direction decides
|
|
154
|
+
begin(+t.dataset.i);
|
|
155
|
+
} else if (v > val[0] && v < val[1]) {
|
|
156
|
+
drag.mode = 'middle'; // drag both, or a click moves the nearest
|
|
157
|
+
} else {
|
|
158
|
+
const i = nearest(v);
|
|
159
|
+
begin(i); moveThumb(i, v, { animate: true });
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
on(rail, 'pointermove', (e) => {
|
|
163
|
+
if (!drag || e.pointerId !== drag.id) return;
|
|
164
|
+
const dx = e.clientX - drag.x0;
|
|
165
|
+
if (drag.mode === 'pick') {
|
|
166
|
+
if (Math.abs(dx) < 2) return;
|
|
167
|
+
const i = dx < 0 ? 0 : 1;
|
|
168
|
+
thumbs.forEach((x, k) => { if (k !== i) grab(k, false); });
|
|
169
|
+
drag.mode = 'thumb'; drag.i = i; front(i); thumbs[i].focus({ preventScroll: true });
|
|
170
|
+
}
|
|
171
|
+
if (drag.mode === 'middle') {
|
|
172
|
+
if (Math.abs(dx) < 3 && !drag.moved) return;
|
|
173
|
+
if (!drag.moved) { drag.moved = true; root.classList.add('is-grab'); grab(0, true); grab(1, true); }
|
|
174
|
+
const width = drag.from[1] - drag.from[0];
|
|
175
|
+
const a = clamp(snap(drag.from[0] + valueAt(e.clientX) - drag.v0), min, max - width);
|
|
176
|
+
put([a, +(a + width).toFixed(dec)]);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (drag.mode === 'thumb') moveThumb(drag.i, valueAt(e.clientX));
|
|
180
|
+
});
|
|
181
|
+
const end = (e) => {
|
|
182
|
+
if (!drag || (e.pointerId != null && e.pointerId !== drag.id)) return;
|
|
183
|
+
const d = drag; drag = null;
|
|
184
|
+
root.classList.remove('is-grab');
|
|
185
|
+
if (d.mode === 'middle' && !d.moved) { // a click inside the range: the nearest thumb glides there
|
|
186
|
+
const i = Math.abs(d.v0 - val[0]) <= Math.abs(d.v0 - val[1]) ? 0 : 1;
|
|
187
|
+
front(i); thumbs[i].focus({ preventScroll: true }); moveThumb(i, d.v0, { animate: true });
|
|
188
|
+
}
|
|
189
|
+
thumbs.forEach((x, k) => { if (x.classList.contains('is-drag')) grab(k, false); });
|
|
190
|
+
if (!same(d.from, val)) changed();
|
|
191
|
+
};
|
|
192
|
+
on(rail, 'pointerup', end);
|
|
193
|
+
on(rail, 'pointercancel', end);
|
|
194
|
+
on(rail, 'lostpointercapture', end);
|
|
195
|
+
|
|
196
|
+
/* ---------- keyboard ---------- */
|
|
197
|
+
thumbs.forEach((t, i) => {
|
|
198
|
+
on(t, 'keydown', (e) => {
|
|
199
|
+
if (o.disabled) return;
|
|
200
|
+
const k = e.key, big = step * 10;
|
|
201
|
+
let v = null;
|
|
202
|
+
if (k === 'ArrowRight' || k === 'ArrowUp') v = val[i] + step;
|
|
203
|
+
else if (k === 'ArrowLeft' || k === 'ArrowDown') v = val[i] - step;
|
|
204
|
+
else if (k === 'PageUp') v = val[i] + big;
|
|
205
|
+
else if (k === 'PageDown') v = val[i] - big;
|
|
206
|
+
else if (k === 'Home') v = min;
|
|
207
|
+
else if (k === 'End') v = max;
|
|
208
|
+
if (v === null) return;
|
|
209
|
+
e.preventDefault(); front(i);
|
|
210
|
+
if (moveThumb(i, v, { animate: true })) changed();
|
|
211
|
+
});
|
|
212
|
+
on(t, 'focus', () => front(i));
|
|
213
|
+
});
|
|
214
|
+
markEls.forEach((m) => on(m, 'click', () => {
|
|
215
|
+
if (o.disabled) return;
|
|
216
|
+
const v = +m.dataset.v, i = v <= val[0] ? 0 : v >= val[1] ? 1 : nearest(v);
|
|
217
|
+
front(i); if (moveThumb(i, v, { animate: true })) changed();
|
|
218
|
+
}));
|
|
219
|
+
|
|
220
|
+
/* ---------- number boxes ---------- */
|
|
221
|
+
nums.forEach((n, i) => {
|
|
222
|
+
/** Read the box; raw: leave the plain number in it (still typing) rather than the formatted one. */
|
|
223
|
+
const commit = (raw) => {
|
|
224
|
+
const v = parse(n.value);
|
|
225
|
+
if (!Number.isFinite(v)) { n.value = raw ? String(val[i]) : fmt(val[i]); M.shake(n.closest('.rs__in')); return; }
|
|
226
|
+
if (moveThumb(i, v, { animate: true })) changed();
|
|
227
|
+
n.value = raw ? String(val[i]) : fmt(val[i]);
|
|
228
|
+
if (snap(clamp(v)) !== val[i]) M.flash(n); // it was pulled inside the limits
|
|
229
|
+
};
|
|
230
|
+
on(n, 'focus', () => { n.value = String(val[i]); n.select(); });
|
|
231
|
+
on(n, 'blur', () => commit(false));
|
|
232
|
+
on(n, 'keydown', (e) => {
|
|
233
|
+
if (e.key === 'Enter') { e.preventDefault(); commit(true); n.select(); }
|
|
234
|
+
else if (e.key === 'Escape') { e.preventDefault(); n.value = String(val[i]); n.select(); }
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
let ro = null;
|
|
239
|
+
if (typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(() => place()); ro.observe(rail); }
|
|
240
|
+
|
|
241
|
+
const api = {
|
|
242
|
+
el: root, opts: o,
|
|
243
|
+
get value() { return [...val]; },
|
|
244
|
+
/** Go to [low, high] (snapped, kept in the limits and minGap apart); the thumbs glide there. */
|
|
245
|
+
set(next = [], { silent = false } = {}) {
|
|
246
|
+
let [a, b] = [+next[0], +next[1]];
|
|
247
|
+
if (!Number.isFinite(a)) a = val[0];
|
|
248
|
+
if (!Number.isFinite(b)) b = val[1];
|
|
249
|
+
a = clamp(snap(a)); b = clamp(snap(b));
|
|
250
|
+
if (a > b) [a, b] = [b, a];
|
|
251
|
+
if (b - a < gap) { b = Math.min(max, a + gap); a = Math.max(min, b - gap); }
|
|
252
|
+
if (put([a, b], { animate: true, silent }) && !silent) changed();
|
|
253
|
+
return api;
|
|
254
|
+
},
|
|
255
|
+
destroy() {
|
|
256
|
+
ac.abort(); ro?.disconnect();
|
|
257
|
+
g.killTweensOf([pos, ...knobs, ...bars]);
|
|
258
|
+
el.innerHTML = '';
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
paint(false);
|
|
263
|
+
front(1);
|
|
264
|
+
if (bars.length && !RM()) g.from(bars, { scaleY: 0, transformOrigin: '50% 100%', duration: 0.6, ease: 'power3.out', stagger: { each: 0.018, from: 'start' }, clearProps: 'transform' });
|
|
265
|
+
return api;
|
|
266
|
+
};
|