Skip to content

Commit

Permalink
fix: allow returnFocus to be garbage collected, fixes #173
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Nov 7, 2021
1 parent d5ec48b commit ad3a4a1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
18 changes: 6 additions & 12 deletions _tests/FocusLock.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,34 +216,28 @@ d-action

expect(document.activeElement.innerHTML).to.be.equal('d-action0');
wrapper.find('.clickTarget0').simulate('click');

await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action1');
wrapper.find('.clickTarget1').simulate('click');

wrapper.find('.clickTarget1').simulate('click');
await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action2');
wrapper.find('.clickTarget2').simulate('click');

wrapper.find('.clickTarget2').simulate('click');
await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action3');
wrapper.find('.clickTarget2').simulate('click');

// unlock
wrapper.find('.clickTarget2').simulate('click');
await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action2');
wrapper.find('.clickTarget1').simulate('click');

wrapper.find('.clickTarget1').simulate('click');
await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action1');
wrapper.find('.clickTarget0').simulate('click');

wrapper.find('.clickTarget0').simulate('click');
await tick();

expect(document.activeElement.innerHTML).to.be.equal('d-action0');
});

Expand Down
9 changes: 9 additions & 0 deletions src/Lock.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {useMergeRefs} from 'use-callback-ref';

import {hiddenGuard} from './FocusGuard';
import {mediumFocus, mediumBlur, mediumSidecar} from './medium';
import {useEffect} from "react";

const emptyArray = [];

Expand Down Expand Up @@ -59,6 +60,14 @@ const FocusLock = React.forwardRef(function FocusLockUI(props, parentRef) {
}
}, [onDeactivationCallback]);

useEffect(() => {
if(!disabled) {
// cleanup return focus on trap deactivation
// sideEffect/returnFocus should happen by this time
originalFocusedElement.current = null;
}
}, []);

const returnFocus = React.useCallback((allowDefer) => {
const {current: returnFocusTo} = originalFocusedElement;
if (returnFocusTo && returnFocusTo.focus) {
Expand Down

0 comments on commit ad3a4a1

Please sign in to comment.