From 0f72d22e7ff454f1d63e97d0b89647963e8c5a90 Mon Sep 17 00:00:00 2001 From: Bryn Ryans Date: Tue, 21 Sep 2021 21:06:30 +0000 Subject: [PATCH] fix: Sidenav selection Tabs in sidenav were not being synced with history. Now if tab selected, history is updated. If page is reloaded, tabs are synced to current history. If link is clicked that updates sidenav panel, panel is updated accordingly. --- .../src/components/SideNav/SideNav.spec.tsx | 3 ++- .../src/components/SideNav/SideNav.tsx | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/api-explorer/src/components/SideNav/SideNav.spec.tsx b/packages/api-explorer/src/components/SideNav/SideNav.spec.tsx index f1f9e94bf..5a4fc362a 100644 --- a/packages/api-explorer/src/components/SideNav/SideNav.spec.tsx +++ b/packages/api-explorer/src/components/SideNav/SideNav.spec.tsx @@ -83,7 +83,8 @@ describe('SideNav', () => { specs={specs} spec={specState.spec} specDispatch={specDispatch} - /> + />, + ['/3.1/methods'] ) expect(screen.getAllByText(allTagsPattern)).toHaveLength(2) expect( diff --git a/packages/api-explorer/src/components/SideNav/SideNav.tsx b/packages/api-explorer/src/components/SideNav/SideNav.tsx index d364fcf85..a002ac161 100644 --- a/packages/api-explorer/src/components/SideNav/SideNav.tsx +++ b/packages/api-explorer/src/components/SideNav/SideNav.tsx @@ -26,6 +26,7 @@ import type { FC, Dispatch } from 'react' import React, { useContext, useEffect, useState } from 'react' +import { useHistory } from 'react-router' import { Heading, TabList, @@ -84,7 +85,15 @@ export const SideNav: FC = ({ if (match && match.params.sideNavTab) { defaultIndex = tabNames.indexOf(match.params.sideNavTab) } - const tabs = useTabs({ defaultIndex }) + const history = useHistory() + const onTabChange = (index: number) => { + const pathParts = history.location.pathname.split('/') + if (pathParts[2] !== tabNames[index]) { + pathParts[2] = tabNames[index] + history.push(pathParts.join('/')) + } + } + const tabs = useTabs({ defaultIndex, onChange: onTabChange }) const { searchSettings, setSearchSettings } = useContext(SearchContext) const [pattern, setSearchPattern] = useState(searchSettings.pattern) const debouncedPattern = useDebounce(pattern, 250) @@ -120,6 +129,13 @@ export const SideNav: FC = ({ setSearchSettings(setPattern(debouncedPattern!)) }, [debouncedPattern, specKey, spec]) + useEffect(() => { + const { selectedIndex, onSelectTab } = tabs + if (defaultIndex !== selectedIndex) { + onSelectTab(defaultIndex) + } + }, [defaultIndex, tabs]) + const size = useWindowSize() const headlessOffset = headless ? 200 : 120 const menuH = size.height - 16 * HEADER_REM - headlessOffset