@y14e/accordion 1.4.14 → 1.4.16

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,908 @@
1
+ // node_modules/@y14e/attributes-utils/dist/index.js
2
+ var DEFAULT_PARSER = (value) => value.split(/\s+/);
3
+ var DEFAULT_SERIALIZER = (tokens) => tokens.join(" ");
4
+ function addTokenToAttribute(element, attribute, token, options = {}) {
5
+ const {
6
+ caseInsensitive = false,
7
+ parse = DEFAULT_PARSER,
8
+ serialize = DEFAULT_SERIALIZER
9
+ } = options;
10
+ const value = element.getAttribute(attribute)?.trim();
11
+ const tokens = value ? parse(value).filter(Boolean) : [];
12
+ if (caseInsensitive) {
13
+ const lower = token.toLowerCase();
14
+ if (tokens.every((token2) => token2.toLowerCase() !== lower)) {
15
+ tokens.push(token);
16
+ element.setAttribute(attribute, serialize(tokens));
17
+ }
18
+ } else {
19
+ const set = new Set(tokens);
20
+ set.add(token);
21
+ element.setAttribute(attribute, serialize([...set]));
22
+ }
23
+ }
24
+ var snapshots = /* @__PURE__ */ new WeakMap();
25
+ function restoreAttributes(elements) {
26
+ for (const element of elements) {
27
+ const snapshot = snapshots.get(element);
28
+ if (!snapshot) {
29
+ continue;
30
+ }
31
+ for (const [attribute, value] of snapshot.entries()) {
32
+ value === null ? element.removeAttribute(attribute) : element.setAttribute(attribute, value);
33
+ }
34
+ snapshots.delete(element);
35
+ }
36
+ }
37
+ function saveAttributes(elements, attributes) {
38
+ elements.forEach((element) => {
39
+ let snapshot = snapshots.get(element);
40
+ if (!snapshot) {
41
+ snapshot = /* @__PURE__ */ new Map();
42
+ snapshots.set(element, snapshot);
43
+ }
44
+ attributes.forEach((attribute) => {
45
+ snapshot.set(attribute, element.getAttribute(attribute));
46
+ });
47
+ });
48
+ }
49
+
50
+ // node_modules/power-focusable/dist/index.js
51
+ var FOCUSABLE_SELECTOR = `:is(a[href], area[href], button, embed, iframe, input:not([type="hidden" i]), object, select, details > summary:first-of-type, textarea, [contenteditable]:not([contenteditable="false" i]), [controls], [tabindex]):not(:disabled, [hidden], [inert], [tabindex="-1"])`;
52
+ function getFocusables(container = document.body, options = {}) {
53
+ if (!(container instanceof Element)) {
54
+ console.warn("Invalid container element. Fallback: <body> element.");
55
+ container = document.body;
56
+ }
57
+ let {
58
+ composed = false,
59
+ filter,
60
+ include,
61
+ skipNegativeTabIndexCheck = false,
62
+ skipVisibilityCheck = false
63
+ } = options;
64
+ if (typeof composed !== "boolean") {
65
+ console.warn("Invalid composed option. Fallback: false.");
66
+ composed = false;
67
+ }
68
+ if (typeof filter !== "undefined" && typeof filter !== "function") {
69
+ console.warn(
70
+ "Invalid filter function. Fallback: no filter function (undefined)."
71
+ );
72
+ filter = void 0;
73
+ }
74
+ if (typeof include !== "undefined" && typeof include !== "function") {
75
+ console.warn(
76
+ "Invalid include function. Fallback: no include function (undefined)."
77
+ );
78
+ include = void 0;
79
+ }
80
+ if (typeof skipNegativeTabIndexCheck !== "boolean") {
81
+ console.warn("Invalid skipNegativeTabIndexCheck option. Fallback: false.");
82
+ skipNegativeTabIndexCheck = false;
83
+ }
84
+ if (typeof skipVisibilityCheck !== "boolean") {
85
+ console.warn("Invalid skipVisibilityCheck option. Fallback: false.");
86
+ skipVisibilityCheck = false;
87
+ }
88
+ const elements = [];
89
+ if (composed || include) {
90
+ let traverse2 = function(node) {
91
+ if (!(node instanceof Element)) {
92
+ return;
93
+ }
94
+ if (isFocusable(node, { skipNegativeTabIndexCheck, skipVisibilityCheck }) || include?.(node)) {
95
+ elements[elements.length] = node;
96
+ }
97
+ const children = getComposedChildren(node);
98
+ for (let i = 0, l = children.length; i < l; i++) {
99
+ const child = children[i];
100
+ child && traverse2(child);
101
+ }
102
+ };
103
+ traverse2(container);
104
+ } else {
105
+ const candidates = container.querySelectorAll(FOCUSABLE_SELECTOR);
106
+ for (let i = 0, l = candidates.length; i < l; i++) {
107
+ const candidate = candidates[i];
108
+ if (candidate && isFocusable(candidate, {
109
+ skipNegativeTabIndexCheck,
110
+ skipVisibilityCheck
111
+ })) {
112
+ elements[elements.length] = candidate;
113
+ }
114
+ }
115
+ }
116
+ const unfiltered = normalizeRadioGroup(sortByTabIndex(elements));
117
+ return filter ? unfiltered.filter(filter) : unfiltered;
118
+ }
119
+ function isFocusable(element, options = {}) {
120
+ if (!(element instanceof Element)) {
121
+ console.warn("Invalid element");
122
+ return false;
123
+ }
124
+ let { skipNegativeTabIndexCheck = false, skipVisibilityCheck = false } = options;
125
+ if (typeof skipNegativeTabIndexCheck !== "boolean") {
126
+ console.warn("Invalid skipNegativeTabIndexCheck option. Fallback: false.");
127
+ skipNegativeTabIndexCheck = false;
128
+ }
129
+ if (typeof skipVisibilityCheck !== "boolean") {
130
+ console.warn("Invalid skipVisibilityCheck option. Fallback: false.");
131
+ skipVisibilityCheck = false;
132
+ }
133
+ if (element.hasAttribute("hidden") || isInert(element)) {
134
+ return false;
135
+ }
136
+ if (!skipNegativeTabIndexCheck && getTabIndex(element) < 0) {
137
+ return false;
138
+ }
139
+ if (!element.matches(
140
+ skipNegativeTabIndexCheck ? FOCUSABLE_SELECTOR.replace(/(,\s*)?\[tabindex="-1"\]/g, "") : FOCUSABLE_SELECTOR
141
+ )) {
142
+ return false;
143
+ }
144
+ if (isDisabledDeep(element)) {
145
+ return false;
146
+ }
147
+ if (!skipVisibilityCheck && !element.checkVisibility({
148
+ contentVisibilityAuto: true,
149
+ opacityProperty: true,
150
+ visibilityProperty: true
151
+ })) {
152
+ return false;
153
+ }
154
+ return true;
155
+ }
156
+ function isDisabledDeep(element) {
157
+ let current = element;
158
+ while (current) {
159
+ if (current instanceof ShadowRoot) {
160
+ if (current.mode !== "open") {
161
+ return false;
162
+ }
163
+ current = current.host;
164
+ continue;
165
+ }
166
+ if (!(current instanceof Element)) {
167
+ current = current.parentNode;
168
+ continue;
169
+ }
170
+ if (current === element && isFormControl(current) && isDisabled(current)) {
171
+ return true;
172
+ }
173
+ if (isInert(current)) {
174
+ return true;
175
+ }
176
+ if (isFormControl(element) && current.tagName === "FIELDSET" && isDisabled(current)) {
177
+ if (!current.querySelector(":scope > legend:first-of-type")?.contains(element)) {
178
+ return true;
179
+ }
180
+ }
181
+ current = current.parentNode;
182
+ }
183
+ return false;
184
+ }
185
+ function normalizeRadioGroup(elements) {
186
+ let map = null;
187
+ for (let i = 0, l = elements.length; i < l; i++) {
188
+ const element = elements[i];
189
+ if (!(element instanceof HTMLInputElement)) {
190
+ continue;
191
+ }
192
+ if (!isUngroupedRadio(element)) {
193
+ continue;
194
+ }
195
+ if (!map) {
196
+ map = /* @__PURE__ */ new Map();
197
+ }
198
+ const key = `${element.form?.id ?? "no-form"}::${element.name}`;
199
+ const group = map.get(key) ?? map.set(key, []).get(key);
200
+ if (group) {
201
+ group[group.length] = element;
202
+ }
203
+ }
204
+ if (!map) {
205
+ return elements;
206
+ }
207
+ const placeholder = /* @__PURE__ */ new Set();
208
+ for (const group of map.values()) {
209
+ placeholder.add(group.find((radio) => radio.checked) ?? group[0]);
210
+ }
211
+ return elements.filter(
212
+ (element) => isUngroupedRadio(element) ? placeholder.has(element) : true
213
+ );
214
+ }
215
+ function sortByTabIndex(elements) {
216
+ const ordered = [];
217
+ const natural = [];
218
+ for (let i = 0, l = elements.length; i < l; i++) {
219
+ const element = elements[i];
220
+ if (element) {
221
+ const target = getTabIndex(element) > 0 ? ordered : natural;
222
+ target[target.length] = element;
223
+ }
224
+ }
225
+ ordered.sort((a, b) => getTabIndex(a) - getTabIndex(b));
226
+ let count = 0;
227
+ const sorted = new Array(ordered.length + natural.length);
228
+ for (let i = 0, l = ordered.length; i < l; i++) {
229
+ sorted[count++] = ordered[i];
230
+ }
231
+ for (let i = 0, l = natural.length; i < l; i++) {
232
+ sorted[count++] = natural[i];
233
+ }
234
+ return sorted;
235
+ }
236
+ function getComposedChildren(node) {
237
+ if (node instanceof ShadowRoot) {
238
+ return getChildren(node);
239
+ }
240
+ if (!(node instanceof Element)) {
241
+ return [];
242
+ }
243
+ if (node instanceof HTMLSlotElement) {
244
+ const assigned = node.assignedElements({ flatten: true });
245
+ if (assigned.length) {
246
+ return assigned;
247
+ }
248
+ }
249
+ if (node instanceof HTMLElement && node.shadowRoot?.mode === "open") {
250
+ return getChildren(node.shadowRoot);
251
+ }
252
+ return getChildren(node);
253
+ }
254
+ function focusElement(element) {
255
+ "focus" in element && typeof element.focus === "function" && element.focus();
256
+ }
257
+ function getActiveElement() {
258
+ let current = document.activeElement;
259
+ while (current?.shadowRoot?.activeElement) {
260
+ current = current.shadowRoot.activeElement;
261
+ }
262
+ return current;
263
+ }
264
+ function getChildren(node) {
265
+ const elements = [];
266
+ for (let child = node.firstElementChild; child; child = child.nextElementSibling) {
267
+ elements[elements.length] = child;
268
+ }
269
+ return elements;
270
+ }
271
+ function getTabIndex(element) {
272
+ return "tabIndex" in element ? Number(element.tabIndex) : 0;
273
+ }
274
+ function isDisabled(element) {
275
+ return "disabled" in element && !!element.disabled;
276
+ }
277
+ function isFormControl(element) {
278
+ const name = element.tagName;
279
+ return name === "BUTTON" || name === "INPUT" || name === "SELECT" || name === "TEXTAREA";
280
+ }
281
+ function isInert(element) {
282
+ return "inert" in element && !!element.inert;
283
+ }
284
+ function isUngroupedRadio(element) {
285
+ return element instanceof HTMLInputElement && element.type === "radio" && !!element.name;
286
+ }
287
+
288
+ // node_modules/@y14e/button/dist/index.js
289
+ var Button = class {
290
+ #element;
291
+ #controller = null;
292
+ #isDestroyed = false;
293
+ constructor(element) {
294
+ if (!(element instanceof HTMLElement)) {
295
+ throw new TypeError("Invalid element");
296
+ }
297
+ if (element.hasAttribute("data-button-initialized")) {
298
+ console.warn("Already initialized");
299
+ return;
300
+ }
301
+ this.#element = element;
302
+ this.#initialize();
303
+ }
304
+ destroy() {
305
+ if (this.#isDestroyed) {
306
+ return;
307
+ }
308
+ this.#isDestroyed = true;
309
+ this.#controller?.abort();
310
+ this.#controller = null;
311
+ this.#element.removeAttribute("data-button-initialized");
312
+ }
313
+ #initialize() {
314
+ this.#controller = new AbortController();
315
+ this.#element.addEventListener("keydown", this.#onKeyDown, {
316
+ signal: this.#controller.signal
317
+ });
318
+ this.#element.setAttribute("data-button-initialized", "");
319
+ }
320
+ #onKeyDown = (event) => {
321
+ const { key, altKey, ctrlKey, metaKey, shiftKey } = event;
322
+ if (altKey || ctrlKey || metaKey || shiftKey) {
323
+ return;
324
+ }
325
+ if (!["Enter", " "].includes(key)) {
326
+ return;
327
+ }
328
+ const active = getActiveElement();
329
+ if (!(active instanceof HTMLElement)) {
330
+ return;
331
+ }
332
+ event.preventDefault();
333
+ active.click();
334
+ };
335
+ };
336
+
337
+ // node_modules/@y14e/roving-tabindex/dist/index.js
338
+ function createRovingTabIndex(container, options = {}) {
339
+ if (!(container instanceof Element)) {
340
+ console.warn("Invalid container element");
341
+ return () => {
342
+ };
343
+ }
344
+ const roving = new RovingTabIndex(container, options);
345
+ return () => roving.destroy();
346
+ }
347
+ var RovingTabIndex = class _RovingTabIndex {
348
+ static #initialized = /* @__PURE__ */ new Set();
349
+ #container;
350
+ #settings;
351
+ #focusables = /* @__PURE__ */ new Set();
352
+ #focusablesByFirstChar = /* @__PURE__ */ new Map();
353
+ #selectorFilter;
354
+ #controller = null;
355
+ #isDestroyed = false;
356
+ constructor(container, options = {}) {
357
+ this.#container = container;
358
+ let {
359
+ direction,
360
+ navigationOnly = false,
361
+ noMemory = false,
362
+ noStart = false,
363
+ selector,
364
+ typeahead = false,
365
+ wrap = false
366
+ } = options;
367
+ if (typeof direction !== "undefined" && !["horizontal", "vertical"].includes(direction)) {
368
+ console.warn("Invalid direction option. Fallback: both (undefined).");
369
+ direction = void 0;
370
+ }
371
+ if (typeof navigationOnly !== "boolean") {
372
+ console.warn("Invalid navigationOnly option. Fallback: false.");
373
+ navigationOnly = false;
374
+ }
375
+ if (typeof noMemory !== "boolean") {
376
+ console.warn("Invalid noMemory option. Fallback: false.");
377
+ noMemory = false;
378
+ }
379
+ if (typeof noStart !== "boolean") {
380
+ console.warn("Invalid noStart option. Fallback: false.");
381
+ noStart = false;
382
+ }
383
+ if (typeof selector !== "undefined" && (typeof selector !== "string" || !selector.trim())) {
384
+ console.warn(
385
+ "Invalid selector. Fallback: all focusable elements (undefined)."
386
+ );
387
+ selector = void 0;
388
+ }
389
+ if (typeof typeahead !== "boolean") {
390
+ console.warn("Invalid typeahead option. Fallback: false.");
391
+ typeahead = false;
392
+ }
393
+ if (typeof wrap !== "boolean") {
394
+ console.warn("Invalid wrap option. Fallback: false.");
395
+ wrap = false;
396
+ }
397
+ this.#settings = {
398
+ navigationOnly,
399
+ noMemory,
400
+ noStart,
401
+ typeahead,
402
+ wrap
403
+ };
404
+ direction && Object.assign(this.#settings, { direction });
405
+ selector && Object.assign(this.#settings, { selector });
406
+ this.#selectorFilter = this.#createSelectorFilter();
407
+ this.#initialize();
408
+ }
409
+ destroy() {
410
+ if (this.#isDestroyed) {
411
+ return;
412
+ }
413
+ this.#isDestroyed = true;
414
+ this.#controller?.abort();
415
+ this.#controller = null;
416
+ restoreAttributes([...this.#focusables]);
417
+ this.#focusables.clear();
418
+ this.#focusablesByFirstChar.clear();
419
+ }
420
+ #initialize() {
421
+ this.#update(document.activeElement);
422
+ if (!(this.#container instanceof HTMLElement)) {
423
+ return;
424
+ }
425
+ this.#controller = new AbortController();
426
+ const { signal } = this.#controller;
427
+ this.#container.addEventListener("focusin", this.#onFocusIn, {
428
+ capture: true,
429
+ signal
430
+ });
431
+ this.#container.addEventListener("keydown", this.#onKeyDown, {
432
+ capture: true,
433
+ signal
434
+ });
435
+ }
436
+ #onFocusIn = (event) => {
437
+ const { target } = event;
438
+ if (!(target instanceof Element)) {
439
+ return;
440
+ }
441
+ const isFocusable3 = this.#focusables.has(target);
442
+ this.#settings.noMemory && !isFocusable3 ? this.#update(null) : isFocusable3 && this.#update(target);
443
+ };
444
+ #onKeyDown = (event) => {
445
+ const { key, altKey, ctrlKey, metaKey, shiftKey } = event;
446
+ if (altKey || ctrlKey || metaKey || shiftKey) {
447
+ return;
448
+ }
449
+ const { direction, typeahead, wrap } = this.#settings;
450
+ const isBoth = !direction;
451
+ const isHorizontal = direction === "horizontal";
452
+ if (![
453
+ "End",
454
+ "Home",
455
+ ...isBoth ? ["ArrowLeft", "ArrowUp"] : [`Arrow${isHorizontal ? "Left" : "Up"}`],
456
+ ...isBoth ? ["ArrowRight", "ArrowDown"] : [`Arrow${isHorizontal ? "Right" : "Down"}`]
457
+ ].includes(key)) {
458
+ if (!typeahead || !/^\S$/i.test(key) || !this.#focusablesByFirstChar.has(key.toUpperCase())) {
459
+ return;
460
+ }
461
+ }
462
+ const active = getActiveElement();
463
+ if (!(active instanceof HTMLElement)) {
464
+ return;
465
+ }
466
+ const current = this.#getFocusables();
467
+ if (!current.includes(active)) {
468
+ return;
469
+ }
470
+ event.preventDefault();
471
+ const currentIndex = current.indexOf(active);
472
+ let newIndex;
473
+ let target = current;
474
+ switch (key) {
475
+ case "End":
476
+ newIndex = -1;
477
+ break;
478
+ case "Home":
479
+ newIndex = 0;
480
+ break;
481
+ case "ArrowLeft":
482
+ case "ArrowUp": {
483
+ const rawIndex = currentIndex - 1;
484
+ newIndex = wrap ? rawIndex : Math.max(rawIndex, 0);
485
+ break;
486
+ }
487
+ case "ArrowRight":
488
+ case "ArrowDown": {
489
+ const rawIndex = currentIndex + 1;
490
+ newIndex = wrap ? rawIndex % current.length : Math.min(rawIndex, current.length - 1);
491
+ break;
492
+ }
493
+ default: {
494
+ target = this.#focusablesByFirstChar.get(key.toUpperCase()) ?? [];
495
+ const foundIndex = target.findIndex(
496
+ (focusable2) => current.indexOf(focusable2) > currentIndex
497
+ );
498
+ newIndex = foundIndex >= 0 ? foundIndex : 0;
499
+ }
500
+ }
501
+ const focusable = target.at(newIndex);
502
+ focusable && focusElement(focusable);
503
+ };
504
+ #update(active) {
505
+ const current = new Set(this.#getFocusables());
506
+ for (const focusable of this.#focusables) {
507
+ if (!current.has(focusable)) {
508
+ focusable.isConnected && restoreAttributes([focusable]);
509
+ this.#focusables.delete(focusable);
510
+ this.#focusablesByFirstChar.forEach((focusables) => {
511
+ const index = focusables.indexOf(focusable);
512
+ index >= 0 && focusables.splice(index, 1);
513
+ });
514
+ }
515
+ }
516
+ const { navigationOnly, noStart, typeahead } = this.#settings;
517
+ for (const focusable of current) {
518
+ if (this.#focusables.has(focusable)) {
519
+ continue;
520
+ }
521
+ if (_RovingTabIndex.#initialized.has(focusable)) {
522
+ throw new TypeError("Already initialized");
523
+ }
524
+ this.#focusables.add(focusable);
525
+ _RovingTabIndex.#initialized.add(focusable);
526
+ if (!navigationOnly) {
527
+ saveAttributes([focusable], ["tabindex"]);
528
+ focusable.setAttribute("tabindex", "-1");
529
+ }
530
+ if (!typeahead) {
531
+ continue;
532
+ }
533
+ const char = focusable.textContent?.trim()?.at(0)?.toUpperCase();
534
+ const value = focusable.ariaKeyShortcuts?.trim();
535
+ const keys = new Set(
536
+ value ? value.split(/\s+/).filter((key) => /^\S$/i.test(key)).map((key) => key.toUpperCase()) : []
537
+ );
538
+ if (char) {
539
+ keys.add(char);
540
+ saveAttributes([focusable], ["aria-keyshortcuts"]);
541
+ addTokenToAttribute(focusable, "aria-keyshortcuts", char, {
542
+ caseInsensitive: true
543
+ });
544
+ }
545
+ keys.forEach((key) => {
546
+ const focusables = this.#focusablesByFirstChar.get(key) ?? [];
547
+ focusables.push(focusable);
548
+ this.#focusablesByFirstChar.set(key, focusables);
549
+ });
550
+ }
551
+ if (!navigationOnly) {
552
+ if (active && this.#focusables.has(active)) {
553
+ this.#focusables.forEach((focusable) => {
554
+ focusable.setAttribute("tabindex", focusable === active ? "0" : "-1");
555
+ });
556
+ } else {
557
+ [...this.#focusables].forEach((focusable, i) => {
558
+ focusable.setAttribute("tabindex", i || noStart ? "-1" : "0");
559
+ });
560
+ }
561
+ }
562
+ }
563
+ #createSelectorFilter() {
564
+ const { selector } = this.#settings;
565
+ return (element) => !selector || [...this.#container.querySelectorAll(selector)].includes(element);
566
+ }
567
+ #getFocusables() {
568
+ return getFocusables(this.#container, {
569
+ composed: true,
570
+ filter: this.#selectorFilter,
571
+ skipNegativeTabIndexCheck: !this.#settings.navigationOnly,
572
+ skipVisibilityCheck: true
573
+ });
574
+ }
575
+ };
576
+
577
+ // src/index.ts
578
+ var Accordion = class _Accordion {
579
+ static defaults = {};
580
+ #rootElement;
581
+ #defaults = {
582
+ animation: { duration: 300, easing: "ease" },
583
+ selector: {
584
+ content: ":has(> [data-accordion-trigger]) + *",
585
+ trigger: "[data-accordion-trigger]"
586
+ }
587
+ };
588
+ #settings;
589
+ #triggerElements;
590
+ #contentElements;
591
+ #bindings = /* @__PURE__ */ new WeakMap();
592
+ #eventController = null;
593
+ #animationController = null;
594
+ #cleanupRovingTabIndex = null;
595
+ #buttons = [];
596
+ #isDestroyed = false;
597
+ constructor(root, options = {}) {
598
+ if (!(root instanceof HTMLElement)) {
599
+ throw new TypeError("Invalid root element");
600
+ }
601
+ if (root.hasAttribute("data-accordion-initialized")) {
602
+ console.warn("Already initialized");
603
+ return;
604
+ }
605
+ this.#rootElement = root;
606
+ this.#defaults = this.#mergeOptions(this.#defaults, _Accordion.defaults);
607
+ this.#settings = this.#mergeOptions(this.#defaults, options);
608
+ matchMedia("(prefers-reduced-motion: reduce)").matches && Object.assign(this.#settings.animation, { duration: 0 });
609
+ const { trigger, content } = this.#settings.selector;
610
+ const NOT_NESTED = `:not(:scope ${content} *)`;
611
+ this.#triggerElements = [
612
+ ...this.#rootElement.querySelectorAll(
613
+ `${trigger}${NOT_NESTED}`
614
+ )
615
+ ];
616
+ if (!this.#triggerElements.length) {
617
+ console.warn("Missing trigger elements");
618
+ return;
619
+ }
620
+ this.#contentElements = [
621
+ ...this.#rootElement.querySelectorAll(
622
+ `${content}${NOT_NESTED}`
623
+ )
624
+ ];
625
+ if (!this.#contentElements.length) {
626
+ console.warn("Missing content elements");
627
+ return;
628
+ }
629
+ this.#triggerElements.forEach((trigger2, i) => {
630
+ const content2 = this.#contentElements[i];
631
+ if (!content2) {
632
+ return;
633
+ }
634
+ const binding = createBinding(trigger2, content2);
635
+ this.#bindings.set(trigger2, binding);
636
+ this.#bindings.set(content2, binding);
637
+ });
638
+ this.#initialize();
639
+ }
640
+ close(trigger) {
641
+ if (this.#isDestroyed) {
642
+ return;
643
+ }
644
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
645
+ console.warn("Invalid trigger element");
646
+ return;
647
+ }
648
+ this.#toggle(trigger, false);
649
+ }
650
+ async destroy(force = false) {
651
+ if (this.#isDestroyed) {
652
+ return;
653
+ }
654
+ this.#isDestroyed = true;
655
+ this.#eventController?.abort();
656
+ this.#eventController = null;
657
+ this.#cleanupRovingTabIndex?.();
658
+ this.#cleanupRovingTabIndex = null;
659
+ this.#buttons.forEach((button) => {
660
+ button.destroy();
661
+ });
662
+ this.#buttons.length = 0;
663
+ !force && await this.#waitAnimationsFinish();
664
+ this.#contentElements.forEach((content) => {
665
+ force && this.#bindings.get(content)?.animation?.finish();
666
+ this.#onAnimationFinish(content);
667
+ });
668
+ this.#animationController?.abort();
669
+ this.#animationController = null;
670
+ restoreAttributes([...this.#triggerElements, ...this.#contentElements]);
671
+ this.#triggerElements.length = 0;
672
+ this.#contentElements.length = 0;
673
+ this.#rootElement.removeAttribute("data-accordion-initialized");
674
+ }
675
+ open(trigger) {
676
+ if (this.#isDestroyed) {
677
+ return;
678
+ }
679
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
680
+ console.warn("Invalid trigger element");
681
+ return;
682
+ }
683
+ this.#toggle(trigger, true);
684
+ }
685
+ #initialize() {
686
+ saveAttributes(this.#triggerElements, [
687
+ "aria-controls",
688
+ "aria-disabled",
689
+ "id",
690
+ "style",
691
+ "tabindex"
692
+ ]);
693
+ saveAttributes(this.#contentElements, ["aria-labelledby", "id", "role"]);
694
+ this.#eventController = new AbortController();
695
+ const { signal } = this.#eventController;
696
+ this.#triggerElements.forEach((trigger2, i) => {
697
+ const id = Math.random().toString(36).slice(-8);
698
+ const content2 = this.#contentElements[i];
699
+ if (!content2) {
700
+ return;
701
+ }
702
+ content2.id ||= `accordion-content-${id}`;
703
+ addTokenToAttribute(trigger2, "aria-controls", content2.id);
704
+ trigger2.setAttribute(
705
+ "aria-expanded",
706
+ String(trigger2.ariaExpanded === "true")
707
+ );
708
+ trigger2.id ||= `accordion-trigger-${id}`;
709
+ if (!isFocusable2(trigger2)) {
710
+ trigger2.setAttribute("aria-disabled", "true");
711
+ trigger2.setAttribute("tabindex", "-1");
712
+ trigger2.style.setProperty("pointer-events", "none");
713
+ }
714
+ trigger2.addEventListener("click", this.#onTriggerClick, { signal });
715
+ addTokenToAttribute(content2, "aria-labelledby", trigger2.id);
716
+ content2.setAttribute("role", "region");
717
+ content2.addEventListener("beforematch", this.#onContentBeforeMatch, {
718
+ signal
719
+ });
720
+ this.#buttons.push(new Button(trigger2));
721
+ });
722
+ const { trigger, content } = this.#settings.selector;
723
+ this.#cleanupRovingTabIndex = createRovingTabIndex(this.#rootElement, {
724
+ direction: "vertical",
725
+ navigationOnly: true,
726
+ selector: `${trigger}:not(:scope ${content} *)`,
727
+ wrap: true
728
+ });
729
+ this.#rootElement.setAttribute("data-accordion-initialized", "");
730
+ }
731
+ #onTriggerClick = (event) => {
732
+ event.preventDefault();
733
+ const trigger = event.currentTarget;
734
+ if (!(trigger instanceof HTMLElement)) {
735
+ return;
736
+ }
737
+ this.#toggle(trigger, trigger.ariaExpanded === "false");
738
+ };
739
+ #onContentBeforeMatch = (event) => {
740
+ const content = event.currentTarget;
741
+ if (!(content instanceof HTMLElement)) {
742
+ return;
743
+ }
744
+ const binding = this.#bindings.get(content);
745
+ if (!binding) {
746
+ return;
747
+ }
748
+ binding.trigger.ariaExpanded === "false" && this.#toggle(binding.trigger, true, true);
749
+ };
750
+ #toggle(trigger, isOpen, isMatch = false) {
751
+ if (trigger.ariaExpanded === String(isOpen)) {
752
+ return;
753
+ }
754
+ const name = trigger.getAttribute("data-accordion-name");
755
+ if (name && isOpen) {
756
+ const opened = this.#triggerElements.find(
757
+ (t) => t !== trigger && t.getAttribute("data-accordion-name") === name && t.ariaExpanded === "true"
758
+ );
759
+ opened && this.#toggle(opened, false, isMatch);
760
+ }
761
+ trigger.setAttribute(
762
+ "aria-label",
763
+ trigger.getAttribute(
764
+ `data-accordion-${isOpen ? "expanded" : "collapsed"}-label`
765
+ ) ?? trigger.ariaLabel ?? ""
766
+ );
767
+ const binding = this.#bindings.get(trigger);
768
+ if (!binding) {
769
+ return;
770
+ }
771
+ const { content } = binding;
772
+ const startSize = content.hidden ? 0 : content.offsetHeight;
773
+ if (content.hidden) {
774
+ content.hidden = false;
775
+ }
776
+ const endSize = isOpen ? content.scrollHeight : 0;
777
+ binding.animation?.cancel();
778
+ content.style.setProperty("overflow", "clip");
779
+ const { duration, easing } = this.#settings.animation;
780
+ const animation = content.animate(
781
+ { blockSize: [`${startSize}px`, `${endSize}px`] },
782
+ { duration: isMatch ? 0 : duration, easing }
783
+ );
784
+ binding.animation = animation;
785
+ trigger.setAttribute("aria-expanded", String(isOpen));
786
+ function cleanup() {
787
+ if (binding?.animation === animation) {
788
+ binding.animation = null;
789
+ }
790
+ }
791
+ this.#animationController = new AbortController();
792
+ const { signal } = this.#animationController;
793
+ animation.addEventListener("cancel", cleanup, { once: true, signal });
794
+ animation.addEventListener(
795
+ "finish",
796
+ () => {
797
+ if (binding?.animation === animation) {
798
+ this.#onAnimationFinish(content);
799
+ cleanup();
800
+ }
801
+ },
802
+ { once: true, signal }
803
+ );
804
+ }
805
+ #mergeOptions(target, source) {
806
+ return {
807
+ animation: { ...target.animation, ...source.animation ?? {} },
808
+ selector: { ...target.selector, ...source.selector ?? {} }
809
+ };
810
+ }
811
+ #onAnimationFinish(content) {
812
+ const trigger = this.#bindings.get(content)?.trigger;
813
+ if (!trigger) {
814
+ return;
815
+ }
816
+ if (trigger.ariaExpanded === "false") {
817
+ content.setAttribute("hidden", "until-found");
818
+ }
819
+ ["block-size", "overflow"].forEach((name) => {
820
+ content.style.removeProperty(name);
821
+ });
822
+ }
823
+ async #waitAnimationsFinish() {
824
+ const promises = [];
825
+ this.#contentElements.forEach((content) => {
826
+ const animation = this.#bindings.get(content)?.animation;
827
+ animation && promises.push(waitAnimationFinish(animation));
828
+ });
829
+ await Promise.allSettled(promises);
830
+ }
831
+ };
832
+ function createBinding(trigger, content) {
833
+ return { trigger, content, animation: null };
834
+ }
835
+ function isFocusable2(element) {
836
+ return !element.hasAttribute("disabled") && element.tabIndex >= 0;
837
+ }
838
+ function waitAnimationFinish(animation) {
839
+ if (["idle", "finished"].includes(animation.playState)) {
840
+ return Promise.resolve();
841
+ } else {
842
+ return new Promise(
843
+ (resolve) => animation.addEventListener("finish", () => resolve(), { once: true })
844
+ );
845
+ }
846
+ }
847
+ /**
848
+ * Accordion
849
+ * WAI-ARIA compliant accordion pattern implementation in TypeScript.
850
+ *
851
+ * @version 1.4.16
852
+ * @author Yusuke Kamiyamane
853
+ * @license MIT
854
+ * @copyright Copyright (c) Yusuke Kamiyamane
855
+ * @see {@link https://github.com/y14e/accordion}
856
+ */
857
+ /*! Bundled license information:
858
+
859
+ @y14e/attributes-utils/dist/index.js:
860
+ (**
861
+ * Attributes Utils
862
+ *
863
+ * @version 1.1.2
864
+ * @author Yusuke Kamiyamane
865
+ * @license MIT
866
+ * @copyright Copyright (c) Yusuke Kamiyamane
867
+ * @see {@link https://github.com/y14e/attributes-utils}
868
+ *)
869
+
870
+ power-focusable/dist/index.js:
871
+ (**
872
+ * Power Focusable
873
+ * High-precision focus management utility with full composed tree support.
874
+ * Handles complex focus rules including tabindex ordering, radio groups, inert.
875
+ *
876
+ * @version 4.3.3
877
+ * @author Yusuke Kamiyamane
878
+ * @license MIT
879
+ * @copyright Copyright (c) Yusuke Kamiyamane
880
+ * @see {@link https://github.com/y14e/power-focusable}
881
+ *)
882
+
883
+ @y14e/button/dist/index.js:
884
+ (**
885
+ * Button
886
+ *
887
+ * @version 1.0.6
888
+ * @author Yusuke Kamiyamane
889
+ * @license MIT
890
+ * @copyright Copyright (c) Yusuke Kamiyamane
891
+ * @see {@link https://github.com/y14e/button}
892
+ *)
893
+
894
+ @y14e/roving-tabindex/dist/index.js:
895
+ (**
896
+ * Roving Tabindex
897
+ * Lightweight roving tabindex utility with fully focus management.
898
+ * Designed for accessible menus, tabs, toolbars, and composite widgets.
899
+ *
900
+ * @version 3.0.12
901
+ * @author Yusuke Kamiyamane
902
+ * @license MIT
903
+ * @copyright Copyright (c) Yusuke Kamiyamane
904
+ * @see {@link https://github.com/y14e/roving-tabindex}
905
+ *)
906
+ */
907
+
908
+ export { Accordion as default };