@sticker-pop/web 0.0.0-stage → 0.1.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,1011 @@
1
+ // Sticker Pop behaviours for the web: the interactive parts that CSS alone
2
+ // can't do. No dependencies; works with the markup in components.css.
3
+ import tokens from './tokens.mjs';
4
+ import { popInitials, popAvatarColor, popPageItems } from './format.mjs';
5
+
6
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
7
+
8
+ /**
9
+ * Makes chips, segments, switches and nav items in `root` toggle their ARIA
10
+ * state on click (aria-pressed, aria-checked, aria-current), and wires add menus, menus
11
+ * and selects.
12
+ */
13
+ export function wirePopControls(root = document) {
14
+ stabilizePopChips(root);
15
+ wirePopDials(root);
16
+ wirePopMenus(root);
17
+ wirePopSelects(root);
18
+ wirePopTopBars(root);
19
+ wirePopSearch(root);
20
+ wirePopDateTiles(root);
21
+ wirePopTabs(root);
22
+ wirePopSliders(root);
23
+ wirePopSteppers(root);
24
+ wirePopKeypads(root);
25
+ wirePopAvatars(root);
26
+ wirePopTooltips(root);
27
+ wirePopTagInputs(root);
28
+ wirePopAttachments(root);
29
+ root.querySelectorAll('.sp-chip[aria-pressed]:not(:disabled)').forEach((b) =>
30
+ b.addEventListener('click', () => b.setAttribute('aria-pressed', String(b.getAttribute('aria-pressed') !== 'true'))));
31
+ root.querySelectorAll('.sp-segmented:not([aria-disabled]) > button').forEach((b) =>
32
+ b.addEventListener('click', () => b.parentElement.querySelectorAll('button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)))));
33
+ root.querySelectorAll('.sp-switch:not(:disabled)').forEach((b) =>
34
+ b.addEventListener('click', () => b.setAttribute('aria-checked', String(b.getAttribute('aria-checked') !== 'true'))));
35
+ root.querySelectorAll('.sp-nav').forEach((nav) => nav.querySelectorAll('.sp-nav__item').forEach((b) =>
36
+ b.addEventListener('click', () => {
37
+ nav.querySelectorAll('.sp-nav__item').forEach((x) => x.removeAttribute('aria-current'));
38
+ b.setAttribute('aria-current', 'page');
39
+ })));
40
+ }
41
+
42
+ /**
43
+ * Wraps each chip's text in .sp-chip__label so it reserves the width of its
44
+ * bold (selected) form; the chip then never changes size when toggled.
45
+ */
46
+ export function stabilizePopChips(root = document) {
47
+ root.querySelectorAll('.sp-chip').forEach((chip) => {
48
+ if (chip.querySelector('.sp-chip__label')) return;
49
+ for (const node of [...chip.childNodes]) {
50
+ if (node.nodeType !== Node.TEXT_NODE || !node.textContent.trim()) continue;
51
+ const label = document.createElement('span');
52
+ label.className = 'sp-chip__label';
53
+ label.dataset.label = node.textContent.trim();
54
+ label.textContent = node.textContent.trim();
55
+ node.replaceWith(label);
56
+ }
57
+ });
58
+ }
59
+
60
+ let snackTimer;
61
+ /**
62
+ * Shows a floating ink snackbar: 3 s, or 6 s with an action. Only for
63
+ * confirmations ("Saved", "Deleted · Undo"); never for form errors.
64
+ */
65
+ export function showPopSnack(message, { actionLabel, onAction } = {}) {
66
+ document.querySelector('.sp-snack-host')?.remove();
67
+ const host = document.createElement('div');
68
+ host.className = 'sp-root sp-snack-host';
69
+ host.setAttribute('role', 'status');
70
+ host.style.cssText = 'position:fixed;left:16px;right:16px;bottom:16px;z-index:1000;max-width:560px;margin:0 auto';
71
+ host.innerHTML = `<div class="sp-snackbar">${esc(message)}${actionLabel ? `<button type="button">${esc(actionLabel)}</button>` : ''}</div>`;
72
+ document.body.append(host);
73
+ host.querySelector('button')?.addEventListener('click', () => { onAction?.(); host.remove(); });
74
+ clearTimeout(snackTimer);
75
+ snackTimer = setTimeout(() => host.remove(), actionLabel ? tokens.motion.snackbarWithAction : tokens.motion.snackbar);
76
+ }
77
+
78
+ /**
79
+ * Opens a <dialog class="sp-dialog"> or <dialog class="sp-sheet"> modally.
80
+ * Elements inside with [data-sp-close] close it.
81
+ */
82
+ export function openPop(dialog) {
83
+ dialog.querySelectorAll('[data-sp-close]').forEach((b) => b.addEventListener('click', () => dialog.close(), { once: true }));
84
+ if (typeof dialog.showModal === 'function') dialog.showModal();
85
+ }
86
+
87
+ /**
88
+ * Runs a coach-mark tour: a 72% ink scrim with a rounded, yellow-outlined
89
+ * cut-out around each step's target and a tilted yellow tour card on the
90
+ * roomier side. Resolves true when finished, false when skipped.
91
+ * steps: [{ target: Element | selector, title, body }]
92
+ */
93
+ export function showPopTour(steps) {
94
+ return new Promise((resolve) => {
95
+ let i = 0;
96
+ // One overlay for the whole tour: steps move the spotlight and swap the
97
+ // card's text, so the scrim never disappears between steps.
98
+ const layer = document.createElement('div');
99
+ layer.className = 'sp-root';
100
+ layer.style.cssText = 'position:fixed;inset:0;z-index:1000';
101
+ layer.innerHTML = `
102
+ <div data-hole style="position:fixed;border:3px solid var(--sp-color-yellow);border-radius:var(--sp-radius-spotlight);box-shadow:0 0 0 100vmax var(--sp-color-scrim)"></div>
103
+ <div class="sp-tour-card" role="dialog" aria-modal="true" aria-labelledby="sp-tour-title"
104
+ style="position:fixed;left:16px;right:16px;max-width:420px;margin:0 auto">
105
+ <div style="display:flex;align-items:center;justify-content:space-between">
106
+ <div class="sp-dots" data-dots></div>
107
+ <button type="button" class="sp-text-button sp-text-button--underline" data-skip>Skip</button>
108
+ </div>
109
+ <div class="sp-text-sheet-title" id="sp-tour-title" data-title></div>
110
+ <div class="sp-text-body" data-body></div>
111
+ <button type="button" class="sp-button" data-next></button>
112
+ </div>`;
113
+ document.body.append(layer);
114
+ const hole = layer.querySelector('[data-hole]');
115
+ const card = layer.querySelector('.sp-tour-card');
116
+ const close = (done) => { layer.remove(); removeEventListener('resize', place); resolve(done); };
117
+ layer.querySelector('[data-skip]').addEventListener('click', () => close(false));
118
+ layer.querySelector('[data-next]').addEventListener('click', () => {
119
+ if (i === steps.length - 1) close(true);
120
+ else { i++; render(); }
121
+ });
122
+
123
+ function target() {
124
+ const t = steps[i].target;
125
+ return typeof t === 'string' ? document.querySelector(t) : t;
126
+ }
127
+
128
+ function place() {
129
+ const r = target()?.getBoundingClientRect();
130
+ const pad = 8;
131
+ if (r) {
132
+ Object.assign(hole.style, { left: `${r.left - pad}px`, top: `${r.top - pad}px`, width: `${r.width + pad * 2}px`, height: `${r.height + pad * 2}px`, border: '' });
133
+ } else {
134
+ Object.assign(hole.style, { left: '50%', top: '50%', width: '0', height: '0', border: '0' });
135
+ }
136
+ const below = !r || r.top + r.height / 2 < innerHeight / 2;
137
+ card.style.top = below ? `${(r ? r.bottom + pad : 80) + 16}px` : '';
138
+ card.style.bottom = below ? '' : `${innerHeight - r.top + pad + 16}px`;
139
+ }
140
+
141
+ function render() {
142
+ const step = steps[i];
143
+ const last = i === steps.length - 1;
144
+ target()?.scrollIntoView({ block: 'center', behavior: 'instant' });
145
+ layer.querySelector('[data-dots]').innerHTML = steps.map((_, k) => `<i class="${k < i ? 'is-reached' : k === i ? 'is-current' : ''}"></i>`).join('');
146
+ layer.querySelector('[data-dots]').setAttribute('aria-label', `Step ${i + 1} of ${steps.length}`);
147
+ layer.querySelector('[data-skip]').hidden = last;
148
+ layer.querySelector('[data-title]').textContent = step.title;
149
+ layer.querySelector('[data-body]').textContent = step.body;
150
+ layer.querySelector('[data-next]').textContent = last ? 'Got it' : 'Next';
151
+ card.style.transform = `rotate(${i % 2 ? 1.5 : -1.5}deg)`;
152
+ // Measure after the scroll has been applied.
153
+ requestAnimationFrame(place);
154
+ place();
155
+ layer.querySelector('[data-next]').focus({ preventScroll: true });
156
+ }
157
+
158
+ addEventListener('resize', place);
159
+ render();
160
+ });
161
+ }
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // Add menu (speed dial on the nav add button)
165
+
166
+ const DIAL_TILTS = { fan: [-3, 2, -2, 3], stack: [-2, 2] };
167
+
168
+ /**
169
+ * Places the options of one add menu: a fan (an arc above the button, the
170
+ * default) or, with .sp-dial--stack, a column. Call again after changing the
171
+ * layout class or the options.
172
+ */
173
+ export function layoutPopDial(dial) {
174
+ const options = [...dial.querySelectorAll('.sp-dial__option')];
175
+ const n = options.length;
176
+ const stack = dial.classList.contains('sp-dial--stack');
177
+ const tilts = DIAL_TILTS[stack ? 'stack' : 'fan'];
178
+ options.forEach((o, i) => {
179
+ let x = 0;
180
+ let y;
181
+ if (stack) {
182
+ y = -(96 + i * 76);
183
+ } else {
184
+ // Spread over 120° (64° for two); the middle option sits highest.
185
+ const span = n <= 1 ? 0 : n === 2 ? 64 : 120;
186
+ const deg = 90 + span / 2 - (n <= 1 ? 0 : (span * i) / (n - 1));
187
+ const a = (deg * Math.PI) / 180;
188
+ x = Math.round(96 * Math.cos(a));
189
+ y = -Math.round(66 + 70 * Math.sin(a));
190
+ }
191
+ o.style.setProperty('--x', `${x}px`);
192
+ o.style.setProperty('--y', `${y}px`);
193
+ o.style.setProperty('--tilt', `${tilts[i % tilts.length]}deg`);
194
+ o.style.setProperty('--i', String(i));
195
+ o.style.setProperty('--ri', String(n - 1 - i));
196
+ });
197
+ }
198
+
199
+ const motionScale = (el) => Number(getComputedStyle(el).getPropertyValue('--sp-motion-scale')) || 1;
200
+
201
+ /**
202
+ * Wires every [data-pop-dial] in `root`. The add button toggles the menu;
203
+ * Escape, a tap on the scrim or focus leaving the menu closes it; arrow keys
204
+ * move between options. Choosing an option fires a bubbling
205
+ * `pop-dial-select` event ({ value, label }) on the dial, presses the option
206
+ * into its shadow, then closes the menu.
207
+ */
208
+ export function wirePopDials(root = document) {
209
+ root.querySelectorAll('[data-pop-dial]').forEach((dial) => {
210
+ if (dial.dataset.popDialWired) return;
211
+ dial.dataset.popDialWired = '1';
212
+ const button = dial.querySelector('.sp-add');
213
+ const menu = dial.querySelector('.sp-dial__menu');
214
+ const options = [...menu.querySelectorAll('.sp-dial__option')];
215
+ if (!menu.id) menu.id = `sp-dial-${Math.random().toString(36).slice(2, 8)}`;
216
+ menu.setAttribute('role', 'menu');
217
+ options.forEach((o) => { o.setAttribute('role', 'menuitem'); o.tabIndex = -1; });
218
+ button.setAttribute('aria-haspopup', 'menu');
219
+ button.setAttribute('aria-controls', menu.id);
220
+ button.setAttribute('aria-expanded', 'false');
221
+ const closedLabel = button.getAttribute('aria-label') || 'Add';
222
+ const openLabel = dial.dataset.closeLabel || 'Close add menu';
223
+ layoutPopDial(dial);
224
+
225
+ const host = dial.closest('[data-pop-dial-root]');
226
+ const scrim = document.createElement('div');
227
+ scrim.className = host ? 'sp-dial-scrim' : 'sp-dial-scrim sp-dial-scrim--page';
228
+ (host ?? document.body).appendChild(scrim);
229
+
230
+ let open = false;
231
+ const set = (next, { focus = true } = {}) => {
232
+ if (next === open) return;
233
+ open = next;
234
+ dial.toggleAttribute('data-open', open);
235
+ scrim.toggleAttribute('data-open', open);
236
+ button.setAttribute('aria-expanded', String(open));
237
+ button.setAttribute('aria-label', open ? openLabel : closedLabel);
238
+ options.forEach((o) => { o.tabIndex = open ? 0 : -1; });
239
+ if (focus) (open ? options[0] : button)?.focus({ preventScroll: true });
240
+ };
241
+
242
+ button.addEventListener('click', () => set(!open, { focus: open || button.matches(':focus-visible') }));
243
+ scrim.addEventListener('click', () => set(false, { focus: false }));
244
+ dial.addEventListener('keydown', (e) => {
245
+ if (!open) return;
246
+ if (e.key === 'Escape') { e.preventDefault(); set(false); return; }
247
+ const i = options.indexOf(document.activeElement);
248
+ if (i < 0) return;
249
+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key];
250
+ if (step) { e.preventDefault(); options[(i + step + options.length) % options.length].focus(); }
251
+ if (e.key === 'Home') { e.preventDefault(); options[0].focus(); }
252
+ if (e.key === 'End') { e.preventDefault(); options.at(-1).focus(); }
253
+ });
254
+ dial.addEventListener('focusout', (e) => {
255
+ if (open && e.relatedTarget && !dial.contains(e.relatedTarget)) set(false, { focus: false });
256
+ });
257
+ options.forEach((o) => o.addEventListener('click', () => {
258
+ o.toggleAttribute('data-chosen', true);
259
+ const label = o.querySelector('.sp-dial__label')?.textContent ?? '';
260
+ dial.dispatchEvent(new CustomEvent('pop-dial-select', { bubbles: true, detail: { value: o.dataset.value ?? label, label } }));
261
+ setTimeout(() => { set(false); o.removeAttribute('data-chosen'); }, tokens.motion.dialPress * motionScale(dial));
262
+ }));
263
+ dial.popDial = { open: () => set(true, { focus: false }), close: () => set(false, { focus: false }), get isOpen() { return open; } };
264
+ });
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Menus and selects (popovers)
269
+
270
+ const EDGE = tokens.space.sm;
271
+
272
+ /**
273
+ * Places a popover next to its anchor: below, lined up with the anchor's
274
+ * trailing edge (`align: 'end'`, menus) or leading edge (`'start'`, selects),
275
+ * flipped above when there's no room, and kept 8 from the window edges.
276
+ */
277
+ export function placePopover(pop, anchor, { align = 'end', matchWidth = false } = {}) {
278
+ const a = anchor.getBoundingClientRect();
279
+ if (matchWidth) pop.style.minWidth = `${Math.max(a.width, tokens.size.menuMinWidth)}px`;
280
+ const w = pop.offsetWidth;
281
+ const h = pop.offsetHeight;
282
+ const vw = document.documentElement.clientWidth;
283
+ const vh = window.innerHeight;
284
+ let x = align === 'end' ? a.right - w : a.left;
285
+ x = Math.min(Math.max(x, EDGE), Math.max(EDGE, vw - w - EDGE));
286
+ const below = a.bottom + EDGE;
287
+ const above = below + h > vh - EDGE && a.top - EDGE - h >= EDGE;
288
+ const y = above ? a.top - EDGE - h : Math.min(below, Math.max(EDGE, vh - h - EDGE));
289
+ pop.style.left = `${Math.round(x)}px`;
290
+ pop.style.top = `${Math.round(y)}px`;
291
+ pop.classList.toggle('is-above', above);
292
+ }
293
+
294
+ /** Keeps an open popover next to its anchor while the page scrolls or resizes. */
295
+ function follow(pop, anchor, opts) {
296
+ const place = () => pop.matches(':popover-open') && placePopover(pop, anchor, opts);
297
+ pop.addEventListener('toggle', (e) => {
298
+ if (e.newState === 'open') {
299
+ window.addEventListener('scroll', place, true);
300
+ window.addEventListener('resize', place);
301
+ } else {
302
+ window.removeEventListener('scroll', place, true);
303
+ window.removeEventListener('resize', place);
304
+ }
305
+ });
306
+ }
307
+
308
+ /** Arrow keys, Home and End move focus between `items`. */
309
+ function roveFocus(container, items) {
310
+ container.addEventListener('keydown', (e) => {
311
+ const list = items().filter((x) => !x.disabled && x.getAttribute('aria-disabled') !== 'true');
312
+ const i = list.indexOf(document.activeElement);
313
+ const to = { ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: list.length - 1 }[e.key];
314
+ if (to === undefined || !list.length) return;
315
+ e.preventDefault();
316
+ list[(to + list.length) % list.length].focus();
317
+ });
318
+ }
319
+
320
+ const supportsPopover = typeof HTMLElement !== 'undefined' && 'popover' in HTMLElement.prototype;
321
+
322
+ /**
323
+ * Wires every `.sp-menu[popover]` in `root` that a `[popovertarget]` button
324
+ * opens: positions it under the button (trailing edges lined up), moves focus
325
+ * to the first item, arrow keys move between items, and picking an item
326
+ * closes it. The browser handles Escape and taps outside.
327
+ */
328
+ export function wirePopMenus(root = document) {
329
+ if (!supportsPopover) return;
330
+ root.querySelectorAll('.sp-menu[popover]:not(.sp-select__list)').forEach((menu) => {
331
+ if (menu.dataset.popWired) return;
332
+ menu.dataset.popWired = '1';
333
+ if (!menu.getAttribute('role')) menu.setAttribute('role', 'menu');
334
+ const items = () => [...menu.querySelectorAll('.sp-menu__item')];
335
+ items().forEach((it) => { if (!it.getAttribute('role')) it.setAttribute('role', 'menuitem'); });
336
+ const invoker = () => document.querySelector(`[popovertarget="${CSS.escape(menu.id)}"]`);
337
+ invoker()?.setAttribute('aria-haspopup', 'menu');
338
+ menu.addEventListener('toggle', (e) => {
339
+ const button = invoker();
340
+ button?.setAttribute('aria-expanded', String(e.newState === 'open'));
341
+ if (e.newState !== 'open' || !button) return;
342
+ placePopover(menu, button, { align: 'end' });
343
+ items().find((x) => !x.disabled)?.focus({ preventScroll: true });
344
+ });
345
+ const button = invoker();
346
+ if (button) follow(menu, button, { align: 'end' });
347
+ roveFocus(menu, items);
348
+ menu.addEventListener('keydown', (e) => { if (e.key === 'Tab') menu.hidePopover(); });
349
+ menu.addEventListener('click', (e) => {
350
+ const item = e.target.closest('.sp-menu__item');
351
+ if (item && !item.disabled && item.getAttribute('aria-disabled') !== 'true') menu.hidePopover();
352
+ });
353
+ });
354
+ }
355
+
356
+ let popSeq = 0;
357
+
358
+ /**
359
+ * Turns every native `select.sp-select` in `root` into a Sticker Pop select:
360
+ * a field-style trigger and a listbox popover of sticker rows (the chosen one
361
+ * yellow with a tick). The native select stays in the DOM and in sync, so
362
+ * forms, `change` events and `select.value` keep working. Options can carry
363
+ * `data-icon` (a Material Symbols name) and `data-caption`; an option with
364
+ * `value=""` is the placeholder. Without popover support the native select is
365
+ * left as it is (still styled).
366
+ */
367
+ export function wirePopSelects(root = document) {
368
+ if (!supportsPopover) return;
369
+ root.querySelectorAll('select.sp-select').forEach((select) => {
370
+ if (select.dataset.popWired) return;
371
+ select.dataset.popWired = '1';
372
+ const n = ++popSeq;
373
+ const wrap = document.createElement('div');
374
+ wrap.className = 'sp-select-wrap';
375
+ select.before(wrap);
376
+ wrap.append(select);
377
+ select.tabIndex = -1;
378
+ select.setAttribute('aria-hidden', 'true');
379
+
380
+ const trigger = document.createElement('button');
381
+ trigger.type = 'button';
382
+ trigger.className = 'sp-select__trigger';
383
+ trigger.setAttribute('aria-haspopup', 'listbox');
384
+ trigger.setAttribute('aria-expanded', 'false');
385
+ const list = document.createElement('div');
386
+ list.className = 'sp-menu sp-select__list';
387
+ list.id = `sp-select-list-${n}`;
388
+ list.setAttribute('role', 'listbox');
389
+ list.popover = 'auto';
390
+ trigger.setAttribute('aria-controls', list.id);
391
+ trigger.popoverTargetElement = list;
392
+ wrap.append(trigger, list);
393
+
394
+ const label = select.id ? document.querySelector(`label[for="${CSS.escape(select.id)}"]`) : null;
395
+ const valueId = `sp-select-value-${n}`;
396
+ if (label) {
397
+ label.id ||= `sp-select-label-${n}`;
398
+ trigger.setAttribute('aria-labelledby', `${label.id} ${valueId}`);
399
+ label.addEventListener('click', (e) => { e.preventDefault(); trigger.focus(); });
400
+ } else if (select.getAttribute('aria-label')) {
401
+ trigger.setAttribute('aria-label', select.getAttribute('aria-label'));
402
+ }
403
+
404
+ const rows = () => [...list.querySelectorAll('.sp-menu__item')];
405
+ const build = () => {
406
+ list.replaceChildren(...[...select.options].filter((o) => o.value !== '' && !o.hidden).map((o) => {
407
+ const row = document.createElement('div');
408
+ row.className = 'sp-menu__item';
409
+ row.setAttribute('role', 'option');
410
+ row.tabIndex = -1;
411
+ row.dataset.value = o.value;
412
+ if (o.disabled) row.setAttribute('aria-disabled', 'true');
413
+ row.innerHTML = `${o.dataset.icon ? `<span class="sp-icon" aria-hidden="true">${esc(o.dataset.icon)}</span>` : ''}<span class="sp-menu__text"><span class="sp-menu__label">${esc(o.textContent.trim())}</span>${o.dataset.caption ? `<span class="sp-menu__caption">${esc(o.dataset.caption)}</span>` : ''}</span><span class="sp-icon sp-menu__check" aria-hidden="true">check</span>`;
414
+ return row;
415
+ }));
416
+ };
417
+ const render = () => {
418
+ const o = select.selectedOptions[0];
419
+ const placeholder = !o || o.value === '';
420
+ const icon = !placeholder && o.dataset.icon ? `<span class="sp-icon" aria-hidden="true">${esc(o.dataset.icon)}</span>` : '';
421
+ trigger.innerHTML = `${icon}<span class="sp-select__value${placeholder ? ' is-placeholder' : ''}" id="${valueId}">${esc(o?.textContent.trim() ?? '')}</span><span class="sp-icon sp-select__chevron" aria-hidden="true">expand_more</span>`;
422
+ trigger.disabled = select.disabled;
423
+ wrap.classList.toggle('is-invalid', select.getAttribute('aria-invalid') === 'true');
424
+ rows().forEach((r) => r.setAttribute('aria-selected', String(r.dataset.value === select.value && !placeholder)));
425
+ };
426
+ const pick = (row) => {
427
+ if (!row || row.getAttribute('aria-disabled') === 'true') return;
428
+ if (select.value !== row.dataset.value) {
429
+ select.value = row.dataset.value;
430
+ select.dispatchEvent(new Event('input', { bubbles: true }));
431
+ select.dispatchEvent(new Event('change', { bubbles: true }));
432
+ }
433
+ render();
434
+ list.hidePopover();
435
+ };
436
+
437
+ build();
438
+ render();
439
+ follow(list, trigger, { align: 'start', matchWidth: true });
440
+ roveFocus(list, rows);
441
+ list.addEventListener('toggle', (e) => {
442
+ const open = e.newState === 'open';
443
+ trigger.setAttribute('aria-expanded', String(open));
444
+ if (open) {
445
+ placePopover(list, trigger, { align: 'start', matchWidth: true });
446
+ const current = rows().find((r) => r.getAttribute('aria-selected') === 'true') ?? rows()[0];
447
+ current?.focus({ preventScroll: true });
448
+ current?.scrollIntoView({ block: 'nearest' });
449
+ } else if (list.contains(document.activeElement) || document.activeElement === document.body) {
450
+ trigger.focus({ preventScroll: true });
451
+ }
452
+ });
453
+ list.addEventListener('click', (e) => pick(e.target.closest('.sp-menu__item')));
454
+ let typed = '';
455
+ let typedAt = 0;
456
+ list.addEventListener('keydown', (e) => {
457
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(document.activeElement.closest?.('.sp-menu__item')); return; }
458
+ if (e.key === 'Tab') { list.hidePopover(); return; }
459
+ if (e.key.length === 1 && /\S/.test(e.key)) {
460
+ // Type-ahead: jump to the first option starting with what was typed.
461
+ typed = Date.now() - typedAt > 700 ? e.key : typed + e.key;
462
+ typedAt = Date.now();
463
+ rows().find((r) => r.textContent.trim().toLowerCase().startsWith(typed.toLowerCase()))?.focus();
464
+ }
465
+ });
466
+ trigger.addEventListener('keydown', (e) => {
467
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); list.showPopover(); }
468
+ });
469
+ select.addEventListener('change', render);
470
+ new MutationObserver(() => { build(); render(); }).observe(select, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled', 'aria-invalid'] });
471
+ select.popSelect = { refresh: () => { build(); render(); } };
472
+ });
473
+ }
474
+
475
+ // ---------------------------------------------------------------------------
476
+ // Top app bar
477
+
478
+ function scrollParent(el) {
479
+ for (let p = el.parentElement; p; p = p.parentElement) {
480
+ const o = getComputedStyle(p).overflowY;
481
+ if ((o === 'auto' || o === 'scroll') && p.scrollHeight > p.clientHeight) return p;
482
+ }
483
+ return window;
484
+ }
485
+
486
+ /**
487
+ * Gives every `.sp-top-bar` in `root` its scrolled look (paper fill, ink line
488
+ * along the bottom) while content is scrolled under it. Watches the bar's
489
+ * nearest scrolling ancestor, or the window.
490
+ */
491
+ export function wirePopTopBars(root = document) {
492
+ root.querySelectorAll('.sp-top-bar').forEach((bar) => {
493
+ if (bar.dataset.popWired) return;
494
+ bar.dataset.popWired = '1';
495
+ const scroller = scrollParent(bar);
496
+ const update = () => {
497
+ const y = scroller === window ? window.scrollY : scroller.scrollTop;
498
+ bar.classList.toggle('is-scrolled', y > 0);
499
+ };
500
+ scroller.addEventListener('scroll', update, { passive: true });
501
+ update();
502
+ });
503
+ }
504
+
505
+ // ---------------------------------------------------------------------------
506
+ // Search field
507
+
508
+ /** Shows each `.sp-search` clear button while its input has text; the button empties the input and keeps focus there. */
509
+ export function wirePopSearch(root = document) {
510
+ root.querySelectorAll('.sp-search').forEach((box) => {
511
+ if (box.dataset.popWired) return;
512
+ box.dataset.popWired = '1';
513
+ const input = box.querySelector('input');
514
+ const clear = box.querySelector('.sp-search__clear');
515
+ if (!input || !clear) return;
516
+ const sync = () => { clear.hidden = !input.value; };
517
+ input.addEventListener('input', sync);
518
+ clear.addEventListener('click', () => {
519
+ input.value = '';
520
+ input.dispatchEvent(new Event('input', { bubbles: true }));
521
+ input.focus();
522
+ });
523
+ sync();
524
+ });
525
+ }
526
+
527
+ // ---------------------------------------------------------------------------
528
+ // Dates
529
+
530
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
531
+ const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
532
+ const dayOnly = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
533
+ const sameDay = (a, b) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
534
+
535
+ /** Makes each `.sp-date-tiles` group single-select: the pressed tile gets aria-pressed="true". */
536
+ export function wirePopDateTiles(root = document) {
537
+ root.querySelectorAll('.sp-date-tiles').forEach((group) => {
538
+ if (group.dataset.popWired) return;
539
+ group.dataset.popWired = '1';
540
+ group.addEventListener('click', (e) => {
541
+ const tile = e.target.closest('.sp-date-tile[aria-pressed]');
542
+ if (!tile) return;
543
+ group.querySelectorAll('.sp-date-tile[aria-pressed]').forEach((t) => t.setAttribute('aria-pressed', String(t === tile)));
544
+ });
545
+ });
546
+ }
547
+
548
+ /**
549
+ * Renders a month calendar into `el` and keeps it interactive: previous /
550
+ * next month, a 7-column grid of day buttons (chosen: yellow; today: ink
551
+ * ring), arrow keys to move by day or week, Enter to pick. Returns
552
+ * `{ get value, set(date) }`.
553
+ *
554
+ * With `range: true` it picks a span of days instead: the first pick sets
555
+ * the start, the second the end (an earlier day moves the start), a third
556
+ * starts again; start and end are yellow, joined by a mint band.
557
+ * `onChange(start, end)` gets both (end null until the second pick); the
558
+ * result also has `get start` and `get end`.
559
+ */
560
+ export function mountPopCalendar(el, { value = null, today = new Date(), min = null, max = null, firstWeekday = 1, onChange = () => {}, range = false, start = null, end = null } = {}) {
561
+ let selected = value ? dayOnly(value) : null;
562
+ let from = start ? dayOnly(start) : null;
563
+ let to = end ? dayOnly(end) : null;
564
+ const anchor = range ? from : selected;
565
+ let month = new Date((anchor ?? today).getFullYear(), (anchor ?? today).getMonth(), 1);
566
+ let focusDay = null;
567
+ const t = dayOnly(today);
568
+ const lo = min ? dayOnly(min) : null;
569
+ const hi = max ? dayOnly(max) : null;
570
+ const ok = (d) => (!lo || d >= lo) && (!hi || d <= hi);
571
+ const render = () => {
572
+ const lead = (month.getDay() - firstWeekday + 7) % 7;
573
+ const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
574
+ const canPrev = !lo || new Date(month.getFullYear(), month.getMonth(), 0) >= lo;
575
+ const canNext = !hi || new Date(month.getFullYear(), month.getMonth() + 1, 1) <= hi;
576
+ const heads = Array.from({ length: 7 }, (_, i) => `<span class="sp-calendar__weekday" aria-hidden="true">${WEEKDAYS[(firstWeekday + 6 + i) % 7][0]}</span>`).join('');
577
+ const blanks = '<span></span>'.repeat(lead);
578
+ const cells = Array.from({ length: days }, (_, i) => {
579
+ const d = new Date(month.getFullYear(), month.getMonth(), i + 1);
580
+ const isStart = range && sameDay(d, from);
581
+ const isEnd = range && sameDay(d, to);
582
+ const inside = range && from && to && d > from && d < to;
583
+ const role = isStart && isEnd ? ', start and end' : isStart ? ', start' : isEnd ? ', end' : inside ? ', in range' : '';
584
+ const label = `${i + 1} ${MONTHS[d.getMonth()]} ${d.getFullYear()}${sameDay(d, t) ? ', today' : ''}${role}`;
585
+ const pressed = range ? isStart || isEnd : sameDay(d, selected);
586
+ const button = `<button type="button" class="sp-calendar__day${sameDay(d, t) ? ' is-today' : ''}" data-day="${i + 1}" aria-pressed="${pressed}" aria-label="${label}"${ok(d) ? '' : ' disabled'} tabindex="-1">${i + 1}</button>`;
587
+ if (!range) return button;
588
+ const joined = to && !sameDay(from, to);
589
+ const band = !joined ? '' : inside ? ' is-in' : isStart ? ' is-start' : isEnd ? ' is-end' : '';
590
+ return `<span class="sp-calendar__cell${band}">${button}</span>`;
591
+ }).join('');
592
+ el.innerHTML = `<div class="sp-calendar"><div class="sp-calendar__head"><h3 class="sp-calendar__title" aria-live="polite">${MONTHS[month.getMonth()]} ${month.getFullYear()}</h3><button type="button" class="sp-icon-button" data-nav="-1" aria-label="Previous month"${canPrev ? '' : ' disabled'}><span class="sp-icon">chevron_left</span></button><button type="button" class="sp-icon-button" data-nav="1" aria-label="Next month"${canNext ? '' : ' disabled'}><span class="sp-icon">chevron_right</span></button></div><div class="sp-calendar__grid">${heads}${blanks}${cells}</div></div>`;
593
+ const buttons = [...el.querySelectorAll('.sp-calendar__day')];
594
+ const target = buttons.find((b) => focusDay && +b.dataset.day === focusDay.getDate() && focusDay.getMonth() === month.getMonth())
595
+ ?? buttons.find((b) => b.getAttribute('aria-pressed') === 'true') ?? buttons.find((b) => b.classList.contains('is-today')) ?? buttons.find((b) => !b.disabled);
596
+ if (target) target.tabIndex = 0;
597
+ if (focusDay && target) target.focus();
598
+ };
599
+ el.addEventListener('click', (e) => {
600
+ const nav = e.target.closest('[data-nav]');
601
+ if (nav) { month = new Date(month.getFullYear(), month.getMonth() + Number(nav.dataset.nav), 1); focusDay = null; render(); return; }
602
+ const day = e.target.closest('.sp-calendar__day');
603
+ if (!day || day.disabled) return;
604
+ const picked = new Date(month.getFullYear(), month.getMonth(), Number(day.dataset.day));
605
+ focusDay = picked;
606
+ if (range) {
607
+ if (!from || to || picked < from) { from = picked; to = null; } else { to = picked; }
608
+ render();
609
+ onChange(from, to);
610
+ return;
611
+ }
612
+ selected = picked;
613
+ render();
614
+ onChange(selected);
615
+ });
616
+ el.addEventListener('keydown', (e) => {
617
+ const day = e.target.closest('.sp-calendar__day');
618
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[e.key];
619
+ if (!day || step === undefined) return;
620
+ e.preventDefault();
621
+ const d = new Date(month.getFullYear(), month.getMonth(), Number(day.dataset.day) + step);
622
+ if (!ok(d)) return;
623
+ focusDay = d;
624
+ if (d.getMonth() !== month.getMonth() || d.getFullYear() !== month.getFullYear()) month = new Date(d.getFullYear(), d.getMonth(), 1);
625
+ render();
626
+ });
627
+ render();
628
+ return { get value() { return selected; }, get start() { return from; }, get end() { return to; }, set(d) { selected = d ? dayOnly(d) : null; if (d) month = new Date(d.getFullYear(), d.getMonth(), 1); render(); } };
629
+ }
630
+
631
+ // ---------------------------------------------------------------------------
632
+ // Tabs
633
+
634
+ /**
635
+ * Wires each `.sp-tabs[role=tablist]`: clicking or arrow keys select a tab
636
+ * (aria-selected, roving tabindex), and a tab's `aria-controls` panel is
637
+ * shown while the others are hidden.
638
+ */
639
+ export function wirePopTabs(root = document) {
640
+ root.querySelectorAll('.sp-tabs[role="tablist"]').forEach((list) => {
641
+ if (list.dataset.popWired) return;
642
+ list.dataset.popWired = '1';
643
+ const tabs = () => [...list.querySelectorAll('[role="tab"]')];
644
+ const select = (tab, focus) => {
645
+ tabs().forEach((t) => {
646
+ const on = t === tab;
647
+ t.setAttribute('aria-selected', String(on));
648
+ t.tabIndex = on ? 0 : -1;
649
+ const panel = t.getAttribute('aria-controls') && document.getElementById(t.getAttribute('aria-controls'));
650
+ if (panel) panel.hidden = !on;
651
+ });
652
+ if (focus) tab.focus();
653
+ list.dispatchEvent(new CustomEvent('pop-tab-change', { bubbles: true, detail: { index: tabs().indexOf(tab) } }));
654
+ };
655
+ list.addEventListener('click', (e) => { const t = e.target.closest('[role="tab"]'); if (t) select(t, false); });
656
+ list.addEventListener('keydown', (e) => {
657
+ const all = tabs();
658
+ const i = all.indexOf(document.activeElement);
659
+ const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: all.length - 1 }[e.key];
660
+ if (i < 0 || to === undefined) return;
661
+ e.preventDefault();
662
+ select(all[(to + all.length) % all.length], true);
663
+ });
664
+ select(tabs().find((t) => t.getAttribute('aria-selected') === 'true') ?? tabs()[0], false);
665
+ });
666
+ }
667
+
668
+ // ---------------------------------------------------------------------------
669
+ // Slider
670
+
671
+ /** Keeps each `.sp-slider`'s mint fill (--sp-slider-fill) in step with its range input. */
672
+ export function wirePopSliders(root = document) {
673
+ root.querySelectorAll('.sp-slider').forEach((box) => {
674
+ const input = box.querySelector('input[type="range"]');
675
+ if (!input || box.dataset.popWired) return;
676
+ box.dataset.popWired = '1';
677
+ const sync = () => {
678
+ const min = Number(input.min || 0);
679
+ const max = Number(input.max || 100);
680
+ box.style.setProperty('--sp-slider-fill', String(max === min ? 0 : (Number(input.value) - min) / (max - min)));
681
+ };
682
+ input.addEventListener('input', sync);
683
+ sync();
684
+ });
685
+ }
686
+
687
+ // ---------------------------------------------------------------------------
688
+ // Stepper
689
+
690
+ /**
691
+ * Wires each `.sp-stepper` (data-min, data-max, data-step, a value in
692
+ * `.sp-stepper__value`): the − and + buttons step it, disable at the limits,
693
+ * and fire a bubbling `pop-step` event with `{ value }`.
694
+ */
695
+ export function wirePopSteppers(root = document) {
696
+ root.querySelectorAll('.sp-stepper').forEach((box) => {
697
+ if (box.dataset.popWired) return;
698
+ box.dataset.popWired = '1';
699
+ const out = box.querySelector('.sp-stepper__value');
700
+ const [down, up] = box.querySelectorAll('button');
701
+ const min = Number(box.dataset.min ?? 0);
702
+ const max = Number(box.dataset.max ?? 99);
703
+ const step = Number(box.dataset.step ?? 1);
704
+ let value = Number(out.textContent);
705
+ const render = () => {
706
+ out.textContent = String(value);
707
+ down.disabled = value - step < min;
708
+ up.disabled = value + step > max;
709
+ };
710
+ const set = (v) => { value = v; render(); box.dispatchEvent(new CustomEvent('pop-step', { bubbles: true, detail: { value } })); };
711
+ down.addEventListener('click', () => set(value - step));
712
+ up.addEventListener('click', () => set(value + step));
713
+ render();
714
+ });
715
+ }
716
+
717
+ // ---------------------------------------------------------------------------
718
+ // Number keypad
719
+
720
+ /**
721
+ * Wires each `.sp-keypad` (buttons with data-key="0"–"9", "." or "⌫"):
722
+ * clicks fire a bubbling `pop-key` event with `{ key }`. Pair it with
723
+ * `applyPopKey` from format.mjs.
724
+ */
725
+ export function wirePopKeypads(root = document) {
726
+ root.querySelectorAll('.sp-keypad').forEach((pad) => {
727
+ if (pad.dataset.popWired) return;
728
+ pad.dataset.popWired = '1';
729
+ pad.addEventListener('click', (e) => {
730
+ const b = e.target.closest('button[data-key]');
731
+ if (b) pad.dispatchEvent(new CustomEvent('pop-key', { bubbles: true, detail: { key: b.dataset.key } }));
732
+ });
733
+ });
734
+ }
735
+
736
+ // ---------------------------------------------------------------------------
737
+ // Avatar
738
+
739
+ /** Fills each `.sp-avatar[data-name]` with its initials and the colour its name always gets, and labels it. */
740
+ export function wirePopAvatars(root = document) {
741
+ root.querySelectorAll('.sp-avatar[data-name]').forEach((a) => {
742
+ const name = a.dataset.name;
743
+ a.textContent = popInitials(name);
744
+ if (!a.style.getPropertyValue('--sp-avatar-fill')) a.style.setProperty('--sp-avatar-fill', `var(--sp-color-${popAvatarColor(name)})`);
745
+ a.setAttribute('role', 'img');
746
+ a.setAttribute('aria-label', name);
747
+ });
748
+ }
749
+
750
+ // ---------------------------------------------------------------------------
751
+ // Tooltip
752
+
753
+ let tipSeq = 0;
754
+ /**
755
+ * Wires every `[data-tip]` in `root`: a tap or click shows the bubble for
756
+ * 3 s (hover and keyboard focus show it through CSS), and the text is linked
757
+ * with aria-describedby so screen readers hear it.
758
+ */
759
+ export function wirePopTooltips(root = document) {
760
+ root.querySelectorAll('[data-tip]').forEach((el) => {
761
+ if (el.dataset.popWired) return;
762
+ el.dataset.popWired = '1';
763
+ const note = document.createElement('span');
764
+ note.className = 'sp-visually-hidden';
765
+ note.id = `sp-tip-${++tipSeq}`;
766
+ note.textContent = el.dataset.tip;
767
+ el.after(note);
768
+ el.setAttribute('aria-describedby', note.id);
769
+ let timer;
770
+ el.addEventListener('click', () => {
771
+ el.classList.add('is-open');
772
+ clearTimeout(timer);
773
+ timer = setTimeout(() => el.classList.remove('is-open'), tokens.motion.snackbar);
774
+ });
775
+ });
776
+ }
777
+
778
+ // ---------------------------------------------------------------------------
779
+ // Tag input
780
+
781
+ /**
782
+ * Wires each `.sp-tags` (starting tags in data-tags, comma-separated; an
783
+ * optional data-name adds a hidden input for forms): Enter or a comma adds
784
+ * the typed tag as a removable chip, backspace in an empty field removes the
785
+ * last, duplicates are skipped. Fires a bubbling `pop-tags` event with
786
+ * `{ tags }`.
787
+ */
788
+ export function wirePopTagInputs(root = document) {
789
+ root.querySelectorAll('.sp-tags').forEach((box) => {
790
+ if (box.dataset.popWired) return;
791
+ box.dataset.popWired = '1';
792
+ const input = box.querySelector('.sp-tags__input');
793
+ const placeholder = input.placeholder;
794
+ let tags = (box.dataset.tags ?? '').split(',').map((t) => t.trim()).filter(Boolean);
795
+ let hidden = null;
796
+ if (box.dataset.name) {
797
+ hidden = document.createElement('input');
798
+ hidden.type = 'hidden';
799
+ hidden.name = box.dataset.name;
800
+ box.append(hidden);
801
+ }
802
+ const render = () => {
803
+ box.querySelectorAll('.sp-chip').forEach((c) => c.remove());
804
+ for (const t of tags) {
805
+ const chip = document.createElement('span');
806
+ chip.className = 'sp-chip sp-chip--removable';
807
+ chip.innerHTML = `${esc(t)}<button type="button" class="sp-chip__remove" aria-label="Remove ${esc(t)}"><span class="sp-icon" style="font-size:16px">close</span></button>`;
808
+ chip.querySelector('button').addEventListener('click', (e) => { e.stopPropagation(); set(tags.filter((x) => x !== t)); input.focus(); });
809
+ input.before(chip);
810
+ }
811
+ input.placeholder = tags.length ? '' : placeholder;
812
+ if (hidden) hidden.value = tags.join(',');
813
+ };
814
+ const set = (next) => { tags = next; render(); box.dispatchEvent(new CustomEvent('pop-tags', { bubbles: true, detail: { tags: [...tags] } })); };
815
+ const add = () => {
816
+ const t = input.value.replace(/,/g, '').trim();
817
+ input.value = '';
818
+ if (t && !tags.some((x) => x.toLowerCase() === t.toLowerCase())) set([...tags, t]);
819
+ };
820
+ input.addEventListener('keydown', (e) => {
821
+ if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(); }
822
+ if (e.key === 'Backspace' && !input.value && tags.length) set(tags.slice(0, -1));
823
+ });
824
+ input.addEventListener('blur', add);
825
+ box.addEventListener('click', (e) => { if (e.target === box) input.focus(); });
826
+ render();
827
+ });
828
+ }
829
+
830
+ // ---------------------------------------------------------------------------
831
+ // PIN entry
832
+
833
+ /**
834
+ * Draws a `.sp-pin` for `value` (digits typed so far): `length` boxes, dots
835
+ * when `obscure`, the next box outlined, orange when `error`. Labels it for
836
+ * screen readers ("PIN, 2 of 4 entered").
837
+ */
838
+ export function renderPopPin(el, value, { length = Number(el.dataset.length ?? 4), obscure = el.dataset.obscure !== 'false', error = false, label = el.dataset.label ?? 'PIN' } = {}) {
839
+ el.classList.toggle('is-error', !!error);
840
+ el.setAttribute('role', 'status');
841
+ el.setAttribute('aria-label', `${label}, ${value.length} of ${length} entered`);
842
+ el.innerHTML = Array.from({ length }, (_, i) => {
843
+ const filled = i < value.length;
844
+ const cls = `sp-pin__box${filled && obscure ? ' is-dot' : ''}${!error && i === value.length ? ' is-next' : ''}`;
845
+ return `<span class="${cls}" aria-hidden="true">${filled && !obscure ? esc(value[i]) : ''}</span>`;
846
+ }).join('');
847
+ }
848
+
849
+ /**
850
+ * Wires each `.sp-attach` (a label around a file input): when a file is
851
+ * chosen the tile is hidden and a `.sp-attach-file` row shows its name, size
852
+ * and an image thumbnail; Remove clears the input and brings the tile back
853
+ * (focus returns to it). Fires a bubbling `pop-attach` event with `{ file }`
854
+ * (null when removed).
855
+ */
856
+ export function wirePopAttachments(root = document) {
857
+ root.querySelectorAll('.sp-attach').forEach((tile) => {
858
+ if (tile.dataset.popWired) return;
859
+ tile.dataset.popWired = '1';
860
+ const input = tile.querySelector('input[type="file"]');
861
+ if (!input) return;
862
+ let row = null;
863
+ const clear = () => {
864
+ row?.remove();
865
+ row = null;
866
+ input.value = '';
867
+ tile.hidden = false;
868
+ input.focus();
869
+ tile.dispatchEvent(new CustomEvent('pop-attach', { bubbles: true, detail: { file: null } }));
870
+ };
871
+ input.addEventListener('change', () => {
872
+ const file = input.files?.[0];
873
+ if (!file) return;
874
+ row = document.createElement('div');
875
+ row.className = 'sp-attach-file';
876
+ const thumb = document.createElement('span');
877
+ thumb.className = 'sp-attach-file__thumb';
878
+ thumb.setAttribute('aria-hidden', 'true');
879
+ if (file.type.startsWith('image/')) {
880
+ const img = document.createElement('img');
881
+ img.alt = '';
882
+ img.src = URL.createObjectURL(file);
883
+ thumb.append(img);
884
+ } else {
885
+ thumb.innerHTML = '<span class="sp-icon">description</span>';
886
+ }
887
+ const text = document.createElement('span');
888
+ const name = document.createElement('span');
889
+ name.className = 'sp-attach-file__name';
890
+ name.textContent = file.name;
891
+ const size = document.createElement('span');
892
+ size.className = 'sp-attach-file__size';
893
+ size.textContent = file.size >= 1048576 ? `${(file.size / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(file.size / 1024))} KB`;
894
+ size.style.display = 'block';
895
+ text.append(name, size);
896
+ const remove = document.createElement('button');
897
+ remove.type = 'button';
898
+ remove.className = 'sp-attach-file__remove';
899
+ remove.setAttribute('aria-label', `Remove ${file.name}`);
900
+ remove.innerHTML = '<span class="sp-icon">close</span>';
901
+ remove.addEventListener('click', clear);
902
+ row.append(thumb, text, remove);
903
+ tile.hidden = true;
904
+ tile.after(row);
905
+ remove.focus();
906
+ tile.dispatchEvent(new CustomEvent('pop-attach', { bubbles: true, detail: { file } }));
907
+ });
908
+ });
909
+ }
910
+
911
+ /**
912
+ * Pull to refresh for a scrolling element (`.sp-refresh-host`). Pulling down
913
+ * from the top (touch, pen or mouse) moves a `.sp-refresh` sticker down by
914
+ * half the pull, up to 96, filling its ring; letting go past 64 calls
915
+ * `onRefresh()` and spins until its promise settles. Add a visible Refresh
916
+ * button too: the gesture alone isn't reachable by keyboard or screen
917
+ * readers. Returns `{ refresh() }` to run the same flow from that button.
918
+ */
919
+ export function wirePopPullToRefresh(host, onRefresh) {
920
+ const TRIGGER = 64;
921
+ const MAX = 96;
922
+ host.classList.add('sp-refresh-host');
923
+ const ind = document.createElement('div');
924
+ ind.className = 'sp-refresh';
925
+ ind.setAttribute('aria-hidden', 'true');
926
+ ind.innerHTML = '<svg class="sp-refresh__ring" viewBox="0 0 20 20"><circle cx="10" cy="10" r="8.75" pathLength="1"/><circle cx="10" cy="10" r="8.75" pathLength="1"/></svg><span class="sp-spinner" style="width:20px;height:20px"></span>';
927
+ host.prepend(ind);
928
+ const live = document.createElement('span');
929
+ live.className = 'sp-visually-hidden';
930
+ live.setAttribute('role', 'status');
931
+ host.prepend(live);
932
+ let startY = null;
933
+ let pull = 0;
934
+ let busy = false;
935
+ const show = (px) => {
936
+ ind.style.setProperty('--sp-refresh-pull', `${px}px`);
937
+ ind.style.setProperty('--sp-refresh-progress', String(Math.min(px / TRIGGER, 1)));
938
+ };
939
+ const refresh = async () => {
940
+ if (busy) return;
941
+ busy = true;
942
+ ind.classList.remove('is-pulling');
943
+ ind.classList.add('is-refreshing');
944
+ show(TRIGGER);
945
+ live.textContent = 'Refreshing';
946
+ try { await onRefresh(); } finally {
947
+ busy = false;
948
+ ind.classList.remove('is-refreshing');
949
+ show(0);
950
+ live.textContent = 'Refreshed';
951
+ }
952
+ };
953
+ host.addEventListener('pointerdown', (e) => {
954
+ if (busy || host.scrollTop > 0 || (e.pointerType === 'mouse' && e.button !== 0)) return;
955
+ startY = e.clientY;
956
+ pull = 0;
957
+ });
958
+ host.addEventListener('pointermove', (e) => {
959
+ if (startY === null) return;
960
+ const dy = e.clientY - startY;
961
+ if (dy <= 0 || host.scrollTop > 0) { if (pull) { pull = 0; show(0); } return; }
962
+ if (!pull && dy > 8) {
963
+ host.setPointerCapture?.(e.pointerId);
964
+ host.classList.add('is-pulling');
965
+ window.getSelection()?.removeAllRanges();
966
+ }
967
+ pull = Math.min(dy / 2, MAX);
968
+ ind.classList.add('is-pulling');
969
+ show(pull);
970
+ });
971
+ const end = () => {
972
+ if (startY === null) return;
973
+ startY = null;
974
+ host.classList.remove('is-pulling');
975
+ ind.classList.remove('is-pulling');
976
+ if (pull >= TRIGGER) refresh(); else show(0);
977
+ pull = 0;
978
+ };
979
+ host.addEventListener('pointerup', end);
980
+ host.addEventListener('pointercancel', end);
981
+ host.addEventListener('touchmove', (e) => { if (pull > 0) e.preventDefault(); }, { passive: false });
982
+ return { refresh };
983
+ }
984
+
985
+ /**
986
+ * Renders page navigation into `el`: previous / next sticker icon buttons
987
+ * around the page numbers (current page yellow, aria-current="page"), or
988
+ * "Page 3 of 12" between the arrows where the row doesn't fit (a container
989
+ * query at 404). Calls `onChange(page)`; returns `{ get page, set(page) }`.
990
+ */
991
+ export function renderPopPagination(el, { page = 1, count = 1, onChange = () => {} } = {}) {
992
+ el.classList.add('sp-pagination-host');
993
+ let current = page;
994
+ const render = () => {
995
+ const nums = popPageItems(current, count).map((p) => p === null
996
+ ? '<span class="sp-pagination__gap" aria-hidden="true">…</span>'
997
+ : `<button type="button" class="sp-pagination__page" data-page="${p}" aria-label="Page ${p} of ${count}"${p === current ? ' aria-current="page"' : ''}>${p}</button>`).join('');
998
+ el.innerHTML = `<nav class="sp-pagination" aria-label="Pages"><button type="button" class="sp-icon-button" data-page="${current - 1}" aria-label="Previous page"${current <= 1 ? ' disabled' : ''}><span class="sp-icon">chevron_left</span></button><span class="sp-pagination__pages">${nums}</span><span class="sp-pagination__label" aria-live="polite">Page ${current} of ${count}</span><button type="button" class="sp-icon-button" data-page="${current + 1}" aria-label="Next page"${current >= count ? ' disabled' : ''}><span class="sp-icon">chevron_right</span></button></nav>`;
999
+ };
1000
+ el.addEventListener('click', (e) => {
1001
+ const b = e.target.closest('[data-page]');
1002
+ if (!b || b.disabled || b.getAttribute('aria-current')) return;
1003
+ const label = b.getAttribute('aria-label');
1004
+ current = Math.min(Math.max(Number(b.dataset.page), 1), count);
1005
+ render();
1006
+ el.querySelector(`[aria-label="${label}"]:not(:disabled)`)?.focus() ?? el.querySelector('[aria-current]')?.focus();
1007
+ onChange(current);
1008
+ });
1009
+ render();
1010
+ return { get page() { return current; }, set(p) { current = p; render(); } };
1011
+ }