Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add isInitial property to the location object, use it instead of …
…`isFirstRender` in the `NavigatorScreen`
  • Loading branch information
ciampo committed Dec 14, 2021
commit c78e792745acc091229914da168065c7194f50b3
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function NavigatorProvider(
{
path: initialPath,
isBack: false,
isInitial: true,
},
] );

Expand All @@ -59,11 +60,13 @@ function NavigatorProvider(
...locationHistory.slice( 0, -1 ),
{
...locationHistory[ locationHistory.length - 1 ],
isBack: false,
focusRestorationSelector,
},
{
path,
isBack: false,
isInitial: false,
...restOptions,
},
] );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@ import { css } from '@emotion/react';
* WordPress dependencies
*/
import { focus } from '@wordpress/dom';
import {
useContext,
useEffect,
useMemo,
useState,
useRef,
} from '@wordpress/element';
import { useContext, useEffect, useMemo, useRef } from '@wordpress/element';
import { useReducedMotion } from '@wordpress/compose';
import { isRTL } from '@wordpress/i18n';

Expand Down Expand Up @@ -73,14 +67,14 @@ function NavigatorScreen( props: Props, forwardedRef: Ref< any > ) {
);

// Focus restoration
const [ isFirstRender, setIsFirstRender ] = useState( true );
const isInitialLocation = location.isInitial && ! location.isBack;

useEffect( () => {
// Only attempt to restore focus:
// - after the first render (to avoid moving focus on page load)
// - if the current location is not the initial one (to avoid moving focus on page load)
// - when the screen becomes visible
// - the wrapper ref has been assigned
if ( isFirstRender || ! isMatch || ! wrapperRef.current ) {
setIsFirstRender( false );
// - if the wrapper ref has been assigned
if ( isInitialLocation || ! isMatch || ! wrapperRef.current ) {
return;
}

Expand All @@ -105,7 +99,7 @@ function NavigatorScreen( props: Props, forwardedRef: Ref< any > ) {
}

elementToFocus.focus();
}, [ isFirstRender, isMatch ] );
}, [ isInitialLocation, isMatch ] );

if ( ! isMatch ) {
return null;
Expand Down
1 change: 1 addition & 0 deletions packages/components/src/navigator/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type NavigateOptions = {
};

export type NavigatorLocation = NavigateOptions & {
isInitial?: boolean;
isBack?: boolean;
path?: string;
};
Expand Down