Skip to content

Commit

Permalink
Keep focusSelector across multiple back navigations
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Apr 17, 2024
1 parent d3aec42 commit 3b75842
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions packages/edit-site/src/components/sidebar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,36 +32,38 @@ function getAnim( direction ) {
}

export default function SidebarContent( { routeKey, children } ) {
const [ { navDirection, focusSelector }, setNavState ] = useState( {
const [ navState, setNavState ] = useState( {
navDirection: null,
focusSelector: null,
} );

const navigate = useCallback( ( direction, backFocusSelector = null ) => {
setNavState( ( prevDir ) => ( {
navDirection: direction,
const navigate = useCallback( ( direction, focusSelector = null ) => {
setNavState( ( prevState ) => ( {
direction,
focusSelector:
direction === 'forward'
? backFocusSelector
: prevDir.focusSelector,
direction === 'forward' && focusSelector
? focusSelector
: prevState.focusSelector,
} ) );
}, [] );

const wrapperRef = useRef();
useEffect( () => {
let elementToFocus;
if ( navDirection === 'back' && focusSelector ) {
elementToFocus = wrapperRef.current.querySelector( focusSelector );
if ( navState.direction === 'back' && navState.focusSelector ) {
elementToFocus = wrapperRef.current.querySelector(
navState.focusSelector
);
}
if ( navDirection !== null && ! elementToFocus ) {
if ( navState.direction !== null && ! elementToFocus ) {
const [ firstTabbable ] = focus.tabbable.find( wrapperRef.current );
elementToFocus = firstTabbable ?? wrapperRef.current;
}
elementToFocus?.focus();
}, [ navDirection, focusSelector ] );
}, [ navState ] );

const disableMotion = useReducedMotion();
const { initial, animate } = getAnim( navDirection );
const { initial, animate } = getAnim( navState.direction );

return (
<SidebarNavigationContext.Provider value={ navigate }>
Expand Down

0 comments on commit 3b75842

Please sign in to comment.