All files / src/lifecycle context.ts

100% Statements 6/6
100% Branches 1/1
100% Functions 1/1
100% Lines 6/6

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                                                                                1x 5x 5x 5x 5x 5x  
import type { Context } from '../types';
 
/**
 * Creates a new context object for dependency injection throughout the component tree.
 *
 * Contexts enable sharing data between components without prop drilling. Components
 * can provide values in a scope, and descendant components can inject those values.
 * If no provider is found, the default value is returned.
 *
 * @param defaultValue Optional fallback value when no provider is found in the hierarchy
 * @returns A context object that can be used with provide() and inject()
 *
 * @example
 * ```typescript
 * // Create a context with a default theme
 * const ThemeContext = createContext<Theme>({
 *   primary: 'blue',
 *   secondary: 'gray'
 * });
 *
 * // In a component
 * function App() {
 *   return createRoot(() => {
 *     // Provide a custom theme
 *     provide(ThemeContext, { primary: 'red', secondary: 'green' });
 *
 *     // Child components can inject this theme
 *     return h.div({}, h(ThemeButton));
 *   });
 * }
 *
 * // In ThemeButton component
 * function ThemeButton() {
 *   const theme = inject(ThemeContext);
 *   return h.button({
 *     style: { backgroundColor: theme.primary }
 *   }, 'Themed Button');
 * }
 * ```
 */
export function createContext<T>(defaultValue?: T): Context<T> {
  return {
    id: Symbol('context'),
    defaultValue,
  };
}