1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React, { useEffect, useState, useRef } from 'react';
6 import { Tabs, Tab, List, ListItem, StyleRulesCallback, withStyles } from '@material-ui/core';
7 import { WithStyles } from '@material-ui/core';
8 import classNames from 'classnames';
9 import { ArvadosTheme } from 'common/custom-theme';
11 type TabbedListClasses = 'root' | 'tabs' | 'list' | 'listItem';
13 const tabbedListStyles: StyleRulesCallback<TabbedListClasses> = (theme: ArvadosTheme) => ({
18 backgroundColor: theme.palette.background.paper,
22 borderBottom: '1px solid lightgrey',
32 type SingleTabProps<T> = {
37 type TabPanelProps = {
38 children: React.ReactNode;
43 type TabbedListProps<T> = {
44 tabbedListContents: SingleTabProps<T>[];
45 renderListItem?: (item: T) => React.ReactNode;
46 injectedStyles?: string;
47 keypress?: { key: string };
48 selectedIndex?: number;
51 export const TabbedList = withStyles(tabbedListStyles)(<T, _>({ tabbedListContents, renderListItem, selectedIndex, keypress, injectedStyles, classes }: TabbedListProps<T> & WithStyles<TabbedListClasses>) => {
52 const [tabNr, setTabNr] = useState(0);
53 const listRefs = useRef<HTMLDivElement[]>([]);
56 if (keypress) handleKeyPress(keypress.key);
60 if (selectedIndex !== undefined && listRefs.current[selectedIndex]) {
61 listRefs.current[selectedIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
65 const handleKeyPress = (keypress: string) => {
66 const numTabs = tabbedListContents.length;
67 if (keypress === 'Tab') {
68 setTabNr((tabNr + 1) % numTabs);
72 const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
73 event.preventDefault();
78 <div className={classNames(classes.root, injectedStyles)}>
79 <div className={classes.tabs}>
82 onChange={handleTabChange}
85 {tabbedListContents.map((tab) => (
86 <Tab label={tab.label} />
94 <List className={classes.list}>
95 {tabbedListContents[tabNr].items.map((item, i) => (
96 <div ref={(el) => { if (!!el) listRefs.current[i] = el}}>
98 className={classes.listItem}
99 selected={i === selectedIndex}
101 {renderListItem ? renderListItem(item) : JSON.stringify(item)}
111 const TabPanel = ({ children, value, index }: TabPanelProps) => {
112 return <div hidden={value !== index}>{value === index && children}</div>;