go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/build/components/builder_table/context.tsx (about)

     1  // Copyright 2024 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 { ReactNode, createContext, useContext } from 'react';
    16  
    17  import {
    18    DecoratedClient,
    19    usePrpcServiceClient,
    20  } from '@/common/hooks/prpc_query';
    21  import { BatchedBuildsClientImpl } from '@/proto_utils/batched_builds_client';
    22  
    23  const BuildsClientCtx =
    24    createContext<DecoratedClient<BatchedBuildsClientImpl> | null>(null);
    25  const NumOfBuildsCtx = createContext<number | null>(null);
    26  
    27  export interface BuilderTableContextProviderProps {
    28    readonly numOfBuilds: number;
    29    readonly maxBatchSize: number;
    30    readonly children: ReactNode;
    31  }
    32  
    33  export function BuilderTableContextProvider({
    34    numOfBuilds,
    35    maxBatchSize,
    36    children,
    37  }: BuilderTableContextProviderProps) {
    38    const buildsClient = usePrpcServiceClient(
    39      {
    40        host: SETTINGS.buildbucket.host,
    41        ClientImpl: BatchedBuildsClientImpl,
    42      },
    43      { maxBatchSize },
    44    );
    45  
    46    return (
    47      <BuildsClientCtx.Provider value={buildsClient}>
    48        <NumOfBuildsCtx.Provider value={numOfBuilds}>
    49          {children}
    50        </NumOfBuildsCtx.Provider>
    51      </BuildsClientCtx.Provider>
    52    );
    53  }
    54  
    55  export function useBuildsClient() {
    56    const ctx = useContext(BuildsClientCtx);
    57    if (ctx === null) {
    58      throw new Error(
    59        'useBuildsClient can only be used within BuilderTableContextProvider',
    60      );
    61    }
    62    return ctx;
    63  }
    64  
    65  export function useNumOfBuilds() {
    66    const ctx = useContext(NumOfBuildsCtx);
    67    if (ctx === null) {
    68      throw new Error(
    69        'useNumOfBuilds can only be used within BuilderTableContextProvider',
    70      );
    71    }
    72    return ctx;
    73  }