Skip to content

Commit

Permalink
change returnRef to disableReturnRef
Browse files Browse the repository at this point in the history
Instead of allowing consumers to specify a target for return, instead, the return can now be disabled via a ref value.

This helps address a lot of issues where the new focus target isn't easily known.
  • Loading branch information
faultyserver committed May 29, 2020
1 parent 11b70ad commit 3207e2f
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/useFocusLock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,13 @@ export function useLockSubscription(callback: LockListener) {
* occur at the end of the lifetime of the caller component. In other words,
* return focus to where it was before the caller component was mounted.
*/
export function useFocusReturn(returnTo?: React.RefObject<HTMLElement>) {
export function useFocusReturn(disabledRef?: React.RefObject<boolean>) {
// This isn't necessarily safe, but realistically it's sufficient.
const [focusedOnMount] = React.useState(() => document.activeElement as HTMLElement);
const [target] = React.useState(() => document.activeElement as HTMLElement);

React.useLayoutEffect(() => {
return () => {
// Specifically want the actual current value when this hook is cleaning up.
// eslint-disable-next-line react-hooks/exhaustive-deps
const target = returnTo != null ? returnTo.current : focusedOnMount;
if (disabledRef != null && disabledRef.current) return;
// Happens on next tick to ensure it is not overwritten by focus lock.
requestAnimationFrame(() => {
target != null && target.focus();
Expand Down Expand Up @@ -67,12 +65,12 @@ export function useLockLayer(controlledUID?: string) {
export default function useFocusLock(
containerRef: React.RefObject<HTMLElement>,
options: {
returnRef?: React.RefObject<HTMLElement>;
disableReturnRef?: React.RefObject<boolean>;
attachTo?: HTMLElement | Document;
disable?: boolean;
} = {},
) {
const { returnRef, attachTo = document, disable } = options;
const { disableReturnRef, attachTo = document, disable } = options;
// Create a new layer for this lock to occupy
const enabledRef = useLockLayer();

Expand Down Expand Up @@ -140,7 +138,7 @@ export default function useFocusLock(
// This happens at the end to absolutely ensure that the return is the last
// thing that will run as part of this hook (i.e., that the focus handlers
// have been fully detached).
useFocusReturn(returnRef);
useFocusReturn(disableReturnRef);
}

/**
Expand Down

0 comments on commit 3207e2f

Please sign in to comment.