# All files / src/context SidebarContext.tsx

0% Statements 0/25
0% Branches 0/1
0% Functions 0/1
0% Lines 0/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63

     import React, {
      createContext,
      useCallback,
      useContext,
      useState,
      type JSX,
      type ReactNode,
    } from "react";

    /** Setter function for updating sidebar content. */
    type SidebarSetter = (content: ReactNode | undefined) => void;

    /**
     * Context that holds the current sidebar content node.
     * Consumed by the Sidebar component to render slot content.
     */
    const SidebarContentContext: React.Context<ReactNode | undefined> = createContext<
      ReactNode | undefined
    >(undefined);

    /**
     * Context that holds a stable setter for updating sidebar content.
     * Consumed by layout route wrappers to declare their sidebar content.
     */
    const SidebarSetterContext: React.Context<SidebarSetter | undefined> = createContext<
      SidebarSetter | undefined
    >(undefined);

    /** Props for the SidebarProvider component. */
    interface SidebarProviderProps {
      /** Child components. */
      children: ReactNode;
    }

    /** Provides sidebar slot state to the component tree. */
    export function SidebarProvider({ children }: SidebarProviderProps): JSX.Element {
      const [content, setContent] = useState<ReactNode | undefined>(undefined);

      const stableSetContent: SidebarSetter = useCallback((node: ReactNode | undefined) => {
        setContent(node);
      }, []);

      return (
        <SidebarSetterContext.Provider value={stableSetContent}>
          <SidebarContentContext.Provider value={content}>{children}</SidebarContentContext.Provider>
        </SidebarSetterContext.Provider>
      );
    }

    /** Read the current sidebar content. Returns `undefined` when no content is set. */
    export function useSidebarContent(): ReactNode | undefined {
      return useContext(SidebarContentContext);
    }

    /** Get the sidebar content setter. Must be called within a SidebarProvider. */
    export function useSidebarSetter(): SidebarSetter {
      const setter = useContext(SidebarSetterContext);
      if (setter === undefined) {
        throw new Error("useSidebarSetter must be used within a SidebarProvider");
      }
      return setter;
    }