21642: Add unit tests for conditional tabs, add test case for main process output...
[arvados.git] / services / workbench2 / src / components / conditional-tabs / conditional-tabs.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React, { ReactNode, useEffect, useState } from "react";
6 import { Tabs, Tab } from "@material-ui/core";
7 import { TabsProps } from "@material-ui/core/Tabs";
8
9 export type TabData = {
10     show: boolean;
11     label: string;
12     content: ReactNode;
13 };
14
15 type ConditionalTabsProps = {
16     tabs: TabData[];
17 };
18
19 export const ConditionalTabs = (props: Omit<TabsProps, 'value' | 'onChange'> & ConditionalTabsProps) => {
20     const [tabState, setTabState] = useState(0);
21     const visibleTabs = props.tabs.filter(tab => tab.show);
22     const activeTab = visibleTabs[tabState];
23     const visibleTabNames = visibleTabs.map(tab => tab.label).join();
24
25     const handleTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
26         setTabState(value);
27     };
28
29     // Reset tab to 0 when tab visibility changes
30     // (or if tab set change causes visible set to change)
31     useEffect(() => {
32         setTabState(0);
33     }, [visibleTabNames]);
34
35     return <>
36         <Tabs
37             {...props}
38             value={tabState}
39             onChange={handleTabChange} >
40             {visibleTabs.map(tab => <Tab key={tab.label} label={tab.label} />)}
41         </Tabs>
42         {activeTab && activeTab.content}
43     </>;
44 };