-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzephyr-framework.js
More file actions
2456 lines (2189 loc) · 86.3 KB
/
Copy pathzephyr-framework.js
File metadata and controls
2456 lines (2189 loc) · 86.3 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
/**
* Zephyr - Zero-JS Interactive Framework
* Uses View Transitions, CSS :has(), container queries, and HTML primitives
*
* @description A component framework that delivers rich interactions without
* shipping JavaScript to users for runtime interactions. JS runs once at page
* load to register custom elements and attach event listeners.
*
* Naming conventions:
* - Public/protected methods: camelCase (attachTemplate, attachBehaviors)
* - Private members: underscore prefix (_currentIndex, _transition)
* - formAssociated: only on components that participate in forms
*
* State attribute conventions:
* - data-open: binary open/closed state (accordion, select, dropdown)
* - data-active: selected/current item in a set (tabs, carousel slides)
* - data-visible: visibility toggle (toast notifications)
*/
/**
* Base class for all Zephyr components.
* Provides shared utilities for view transitions, toggle behavior,
* click-outside handling, and lifecycle management.
*/
class ZephyrElement extends HTMLElement {
connectedCallback() {
// Trigger buttons default to type="submit" — inside a <form> a click would
// submit and navigate. Defuse unless the author set an explicit type.
this.querySelectorAll('button[slot="trigger"]:not([type])').forEach(b => { b.type = 'button'; });
this.attachTemplate();
this.attachBehaviors();
}
disconnectedCallback() {
this._cleanup();
}
/** Override in subclasses to set up component DOM structure. */
attachTemplate() {}
/** Auto-wires declarative behaviors from data attributes. */
attachBehaviors() {
this.querySelectorAll('[data-toggle]').forEach(el => {
el.addEventListener('click', (e) => {
e.preventDefault();
const target = this.querySelector(el.dataset.toggle);
if (target) {
target.toggleAttribute('data-open');
}
});
});
this.querySelectorAll('[data-tab]').forEach(el => {
el.addEventListener('click', (e) => {
e.preventDefault();
const tabName = el.dataset.tab;
const group = el.closest('[data-tab-group]');
group.querySelectorAll('[data-tab]').forEach(t => {
t.removeAttribute('data-active');
t.setAttribute('aria-selected', 'false');
t.setAttribute('tabindex', '-1');
});
group.querySelectorAll('[data-tab-panel]').forEach(p => p.removeAttribute('data-active'));
el.setAttribute('data-active', '');
el.setAttribute('aria-selected', 'true');
el.setAttribute('tabindex', '0');
group.querySelector(`[data-tab-panel="${tabName}"]`)?.setAttribute('data-active', '');
});
});
}
/**
* Wraps a DOM mutation in a View Transition if the API is available.
* Falls back to executing the function directly in unsupported browsers,
* when the user prefers reduced motion, or in agent headless mode — in all
* three cases the mutation applies synchronously.
* @param {Function} fn - The DOM mutation to perform
*/
static withTransition(fn) {
const skipTransition =
!document.startViewTransition ||
document.documentElement.hasAttribute('data-z-headless') ||
(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
if (skipTransition) {
fn();
return;
}
const transition = document.startViewTransition(() => fn());
// A skipped transition (hidden tab, rapid successive calls) rejects these
// promises; the DOM update still applies, so the rejection is benign.
transition.finished.catch(() => {});
if (transition.ready) transition.ready.catch(() => {});
}
/** Toggles the data-open attribute on this element. */
_toggleOpen() {
const isOpen = this.hasAttribute('data-open');
if (isOpen) {
this.removeAttribute('data-open');
} else {
this.setAttribute('data-open', '');
}
return !isOpen;
}
/**
* Registers this element with the shared click-outside handler.
* When a click occurs outside this element, data-open is removed.
*/
_attachClickOutside() {
ZephyrElement._clickOutsideElements.add(this);
}
/** Removes this element from the click-outside registry. */
_detachClickOutside() {
ZephyrElement._clickOutsideElements.delete(this);
}
/** Override in subclasses to clean up listeners, intervals, etc. */
_cleanup() {
this._detachClickOutside();
}
}
/** Shared registry of elements that need click-outside handling. */
ZephyrElement._clickOutsideElements = new Set();
/** Single delegated click-outside listener (shared across all instances). */
document.addEventListener('click', (e) => {
ZephyrElement._clickOutsideElements.forEach(el => {
if (!el.contains(e.target)) {
el.removeAttribute('data-open');
const trigger = el.querySelector('[slot="trigger"]');
if (trigger) trigger.setAttribute('aria-expanded', 'false');
}
});
});
// ---------------------------------------------------------------------------
// Accordion
// ---------------------------------------------------------------------------
/** Minimal registration for z-accordion-item so it is a proper custom element. */
class ZAccordionItem extends HTMLElement {}
/**
* Collapsible accordion component.
* Uses CSS Grid grid-template-rows transition with :has([data-open]) selector.
* Dispatches 'toggle' events when items open/close.
*/
class ZAccordion extends ZephyrElement {
attachTemplate() {
const items = Array.from(this.querySelectorAll('z-accordion-item'));
items.forEach((item, idx) => {
const trigger = item.querySelector('[slot="trigger"]');
const content = item.querySelector('[slot="content"]');
if (trigger && content) {
const contentId = `accordion-content-${this._uid()}-${idx}`;
trigger.setAttribute('data-toggle', `#${contentId}`);
trigger.setAttribute('aria-expanded', 'false');
trigger.setAttribute('aria-controls', contentId);
content.id = contentId;
content.setAttribute('role', 'region');
content.setAttribute('aria-labelledby', trigger.id || `accordion-trigger-${this._uid()}-${idx}`);
if (!trigger.id) trigger.id = `accordion-trigger-${this._uid()}-${idx}`;
trigger.addEventListener('click', () => {
const isOpen = content.hasAttribute('data-open');
trigger.setAttribute('aria-expanded', String(!isOpen));
this.dispatchEvent(new CustomEvent('toggle', {
bubbles: true,
detail: { index: idx, open: !isOpen }
}));
});
trigger.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
trigger.click();
}
});
}
});
}
/** Generates a simple unique ID for this accordion instance. */
_uid() {
if (!this.__uid) this.__uid = Math.random().toString(36).slice(2, 8);
return this.__uid;
}
}
// ---------------------------------------------------------------------------
// Modal
// ---------------------------------------------------------------------------
/**
* Modal dialog component wrapping native <dialog>.
* Uses View Transitions API for smooth entrance/exit animations.
* Dispatches 'open' and 'close' events.
*/
class ZModal extends ZephyrElement {
attachTemplate() {
const dialog = document.createElement('dialog');
// Move child nodes into dialog (avoids innerHTML XSS risk)
while (this.firstChild) {
dialog.appendChild(this.firstChild);
}
this.appendChild(dialog);
// Auto-detect heading for aria-labelledby
const heading = dialog.querySelector('h1, h2, h3, h4, h5, h6');
if (heading) {
if (!heading.id) heading.id = `modal-heading-${Math.random().toString(36).slice(2, 8)}`;
dialog.setAttribute('aria-labelledby', heading.id);
}
dialog.addEventListener('click', (e) => {
if (e.target === dialog) {
this.close();
}
});
// Escape key is handled natively by <dialog>, but we dispatch event.
// Mirror the native state to data-open so agents (getState/observe) see it.
// The close event arrives via a queued task — skip the removal if the
// dialog was reopened before the task ran.
dialog.addEventListener('close', () => {
if (!dialog.open) this.removeAttribute('data-open');
this.dispatchEvent(new CustomEvent('close', { bubbles: true }));
});
}
/** Opens the modal dialog with a View Transition animation. */
open() {
const dialog = this.querySelector('dialog');
ZephyrElement.withTransition(() => {
dialog.showModal();
this.setAttribute('data-open', '');
});
this.dispatchEvent(new CustomEvent('open', { bubbles: true }));
}
/** Closes the modal dialog with a View Transition animation. */
close() {
const dialog = this.querySelector('dialog');
ZephyrElement.withTransition(() => {
dialog.close();
this.removeAttribute('data-open');
});
}
}
// ---------------------------------------------------------------------------
// Tabs
// ---------------------------------------------------------------------------
/**
* Tab panel component with View Transitions.
* Uses container queries for responsive tab layouts.
* Supports keyboard navigation: ArrowLeft/Right, Home, End.
*/
class ZTabs extends ZephyrElement {
attachTemplate() {
this.setAttribute('data-tab-group', '');
const tabs = Array.from(this.querySelectorAll('[data-tab]'));
const panels = Array.from(this.querySelectorAll('[data-tab-panel]'));
// Wire up ARIA relationships
tabs.forEach((tab, idx) => {
const panelName = tab.dataset.tab;
const panel = this.querySelector(`[data-tab-panel="${panelName}"]`);
const tabId = `tab-${panelName}-${Math.random().toString(36).slice(2, 8)}`;
const panelId = `panel-${panelName}-${Math.random().toString(36).slice(2, 8)}`;
tab.id = tabId;
tab.setAttribute('aria-controls', panelId);
tab.setAttribute('aria-selected', idx === 0 ? 'true' : 'false');
tab.setAttribute('tabindex', idx === 0 ? '0' : '-1');
if (panel) {
panel.id = panelId;
panel.setAttribute('aria-labelledby', tabId);
}
});
// Activate first tab
if (tabs[0] && panels[0]) {
tabs[0].setAttribute('data-active', '');
panels[0].setAttribute('data-active', '');
}
// Keyboard navigation on tablist
const tablist = this.querySelector('[role="tablist"]');
if (tablist) {
tablist.addEventListener('keydown', (e) => {
const currentTab = tabs.find(t => t.hasAttribute('data-active'));
const currentIdx = tabs.indexOf(currentTab);
let nextIdx = -1;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
nextIdx = (currentIdx + 1) % tabs.length;
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
nextIdx = (currentIdx - 1 + tabs.length) % tabs.length;
} else if (e.key === 'Home') {
nextIdx = 0;
} else if (e.key === 'End') {
nextIdx = tabs.length - 1;
}
if (nextIdx >= 0) {
e.preventDefault();
tabs[nextIdx].click();
tabs[nextIdx].focus();
}
});
}
}
}
// ---------------------------------------------------------------------------
// Select (form-associated)
// ---------------------------------------------------------------------------
/**
* Custom select component that integrates with native HTML forms.
* Uses ElementInternals API for form participation.
* Dispatches 'change' events on selection.
* Supports keyboard navigation: ArrowUp/Down, Enter, Escape.
*/
class ZSelect extends ZephyrElement {
static formAssociated = true;
constructor() {
super();
this._internals = this.attachInternals();
this._value = '';
}
get value() {
return this._value;
}
set value(v) {
this._value = v;
this._internals.setFormValue(v);
}
attachTemplate() {
const button = this.querySelector('[slot="trigger"]');
const options = this.querySelector('[slot="options"]');
const items = Array.from(options.querySelectorAll('[data-value]'));
// ARIA setup
button.setAttribute('aria-expanded', 'false');
button.setAttribute('aria-haspopup', 'listbox');
options.setAttribute('role', 'listbox');
// Listboxes need an accessible name — label via the trigger button
if (!button.id) button.id = `select-trigger-${Math.random().toString(36).slice(2, 8)}`;
if (!options.hasAttribute('aria-label') && !options.hasAttribute('aria-labelledby')) {
options.setAttribute('aria-labelledby', button.id);
}
items.forEach(item => item.setAttribute('role', 'option'));
button.addEventListener('click', () => {
const isOpen = this._toggleOpen();
button.setAttribute('aria-expanded', String(isOpen));
});
items.forEach(item => {
item.addEventListener('click', () => {
this.value = item.dataset.value;
button.textContent = item.textContent;
this.removeAttribute('data-open');
button.setAttribute('aria-expanded', 'false');
this.dispatchEvent(new Event('change', { bubbles: true }));
});
});
// Keyboard navigation
this.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
this.removeAttribute('data-open');
button.setAttribute('aria-expanded', 'false');
button.focus();
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
if (!this.hasAttribute('data-open')) {
this.setAttribute('data-open', '');
button.setAttribute('aria-expanded', 'true');
}
const focused = items.find(i => i === document.activeElement);
const idx = focused ? items.indexOf(focused) : -1;
const next = e.key === 'ArrowDown'
? items[(idx + 1) % items.length]
: items[(idx - 1 + items.length) % items.length];
next.setAttribute('tabindex', '0');
next.focus();
} else if (e.key === 'Enter' && document.activeElement.hasAttribute('data-value')) {
document.activeElement.click();
}
});
this._attachClickOutside();
}
_cleanup() {
super._cleanup();
}
}
// ---------------------------------------------------------------------------
// Carousel
// ---------------------------------------------------------------------------
/**
* Slide carousel with View Transitions and optional autoplay.
* Dispatches 'slide' events with detail: { index, direction }.
* Supports keyboard navigation: ArrowLeft/Right.
*/
class ZCarousel extends ZephyrElement {
attachTemplate() {
this._currentIndex = 0;
this._items = Array.from(this.querySelectorAll('[slot="item"]'));
this._autoplayInterval = null;
this._items.forEach((item, idx) => {
item.setAttribute('data-index', idx);
if (idx === 0) item.setAttribute('data-active', '');
});
const prevBtn = this.querySelector('[data-prev]');
const nextBtn = this.querySelector('[data-next]');
prevBtn?.addEventListener('click', () => this.prev());
nextBtn?.addEventListener('click', () => this.next());
// Keyboard navigation
this.setAttribute('tabindex', '0');
this.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft') { e.preventDefault(); this.prev(); }
if (e.key === 'ArrowRight') { e.preventDefault(); this.next(); }
});
if (this.hasAttribute('data-autoplay')) {
this._startAutoplay();
}
}
/** Transitions to the previous slide. */
prev() {
this._transition(-1);
}
/** Transitions to the next slide. */
next() {
this._transition(1);
}
_transition(direction) {
const nextIndex = (this._currentIndex + direction + this._items.length) % this._items.length;
ZephyrElement.withTransition(() => this._updateSlide(nextIndex));
this.dispatchEvent(new CustomEvent('slide', {
bubbles: true,
detail: { index: nextIndex, direction: direction > 0 ? 'next' : 'prev' }
}));
}
_updateSlide(nextIndex) {
this._items[this._currentIndex].removeAttribute('data-active');
this._items[nextIndex].setAttribute('data-active', '');
this._currentIndex = nextIndex;
}
_startAutoplay() {
const interval = parseInt(this.dataset.autoplay) || 3000;
this._autoplayInterval = setInterval(() => this.next(), interval);
}
_cleanup() {
super._cleanup();
if (this._autoplayInterval) {
clearInterval(this._autoplayInterval);
this._autoplayInterval = null;
}
}
}
// ---------------------------------------------------------------------------
// Toast / Notification
// ---------------------------------------------------------------------------
/**
* Toast notification component.
* Dispatches 'show' and 'hide' events.
* @example Zephyr.toast('Hello!', 3000)
*/
class ZToast extends ZephyrElement {
/**
* Displays a toast message for the given duration.
* @param {string} message - The message to display
* @param {number} [duration=3000] - Duration in milliseconds before auto-hide
*/
show(message, duration = 3000) {
this.textContent = message;
this.setAttribute('data-visible', '');
this.setAttribute('role', 'alert');
this.setAttribute('aria-live', 'polite');
this.dispatchEvent(new CustomEvent('show', { bubbles: true, detail: { message } }));
this._hideTimeout = setTimeout(() => {
ZephyrElement.withTransition(() => this.removeAttribute('data-visible'));
this.dispatchEvent(new CustomEvent('hide', { bubbles: true }));
}, duration);
}
_cleanup() {
super._cleanup();
if (this._hideTimeout) {
clearTimeout(this._hideTimeout);
this._hideTimeout = null;
}
}
}
// ---------------------------------------------------------------------------
// Dropdown
// ---------------------------------------------------------------------------
/**
* Dropdown menu component with click-outside handling.
* Dispatches 'toggle' events when opened/closed.
* Supports Escape key to close.
*/
class ZDropdown extends ZephyrElement {
attachTemplate() {
const trigger = this.querySelector('[slot="trigger"]');
// ARIA setup
if (trigger) {
trigger.setAttribute('aria-expanded', 'false');
trigger.setAttribute('aria-haspopup', 'true');
}
trigger?.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = this._toggleOpen();
trigger.setAttribute('aria-expanded', String(isOpen));
this.dispatchEvent(new CustomEvent('toggle', {
bubbles: true,
detail: { open: isOpen }
}));
});
// Escape key closes dropdown
this.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.hasAttribute('data-open')) {
this.removeAttribute('data-open');
trigger?.setAttribute('aria-expanded', 'false');
trigger?.focus();
this.dispatchEvent(new CustomEvent('toggle', {
bubbles: true,
detail: { open: false }
}));
}
});
this._attachClickOutside();
}
_cleanup() {
super._cleanup();
}
}
// ---------------------------------------------------------------------------
// Combobox
// ---------------------------------------------------------------------------
/**
* Combobox component with filterable options and keyboard navigation.
* Combines a text input with a dropdown listbox.
* Dispatches 'change' events on selection, 'input' events on filter.
* Supports ArrowUp/Down, Enter, Escape.
*/
class ZCombobox extends ZephyrElement {
static formAssociated = true;
constructor() {
super();
this._internals = this.attachInternals();
this._value = '';
}
get value() { return this._value; }
set value(v) {
this._value = v;
this._internals.setFormValue(v);
}
attachTemplate() {
const input = this.querySelector('input');
const listbox = this.querySelector('[slot="listbox"]');
const items = Array.from(listbox.querySelectorAll('[data-value]'));
// ARIA setup
input.setAttribute('role', 'combobox');
input.setAttribute('aria-expanded', 'false');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-haspopup', 'listbox');
listbox.setAttribute('role', 'listbox');
// Listboxes need an accessible name; scrollable lists need keyboard focus
if (!listbox.hasAttribute('aria-label') && !listbox.hasAttribute('aria-labelledby')) {
listbox.setAttribute('aria-label', input.getAttribute('placeholder') || 'Options');
}
if (!listbox.hasAttribute('tabindex')) listbox.setAttribute('tabindex', '0');
items.forEach(item => {
item.setAttribute('role', 'option');
item.setAttribute('tabindex', '-1');
});
let activeIdx = -1;
const showList = () => {
this.setAttribute('data-open', '');
input.setAttribute('aria-expanded', 'true');
};
const hideList = () => {
this.removeAttribute('data-open');
input.setAttribute('aria-expanded', 'false');
activeIdx = -1;
items.forEach(i => i.removeAttribute('data-highlighted'));
};
const selectItem = (item) => {
this.value = item.dataset.value;
input.value = item.textContent.trim();
hideList();
this.dispatchEvent(new Event('change', { bubbles: true }));
};
const filterItems = (query) => {
const q = query.toLowerCase();
let visibleCount = 0;
items.forEach(item => {
const matches = item.textContent.toLowerCase().includes(q);
item.style.display = matches ? '' : 'none';
if (matches) visibleCount++;
});
if (visibleCount > 0 && query.length > 0) {
showList();
} else if (query.length === 0) {
items.forEach(i => i.style.display = '');
showList();
}
activeIdx = -1;
};
const highlightIdx = (idx) => {
const visible = items.filter(i => i.style.display !== 'none');
if (visible.length === 0) return;
activeIdx = ((idx % visible.length) + visible.length) % visible.length;
items.forEach(i => i.removeAttribute('data-highlighted'));
visible[activeIdx].setAttribute('data-highlighted', '');
visible[activeIdx].scrollIntoView({ block: 'nearest' });
};
input.addEventListener('focus', () => {
filterItems(input.value);
});
input.addEventListener('input', () => {
filterItems(input.value);
this.dispatchEvent(new Event('input', { bubbles: true }));
});
input.addEventListener('keydown', (e) => {
const visible = items.filter(i => i.style.display !== 'none');
if (e.key === 'ArrowDown') {
e.preventDefault();
if (!this.hasAttribute('data-open')) showList();
highlightIdx(activeIdx + 1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (!this.hasAttribute('data-open')) showList();
highlightIdx(activeIdx - 1);
} else if (e.key === 'Enter') {
e.preventDefault();
if (activeIdx >= 0 && visible[activeIdx]) {
selectItem(visible[activeIdx]);
}
} else if (e.key === 'Escape') {
hideList();
input.focus();
}
});
items.forEach(item => {
item.addEventListener('click', () => selectItem(item));
});
this._attachClickOutside();
this._hideList = hideList;
}
_cleanup() {
super._cleanup();
}
}
// ---------------------------------------------------------------------------
// Date Picker
// ---------------------------------------------------------------------------
/**
* Enhanced date picker wrapping native <input type="date">.
* Provides a styled trigger that displays the formatted date.
* Dispatches 'change' events on date selection.
*/
class ZDatepicker extends ZephyrElement {
static formAssociated = true;
constructor() {
super();
this._internals = this.attachInternals();
this._value = '';
}
get value() { return this._value; }
set value(v) {
this._value = v;
this._internals.setFormValue(v);
}
attachTemplate() {
const display = this.querySelector('[slot="display"]');
let input = this.querySelector('input[type="date"]');
if (!input) {
input = document.createElement('input');
input.type = 'date';
input.setAttribute('aria-hidden', 'true');
input.tabIndex = -1;
this.appendChild(input);
}
// Style the native input to be visually hidden but functional
input.classList.add('z-datepicker-native');
const placeholder = display?.textContent || 'Select date';
if (display) {
display.setAttribute('role', 'button');
display.setAttribute('tabindex', '0');
display.setAttribute('aria-label', 'Choose date');
display.addEventListener('click', () => {
input.showPicker?.() || input.focus();
});
display.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
input.showPicker?.() || input.focus();
}
});
}
input.addEventListener('change', () => {
this.value = input.value;
if (display && input.value) {
const date = new Date(input.value + 'T00:00:00');
display.textContent = date.toLocaleDateString(undefined, {
year: 'numeric', month: 'long', day: 'numeric'
});
display.setAttribute('data-has-value', '');
} else if (display) {
display.textContent = placeholder;
display.removeAttribute('data-has-value');
}
this.dispatchEvent(new Event('change', { bubbles: true }));
});
// Initialize from existing value
if (input.value) {
input.dispatchEvent(new Event('change'));
}
}
}
// ---------------------------------------------------------------------------
// Infinite Scroll
// ---------------------------------------------------------------------------
/**
* Infinite scroll container using IntersectionObserver.
* Watches a sentinel element at the bottom and dispatches 'loadmore'
* when it becomes visible, signaling the consumer to append content.
* Set data-loading attribute while fetching to prevent duplicate events.
*/
class ZInfiniteScroll extends ZephyrElement {
attachTemplate() {
// Scrollable region must be keyboard-reachable to scroll without a mouse
if (!this.hasAttribute('tabindex')) this.setAttribute('tabindex', '0');
// Create sentinel element
this._sentinel = document.createElement('div');
this._sentinel.classList.add('z-infinite-sentinel');
this._sentinel.setAttribute('aria-hidden', 'true');
this.appendChild(this._sentinel);
this._observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && !this.hasAttribute('data-loading') && !this.hasAttribute('data-done')) {
this.dispatchEvent(new CustomEvent('loadmore', { bubbles: true }));
}
});
}, {
root: this.hasAttribute('data-root') ? this : null,
rootMargin: this.dataset.rootMargin || '200px',
threshold: 0
});
this._observer.observe(this._sentinel);
}
/** Call when all data has been loaded to stop observing. */
complete() {
this.setAttribute('data-done', '');
if (this._observer) {
this._observer.disconnect();
}
}
_cleanup() {
super._cleanup();
if (this._observer) {
this._observer.disconnect();
this._observer = null;
}
}
}
// ---------------------------------------------------------------------------
// Sortable (Drag & Drop)
// ---------------------------------------------------------------------------
/**
* Drag & drop sortable list using the native HTML Drag and Drop API.
* Children with [data-sortable] become draggable.
* Dispatches 'sort' event with detail: { order } after reorder.
*/
class ZSortable extends ZephyrElement {
attachTemplate() {
this._draggedEl = null;
const items = () => Array.from(this.querySelectorAll('[data-sortable]'));
const setupItem = (item) => {
item.setAttribute('draggable', 'true');
item.setAttribute('role', 'listitem');
item.addEventListener('dragstart', (e) => {
this._draggedEl = item;
item.setAttribute('data-dragging', '');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', '');
});
item.addEventListener('dragend', () => {
item.removeAttribute('data-dragging');
this._draggedEl = null;
// Remove all drop indicators
items().forEach(i => i.removeAttribute('data-drag-over'));
this._emitOrder();
});
item.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (this._draggedEl && this._draggedEl !== item) {
item.setAttribute('data-drag-over', '');
}
});
item.addEventListener('dragleave', () => {
item.removeAttribute('data-drag-over');
});
item.addEventListener('drop', (e) => {
e.preventDefault();
item.removeAttribute('data-drag-over');
if (this._draggedEl && this._draggedEl !== item) {
const allItems = items();
const fromIdx = allItems.indexOf(this._draggedEl);
const toIdx = allItems.indexOf(item);
if (fromIdx < toIdx) {
item.after(this._draggedEl);
} else {
item.before(this._draggedEl);
}
}
});
};
this.setAttribute('role', 'list');
items().forEach(setupItem);
// Observe for dynamically added items
this._mutationObserver = new MutationObserver((mutations) => {
mutations.forEach(m => {
m.addedNodes.forEach(node => {
if (node.nodeType === 1 && node.hasAttribute('data-sortable')) {
setupItem(node);
}
});
});
});
this._mutationObserver.observe(this, { childList: true });
}
_emitOrder() {
const order = Array.from(this.querySelectorAll('[data-sortable]'))
.map((el, idx) => ({ index: idx, value: el.dataset.sortable || el.textContent.trim() }));
this.dispatchEvent(new CustomEvent('sort', { bubbles: true, detail: { order } }));
}
_cleanup() {
super._cleanup();
if (this._mutationObserver) {
this._mutationObserver.disconnect();
this._mutationObserver = null;
}
}
}
// ---------------------------------------------------------------------------
// File Upload
// ---------------------------------------------------------------------------
/**
* File upload component with drag-and-drop zone and progress display.
* Wraps a native <input type="file"> with a styled drop zone.
* Dispatches 'upload' event with detail: { files } when files are selected.
* Handles drag-over visual state via data-dragover attribute.
*/
class ZFileUpload extends ZephyrElement {
attachTemplate() {
const dropZone = this.querySelector('[slot="dropzone"]') || this;
let fileInput = this.querySelector('input[type="file"]');
const fileList = this.querySelector('[slot="filelist"]');
if (!fileInput) {
fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.multiple = this.hasAttribute('data-multiple');
fileInput.accept = this.dataset.accept || '';
fileInput.classList.add('z-file-input-hidden');
this.appendChild(fileInput);
}
if (!fileInput.hasAttribute('aria-label') && !fileInput.hasAttribute('aria-labelledby')) {
fileInput.setAttribute('aria-label', 'File upload');
}
// ARIA
dropZone.setAttribute('role', 'button');
dropZone.setAttribute('tabindex', '0');
dropZone.setAttribute('aria-label', 'Drop files here or click to browse');
// Click to browse
dropZone.addEventListener('click', (e) => {
if (e.target === fileInput) return;
fileInput.click();
});
dropZone.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
fileInput.click();
}
});
// Drag and drop
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
this.setAttribute('data-dragover', '');
});
dropZone.addEventListener('dragleave', (e) => {
if (!this.contains(e.relatedTarget)) {
this.removeAttribute('data-dragover');