Skip to content
Merged
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
24 changes: 22 additions & 2 deletions docs/6.x/docs/guides/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ In 5.x, `PaperProvider` set the `scale` itself and replaced any `scale` in the t

If your app was written for a 6.0 alpha build, which also read a `scale` set on `PaperProvider`, remove it from that theme too.

Other `scale` values, which made animations slower or faster, have no replacement in 6.0. A `scale` in a component's `theme` prop, such as `theme={{ animation: { scale: 2 } }}`, does nothing now, and it can no longer turn animations back on while reduce motion is on. Paper ignores an `animation` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider` or a component, or typed as `Theme`, but not in the `theme` prop of `ThemeProvider`, which accepts any value, or in an untyped variable that also holds other theme keys.
Other `scale` values, which made animations slower or faster, have no replacement in 6.0. A `scale` in a component's `theme` prop, such as `theme={{ animation: { scale: 2 } }}`, does nothing now, and it can no longer turn animations back on while reduce motion is on. Paper ignores an `animation` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider`, `ThemeProvider` or a component, or typed as `Theme`, but not in an untyped variable that also holds other theme keys.

In 5.x, `PaperProvider` also followed the device setting only when you passed no `theme`. In 6.x, `'auto'` follows the device setting with every theme, so if your app passes a custom theme, Paper's animations now stop when the user turns on reduce motion. 6.x also reads the setting when the app starts, while 5.x only reacted when it changed.

Expand Down Expand Up @@ -254,7 +254,7 @@ If you import it from Paper's type declarations instead, the path changed:

#### `roundness`

The `roundness` theme property was removed. Corner radii are now set in `theme.shapes.corner`, a scale of roles from `extraSmall` (4) to `extraExtraLarge` (48), and each component uses one fixed role. Paper ignores a `roundness` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider` or a component, or typed as `Theme`, but not in the `theme` prop of `ThemeProvider`, which accepts any value, or in an untyped variable that also holds other theme keys.
The `roundness` theme property was removed. Corner radii are now set in `theme.shapes.corner`, a scale of roles from `extraSmall` (4) to `extraExtraLarge` (48), and each component uses one fixed role. Paper ignores a `roundness` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider`, `ThemeProvider` or a component, or typed as `Theme`, but not in an untyped variable that also holds other theme keys.

In 5.x, each of these components multiplied `roundness` by a fixed number, and the 6.x defaults match the 5.x corners with the default `roundness` of 4. To port a custom `roundness`, set each role to your `roundness` times its multiplier:

Expand Down Expand Up @@ -331,6 +331,26 @@ As with `roundness`, Paper ignores these keys, and TypeScript reports them in th
+const fonts = configureFonts({ config: fontConfig });
```

#### `ThemeProvider`

`ThemeProvider` now merges its `theme` deeply onto the theme above it, as `PaperProvider` and a component's `theme` prop do, so a nested theme only needs the keys it changes. In 5.x it replaced the theme above it, so a partial theme made Paper's components throw when they rendered.

```diff
<PaperProvider>
<ThemeProvider
- theme={{
- ...LightTheme,
- colors: { ...LightTheme.colors, primary: 'tomato' },
- }}
+ theme={{ colors: { primary: 'tomato' } }}
>
<App />
</ThemeProvider>
</PaperProvider>
```

A full theme, such as `DarkTheme` or the theme `useTheme()` returns, gives the same result as before, except that custom keys of the theme above it are kept. The `theme` prop is now typed as a partial `Theme`, as on `PaperProvider`, so TypeScript reports a value that isn't a theme, such as a number, and keys the theme doesn't have, such as `roundness`. The `theme` prop of a component returned by `withTheme` gets the same type, and the component you wrap must take a `Theme` in its `theme` prop. A `ThemeProvider` without a `theme` now passes the theme above it on. In 5.x it gave its children the default light theme. To keep that, pass `theme={LightTheme}`.

### Accessibility props

Components now use React Native's `aria-*` props and `role` instead of the `accessibility*` props. `accessibilityLabel` is now `aria-label`, the `accessibilityRole` of `Button` is now `role`, and the `accessibilityState` of `FAB` and `Menu.Item` is now `aria-checked` and `aria-selected`.
Expand Down
20 changes: 20 additions & 0 deletions docs/6.x/docs/guides/theming.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,26 @@ export default function HomeScreen() {

React Native Paper ships with Material Design 3 (Material You) only. Customize the default experience by extending `LightTheme` or `DarkTheme` (see [Extending the theme](#extending-the-theme) and [Advanced theme overrides](#advanced-theme-overrides)).

## Applying a theme to part of the app

To change the theme of every component in one part of your app, wrap that part in `ThemeProvider`. Like a component's `theme` prop, its `theme` is merged deeply onto the theme above it, so pass only the keys you change:

```js
import * as React from 'react';
import { Button, ThemeProvider } from 'react-native-paper';

