JavaScript API

API

css.createTheme

Themes such as light and dark, switched by a class, an attribute or a media query.

type CreateTheme = {
  [key: string]: {
    default: string;
    theme: string;
  };
};

export type createTheme = <const T extends CreateTheme>(themeSelector: CreateThemeSelector, rule: T) => CreateThemeReturnType<T>;
export const createTheme: createTheme;

createTheme defines scoped CSS variables for custom themes.
Since a unique hash is automatically prepended to the generated variable names, there is zero risk of name collisions with other themes or global CSS variables.

References between Plumeria themes are not supported: default and theme accept strings, not another theme member, and generated CSS variable names are content hashes that can change when the theme changes.

Example

Toggle the theme by adding a class to the root element.

TypeScript
import * as css from '@plumeria/core';

export const theme = css.createTheme('.dark', {
  text: {
    default: '#333',
    theme: '#eaeaea',
  },
});
CSS
:where(:root) {
  --xvgqnxo9-text: #333;
}

.dark {
  --xvgqnxo9-text: #eaeaea;
}

Usage

import * as css from '@plumeria/core';
import { theme } from 'lib/theme';

const styles = css.create({
  title: {
    color: theme.text,
  },
});

Selectors

The first argument also takes attribute selectors and nesting-capable conditional at-rules such as @media, @container and @supports.

Attribute

For attribute-based setups such as next-themes.

TypeScript
import * as css from '@plumeria/core';

export const theme = css.createTheme('[data-theme="dark"]', {
  text: {
    default: '#333',
    theme: '#eaeaea',
  },
});
CSS
:where(:root) {
  --xipw25nr-text: #333;
}

[data-theme="dark"] {
  --xipw25nr-text: #eaeaea;
}

Media query

Follows the system setting without any JavaScript.

TypeScript
import * as css from '@plumeria/core';

export const theme = css.createTheme('@media (prefers-color-scheme: dark)', {
  text: {
    default: '#333',
    theme: '#eaeaea',
  },
});
CSS
:where(:root) {
  --xnof3ra0-text: #333;
}

@media (prefers-color-scheme: dark) {
  :where(:root) {
    --xnof3ra0-text: #eaeaea;
  }
}

Good to know

All APIs, including createTheme, are not compiled until the theme variable is actually used in a styling block.

Edit on GitHub

On this page