|
1 | 1 | /* eslint-disable class-methods-use-this */ |
| 2 | +import React, { JSX, useRef } from 'react'; |
| 3 | +import { render, cleanup } from '@testing-library/react'; |
2 | 4 | import { spyElementPrototype } from '../src/test/domHook'; |
3 | | -import { getFocusNodeList, triggerFocus } from '../src/Dom/focus'; |
| 5 | +import { getFocusNodeList, triggerFocus, useLockFocus } from '../src/Dom/focus'; |
4 | 6 |
|
5 | 7 | describe('focus', () => { |
6 | 8 | beforeAll(() => { |
@@ -56,4 +58,42 @@ describe('focus', () => { |
56 | 58 | focusSpy.mockRestore(); |
57 | 59 | setSelectionRangeSpy.mockRestore(); |
58 | 60 | }); |
| 61 | + |
| 62 | + describe('useLockFocus', () => { |
| 63 | + const TestComponent: React.FC<{ lock: boolean }> = ({ lock }) => { |
| 64 | + const elementRef = useRef<HTMLDivElement>(null); |
| 65 | + useLockFocus(lock, () => elementRef.current); |
| 66 | + |
| 67 | + return ( |
| 68 | + <> |
| 69 | + <button data-testid="outer-button">Outer</button> |
| 70 | + <div ref={elementRef} data-testid="focus-container" tabIndex={0}> |
| 71 | + <input key="input1" data-testid="input1" /> |
| 72 | + <button key="button1" data-testid="button1"> |
| 73 | + Button |
| 74 | + </button> |
| 75 | + </div> |
| 76 | + </> |
| 77 | + ); |
| 78 | + }; |
| 79 | + |
| 80 | + it('should restore focus to range when focusing other elements', () => { |
| 81 | + const { getByTestId } = render(<TestComponent lock={true} />); |
| 82 | + |
| 83 | + const focusContainer = getByTestId('focus-container'); |
| 84 | + const input1 = getByTestId('input1') as HTMLInputElement; |
| 85 | + |
| 86 | + // Should focus to first focusable element after lock |
| 87 | + expect(document.activeElement).toBe(focusContainer); |
| 88 | + |
| 89 | + // Focus inside container first |
| 90 | + input1.focus(); |
| 91 | + expect(document.activeElement).toBe(input1); |
| 92 | + |
| 93 | + // Focus outer button |
| 94 | + const outerButton = getByTestId('outer-button') as HTMLButtonElement; |
| 95 | + outerButton.focus(); |
| 96 | + expect(document.activeElement).toBe(input1); |
| 97 | + }); |
| 98 | + }); |
59 | 99 | }); |
0 commit comments