Skip to content

Theming: Set themes.normal according to user preference and export getPreferredColorScheme#28721

Merged
yannbf merged 13 commits into
storybookjs:nextfrom
elisezhg:feat/themes-normal
Nov 3, 2025
Merged

Theming: Set themes.normal according to user preference and export getPreferredColorScheme#28721
yannbf merged 13 commits into
storybookjs:nextfrom
elisezhg:feat/themes-normal

Conversation

@elisezhg
Copy link
Copy Markdown
Contributor

@elisezhg elisezhg commented Jul 27, 2024

Closes #28664

What I did

  • Set themes.normal to either the light or dark theme, according to the user preference
  • Export getPreferredColorScheme as suggested in the issue so it can be used in custom themes

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

  1. Run a sandbox for template, e.g. yarn task --task sandbox --start-from auto --template react-vite/default-ts
  2. Set the docs theme to themes.normal in your preview.ts:
const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
    // ***********************
    docs: {
      theme: themes.normal,
    },
    // ***********************
  },
};
  1. Open Storybook in your browser
  2. Notice that the docs pages' theme is now in sync with the user preference
image image

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=<PR_NUMBER>

name before after diff z %
createSize 0 B 0 B 0 B - -
generateSize 77.8 MB 77.8 MB 0 B 1.33 0%
initSize 143 MB 143 MB 579 B 1.19 0%
diffSize 65.6 MB 65.6 MB 579 B 1.18 0%
buildSize 7.19 MB 7.19 MB 431 B -0.86 0%
buildSbAddonsSize 1.85 MB 1.85 MB 225 B -0.69 0%
buildSbCommonSize 195 kB 195 kB 0 B - 0%
buildSbManagerSize 1.87 MB 1.87 MB 192 B 0.45 0%
buildSbPreviewSize 0 B 0 B 0 B - -
buildStaticSize 0 B 0 B 0 B - -
buildPrebuildSize 3.92 MB 3.92 MB 417 B -0.68 0%
buildPreviewSize 3.28 MB 3.28 MB 14 B -0.9 0%
testBuildSize 0 B 0 B 0 B - -
testBuildSbAddonsSize 0 B 0 B 0 B - -
testBuildSbCommonSize 0 B 0 B 0 B - -
testBuildSbManagerSize 0 B 0 B 0 B - -
testBuildSbPreviewSize 0 B 0 B 0 B - -
testBuildStaticSize 0 B 0 B 0 B - -
testBuildPrebuildSize 0 B 0 B 0 B - -
testBuildPreviewSize 0 B 0 B 0 B - -
name before after diff z %
createTime 7.2s 7.1s -63ms -0.93 -0.9%
generateTime 21.1s 20.6s -458ms -0.18 -2.2%
initTime 14.6s 14.8s 142ms -0.16 1%
buildTime 11.5s 10.6s -870ms 1.43 🔰-8.2%
testBuildTime 0ms 0ms 0ms - -
devPreviewResponsive 5.5s 5.5s -13ms 0.2 -0.2%
devManagerResponsive 4.1s 3.7s -312ms -0.29 -8.2%
devManagerHeaderVisible 755ms 580ms -175ms -0.51 -30.2%
devManagerIndexVisible 799ms 608ms -191ms -0.48 -31.4%
devStoryVisibleUncached 2s 1.3s -716ms -1.26 🔰-51.8%
devStoryVisible 800ms 609ms -191ms -0.54 -31.4%
devAutodocsVisible 711ms 469ms -242ms -0.74 -51.6%
devMDXVisible 577ms 494ms -83ms -0.62 -16.8%
buildManagerHeaderVisible 595ms 511ms -84ms -0.86 -16.4%
buildManagerIndexVisible 682ms 602ms -80ms -0.85 -13.3%
buildStoryVisible 575ms 503ms -72ms -0.87 -14.3%
buildAutodocsVisible 562ms 409ms -153ms -0.84 -37.4%
buildMDXVisible 545ms 409ms -136ms -1.08 -33.3%

Greptile Summary

This pull request introduces dynamic theming based on user preferences and exports a utility function for broader use.

  • Updated code/core/src/manager/globals/exports.ts: Added getPreferredColorScheme to global exports.
  • Modified code/core/src/theming/create.ts: Introduced dynamic setting of themes.normal based on user preference.
  • Updated code/core/src/theming/index.ts: Exported getPreferredColorScheme utility function.
  • Enhanced code/core/src/theming/tests/create.test.js: Added tests to verify themes.normal respects user preferences.

Summary by CodeRabbit

  • New Features
    • Automatically selects the default theme (light or dark) based on your system/browser preference.
    • Theming APIs now include a way to read the preferred color scheme, enabling richer customizations.
  • Tests
    • Added tests to verify the default theme follows the user’s preferred color scheme (light vs. dark).

Copy link
Copy Markdown
Contributor

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

4 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

@valentinpalkovic valentinpalkovic added theming addon: docs bug ci:normal Run our default set of CI jobs (choose this for most PRs). labels Jul 29, 2024
@nx-cloud
Copy link
Copy Markdown

nx-cloud Bot commented Jul 29, 2024

View your CI Pipeline Execution ↗ for commit 99d61a0

Command Status Duration Result
nx run-many -t build --parallel=3 ✅ Succeeded 56s View ↗

☁️ Nx Cloud last updated this comment at 2025-11-03 10:06:36 UTC

Copy link
Copy Markdown
Member

@ndelangen ndelangen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cdedreuille are you ok with this?

@thomasaull
Copy link
Copy Markdown

thomasaull commented Oct 21, 2024

I just found this, when I was setting a brandImage like this:

import { addons } from '@storybook/manager-api'
import { themes } from '@storybook/theming'

addons.setConfig({
  theme: {
    ...themes.normal,
    brandImage: 'path/to/my/logo.svg',
  },
})

and the dark mode following the system preferences would not work anymore.

The development of the MR seems to be finished but it was not merged yet, is there anything which needs to be done still?

@ndelangen Looks like @cdedreuille didn’t find the time to review this, is there anyone else who could bring this forward?

@MichaelArestad
Copy link
Copy Markdown
Contributor

I'm not entirely certain what side effects might occur here, but overall I think this is a good idea. I do need another engineer on the team to take a look at it. @Sidnioulz Are you checking this out? I am also curious about the bug reported by @thomasaull

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 13, 2025

📝 Walkthrough

Walkthrough

Adds getPreferredColorScheme to global and theming exports. Updates theme creation to compute themes.normal from the preferred color scheme. Introduces internal Themes and themesBase types/constants. Extends tests to mock preference and verify normal resolves to light or dark accordingly.

Changes

Cohort / File(s) Summary of changes
Theming creation logic
code/core/src/theming/create.ts
Introduced Themes interface, themesBase, and preferredColorScheme. Rebuilt themes as { ...themesBase, normal: themesBase[preferredColorScheme] } instead of hard-coding normal.
Theming public exports
code/core/src/theming/index.ts
Re-exported getPreferredColorScheme from ./utils alongside lighten and darken.
Global export surfaces
code/core/src/manager/globals/exports.ts
Added getPreferredColorScheme to export lists for storybook/internal/theming, @storybook/theming, and @storybook/core/theming.
Tests for theme selection
code/core/src/theming/tests/create.test.js
Mocked getPreferredColorScheme and added tests verifying themes.normal equals light or dark based on mocked preference, using module reset and dynamic import.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Consumer
  participant Theming as theming/create
  participant Utils as theming/utils

  App->>Theming: import { themes }
  activate Theming
  Theming->>Utils: getPreferredColorScheme()
  activate Utils
  Utils-->>Theming: "light" | "dark"
  deactivate Utils
  Theming->>Theming: build themesBase {light, dark}
  Theming->>Theming: set normal = themesBase[preferred]
  Theming-->>App: export themes {light, dark, normal}
  deactivate Theming
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
code/core/src/theming/tests/create.test.js (1)

6-8: Align mock setup with coding guidelines.

The mock should include the spy: true option and avoid inline implementations.

As per coding guidelines:

  • "Use vi.mock() with the spy: true option for all package and file mocks"
  • "Mock implementations should be placed in beforeEach blocks"

Apply this diff:

-vi.mock('./../utils', () => ({
-  getPreferredColorScheme: vi.fn().mockReturnValue('light'),
-}));
+vi.mock('./../utils', { spy: true });

