go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/generic_libs/components/routed_tabs/routed_tab.tsx (about)

     1  // Copyright 2023 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  import { Tab, TabProps } from '@mui/material';
    16  import { Link } from 'react-router-dom';
    17  
    18  import { useActiveTabId } from './context';
    19  
    20  export interface RoutedTabProps
    21    extends Omit<TabProps<typeof Link>, 'component' | 'value'> {
    22    // This prop has to have name `value` because mui <Tabs /> iterate over its
    23    // children and collect the `value` props from them to build a list of valid
    24    // tabs.
    25    readonly value: string;
    26    /**
    27     * Hide the tab if the tab is not the current active one.
    28     *
    29     * Sometimes it is useful to conditionally display a tab selector (e.g. base
    30     * on the user permission, whether the data is available, etc). But this can
    31     * get confusing when users hit a tab without a tab selector via a URL route.
    32     * Use this flag to hide the tab selector only when the tab is inactive.
    33     */
    34    readonly hideWhenInactive?: boolean;
    35  }
    36  
    37  /**
    38   * A tab implementation based on MUI tab and react router.
    39   *
    40   * It's similar to MUI `<Tab />` except that
    41   *  * `value` on `<RoutedTabs />` is managed automatically, and
    42   *  * it contains `<Outlet />`.
    43   */
    44  export function RoutedTab({
    45    value,
    46    hideWhenInactive = false,
    47    ...props
    48  }: RoutedTabProps) {
    49    const activeTabId = useActiveTabId();
    50    const shouldHide = hideWhenInactive && value !== activeTabId;
    51  
    52    return (
    53      <Tab
    54        {...props}
    55        value={value}
    56        component={Link}
    57        sx={{ display: shouldHide ? 'none' : '' }}
    58      />
    59    );
    60  }