1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React, { useEffect, 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' | 'notFoundLabel';
13 const tabbedListStyles: StyleRulesCallback<TabbedListClasses> = (theme: ArvadosTheme) => ({
18 backgroundColor: theme.palette.background.paper,
22 borderBottom: '1px solid lightgrey',
30 backgroundColor: theme.palette.grey[200],
35 padding: theme.spacing.unit,
36 color: theme.palette.grey[700],
41 type TabPanelProps = {
42 children: React.ReactNode;
47 type TabbedListProps<T> = {
48 tabbedListContents: Record<string, T[]>;
49 injectedStyles?: string;
50 selectedIndex?: number;
52 includeContentsLength: boolean;
53 handleSelect?: (selection: T) => React.MouseEventHandler<HTMLElement> | undefined;
54 renderListItem?: (item: T) => React.ReactNode;
55 handleTabChange?: (event: React.SyntheticEvent, newValue: number) => void;
58 export const TabbedList = withStyles(tabbedListStyles)(<T,>({ tabbedListContents, selectedIndex, selectedTab, injectedStyles, classes, handleSelect, renderListItem, handleTabChange, includeContentsLength }: TabbedListProps<T> & WithStyles<TabbedListClasses>) => {
59 const tabNr = selectedTab || 0;
60 const listRefs = useRef<HTMLDivElement[]>([]);
61 const tabLabels = Object.keys(tabbedListContents);
64 if (selectedIndex !== undefined && listRefs.current[selectedIndex]) {
65 listRefs.current[selectedIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
70 <div className={classNames(classes.root, injectedStyles)}>
71 <div className={classes.tabs}>
74 onChange={handleTabChange}
77 {tabLabels.map((label) => (
78 <Tab data-cy={`${label}-tab-label`} label={includeContentsLength ? `${label} (${tabbedListContents[label].length})` : label} />
86 <List className={classes.list}>
87 {tabbedListContents[tabLabels[tabNr]].length === 0 && <div className={classes.notFoundLabel}>no matching {tabLabels[tabNr]} found</div>}
88 {tabbedListContents[tabLabels[tabNr]].map((item, i) => (
89 <div ref={(el) => { if (!!el) listRefs.current[i] = el}}>
91 className={classes.listItem}
92 selected={i === selectedIndex}
93 onClick={handleSelect && handleSelect(item)}
95 {renderListItem ? renderListItem(item) : JSON.stringify(item)}
105 const TabPanel = ({ children, value, index }: TabPanelProps) => {
106 return <div hidden={value !== index}>{value === index && children}</div>;