Then add a beforeEach block in the 'themes' describe block to set the default behavior:

 describe('themes', () => {
   beforeEach(() => {
     vi.resetModules();
+    vi.mocked(getPreferredColorScheme).mockReturnValue('light');
   });
code/core/src/theming/create.ts (1)

18-18: Confirm SSR fallback and consider reactive updates
getPreferredColorScheme falls back to 'light' when window.matchMedia is unavailable (e.g. SSR), so server safety is covered. Since it’s evaluated once at module load, system preference changes at runtime won’t update themes.normal—consider re-evaluating on mount or subscribing to prefers-color-scheme change events for dynamic updates.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f371ba and c83e97b.

📒 Files selected for processing (4)
  • code/core/src/manager/globals/exports.ts (3 hunks)
  • code/core/src/theming/create.ts (1 hunks)
  • code/core/src/theming/index.ts (1 hunks)
  • code/core/src/theming/tests/create.test.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier formatting on changed files before committing
Run ESLint on changed files and fix all errors/warnings before committing (use yarn lint:js:cmd <file>)

Files:

  • code/core/src/manager/globals/exports.ts
  • code/core/src/theming/create.ts
  • code/core/src/theming/tests/create.test.js
  • code/core/src/theming/index.ts
**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Export functions from modules when they need to be unit-tested

Files:

  • code/core/src/manager/globals/exports.ts
  • code/core/src/theming/create.ts
  • code/core/src/theming/tests/create.test.js
  • code/core/src/theming/index.ts
code/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

In application code, use Storybook loggers instead of console.* (client code: storybook/internal/client-logger; server code: storybook/internal/node-logger)

Files:

  • code/core/src/manager/globals/exports.ts
  • code/core/src/theming/create.ts
  • code/core/src/theming/tests/create.test.js
  • code/core/src/theming/index.ts
{code/**,scripts/**}/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not use console.log, console.warn, or console.error directly unless in isolated files where importing loggers would significantly increase bundle size

Files:

  • code/core/src/manager/globals/exports.ts
  • code/core/src/theming/create.ts
  • code/core/src/theming/tests/create.test.js
  • code/core/src/theming/index.ts
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/spy-mocking.mdc)

**/*.test.{ts,tsx,js,jsx}: Use vi.mock() with the spy: true option for all package and file mocks in Vitest tests
Place all mocks at the top of the test file before any test cases
Use vi.mocked() to type and access mocked functions
Implement mock behaviors in beforeEach blocks
Mock all required dependencies that the test subject uses
Mock implementations should be placed in beforeEach blocks
Each mock implementation should return a Promise for async functions
Mock implementations should match the expected return type of the original function
Use vi.mocked() to access and implement mock behaviors
Mock all required properties and methods that the test subject uses
Avoid direct function mocking without vi.mocked()
Avoid mock implementations outside of beforeEach blocks
Avoid mocking without the spy: true option
Avoid inline mock implementations within test cases
Avoid mocking only a subset of required dependencies
Mock at the highest level of abstraction needed
Keep mock implementations simple and focused
Use type-safe mocking with vi.mocked()
Document complex mock behaviors
Group related mocks together

Files:

  • code/core/src/theming/tests/create.test.js
**/*.@(test|spec).{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.@(test|spec).{ts,tsx,js,jsx}: Unit tests should import and execute the functions under test rather than only asserting on syntax patterns
Mock external dependencies in tests using vi.mock() (e.g., filesystem, loggers)

Files:

  • code/core/src/theming/tests/create.test.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: normal
  • GitHub Check: Core Unit Tests, windows-latest
🔇 Additional comments (5)
code/core/src/theming/index.ts (1)

43-43: LGTM! Clean addition to the public API.

The export of getPreferredColorScheme aligns with the PR objective to enable custom themes that can detect and respond to user color-scheme preferences.

code/core/src/theming/tests/create.test.js (1)

151-171: LGTM! Tests correctly verify theme resolution.

The test suite effectively validates that themes.normal resolves to either themes.light or themes.dark based on the user's color-scheme preference. The use of dynamic imports with vi.resetModules() ensures each test observes the theme initialization with the mocked preference.

code/core/src/manager/globals/exports.ts (1)

678-678: LGTM! Consistent addition to public theming APIs.

Adding getPreferredColorScheme to all three theming export surfaces (storybook/internal/theming, @storybook/theming, @storybook/core/theming) ensures consistent API availability across different import paths.

Also applies to: 705-705, 732-732

code/core/src/theming/create.ts (2)

7-23: Clean refactoring of theme initialization logic.

The introduction of the Themes interface and themesBase constant improves code organization and makes the dynamic resolution of themes.normal explicit and testable. The approach correctly implements the PR objective of making themes.normal follow the user's system color-scheme preference.


20-23: Resolved — preferredColorScheme is always 'light' | 'dark'; indexing is safe.
getPreferredColorScheme (code/core/src/theming/utils.ts) returns 'light' or 'dark' on all paths (fallback 'light'), so themesBase[preferredColorScheme] cannot be undefined.

@Sidnioulz Sidnioulz changed the base branch from next-8.5 to next October 13, 2025 17:21
Copy link
Copy Markdown
Contributor

@Sidnioulz Sidnioulz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still works well after rebasing. We're missing a mention of the normal theme in documentation and green CI.

Comment thread docs/configure/user-interface/theming.mdx Outdated
@Sidnioulz
Copy link
Copy Markdown
Contributor

I'm not entirely certain what side effects might occur here, but overall I think this is a good idea. I do need another engineer on the team to take a look at it. @Sidnioulz Are you checking this out? I am also curious about the bug reported by @thomasaull

I could not repro Thomas's report. Let's let him make a proper bug report if he is able to reproduce his issue consistently on next, as this branch was very old and not representative of the state of the codebase.

The change made is good as far as I'm concerned. I've added the missing doc, now we just need green CI.

@thomasaull
Copy link
Copy Markdown

I could not repro Thomas's report. Let's let him make a proper bug report if he is able to reproduce his issue consistently on next, as this branch was very old and not representative of the state of the codebase.

@Sidnioulz Sorry for the misunderstanding, that was not really a bug report but rather an example of what I was trying to achieve but which would not work because the feature implemented in this PR is not yet in the main branch.

As a workaround I'm currently using this until this PR gets merged:

import { create as createTheme, themes } from 'storybook/theming'
import logoLight from '../src/assets/images/logo_light.svg?url'
import logoDark from '../src/assets/images/logo_dark.svg?url'

const themeDark = createTheme({
  ...themes.dark,
  brandImage: logoDark,
})

const themeLight = createTheme({
  ...themes.light,
  brandImage: logoLight,
})

/**
 * Copy-Pasted and adapted from
 * @see https://github.com/storybookjs/storybook/blob/next/code/core/src/theming/utils.ts
 */
function getPreferredColorScheme() {
  if (!window || !window.matchMedia) return 'light'
  const isDarkThemePreferred = window.matchMedia('(prefers-color-scheme: dark)').matches
  if (isDarkThemePreferred) return 'dark'
  return 'light'
}

addons.setConfig({
  theme: getPreferredColorScheme() === 'dark' ? themeDark : themeLight,
})

Copy link
Copy Markdown
Contributor

@jonniebigodes jonniebigodes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@elisezhg, thank you for putting this pull request together and helping with the documentation. Appreciate it 🙏 !

Left a small item documentation-wise to be looked into when possible.

cc @Sidnioulz

Hope both of you have a fantastic weekend

Stay safe

Comment thread docs/configure/user-interface/theming.mdx Outdated
Co-authored-by: jonniebigodes <joaocontadesenvolvimento@gmail.com>
@Sidnioulz Sidnioulz changed the base branch from next to 10.1-with-canary-release October 27, 2025 12:13
@Sidnioulz Sidnioulz changed the base branch from 10.1-with-canary-release to next November 3, 2025 09:47
@yannbf yannbf merged commit 034ba4d into storybookjs:next Nov 3, 2025
53 of 54 checks passed
@github-actions github-actions Bot mentioned this pull request Nov 4, 2025
8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

addon: docs bug ci:normal Run our default set of CI jobs (choose this for most PRs). theming

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: themes.normal not working for docs pages

9 participants