go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/build/legacy/build_page/build_default_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 { untracked } from 'mobx';
    16  import { useEffect } from 'react';
    17  import { useLocation, useNavigate } from 'react-router-dom';
    18  
    19  import { RecoverableErrorBoundary } from '@/common/components/error_handling';
    20  import { useStore } from '@/common/store';
    21  
    22  import { INITIAL_DEFAULT_TAB, parseTab } from './common';
    23  
    24  export function BuildDefaultTab() {
    25    const { pathname, search, hash } = useLocation();
    26    const store = useStore();
    27    const navigate = useNavigate();
    28  
    29    // Remove any trailing '/' so the new URL won't contain '//'.
    30    const basePath = pathname.replace(/\/*$/, '');
    31  
    32    // This is unnecessary since the component isn't an observer.
    33    // But add `untracked` just to be safe.
    34    const defaultTab =
    35      parseTab(untracked(() => store.userConfig.build.defaultTab)) ||
    36      INITIAL_DEFAULT_TAB;
    37  
    38    const newUrl = `${basePath}/${defaultTab}${search}${hash}`;
    39    useEffect(
    40      () => navigate(newUrl, { replace: true }),
    41      // The react-router router implementation could trigger URL related updates
    42      // (e.g. search query update) before unmounting the component and
    43      // redirecting users to the new component.
    44      // This may cause infinite loops if the dependency isn't specified.
    45      [navigate, newUrl],
    46    );
    47  
    48    return <></>;
    49  }
    50  
    51  export const element = (
    52    // See the documentation for `<LoginPage />` for why we handle error this way.
    53    <RecoverableErrorBoundary key="default">
    54      <BuildDefaultTab />
    55    </RecoverableErrorBoundary>
    56  );