Skip to content

Commit

Permalink
Fix focus restoring when activation happened lazily
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Jun 11, 2021
1 parent a59e0c6 commit 404a24c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -315,11 +315,23 @@ function Unstable_TrapFocus(props) {
}
};

const handleFocusSentinel = (event) => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
};

return (
<React.Fragment>
<div tabIndex={0} ref={sentinelStart} data-test="sentinelStart" />
<div
tabIndex={0}
onFocus={handleFocusSentinel}
ref={sentinelStart}
data-test="sentinelStart"
/>
{React.cloneElement(children, { ref: handleRef, onFocus })}
<div tabIndex={0} ref={sentinelEnd} data-test="sentinelEnd" />
<div tabIndex={0} onFocus={handleFocusSentinel} ref={sentinelEnd} data-test="sentinelEnd" />
</React.Fragment>
);
}
Expand Down
23 changes: 23 additions & 0 deletions test/e2e/fixtures/Unstable_TrapFocus/DefaultOpenLazyTrapFocus.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as React from 'react';
import TrapFocus from '@material-ui/core/Unstable_TrapFocus';

export default function BaseTrapFocus() {
const [open, close] = React.useReducer(() => false, true);

return (
<React.Fragment>
<button type="button" autoFocus data-testid="initial-focus">
initial focus
</button>
<TrapFocus isEnabled={() => true} open={open} disableAutoFocus>
<div data-testid="root">
<div>Title</div>
<button type="button" onClick={close}>
close
</button>
<button type="button">noop</button>
</div>
</TrapFocus>
</React.Fragment>
);
}
15 changes: 15 additions & 0 deletions test/e2e/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,21 @@ describe('e2e', () => {
await expect(screen.getByText('ok')).toHaveFocus();
});

it('should loop the tab key after activation', async () => {
await renderFixture('Unstable_TrapFocus/DefaultOpenLazyTrapFocus');

await expect(screen.getByTestId('initial-focus')).toHaveFocus();

await page.keyboard.press('Tab');
await expect(screen.getByText('close')).toHaveFocus();
await page.keyboard.press('Tab');
await expect(screen.getByText('noop')).toHaveFocus();
await page.keyboard.press('Tab');
await expect(screen.getByText('close')).toHaveFocus();
await page.keyboard.press('Enter');
await expect(screen.getByTestId('initial-focus')).toHaveFocus();
});

it('should focus on first focus element after last has received a tab click', async () => {
await renderFixture('Unstable_TrapFocus/OpenTrapFocus');

Expand Down

0 comments on commit 404a24c

Please sign in to comment.