From cbd836aef45e7c2cd97a38c1308d04ba0f8945bc Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 4 Nov 2023 22:19:54 +0100 Subject: [PATCH] visualizer: switch to routed tabs Signed-off-by: Patrik Oldsberg --- .../AppVisualizerPage/AppVisualizerPage.tsx | 70 ++++++++++++++++--- 1 file changed, 61 insertions(+), 9 deletions(-) diff --git a/plugins/visualizer/src/components/AppVisualizerPage/AppVisualizerPage.tsx b/plugins/visualizer/src/components/AppVisualizerPage/AppVisualizerPage.tsx index 78ace296b4..cc7dca24f4 100644 --- a/plugins/visualizer/src/components/AppVisualizerPage/AppVisualizerPage.tsx +++ b/plugins/visualizer/src/components/AppVisualizerPage/AppVisualizerPage.tsx @@ -18,29 +18,81 @@ import { Content, Header, HeaderTabs, Page } from '@backstage/core-components'; import { useApi } from '@backstage/core-plugin-api'; import { appTreeApiRef } from '@backstage/frontend-plugin-api'; import Box from '@material-ui/core/Box'; -import React, { useState } from 'react'; +import React, { useCallback, useEffect, useMemo } from 'react'; import { GraphVisualizer } from './GraphVisualizer'; import { TextVisualizer } from './TextVisualizer'; import { TreeVisualizer } from './TreeVisualizer'; +import { + matchRoutes, + useLocation, + useNavigate, + useParams, + useRoutes, +} from 'react-router-dom'; export function AppVisualizerPage() { const appTreeApi = useApi(appTreeApiRef); const { tree } = appTreeApi.getTree(); - const [tab, setTab] = useState(0); - const tabs = [ - { id: 'graph', label: 'Graph', element: }, - { id: 'tree', label: 'Tree', element: }, - { id: 'text', label: 'Text', element: }, - ]; + const tabs = useMemo( + () => [ + { + id: 'graph', + path: 'graph', + label: 'Graph', + element: , + }, + { + id: 'tree', + path: 'tree', + label: 'Tree', + element: , + }, + { + id: 'text', + path: 'text', + label: 'Text', + element: , + }, + ], + [tree], + ); + + const location = useLocation(); + const element = useRoutes(tabs, location); + + const currentPath = `/${useParams()['*']}`; + const [matchedRoute] = matchRoutes(tabs, currentPath) ?? []; + + const currentTabIndex = matchedRoute + ? tabs.findIndex(t => t.path === matchedRoute.route.path) + : 0; + + const navigate = useNavigate(); + const handleTabChange = useCallback( + (index: number) => { + navigate(tabs[index].id); + }, + [navigate, tabs], + ); + + useEffect(() => { + if (!element) { + navigate(tabs[0].path); + } + }, [element, navigate, tabs]); return (
- - {tabs[tab].element} + + {element}