To make managing the active theme easier, we provide a helper class to get, set and toggle the theme. Additionally,
you can provide callbacks for when the theme gets changed!
@param ― resolveSystemTheme Whether to resolve the `system` theme to the actual theme (`dark` or `light`)
@returns ― The current theme.
getTheme(true);
11
12
// Set the theme to light
13
constthemeHelper: ThemeHelper
themeHelper.
ThemeHelper.setTheme: (theme: Theme) =>void
Sets the current theme.
@param ― theme The new theme. One of `dark`, `light` or `system`.
setTheme('light');
14
15
// Toggle the theme
16
constthemeHelper: ThemeHelper
themeHelper.
ThemeHelper.toggleTheme: () =>void
Toggles the current theme.
If the theme is set to `system` (or no theme is set via the root element),
the theme is set depending on the user's color scheme preference (set in the browser).
toggleTheme();
17
18
// Register an element that should act as a toggle
Using the ThemeHelper class, you can listen to theme changes! This is useful when you have logic that needs to run
whenever the color scheme changes, for example in a three.js canvas where you need to change an image
(*cough cough* our login page *cough*).
script.ts
1
import{
classThemeHelper
A helper to toggle, set and get the current StudioCMS UI theme.
Allows for adding a callback that gets called whenever the theme changes.
@param ― callback The callback to be executed
onThemeChange((
newTheme: Theme
newTheme)=>{
8
// Your logic here!
9
});
Here’s a live example: Change the theme via the option in the top-right corner of your screen. If you’re on mobile,
open the navbar and scroll all the way down. After you’ve changed the theme, check the text below:
One of the few things the ThemeHelper does not do is saving the users theme preference. This is by design, since we don’t want to force websites operating in the EU (and other GDPR-enforcing countries) to have to add a cookie notice just for a UI library. Instead, implementation of this functionality is up to the developers themselves.
As a starting point, here’s a barebones example of how to implement this:
Script Tag
1
import{
classThemeHelper
A helper to toggle, set and get the current StudioCMS UI theme.
Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
Dispatches a storage event on Window objects holding an equivalent Storage object.