@gecko-ui-kit/components 0.0.0-stage → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ };