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
8 changes: 8 additions & 0 deletions .changeset/color-mode-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@maxcwolf/ui-react-native': patch
---

Theme switching is now `useColorMode()`, which returns `{ mode, setMode, name, names, theme }`.
It replaces `useThemeSwitcher()` (`preference`, `setPreference`). `ThemeProvider`'s props are now
`mode`, `defaultMode` and `onModeChange`, and the `ThemePreference` type is `ColorMode`.
`useTheme()` is unchanged.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ export default function App() {
Switch theme anywhere below the provider:

```tsx
const { setPreference } = useThemeSwitcher();
setPreference('dark'); // or 'light', 'system', or any theme you registered
const { setMode } = useColorMode();
setMode('dark'); // or 'light', 'system', or any theme you registered
```

## Components
Expand Down
16 changes: 6 additions & 10 deletions apps/storybook/src/decorators.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { Box, ThemeProvider, type ThemePreference } from '@maxcwolf/ui-react-native';
import { Box, ThemeProvider, type ColorMode } from '@maxcwolf/ui-react-native';
import type { Decorator } from '@storybook/react';

/** The themes the toolbar (web) and captures can pick. `system` follows the device. */
export const themeOptions = [
'system',
'light',
'dark',
] as const satisfies readonly ThemePreference[];
export const themeOptions = ['system', 'light', 'dark'] as const satisfies readonly ColorMode[];

const toPreference = (value: unknown): ThemePreference =>
const toMode = (value: unknown): ColorMode =>
themeOptions.find((option) => option === value) ?? 'system';

/**
Expand All @@ -17,11 +13,11 @@ const toPreference = (value: unknown): ThemePreference =>
* and tested in every theme; on a device, `system` follows the simulator's appearance.
*/
export const withTheme: Decorator = (Story, context) => {
const preference = toPreference(context.globals.theme);
const mode = toMode(context.globals.theme);
return (
<ThemeProvider preference={preference}>
<ThemeProvider mode={mode}>
{/* e2e waits for this id, so axe and screenshots never see the previous theme. */}
<Box testID={`story-theme-${preference}`} flex={1} backgroundColor="background" padding="l">
<Box testID={`story-theme-${mode}`} flex={1} backgroundColor="background" padding="l">
<Story />
</Box>
</ThemeProvider>
Expand Down
14 changes: 9 additions & 5 deletions docs/adr/0005-theme-api.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 0005. Theme API: semantic colors, named themes, switching in the provider

- Status: accepted
- Status: accepted (amended 2026-11-08: the switcher is `useColorMode` with `mode`/`setMode`)
- Date: 2026-11-07

## Context
Expand All @@ -13,8 +13,11 @@ impossible for a component to opt out of.
- Components use semantic color names from one `ThemeColors` type; every theme defines all of
them (a missing one is a type error).
- `ThemeProvider` takes any number of named themes (`themes={{ light, dark, ...rest }}`) and a
preference (`'system'` or a name), controlled or uncontrolled; `useThemeSwitcher()` reads and
changes it at runtime. `'system'` follows `useColorScheme()`.
color mode (`'system'` or a theme name), controlled (`mode`) or uncontrolled (`defaultMode`);
`useColorMode()` reads and changes it at runtime. `'system'` follows `useColorScheme()`.
- Switching is a separate hook from `useTheme()`, as in MUI (`useColorScheme`) and Chakra
(`useColorMode`). `useTheme()` returns only the theme's tokens, which is all components need, so
a component cannot change the app's theme and the theme object stays the plain `Theme` type.
- `createWolfTheme(overrides, base)` builds a theme from partial overrides with the same type.
- `auditThemeContrast(theme)` checks a theme against every pairing the components render, and is
public so apps can test their own themes.
Expand All @@ -23,9 +26,10 @@ impossible for a component to opt out of.
`fontSize`/`fontWeight`/`fontFamily` props.

**Guards:** the `ThemeColors` type, `theme.test.ts` (both themes pass the audit and have the same
shape), ESLint `no-restricted-imports` and `wolf/no-raw-color`, `TextProps`.
shape), ESLint `no-restricted-imports` (Restyle's hooks outside `src/theme/`, `useColorMode` in
components and primitives) and `wolf/no-raw-color`, `TextProps`.

## Consequences

Theme state lives in one place. Persisting the user's choice is the app's job
(`onPreferenceChange`), so the library needs no storage dependency.
(`onModeChange`), so the library needs no storage dependency.
21 changes: 12 additions & 9 deletions docs/theming.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,29 @@ changes their appearance setting. On Android, Expo apps need `expo-system-ui` an
## Let the user choose

```tsx
import { useThemeSwitcher } from '@maxcwolf/ui-react-native';
import { useColorMode } from '@maxcwolf/ui-react-native';

function AppearanceSetting() {
const { name, preference, names, setPreference } = useThemeSwitcher();
// name: the theme showing now ('light'); preference: what was chosen ('system')
const { mode, setMode, name, names } = useColorMode();
// mode: what was chosen ('system'); name: the theme showing now ('light')
// names: every theme the provider has (['light', 'dark'])
return <Button onPress={() => setPreference('dark')}>Dark</Button>;
return <Button onPress={() => setMode('dark')}>Dark</Button>;
}
```

`useColorMode()` is for app code such as a settings screen. Components read the active theme's
tokens with `useTheme()` and never change the mode.

To remember the choice across launches, persist it yourself and hand it back:

```tsx
<ThemeProvider defaultPreference={saved ?? 'system'} onPreferenceChange={save}>
<ThemeProvider defaultMode={saved ?? 'system'} onModeChange={save}>
```

Or control it completely with `preference`, for example from your own settings store:
Or control it completely with `mode`, for example from your own settings store:

```tsx
<ThemeProvider preference={settings.theme}>
<ThemeProvider mode={settings.theme}>
```

## Make a brand theme
Expand Down Expand Up @@ -74,8 +77,8 @@ variant is merged, so `{ heading1: { fontSize: 40 } }` keeps its weight and line
`themes` takes any names. `light` and `dark` back `'system'`; the rest are chosen by name.

```tsx
<ThemeProvider themes={{ light, dark, highContrast, sepia }} defaultPreference="system">
// later: setPreference('highContrast')
<ThemeProvider themes={{ light, dark, highContrast, sepia }} defaultMode="system">
// later: setMode('highContrast')
```

## Check your theme's contrast
Expand Down
Binary file modified e2e/__screenshots__/desktop/foundations-theme--switching--dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/__screenshots__/mobile/foundations-theme--switching--dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/__screenshots__/mobile/foundations-theme--switching--light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion e2e/__transcripts__/foundations-theme--switching.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
heading, Appearance, level 1
Showing "light" (preference: light)
Showing "light" (mode: light)
button, system
button, light
button, dark
Expand Down
2 changes: 1 addition & 1 deletion e2e/tests/keyboard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ test('a button takes keyboard focus with a visible ring, and Enter presses it',
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Enter');
await expect(page.getByText('Showing "dark" (preference: dark)')).toBeVisible();
await expect(page.getByText('Showing "dark" (mode: dark)')).toBeVisible();
});

test('a mouse click does not leave a focus ring behind', async ({ page }) => {
Expand Down
21 changes: 20 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ const restyleOnlyInTheme = {
'Use useTheme / ThemeProvider from the theme layer (src/theme), which types the theme and adds theme switching (ADR 0005).',
};

const colorModeOnlyInApps = {
group: ['**/theme', '**/theme/*'],
importNames: ['useColorMode'],
message:
'Components read tokens with useTheme(); changing the color mode belongs to the app (ADR 0005).',
};

const testingLibraryRender = {
name: '@testing-library/react-native',
importNames: ['render'],
Expand Down Expand Up @@ -142,7 +149,19 @@ export default tseslint.config(
rules: {
'no-restricted-imports': [
'error',
{ paths: [restyleOnlyInTheme, reactNativeViewsInComponents] },
{
paths: [restyleOnlyInTheme, reactNativeViewsInComponents],
patterns: [colorModeOnlyInApps],
},
],
},
},
{
files: ['packages/ui/src/primitives/**/*.{ts,tsx}'],
rules: {
'no-restricted-imports': [
'error',
{ paths: [restyleOnlyInTheme], patterns: [colorModeOnlyInApps] },
],
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ exports[`exports exactly the public API 1`] = `
"iconNames",
"lightColors",
"lightTheme",
"useColorMode",
"useTheme",
"useThemeSwitcher",
]
`;
6 changes: 3 additions & 3 deletions packages/ui/src/test-utils/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import {
type RenderResult,
} from '@testing-library/react-native';
import type { ReactElement } from 'react';
import { ThemeProvider, type ThemePreference, type ThemeSet } from '../theme';
import { ThemeProvider, type ColorMode, type ThemeSet } from '../theme';

interface Options extends Omit<RenderOptions, 'wrapper'> {
/** The theme to render under. Defaults to `'light'`, so a test never depends on the device. */
theme?: ThemePreference;
theme?: ColorMode;
themes?: ThemeSet;
}

Expand All @@ -20,7 +20,7 @@ export function render(
return rtlRender(ui, {
...options,
wrapper: ({ children }) => (
<ThemeProvider preference={theme} {...(themes ? { themes } : {})}>
<ThemeProvider mode={theme} {...(themes ? { themes } : {})}>
{children}
</ThemeProvider>
),
Expand Down
12 changes: 6 additions & 6 deletions packages/ui/src/theme/Theme.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Box, Text } from '../primitives';
import type { ColorName } from './colors';
import { createWolfTheme } from './create-theme';
import { darkTheme, lightTheme, type TextVariant } from './theme';
import { ThemeProvider, useThemeSwitcher } from './ThemeProvider';
import { ThemeProvider, useColorMode } from './ThemeProvider';
import { useTheme } from './use-theme';

const meta = { title: 'Foundations/Theme' } satisfies Meta;
Expand Down Expand Up @@ -83,21 +83,21 @@ const brandDark = createWolfTheme(
);

function ThemeSettings() {
const { name, preference, names, setPreference } = useThemeSwitcher();
const { name, mode, names, setMode } = useColorMode();
return (
<Box backgroundColor="background" padding="l" gap="m">
<Text variant="heading3" role="heading">
Appearance
</Text>
<Text variant="body">{`Showing "${name}" (preference: ${preference})`}</Text>
<Text variant="body">{`Showing "${name}" (mode: ${mode})`}</Text>
<Stack direction="row" gap="s" flexWrap="wrap">
{['system', ...names].map((option) => (
<Button
key={option}
size="s"
variant={option === preference ? 'primary' : 'secondary'}
variant={option === mode ? 'primary' : 'secondary'}
onPress={() => {
setPreference(option);
setMode(option);
}}
>
{option}
Expand All @@ -116,7 +116,7 @@ export const Switching: Story = {
render: () => (
<ThemeProvider
themes={{ light: lightTheme, dark: darkTheme, brand, brandDark }}
defaultPreference="light"
defaultMode="light"
>
<ThemeSettings />
</ThemeProvider>
Expand Down
33 changes: 15 additions & 18 deletions packages/ui/src/theme/ThemeProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,22 @@ import * as ReactNative from 'react-native';
import { Box, Pressable, Text } from '../primitives';
import { createWolfTheme } from './create-theme';
import { darkTheme, lightTheme } from './theme';
import { ThemeProvider, useThemeSwitcher } from './ThemeProvider';
import { ThemeProvider, useColorMode } from './ThemeProvider';

/** Shows what useThemeSwitcher reports and offers one button per theme, like a settings screen. */
/** Shows what useColorMode reports and offers one button per theme, like a settings screen. */
function ThemeSettings() {
const { name, preference, names, setPreference } = useThemeSwitcher();
const { name, mode, names, setMode } = useColorMode();
return (
<Box testID="screen" backgroundColor="background">
<Text variant="body">{`active: ${name}`}</Text>
<Text variant="body">{`preference: ${preference}`}</Text>
<Text variant="body">{`mode: ${mode}`}</Text>
{['system', ...names].map((option) => (
<Pressable
key={option}
role="button"
accessibilityLabel={`Use ${option}`}
onPress={() => {
setPreference(option);
setMode(option);
}}
/>
))}
Expand All @@ -43,34 +43,31 @@ describe('ThemeProvider', () => {
</ThemeProvider>,
);
expect(screen.getByText('active: dark')).toBeOnTheScreen();
expect(screen.getByText('preference: system')).toBeOnTheScreen();
expect(screen.getByText('mode: system')).toBeOnTheScreen();
expect(screen.getByTestId('screen')).toHaveStyle({
backgroundColor: darkTheme.colors.background,
});
});

it('switches theme at runtime and reports the change', async () => {
const onPreferenceChange = jest.fn();
const onModeChange = jest.fn();
await render(
<ThemeProvider onPreferenceChange={onPreferenceChange}>
<ThemeProvider onModeChange={onModeChange}>
<ThemeSettings />
</ThemeProvider>,
);
await userEvent.press(screen.getByRole('button', { name: 'Use dark' }));
expect(screen.getByTestId('screen')).toHaveStyle({
backgroundColor: darkTheme.colors.background,
});
expect(screen.getByText('preference: dark')).toBeOnTheScreen();
expect(onPreferenceChange).toHaveBeenCalledWith('dark');
expect(screen.getByText('mode: dark')).toBeOnTheScreen();
expect(onModeChange).toHaveBeenCalledWith('dark');
});

it('switches between any number of named themes', async () => {
const sepia = createWolfTheme({ colors: { background: '#F4ECD8' } });
await render(
<ThemeProvider
themes={{ light: lightTheme, dark: darkTheme, sepia }}
defaultPreference="sepia"
>
<ThemeProvider themes={{ light: lightTheme, dark: darkTheme, sepia }} defaultMode="sepia">
<ThemeSettings />
</ThemeProvider>,
);
Expand All @@ -81,25 +78,25 @@ describe('ThemeProvider', () => {

it('can be controlled by its parent', async () => {
const { rerender } = await render(
<ThemeProvider preference="light">
<ThemeProvider mode="light">
<ThemeSettings />
</ThemeProvider>,
);
expect(screen.getByText('active: light')).toBeOnTheScreen();
await rerender(
<ThemeProvider preference="dark">
<ThemeProvider mode="dark">
<ThemeSettings />
</ThemeProvider>,
);
expect(screen.getByText('active: dark')).toBeOnTheScreen();
});
});

describe('useThemeSwitcher', () => {
describe('useColorMode', () => {
it('explains itself when used outside a ThemeProvider', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
await expect(render(<ThemeSettings />)).rejects.toThrow(
'useThemeSwitcher must be used inside a wolf-ui ThemeProvider.',
'useColorMode must be used inside a wolf-ui ThemeProvider.',
);
});
});
Loading
Loading