Skip to content

Commit 1fd5232

Browse files
committed
refactor(useFocusTrap): reduced loop iterations when finding focus index
1 parent 24b6ce8 commit 1fd5232

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/hooks/useFocusTrap.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,6 @@ export interface UseFocusTrapOptions {
99
focusLastOnUnlock?: boolean;
1010
}
1111

12-
function findFocusableIndex(elements: NodeListOf<HTMLElement>, toFind: Element | EventTarget | null) {
13-
let index = -1;
14-
if (!toFind) return index;
15-
elements.forEach((element, i) => {
16-
if (index !== -1) return;
17-
if (element === toFind) index = i;
18-
});
19-
return index;
20-
}
21-
2212
/**
2313
* A hook for trapping focus within an element. Returns a ref which can be given
2414
* to any element to trap focus within that element when `locked` is true.
@@ -124,3 +114,15 @@ export function useFocusTrap<T extends HTMLElement>(locked = false, options: Use
124114

125115
return focusRef;
126116
}
117+
118+
export function findFocusableIndex(elements: NodeListOf<HTMLElement>, toFind: Element | EventTarget | null) {
119+
let index = -1;
120+
if (!toFind) return index;
121+
for (let i = 0; i < elements.length; i++) {
122+
if (elements[i] === toFind) {
123+
index = i;
124+
break;
125+
}
126+
}
127+
return index;
128+
}

0 commit comments

Comments
 (0)