Behaviors
Theme
The theme contract as code. It keeps each site’s existing storage key.
Usage#
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.
import { themeInitScript } from '@originlabsbr/halora/theme';
const snippet = themeInitScript({ storageKey: 'originlabs-theme' });
// <script>${snippet}</script>API#
| Name | Signature | Description |
|---|---|---|
resolveTheme | ({ stored, prefersDark }) => "light" | "dark" | Pure rule: a valid stored value wins, then the OS preference, then light. |
initTheme | (options?) => ThemeController | Wire toggles, storage, OS changes. Calling it again replaces the previous controller. |
themeInitScript | ({ storageKey? }) => string | The head snippet. Escapes the key. Never throws. |
themeLabel | (theme, labels?) => string | The action label for a toggle. |
getTheme | (root?) => Theme | Read data-theme. |
readStoredTheme | (key?, storage?) => Theme | null | Read and validate the stored value. |
systemPrefersDark | () => boolean | The media query. |
Options#
| Option | Default | Description |
|---|---|---|
storageKey | "theme" | localStorage key. |
toggleSelector | "[data-ha-theme-toggle]" | Which buttons toggle. |
labels | English | { toLight, toDark }. |
root | document.documentElement | Element that gets data-theme. |
storage | localStorage | Any getItem/setItem object. |
onChange | none | Called with the new theme. |