@y14e/roving-tabindex 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 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,52 @@
1
+ # Roving Tabindex
2
+
3
+ Lightweight roving tabindex utility with fully focus management. Designed for accessible menus, tabs, toolbars, and composite widgets.
4
+
5
+ > [!NOTE]
6
+ > Focus traversal works across shadow DOM boundaries using composed-tree-aware focus detection powered by [Power Focusable](https://github.com/y14e/power-focusable).
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm i @y14e/roving-tabindex
12
+ ```
13
+
14
+ ```ts
15
+ // npm
16
+ import { createRovingTabIndex } from '@y14e/roving-tabindex';
17
+
18
+ // CDNs
19
+ import { createRovingTabIndex } from 'https://esm.sh/@y14e/roving-tabindex'
20
+ // or
21
+ import { createRovingTabIndex } from 'https://cdn.jsdelivr.net/npm/@y14e/roving-tabindex/+esm';
22
+ // or
23
+ import { createRovingTabIndex } from 'https://unpkg.com/@y14e/roving-tabindex/dist/index.js';
24
+ ```
25
+
26
+ ## 📦 APIs
27
+
28
+ ### `createRovingTabIndex`
29
+
30
+ Creates a roving tabindex controller and preserves a single tabbable element within the container while enabling keyboard navigation between focusable items.
31
+
32
+ ```ts
33
+ const cleanup = createRovingTabIndex(container, options);
34
+ // => () => void
35
+ //
36
+ // container: Element
37
+ // options (optional): RovingTabIndexOptions
38
+ ```
39
+
40
+ ## 🪄 Options
41
+
42
+ ```ts
43
+ interface RovingTabIndexOptions {
44
+ direction?: 'horizontal' | 'vertical'; // default: both (undefined)
45
+ selector?: string;
46
+ wrap?: boolean; // default: false
47
+ }
48
+ ```
49
+
50
+ ### `wrap`
51
+
52
+ If `true`, wraps around to the first or last element when reaching the end.
package/dist/index.cjs ADDED
@@ -0,0 +1,416 @@
1
+ 'use strict';
2
+
3
+ // node_modules/power-focusable/dist/index.js
4
+ 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"])`;
5
+ function getFocusables(container = document.body, options = {}) {
6
+ if (!(container instanceof Element)) {
7
+ console.warn("Invalid container element. Fallback: <body> element.");
8
+ container = document.body;
9
+ }
10
+ const { composed = false } = options;
11
+ let { filter, include } = options;
12
+ if (filter && typeof filter !== "function") {
13
+ console.warn("Invalid filter function");
14
+ filter = void 0;
15
+ }
16
+ if (include && typeof include !== "function") {
17
+ console.warn("Invalid include function");
18
+ include = void 0;
19
+ }
20
+ const elements = [];
21
+ if (composed || include) {
22
+ let traverse2 = function(node) {
23
+ if (node instanceof Element) {
24
+ if (isFocusable(node) || include?.(node)) {
25
+ elements[elements.length] = node;
26
+ }
27
+ }
28
+ const children = getComposedChildren(node);
29
+ for (let i = 0, l = children.length; i < l; i++) {
30
+ const child = children[i];
31
+ if (!child) {
32
+ continue;
33
+ }
34
+ traverse2(child);
35
+ }
36
+ };
37
+ traverse2(container);
38
+ } else {
39
+ const candidates = container.querySelectorAll(FOCUSABLE_SELECTOR);
40
+ for (let i = 0, l = candidates.length; i < l; i++) {
41
+ const candidate = candidates[i];
42
+ if (!(candidate instanceof Element)) {
43
+ continue;
44
+ }
45
+ if (isFocusable(candidate)) {
46
+ elements[elements.length] = candidate;
47
+ }
48
+ }
49
+ }
50
+ const unfiltered = normalizeRadioGroup(sortByTabIndex(elements));
51
+ return filter ? unfiltered.filter(filter) : unfiltered;
52
+ }
53
+ function isFocusable(element) {
54
+ if (!(element instanceof Element)) {
55
+ console.warn("Invalid element");
56
+ return false;
57
+ }
58
+ if (element.hasAttribute("hidden") || isInert(element)) {
59
+ return false;
60
+ }
61
+ if (getTabIndex(element) < 0) {
62
+ return false;
63
+ }
64
+ if (!element.matches(FOCUSABLE_SELECTOR)) {
65
+ return false;
66
+ }
67
+ if (isDisabledDeep(element)) {
68
+ return false;
69
+ }
70
+ if (!element.checkVisibility({
71
+ contentVisibilityAuto: true,
72
+ opacityProperty: true,
73
+ visibilityProperty: true
74
+ })) {
75
+ return false;
76
+ }
77
+ return true;
78
+ }
79
+ function isDisabledDeep(element) {
80
+ let current = element;
81
+ while (current) {
82
+ if (current instanceof ShadowRoot) {
83
+ if (current.mode !== "open") {
84
+ return false;
85
+ }
86
+ current = current.host;
87
+ continue;
88
+ }
89
+ if (!(current instanceof Element)) {
90
+ current = current.parentNode;
91
+ continue;
92
+ }
93
+ if (current === element && isFormControl(current) && isDisabled(current)) {
94
+ return true;
95
+ }
96
+ if (isInert(current)) {
97
+ return true;
98
+ }
99
+ if (isFormControl(element) && current.tagName === "FIELDSET" && isDisabled(current)) {
100
+ if (!current.querySelector(":scope > legend:first-of-type")?.contains(element)) {
101
+ return true;
102
+ }
103
+ }
104
+ current = current.parentNode;
105
+ }
106
+ return false;
107
+ }
108
+ function normalizeRadioGroup(elements) {
109
+ let map = null;
110
+ for (let i = 0, l = elements.length; i < l; i++) {
111
+ const element = elements[i];
112
+ if (!(element instanceof HTMLInputElement)) {
113
+ continue;
114
+ }
115
+ if (!isUngroupedRadio(element)) {
116
+ continue;
117
+ }
118
+ if (!map) {
119
+ map = /* @__PURE__ */ new Map();
120
+ }
121
+ const key = `${element.form?.id ?? "no-form"}::${element.name}`;
122
+ const group = map.get(key) ?? map.set(key, []).get(key);
123
+ if (group) {
124
+ group[group.length] = element;
125
+ }
126
+ }
127
+ if (!map) {
128
+ return elements;
129
+ }
130
+ const placeholder = /* @__PURE__ */ new Set();
131
+ for (const group of map.values()) {
132
+ placeholder.add(group.find((radio) => radio.checked) ?? group[0]);
133
+ }
134
+ return elements.filter((element) => {
135
+ if (isUngroupedRadio(element)) {
136
+ return placeholder.has(element);
137
+ }
138
+ return true;
139
+ });
140
+ }
141
+ function sortByTabIndex(elements) {
142
+ const ordered = [];
143
+ const natural = [];
144
+ for (let i = 0, l = elements.length; i < l; i++) {
145
+ const element = elements[i];
146
+ if (!element) {
147
+ continue;
148
+ }
149
+ const target = getTabIndex(element) > 0 ? ordered : natural;
150
+ target[target.length] = element;
151
+ }
152
+ ordered.sort((a, b) => getTabIndex(a) - getTabIndex(b));
153
+ let count = 0;
154
+ const sorted = new Array(ordered.length + natural.length);
155
+ for (let i = 0, l = ordered.length; i < l; i++) {
156
+ sorted[count++] = ordered[i];
157
+ }
158
+ for (let i = 0, l = natural.length; i < l; i++) {
159
+ sorted[count++] = natural[i];
160
+ }
161
+ return sorted;
162
+ }
163
+ function getComposedChildren(node) {
164
+ if (node instanceof ShadowRoot) {
165
+ return getChildren(node);
166
+ }
167
+ if (!(node instanceof Element)) {
168
+ return [];
169
+ }
170
+ if (node instanceof HTMLSlotElement) {
171
+ const assigned = node.assignedElements({ flatten: true });
172
+ if (assigned.length) {
173
+ return assigned;
174
+ }
175
+ }
176
+ if (node instanceof HTMLElement && node.shadowRoot?.mode === "open") {
177
+ return getChildren(node.shadowRoot);
178
+ }
179
+ return getChildren(node);
180
+ }
181
+ function getChildren(node) {
182
+ const elements = [];
183
+ for (let child = node.firstElementChild; child; child = child.nextElementSibling) {
184
+ elements[elements.length] = child;
185
+ }
186
+ return elements;
187
+ }
188
+ function getTabIndex(element) {
189
+ return "tabIndex" in element ? Number(element.tabIndex) : 0;
190
+ }
191
+ function isDisabled(element) {
192
+ return "disabled" in element && !!element.disabled;
193
+ }
194
+ function isFormControl(element) {
195
+ const name = element.tagName;
196
+ return name === "BUTTON" || name === "INPUT" || name === "SELECT" || name === "TEXTAREA";
197
+ }
198
+ function isInert(element) {
199
+ return "inert" in element && !!element.inert;
200
+ }
201
+ function isUngroupedRadio(element) {
202
+ return element instanceof HTMLInputElement && element.type === "radio" && !!element.name;
203
+ }
204
+
205
+ // src/index.ts
206
+ function createRovingTabIndex(container, options = {}) {
207
+ if (!(container instanceof Element)) {
208
+ throw new Error("Invalid container element");
209
+ }
210
+ const roving = new RovingTabIndex(container, options);
211
+ return () => roving.destroy();
212
+ }
213
+ var RovingTabIndex = class {
214
+ #container;
215
+ #options;
216
+ #focusables = /* @__PURE__ */ new Set();
217
+ #tabIndexes = /* @__PURE__ */ new Map();
218
+ #selectorFilter;
219
+ #controller = null;
220
+ #isDestroyed = false;
221
+ constructor(container, options = {}) {
222
+ this.#container = container;
223
+ this.#options = options;
224
+ const { direction, selector, wrap = false } = this.#options;
225
+ if (direction && !["horizontal", "vertical"].includes(direction)) {
226
+ console.warn("Invalid direction. Fallback: both (undefined).");
227
+ Object.assign(this.#options, { direction: void 0 });
228
+ }
229
+ if (typeof selector !== "string") {
230
+ console.warn("Invalid selector. Fallback: all focusable elements.");
231
+ Object.assign(this.#options, { selector: void 0 });
232
+ }
233
+ if (typeof wrap !== "boolean") {
234
+ console.warn("Invalid wrap. Fallback: false.");
235
+ Object.assign(this.#options, { wrap: false });
236
+ }
237
+ this.#selectorFilter = this.#createSelectorFilter();
238
+ this.#initialize();
239
+ }
240
+ destroy() {
241
+ if (this.#isDestroyed) {
242
+ return;
243
+ }
244
+ this.#isDestroyed = true;
245
+ this.#controller?.abort();
246
+ this.#controller = null;
247
+ this.#focusables.forEach((focusable) => {
248
+ const index = this.#tabIndexes.get(focusable);
249
+ if (index == null) {
250
+ focusable.removeAttribute("tabindex");
251
+ } else {
252
+ focusable.setAttribute("tabindex", index);
253
+ }
254
+ });
255
+ this.#focusables.clear();
256
+ this.#tabIndexes.clear();
257
+ this.#container.removeAttribute("data-roving-tabindex-initialized");
258
+ }
259
+ #initialize() {
260
+ this.#update(document.activeElement);
261
+ this.#controller = new AbortController();
262
+ document.addEventListener("keydown", this.#onKeyDown, {
263
+ capture: true,
264
+ signal: this.#controller.signal
265
+ });
266
+ this.#container.setAttribute("data-roving-tabindex-initialized", "");
267
+ }
268
+ #onKeyDown = (event) => {
269
+ if (!event.composedPath().includes(this.#container)) {
270
+ return;
271
+ }
272
+ const { key, altKey, ctrlKey, metaKey } = event;
273
+ if (altKey || ctrlKey || metaKey) {
274
+ return;
275
+ }
276
+ const { direction } = this.#options;
277
+ const isBoth = !direction;
278
+ const isHorizontal = direction === "horizontal";
279
+ if (![
280
+ "End",
281
+ "Home",
282
+ ...isBoth ? ["ArrowLeft", "ArrowUp"] : [`Arrow${isHorizontal ? "Left" : "Up"}`],
283
+ ...isBoth ? ["ArrowRight", "ArrowDown"] : [`Arrow${isHorizontal ? "Right" : "Down"}`]
284
+ ].includes(key)) {
285
+ return;
286
+ }
287
+ const active = getActiveElement();
288
+ if (!(active instanceof HTMLElement)) {
289
+ return;
290
+ }
291
+ const focusables = this.#getFocusables();
292
+ if (!focusables.includes(active)) {
293
+ return;
294
+ }
295
+ event.preventDefault();
296
+ event.stopPropagation();
297
+ const currentIndex = focusables.indexOf(active);
298
+ let rawIndex;
299
+ let newIndex = currentIndex;
300
+ const { wrap = false } = this.#options;
301
+ switch (key) {
302
+ case "End":
303
+ newIndex = -1;
304
+ break;
305
+ case "Home":
306
+ newIndex = 0;
307
+ break;
308
+ case "ArrowLeft":
309
+ case "ArrowUp":
310
+ rawIndex = currentIndex - 1;
311
+ newIndex = wrap ? rawIndex : Math.max(rawIndex, 0);
312
+ break;
313
+ case "ArrowRight":
314
+ case "ArrowDown":
315
+ rawIndex = currentIndex + 1;
316
+ newIndex = wrap ? rawIndex % focusables.length : Math.min(rawIndex, focusables.length - 1);
317
+ break;
318
+ }
319
+ const focusable = focusables.at(newIndex);
320
+ if (!focusable) {
321
+ return;
322
+ }
323
+ this.#update(focusable);
324
+ focusElement(focusable);
325
+ };
326
+ #update(active) {
327
+ const current = /* @__PURE__ */ new Set([
328
+ ...this.#getFocusables(),
329
+ ...getFocusables(this.#container, {
330
+ composed: true,
331
+ filter: this.#selectorFilter
332
+ })
333
+ ]);
334
+ this.#focusables.forEach((focusable) => {
335
+ if (current.has(focusable)) {
336
+ return;
337
+ }
338
+ if (focusable.isConnected) {
339
+ const index = this.#tabIndexes.get(focusable);
340
+ if (index == null) {
341
+ focusable.removeAttribute("tabindex");
342
+ } else {
343
+ focusable.setAttribute("tabindex", index);
344
+ }
345
+ }
346
+ this.#focusables.delete(focusable);
347
+ this.#tabIndexes.delete(focusable);
348
+ });
349
+ current.forEach((c) => {
350
+ if (this.#focusables.has(c)) {
351
+ return;
352
+ }
353
+ this.#focusables.add(c);
354
+ this.#tabIndexes.set(c, c.getAttribute("tabindex"));
355
+ c.setAttribute("tabindex", "-1");
356
+ });
357
+ if (active && this.#focusables.has(active)) {
358
+ this.#focusables.forEach((focusable) => {
359
+ focusable.setAttribute("tabindex", focusable === active ? "0" : "-1");
360
+ });
361
+ return;
362
+ }
363
+ [...this.#focusables].forEach((focusable, i) => {
364
+ focusable.setAttribute("tabindex", i ? "-1" : "0");
365
+ });
366
+ }
367
+ #createSelectorFilter() {
368
+ const { selector } = this.#options;
369
+ return (element) => !selector || element.matches(selector);
370
+ }
371
+ #getFocusables() {
372
+ return getFocusables(this.#container, {
373
+ composed: true,
374
+ filter: this.#selectorFilter,
375
+ include: (element) => this.#focusables.has(element)
376
+ });
377
+ }
378
+ };
379
+ function focusElement(element) {
380
+ "focus" in element && typeof element.focus === "function" && element.focus();
381
+ }
382
+ function getActiveElement() {
383
+ let current = document.activeElement;
384
+ while (current?.shadowRoot?.activeElement) {
385
+ current = current.shadowRoot.activeElement;
386
+ }
387
+ return current;
388
+ }
389
+ /**
390
+ * Roving Tabindex
391
+ * Lightweight roving tabindex utility with fully focus management.
392
+ * Designed for accessible menus, tabs, toolbars, and composite widgets.
393
+ *
394
+ * @version 1.0.0
395
+ * @author Yusuke Kamiyamane
396
+ * @license MIT
397
+ * @copyright Copyright (c) Yusuke Kamiyamane
398
+ * @see {@link https://github.com/y14e/roving-tabindex}
399
+ */
400
+ /*! Bundled license information:
401
+
402
+ power-focusable/dist/index.js:
403
+ (**
404
+ * Power Focusable
405
+ * High-precision focus management utility with full composed tree support.
406
+ * Handles complex focus rules including tabindex ordering, radio groups, inert.
407
+ *
408
+ * @version 4.1.5
409
+ * @author Yusuke Kamiyamane
410
+ * @license MIT
411
+ * @copyright Copyright (c) Yusuke Kamiyamane
412
+ * @see {@link https://github.com/y14e/power-focusable}
413
+ *)
414
+ */
415
+
416
+ exports.createRovingTabIndex = createRovingTabIndex;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Roving Tabindex
3
+ * Lightweight roving tabindex utility with fully focus management.
4
+ * Designed for accessible menus, tabs, toolbars, and composite widgets.
5
+ *
6
+ * @version 1.0.0
7
+ * @author Yusuke Kamiyamane
8
+ * @license MIT
9
+ * @copyright Copyright (c) Yusuke Kamiyamane
10
+ * @see {@link https://github.com/y14e/roving-tabindex}
11
+ */
12
+ interface RovingTabIndexOptions {
13
+ readonly direction?: 'horizontal' | 'vertical';
14
+ readonly selector?: string;
15
+ readonly wrap?: boolean;
16
+ }
17
+ declare function createRovingTabIndex(container: Element, options?: RovingTabIndexOptions): () => void;
18
+
19
+ export { createRovingTabIndex };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Roving Tabindex
3
+ * Lightweight roving tabindex utility with fully focus management.
4
+ * Designed for accessible menus, tabs, toolbars, and composite widgets.
5
+ *
6
+ * @version 1.0.0
7
+ * @author Yusuke Kamiyamane
8
+ * @license MIT
9
+ * @copyright Copyright (c) Yusuke Kamiyamane
10
+ * @see {@link https://github.com/y14e/roving-tabindex}
11
+ */
12
+ interface RovingTabIndexOptions {
13
+ readonly direction?: 'horizontal' | 'vertical';
14
+ readonly selector?: string;
15
+ readonly wrap?: boolean;
16
+ }
17
+ declare function createRovingTabIndex(container: Element, options?: RovingTabIndexOptions): () => void;
18
+
19
+ export { createRovingTabIndex };
package/dist/index.js ADDED
@@ -0,0 +1,414 @@
1
+ // node_modules/power-focusable/dist/index.js
2
+ 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"])`;
3
+ function getFocusables(container = document.body, options = {}) {
4
+ if (!(container instanceof Element)) {
5
+ console.warn("Invalid container element. Fallback: <body> element.");
6
+ container = document.body;
7
+ }
8
+ const { composed = false } = options;
9
+ let { filter, include } = options;
10
+ if (filter && typeof filter !== "function") {
11
+ console.warn("Invalid filter function");
12
+ filter = void 0;
13
+ }
14
+ if (include && typeof include !== "function") {
15
+ console.warn("Invalid include function");
16
+ include = void 0;
17
+ }
18
+ const elements = [];
19
+ if (composed || include) {
20
+ let traverse2 = function(node) {
21
+ if (node instanceof Element) {
22
+ if (isFocusable(node) || include?.(node)) {
23
+ elements[elements.length] = node;
24
+ }
25
+ }
26
+ const children = getComposedChildren(node);
27
+ for (let i = 0, l = children.length; i < l; i++) {
28
+ const child = children[i];
29
+ if (!child) {
30
+ continue;
31
+ }
32
+ traverse2(child);
33
+ }
34
+ };
35
+ traverse2(container);
36
+ } else {
37
+ const candidates = container.querySelectorAll(FOCUSABLE_SELECTOR);
38
+ for (let i = 0, l = candidates.length; i < l; i++) {
39
+ const candidate = candidates[i];
40
+ if (!(candidate instanceof Element)) {
41
+ continue;
42
+ }
43
+ if (isFocusable(candidate)) {
44
+ elements[elements.length] = candidate;
45
+ }
46
+ }
47
+ }
48
+ const unfiltered = normalizeRadioGroup(sortByTabIndex(elements));
49
+ return filter ? unfiltered.filter(filter) : unfiltered;
50
+ }
51
+ function isFocusable(element) {
52
+ if (!(element instanceof Element)) {
53
+ console.warn("Invalid element");
54
+ return false;
55
+ }
56
+ if (element.hasAttribute("hidden") || isInert(element)) {
57
+ return false;
58
+ }
59
+ if (getTabIndex(element) < 0) {
60
+ return false;
61
+ }
62
+ if (!element.matches(FOCUSABLE_SELECTOR)) {
63
+ return false;
64
+ }
65
+ if (isDisabledDeep(element)) {
66
+ return false;
67
+ }
68
+ if (!element.checkVisibility({
69
+ contentVisibilityAuto: true,
70
+ opacityProperty: true,
71
+ visibilityProperty: true
72
+ })) {
73
+ return false;
74
+ }
75
+ return true;
76
+ }
77
+ function isDisabledDeep(element) {
78
+ let current = element;
79
+ while (current) {
80
+ if (current instanceof ShadowRoot) {
81
+ if (current.mode !== "open") {
82
+ return false;
83
+ }
84
+ current = current.host;
85
+ continue;
86
+ }
87
+ if (!(current instanceof Element)) {
88
+ current = current.parentNode;
89
+ continue;
90
+ }
91
+ if (current === element && isFormControl(current) && isDisabled(current)) {
92
+ return true;
93
+ }
94
+ if (isInert(current)) {
95
+ return true;
96
+ }
97
+ if (isFormControl(element) && current.tagName === "FIELDSET" && isDisabled(current)) {
98
+ if (!current.querySelector(":scope > legend:first-of-type")?.contains(element)) {
99
+ return true;
100
+ }
101
+ }
102
+ current = current.parentNode;
103
+ }
104
+ return false;
105
+ }
106
+ function normalizeRadioGroup(elements) {
107
+ let map = null;
108
+ for (let i = 0, l = elements.length; i < l; i++) {
109
+ const element = elements[i];
110
+ if (!(element instanceof HTMLInputElement)) {
111
+ continue;
112
+ }
113
+ if (!isUngroupedRadio(element)) {
114
+ continue;
115
+ }
116
+ if (!map) {
117
+ map = /* @__PURE__ */ new Map();
118
+ }
119
+ const key = `${element.form?.id ?? "no-form"}::${element.name}`;
120
+ const group = map.get(key) ?? map.set(key, []).get(key);
121
+ if (group) {
122
+ group[group.length] = element;
123
+ }
124
+ }
125
+ if (!map) {
126
+ return elements;
127
+ }
128
+ const placeholder = /* @__PURE__ */ new Set();
129
+ for (const group of map.values()) {
130
+ placeholder.add(group.find((radio) => radio.checked) ?? group[0]);
131
+ }
132
+ return elements.filter((element) => {
133
+ if (isUngroupedRadio(element)) {
134
+ return placeholder.has(element);
135
+ }
136
+ return true;
137
+ });
138
+ }
139
+ function sortByTabIndex(elements) {
140
+ const ordered = [];
141
+ const natural = [];
142
+ for (let i = 0, l = elements.length; i < l; i++) {
143
+ const element = elements[i];
144
+ if (!element) {
145
+ continue;
146
+ }
147
+ const target = getTabIndex(element) > 0 ? ordered : natural;
148
+ target[target.length] = element;
149
+ }
150
+ ordered.sort((a, b) => getTabIndex(a) - getTabIndex(b));
151
+ let count = 0;
152
+ const sorted = new Array(ordered.length + natural.length);
153
+ for (let i = 0, l = ordered.length; i < l; i++) {
154
+ sorted[count++] = ordered[i];
155
+ }
156
+ for (let i = 0, l = natural.length; i < l; i++) {
157
+ sorted[count++] = natural[i];
158
+ }
159
+ return sorted;
160
+ }
161
+ function getComposedChildren(node) {
162
+ if (node instanceof ShadowRoot) {
163
+ return getChildren(node);
164
+ }
165
+ if (!(node instanceof Element)) {
166
+ return [];
167
+ }
168
+ if (node instanceof HTMLSlotElement) {
169
+ const assigned = node.assignedElements({ flatten: true });
170
+ if (assigned.length) {
171
+ return assigned;
172
+ }
173
+ }
174
+ if (node instanceof HTMLElement && node.shadowRoot?.mode === "open") {
175
+ return getChildren(node.shadowRoot);
176
+ }
177
+ return getChildren(node);
178
+ }
179
+ function getChildren(node) {
180
+ const elements = [];
181
+ for (let child = node.firstElementChild; child; child = child.nextElementSibling) {
182
+ elements[elements.length] = child;
183
+ }
184
+ return elements;
185
+ }
186
+ function getTabIndex(element) {
187
+ return "tabIndex" in element ? Number(element.tabIndex) : 0;
188
+ }
189
+ function isDisabled(element) {
190
+ return "disabled" in element && !!element.disabled;
191
+ }
192
+ function isFormControl(element) {
193
+ const name = element.tagName;
194
+ return name === "BUTTON" || name === "INPUT" || name === "SELECT" || name === "TEXTAREA";
195
+ }
196
+ function isInert(element) {
197
+ return "inert" in element && !!element.inert;
198
+ }
199
+ function isUngroupedRadio(element) {
200
+ return element instanceof HTMLInputElement && element.type === "radio" && !!element.name;
201
+ }
202
+
203
+ // src/index.ts
204
+ function createRovingTabIndex(container, options = {}) {
205
+ if (!(container instanceof Element)) {
206
+ throw new Error("Invalid container element");
207
+ }
208
+ const roving = new RovingTabIndex(container, options);
209
+ return () => roving.destroy();
210
+ }
211
+ var RovingTabIndex = class {
212
+ #container;
213
+ #options;
214
+ #focusables = /* @__PURE__ */ new Set();
215
+ #tabIndexes = /* @__PURE__ */ new Map();
216
+ #selectorFilter;
217
+ #controller = null;
218
+ #isDestroyed = false;
219
+ constructor(container, options = {}) {
220
+ this.#container = container;
221
+ this.#options = options;
222
+ const { direction, selector, wrap = false } = this.#options;
223
+ if (direction && !["horizontal", "vertical"].includes(direction)) {
224
+ console.warn("Invalid direction. Fallback: both (undefined).");
225
+ Object.assign(this.#options, { direction: void 0 });
226
+ }
227
+ if (typeof selector !== "string") {
228
+ console.warn("Invalid selector. Fallback: all focusable elements.");
229
+ Object.assign(this.#options, { selector: void 0 });
230
+ }
231
+ if (typeof wrap !== "boolean") {
232
+ console.warn("Invalid wrap. Fallback: false.");
233
+ Object.assign(this.#options, { wrap: false });
234
+ }
235
+ this.#selectorFilter = this.#createSelectorFilter();
236
+ this.#initialize();
237
+ }
238
+ destroy() {
239
+ if (this.#isDestroyed) {
240
+ return;
241
+ }
242
+ this.#isDestroyed = true;
243
+ this.#controller?.abort();
244
+ this.#controller = null;
245
+ this.#focusables.forEach((focusable) => {
246
+ const index = this.#tabIndexes.get(focusable);
247
+ if (index == null) {
248
+ focusable.removeAttribute("tabindex");
249
+ } else {
250
+ focusable.setAttribute("tabindex", index);
251
+ }
252
+ });
253
+ this.#focusables.clear();
254
+ this.#tabIndexes.clear();
255
+ this.#container.removeAttribute("data-roving-tabindex-initialized");
256
+ }
257
+ #initialize() {
258
+ this.#update(document.activeElement);
259
+ this.#controller = new AbortController();
260
+ document.addEventListener("keydown", this.#onKeyDown, {
261
+ capture: true,
262
+ signal: this.#controller.signal
263
+ });
264
+ this.#container.setAttribute("data-roving-tabindex-initialized", "");
265
+ }
266
+ #onKeyDown = (event) => {
267
+ if (!event.composedPath().includes(this.#container)) {
268
+ return;
269
+ }
270
+ const { key, altKey, ctrlKey, metaKey } = event;
271
+ if (altKey || ctrlKey || metaKey) {
272
+ return;
273
+ }
274
+ const { direction } = this.#options;
275
+ const isBoth = !direction;
276
+ const isHorizontal = direction === "horizontal";
277
+ if (![
278
+ "End",
279
+ "Home",
280
+ ...isBoth ? ["ArrowLeft", "ArrowUp"] : [`Arrow${isHorizontal ? "Left" : "Up"}`],
281
+ ...isBoth ? ["ArrowRight", "ArrowDown"] : [`Arrow${isHorizontal ? "Right" : "Down"}`]
282
+ ].includes(key)) {
283
+ return;
284
+ }
285
+ const active = getActiveElement();
286
+ if (!(active instanceof HTMLElement)) {
287
+ return;
288
+ }
289
+ const focusables = this.#getFocusables();
290
+ if (!focusables.includes(active)) {
291
+ return;
292
+ }
293
+ event.preventDefault();
294
+ event.stopPropagation();
295
+ const currentIndex = focusables.indexOf(active);
296
+ let rawIndex;
297
+ let newIndex = currentIndex;
298
+ const { wrap = false } = this.#options;
299
+ switch (key) {
300
+ case "End":
301
+ newIndex = -1;
302
+ break;
303
+ case "Home":
304
+ newIndex = 0;
305
+ break;
306
+ case "ArrowLeft":
307
+ case "ArrowUp":
308
+ rawIndex = currentIndex - 1;
309
+ newIndex = wrap ? rawIndex : Math.max(rawIndex, 0);
310
+ break;
311
+ case "ArrowRight":
312
+ case "ArrowDown":
313
+ rawIndex = currentIndex + 1;
314
+ newIndex = wrap ? rawIndex % focusables.length : Math.min(rawIndex, focusables.length - 1);
315
+ break;
316
+ }
317
+ const focusable = focusables.at(newIndex);
318
+ if (!focusable) {
319
+ return;
320
+ }
321
+ this.#update(focusable);
322
+ focusElement(focusable);
323
+ };
324
+ #update(active) {
325
+ const current = /* @__PURE__ */ new Set([
326
+ ...this.#getFocusables(),
327
+ ...getFocusables(this.#container, {
328
+ composed: true,
329
+ filter: this.#selectorFilter
330
+ })
331
+ ]);
332
+ this.#focusables.forEach((focusable) => {
333
+ if (current.has(focusable)) {
334
+ return;
335
+ }
336
+ if (focusable.isConnected) {
337
+ const index = this.#tabIndexes.get(focusable);
338
+ if (index == null) {
339
+ focusable.removeAttribute("tabindex");
340
+ } else {
341
+ focusable.setAttribute("tabindex", index);
342
+ }
343
+ }
344
+ this.#focusables.delete(focusable);
345
+ this.#tabIndexes.delete(focusable);
346
+ });
347
+ current.forEach((c) => {
348
+ if (this.#focusables.has(c)) {
349
+ return;
350
+ }
351
+ this.#focusables.add(c);
352
+ this.#tabIndexes.set(c, c.getAttribute("tabindex"));
353
+ c.setAttribute("tabindex", "-1");
354
+ });
355
+ if (active && this.#focusables.has(active)) {
356
+ this.#focusables.forEach((focusable) => {
357
+ focusable.setAttribute("tabindex", focusable === active ? "0" : "-1");
358
+ });
359
+ return;
360
+ }
361
+ [...this.#focusables].forEach((focusable, i) => {
362
+ focusable.setAttribute("tabindex", i ? "-1" : "0");
363
+ });
364
+ }
365
+ #createSelectorFilter() {
366
+ const { selector } = this.#options;
367
+ return (element) => !selector || element.matches(selector);
368
+ }
369
+ #getFocusables() {
370
+ return getFocusables(this.#container, {
371
+ composed: true,
372
+ filter: this.#selectorFilter,
373
+ include: (element) => this.#focusables.has(element)
374
+ });
375
+ }
376
+ };
377
+ function focusElement(element) {
378
+ "focus" in element && typeof element.focus === "function" && element.focus();
379
+ }
380
+ function getActiveElement() {
381
+ let current = document.activeElement;
382
+ while (current?.shadowRoot?.activeElement) {
383
+ current = current.shadowRoot.activeElement;
384
+ }
385
+ return current;
386
+ }
387
+ /**
388
+ * Roving Tabindex
389
+ * Lightweight roving tabindex utility with fully focus management.
390
+ * Designed for accessible menus, tabs, toolbars, and composite widgets.
391
+ *
392
+ * @version 1.0.0
393
+ * @author Yusuke Kamiyamane
394
+ * @license MIT
395
+ * @copyright Copyright (c) Yusuke Kamiyamane
396
+ * @see {@link https://github.com/y14e/roving-tabindex}
397
+ */
398
+ /*! Bundled license information:
399
+
400
+ power-focusable/dist/index.js:
401
+ (**
402
+ * Power Focusable
403
+ * High-precision focus management utility with full composed tree support.
404
+ * Handles complex focus rules including tabindex ordering, radio groups, inert.
405
+ *
406
+ * @version 4.1.5
407
+ * @author Yusuke Kamiyamane
408
+ * @license MIT
409
+ * @copyright Copyright (c) Yusuke Kamiyamane
410
+ * @see {@link https://github.com/y14e/power-focusable}
411
+ *)
412
+ */
413
+
414
+ export { createRovingTabIndex };
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@y14e/roving-tabindex",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight roving tabindex utility with fully focus management",
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
+ "focus",
30
+ "focus-management",
31
+ "focusable",
32
+ "roving",
33
+ "roving-tabindex",
34
+ "shadow-dom",
35
+ "shadowdom",
36
+ "tabindex",
37
+ "typescript",
38
+ "utility"
39
+ ],
40
+ "author": "Yusuke Kamiyamane",
41
+ "license": "MIT",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/y14e/roving-tabindex.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/y14e/roving-tabindex/issues"
48
+ },
49
+ "homepage": "https://github.com/y14e/roving-tabindex#readme",
50
+ "devDependencies": {
51
+ "bun-types": "latest",
52
+ "power-focusable": "^4.1.5",
53
+ "tsup": "^8.0.0",
54
+ "typescript": "^5.6.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=18"
58
+ }
59
+ }