Skip to content
Halorav0.1.0

Behaviors

Theme

The theme contract as code. It keeps each site’s existing storage key.

Usage#

JavaScript
import { initTheme } from '@originlabsbr/halora/theme';

const theme = initTheme({
  storageKey: 'gabarito-theme',
  labels: { toLight: 'Mudar para o tema claro', toDark: 'Mudar para o tema escuro' },
});

theme.toggle();      // switch and store
theme.set('dark');   // set and store
theme.theme;         // "dark"
theme.destroy();

initTheme reads the attribute the pre-paint snippet already set, or resolves it if it is missing. It wires every [data-ha-theme-toggle] by delegation, so buttons rendered later work too. It follows OS changes while the visitor has not chosen, and follows other tabs through the storage event.

Pre-paint snippet#

Put this in the head so the theme is set before first paint. Generate it for any storage key, or use the file @originlabsbr/halora/theme-init for the default key.

JavaScript
import { themeInitScript } from '@originlabsbr/halora/theme';

const snippet = themeInitScript({ storageKey: 'originlabs-theme' });
// <script>${snippet}</script>

API#

NameSignatureDescription
resolveTheme({ stored, prefersDark }) => "light" | "dark"Pure rule: a valid stored value wins, then the OS preference, then light.
initTheme(options?) => ThemeControllerWire toggles, storage, OS changes. Calling it again replaces the previous controller.
themeInitScript({ storageKey? }) => stringThe head snippet. Escapes the key. Never throws.
themeLabel(theme, labels?) => stringThe action label for a toggle.
getTheme(root?) => ThemeRead data-theme.
readStoredTheme(key?, storage?) => Theme | nullRead and validate the stored value.
systemPrefersDark() => booleanThe media query.

Options#

OptionDefaultDescription
storageKey"theme"localStorage key.
toggleSelector"[data-ha-theme-toggle]"Which buttons toggle.
labelsEnglish{ toLight, toDark }.
rootdocument.documentElementElement that gets data-theme.
storagelocalStorageAny getItem/setItem object.
onChangenoneCalled with the new theme.

Edit this page on GitHub

Type to search.