@y14e/accordion 1.2.4

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yusuke Kamiyamane
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # Accordion
2
+
3
+ WAI-ARIA compliant [accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) pattern implementation in TypeScript.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @y14e/accordion
9
+ ```
10
+
11
+ ```ts
12
+ // npm
13
+ import Accordion from '@y14e/accordion';
14
+
15
+ // CDNs
16
+ import Accordion from 'https://esm.sh/@y14e/accordion'
17
+ // or
18
+ import Accordion from 'https://cdn.jsdelivr.net/npm/@y14e/accordion/+esm';
19
+ // or
20
+ import Accordion from 'https://unpkg.com/@y14e/accordion/dist/index.js';
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ new Accordion(root, options);
27
+ // => Accordion
28
+ //
29
+ // root: HTMLElement
30
+ // options (optional): AccordionOptions
31
+
32
+ ```
33
+
34
+ ## 🪄 Options
35
+
36
+ ```ts
37
+ interface AccordionOptions {
38
+ animation?: {
39
+ duration?: number; // ms (default: 300)
40
+ easing?: string; // <easing-function> (default: 'ease')
41
+ };
42
+ selector?: {
43
+ content?: string; // default: ':has(> [data-accordion-trigger]) + *'
44
+ trigger?: string; // default: '[data-accordion-trigger]'
45
+ };
46
+ }
47
+ ```
48
+
49
+ ### ⚙️ Customize defaults
50
+
51
+ Override the global default settings applied to all accordion instances.
52
+
53
+ ```ts
54
+ import Accordion from './accordion';
55
+
56
+ Accordion.defaults = {
57
+ animation: {
58
+ duration: 1000,
59
+ },
60
+ selector: {
61
+ content: '.content',
62
+ trigger: '.trigger',
63
+ },
64
+ };
65
+
66
+ new Accordion(root);
67
+ ```
68
+
69
+ ## 📦 APIs
70
+
71
+ ### `open`
72
+
73
+ ```ts
74
+ accordion.open(trigger);
75
+ // => void
76
+ //
77
+ // trigger: HTMLElement
78
+ ```
79
+
80
+ ### `close`
81
+
82
+ ```ts
83
+ accordion.close(trigger);
84
+ // => void
85
+ //
86
+ // trigger: HTMLElement
87
+ ```
88
+
89
+ ### `destroy`
90
+
91
+ Destroys the instance and cleans up all event listeners.
92
+
93
+ ```ts
94
+ accordion.destroy(force);
95
+ // => Promise<void>
96
+ //
97
+ // force (optional): If true, skips waiting for animations to finish.
98
+ ```
99
+
100
+ ## Demo
101
+
102
+ https://y14e.github.io/accordion-ts/
package/dist/index.cjs ADDED
@@ -0,0 +1,309 @@
1
+ 'use strict';
2
+
3
+ // src/index.ts
4
+ var Accordion = class _Accordion {
5
+ static defaults = {};
6
+ #rootElement;
7
+ #defaults = {
8
+ animation: { duration: 300, easing: "ease" },
9
+ selector: {
10
+ content: ":has(> [data-accordion-trigger]) + *",
11
+ trigger: "[data-accordion-trigger]"
12
+ }
13
+ };
14
+ #settings;
15
+ #triggerElements;
16
+ #contentElements;
17
+ #bindings = /* @__PURE__ */ new WeakMap();
18
+ #eventController = null;
19
+ #animationController = null;
20
+ #isDestroyed = false;
21
+ constructor(root, options = {}) {
22
+ if (!(root instanceof HTMLElement)) {
23
+ throw new TypeError("Invalid root element");
24
+ }
25
+ if (root.hasAttribute("data-accordion-initialized")) {
26
+ console.warn("Already initialized");
27
+ return;
28
+ }
29
+ this.#rootElement = root;
30
+ this.#defaults = this.#mergeOptions(this.#defaults, _Accordion.defaults);
31
+ this.#settings = this.#mergeOptions(this.#defaults, options);
32
+ matchMedia("(prefers-reduced-motion: reduce)").matches && Object.assign(this.#settings.animation, { duration: 0 });
33
+ const { trigger, content } = this.#settings.selector;
34
+ const NOT_NESTED = `:not(:scope ${content} *)`;
35
+ this.#triggerElements = [
36
+ ...this.#rootElement.querySelectorAll(
37
+ `${trigger}${NOT_NESTED}`
38
+ )
39
+ ];
40
+ if (!this.#triggerElements.length) {
41
+ console.warn("Missing trigger elements");
42
+ return;
43
+ }
44
+ this.#contentElements = [
45
+ ...this.#rootElement.querySelectorAll(
46
+ `${content}${NOT_NESTED}`
47
+ )
48
+ ];
49
+ if (!this.#contentElements.length) {
50
+ console.warn("Missing content elements");
51
+ return;
52
+ }
53
+ this.#triggerElements.forEach((trigger2, i) => {
54
+ const content2 = this.#contentElements[i];
55
+ if (!content2) {
56
+ return;
57
+ }
58
+ const binding = createBinding(trigger2, content2);
59
+ this.#bindings.set(trigger2, binding);
60
+ this.#bindings.set(content2, binding);
61
+ });
62
+ this.#initialize();
63
+ }
64
+ open(trigger) {
65
+ if (this.#isDestroyed) {
66
+ return;
67
+ }
68
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
69
+ console.warn("Invalid trigger element");
70
+ return;
71
+ }
72
+ this.#toggle(trigger, true);
73
+ }
74
+ close(trigger) {
75
+ if (this.#isDestroyed) {
76
+ return;
77
+ }
78
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
79
+ console.warn("Invalid trigger element");
80
+ return;
81
+ }
82
+ this.#toggle(trigger, false);
83
+ }
84
+ async destroy(force = false) {
85
+ if (this.#isDestroyed) {
86
+ return;
87
+ }
88
+ this.#isDestroyed = true;
89
+ this.#eventController?.abort();
90
+ this.#eventController = null;
91
+ !force && await this.#waitAnimationsFinish();
92
+ this.#contentElements.forEach((content) => {
93
+ force && this.#bindings.get(content)?.animation?.finish();
94
+ this.#onAnimationFinish(content);
95
+ });
96
+ this.#animationController?.abort();
97
+ this.#animationController = null;
98
+ this.#triggerElements.length = 0;
99
+ this.#contentElements.length = 0;
100
+ this.#rootElement.removeAttribute("data-accordion-initialized");
101
+ }
102
+ #initialize() {
103
+ this.#eventController = new AbortController();
104
+ const { signal } = this.#eventController;
105
+ this.#triggerElements.forEach((trigger, i) => {
106
+ const id = Math.random().toString(36).slice(-8);
107
+ const content = this.#contentElements[i];
108
+ if (!content) {
109
+ return;
110
+ }
111
+ content.id ||= `accordion-content-${id}`;
112
+ addTokenToAttribute(trigger, "aria-controls", content.id);
113
+ trigger.setAttribute(
114
+ "aria-expanded",
115
+ trigger.ariaExpanded === "true" ? "true" : "false"
116
+ );
117
+ trigger.id ||= `accordion-trigger-${id}`;
118
+ if (!isFocusable(trigger)) {
119
+ trigger.setAttribute("aria-disabled", "true");
120
+ trigger.setAttribute("tabindex", "-1");
121
+ trigger.style.setProperty("pointer-events", "none");
122
+ }
123
+ trigger.addEventListener("click", this.#onTriggerClick, { signal });
124
+ trigger.addEventListener("keydown", this.#onTriggerKeyDown, { signal });
125
+ addTokenToAttribute(content, "aria-labelledby", trigger.id);
126
+ content.setAttribute("role", "region");
127
+ content.addEventListener("beforematch", this.#onContentBeforeMatch, {
128
+ signal
129
+ });
130
+ });
131
+ this.#rootElement.setAttribute("data-accordion-initialized", "");
132
+ }
133
+ #onTriggerClick = (event) => {
134
+ event.preventDefault();
135
+ event.stopPropagation();
136
+ const trigger = event.currentTarget;
137
+ if (!(trigger instanceof HTMLElement)) {
138
+ return;
139
+ }
140
+ this.#toggle(trigger, trigger.ariaExpanded !== "true");
141
+ };
142
+ #onTriggerKeyDown = (event) => {
143
+ const { key } = event;
144
+ if (!["Enter", " ", "End", "Home", "ArrowUp", "ArrowDown"].includes(key)) {
145
+ return;
146
+ }
147
+ event.preventDefault();
148
+ event.stopPropagation();
149
+ const focusables = this.#triggerElements.filter(isFocusable);
150
+ const active = getActiveElement();
151
+ if (!(active instanceof HTMLElement)) {
152
+ return;
153
+ }
154
+ const currentIndex = focusables.indexOf(active);
155
+ let newIndex = currentIndex;
156
+ switch (key) {
157
+ case "Enter":
158
+ case " ":
159
+ active.click();
160
+ return;
161
+ case "End":
162
+ newIndex = -1;
163
+ break;
164
+ case "Home":
165
+ newIndex = 0;
166
+ break;
167
+ case "ArrowUp":
168
+ newIndex = currentIndex - 1;
169
+ break;
170
+ case "ArrowDown":
171
+ newIndex = (currentIndex + 1) % focusables.length;
172
+ break;
173
+ }
174
+ focusables.at(newIndex)?.focus();
175
+ };
176
+ #onContentBeforeMatch = (event) => {
177
+ const content = event.currentTarget;
178
+ if (!(content instanceof HTMLElement)) {
179
+ return;
180
+ }
181
+ const binding = this.#bindings.get(content);
182
+ if (!binding) {
183
+ return;
184
+ }
185
+ binding.trigger.ariaExpanded !== "true" && this.#toggle(binding.trigger, true, true);
186
+ };
187
+ #toggle(trigger, isOpen, isMatch = false) {
188
+ if (trigger.ariaExpanded === String(isOpen)) {
189
+ return;
190
+ }
191
+ const name = trigger.getAttribute("data-accordion-name");
192
+ if (name && isOpen) {
193
+ const opened = this.#triggerElements.find(
194
+ (t) => t !== trigger && t.getAttribute("data-accordion-name") === name && t.ariaExpanded === "true"
195
+ );
196
+ if (opened) {
197
+ this.#toggle(opened, false, isMatch);
198
+ }
199
+ }
200
+ trigger.setAttribute(
201
+ "aria-label",
202
+ trigger.getAttribute(
203
+ `data-accordion-${isOpen ? "expanded" : "collapsed"}-label`
204
+ ) ?? trigger.ariaLabel ?? ""
205
+ );
206
+ const binding = this.#bindings.get(trigger);
207
+ if (!binding) {
208
+ return;
209
+ }
210
+ const { content } = binding;
211
+ const startSize = content.hidden ? 0 : content.offsetHeight;
212
+ if (content.hidden) {
213
+ content.hidden = false;
214
+ }
215
+ const endSize = isOpen ? content.scrollHeight : 0;
216
+ binding.animation?.cancel();
217
+ content.style.setProperty("overflow", "clip");
218
+ const { duration, easing } = this.#settings.animation;
219
+ const animation = content.animate(
220
+ { blockSize: [`${startSize}px`, `${endSize}px`] },
221
+ { duration: isMatch ? 0 : duration, easing }
222
+ );
223
+ binding.animation = animation;
224
+ trigger.setAttribute("aria-expanded", String(isOpen));
225
+ function cleanup() {
226
+ if (binding?.animation === animation) {
227
+ binding.animation = null;
228
+ }
229
+ }
230
+ this.#animationController = new AbortController();
231
+ const { signal } = this.#animationController;
232
+ animation.addEventListener("cancel", cleanup, { once: true, signal });
233
+ animation.addEventListener(
234
+ "finish",
235
+ () => {
236
+ this.#onAnimationFinish(content);
237
+ cleanup();
238
+ },
239
+ { once: true, signal }
240
+ );
241
+ }
242
+ #mergeOptions(target, source) {
243
+ return {
244
+ animation: { ...target.animation, ...source.animation ?? {} },
245
+ selector: { ...target.selector, ...source.selector ?? {} }
246
+ };
247
+ }
248
+ #onAnimationFinish(content) {
249
+ const trigger = this.#bindings.get(content)?.trigger;
250
+ if (!trigger) {
251
+ return;
252
+ }
253
+ if (trigger.ariaExpanded === "false") {
254
+ content.setAttribute("hidden", "until-found");
255
+ }
256
+ const { style } = content;
257
+ style.removeProperty("block-size");
258
+ style.removeProperty("overflow");
259
+ }
260
+ async #waitAnimationsFinish() {
261
+ const promises = [];
262
+ this.#contentElements.forEach((content) => {
263
+ const animation = this.#bindings.get(content)?.animation;
264
+ animation && promises.push(waitAnimationFinish(animation));
265
+ });
266
+ await Promise.allSettled(promises);
267
+ }
268
+ };
269
+ function addTokenToAttribute(element, attribute, token) {
270
+ const tokens = new Set(
271
+ element.getAttribute(attribute)?.trim().split(/\s+/) ?? []
272
+ );
273
+ tokens.add(token);
274
+ element.setAttribute(attribute, [...tokens].join(" "));
275
+ }
276
+ function createBinding(trigger, content) {
277
+ return { trigger, content, animation: null };
278
+ }
279
+ function getActiveElement() {
280
+ let current = document.activeElement;
281
+ while (current?.shadowRoot?.activeElement) {
282
+ current = current.shadowRoot.activeElement;
283
+ }
284
+ return current;
285
+ }
286
+ function isFocusable(element) {
287
+ return !element.hasAttribute("disabled") && element.tabIndex >= 0;
288
+ }
289
+ function waitAnimationFinish(animation) {
290
+ const { playState } = animation;
291
+ if (playState === "idle" || playState === "finished") {
292
+ return Promise.resolve();
293
+ }
294
+ return new Promise(
295
+ (resolve) => animation.addEventListener("finish", () => resolve(), { once: true })
296
+ );
297
+ }
298
+ /**
299
+ * Accordion
300
+ * WAI-ARIA compliant accordion pattern implementation in TypeScript.
301
+ *
302
+ * @version 1.2.4
303
+ * @author Yusuke Kamiyamane
304
+ * @license MIT
305
+ * @copyright Copyright (c) Yusuke Kamiyamane
306
+ * @see {@link https://github.com/y14e/accordion}
307
+ */
308
+
309
+ module.exports = Accordion;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Accordion
3
+ * WAI-ARIA compliant accordion pattern implementation in TypeScript.
4
+ *
5
+ * @version 1.2.4
6
+ * @author Yusuke Kamiyamane
7
+ * @license MIT
8
+ * @copyright Copyright (c) Yusuke Kamiyamane
9
+ * @see {@link https://github.com/y14e/accordion}
10
+ */
11
+ interface AccordionOptions {
12
+ readonly animation?: {
13
+ readonly duration?: number;
14
+ readonly easing?: string;
15
+ };
16
+ readonly selector?: {
17
+ readonly content?: string;
18
+ readonly trigger?: string;
19
+ };
20
+ }
21
+ declare class Accordion {
22
+ #private;
23
+ static defaults: AccordionOptions;
24
+ constructor(root: HTMLElement, options?: AccordionOptions);
25
+ open(trigger: HTMLElement): void;
26
+ close(trigger: HTMLElement): void;
27
+ destroy(force?: boolean): Promise<void>;
28
+ }
29
+
30
+ export { type AccordionOptions, Accordion as default };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Accordion
3
+ * WAI-ARIA compliant accordion pattern implementation in TypeScript.
4
+ *
5
+ * @version 1.2.4
6
+ * @author Yusuke Kamiyamane
7
+ * @license MIT
8
+ * @copyright Copyright (c) Yusuke Kamiyamane
9
+ * @see {@link https://github.com/y14e/accordion}
10
+ */
11
+ interface AccordionOptions {
12
+ readonly animation?: {
13
+ readonly duration?: number;
14
+ readonly easing?: string;
15
+ };
16
+ readonly selector?: {
17
+ readonly content?: string;
18
+ readonly trigger?: string;
19
+ };
20
+ }
21
+ declare class Accordion {
22
+ #private;
23
+ static defaults: AccordionOptions;
24
+ constructor(root: HTMLElement, options?: AccordionOptions);
25
+ open(trigger: HTMLElement): void;
26
+ close(trigger: HTMLElement): void;
27
+ destroy(force?: boolean): Promise<void>;
28
+ }
29
+
30
+ export { type AccordionOptions, Accordion as default };
package/dist/index.js ADDED
@@ -0,0 +1,307 @@
1
+ // src/index.ts
2
+ var Accordion = class _Accordion {
3
+ static defaults = {};
4
+ #rootElement;
5
+ #defaults = {
6
+ animation: { duration: 300, easing: "ease" },
7
+ selector: {
8
+ content: ":has(> [data-accordion-trigger]) + *",
9
+ trigger: "[data-accordion-trigger]"
10
+ }
11
+ };
12
+ #settings;
13
+ #triggerElements;
14
+ #contentElements;
15
+ #bindings = /* @__PURE__ */ new WeakMap();
16
+ #eventController = null;
17
+ #animationController = null;
18
+ #isDestroyed = false;
19
+ constructor(root, options = {}) {
20
+ if (!(root instanceof HTMLElement)) {
21
+ throw new TypeError("Invalid root element");
22
+ }
23
+ if (root.hasAttribute("data-accordion-initialized")) {
24
+ console.warn("Already initialized");
25
+ return;
26
+ }
27
+ this.#rootElement = root;
28
+ this.#defaults = this.#mergeOptions(this.#defaults, _Accordion.defaults);
29
+ this.#settings = this.#mergeOptions(this.#defaults, options);
30
+ matchMedia("(prefers-reduced-motion: reduce)").matches && Object.assign(this.#settings.animation, { duration: 0 });
31
+ const { trigger, content } = this.#settings.selector;
32
+ const NOT_NESTED = `:not(:scope ${content} *)`;
33
+ this.#triggerElements = [
34
+ ...this.#rootElement.querySelectorAll(
35
+ `${trigger}${NOT_NESTED}`
36
+ )
37
+ ];
38
+ if (!this.#triggerElements.length) {
39
+ console.warn("Missing trigger elements");
40
+ return;
41
+ }
42
+ this.#contentElements = [
43
+ ...this.#rootElement.querySelectorAll(
44
+ `${content}${NOT_NESTED}`
45
+ )
46
+ ];
47
+ if (!this.#contentElements.length) {
48
+ console.warn("Missing content elements");
49
+ return;
50
+ }
51
+ this.#triggerElements.forEach((trigger2, i) => {
52
+ const content2 = this.#contentElements[i];
53
+ if (!content2) {
54
+ return;
55
+ }
56
+ const binding = createBinding(trigger2, content2);
57
+ this.#bindings.set(trigger2, binding);
58
+ this.#bindings.set(content2, binding);
59
+ });
60
+ this.#initialize();
61
+ }
62
+ open(trigger) {
63
+ if (this.#isDestroyed) {
64
+ return;
65
+ }
66
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
67
+ console.warn("Invalid trigger element");
68
+ return;
69
+ }
70
+ this.#toggle(trigger, true);
71
+ }
72
+ close(trigger) {
73
+ if (this.#isDestroyed) {
74
+ return;
75
+ }
76
+ if (!(trigger instanceof HTMLElement) || !this.#bindings.has(trigger)) {
77
+ console.warn("Invalid trigger element");
78
+ return;
79
+ }
80
+ this.#toggle(trigger, false);
81
+ }
82
+ async destroy(force = false) {
83
+ if (this.#isDestroyed) {
84
+ return;
85
+ }
86
+ this.#isDestroyed = true;
87
+ this.#eventController?.abort();
88
+ this.#eventController = null;
89
+ !force && await this.#waitAnimationsFinish();
90
+ this.#contentElements.forEach((content) => {
91
+ force && this.#bindings.get(content)?.animation?.finish();
92
+ this.#onAnimationFinish(content);
93
+ });
94
+ this.#animationController?.abort();
95
+ this.#animationController = null;
96
+ this.#triggerElements.length = 0;
97
+ this.#contentElements.length = 0;
98
+ this.#rootElement.removeAttribute("data-accordion-initialized");
99
+ }
100
+ #initialize() {
101
+ this.#eventController = new AbortController();
102
+ const { signal } = this.#eventController;
103
+ this.#triggerElements.forEach((trigger, i) => {
104
+ const id = Math.random().toString(36).slice(-8);
105
+ const content = this.#contentElements[i];
106
+ if (!content) {
107
+ return;
108
+ }
109
+ content.id ||= `accordion-content-${id}`;
110
+ addTokenToAttribute(trigger, "aria-controls", content.id);
111
+ trigger.setAttribute(
112
+ "aria-expanded",
113
+ trigger.ariaExpanded === "true" ? "true" : "false"
114
+ );
115
+ trigger.id ||= `accordion-trigger-${id}`;
116
+ if (!isFocusable(trigger)) {
117
+ trigger.setAttribute("aria-disabled", "true");
118
+ trigger.setAttribute("tabindex", "-1");
119
+ trigger.style.setProperty("pointer-events", "none");
120
+ }
121
+ trigger.addEventListener("click", this.#onTriggerClick, { signal });
122
+ trigger.addEventListener("keydown", this.#onTriggerKeyDown, { signal });
123
+ addTokenToAttribute(content, "aria-labelledby", trigger.id);
124
+ content.setAttribute("role", "region");
125
+ content.addEventListener("beforematch", this.#onContentBeforeMatch, {
126
+ signal
127
+ });
128
+ });
129
+ this.#rootElement.setAttribute("data-accordion-initialized", "");
130
+ }
131
+ #onTriggerClick = (event) => {
132
+ event.preventDefault();
133
+ event.stopPropagation();
134
+ const trigger = event.currentTarget;
135
+ if (!(trigger instanceof HTMLElement)) {
136
+ return;
137
+ }
138
+ this.#toggle(trigger, trigger.ariaExpanded !== "true");
139
+ };
140
+ #onTriggerKeyDown = (event) => {
141
+ const { key } = event;
142
+ if (!["Enter", " ", "End", "Home", "ArrowUp", "ArrowDown"].includes(key)) {
143
+ return;
144
+ }
145
+ event.preventDefault();
146
+ event.stopPropagation();
147
+ const focusables = this.#triggerElements.filter(isFocusable);
148
+ const active = getActiveElement();
149
+ if (!(active instanceof HTMLElement)) {
150
+ return;
151
+ }
152
+ const currentIndex = focusables.indexOf(active);
153
+ let newIndex = currentIndex;
154
+ switch (key) {
155
+ case "Enter":
156
+ case " ":
157
+ active.click();
158
+ return;
159
+ case "End":
160
+ newIndex = -1;
161
+ break;
162
+ case "Home":
163
+ newIndex = 0;
164
+ break;
165
+ case "ArrowUp":
166
+ newIndex = currentIndex - 1;
167
+ break;
168
+ case "ArrowDown":
169
+ newIndex = (currentIndex + 1) % focusables.length;
170
+ break;
171
+ }
172
+ focusables.at(newIndex)?.focus();
173
+ };
174
+ #onContentBeforeMatch = (event) => {
175
+ const content = event.currentTarget;
176
+ if (!(content instanceof HTMLElement)) {
177
+ return;
178
+ }
179
+ const binding = this.#bindings.get(content);
180
+ if (!binding) {
181
+ return;
182
+ }
183
+ binding.trigger.ariaExpanded !== "true" && this.#toggle(binding.trigger, true, true);
184
+ };
185
+ #toggle(trigger, isOpen, isMatch = false) {
186
+ if (trigger.ariaExpanded === String(isOpen)) {
187
+ return;
188
+ }
189
+ const name = trigger.getAttribute("data-accordion-name");
190
+ if (name && isOpen) {
191
+ const opened = this.#triggerElements.find(
192
+ (t) => t !== trigger && t.getAttribute("data-accordion-name") === name && t.ariaExpanded === "true"
193
+ );
194
+ if (opened) {
195
+ this.#toggle(opened, false, isMatch);
196
+ }
197
+ }
198
+ trigger.setAttribute(
199
+ "aria-label",
200
+ trigger.getAttribute(
201
+ `data-accordion-${isOpen ? "expanded" : "collapsed"}-label`
202
+ ) ?? trigger.ariaLabel ?? ""
203
+ );
204
+ const binding = this.#bindings.get(trigger);
205
+ if (!binding) {
206
+ return;
207
+ }
208
+ const { content } = binding;
209
+ const startSize = content.hidden ? 0 : content.offsetHeight;
210
+ if (content.hidden) {
211
+ content.hidden = false;
212
+ }
213
+ const endSize = isOpen ? content.scrollHeight : 0;
214
+ binding.animation?.cancel();
215
+ content.style.setProperty("overflow", "clip");
216
+ const { duration, easing } = this.#settings.animation;
217
+ const animation = content.animate(
218
+ { blockSize: [`${startSize}px`, `${endSize}px`] },
219
+ { duration: isMatch ? 0 : duration, easing }
220
+ );
221
+ binding.animation = animation;
222
+ trigger.setAttribute("aria-expanded", String(isOpen));
223
+ function cleanup() {
224
+ if (binding?.animation === animation) {
225
+ binding.animation = null;
226
+ }
227
+ }
228
+ this.#animationController = new AbortController();
229
+ const { signal } = this.#animationController;
230
+ animation.addEventListener("cancel", cleanup, { once: true, signal });
231
+ animation.addEventListener(
232
+ "finish",
233
+ () => {
234
+ this.#onAnimationFinish(content);
235
+ cleanup();
236
+ },
237
+ { once: true, signal }
238
+ );
239
+ }
240
+ #mergeOptions(target, source) {
241
+ return {
242
+ animation: { ...target.animation, ...source.animation ?? {} },
243
+ selector: { ...target.selector, ...source.selector ?? {} }
244
+ };
245
+ }
246
+ #onAnimationFinish(content) {
247
+ const trigger = this.#bindings.get(content)?.trigger;
248
+ if (!trigger) {
249
+ return;
250
+ }
251
+ if (trigger.ariaExpanded === "false") {
252
+ content.setAttribute("hidden", "until-found");
253
+ }
254
+ const { style } = content;
255
+ style.removeProperty("block-size");
256
+ style.removeProperty("overflow");
257
+ }
258
+ async #waitAnimationsFinish() {
259
+ const promises = [];
260
+ this.#contentElements.forEach((content) => {
261
+ const animation = this.#bindings.get(content)?.animation;
262
+ animation && promises.push(waitAnimationFinish(animation));
263
+ });
264
+ await Promise.allSettled(promises);
265
+ }
266
+ };
267
+ function addTokenToAttribute(element, attribute, token) {
268
+ const tokens = new Set(
269
+ element.getAttribute(attribute)?.trim().split(/\s+/) ?? []
270
+ );
271
+ tokens.add(token);
272
+ element.setAttribute(attribute, [...tokens].join(" "));
273
+ }
274
+ function createBinding(trigger, content) {
275
+ return { trigger, content, animation: null };
276
+ }
277
+ function getActiveElement() {
278
+ let current = document.activeElement;
279
+ while (current?.shadowRoot?.activeElement) {
280
+ current = current.shadowRoot.activeElement;
281
+ }
282
+ return current;
283
+ }
284
+ function isFocusable(element) {
285
+ return !element.hasAttribute("disabled") && element.tabIndex >= 0;
286
+ }
287
+ function waitAnimationFinish(animation) {
288
+ const { playState } = animation;
289
+ if (playState === "idle" || playState === "finished") {
290
+ return Promise.resolve();
291
+ }
292
+ return new Promise(
293
+ (resolve) => animation.addEventListener("finish", () => resolve(), { once: true })
294
+ );
295
+ }
296
+ /**
297
+ * Accordion
298
+ * WAI-ARIA compliant accordion pattern implementation in TypeScript.
299
+ *
300
+ * @version 1.2.4
301
+ * @author Yusuke Kamiyamane
302
+ * @license MIT
303
+ * @copyright Copyright (c) Yusuke Kamiyamane
304
+ * @see {@link https://github.com/y14e/accordion}
305
+ */
306
+
307
+ export { Accordion as default };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@y14e/accordion",
3
+ "version": "1.2.4",
4
+ "description": "WAI-ARIA compliant accordion pattern implementation in TypeScript",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "LICENSE",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "prepublishOnly": "npm run build",
24
+ "lint": "tsc --noEmit"
25
+ },
26
+ "keywords": [
27
+ "a11y",
28
+ "accessibility",
29
+ "accordion",
30
+ "collapsible",
31
+ "component",
32
+ "typescript",
33
+ "utility"
34
+ ],
35
+ "author": "Yusuke Kamiyamane",
36
+ "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/y14e/accordion.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/y14e/accordion/issues"
43
+ },
44
+ "homepage": "https://github.com/y14e/accordion#readme",
45
+ "devDependencies": {
46
+ "bun-types": "latest",
47
+ "tsup": "^8.0.0",
48
+ "typescript": "^5.6.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=18"
52
+ }
53
+ }