import React, { createContext, type PropsWithChildren, useContext, useMemo, } from 'react'; import { defaultTheme, type Theme } from '../theme/theme'; /** * Recursively marks every property of `T` as optional. * * The `extends object` guard is required, not cosmetic: `Theme` carries a * `[component: string]: any` index signature, which the mapped type inherits. * Without the guard that index signature becomes `DeepPartial`, an * all-object type that no primitive leaf can satisfy, and every theme override * fails to typecheck. Guarding short-circuits `any` back to `any`. */ export type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; export type StreamThemeInputValue = { mergedStyle?: Theme; style?: DeepPartial; }; /** * @deprecated Use StreamThemeInputValue instead. */ export type ThemeProviderInputValue = StreamThemeInputValue; export type MergedThemesParams = { style?: DeepPartial; theme?: Theme; }; export type ThemeContextValue = { theme: Theme; }; const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const merge = >( target: T, source: DeepPartial, ) => { for (const key in source) { const sourceValue = source[key]; if (sourceValue === undefined) continue; const targetValue = target[key as keyof T]; if (isObject(sourceValue) && isObject(targetValue)) { merge(targetValue, sourceValue as DeepPartial>); } else { target[key as keyof T] = sourceValue as T[keyof T]; } } }; export const mergeThemes = (params: MergedThemesParams) => { const { style, theme } = params; const finalTheme = ( !theme || Object.keys(theme).length === 0 ? JSON.parse(JSON.stringify(defaultTheme)) : JSON.parse(JSON.stringify(theme)) ) as Theme; if (style) { merge(finalTheme, style); } return finalTheme; }; const DEFAULT_BASE_CONTEXT_VALUE = {}; export const ThemeContext = createContext( DEFAULT_BASE_CONTEXT_VALUE as Theme, ); export const StreamTheme: React.FC< PropsWithChildren> > = (props) => { const { children, mergedStyle, style, theme } = props; const modifiedTheme = useMemo(() => { if (mergedStyle) { return mergedStyle; } return mergeThemes({ style, theme }); }, [mergedStyle, style, theme]); return ( {children} ); }; /** * @deprecated Use StreamTheme instead of ThemeProvider. */ export const ThemeProvider = StreamTheme; export const useTheme = () => { const theme = useContext(ThemeContext); if (theme === DEFAULT_BASE_CONTEXT_VALUE) { throw new Error( 'The useThemeContext hook was called outside the ThemeContext Provider. Make sure you have configured OverlayProvider component correctly - https://getstream.io/chat/docs/sdk/reactnative/basics/hello_stream_chat/#overlay-provider', ); } return { theme }; };