Skip to content

Commit

Permalink
Fix the navigation not listening to the back button (gravitational#21207
Browse files Browse the repository at this point in the history
)

* Fix the navigation not listening to the back button

* Update web/packages/teleport/src/Navigation/Navigation.tsx

Co-authored-by: Rafał Cieślak <rafal.cieslak@goteleport.com>

* Allow for history.Location and Location types to be used

* Run prettier

---------

Co-authored-by: Rafał Cieślak <rafal.cieslak@goteleport.com>
  • Loading branch information
ryanclark and ravicious authored Feb 3, 2023
1 parent a604a2b commit 3c464d6
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions web/packages/teleport/src/Navigation/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { NavigationCategoryContainer } from 'teleport/Navigation/NavigationCateg

import logo from './logo.png';

import type { Location } from 'history';
import type * as history from 'history';

import type { TeleportFeature } from 'teleport/types';

Expand Down Expand Up @@ -77,7 +77,7 @@ export function getFirstRouteForCategory(

function getCategoryForRoute(
features: TeleportFeature[],
route: Location<unknown>
route: history.Location<unknown> | Location
) {
const feature = features
.filter(feature => Boolean(feature.route))
Expand Down Expand Up @@ -105,32 +105,55 @@ export function Navigation() {
NavigationCategory.Resources
);

const [previousRoute, setPreviousRoute] = useState('');
const [previousRoute, setPreviousRoute] = useState<{
[category: string]: string;
}>({});

useEffect(() => {
return history.listen(next => {
const handleLocationChange = useCallback(
(next: history.Location<unknown> | Location) => {
const previousPathName = location.pathname;

const category = getCategoryForRoute(features, next);

if (category && category !== view) {
setPreviousRoute(previousPathName);
setPreviousRoute(previous => ({
...previous,
[view]: previousPathName,
}));
setView(category);
}
});
},
[location, view]
);

useEffect(() => {
return history.listen(handleLocationChange);
}, [history, location.pathname, features, view]);

const handlePopState = useCallback(
(event: PopStateEvent) => {
handleLocationChange((event.currentTarget as Window).location);
},
[view]
);

useEffect(() => {
window.addEventListener('popstate', handlePopState);

return () => window.removeEventListener('popstate', handlePopState);
}, [handlePopState]);

const handleCategoryChange = useCallback(
(category: NavigationCategory) => {
if (view === category) {
return;
}

history.push(
previousRoute || getFirstRouteForCategory(features, category)
previousRoute[category] || getFirstRouteForCategory(features, category)
);
},
[view, location.pathname, previousRoute]
[view, previousRoute]
);

const categories = NAVIGATION_CATEGORIES.map((category, index) => (
Expand Down

0 comments on commit 3c464d6

Please sign in to comment.