go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/gitiles/components/commit_table/commit_table.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 { Table } from '@mui/material';
    16  import { ReactNode, useEffect, useMemo, useRef, useState } from 'react';
    17  import { useLatest } from 'react-use';
    18  
    19  import { DefaultExpandedStateProvider, RepoUrlProvider } from './context';
    20  
    21  export interface CommitTableProps {
    22    readonly repoUrl: string;
    23    readonly initDefaultExpanded?: boolean;
    24    readonly onDefaultExpandedChanged?: (expand: boolean) => void;
    25    readonly children: ReactNode;
    26  }
    27  
    28  export function CommitTable({
    29    repoUrl,
    30    initDefaultExpanded = false,
    31    onDefaultExpandedChanged = () => {
    32      /* Noop by default. */
    33    },
    34    children,
    35  }: CommitTableProps) {
    36    const [defaultExpanded, setDefaultExpanded] = useState(initDefaultExpanded);
    37    const defaultExpandedState = useMemo(
    38      () => [defaultExpanded, setDefaultExpanded] as const,
    39      [defaultExpanded],
    40    );
    41  
    42    const onDefaultExpandedChangedRef = useLatest(onDefaultExpandedChanged);
    43    const isFirstCall = useRef(true);
    44    useEffect(() => {
    45      // Skip the first call because the default state were not changed.
    46      if (isFirstCall.current) {
    47        isFirstCall.current = false;
    48        return;
    49      }
    50      onDefaultExpandedChangedRef.current(defaultExpanded);
    51    }, [onDefaultExpandedChangedRef, defaultExpanded]);
    52  
    53    return (
    54      <Table
    55        size="small"
    56        sx={{
    57          borderCollapse: 'separate',
    58          '& td, th': {
    59            padding: '0px 8px',
    60          },
    61          minWidth: '1000px',
    62        }}
    63      >
    64        <DefaultExpandedStateProvider value={defaultExpandedState}>
    65          <RepoUrlProvider value={repoUrl}>{children}</RepoUrlProvider>
    66        </DefaultExpandedStateProvider>
    67      </Table>
    68    );
    69  }