dark-reader-aware-theme-toggle-button
Version:
Dark mode toggle button that detects the Dark Reader extension and steps aside
58 lines (53 loc) • 2.69 kB
text/typescript
/**
* Returns true when the Dark Reader browser extension is actively modifying
* the page. Checks all known signals across dynamic, filter, and static modes.
*/
declare function isDarkReaderActive(doc?: Document): boolean;
/**
* Watch for Dark Reader being enabled or disabled. Calls `onChange` immediately
* and whenever DR signals appear or disappear. Returns an unsubscribe function.
*/
declare function watchDarkReader(onChange: (active: boolean) => void, doc?: Document): () => void;
type Theme = 'light' | 'dark';
interface ThemeOptions {
/** localStorage key. Default: `theme` */
storageKey?: string;
/** Attribute on `<html>`. Default: `data-theme` */
attribute?: string;
/** Attribute value for dark mode. Default: `dark` */
darkValue?: string;
/** Use prefers-color-scheme when no saved preference exists. Default: false */
respectSystemPreference?: boolean;
}
/** Read saved theme, optionally falling back to system preference. */
declare function getTheme(options?: ThemeOptions, doc?: Document): Theme;
/** Apply theme to `<html>` and persist to localStorage. */
declare function setTheme(theme: Theme, options?: ThemeOptions, doc?: Document): void;
/** Read current theme from the DOM attribute (not localStorage). */
declare function getCurrentTheme(options?: ThemeOptions, doc?: Document): Theme;
/** Toggle theme; returns the new value. */
declare function toggleTheme(options?: ThemeOptions, doc?: Document): Theme;
/** Apply saved theme before first paint to avoid flash. Call from an inline `<head>` script. */
declare function initThemeEarly(options?: ThemeOptions, doc?: Document): Theme;
interface MountOptions extends ThemeOptions {
/** Button element or CSS selector */
button: string | HTMLElement;
/** Label element or CSS selector (optional; falls back to button textContent) */
label?: string | HTMLElement;
/** Button label text in each theme state */
labels?: {
light: string;
dark: string;
};
/** Hide the button while Dark Reader is active. Default: true */
hideWhenDarkReaderActive?: boolean;
/** Called after initial mount and on each toggle */
onThemeChange?: (theme: Theme) => void;
}
/**
* Wire a button to toggle `data-theme` on `<html>`, persist preference, update
* label text, and hide the button when Dark Reader is active.
* Returns an unmount function.
*/
declare function mountThemeToggleButton(options: MountOptions, doc?: Document): () => void;
export { type MountOptions, type Theme, type ThemeOptions, getCurrentTheme, getTheme, initThemeEarly, isDarkReaderActive, mountThemeToggleButton, setTheme, toggleTheme, watchDarkReader };