All files / react/src context.tsx

100% Statements 17/17
100% Branches 4/4
100% Functions 3/3
100% Lines 17/17

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 371x                             1x 4x 2x 2x   2x 2x 2x   2x 2x 2x 2x 2x   2x   4x   4x 4x  
import { getContext, setContext, shortId } from '@anchorlib/core';
import type { FC, ReactNode } from 'react';
 
/**
 * Creates a context provider component for managing scoped context values.
 *
 * This function generates a React provider component that manages context values
 * using a unique symbol identifier. It provides automatic cleanup and restoration
 * of previous context values when the provider unmounts.
 *
 * @template T - The type of value to be stored in the context
 * @param key - A unique symbol identifier for the context. Defaults to a generated symbol.
 * @param displayName - Optional display name for the provider component for debugging purposes
 * @returns A React functional component that provides context scoping
 */
export function contextProvider<T>(key: symbol = Symbol(shortId()), displayName?: string) {
  function Provider({ value, children }: { value: T; children: ReactNode }) {
    const prev = getContext(key);
    setContext(key, value);
 
    const Restore = () => {
      return <>{setContext(key, prev)}</>;
    };
 
    return (
      <>
        {children}
        <Restore />
      </>
    );
  }
 
  Provider.displayName = `ContextProvider(${displayName || 'Anonymous'})`;
 
  return Provider as FC<{ value: T; children: ReactNode }>;
}