From fe16bbf0bbe6f9f4c8cdccdc452005cab805c8da Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Sun, 25 Aug 2024 14:09:13 +0200 Subject: [PATCH] Refactor focus selector logic, better cleanup, lazier map copy --- .../navigator-provider/component.tsx | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/components/src/navigator/navigator-provider/component.tsx b/packages/components/src/navigator/navigator-provider/component.tsx index 0e3c3b9a5fc62..101ab57ff6ea4 100644 --- a/packages/components/src/navigator/navigator-provider/component.tsx +++ b/packages/components/src/navigator/navigator-provider/component.tsx @@ -83,25 +83,32 @@ function goTo( return { currentLocation, focusSelectors }; } - let focusSelectorsCopy; + let focusSelectorsCopy: typeof focusSelectors | undefined; + function getFocusSelectorsCopy() { + focusSelectorsCopy = + focusSelectorsCopy ?? new Map( state.focusSelectors ); + return focusSelectorsCopy; + } // Set a focus selector that will be used when navigating // back to the current location. if ( focusTargetSelector && currentLocation?.path ) { - if ( ! focusSelectorsCopy ) { - focusSelectorsCopy = new Map( state.focusSelectors ); - } - focusSelectorsCopy.set( currentLocation.path, focusTargetSelector ); + getFocusSelectorsCopy().set( + currentLocation.path, + focusTargetSelector + ); } // Get the focus selector for the new location. let currentFocusSelector; - if ( isBack ) { - if ( ! focusSelectorsCopy ) { - focusSelectorsCopy = new Map( state.focusSelectors ); + if ( focusSelectors.get( path ) ) { + if ( isBack ) { + // Use the found focus selector only when navigating back. + currentFocusSelector = focusSelectors.get( path ); } - currentFocusSelector = focusSelectorsCopy.get( path ); - focusSelectorsCopy.delete( path ); + // Make a copy of the focusSelectors map to remove the focus selector + // only if necessary (ie. a focus selector was found). + getFocusSelectorsCopy().delete( path ); } return {