API
Everything @k8ordo/color-scheme exports: the components, the hook, values and types.
On this page
ColorSchemeScript
Import from @k8ordo/color-scheme
The inline script that puts dark on <html> before the first paint, and writes the theme-color <meta> when given themeColor. It goes in the root layout’s <head>.
ColorSchemeScript(props: ColorSchemeScriptProps): ReactNodeParameters
defaultPreferenceColorSchemePreference = 'system'- What applies to a visitor who has chosen nothing, at the first paint. Pass the same value as the provider’s
defaultPreference. themeColor{ light: string; dark: string } | undefined- The light and dark colors for the browser’s own UI, such as the address bar. Given them, the script writes
theme-color<meta>that match the scheme on screen. Render notheme-color<meta>of your own. noncestring | undefined- The nonce to put on the script. In
@k8ordo/framework’s server mode, passnonce(). Leave it out when the script is allowed by hash.
Caveats
- It is exported from a
'use client'module, so a root layout that is a Server Component can render it directly. The script's text is written into the HTML only, never into the payload. - It has to come before every stylesheet.
@k8ordo/frameworkmoves the inline scripts written in<head>ahead of the stylesheets.
layout.tsxexport default function RootLayout({
children,
}: {
children: ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<ColorSchemeScript />
</head>
<body>
<ColorSchemeProvider>{children}</ColorSchemeProvider>
</body>
</html>
);
}ColorSchemeProvider
Import from @k8ordo/color-scheme
The provider that wraps the whole page. It goes in the root layout, inside <body>. After hydration it updates dark on <html> whenever the stored choice or the OS setting changes, and the theme-color <meta> the script wrote along with it.
ColorSchemeProvider(props: ColorSchemeProviderProps): ReactNodeParameters
defaultPreferenceColorSchemePreference = 'system'- What applies to a visitor who has chosen nothing.
'system'follows the OS setting.'light'or'dark'keeps every visitor on that scheme until they choose. GiveColorSchemeScriptthe same value. childrenReactNode- The whole page.
Caveats
- It is exported from a
'use client'module, so a root layout that is a Server Component can render it directly. - Put
suppressHydrationWarningon<html>. Theclassthe script adds is not in the server HTML, and React reports it as a mismatch in development. - Put exactly one in the application. With two, each writes the class, and they can disagree.
layout.tsxexport default function RootLayout({
children,
}: {
children: ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<ColorSchemeScript />
</head>
<body>
<ColorSchemeProvider>{children}</ColorSchemeProvider>
</body>
</html>
);
}useColorScheme
Import from @k8ordo/color-scheme
Returns the scheme on screen, the visitor’s choice, and a function that changes it. Use it in a Client Component.
useColorScheme(): UseColorSchemeReturns
UseColorScheme — An object holding scheme, preference and setPreference.
Fields
scheme'light' | 'dark'- What is on screen. It is decided by the visitor’s choice, then the provider’s default, then the OS setting.
preference'light' | 'dark' | 'system'- What the visitor chose.
'system'while nothing is chosen. setPreference(preference: ColorSchemePreference) => void- Stores a choice.
'system'clears the stored choice, so the provider’s default applies again.
Caveats
- Called outside the provider, it throws an error starting with
useColorScheme needs <ColorSchemeProvider> above it. It does not return the default. - It only reads what the provider decided. It never changes the class on
<html>or localStorage. - In the server render and the hydration render it returns the value decided from the default, which is
'light'for a'system'default. The stored choice and the OS setting are reflected from the render after that.
scheme-toggle.tsxconst { scheme, setPreference } = useColorScheme();
<button
onClick={() => {
setPreference(scheme === 'dark' ? 'light' : 'dark');
}}
type="button"
>
Toggle
</button>A toggle and a three-way choice are built in the Switch guide.
colorSchemeState
Import from @k8ordo/color-scheme
The @k8ordo/state defineLocalState definition that says where the preference is stored. It is saved in localStorage under k8ordo-state:color-scheme, as an object with one field, preference.
const colorSchemeState = defineLocalState(
'color-scheme',
z.object({ preference: z.optional(z.enum(['light', 'dark'])) }),
);Fields
kind'local'- The kind of place the state is stored in.
'local', for localStorage. key'color-scheme'- Its name within
@k8ordo/state. There is one store per name. schemaZodMiniObject- The schema the definition was given.
storageKey'k8ordo-state:color-scheme'- The localStorage key:
k8ordo-state:followed bykey. inlineRead() => string- Returns a JavaScript expression for an inline script. It evaluates to the stored object, or to
nullwhen the value cannot be read.
Caveats
useAppState(colorSchemeState)reads the storedpreferencewithout the hook. Its value is'light' | 'dark' | undefined, not the resolvedscheme.- Change the choice through
setPreference. A directlocalStorage.setItemin the same tab is not reflected until a reload. - Do not define another
defineLocalState('color-scheme', …). Stores are shared by name, so both definitions would read and write the same stored value.
stored-preference.tsxconst [{ preference }] = useAppState(colorSchemeState);
// 'light' | 'dark' | undefinedcolorSchemeScriptHash
Import from @k8ordo/color-scheme
Resolves to the SHA-256 of ColorSchemeScript’s inline script as a CSP source, 'sha256-…'. Put it in a policy that allows the script without a nonce.
colorSchemeScriptHash(
options?: ColorSchemeScriptOptions,
): Promise<string>Parameters
options.defaultPreferenceColorSchemePreference = 'system'- The
defaultPreferenceColorSchemeScriptis given. The default is written into the script, so the hash depends on it. options.themeColor{ light: string; dark: string } | undefined- The
themeColorColorSchemeScriptis given. The colors are written into the script too, so the hash depends on them. The order of the keys does not.
Returns
Promise<string> — A CSP source such as 'sha256-…', quotes included.
Caveats
- Call it where the policy is written, every time, instead of copying its value. The script text belongs to the installed version, and an update may change it.
- Where every response can carry a nonce, the hash is not needed.
vite.config.tsframework({
mode: 'static',
csp: {
'script-src': ["'self'", await colorSchemeScriptHash()],
},
});Building the policy is covered in the CSP guide.
ColorScheme
Import from @k8ordo/color-scheme
A scheme that can be on screen. The type of scheme.
type ColorScheme = 'light' | 'dark';ColorSchemePreference
Import from @k8ordo/color-scheme
A scheme, or 'system'. As a visitor’s choice, 'system' means nothing chosen, so the provider’s default applies. As that default, it follows the OS setting.
type ColorSchemePreference = ColorScheme | 'system';ColorSchemeProviderProps
Import from @k8ordo/color-scheme
The props of ColorSchemeProvider. Use it for a component of your own that wraps the provider.
type ColorSchemeProviderProps = {
readonly defaultPreference?: ColorSchemePreference;
readonly children: ReactNode;
};ColorSchemeScriptOptions
Import from @k8ordo/color-scheme
The props of ColorSchemeScript that are written into the script. The type of colorSchemeScriptHash()’s argument.
type ColorSchemeScriptOptions = {
readonly defaultPreference?: ColorSchemePreference;
readonly themeColor?: {
readonly light: string;
readonly dark: string;
};
};ColorSchemeScriptProps
Import from @k8ordo/color-scheme
The props of ColorSchemeScript. Use it for a component of your own that wraps the script.
type ColorSchemeScriptProps = ColorSchemeScriptOptions & {
readonly nonce?: string;
};UseColorScheme
Import from @k8ordo/color-scheme
What useColorScheme() returns. Use it for a component that receives the hook’s value as props.
type UseColorScheme = {
readonly scheme: ColorScheme;
readonly preference: ColorSchemePreference;
readonly setPreference: (preference: ColorSchemePreference) => void;
};