export default function CheckoutActions() {
return (
<ThemeProvider theme={{ colors: { primary: 'tomato' } }}>
<Button>Pay</Button>
<Button mode="outlined">Cancel</Button>
</ThemeProvider>
);
}
```

Unlike `PaperProvider`, `ThemeProvider` doesn't choose between `LightTheme` and `DarkTheme` from `dark`. To show part of the app in the dark theme, pass `DarkTheme` itself.

## Applying a theme to a paper component

If you want to change the theme for a certain component from the library, you can directly pass the `theme` prop to the component. The theme passed as the prop is merged with the theme from the `PaperProvider`:
Expand Down
6 changes: 4 additions & 2 deletions src/components/Portal/Portal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
SettingsContext,
Provider as SettingsProvider,
} from '../../core/settings';
import { ThemeProvider, useInternalTheme } from '../../core/theming';
import { InternalThemeProvider, useInternalTheme } from '../../core/theming';
import { ReduceMotionContext } from '../../theme/accessibility/ReduceMotionContext';
import type { ThemeProp } from '../../theme/types';

Expand Down Expand Up @@ -60,7 +60,9 @@ const Portal = ({ children, modal, theme: themeOverrides }: Props) => {
<SettingsProvider value={settings}>
<ReduceMotionContext.Provider value={reduceMotion}>
<LocaleProvider direction={direction}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
<InternalThemeProvider theme={theme}>
{children}
</InternalThemeProvider>
</LocaleProvider>
</ReduceMotionContext.Provider>
</SettingsProvider>
Expand Down
6 changes: 4 additions & 2 deletions src/core/PaperProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getDefaultDirection, LocaleProvider, type Direction } from './locale';
import SafeAreaProviderCompat from './SafeAreaProviderCompat';
import { Provider as SettingsProvider } from './settings';
import type { Settings } from './settings';
import { safeMerge, ThemeProvider } from './theming';
import { InternalThemeProvider, safeMerge } from './theming';
import {
useResolvedReduceMotion,
type ReduceMotionPreference,
Expand Down Expand Up @@ -69,7 +69,9 @@ const PaperProvider = (props: Props) => {
<SettingsProvider value={settingsValue}>
<ReduceMotionContext.Provider value={resolvedReduceMotion}>
<LocaleProvider direction={direction}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
<InternalThemeProvider theme={theme}>
{children}
</InternalThemeProvider>
</LocaleProvider>
</ReduceMotionContext.Provider>
</SettingsProvider>
Expand Down
196 changes: 196 additions & 0 deletions src/theme/__tests__/ThemeProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import * as React from 'react';
import { PlatformColor } from 'react-native';

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

import Button from '../../components/Button/Button';
import Text from '../../components/Typography/Text';
import PaperProvider from '../../core/PaperProvider';
import { ThemeProvider, useTheme } from '../provider';
import { DarkTheme, LightTheme } from '../schemes';
import type { Theme, ThemeProp } from '../types';

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

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

const MemoThemeReader = React.memo(ThemeReader);

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

describe('ThemeProvider', () => {
it('renders a partial theme and keeps the other keys of the theme above it', async () => {
const onTheme = createOnTheme();

await render(
<PaperProvider theme={DarkTheme} reduceMotion="off">
<ThemeProvider theme={{ colors: { primary: 'red' } }}>
<Button>Press me</Button>
<ThemeReader onTheme={onTheme} />
</ThemeProvider>
</PaperProvider>
);

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

it('merges nested themes in order', async () => {
const onTheme = createOnTheme();

await render(
<PaperProvider theme={LightTheme} reduceMotion="off">
<ThemeProvider
theme={{ colors: { primary: 'red', secondary: 'green' } }}
>
<ThemeProvider theme={{ colors: { secondary: 'blue' } }}>
<ThemeReader onTheme={onTheme} />
</ThemeProvider>
</ThemeProvider>
</PaperProvider>
);

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

it.each([
{ label: 'DarkTheme', parent: LightTheme, theme: DarkTheme },
{ label: 'LightTheme', parent: DarkTheme, theme: LightTheme },
{
label: 'a theme with custom keys',
parent: DarkTheme,
theme: {
...LightTheme,
custom: 'property',
colors: { ...LightTheme.colors, brandPrimary: '#fefefe' },
},
},
])(
'gives the components the values of a full theme: $label',
async ({ parent, theme }) => {
const onTheme = createOnTheme();

await render(
<PaperProvider theme={parent} reduceMotion="off">
<ThemeProvider theme={theme}>
<ThemeReader onTheme={onTheme} />
</ThemeProvider>
</PaperProvider>
);

expect(onTheme.mock.lastCall?.[0]).toStrictEqual(theme);
}
);

it('drops prototype keys from a theme parsed from JSON', async () => {
const theme: ThemeProp = JSON.parse(
'{"__proto__": {"polluted": "yes"}, "constructor": {"polluted": "yes"}, "colors": {"__proto__": {"polluted": "yes"}, "constructor": {"polluted": "yes"}, "primary": "red"}}'
);
const onTheme = createOnTheme();

await render(
<PaperProvider theme={LightTheme} reduceMotion="off">
<ThemeProvider theme={theme}>
<ThemeReader onTheme={onTheme} />
</ThemeProvider>
</PaperProvider>
);

expect(onTheme).toHaveBeenCalled();
const [received] = onTheme.mock.calls[0];
for (const value of [received, received.colors]) {
expect(Object.getPrototypeOf(value)).toBe(Object.prototype);
for (const key of ['__proto__', 'constructor']) {
expect(Object.prototype.hasOwnProperty.call(value, key)).toBe(false);
}
expect(value).not.toHaveProperty('polluted');
}
expect(received.colors.primary).toBe('red');
expect(received.colors.secondary).toBe(LightTheme.colors.secondary);
expect({}).not.toHaveProperty('polluted');
});

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

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

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

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

await render(
<PaperProvider theme={DarkTheme} reduceMotion="off">
<ThemeReader onTheme={onParentTheme} />
<ThemeProvider>
<ThemeReader onTheme={onTheme} />
</ThemeProvider>
</PaperProvider>
);

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

it('does not re-render its children for an equal theme', async () => {
const onTheme = createOnTheme();
const renderTree = (primary: string) => (
<PaperProvider theme={LightTheme} reduceMotion="off">
<ThemeProvider theme={{ colors: { primary } }}>
<MemoThemeReader onTheme={onTheme} />
</ThemeProvider>
</PaperProvider>
);

const { rerender } = await render(renderTree('red'));
await rerender(renderTree('red'));

expect(onTheme).toHaveBeenCalledTimes(1);

await rerender(renderTree('blue'));

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

it('takes a partial theme, and TypeScript reports anything else', async () => {
// `yarn typecheck` fails if one of these stops being a type error.
await render(
<PaperProvider theme={LightTheme} reduceMotion="off">
<ThemeProvider theme={{ colors: { primary: 'red' } }}>
<Text>Partial theme</Text>
</ThemeProvider>
{/* @ts-expect-error: `roundness` was removed from the theme */}
<ThemeProvider theme={{ roundness: 2 }}>
<Text>Removed key</Text>
</ThemeProvider>
{/* @ts-expect-error: a number isn't a theme */}
<ThemeProvider theme={42}>{null}</ThemeProvider>
</PaperProvider>
);

expect(screen.getByText('Partial theme')).toBeOnTheScreen();
expect(screen.getByText('Removed key')).toBeOnTheScreen();
});
});
29 changes: 25 additions & 4 deletions src/theme/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ import type { $DeepPartial } from '@callstack/react-theme-provider';
import isEqual from 'fast-deep-equal';

import { DarkTheme, LightTheme } from './schemes';
import type { Theme, NavigationTheme } from './types';
import type { Theme, ThemeProp, NavigationTheme } from './types';

const {
ThemeProvider,
// 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<unknown>(LightTheme);
} = createTheming<Theme>(LightTheme);

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

export function useTheme<T = Theme>(overrides?: $DeepPartial<T>) {
const safeOverrides = React.useMemo(
Expand Down Expand Up @@ -113,6 +115,25 @@ export const useInternalTheme = (
);
};

type ThemeProviderProps = {
children: React.ReactNode;
/**
* Theme for the components below it, merged deeply onto the theme above it.
*/
theme?: ThemeProp;
};

export const ThemeProvider = ({
children,
theme: themeOverrides,
}: ThemeProviderProps) => {
const theme = useInternalTheme(themeOverrides);

return (
<InternalThemeProvider theme={theme}>{children}</InternalThemeProvider>
);
};

export function adaptNavigationTheme<T extends NavigationTheme>(themes: {
reactNavigationLight: T;
materialLight?: Theme;
Expand Down
Loading