Theme Toggle for Astro
Controls for switching between light and dark color modes within a Astro website.
Installation
bunx --bun shadcn@latest add @gnostic/theme-togglenpx shadcn@latest add @gnostic/theme-togglepnpm dlx shadcn@latest add @gnostic/theme-toggleComplete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/coreCopy the files
src/components/ui/theme-toggle/index.ts
export { default as ThemeToggle } from './theme-toggle.astro'
export { default as ThemeProvider } from './theme-provider.astro'
export { create, createThemeToggle, setTheme } from './theme-toggle.ts'
export type { ThemeToggleController } from './theme-toggle.ts'
export type {
Theme,
ThemeProviderProps,
ThemeToggleProps,
ThemeEffect,
ThemeEffectStart,
ThemeEffectVariant,
ThemeChangeDetail,
ThemeApplyDetail,
} from './types.ts'
src/components/ui/theme-toggle/theme-provider.astro
---
import type { Theme, ThemeProviderProps } from "./types.ts"
type Props = ThemeProviderProps
const {
storageKey = "theme",
defaultTheme: defaultThemeProp = "system",
storage = "localStorage",
attributeType = "both",
effect,
} = Astro.props
let defaultTheme = defaultThemeProp
// For SSR only - if page isnt prerendered we can access the cookie from the request
if (storage === "cookie" && !Astro.isPrerendered) {
const themeCookie = Astro.cookies.get(storageKey)?.value
if (themeCookie && ["light", "dark"].includes(themeCookie)) {
defaultTheme = themeCookie as Theme
}
}
---
<script
is:inline
data-astro-rerun
define:vars={{
storageKey,
defaultTheme,
storageType: storage,
attributeType,
effect,
}}
>
document.dispatchEvent(new Event("theme:provider-dispose"))
const media = window.matchMedia("(prefers-color-scheme: dark)")
const valid = (value) => ["light", "dark", "system"].includes(value)
const read = () => {
try {
if (storageType === "cookie") {
const name = `${encodeURIComponent(storageKey)}=`
const match = document.cookie
.split("; ")
.find((part) => part.startsWith(name))
return match ? decodeURIComponent(match.slice(name.length)) : null
}
return window[storageType].getItem(storageKey)
} catch {
return null
}
}
const save = (theme) => {
try {
if (storageType === "cookie") {
document.cookie = `${encodeURIComponent(storageKey)}=${encodeURIComponent(theme)}; path=/; samesite=lax`
} else {
window[storageType].setItem(storageKey, theme)
}
} catch {}
}
const saved = read()
let preference = valid(saved) ? saved : defaultTheme
const current = (event) => {
event.detail.effect = effect
if (attributeType === "none") {
event.detail.theme =
preference === "system"
? media.matches
? "dark"
: "light"
: preference
} else if (attributeType === "class") {
event.detail.theme = document.documentElement.classList.contains("dark")
? "dark"
: "light"
} else {
event.detail.theme = document.documentElement.getAttribute("data-theme")
}
}
const apply = (theme, disableTransitions = false) => {
const resolved =
theme === "system" ? (media.matches ? "dark" : "light") : theme
let style
if (disableTransitions) {
style = document.createElement("style")
style.textContent =
"*, *::before, *::after { transition: none !important; }"
document.head.appendChild(style)
}
if (attributeType === "both" || attributeType === "attribute") {
document.documentElement.setAttribute("data-theme", resolved)
}
if (attributeType === "both" || attributeType === "class") {
document.documentElement.classList.toggle("dark", resolved === "dark")
}
if (style) {
void document.documentElement.offsetHeight
requestAnimationFrame(() => style.remove())
}
return resolved
}
const change = (event) => {
if (event.detail.resolvedTheme || !valid(event.detail.theme)) return
preference = event.detail.theme
event.detail.resolvedTheme = apply(
preference,
event.detail.disableTransitions ?? true,
)
save(preference)
}
const sync = () => {
const resolvedTheme = apply(preference)
document.dispatchEvent(
new CustomEvent("theme:change", {
detail: { theme: preference, resolvedTheme },
bubbles: true,
}),
)
}
const systemChange = () => {
if (preference === "system") sync()
}
const storageChange = (event) => {
if (storageType === "cookie") return
try {
if (
event.storageArea !== window[storageType] ||
(event.key !== storageKey && event.key !== null)
)
return
} catch {
return
}
preference = valid(event.newValue) ? event.newValue : defaultTheme
sync()
}
const cleanup = () => {
document.removeEventListener("theme:read", current)
document.removeEventListener("theme:apply", change)
document.removeEventListener("theme:provider-dispose", cleanup)
document.removeEventListener("astro:before-swap", cleanup)
media.removeEventListener("change", systemChange)
window.removeEventListener("storage", storageChange)
}
document.addEventListener("theme:read", current)
document.addEventListener("theme:apply", change)
document.addEventListener("theme:provider-dispose", cleanup, { once: true })
document.addEventListener("astro:before-swap", cleanup, { once: true })
media.addEventListener("change", systemChange)
window.addEventListener("storage", storageChange)
sync()
</script>
<style is:global>
/*
View transitions animate in CSS. Blast uses the Material standard
curve. Reveal uses ease-out.
*/
html[data-theme-vt="reveal"]::view-transition-old(root),
html[data-theme-vt="blast"]::view-transition-old(root) {
animation: none;
mix-blend-mode: normal;
}
html[data-theme-vt="reveal"]::view-transition-new(root) {
mix-blend-mode: normal;
animation: theme-effect-reveal 400ms ease-out;
}
html[data-theme-vt="blast"]::view-transition-new(root) {
mix-blend-mode: normal;
animation: theme-effect-blast 700ms cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes theme-effect-reveal {
from {
clip-path: var(--theme-effect-from, inset(100% 0 0 0));
filter: blur(var(--theme-effect-blur, 0px));
}
to {
clip-path: inset(0 0 0 0);
filter: blur(0px);
}
}
@keyframes theme-effect-blast {
from {
clip-path: circle(0% at var(--theme-effect-origin, 50% 100%));
filter: blur(var(--theme-effect-blur, 0px));
}
to {
clip-path: circle(150% at var(--theme-effect-origin, 50% 100%));
filter: blur(0px);
}
}
</style>
src/components/ui/theme-toggle/theme-toggle.astro
---
import type { ComponentProps } from "astro/types"
import Moon from "@lucide/astro/icons/moon"
import Sun from "@lucide/astro/icons/sun"
import { cn } from "cn"
import { Button } from "../button/index.ts"
import type { ThemeToggleProps } from "./types.ts"
type Props = ComponentProps<typeof Button> & ThemeToggleProps
const {
class: className,
variant = "ghost",
size = "icon-sm",
effect,
...props
} = Astro.props
---
<Button
data-theme-toggle
data-theme-effect={effect === undefined ? undefined : JSON.stringify(effect)}
aria-label="Toggle theme"
variant={variant}
size={size}
class={cn("relative", className)}
{...props}
>
<!-- One slot. Icon classes choose the light and dark marks. -->
<slot>
<Sun class="dark:hidden" />
<Moon class="hidden dark:block" />
</slot>
</Button>
<script>
import { create, type ThemeToggleController } from "./theme-toggle.ts"
const controllers: ThemeToggleController[] = []
const initialize = () => controllers.push(...create())
initialize()
document.addEventListener("astro:page-load", initialize)
document.addEventListener("astro:before-swap", () => {
for (const controller of controllers) controller.destroy()
controllers.length = 0
})
</script>
src/components/ui/theme-toggle/theme-toggle.ts
import {
clearRootBinding,
getRootBinding,
hasRootBinding,
setRootBinding,
} from '@data-slot/core'
import type {
Theme,
ThemeToggleProps,
ThemeEffect,
ThemeEffectStart,
ThemeChangeDetail,
ThemeApplyDetail,
} from './types.ts'
export type { ThemeChangeDetail, ThemeApplyDetail } from './types.ts'
const BINDING_KEY = '@gnostic/theme-toggle'
declare global {
interface DocumentEventMap {
'theme:read': CustomEvent<{
theme?: 'light' | 'dark'
effect?: ThemeEffect
}>
'theme:before-change': CustomEvent<ThemeChangeDetail>
'theme:apply': CustomEvent<ThemeApplyDetail>
'theme:change': CustomEvent<ThemeApplyDetail>
}
interface HTMLElementEventMap {
'theme:before-change': CustomEvent<ThemeChangeDetail>
}
}
export interface ThemeToggleController {
readonly root: HTMLButtonElement
readonly theme: 'light' | 'dark'
setTheme(theme: Theme, options?: ThemeToggleProps): void
toggle(): void
destroy(): void
}
function readTheme(doc: Document) {
const detail: DocumentEventMap['theme:read']['detail'] = {}
doc.dispatchEvent(new CustomEvent('theme:read', { detail }))
if (!detail.theme)
throw new Error(
'ThemeProvider is required before using ThemeToggle or setTheme().',
)
return { theme: detail.theme, effect: detail.effect }
}
/** Request a theme change. Listeners can cancel it or set detail.effect. */
export function setTheme(
theme: Theme,
options: Omit<ThemeChangeDetail, 'theme'> = {},
doc: Document = document,
): void {
const provider = readTheme(doc)
const effect = options.effect ?? provider.effect
const detail: ThemeApplyDetail = {
...options,
theme,
...(effect === undefined ? {} : { effect }),
}
const target = detail.source ?? doc
if (
!target.dispatchEvent(
new CustomEvent('theme:before-change', {
detail,
bubbles: true,
cancelable: true,
}),
)
)
return
runThemeEffect(doc, detail, () => {
doc.dispatchEvent(new CustomEvent('theme:apply', { detail }))
if (!detail.resolvedTheme) return
doc.dispatchEvent(
new CustomEvent('theme:change', { detail, bubbles: true }),
)
})
}
/** Bind one toggle. Repeated calls return the same controller. */
export function createThemeToggle(
root: HTMLButtonElement,
options: ThemeToggleProps = {},
): ThemeToggleController {
const existing = getRootBinding<ThemeToggleController>(root, BINDING_KEY)
if (existing) return existing
const doc = root.ownerDocument
let destroyed = false
let theme = readTheme(doc).theme
let effect = options.effect
if (effect === undefined && root.dataset.themeEffect) {
try {
effect = JSON.parse(root.dataset.themeEffect)
} catch {
/* Use the page default. */
}
}
const sync = (value = readTheme(doc).theme) => {
theme = value
const dark = theme === 'dark'
root.setAttribute('aria-pressed', String(dark))
root.setAttribute('data-state', dark ? 'on' : 'off')
root.toggleAttribute('data-pressed', dark)
}
const change = (event: DocumentEventMap['theme:change']) =>
sync(event.detail.resolvedTheme)
const observer = new MutationObserver(() => sync())
observer.observe(doc.documentElement, {
attributes: true,
attributeFilter: ['class', 'data-theme'],
})
doc.addEventListener('theme:change', change)
const controller: ThemeToggleController = {
root,
get theme() {
return theme
},
setTheme(value, overrides = {}) {
if (destroyed) return
setTheme(
value,
{
...(effect === undefined ? {} : { effect }),
...overrides,
source: root,
},
doc,
)
},
toggle() {
if (
destroyed ||
root.matches(':disabled') ||
root.getAttribute('aria-disabled') === 'true'
)
return
controller.setTheme(theme === 'dark' ? 'light' : 'dark')
},
destroy() {
if (destroyed) return
destroyed = true
root.removeEventListener('click', click)
doc.removeEventListener('theme:change', change)
observer.disconnect()
clearRootBinding(root, BINDING_KEY, controller)
},
}
const click = (event: Event) => {
if (!event.defaultPrevented) controller.toggle()
}
root.addEventListener('click', click)
sync()
return setRootBinding(root, BINDING_KEY, controller)
}
/** Bind each unbound toggle within a document or element. */
export function create(scope: ParentNode = document): ThemeToggleController[] {
const selector = 'button[data-theme-toggle]'
const roots = [...scope.querySelectorAll<HTMLButtonElement>(selector)]
if (scope instanceof Element && scope.matches(selector))
roots.unshift(scope as HTMLButtonElement)
return roots
.filter((root) => !hasRootBinding(root, BINDING_KEY))
.map((root) => createThemeToggle(root))
}
function revealEffect(
start: ThemeEffectStart,
rect: DOMRect | undefined,
view: Window,
) {
const positions: Record<Exclude<ThemeEffectStart, 'toggle'>, string> = {
'top-left': 'inset(0 100% 100% 0)',
'top-right': 'inset(0 0 100% 100%)',
'bottom-left': 'inset(100% 100% 0 0)',
'bottom-right': 'inset(100% 0 0 100%)',
center: 'inset(50% 50% 50% 50%)',
'bottom-up': 'inset(100% 0 0 0)',
}
return {
'--theme-effect-from': rect
? `inset(${(rect.top / view.innerHeight) * 100}% ${((view.innerWidth - rect.right) / view.innerWidth) * 100}% ${((view.innerHeight - rect.bottom) / view.innerHeight) * 100}% ${(rect.left / view.innerWidth) * 100}%)`
: positions[start === 'toggle' ? 'bottom-up' : start],
}
}
function blastEffect(start: ThemeEffectStart, rect: DOMRect | undefined) {
const positions: Record<Exclude<ThemeEffectStart, 'toggle'>, string> = {
'top-left': '0% 0%',
'top-right': '100% 0%',
'bottom-left': '0% 100%',
'bottom-right': '100% 100%',
center: '50% 50%',
'bottom-up': '50% 100%',
}
return {
'--theme-effect-origin': rect
? `${rect.left + rect.width / 2}px ${rect.top + rect.height / 2}px`
: positions[start === 'toggle' ? 'bottom-up' : start],
}
}
const effects = { reveal: revealEffect, blast: blastEffect }
const active = new WeakMap<Document, () => void>()
function runThemeEffect(
doc: Document,
detail: ThemeChangeDetail,
apply: () => void,
): void {
active.get(doc)?.()
const effect = detail.effect
const view = doc.defaultView
if (
!effect ||
!view ||
view.matchMedia('(prefers-reduced-motion: reduce)').matches ||
typeof doc.startViewTransition !== 'function'
) {
apply()
return
}
const root = doc.documentElement
const variant = effect.variant ?? 'reveal'
const start = effect.start ?? 'toggle'
const rect =
start === 'toggle' ? detail.source?.getBoundingClientRect() : undefined
const properties = {
'--theme-effect-blur': effect.blur ? '8px' : '0px',
...effects[variant](start, rect, view),
}
for (const [name, value] of Object.entries(properties))
root.style.setProperty(name, value)
root.dataset.themeVt = variant
let cancelled = false
let applied = false
let transition: ViewTransition | undefined
const update = () => {
if (cancelled || applied) return
applied = true
apply()
}
const cleanup = () => {
doc.removeEventListener('astro:before-swap', cancel)
doc.removeEventListener('theme:provider-dispose', cancel)
if (active.get(doc) !== cancel) return
active.delete(doc)
delete root.dataset.themeVt
for (const name of Object.keys(properties))
root.style.removeProperty(name)
}
const cancel = () => {
cancelled = true
transition?.skipTransition()
cleanup()
}
active.set(doc, cancel)
doc.addEventListener('astro:before-swap', cancel, { once: true })
doc.addEventListener('theme:provider-dispose', cancel, { once: true })
try {
transition = doc.startViewTransition(update)
void transition.ready.catch(() => {})
void transition.finished.then(cleanup, cleanup)
} catch {
cleanup()
update()
}
}
src/components/ui/theme-toggle/types.ts
export type Theme = 'light' | 'dark' | 'system'
/**
* Shape of the theme view transition.
*
* - `reveal` — a clip grows from the start point to the full viewport
* - `blast` — a circle grows outward from the start point
*/
export type ThemeEffectVariant = 'reveal' | 'blast'
/**
* Point where a reveal or blast theme transition begins.
*
* `toggle` uses the theme toggle that was activated.
*/
export type ThemeEffectStart =
| 'toggle'
| 'top-left'
| 'top-right'
| 'bottom-left'
| 'bottom-right'
| 'center'
| 'bottom-up'
/** Props for a light and dark theme control. */
export interface ThemeToggleProps {
/** Override the page effect for this control. Use false to skip it. */
effect?: ThemeEffect | false
}
/** View transition options shared by the provider and individual controls. */
export interface ThemeEffect {
/**
* Animation variant.
*
* @default "reveal"
*/
variant?: ThemeEffectVariant
/**
* Where a reveal or blast effect starts.
*
* @default "toggle" - the coordinate of the theme toggle that was activated
*/
start?: ThemeEffectStart
/**
* Blur the new theme as the effect opens.
*
* @default false
*/
blur?: boolean
}
export type ThemeProviderProps = {
/**
* Default effect for requested theme changes. Omit to change mode without animation.
*
* @default undefined
*/
effect?: ThemeEffect
/**
* The key used in the selected storage.
*
* @default "theme"
*/
storageKey?: string
/**
* The theme to use when no saved preference is found.
*
* @default "system"
*/
defaultTheme?: Theme
/**
* The storage to use for storing the theme preference.
*
* - `localStorage` - stored in the user's browser until cleared manually
* - `sessionStorage` - stored in the user's browser until the session ends (tab closed)
* - `cookie` - stored in a session cookie
*
* @default "localStorage"
*/
storage?: 'localStorage' | 'sessionStorage' | 'cookie'
/**
* The attribute type to use to set the theme
*
* - `attribute` - set the `data-theme` attribute on the root element
* - `class` - set a `dark` class on the root element when dark mode is enabled
* - `both` - set both `data-theme` and `dark` class on root element
* - `none` - emit theme events without changing root attributes
*
* @default "both"
*/
attributeType?: 'attribute' | 'class' | 'both' | 'none'
}
export interface ThemeChangeDetail extends ThemeToggleProps {
theme: Theme
source?: HTMLElement
disableTransitions?: boolean
}
export interface ThemeApplyDetail extends ThemeChangeDetail {
/** Set by the provider after it applies the requested theme. */
resolvedTheme?: 'light' | 'dark'
}
Setup
The theme toggle requires one ThemeProvider in your document’s <head>. The provider applies the initial mode before the page appears and saves theme preferences. The toggle and browser API report an error when no provider is present.
Add the provider to your layout’s head section:
---
import { ThemeProvider } from "@/components/ui/theme-toggle"
---
<html>
<head>
<ThemeProvider />
<!-- other head elements -->
</head>
<body>
<!-- your content -->
</body>
</html>
Render ThemeProvider before the visible page. Its inline script applies the initial theme early, using the approach documented in the shadcn Astro dark mode guide.
Usage
import { ThemeToggle } from "@/components/ui/theme-toggle"
<ThemeToggle />
Examples
Use Cookie storage
The ThemeProvider allows customizing the storage mechanism for the theme preference.
---
import { ThemeProvider } from "@/components/ui/theme-toggle"
---
<ThemeProvider
storage="cookie"
storageKey="color-mode"
defaultTheme="light"
attributeType="attribute"
/>
View transition
Set effect on the existing ThemeProvider to choose the default view transition. The prop defaults to undefined, so mode changes have no animation unless the provider or a toggle supplies an effect. The provider includes the transition styles; they apply only while data-theme-vt is set on the document root.
---
import { ThemeProvider, ThemeToggle } from "@/components/ui/theme-toggle"
---
<html>
<head>
<ThemeProvider effect={{ variant: "blast", start: "toggle" }} />
</head>
<body>
<ThemeToggle />
</body>
</html>
reveal opens a clip from the start point. blast grows a circle from that point. Set blur to soften the new theme as the effect opens.
<ThemeProvider effect={{ variant: "reveal", start: "bottom-up", blur: true }} />
start: "toggle" uses the toggle that was clicked. The other start values are top-left, top-right, bottom-left, bottom-right, center, and bottom-up.
The effect is skipped when the browser has no View Transitions API, and when the user prefers reduced motion.
Each toggle can override the provider effect. Omit the prop to inherit the provider setting. Use false to skip it:
<ThemeToggle effect={{ variant: "reveal", start: "center" }} />
<ThemeToggle effect={false} />
Browser API and events
The component binds a click listener to each button. It does not listen for clicks on the document. It binds new page controls after Astro navigation and removes its listeners before a page swap.
The provider also removes its listeners on astro:before-swap, before Astro
replaces the page during client navigation. theme:before-change runs before a
requested mode change. A mode change does not replace the page.
Each provider run sends the internal theme:provider-dispose event. The old
provider uses it to remove its listeners. The transition runner uses it to cancel
a pending animation. This prevents duplicate listeners and an old animation from
changing the mode after the provider has been replaced. Application code does not
need to send this event.
Import browser functions from theme-toggle.ts:
<script>
import { create, createThemeToggle, setTheme } from "@/components/ui/theme-toggle/theme-toggle.ts"
// Bind controls added by your own script. Existing controls are skipped.
const controllers = create()
// Get or create the controller for one button.
const button = document.querySelector<HTMLButtonElement>("#color-mode")
if (button) {
const toggle = createThemeToggle(button)
toggle.setTheme("dark", { effect: { variant: "blast", start: "center" } })
// Call toggle.destroy() before your script removes this button.
}
// A theme change without a button uses the same events and provider.
setTheme("system", { effect: false })
</script>
create(scope) returns only the controllers it creates. createThemeToggle(button)
returns an existing controller when the button is already bound. Each controller
has theme, setTheme(), toggle(), and destroy().
| Event | Purpose |
|---|---|
theme:before-change |
Bubbles from the source button, or fires on the document for setTheme(). Call preventDefault() to cancel. Set detail.effect to choose an effect for this change. |
theme:apply |
Runs on the document inside the transition update. The provider applies and saves detail.theme, then sets detail.resolvedTheme. |
theme:change |
Runs on the document after the theme is applied. All toggles update their state. |
Event detail includes theme, optional source, and optional effect.
theme:change also includes resolvedTheme (light or dark).
The events do not stop other listeners. Use setTheme() or a controller to
request a change through the full event sequence.
document.addEventListener("theme:before-change", (event) => {
if (event.detail.source?.id === "color-mode") {
event.detail.effect = { variant: "blast", start: "toggle", blur: true }
}
})
document.addEventListener("theme:change", (event) => {
console.log(event.detail.resolvedTheme)
})
Alternate Icon
Pass icons in the slot. Use dark:hidden on the light icon and hidden dark:block on the dark icon when the two marks differ.
Notes
ThemeToggleis a two-state light and dark switch.ThemeProviderreads the saved preference first and falls back to thedefaultTheme. The default value,system, follows the system color scheme.- If you need a richer theme picker, build that separately on top of the same
.darkclass convention.
API Reference
ThemeToggleProps
effect?ThemeEffect | false
Override the page effect for this control. Use false to skip it.
ThemeEffect | falseThemeProviderProps
effect?ThemeEffect
Default effect for requested theme changes. Omit to change mode without animation.
ThemeEffectundefinedstorageKey?string
The key used in the selected storage.
string"theme"defaultTheme?Theme
The theme to use when no saved preference is found.
Theme"system"storage?'localStorage' | 'sessionStorage' | 'cookie'
The storage to use for storing the theme preference. - `localStorage` - stored in the user's browser until cleared manually - `sessionStorage` - stored in the user's browser until the session ends (tab closed) - `cookie` - stored in a session cookie
'localStorage' | 'sessionStorage' | 'cookie'"localStorage"attributeType?'attribute' | 'class' | 'both' | 'none'
The attribute type to use to set the theme - `attribute` - set the `data-theme` attribute on the root element - `class` - set a `dark` class on the root element when dark mode is enabled - `both` - set both `data-theme` and `dark` class on root element - `none` - emit theme events without changing root attributes
'attribute' | 'class' | 'both' | 'none'"both"ThemeEffect
Options for the provider’s effect prop and per-toggle overrides. This is a type, not a component.
variant?ThemeEffectVariant
Animation variant.
ThemeEffectVariant"reveal"start?ThemeEffectStart
Where a reveal or blast effect starts.
ThemeEffectStart"toggle" - the coordinate of the theme toggle that was activatedblur?boolean
Blur the new theme as the effect opens.
booleanfalseWhen to use Theme Toggle
Use ThemeToggle where a user can change the page color mode. Keep its control in a stable location, such as the header. It changes color mode rather than choosing a complete palette.
Keyboard and behavior
Give the control a useful accessible name and check keyboard activation. Verify the chosen mode after page navigation. The rest of the page must also use theme tokens for the change to remain consistent.
Theme and layout
Check images, borders, and focus rings in both modes. Fixed light backgrounds in page content can defeat the theme even when the toggle itself works.