-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsui.js
More file actions
1303 lines (1119 loc) · 46 KB
/
Copy pathsui.js
File metadata and controls
1303 lines (1119 loc) · 46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Speyer UI System (SUI) — Interactive Toolkit
* Version: 3.5.0
* https://github.com/adrianspeyer/speyer-ui
*
* Lightweight, dependency-free behaviors for SUI components.
* CSS handles appearance; this adds interactivity.
*
* Usage:
* <script src="sui.js"></script>
* — Auto-initializes via data-sui-* attributes
* — Or call SUI.modal.open('#id'), SUI.toast.success('msg'), etc.
*
* Made in Canada with love 🇨🇦
* License: MIT
*/
const SUI = (() => {
'use strict';
/* ====================================================================
Helpers
==================================================================== */
const $ = (sel, ctx = document) => ctx.querySelector(sel);
const $$ = (sel, ctx = document) => Array.from(ctx.querySelectorAll(sel));
function uid() {
return 'sui-' + Math.random().toString(36).slice(2, 9);
}
// Handler tracking for destroy() support
function suiOn(root, target, event, fn) {
target.addEventListener(event, fn);
if (!root._suiHandlers) root._suiHandlers = [];
root._suiHandlers.push({ target, event, fn });
}
function suiOff(root) {
if (root._suiHandlers) {
root._suiHandlers.forEach(h => h.target.removeEventListener(h.event, h.fn));
delete root._suiHandlers;
}
delete root._suiInit;
delete root._suiSetView;
}
/* ====================================================================
Theme
==================================================================== */
const theme = {
KEY: 'sui-theme',
current() {
return localStorage.getItem(this.KEY) || 'auto';
},
set(mode) {
const root = document.documentElement;
if (mode === 'dark') root.setAttribute('data-theme', 'dark');
else if (mode === 'light') root.setAttribute('data-theme', 'light');
else root.removeAttribute('data-theme');
localStorage.setItem(this.KEY, mode);
},
toggle() {
// Detect what the user actually sees and flip it
const isDark = document.documentElement.getAttribute('data-theme') === 'dark' ||
(!document.documentElement.hasAttribute('data-theme') &&
window.matchMedia('(prefers-color-scheme: dark)').matches);
this.set(isDark ? 'light' : 'dark');
return this.current();
},
/** Returns the actual rendered theme ('light' or 'dark'), even when preference is 'auto'. */
resolved() {
const explicit = document.documentElement.getAttribute('data-theme');
if (explicit === 'dark' || explicit === 'light') return explicit;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
},
init() {
this.set(this.current());
}
};
/* ====================================================================
Tabs
==================================================================== */
const tabs = {
init(navEl) {
if (navEl._suiInit) return; // Idempotency guard — safe to call repeatedly
navEl._suiInit = true;
const tabBtns = $$('.sui-tab', navEl);
if (!tabBtns.length) return;
// Determine scope: if inside a [data-sui-tabs] wrapper, scope panels to that wrapper
const scope = navEl.closest('[data-sui-tabs]') || document;
// Enforce ARIA roles — tablist on nav, tab on buttons
if (!navEl.hasAttribute('role')) navEl.setAttribute('role', 'tablist');
tabBtns.forEach(t => {
if (!t.hasAttribute('role')) t.setAttribute('role', 'tab');
// Ensure accessible name exists (fallback to data-tab)
if (!t.hasAttribute('aria-label') && !t.textContent.trim()) {
t.setAttribute('aria-label', t.getAttribute('data-tab'));
}
});
// Collect panels — global tabs must skip panels inside a [data-sui-tabs] scope
const panels = $$('[data-view]', scope).filter(v =>
scope !== document || !v.closest('[data-sui-tabs]')
);
// Enforce tabpanel role on associated sections within scope
panels.forEach(v => {
if (!v.hasAttribute('role')) v.setAttribute('role', 'tabpanel');
});
// A7: Wire aria-controls (tab → panel) and aria-labelledby (panel → tab)
tabBtns.forEach(t => {
const key = t.getAttribute('data-tab');
if (!key) return;
const panel = panels.find(v => v.getAttribute('data-view') === key);
if (!panel) return;
if (!t.id) t.id = uid();
if (!panel.id) panel.id = uid();
t.setAttribute('aria-controls', panel.id);
panel.setAttribute('aria-labelledby', t.id);
});
const setView = (key) => {
panels.forEach(v =>
v.classList.toggle('is-active', v.getAttribute('data-view') === key)
);
tabBtns.forEach(t => {
const isActive = t.getAttribute('data-tab') === key;
t.setAttribute('aria-selected', isActive ? 'true' : 'false');
t.setAttribute('tabindex', isActive ? '0' : '-1');
});
// Only scroll to top for unscoped (global) tabs
if (scope === document) window.scrollTo({ top: 0, behavior: 'instant' });
};
// Store reference for programmatic access
navEl._suiSetView = setView;
tabBtns.forEach(t => suiOn(navEl, t, 'click', () => setView(t.getAttribute('data-tab'))));
// Keyboard nav
suiOn(navEl, navEl, 'keydown', e => {
const arr = tabBtns;
const idx = arr.indexOf(document.activeElement);
if (idx < 0) return;
if (e.key === 'ArrowRight') { e.preventDefault(); const next = arr[(idx + 1) % arr.length]; next.focus(); next.click(); }
if (e.key === 'ArrowLeft') { e.preventDefault(); const prev = arr[(idx - 1 + arr.length) % arr.length]; prev.focus(); prev.click(); }
});
// Set initial view
const active = tabBtns.find(t => t.getAttribute('aria-selected') === 'true') || tabBtns[0];
setView(active.getAttribute('data-tab'));
},
activate(tabEl) {
if (typeof tabEl === 'string') tabEl = $(tabEl);
if (!tabEl) return;
const navEl = tabEl.closest('[role="tablist"]');
if (navEl && navEl._suiSetView) {
navEl._suiSetView(tabEl.getAttribute('data-tab'));
}
},
destroy(navEl) {
if (typeof navEl === 'string') navEl = $(navEl);
if (navEl) suiOff(navEl);
}
};
/* ====================================================================
Accordion
==================================================================== */
const accordion = {
toggle(trigger) {
if (typeof trigger === 'string') trigger = $(trigger);
if (!trigger) return;
const panel = trigger.nextElementSibling;
if (!panel) return;
const expanded = trigger.getAttribute('aria-expanded') === 'true';
trigger.setAttribute('aria-expanded', expanded ? 'false' : 'true');
panel.hidden = expanded;
},
expandAll(container) {
if (typeof container === 'string') container = $(container);
if (!container) return;
$$('.sui-accordion-trigger', container).forEach(trigger => {
trigger.setAttribute('aria-expanded', 'true');
const panel = trigger.nextElementSibling;
if (panel) panel.hidden = false;
});
},
collapseAll(container) {
if (typeof container === 'string') container = $(container);
if (!container) return;
$$('.sui-accordion-trigger', container).forEach(trigger => {
trigger.setAttribute('aria-expanded', 'false');
const panel = trigger.nextElementSibling;
if (panel) panel.hidden = true;
});
},
init(container) {
if (container._suiInit) return; // Idempotency guard
container._suiInit = true;
$$('.sui-accordion-trigger', container).forEach(trigger => {
const panel = trigger.nextElementSibling;
if (!panel) return;
// Set initial state
if (trigger.getAttribute('aria-expanded') !== 'true') {
panel.hidden = true;
trigger.setAttribute('aria-expanded', 'false');
}
suiOn(container, trigger, 'click', () => this.toggle(trigger));
suiOn(container, trigger, 'keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); trigger.click(); }
});
});
},
destroy(container) {
if (typeof container === 'string') container = $(container);
if (container) suiOff(container);
}
};
/* ====================================================================
Dropdown
==================================================================== */
const dropdown = {
_active: null,
init(el) {
if (el._suiInit) return; // Idempotency guard
el._suiInit = true;
const trigger = el.querySelector('[data-sui-dropdown-trigger]') || el.querySelector('.sui-btn');
const menu = el.querySelector('.sui-dropdown-menu');
if (!trigger || !menu) return;
// Enforce ARIA roles
trigger.setAttribute('aria-haspopup', 'true');
trigger.setAttribute('aria-expanded', 'false');
if (!menu.hasAttribute('role')) menu.setAttribute('role', 'menu');
$$('.sui-dropdown-item', menu).forEach(item => {
if (!item.hasAttribute('role')) item.setAttribute('role', 'menuitem');
});
suiOn(el, trigger, 'click', e => {
e.stopPropagation();
this.toggle(el);
});
// Arrow key navigation within menu
suiOn(el, menu, 'keydown', e => {
const items = $$('.sui-dropdown-item', menu);
const idx = items.indexOf(document.activeElement);
if (e.key === 'ArrowDown') { e.preventDefault(); items[(idx + 1) % items.length]?.focus(); }
if (e.key === 'ArrowUp') { e.preventDefault(); items[(idx - 1 + items.length) % items.length]?.focus(); }
if (e.key === 'Escape') { this.close(el); trigger.focus(); }
});
},
open(el) {
if (typeof el === 'string') el = $(el);
if (this._active && this._active !== el) this.close(this._active);
el.classList.add('is-open');
this._active = el;
const trigger = el.querySelector('[data-sui-dropdown-trigger]') || el.querySelector('.sui-btn');
if (trigger) trigger.setAttribute('aria-expanded', 'true');
// Focus first item
const first = el.querySelector('.sui-dropdown-item');
if (first) setTimeout(() => first.focus(), 50);
// Register outside-click handler (one-time, removed on close)
if (!this._outsideClick) {
this._outsideClick = () => { if (this._active) this.close(this._active); };
setTimeout(() => document.addEventListener('click', this._outsideClick), 0);
}
},
close(el) {
if (typeof el === 'string') el = $(el);
if (!el) return;
el.classList.remove('is-open');
const trigger = el.querySelector('[data-sui-dropdown-trigger]') || el.querySelector('.sui-btn');
if (trigger) trigger.setAttribute('aria-expanded', 'false');
if (this._active === el) this._active = null;
// Remove outside-click handler when nothing is open
if (!this._active && this._outsideClick) {
document.removeEventListener('click', this._outsideClick);
this._outsideClick = null;
}
},
toggle(el) {
if (typeof el === 'string') el = $(el);
el.classList.contains('is-open') ? this.close(el) : this.open(el);
},
destroy(el) {
if (typeof el === 'string') el = $(el);
if (!el) return;
if (this._active === el) this.close(el);
suiOff(el);
}
};
/* ====================================================================
Modal
==================================================================== */
const modal = {
_stack: [],
_previousFocus: null,
open(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
this._previousFocus = document.activeElement;
// Native <dialog> path — browser handles focus trap, scroll lock, Escape
if (el.tagName === 'DIALOG') {
el.showModal();
// Close on backdrop click
el.addEventListener('click', el._suiBackdrop = (e) => {
if (e.target === el) this.close(el);
});
// iOS Safari: showModal() marks siblings inert but may fail
// to remove the attribute on close. Persistent cleanup listener.
if (!el._suiInertCleanup) {
el._suiInertCleanup = () => {
document.querySelectorAll('[inert]').forEach(n => n.removeAttribute('inert'));
};
el.addEventListener('close', el._suiInertCleanup);
}
this._stack.push(el);
return;
}
// Legacy overlay path (deprecated — will be removed in v3.0)
el.classList.add('is-open');
el.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
// Focus trap
const focusable = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', el);
if (focusable.length) focusable[0].focus();
const trapFocus = (e) => {
if (e.key === 'Tab') {
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === first) { e.preventDefault(); last.focus(); }
} else {
if (document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
if (e.key === 'Escape') this.close(el);
};
el._suiTrap = trapFocus;
el.addEventListener('keydown', trapFocus);
this._stack.push(el);
},
close(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
// Native <dialog> path
if (el.tagName === 'DIALOG') {
el.close();
// iOS Safari inert cleanup (synchronous — close event may be async)
document.querySelectorAll('[inert]').forEach(n => n.removeAttribute('inert'));
if (el._suiBackdrop) {
el.removeEventListener('click', el._suiBackdrop);
delete el._suiBackdrop;
}
this._stack = this._stack.filter(m => m !== el);
if (this._previousFocus) this._previousFocus.focus();
return;
}
// Legacy overlay path
el.classList.remove('is-open');
el.setAttribute('aria-hidden', 'true');
if (el._suiTrap) {
el.removeEventListener('keydown', el._suiTrap);
delete el._suiTrap;
}
this._stack = this._stack.filter(m => m !== el);
if (this._stack.length === 0) document.body.style.overflow = '';
if (this._previousFocus) this._previousFocus.focus();
}
};
/* ====================================================================
Toast
==================================================================== */
const toast = {
_container: null,
_ensureContainer() {
if (!this._container) {
this._container = document.createElement('div');
this._container.className = 'sui-toast-container';
this._container.setAttribute('aria-live', 'polite');
this._container.setAttribute('aria-label', 'Notifications');
document.body.appendChild(this._container);
}
return this._container;
},
/**
* Show a toast notification
* @param {Object} opts
* @param {string} opts.title - Toast title
* @param {string} [opts.message] - Optional description
* @param {string} [opts.type] - success|warning|error|info
* @param {number} [opts.duration] - Auto-dismiss ms (default 4000, 0 = manual)
*/
show({ title, message = '', type = 'info', duration = 4000 }) {
const container = this._ensureContainer();
const icons = {
success: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
warning: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
error: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'
};
// Hardening: guard against unexpected types (prevents odd class injection + ensures icon fallback)
const allowed = ['success', 'warning', 'error', 'info'];
if (!allowed.includes(type)) type = 'info';
const el = document.createElement('div');
el.className = `sui-toast sui-toast-${type}`;
el.setAttribute('role', 'alert');
if (type === 'error') el.setAttribute('aria-live', 'assertive');
// Build DOM safely (avoid interpolating untrusted strings into HTML)
const icon = document.createElement('span');
icon.className = 'sui-toast-icon';
icon.innerHTML = icons[type] || icons.info; // safe constant SVG only
const content = document.createElement('div');
content.className = 'sui-toast-content';
const titleEl = document.createElement('div');
titleEl.className = 'sui-toast-title';
titleEl.textContent = title != null ? String(title) : '';
content.appendChild(titleEl);
if (message) {
const msgEl = document.createElement('div');
msgEl.className = 'sui-toast-message';
msgEl.textContent = String(message);
content.appendChild(msgEl);
}
const closeBtn = document.createElement('button');
closeBtn.className = 'sui-toast-close';
closeBtn.type = 'button';
closeBtn.setAttribute('aria-label', 'Dismiss');
closeBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
closeBtn.addEventListener('click', () => this._dismiss(el));
el.append(icon, content, closeBtn);
container.appendChild(el);
// Pause auto-dismiss on hover
let timer;
const startTimer = () => {
if (duration > 0) timer = setTimeout(() => this._dismiss(el), duration);
};
el.addEventListener('mouseenter', () => clearTimeout(timer));
el.addEventListener('mouseleave', startTimer);
startTimer();
return el;
},
_dismiss(el) {
el.classList.add('is-exiting');
el.addEventListener('animationend', () => el.remove(), { once: true });
},
/** Programmatic dismissal of a single toast (public wrapper around _dismiss). */
dismiss(el) {
if (typeof el === 'string') el = $(el);
if (el && el.classList.contains('sui-toast')) this._dismiss(el);
},
/** Dismiss all active toasts. */
clearAll() {
if (!this._container) return;
$$('.sui-toast', this._container).forEach(t => this._dismiss(t));
},
// Convenience methods
success(title, message) { return this.show({ title, message, type: 'success' }); },
warning(title, message) { return this.show({ title, message, type: 'warning' }); },
error(title, message) { return this.show({ title, message, type: 'error' }); },
info(title, message) { return this.show({ title, message, type: 'info' }); }
};
/* ====================================================================
Tooltip (smart positioning)
==================================================================== */
const tooltip = {
/** Programmatically show a tooltip (advisory — CSS hover/focus still takes precedence). */
show(el) {
if (typeof el === 'string') el = document.querySelector(el);
if (!el) return;
el.classList.add('is-tooltip-visible');
if (el._suiReposition) el._suiReposition();
// Dismiss on Escape while programmatically shown
el._suiProgKeyHandler = (e) => { if (e.key === 'Escape') this.hide(el); };
document.addEventListener('keydown', el._suiProgKeyHandler);
},
/** Remove programmatic tooltip visibility. */
hide(el) {
if (typeof el === 'string') el = document.querySelector(el);
if (!el) return;
el.classList.remove('is-tooltip-visible');
if (el._suiProgKeyHandler) {
document.removeEventListener('keydown', el._suiProgKeyHandler);
delete el._suiProgKeyHandler;
}
},
init(el) {
if (el._suiInit) return; // Idempotency guard
el._suiInit = true;
const content = el.querySelector('.sui-tooltip-content');
if (!content) return;
const reposition = () => {
const rect = el.getBoundingClientRect();
const tip = content.getBoundingClientRect();
// Reset classes
el.classList.remove('sui-tooltip-bottom');
// If tooltip would overflow top, flip to bottom
if (rect.top - tip.height - 12 < 0) {
el.classList.add('sui-tooltip-bottom');
}
// If tooltip overflows right, shift left
const halfTip = tip.width / 2;
const centerX = rect.left + rect.width / 2;
if (centerX + halfTip > window.innerWidth - 8) {
content.style.left = 'auto';
content.style.right = '0';
content.style.transform = 'none';
} else if (centerX - halfTip < 8) {
content.style.left = '0';
content.style.right = 'auto';
content.style.transform = 'none';
} else {
content.style.left = '50%';
content.style.right = 'auto';
content.style.transform = 'translateX(-50%)';
}
};
el._suiReposition = reposition;
suiOn(el, el, 'mouseenter', reposition);
suiOn(el, el, 'focusin', reposition);
// Escape key dismisses tooltip when focused
suiOn(el, el, 'keydown', e => {
if (e.key === 'Escape') el.blur();
});
},
destroy(el) {
if (typeof el === 'string') el = $(el);
if (!el) return;
delete el._suiReposition;
suiOff(el);
}
};
/* ====================================================================
Avatar (deterministic color from initials)
==================================================================== */
const avatar = {
// SUI-safe palette — all meet 3:1 contrast on white text
COLORS: [
'#2563EB', // blue (5.17:1 on white)
'#15803D', // green (5.02:1)
'#B45309', // amber (5.02:1)
'#B91C1C', // red (6.47:1)
'#0E7490', // cyan (5.36:1)
'#7C3AED', // violet (5.70:1)
'#DB2777', // pink (4.60:1)
'#0F766E', // teal (5.47:1)
'#C2410C', // orange (5.18:1)
'#4F46E5' // indigo (6.29:1)
],
colorFor(text) {
let hash = 0;
for (let i = 0; i < text.length; i++) {
hash = text.charCodeAt(i) + ((hash << 5) - hash);
}
return this.COLORS[Math.abs(hash) % this.COLORS.length];
},
init(el) {
if (el._suiInit) return; // Idempotency guard
el._suiInit = true;
const initials = el.textContent.trim();
if (initials && !el.style.background) {
el.style.background = this.colorFor(initials);
}
},
destroy(el) {
if (typeof el === 'string') el = $(el);
if (el) { delete el._suiInit; }
}
};
/* ====================================================================
Clipboard
==================================================================== */
const copy = {
async text(str) {
try {
await navigator.clipboard.writeText(str);
return true;
} catch {
// Fallback
const ta = document.createElement('textarea');
ta.value = str;
ta.style.cssText = 'position:fixed;left:-9999px;top:-9999px';
document.body.appendChild(ta);
ta.select();
let ok = false;
try { ok = document.execCommand('copy'); } catch {}
document.body.removeChild(ta);
return ok;
}
},
async fromElement(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return false;
return this.text(el.innerText || el.textContent);
}
};
/* ====================================================================
Bottom Sheet
==================================================================== */
const sheet = {
_active: null,
_previousFocus: null,
open(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
this._previousFocus = document.activeElement;
el.classList.add('is-open');
el.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
this._active = el;
// Focus first focusable element in panel
const panel = el.querySelector('.sui-sheet-panel');
if (panel) {
const focusable = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', panel);
if (focusable.length) setTimeout(() => focusable[0].focus(), 50);
}
// Keyboard handler: Escape + focus trap
el._suiKeyHandler = (e) => {
if (e.key === 'Escape') { this.close(el); return; }
if (e.key === 'Tab' && panel) {
const focusable = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', panel);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === first) { e.preventDefault(); last.focus(); }
} else {
if (document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
};
el.addEventListener('keydown', el._suiKeyHandler);
},
close(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
el.classList.remove('is-open');
el.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
if (el._suiKeyHandler) {
el.removeEventListener('keydown', el._suiKeyHandler);
delete el._suiKeyHandler;
}
if (this._active === el) this._active = null;
if (this._previousFocus) this._previousFocus.focus();
},
toggle(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
el.classList.contains('is-open') ? this.close(el) : this.open(el);
}
};
/* ====================================================================
Segmented Control
==================================================================== */
const segmented = {
init(container) {
if (container._suiInit) return; // Idempotency guard
container._suiInit = true;
const segments = $$('.sui-segment', container);
if (!segments.length) return;
// Enforce ARIA roles
if (!container.hasAttribute('role')) container.setAttribute('role', 'radiogroup');
segments.forEach(seg => {
if (!seg.hasAttribute('role')) seg.setAttribute('role', 'radio');
if (!seg.hasAttribute('tabindex')) {
seg.setAttribute('tabindex', seg.getAttribute('aria-checked') === 'true' ? '0' : '-1');
}
});
const select = (target) => {
segments.forEach(s => {
s.setAttribute('aria-checked', 'false');
s.setAttribute('tabindex', '-1');
});
target.setAttribute('aria-checked', 'true');
target.setAttribute('tabindex', '0');
target.focus();
};
// Store reference for programmatic access (A10)
container._suiSetValue = select;
segments.forEach(seg => suiOn(container, seg, 'click', () => select(seg)));
// Arrow key navigation
suiOn(container, container, 'keydown', e => {
const idx = segments.indexOf(document.activeElement);
if (idx < 0) return;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
e.preventDefault();
select(segments[(idx + 1) % segments.length]);
}
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
e.preventDefault();
select(segments[(idx - 1 + segments.length) % segments.length]);
}
});
},
/** Programmatically select a segment. */
select(el) {
if (typeof el === 'string') el = document.querySelector(el);
if (!el) return;
const container = el.closest('.sui-segmented');
if (container && container._suiSetValue) container._suiSetValue(el);
},
destroy(container) {
if (typeof container === 'string') container = $(container);
if (!container) return;
delete container._suiSetValue;
suiOff(container);
}
};
/* ====================================================================
Sidenav — Responsive section navigation
==================================================================== */
const sidenav = {
_active: null,
_previousFocus: null,
_mediaQuery: window.matchMedia('(min-width: 769px)'),
open(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
// Desktop: sidenav is always visible, no overlay
if (this._mediaQuery.matches) return;
this._previousFocus = document.activeElement;
el.classList.add('is-open');
el.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
this._active = el;
// Focus first link in panel
const panel = el.querySelector('.sui-sidenav-panel');
if (panel) {
const focusable = $$('a[href], button, [tabindex]:not([tabindex="-1"])', panel);
if (focusable.length) setTimeout(() => focusable[0].focus(), 50);
}
// Keyboard: Escape + focus trap
el._suiKeyHandler = (e) => {
if (e.key === 'Escape') { this.close(el); return; }
if (e.key === 'Tab' && panel) {
const focusable = $$('a[href], button, [tabindex]:not([tabindex="-1"])', panel);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === first) { e.preventDefault(); last.focus(); }
} else {
if (document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
};
el.addEventListener('keydown', el._suiKeyHandler);
},
close(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
el.classList.remove('is-open');
el.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
if (el._suiKeyHandler) {
el.removeEventListener('keydown', el._suiKeyHandler);
delete el._suiKeyHandler;
}
if (this._active === el) this._active = null;
if (this._previousFocus) this._previousFocus.focus();
},
toggle(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
el.classList.contains('is-open') ? this.close(el) : this.open(el);
},
/** Returns true if the sidenav overlay is open (mobile state). */
isOpen(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
return el ? el.classList.contains('is-open') : false;
},
/** Collapse all sidenav groups within a container */
collapseAll(navSelector) {
const ctx = typeof navSelector === 'string' ? $(navSelector) : navSelector || document;
if (!ctx) return;
$$('.sui-sidenav-group-toggle', ctx).forEach(btn => {
btn.setAttribute('aria-expanded', 'false');
const id = btn.getAttribute('aria-controls');
if (id) { const target = document.getElementById(id); if (target) target.hidden = true; }
});
},
/** Expand all sidenav groups within a container */
expandAll(navSelector) {
const ctx = typeof navSelector === 'string' ? $(navSelector) : navSelector || document;
if (!ctx) return;
$$('.sui-sidenav-group-toggle', ctx).forEach(btn => {
btn.setAttribute('aria-expanded', 'true');
const id = btn.getAttribute('aria-controls');
if (id) { const target = document.getElementById(id); if (target) target.hidden = false; }
});
}
};
/* ====================================================================
Panel — Side panel / slide-over
Desktop: focus moves, no trap (both regions interactive).
Mobile: focus trap (panel is full-screen blocking overlay).
==================================================================== */
const panel = {
_active: null,
_previousFocus: null,
_mediaQuery: window.matchMedia('(min-width: 769px)'),
open(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
this._previousFocus = document.activeElement;
el.classList.add('is-open');
el.setAttribute('aria-hidden', 'false');
this._active = el;
// Update trigger aria-expanded (resolve via el.id so element and string args behave identically — mirrors close())
const id = el.id ? `#${el.id}` : (typeof selector === 'string' ? selector : null);
if (id) $$(`[data-sui-panel="${id}"]`).forEach(t => t.setAttribute('aria-expanded', 'true'));
// Mobile: lock body scroll (full-screen blocking)
if (!this._mediaQuery.matches) document.body.style.overflow = 'hidden';
// Focus first focusable element inside panel
const focusable = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', el);
if (focusable.length) setTimeout(() => focusable[0].focus(), 50);
// Document-level Escape handler — works even when focus is in main content
el._suiDocKeyHandler = (e) => {
if (e.key === 'Escape') this.close(el);
};
document.addEventListener('keydown', el._suiDocKeyHandler);
// Focus trap only on mobile (panel element listener)
el._suiKeyHandler = (e) => {
if (e.key === 'Tab' && !this._mediaQuery.matches) {
const focusable = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', el);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === first) { e.preventDefault(); last.focus(); }
} else {
if (document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
};
el.addEventListener('keydown', el._suiKeyHandler);
// Breakpoint change while open: toggle trap + body scroll
el._suiMqHandler = (mq) => {
if (mq.matches) {
document.body.style.overflow = '';
} else {
document.body.style.overflow = 'hidden';
}
};
this._mediaQuery.addEventListener('change', el._suiMqHandler);
},
close(selector) {
const el = typeof selector === 'string' ? $(selector) : selector;
if (!el) return;
el.classList.remove('is-open');
el.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
// Update trigger aria-expanded (resolve via el.id, string fallback — mirrors open())
const id = el.id ? `#${el.id}` : (typeof selector === 'string' ? selector : null);
if (id) $$(`[data-sui-panel="${id}"]`).forEach(t => t.setAttribute('aria-expanded', 'false'));
if (el._suiDocKeyHandler) {
document.removeEventListener('keydown', el._suiDocKeyHandler);
delete el._suiDocKeyHandler;
}
if (el._suiKeyHandler) {
el.removeEventListener('keydown', el._suiKeyHandler);
delete el._suiKeyHandler;
}
if (el._suiMqHandler) {
this._mediaQuery.removeEventListener('change', el._suiMqHandler);
delete el._suiMqHandler;
}
if (this._active === el) this._active = null;