Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"@callstack/react-theme-provider": "^3.0.9",
"color": "^3.1.2",
"fast-deep-equal": "^3.1.3",
"hoist-non-react-statics": "^3.3.2",
"use-latest-callback": "^0.2.3"
},
"devDependencies": {
Expand All @@ -70,6 +71,7 @@
"@release-it/conventional-changelog": "^1.1.0",
"@testing-library/react-native": "^14.0.0",
"@types/color": "^3.0.0",
"@types/hoist-non-react-statics": "^3.3.6",
"@types/node": "^24.0.0",
"@types/react": "^19.3.0",
"all-contributors-cli": "^6.24.0",
Expand Down
23 changes: 23 additions & 0 deletions src/theme/__tests__/provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,29 @@ describe('useTheme', () => {
expect({}).not.toHaveProperty('polluted');
});

it('replaces an array from overrides instead of joining it', async () => {
const standard = [0.2, 0, 0, 1] as const;

const { result } = await renderHook(() =>
useTheme<Theme>({ motion: { easing: { standard } } })
);

expect(result.current.motion.easing.standard).toEqual(standard);
expect(result.current.motion.easing.emphasized).toEqual(
LightTheme.motion.easing.emphasized
);
});

it('keeps platform colors from overrides as they are', async () => {
const primary = PlatformColor('label');

const { result } = await renderHook(() =>
useTheme<Theme>({ colors: { primary } })
);

expect(result.current.colors.primary).toBe(primary);
});

it('keeps the theme reference while the overrides object stays the same', async () => {
const overrides = { colors: { primary: '#123456' } };
const { result, rerender } = await renderHook(() =>
Expand Down
106 changes: 106 additions & 0 deletions src/theme/__tests__/withTheme.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import * as React from 'react';
import { PlatformColor } from 'react-native';

import { describe, expect, it, jest } from '@jest/globals';
import { render } from '@testing-library/react-native';

import PaperProvider from '../../core/PaperProvider';
import { useTheme, withTheme } from '../provider';
import { DarkTheme } from '../schemes';
import type { Theme } from '../types';

type ThemeReaderProps = {
onTheme: (theme: Theme) => void;
theme: Theme;
};

const ThemeReader = ({ onTheme, theme }: ThemeReaderProps) => {
onTheme(theme);
return null;
};

const ThemedReader = withTheme(ThemeReader);

const ContextReader = ({ onTheme }: Pick<ThemeReaderProps, 'onTheme'>) => {
onTheme(useTheme());
return null;
};

const createOnTheme = () => jest.fn<(theme: Theme) => void>();

describe('withTheme', () => {
it('passes the theme above it on as it is without a theme', async () => {
const onContextTheme = createOnTheme();
const onTheme = createOnTheme();

await render(
<PaperProvider theme={DarkTheme} reduceMotion="off">
<ContextReader onTheme={onContextTheme} />
<ThemedReader onTheme={onTheme} />
</PaperProvider>
);

expect(onTheme.mock.lastCall?.[0]).toBe(onContextTheme.mock.lastCall?.[0]);
});

it('merges its theme prop onto the theme above it', async () => {
const onTheme = createOnTheme();

await render(
<PaperProvider theme={DarkTheme} reduceMotion="off">
<ThemedReader
onTheme={onTheme}
theme={{ colors: { primary: 'red' } }}
/>
</PaperProvider>
);

expect(onTheme.mock.lastCall?.[0].colors).toStrictEqual({
...DarkTheme.colors,
primary: 'red',
});
});

it('replaces an array from its theme prop instead of joining it', async () => {
const standard = [0.2, 0, 0, 1] as const;
const onTheme = createOnTheme();

await render(
<PaperProvider reduceMotion="off">
<ThemedReader
onTheme={onTheme}
theme={{ motion: { easing: { standard } } }}
/>
</PaperProvider>
);

expect(onTheme.mock.lastCall?.[0].motion.easing.standard).toEqual(standard);
});

it('keeps platform colors from its theme prop as they are', async () => {
const primary = PlatformColor('label');
const onTheme = createOnTheme();

await render(
<PaperProvider reduceMotion="off">
<ThemedReader onTheme={onTheme} theme={{ colors: { primary } }} />
</PaperProvider>
);

expect(onTheme.mock.lastCall?.[0].colors.primary).toBe(primary);
});

it('keeps the statics of the component and names it after it', () => {
class Reader extends React.Component<{ theme: Theme }> {
static screenName = 'reader';

render() {
return null;
}
}
const ThemedClassReader = withTheme(Reader);

expect(ThemedClassReader.screenName).toBe('reader');
expect(ThemedClassReader.displayName).toBe('withTheme(Reader)');
});
});
44 changes: 36 additions & 8 deletions src/theme/provider.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import * as React from 'react';

import { createTheming } from '@callstack/react-theme-provider';
import type { $DeepPartial } from '@callstack/react-theme-provider';
import type {
$DeepPartial,
ThemingType,
} from '@callstack/react-theme-provider';
import isEqual from 'fast-deep-equal';
import hoistNonReactStatics from 'hoist-non-react-statics';

import { DarkTheme, LightTheme } from './schemes';
import type { Theme, ThemeProp, NavigationTheme } from './types';
Expand All @@ -11,20 +15,44 @@ const {
// Puts its `theme` into context as it is, so it takes a full theme. It's for
// providers that have merged the theme already, such as `PaperProvider`.
ThemeProvider: InternalThemeProvider,
withTheme,
useTheme: useThemeBase,
} = createTheming<Theme>(LightTheme);

export { InternalThemeProvider, withTheme };
export { InternalThemeProvider };

export function useTheme<T = Theme>(overrides?: $DeepPartial<T>) {
const safeOverrides = React.useMemo(
() => withoutUnsafeKeys(overrides),
[overrides]
// The `useTheme` and `withTheme` of `createTheming` merge with `deepmerge`,
// which joins arrays such as easing curves, so both merge with `safeMerge`.
export function useTheme<T = Theme>(overrides?: $DeepPartial<T>): T {
const theme = useThemeBase<T>();
return React.useMemo(
() => (overrides ? safeMerge(theme, overrides) : theme),
[theme, overrides]
);
return useThemeBase<T>(safeOverrides);
}

type WithThemeProps = {
theme?: $DeepPartial<Theme>;
};

/* eslint-disable @typescript-eslint/no-unsafe-type-assertion */
export const withTheme = (<Props extends { theme: Theme }>(
Comp: React.ComponentType<Props>
) => {
const ThemedComponent = React.forwardRef<unknown, WithThemeProps>(
({ theme: overrides, ...rest }, ref) => {
const theme = useTheme<Theme>(overrides);
return React.createElement(Comp, {
...(rest as Props),
theme,
ref,
});
}
);
ThemedComponent.displayName = `withTheme(${Comp.displayName || Comp.name})`;
return hoistNonReactStatics(ThemedComponent, Comp);
}) as ThemingType<Theme>['withTheme'];
/* eslint-enable @typescript-eslint/no-unsafe-type-assertion */

// Upstream `deepmerge` corrupts PlatformColor objects, so we recurse manually
// and treat sentinels as leaves. Three shapes:
// `semantic` — iOS PlatformColor
Expand Down
15 changes: 14 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5263,6 +5263,17 @@ __metadata:
languageName: node
linkType: hard

"@types/hoist-non-react-statics@npm:^3.3.6":
version: 3.3.7
resolution: "@types/hoist-non-react-statics@npm:3.3.7"
dependencies:
hoist-non-react-statics: "npm:^3.3.0"
peerDependencies:
"@types/react": "*"
checksum: 10c0/ed8f4e88338f7d021d0f956adf6089d2a12b2e254a03c05292324f2e986d2376eb9efdb8a4f04596823e8fca88c9d06361d20dab4a2a00dc935fb36ac911de55
languageName: node
linkType: hard

"@types/http-cache-semantics@npm:*":
version: 4.0.4
resolution: "@types/http-cache-semantics@npm:4.0.4"
Expand Down Expand Up @@ -11926,7 +11937,7 @@ __metadata:
languageName: node
linkType: hard

"hoist-non-react-statics@npm:^3.3.0":
"hoist-non-react-statics@npm:^3.3.0, hoist-non-react-statics@npm:^3.3.2":
version: 3.3.2
resolution: "hoist-non-react-statics@npm:3.3.2"
dependencies:
Expand Down Expand Up @@ -18159,6 +18170,7 @@ __metadata:
"@release-it/conventional-changelog": "npm:^1.1.0"
"@testing-library/react-native": "npm:^14.0.0"
"@types/color": "npm:^3.0.0"
"@types/hoist-non-react-statics": "npm:^3.3.6"
"@types/node": "npm:^24.0.0"
"@types/react": "npm:^19.3.0"
all-contributors-cli: "npm:^6.24.0"
Expand All @@ -18170,6 +18182,7 @@ __metadata:
eslint-plugin-flowtype: "npm:^8.0.3"
eslint-plugin-testing-library: "npm:^7.16.2"
fast-deep-equal: "npm:^3.1.3"
hoist-non-react-statics: "npm:^3.3.2"
jest: "npm:^29.6.3"
jest-file-snapshot: "npm:^0.3.2"
lefthook: "npm:^2.1.9"
Expand Down
Loading