Skip to content

Commit

Permalink
fix(FocusTrap): fix first render modal autoFocus (#7147)
Browse files Browse the repository at this point in the history
* fix(FocusTrap): fix first render modal autoFocus. add module with array functions

* fix(FocusTrap): run linters
  • Loading branch information
EldarMuhamethanov authored Jul 16, 2024
1 parent cdf2646 commit f1a1b81
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/vkui/src/components/FocusTrap/FocusTrap.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AllHTMLAttributes, useCallback, useRef, useState } from 'react';
import { arraysEquals } from '../../helpers/array';
import { useExternRef } from '../../hooks/useExternRef';
import { FOCUSABLE_ELEMENTS_LIST, Keys, pressedKey } from '../../lib/accessibility';
import {
Expand Down Expand Up @@ -53,7 +54,9 @@ export const FocusTrap = <T extends HTMLElement = HTMLElement>({
const element = focusableNodesRef.current[nodeIndex];

if (element) {
element.focus();
element.focus({
preventScroll: true,
});
}
};

Expand All @@ -77,8 +80,14 @@ export const FocusTrap = <T extends HTMLElement = HTMLElement>({
};

const onMutateParentHandler = (parentNode: HTMLElement) => {
const oldFocusableNodes = [...focusableNodesRef.current];

recalculateFocusableNodesRef(parentNode);

if (arraysEquals(oldFocusableNodes, focusableNodesRef.current)) {
return;
}

if (document) {
const activeElement = document.activeElement as HTMLElement;
const currentElementIndex = Math.max(
Expand Down
12 changes: 12 additions & 0 deletions packages/vkui/src/helpers/array.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { arraysEquals } from './array';

describe.each([
{ arrA: [1, 2, 3], arrB: [1, 2, 3], expected: true },
{ arrA: [1, 2, 3, 4], arrB: [1, 2, 3], expected: false },
{ arrA: [1, 2, 3], arrB: [1, 3, 2], expected: false },
{ arrA: [{}, {}], arrB: [{}, {}], expected: false },
])('arraysEquals', ({ arrA, arrB, expected }) => {
test(`returns ${expected}`, () => {
expect(arraysEquals(arrA, arrB)).toBe(expected);
});
});
9 changes: 9 additions & 0 deletions packages/vkui/src/helpers/array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Сравнивает два массива
*/
export function arraysEquals<T>(arrA: T[], arrB: T[]) {
if (arrA.length !== arrB.length) {
return false;
}
return arrA.every((item, index) => item === arrB[index]);
}

0 comments on commit f1a1b81

Please sign in to comment.