Theme Toggle
Light and dark theme switch with six distinct icon animations: rotate, morph, flip, slide, eclipse, and spring.
Rotate
Morph
Flip
Slide
Eclipse
Spring
Rotate
Morph
Flip
Slide
Eclipse
Spring
Rotate
Morph
Flip
Slide
Eclipse
Spring
Rotate
Morph
Flip
Slide
Eclipse
Spring
<div class="flex flex-col items-center gap-5">
<div class="grid w-full grid-cols-6 gap-2">
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="rotate" variant="outline" size="lg" />
<span class="text-xs text-muted">Rotate</span>
</div>
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="morph" variant="outline" size="lg" />
<span class="text-xs text-muted">Morph</span>
</div>
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="flip" variant="outline" size="lg" />
<span class="text-xs text-muted">Flip</span>
</div>
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="slide" variant="outline" size="lg" />
<span class="text-xs text-muted">Slide</span>
</div>
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="eclipse" variant="outline" size="lg" />
<span class="text-xs text-muted">Eclipse</span>
</div>
<div class="flex flex-col items-center gap-2">
<x-markas.theme-toggle animation="spring" variant="outline" size="lg" />
<span class="text-xs text-muted">Spring</span>
</div>
</div>
<x-markas.button variant="secondary" size="sm" x-data x-on:click="document.dispatchEvent(new Event('markas-theme-demo'))">Play all</x-markas.button>
</div>import { Button } from "@/components/markas/Button";
import { ThemeToggle } from "@/components/markas/ThemeToggle";
/** Plays every toggle there and back without changing the page theme. */
const playAll = () => document.dispatchEvent(new Event("markas-theme-demo"));
export default function ThemeToggleExample() {
return (
<div className="flex flex-col items-center gap-5">
<div className="grid w-full grid-cols-6 gap-2">
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="rotate" variant="outline" size="lg" />
<span className="text-xs text-muted">Rotate</span>
</div>
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="morph" variant="outline" size="lg" />
<span className="text-xs text-muted">Morph</span>
</div>
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="flip" variant="outline" size="lg" />
<span className="text-xs text-muted">Flip</span>
</div>
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="slide" variant="outline" size="lg" />
<span className="text-xs text-muted">Slide</span>
</div>
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="eclipse" variant="outline" size="lg" />
<span className="text-xs text-muted">Eclipse</span>
</div>
<div className="flex flex-col items-center gap-2">
<ThemeToggle animation="spring" variant="outline" size="lg" />
<span className="text-xs text-muted">Spring</span>
</div>
</div>
<Button variant="secondary" size="sm" onClick={playAll}>
Play all
</Button>
</div>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
/** Plays every toggle there and back without changing the page theme. */
const playAll = () => document.dispatchEvent(new Event("markas-theme-demo"));
</script>
<template>
<div class="flex flex-col items-center gap-5">
<div class="grid w-full grid-cols-6 gap-2">
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="rotate" variant="outline" size="lg" />
<span class="text-xs text-muted">Rotate</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="morph" variant="outline" size="lg" />
<span class="text-xs text-muted">Morph</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="flip" variant="outline" size="lg" />
<span class="text-xs text-muted">Flip</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="slide" variant="outline" size="lg" />
<span class="text-xs text-muted">Slide</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="eclipse" variant="outline" size="lg" />
<span class="text-xs text-muted">Eclipse</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="spring" variant="outline" size="lg" />
<span class="text-xs text-muted">Spring</span>
</div>
</div>
<Button variant="secondary" size="sm" @click="playAll">Play all</Button>
</div>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
/** Plays every toggle there and back without changing the page theme. */
const playAll = () => document.dispatchEvent(new Event("markas-theme-demo"));
</script>
<div class="flex flex-col items-center gap-5">
<div class="grid w-full grid-cols-6 gap-2">
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="rotate" variant="outline" size="lg" />
<span class="text-xs text-muted">Rotate</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="morph" variant="outline" size="lg" />
<span class="text-xs text-muted">Morph</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="flip" variant="outline" size="lg" />
<span class="text-xs text-muted">Flip</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="slide" variant="outline" size="lg" />
<span class="text-xs text-muted">Slide</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="eclipse" variant="outline" size="lg" />
<span class="text-xs text-muted">Eclipse</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="spring" variant="outline" size="lg" />
<span class="text-xs text-muted">Spring</span>
</div>
</div>
<Button variant="secondary" size="sm" onclick={playAll}>Play all</Button>
</div>---
import Button from "@/components/markas/Button.astro";
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
---
<div class="flex flex-col items-center gap-5">
<div class="grid w-full grid-cols-6 gap-2">
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="rotate" variant="outline" size="lg" />
<span class="text-xs text-muted">Rotate</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="morph" variant="outline" size="lg" />
<span class="text-xs text-muted">Morph</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="flip" variant="outline" size="lg" />
<span class="text-xs text-muted">Flip</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="slide" variant="outline" size="lg" />
<span class="text-xs text-muted">Slide</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="eclipse" variant="outline" size="lg" />
<span class="text-xs text-muted">Eclipse</span>
</div>
<div class="flex flex-col items-center gap-2">
<ThemeToggle animation="spring" variant="outline" size="lg" />
<span class="text-xs text-muted">Spring</span>
</div>
</div>
<Button variant="secondary" size="sm" data-play-all>Play all</Button>
</div>
<script>
/** Plays every toggle there and back without changing the page theme. */
document
.querySelector("[data-play-all]")
?.addEventListener("click", () =>
document.dispatchEvent(new Event("markas-theme-demo")),
);
</script>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { ThemeToggle } from "./markas/theme-toggle.component";
@Component({
selector: "markas-example",
imports: [Button, ThemeToggle],
template: `
<div class="flex flex-col items-center gap-5">
<div class="grid w-full grid-cols-6 gap-2">
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="rotate"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Rotate</span>
</div>
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="morph"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Morph</span>
</div>
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="flip"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Flip</span>
</div>
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="slide"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Slide</span>
</div>
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="eclipse"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Eclipse</span>
</div>
<div class="flex flex-col items-center gap-2">
<button
markas-theme-toggle
animation="spring"
variant="outline"
size="lg"
></button>
<span class="text-xs text-muted">Spring</span>
</div>
</div>
<button markas-button variant="secondary" size="sm" (click)="playAll()">
Play all
</button>
</div>
`,
})
export default class ThemeToggleExample {
/** Plays every toggle there and back without changing the page theme. */
protected playAll() {
document.dispatchEvent(new Event("markas-theme-demo"));
}
}Examples
Sizes and variants
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
<x-markas.theme-toggle size="sm" variant="ghost" />
<x-markas.theme-toggle size="md" variant="ghost" />
<x-markas.theme-toggle size="lg" variant="ghost" />
</div>
<div class="flex items-center gap-3">
<x-markas.theme-toggle size="sm" variant="outline" animation="morph" />
<x-markas.theme-toggle size="md" variant="outline" animation="morph" />
<x-markas.theme-toggle size="lg" variant="outline" animation="morph" />
</div>
<div class="flex items-center gap-3">
<x-markas.theme-toggle size="sm" variant="solid" animation="flip" />
<x-markas.theme-toggle size="md" variant="solid" animation="flip" />
<x-markas.theme-toggle size="lg" variant="solid" animation="flip" />
</div>
</div>import { ThemeToggle } from "@/components/markas/ThemeToggle";
export default function Example() {
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-3">
<ThemeToggle size="sm" variant="ghost" />
<ThemeToggle size="md" variant="ghost" />
<ThemeToggle size="lg" variant="ghost" />
</div>
<div className="flex items-center gap-3">
<ThemeToggle size="sm" variant="outline" animation="morph" />
<ThemeToggle size="md" variant="outline" animation="morph" />
<ThemeToggle size="lg" variant="outline" animation="morph" />
</div>
<div className="flex items-center gap-3">
<ThemeToggle size="sm" variant="solid" animation="flip" />
<ThemeToggle size="md" variant="solid" animation="flip" />
<ThemeToggle size="lg" variant="solid" animation="flip" />
</div>
</div>
);
}<script setup lang="ts">
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="ghost" />
<ThemeToggle size="md" variant="ghost" />
<ThemeToggle size="lg" variant="ghost" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="outline" animation="morph" />
<ThemeToggle size="md" variant="outline" animation="morph" />
<ThemeToggle size="lg" variant="outline" animation="morph" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="solid" animation="flip" />
<ThemeToggle size="md" variant="solid" animation="flip" />
<ThemeToggle size="lg" variant="solid" animation="flip" />
</div>
</div>
</template><script lang="ts">
import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
</script>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="ghost" />
<ThemeToggle size="md" variant="ghost" />
<ThemeToggle size="lg" variant="ghost" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="outline" animation="morph" />
<ThemeToggle size="md" variant="outline" animation="morph" />
<ThemeToggle size="lg" variant="outline" animation="morph" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="solid" animation="flip" />
<ThemeToggle size="md" variant="solid" animation="flip" />
<ThemeToggle size="lg" variant="solid" animation="flip" />
</div>
</div>---
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
---
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="ghost" />
<ThemeToggle size="md" variant="ghost" />
<ThemeToggle size="lg" variant="ghost" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="outline" animation="morph" />
<ThemeToggle size="md" variant="outline" animation="morph" />
<ThemeToggle size="lg" variant="outline" animation="morph" />
</div>
<div class="flex items-center gap-3">
<ThemeToggle size="sm" variant="solid" animation="flip" />
<ThemeToggle size="md" variant="solid" animation="flip" />
<ThemeToggle size="lg" variant="solid" animation="flip" />
</div>
</div>import { Component } from "@angular/core";
import { ThemeToggle } from "./markas/theme-toggle.component";
@Component({
selector: "markas-example",
imports: [ThemeToggle],
template: `
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
<button markas-theme-toggle size="sm" variant="ghost"></button>
<button markas-theme-toggle size="md" variant="ghost"></button>
<button markas-theme-toggle size="lg" variant="ghost"></button>
</div>
<div class="flex items-center gap-3">
<button
markas-theme-toggle
size="sm"
variant="outline"
animation="morph"
></button>
<button
markas-theme-toggle
size="md"
variant="outline"
animation="morph"
></button>
<button
markas-theme-toggle
size="lg"
variant="outline"
animation="morph"
></button>
</div>
<div class="flex items-center gap-3">
<button
markas-theme-toggle
size="sm"
variant="solid"
animation="flip"
></button>
<button
markas-theme-toggle
size="md"
variant="solid"
animation="flip"
></button>
<button
markas-theme-toggle
size="lg"
variant="solid"
animation="flip"
></button>
</div>
</div>
`,
})
export default class ThemeToggleSizesExample {}In a navbar
@php
$link = 'rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
@endphp
<header class="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3">
<a href="#" class="flex items-center gap-2 text-sm font-semibold text-ink {{ $link }}"><svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true"><polygon points="354,578 1256,138 1171,430 268,868" class="fill-ink/15" /><polygon points="553,443 1455,3 1370,295 467,733" class="fill-ink/55" /><polygon points="421,762 1325,318 1240,611 336,1050" class="fill-success/35" /><polygon points="265,1073 1169,629 1084,922 180,1362" class="fill-ink/25" /><polygon points="93,965 997,521 912,814 8,1253" class="fill-ink/75" /><polygon points="347,1135 1251,691 1166,984 262,1424" class="fill-success" /></svg>MarkasUI</a>
<nav aria-label="Main" class="hidden items-center gap-4 text-sm text-muted sm:flex">
<a href="#docs" class="{{ $link }}">Docs</a>
<a href="#components" class="{{ $link }}">Components</a>
<a href="#pricing" class="{{ $link }}">Pricing</a>
</nav>
<x-markas.theme-toggle size="sm" animation="eclipse" />
</header>import { ThemeToggle } from "@/components/markas/ThemeToggle";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const link =
"rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
export default function Example() {
return (
<header className="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3">
<a
href="#"
className={`flex items-center gap-2 text-sm font-semibold text-ink ${link}`}
>
<svg
className="size-6 shrink-0"
viewBox="0 0 1464 1430"
aria-hidden="true"
>
{mark.map((shape) => (
<polygon
key={shape.points}
points={shape.points}
className={shape.className}
/>
))}
</svg>
MarkasUI
</a>
<nav
aria-label="Main"
className="hidden items-center gap-4 text-sm text-muted sm:flex"
>
<a href="#docs" className={link}>
Docs
</a>
<a href="#components" className={link}>
Components
</a>
<a href="#pricing" className={link}>
Pricing
</a>
</nav>
<ThemeToggle size="sm" animation="eclipse" />
</header>
);
}<script setup lang="ts">
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const link =
"rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
</script>
<template>
<header
class="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3"
>
<a
href="#"
:class="`flex items-center gap-2 text-sm font-semibold text-ink ${link}`"
>
<svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
<polygon
v-for="shape in mark"
:key="shape.points"
:points="shape.points"
:class="shape.className"
/>
</svg>
MarkasUI
</a>
<nav
aria-label="Main"
class="hidden items-center gap-4 text-sm text-muted sm:flex"
>
<a href="#docs" :class="link">Docs</a>
<a href="#components" :class="link">Components</a>
<a href="#pricing" :class="link">Pricing</a>
</nav>
<ThemeToggle size="sm" animation="eclipse" />
</header>
</template><script lang="ts">
import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const link =
"rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
</script>
<header
class="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3"
>
<!-- svelte-ignore a11y_invalid_attribute -->
<a
href="#"
class={`flex items-center gap-2 text-sm font-semibold text-ink ${link}`}
>
<svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
{#each mark as shape (shape.points)}<polygon
points={shape.points}
class={shape.className}
/>{/each}
</svg>
MarkasUI
</a>
<nav
aria-label="Main"
class="hidden items-center gap-4 text-sm text-muted sm:flex"
>
<a href="#docs" class={link}>Docs</a>
<a href="#components" class={link}>Components</a>
<a href="#pricing" class={link}>Pricing</a>
</nav>
<ThemeToggle size="sm" animation="eclipse" />
</header>---
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
const mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
const link =
"rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
---
<header class="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3">
<a href="#" class={`flex items-center gap-2 text-sm font-semibold text-ink ${link}`}>
<svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
{mark.map((shape) => (<polygon points={shape.points} class={shape.className} />))}
</svg>
MarkasUI
</a>
<nav aria-label="Main" class="hidden items-center gap-4 text-sm text-muted sm:flex">
<a href="#docs" class={link}>Docs</a>
<a href="#components" class={link}>Components</a>
<a href="#pricing" class={link}>Pricing</a>
</nav>
<ThemeToggle size="sm" animation="eclipse" />
</header>import { Component } from "@angular/core";
import { ThemeToggle } from "./markas/theme-toggle.component";
@Component({
selector: "markas-example",
imports: [ThemeToggle],
template: `
<header
class="flex items-center justify-between gap-4 rounded-xl border border-line bg-surface py-2 pr-2 pl-3"
>
<a
href="#"
[class]="\`flex items-center gap-2 text-sm font-semibold text-ink \${link}\`"
>
<svg class="size-6 shrink-0" viewBox="0 0 1464 1430" aria-hidden="true">
@for (shape of mark; track shape.points) {
<polygon [attr.points]="shape.points" [class]="shape.className" />
}
</svg>
MarkasUI
</a>
<nav
aria-label="Main"
class="hidden items-center gap-4 text-sm text-muted sm:flex"
>
<a href="#docs" [class]="link">Docs</a>
<a href="#components" [class]="link">Components</a>
<a href="#pricing" [class]="link">Pricing</a>
</nav>
<button markas-theme-toggle size="sm" animation="eclipse"></button>
</header>
`,
})
export default class ThemeToggleInNavbarExample {
protected readonly mark = [
{ points: "354,578 1256,138 1171,430 268,868", className: "fill-ink/15" },
{ points: "553,443 1455,3 1370,295 467,733", className: "fill-ink/55" },
{
points: "421,762 1325,318 1240,611 336,1050",
className: "fill-success/35",
},
{ points: "265,1073 1169,629 1084,922 180,1362", className: "fill-ink/25" },
{ points: "93,965 997,521 912,814 8,1253", className: "fill-ink/75" },
{
points: "347,1135 1251,691 1166,984 262,1424",
className: "fill-success",
},
];
protected readonly link =
"rounded-sm transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
}With text
<div class="flex flex-wrap items-center gap-3">
<x-markas.theme-toggle :show-text="true" dark-label="Dark mode" light-label="Light mode" variant="outline" />
<x-markas.theme-toggle :show-text="true" dark-label="Dark mode" light-label="Light mode" variant="solid" animation="morph" size="sm" />
<x-markas.theme-toggle :show-text="true" dark-label="Dark mode" light-label="Light mode" variant="ghost" animation="slide" size="lg" />
</div>import { ThemeToggle } from "@/components/markas/ThemeToggle";
export default function Example() {
return (
<div className="flex flex-wrap items-center gap-3">
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="outline"
/>
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="solid"
animation="morph"
size="sm"
/>
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="ghost"
animation="slide"
size="lg"
/>
</div>
);
}<script setup lang="ts">
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<ThemeToggle
show-text
dark-label="Dark mode"
light-label="Light mode"
variant="outline"
/>
<ThemeToggle
show-text
dark-label="Dark mode"
light-label="Light mode"
variant="solid"
animation="morph"
size="sm"
/>
<ThemeToggle
show-text
dark-label="Dark mode"
light-label="Light mode"
variant="ghost"
animation="slide"
size="lg"
/>
</div>
</template><script lang="ts">
import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
</script>
<div class="flex flex-wrap items-center gap-3">
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="outline"
/>
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="solid"
animation="morph"
size="sm"
/>
<ThemeToggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="ghost"
animation="slide"
size="lg"
/>
</div>---
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
---
<div class="flex flex-wrap items-center gap-3">
<ThemeToggle showText darkLabel="Dark mode" lightLabel="Light mode" variant="outline" />
<ThemeToggle showText darkLabel="Dark mode" lightLabel="Light mode" variant="solid" animation="morph" size="sm" />
<ThemeToggle showText darkLabel="Dark mode" lightLabel="Light mode" variant="ghost" animation="slide" size="lg" />
</div>import { Component } from "@angular/core";
import { ThemeToggle } from "./markas/theme-toggle.component";
@Component({
selector: "markas-example",
imports: [ThemeToggle],
template: `
<div class="flex flex-wrap items-center gap-3">
<button
markas-theme-toggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="outline"
></button>
<button
markas-theme-toggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="solid"
animation="morph"
size="sm"
></button>
<button
markas-theme-toggle
showText
darkLabel="Dark mode"
lightLabel="Light mode"
variant="ghost"
animation="slide"
size="lg"
></button>
</div>
`,
})
export default class ThemeToggleWithLabelExample {}Installation
npx markasui@latest add theme-togglepnpm dlx markasui@latest add theme-toggleyarn dlx markasui@latest add theme-togglebunx --bun markasui@latest add theme-toggle- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/theme-toggle.blade.php.
resources/views/components/markas/theme-toggle.blade.php
@props([
'animation' => 'rotate',
'variant' => 'ghost',
'size' => 'md',
'theme' => null,
'storageKey' => 'markas-theme',
'showText' => false,
'lightLabel' => 'Switch to light theme',
'darkLabel' => 'Switch to dark theme',
])
@php
$base = 'group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50';
$variants = [
'ghost' => 'text-ink hover:bg-subtle',
'outline' => 'border border-line bg-surface text-ink hover:bg-subtle',
'solid' => 'bg-primary text-on-primary hover:bg-primary-strong',
];
// Per size: icon-only button, button with text, icon.
$sizes = [
'sm' => ['size-8 rounded-md', 'h-8 rounded-md px-3 text-sm', 'size-4'],
'md' => ['size-10 rounded-lg', 'h-10 rounded-lg px-4 text-sm', 'size-5'],
'lg' => ['size-12 rounded-lg', 'h-12 rounded-lg px-6 text-base', 'size-6'],
];
// Parts scale and rotate around the icon center.
$icon = '**:origin-[12px_12px]';
// Moon and stars start hidden (the light look); the keyframes show them.
$hidden = 'opacity-0';
$moonPath = 'M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z';
$starPaths = ['M18 2v4m-2-2h4', 'M21.5 9h0', 'M14.5 1.5h0'];
$srOnly = 'sr-only';
// Keyframes from light to dark (reverse for dark to light), the same as React and Vue:
// "selector inside the button|property:value,value;property:...|stagger ms".
$moves = [
'rotate' => [
'g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0',
'g>path|scale:1,1.6,1.6,0',
'svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1',
],
'morph' => [
'g>circle|scale:1,1.6',
'mask>circle|translate:24px -12px,15.5px -3.5px',
'g>path|scale:1,0;opacity:1,0|50',
],
'flip' => [
'svg|transform:perspective(60px) rotateY(0),perspective(60px) rotateY(90deg),perspective(60px) rotateY(-90deg),perspective(60px) rotateY(0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1',
'g|opacity:1,1,0,0;offset:0,.5,.5,1',
'svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1',
],
'slide' => [
'g|translate:0,0 24px',
'svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1',
],
'eclipse' => [
'mask>circle|translate:-6px 0,13.5px -1.5px',
'g>path|scale:1,1.7,.75;opacity:1,.3,.4',
],
'spring' => [
'svg|scale:1,.6,1.15,.95,1',
'g|opacity:1,1,0,0',
'svg>:nth-child(3)|opacity:0,0,1,1',
'svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120',
],
];
// Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
$idKey = 'markas-theme-toggle|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
$__env->markAsRenderedOnce($idKey.$idIndex);
$maskId = 'mask'.hash('xxh32', $idKey.$idIndex);
@endphp
{{-- Same logic as React and Vue: saved choice, then the page dark class, then the system setting. --}}
<button
x-data="{
state: null,
requested: null,
key: @js($storageKey),
moves: @js($moves[$animation]),
page: () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light'),
setDark: (theme) => document.documentElement.classList.toggle('dark', theme === 'dark'),
{{-- mode 0 jumps to the look, 1 animates the switch, 2 plays there and back (demo). --}}
play(toDark, mode) {
const still = mode === 0 || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
for (const move of this.moves) {
const [selector, frames, stagger = 0] = move.split('|');
const keyframes = Object.fromEntries(frames.split(';').map((frame) => {
const [property, values] = frame.split(':');
return [property, values.split(',')];
}));
this.$root.querySelectorAll(selector).forEach((part, i) => part.animate(keyframes, {
duration: still ? 0 : +stagger ? 325 : 650,
delay: still ? 0 : i * +stagger,
fill: 'both',
iterations: mode === 2 ? 2 : 1,
direction: ['reverse', 'normal', 'alternate-reverse', 'alternate'][+toDark + (mode === 2 ? 2 : 0)],
}));
}
},
show(theme) {
if (theme === this.state) return;
this.state = theme;
this.play(theme === 'dark', theme === this.requested ? 1 : 0);
this.requested = null;
},
init() {
let saved = null;
try {
saved = localStorage.getItem(this.key);
} catch {}
const target = @js($theme) ?? (saved === 'light' || saved === 'dark' ? saved : this.page() === 'dark' || window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
if (target !== this.page()) this.setDark(target);
this.show(this.page());
this.observer = new MutationObserver(() => this.show(this.page()));
this.observer.observe(document.documentElement, { attributeFilter: ['class'] });
},
destroy() {
this.observer?.disconnect();
},
toggle() {
const theme = this.page() === 'dark' ? 'light' : 'dark';
this.requested = theme;
this.setDark(theme);
try {
localStorage.setItem(this.key, theme);
} catch {}
document.dispatchEvent(new CustomEvent('markas-theme-change', { detail: theme }));
},
}"
x-on:click="toggle()"
x-on:markas-theme-demo.document="play(page() !== 'dark', 2)"
x-bind:data-state="state"
{{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size][$showText ? 1 : 0]]) }}
>
{{-- The icon parts are animated from JavaScript, so Livewire skips them when it re-renders. --}}
<svg class="{{ $sizes[$size][2] }} {{ $icon }}" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" wire:ignore>
<mask id="{{ $maskId }}">
<rect width="24" height="24" fill="white" />
<circle cy="12" r="5" fill="black" />
</mask>
<g>
<circle cx="12" cy="12" r="4.5" stroke="none" mask="url(#{{ $maskId }})" />
@for ($ray = 0; $ray < 8; $ray++)
<path style="rotate: {{ $ray * 45 }}deg" d="M12 2v2" />
@endfor
</g>
<path class="{{ $hidden }}" d="{{ $moonPath }}" />
@foreach ($starPaths as $starPath)
<path class="{{ $hidden }}" d="{{ $starPath }}" />
@endforeach
</svg>
<span class="{{ $showText ? '' : $srOnly }}" x-text="state === 'dark' ? @js($lightLabel) : @js($darkLabel)">{{ $darkLabel }}</span>
</button>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ThemeToggle.tsx.
src/components/markas/ThemeToggle.tsx
"use client";
import {
useEffect,
useId,
useRef,
useSyncExternalStore,
type ComponentProps,
type MouseEvent,
} from "react";
const base =
"group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
ghost: "text-ink hover:bg-subtle",
outline: "border border-line bg-surface text-ink hover:bg-subtle",
solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";
/**
* Keyframes from light to dark; dark to light plays them in reverse. Every part that
* differs between the themes is animated, and the last frame stays (fill both).
* Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
*/
const turn = "perspective(60px) rotateY(";
const moves = {
rotate: [
"g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
"g>path|scale:1,1.6,1.6,0",
"svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
],
morph: [
"g>circle|scale:1,1.6",
"mask>circle|translate:24px -12px,15.5px -3.5px",
"g>path|scale:1,0;opacity:1,0|50",
],
flip: [
`svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
"g|opacity:1,1,0,0;offset:0,.5,.5,1",
"svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
],
slide: [
"g|translate:0,0 24px",
"svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
],
eclipse: [
"mask>circle|translate:-6px 0,13.5px -1.5px",
"g>path|scale:1,1.7,.75;opacity:1,.3,.4",
],
spring: [
"svg|scale:1,.6,1.15,.95,1",
"g|opacity:1,1,0,0",
"svg>:nth-child(3)|opacity:0,0,1,1",
"svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
"reverse",
"normal",
"alternate-reverse",
"alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;
type Theme = "light" | "dark";
type Animation = keyof typeof moves;
const html = () => document.documentElement;
const pageTheme = (): Theme =>
html().classList.contains("dark") ? "dark" : "light";
const subscribe = (onChange: () => void) => {
const observer = new MutationObserver(onChange);
observer.observe(html(), { attributeFilter: ["class"] });
return () => observer.disconnect();
};
const setDark = (theme: Theme) =>
html().classList.toggle("dark", theme === "dark");
/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
button: HTMLElement,
animation: Animation,
toDark: boolean,
mode: number,
) {
const still =
mode === SET ||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
for (const move of moves[animation]) {
const [selector = "", frames = "", stagger = 0] = move.split("|");
const keyframes = Object.fromEntries(
frames.split(";").map((frame) => {
const [property, values = ""] = frame.split(":");
return [property, values.split(",")];
}),
) as Parameters<HTMLElement["animate"]>[0];
button.querySelectorAll(selector).forEach((part, i) =>
part.animate(keyframes, {
duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
delay: still ? 0 : i * +stagger,
fill: "both",
iterations: mode === DEMO ? 2 : 1,
direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
}),
);
}
}
/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
let saved: string | null = null;
try {
saved = localStorage.getItem(storageKey);
} catch {
// Storage blocked: fall back to the page and the system setting.
}
if (saved === "light" || saved === "dark") return saved;
return pageTheme() === "dark" ||
window.matchMedia?.("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
export type ThemeToggleProps = Omit<ComponentProps<"button">, "children"> & {
animation?: Animation;
variant?: keyof typeof variants;
size?: keyof typeof sizes;
/** Controlled theme. Leave empty to read localStorage and the system setting. */
theme?: Theme;
storageKey?: string;
/** Show the label as visible text next to the icon. */
showText?: boolean;
lightLabel?: string;
darkLabel?: string;
onThemeChange?: (theme: Theme) => void;
};
export function ThemeToggle({
animation = "rotate",
variant = "ghost",
size = "md",
theme,
storageKey = "markas-theme",
showText = false,
lightLabel = "Switch to light theme",
darkLabel = "Switch to dark theme",
onThemeChange,
className,
onClick,
...props
}: ThemeToggleProps) {
const maskId = `mask${useId()}`;
const button = useRef<HTMLButtonElement>(null);
/** The theme a click asked for: reaching it animates, any other change jumps. */
const requested = useRef<Theme>(undefined);
// Follow the html class, so every toggle on the page and outside changes stay in sync.
const state = useSyncExternalStore(subscribe, pageTheme, () => undefined);
// Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
useEffect(() => {
const target = theme ?? readTheme(storageKey);
if (target !== pageTheme()) setDark(target);
// Only a new controlled theme should run this again.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme]);
// Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
useEffect(() => {
if (!state || !button.current) return;
const mode = state === requested.current ? SWITCH : SET;
requested.current = undefined;
play(button.current, animation, state === "dark", mode);
}, [state, animation]);
// "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
useEffect(() => {
const demo = () =>
button.current &&
play(button.current, animation, pageTheme() !== "dark", DEMO);
document.addEventListener("markas-theme-demo", demo);
return () => document.removeEventListener("markas-theme-demo", demo);
}, [animation]);
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented) return;
const next = pageTheme() === "dark" ? "light" : "dark";
requested.current = next;
if (theme === undefined) {
setDark(next);
try {
localStorage.setItem(storageKey, next);
} catch {
// Storage blocked: the theme still applies until the page closes.
}
document.dispatchEvent(
new CustomEvent("markas-theme-change", { detail: next }),
);
}
onThemeChange?.(next);
};
return (
<button
ref={button}
type="button"
data-state={state}
onClick={handleClick}
className={`${base} ${variants[variant]} ${sizes[size][+showText]} ${className ?? ""}`}
{...props}
>
<svg
className={`${sizes[size][2]} ${icon}`}
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
aria-hidden="true"
>
<mask id={maskId}>
<rect width="24" height="24" fill="white" />
<circle cy="12" r="5" fill="black" />
</mask>
<g>
<circle
cx="12"
cy="12"
r="4.5"
stroke="none"
mask={`url(#${maskId})`}
/>
{rays.map((deg) => (
<path key={deg} style={{ rotate: `${deg}deg` }} d="M12 2v2" />
))}
</g>
<path className={hidden} d={moonPath} />
{starPaths.map((d) => (
<path key={d} className={hidden} d={d} />
))}
</svg>
<span className={showText ? undefined : srOnly}>
{state === "dark" ? lightLabel : darkLabel}
</span>
</button>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ThemeToggle.vue.
src/components/markas/ThemeToggle.vue
<script setup lang="ts">
import {
onBeforeUnmount,
onMounted,
ref,
useId,
useTemplateRef,
watch,
watchEffect,
} from "vue";
const variants = {
ghost: "text-ink hover:bg-subtle",
outline: "border border-line bg-surface text-ink hover:bg-subtle",
solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";
/**
* Keyframes from light to dark; dark to light plays them in reverse. Every part that
* differs between the themes is animated, and the last frame stays (fill both).
* Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
*/
const turn = "perspective(60px) rotateY(";
const moves = {
rotate: [
"g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
"g>path|scale:1,1.6,1.6,0",
"svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
],
morph: [
"g>circle|scale:1,1.6",
"mask>circle|translate:24px -12px,15.5px -3.5px",
"g>path|scale:1,0;opacity:1,0|50",
],
flip: [
`svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
"g|opacity:1,1,0,0;offset:0,.5,.5,1",
"svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
],
slide: [
"g|translate:0,0 24px",
"svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
],
eclipse: [
"mask>circle|translate:-6px 0,13.5px -1.5px",
"g>path|scale:1,1.7,.75;opacity:1,.3,.4",
],
spring: [
"svg|scale:1,.6,1.15,.95,1",
"g|opacity:1,1,0,0",
"svg>:nth-child(3)|opacity:0,0,1,1",
"svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
"reverse",
"normal",
"alternate-reverse",
"alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;
type Theme = "light" | "dark";
const props = withDefaults(
defineProps<{
animation?: keyof typeof moves;
variant?: keyof typeof variants;
size?: keyof typeof sizes;
/** Controlled theme. Leave empty to read localStorage and the system setting. */
theme?: Theme;
storageKey?: string;
/** Show the label as visible text next to the icon. */
showText?: boolean;
lightLabel?: string;
darkLabel?: string;
}>(),
{
animation: "rotate",
variant: "ghost",
size: "md",
theme: undefined,
storageKey: "markas-theme",
showText: false,
lightLabel: "Switch to light theme",
darkLabel: "Switch to dark theme",
},
);
const emit = defineEmits<{ change: [theme: Theme] }>();
const base =
"group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const maskId = `mask${useId()}`;
const buttonRef = useTemplateRef<HTMLButtonElement>("buttonRef");
const state = ref<Theme>();
/** The theme a click asked for: reaching it animates, any other change jumps. */
let requested: Theme | undefined;
let observer: MutationObserver | undefined;
const html = () => document.documentElement;
const pageTheme = (): Theme =>
html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
html().classList.toggle("dark", theme === "dark");
/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
button: HTMLElement,
animation: keyof typeof moves,
toDark: boolean,
mode: number,
) {
const still =
mode === SET ||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
for (const move of moves[animation]) {
const [selector = "", frames = "", stagger = 0] = move.split("|");
const keyframes = Object.fromEntries(
frames.split(";").map((frame) => {
const [property, values = ""] = frame.split(":");
return [property, values.split(",")];
}),
) as Parameters<HTMLElement["animate"]>[0];
button.querySelectorAll(selector).forEach((part, i) =>
part.animate(keyframes, {
duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
delay: still ? 0 : i * +stagger,
fill: "both",
iterations: mode === DEMO ? 2 : 1,
direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
}),
);
}
}
// "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
const demo = () =>
buttonRef.value &&
play(buttonRef.value, props.animation, pageTheme() !== "dark", DEMO);
onMounted(() => {
// Now and on controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
// Saved choice first, then a dark class the page already set, then the system setting.
watchEffect(() => {
let saved: string | null = null;
try {
saved = localStorage.getItem(props.storageKey);
} catch {
// Storage blocked: fall back to the page and the system setting.
}
const target: Theme =
props.theme ??
(saved === "light" || saved === "dark"
? saved
: pageTheme() === "dark" ||
window.matchMedia?.("(prefers-color-scheme: dark)").matches
? "dark"
: "light");
if (target !== pageTheme()) setDark(target);
state.value = pageTheme();
});
// Follow the html class, so every toggle on the page and outside changes stay in sync.
observer = new MutationObserver(() => (state.value = pageTheme()));
observer.observe(html(), { attributeFilter: ["class"] });
document.addEventListener("markas-theme-demo", demo);
});
onBeforeUnmount(() => {
observer?.disconnect();
document.removeEventListener("markas-theme-demo", demo);
});
// Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
watch(state, (theme) => {
if (!theme || !buttonRef.value) return;
const mode = theme === requested ? SWITCH : SET;
requested = undefined;
play(buttonRef.value, props.animation, theme === "dark", mode);
});
function toggle() {
const next = pageTheme() === "dark" ? "light" : "dark";
requested = next;
if (props.theme === undefined) {
setDark(next);
try {
localStorage.setItem(props.storageKey, next);
} catch {
// Storage blocked: the theme still applies until the page closes.
}
document.dispatchEvent(
new CustomEvent("markas-theme-change", { detail: next }),
);
}
emit("change", next);
}
</script>
<template>
<button
ref="buttonRef"
type="button"
:data-state="state"
:class="[base, variants[props.variant], sizes[props.size][+props.showText]]"
@click="toggle"
>
<svg
:class="[sizes[props.size][2], icon]"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<mask :id="maskId">
<rect width="24" height="24" fill="white" />
<circle cy="12" r="5" fill="black" />
</mask>
<g>
<circle
cx="12"
cy="12"
r="4.5"
stroke="none"
:mask="`url(#${maskId})`"
/>
<path
v-for="ray in 8"
:key="ray"
:style="{ rotate: `${ray * 45}deg` }"
d="M12 2v2"
/>
</g>
<path :class="hidden" :d="moonPath" />
<path v-for="d in starPaths" :key="d" :class="hidden" :d="d" />
</svg>
<span :class="props.showText ? undefined : srOnly">{{
state === "dark" ? props.lightLabel : props.darkLabel
}}</span>
</button>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/ThemeToggle.svelte.
src/lib/components/markas/ThemeToggle.svelte
<script lang="ts">
import type { HTMLButtonAttributes } from "svelte/elements";
const base =
"group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
ghost: "text-ink hover:bg-subtle",
outline: "border border-line bg-surface text-ink hover:bg-subtle",
solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";
/**
* Keyframes from light to dark; dark to light plays them in reverse. Every part that
* differs between the themes is animated, and the last frame stays (fill both).
* Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
*/
const turn = "perspective(60px) rotateY(";
const moves = {
rotate: [
"g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
"g>path|scale:1,1.6,1.6,0",
"svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
],
morph: [
"g>circle|scale:1,1.6",
"mask>circle|translate:24px -12px,15.5px -3.5px",
"g>path|scale:1,0;opacity:1,0|50",
],
flip: [
`svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
"g|opacity:1,1,0,0;offset:0,.5,.5,1",
"svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
],
slide: [
"g|translate:0,0 24px",
"svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
],
eclipse: [
"mask>circle|translate:-6px 0,13.5px -1.5px",
"g>path|scale:1,1.7,.75;opacity:1,.3,.4",
],
spring: [
"svg|scale:1,.6,1.15,.95,1",
"g|opacity:1,1,0,0",
"svg>:nth-child(3)|opacity:0,0,1,1",
"svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
"reverse",
"normal",
"alternate-reverse",
"alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;
type Theme = "light" | "dark";
type Animation = keyof typeof moves;
const html = () => document.documentElement;
const pageTheme = (): Theme =>
html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
html().classList.toggle("dark", theme === "dark");
/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
button: HTMLElement,
animation: Animation,
toDark: boolean,
mode: number,
) {
const still =
mode === SET ||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
for (const move of moves[animation]) {
const [selector = "", frames = "", stagger = 0] = move.split("|");
const keyframes = Object.fromEntries(
frames.split(";").map((frame) => {
const [property, values = ""] = frame.split(":");
return [property, values.split(",")];
}),
) as Parameters<HTMLElement["animate"]>[0];
button.querySelectorAll(selector).forEach((part, i) =>
part.animate(keyframes, {
duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
delay: still ? 0 : i * +stagger,
fill: "both",
iterations: mode === DEMO ? 2 : 1,
direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
}),
);
}
}
/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
let saved: string | null = null;
try {
saved = localStorage.getItem(storageKey);
} catch {
// Storage blocked: fall back to the page and the system setting.
}
if (saved === "light" || saved === "dark") return saved;
return pageTheme() === "dark" ||
window.matchMedia?.("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
type Props = Omit<HTMLButtonAttributes, "children"> & {
animation?: Animation;
variant?: keyof typeof variants;
size?: keyof typeof sizes;
/** Controlled theme. Leave empty to read localStorage and the system setting. */
theme?: Theme;
storageKey?: string;
/** Show the label as visible text next to the icon. */
showText?: boolean;
lightLabel?: string;
darkLabel?: string;
onThemeChange?: (theme: Theme) => void;
};
let {
animation = "rotate",
variant = "ghost",
size = "md",
theme,
storageKey = "markas-theme",
showText = false,
lightLabel = "Switch to light theme",
darkLabel = "Switch to dark theme",
onThemeChange,
class: className,
onclick,
...rest
}: Props = $props();
const generatedId = $props.id();
const maskId = `mask${generatedId}`;
let button = $state<HTMLButtonElement>();
let current = $state<Theme>();
/** The theme a click asked for: reaching it animates, any other change jumps. */
let requested: Theme | undefined;
// Follow the html class, so every toggle on the page and outside changes stay in sync.
$effect(() => {
current = pageTheme();
const observer = new MutationObserver(() => (current = pageTheme()));
observer.observe(html(), { attributeFilter: ["class"] });
return () => observer.disconnect();
});
// Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
$effect(() => {
const target = theme ?? readTheme(storageKey);
if (target !== pageTheme()) setDark(target);
});
// Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
$effect(() => {
const shown = current;
const name = animation;
if (!shown || !button) return;
const mode = shown === requested ? SWITCH : SET;
requested = undefined;
play(button, name, shown === "dark", mode);
});
// "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
$effect(() => {
const name = animation;
const demo = () =>
button && play(button, name, pageTheme() !== "dark", DEMO);
document.addEventListener("markas-theme-demo", demo);
return () => document.removeEventListener("markas-theme-demo", demo);
});
function handleClick(
event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
) {
onclick?.(event);
if (event.defaultPrevented) return;
const next = pageTheme() === "dark" ? "light" : "dark";
requested = next;
if (theme === undefined) {
setDark(next);
try {
localStorage.setItem(storageKey, next);
} catch {
// Storage blocked: the theme still applies until the page closes.
}
document.dispatchEvent(
new CustomEvent("markas-theme-change", { detail: next }),
);
}
onThemeChange?.(next);
}
</script>
<button
bind:this={button}
type="button"
data-state={current}
onclick={handleClick}
class={[base, variants[variant], sizes[size][+showText], className]}
{...rest}
>
<svg
class={[sizes[size][2], icon]}
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<mask id={maskId}>
<rect width="24" height="24" fill="white" />
<circle cy="12" r="5" fill="black" />
</mask>
<g>
<circle cx="12" cy="12" r="4.5" stroke="none" mask={`url(#${maskId})`} />
{#each rays as deg (deg)}
<path style:rotate={`${deg}deg`} d="M12 2v2" />
{/each}
</g>
<path class={hidden} d={moonPath} />
{#each starPaths as d (d)}
<path class={hidden} {d} />
{/each}
</svg>
<span class={showText ? undefined : srOnly}
>{current === "dark" ? lightLabel : darkLabel}</span
>
</button>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/ThemeToggle.astro.
src/components/markas/ThemeToggle.astro
---
import type { HTMLAttributes } from "astro/types";
const base =
"group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
ghost: "text-ink hover:bg-subtle",
outline: "border border-line bg-surface text-ink hover:bg-subtle",
solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";
type Props = Omit<HTMLAttributes<"button">, "children"> & {
animation?: "rotate" | "morph" | "flip" | "slide" | "eclipse" | "spring";
variant?: keyof typeof variants;
size?: keyof typeof sizes;
/** Theme to apply on load. Leave empty to read localStorage and the system setting. */
theme?: "light" | "dark";
storageKey?: string;
/** Show the label as visible text next to the icon. */
showText?: boolean;
lightLabel?: string;
darkLabel?: string;
};
const {
animation = "rotate",
variant = "ghost",
size = "md",
theme,
storageKey = "markas-theme",
showText = false,
lightLabel = "Switch to light theme",
darkLabel = "Switch to dark theme",
class: className,
...rest
} = Astro.props;
const maskId = `mask-markas-theme-toggle-${crypto.randomUUID().slice(0, 8)}`;
---
<markas-theme-toggle
class="contents"
data-animation={animation}
data-theme={theme}
data-storage-key={storageKey}
data-light-label={lightLabel}
data-dark-label={darkLabel}
>
<button
type="button"
class:list={[base, variants[variant], sizes[size][+showText], className]}
{...rest}
>
<svg
class:list={[sizes[size][2], icon]}
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<mask id={maskId}>
<rect width="24" height="24" fill="white"></rect>
<circle cy="12" r="5" fill="black"></circle>
</mask>
<g>
<circle cx="12" cy="12" r="4.5" stroke="none" mask={`url(#${maskId})`}></circle>
{rays.map((deg) => <path style={`rotate: ${deg}deg`} d="M12 2v2"></path>)}
</g>
<path class={hidden} d={moonPath}></path>
{starPaths.map((d) => <path class={hidden} d={d}></path>)}
</svg>
<span class={showText ? undefined : srOnly}>{darkLabel}</span>
</button>
</markas-theme-toggle>
<script>
/**
* Keyframes from light to dark; dark to light plays them in reverse. Every part that
* differs between the themes is animated, and the last frame stays (fill both).
* Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
*/
const turn = "perspective(60px) rotateY(";
const moves = {
rotate: [
"g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
"g>path|scale:1,1.6,1.6,0",
"svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
],
morph: [
"g>circle|scale:1,1.6",
"mask>circle|translate:24px -12px,15.5px -3.5px",
"g>path|scale:1,0;opacity:1,0|50",
],
flip: [
`svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
"g|opacity:1,1,0,0;offset:0,.5,.5,1",
"svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
],
slide: [
"g|translate:0,0 24px",
"svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
],
eclipse: [
"mask>circle|translate:-6px 0,13.5px -1.5px",
"g>path|scale:1,1.7,.75;opacity:1,.3,.4",
],
spring: [
"svg|scale:1,.6,1.15,.95,1",
"g|opacity:1,1,0,0",
"svg>:nth-child(3)|opacity:0,0,1,1",
"svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
"reverse",
"normal",
"alternate-reverse",
"alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;
type Theme = "light" | "dark";
type Animation = keyof typeof moves;
const html = () => document.documentElement;
const pageTheme = (): Theme =>
html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
html().classList.toggle("dark", theme === "dark");
/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
button: HTMLElement,
animation: Animation,
toDark: boolean,
mode: number,
) {
const still =
mode === SET ||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
for (const move of moves[animation]) {
const [selector = "", frames = "", stagger = 0] = move.split("|");
const keyframes = Object.fromEntries(
frames.split(";").map((frame) => {
const [property, values = ""] = frame.split(":");
return [property, values.split(",")];
}),
) as Parameters<HTMLElement["animate"]>[0];
button.querySelectorAll(selector).forEach((part, i) =>
part.animate(keyframes, {
duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
delay: still ? 0 : i * +stagger,
fill: "both",
iterations: mode === DEMO ? 2 : 1,
direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
}),
);
}
}
/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
let saved: string | null = null;
try {
saved = localStorage.getItem(storageKey);
} catch {
// Storage blocked: fall back to the page and the system setting.
}
if (saved === "light" || saved === "dark") return saved;
return pageTheme() === "dark" ||
window.matchMedia?.("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
/**
* Per instance: saved choice first, then the page dark class, then the system setting. Each
* toggle follows the html class, so every toggle on the page stays in sync, and a click
* animates the switch it asked for.
*/
class ThemeToggle extends HTMLElement {
#requested: Theme | undefined;
#shown: Theme | undefined;
#stop = () => {};
get #button() {
return this.querySelector("button");
}
get #animation() {
return (this.dataset.animation ?? "rotate") as Animation;
}
connectedCallback() {
const button = this.#button;
if (!button) return;
const forced = this.dataset.theme;
const target =
forced === "light" || forced === "dark"
? forced
: readTheme(this.dataset.storageKey ?? "markas-theme");
if (target !== pageTheme()) setDark(target);
this.#show();
const observer = new MutationObserver(() => this.#show());
observer.observe(html(), { attributeFilter: ["class"] });
const click = (event: MouseEvent) => this.#toggle(event);
const demo = () =>
play(button, this.#animation, pageTheme() !== "dark", DEMO);
button.addEventListener("click", click);
document.addEventListener("markas-theme-demo", demo);
this.#stop = () => {
observer.disconnect();
button.removeEventListener("click", click);
document.removeEventListener("markas-theme-demo", demo);
};
}
disconnectedCallback() {
this.#stop();
}
/** Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere. */
#show() {
const button = this.#button;
const theme = pageTheme();
if (!button || theme === this.#shown) return;
this.#shown = theme;
button.dataset.state = theme;
const label = button.querySelector("span");
if (label)
label.textContent =
(theme === "dark"
? this.dataset.lightLabel
: this.dataset.darkLabel) ?? "";
const mode = theme === this.#requested ? SWITCH : SET;
this.#requested = undefined;
play(button, this.#animation, theme === "dark", mode);
}
#toggle(event: MouseEvent) {
if (event.defaultPrevented) return;
const next = pageTheme() === "dark" ? "light" : "dark";
this.#requested = next;
setDark(next);
try {
localStorage.setItem(this.dataset.storageKey ?? "markas-theme", next);
} catch {
// Storage blocked: the theme still applies until the page closes.
}
document.dispatchEvent(
new CustomEvent("markas-theme-change", { detail: next }),
);
}
}
if (!customElements.get("markas-theme-toggle"))
customElements.define("markas-theme-toggle", ThemeToggle);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/theme-toggle.component.ts.
src/app/markas/theme-toggle.component.ts
import {
afterRenderEffect,
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
ElementRef,
inject,
input,
output,
signal,
} from "@angular/core";
const base =
"group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
ghost: "text-ink hover:bg-subtle",
outline: "border border-line bg-surface text-ink hover:bg-subtle",
solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";
/**
* Keyframes from light to dark; dark to light plays them in reverse. Every part that
* differs between the themes is animated, and the last frame stays (fill both).
* Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
*/
const turn = "perspective(60px) rotateY(";
const moves = {
rotate: [
"g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
"g>path|scale:1,1.6,1.6,0",
"svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
],
morph: [
"g>circle|scale:1,1.6",
"mask>circle|translate:24px -12px,15.5px -3.5px",
"g>path|scale:1,0;opacity:1,0|50",
],
flip: [
`svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
"g|opacity:1,1,0,0;offset:0,.5,.5,1",
"svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
],
slide: [
"g|translate:0,0 24px",
"svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
],
eclipse: [
"mask>circle|translate:-6px 0,13.5px -1.5px",
"g>path|scale:1,1.7,.75;opacity:1,.3,.4",
],
spring: [
"svg|scale:1,.6,1.15,.95,1",
"g|opacity:1,1,0,0",
"svg>:nth-child(3)|opacity:0,0,1,1",
"svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
"reverse",
"normal",
"alternate-reverse",
"alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;
type Theme = "light" | "dark";
type Animation = keyof typeof moves;
const html = () => document.documentElement;
const pageTheme = (): Theme =>
html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
html().classList.toggle("dark", theme === "dark");
/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
button: HTMLElement,
animation: Animation,
toDark: boolean,
mode: number,
) {
const still =
mode === SET ||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
for (const move of moves[animation]) {
const [selector = "", frames = "", stagger = 0] = move.split("|");
const keyframes = Object.fromEntries(
frames.split(";").map((frame) => {
const [property, values = ""] = frame.split(":");
return [property, values.split(",")];
}),
) as Parameters<HTMLElement["animate"]>[0];
button.querySelectorAll(selector).forEach((part, i) =>
part.animate(keyframes, {
duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
delay: still ? 0 : i * +stagger,
fill: "both",
iterations: mode === DEMO ? 2 : 1,
direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
}),
);
}
}
/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
let saved: string | null = null;
try {
saved = localStorage.getItem(storageKey);
} catch {
// Storage blocked: fall back to the page and the system setting.
}
if (saved === "light" || saved === "dark") return saved;
return pageTheme() === "dark" ||
window.matchMedia?.("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
export type ThemeToggleAnimation = Animation;
export type ThemeToggleVariant = keyof typeof variants;
export type ThemeToggleSize = keyof typeof sizes;
let nextId = 0;
/**
* Attribute selector on the native button: disabled, aria-*, and the user's class stay on the
* button itself. Follows the html dark class, so every toggle on the page stays in sync.
*/
@Component({
selector: "button[markas-theme-toggle]",
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
"[attr.type]": "type()",
"[attr.data-state]": "current()",
"[class]": "classes()",
"(click)": "toggle($event)",
},
template: `
<svg
[class]="iconClasses()"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<mask [id]="maskId">
<rect width="24" height="24" fill="white" />
<circle cy="12" r="5" fill="black" />
</mask>
<g>
<circle
cx="12"
cy="12"
r="4.5"
stroke="none"
[attr.mask]="'url(#' + maskId + ')'"
/>
@for (deg of rays; track deg) {
<path [style.rotate]="deg + 'deg'" d="M12 2v2" />
}
</g>
<path [class]="hidden" [attr.d]="moonPath" />
@for (d of starPaths; track d) {
<path [class]="hidden" [attr.d]="d" />
}
</svg>
<span [class]="showText() ? '' : srOnly">{{
current() === "dark" ? lightLabel() : darkLabel()
}}</span>
`,
})
export class ThemeToggle {
readonly animation = input<ThemeToggleAnimation>("rotate");
readonly variant = input<ThemeToggleVariant>("ghost");
readonly size = input<ThemeToggleSize>("md");
/** Controlled theme. Leave empty to read localStorage and the system setting. */
readonly theme = input<Theme>();
readonly storageKey = input("markas-theme");
/** Show the label as visible text next to the icon. */
readonly showText = input(false, { transform: booleanAttribute });
readonly lightLabel = input("Switch to light theme");
readonly darkLabel = input("Switch to dark theme");
readonly type = input<"button" | "submit" | "reset">("button");
/** Emits the theme a click asked for. */
readonly themeChange = output<Theme>();
protected readonly rays = rays;
protected readonly hidden = hidden;
protected readonly moonPath = moonPath;
protected readonly starPaths = starPaths;
protected readonly srOnly = srOnly;
protected readonly maskId = `mask-markas-theme-toggle-${nextId++}`;
protected readonly current = signal<Theme | undefined>(undefined);
protected readonly classes = computed(
() =>
`${base} ${variants[this.variant()]} ${sizes[this.size()][+this.showText()]}`,
);
protected readonly iconClasses = computed(
() => `${sizes[this.size()][2]} ${icon}`,
);
private readonly button = inject<ElementRef<HTMLButtonElement>>(ElementRef);
/** The theme a click asked for: reaching it animates, any other change jumps. */
private requested: Theme | undefined;
constructor() {
const destroyRef = inject(DestroyRef);
// Follow the html class, so every toggle on the page and outside changes stay in sync.
afterRenderEffect(() => {
// Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
const target = this.theme() ?? readTheme(this.storageKey());
if (target !== pageTheme()) setDark(target);
this.current.set(pageTheme());
});
if (typeof MutationObserver === "function") {
const observer = new MutationObserver(() =>
this.current.set(pageTheme()),
);
observer.observe(html(), { attributeFilter: ["class"] });
destroyRef.onDestroy(() => observer.disconnect());
}
// Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
afterRenderEffect(() => {
const shown = this.current();
const name = this.animation();
if (!shown) return;
const mode = shown === this.requested ? SWITCH : SET;
this.requested = undefined;
play(this.button.nativeElement, name, shown === "dark", mode);
});
// "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
const demo = () =>
play(
this.button.nativeElement,
this.animation(),
pageTheme() !== "dark",
DEMO,
);
document.addEventListener("markas-theme-demo", demo);
destroyRef.onDestroy(() =>
document.removeEventListener("markas-theme-demo", demo),
);
}
protected toggle(event: MouseEvent) {
if (event.defaultPrevented) return;
const next = pageTheme() === "dark" ? "light" : "dark";
this.requested = next;
if (this.theme() === undefined) {
setDark(next);
try {
localStorage.setItem(this.storageKey(), next);
} catch {
// Storage blocked: the theme still applies until the page closes.
}
document.dispatchEvent(
new CustomEvent("markas-theme-change", { detail: next }),
);
}
this.themeChange.emit(next);
}
}Usage
<x-markas.theme-toggle />
<x-markas.theme-toggle animation="eclipse" variant="outline" size="sm" />
<x-markas.theme-toggle :show-text="true" dark-label="Dark mode" light-label="Light mode" animation="flip" />import { ThemeToggle } from "@/components/markas/ThemeToggle";
<ThemeToggle />
<ThemeToggle animation="eclipse" variant="outline" size="sm" />
<ThemeToggle showText darkLabel="Dark mode" lightLabel="Light mode" animation="flip" onThemeChange={(theme) => console.log(theme)} /><script setup lang="ts">
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
</script>
<template>
<ThemeToggle />
<ThemeToggle animation="eclipse" variant="outline" size="sm" />
<ThemeToggle
show-text
dark-label="Dark mode"
light-label="Light mode"
animation="flip"
@change="(theme) => console.log(theme)"
/>
</template><script lang="ts">
import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
</script>
<ThemeToggle animation="morph" variant="outline" />---
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
---
<ThemeToggle animation="morph" variant="outline" />A small bundled script runs each toggle through the markas-theme-toggle element.
import { Component } from "@angular/core";
import { ThemeToggle } from "./markas/theme-toggle.component";
@Component({
selector: "app-header",
imports: [ThemeToggle],
template: `
<button markas-theme-toggle animation="morph" variant="outline"></button>
`,
})
export class Header {}- The toggle adds or removes the
darkclass on<html>, saves the choice in localStorage (storageKey), and dispatchesmarkas-theme-changeondocumentwith the theme asdetail. - On load it reads the saved choice, then a
darkclass the page already set, thenprefers-color-scheme. Add this to<head>so the page never flashes the wrong theme:
<script>
try {
const saved = localStorage.getItem("markas-theme");
document.documentElement.classList.toggle(
"dark",
saved
? saved === "dark"
: matchMedia("(prefers-color-scheme: dark)").matches,
);
} catch {}
</script>- Animations:
rotate,morph,flip,slide,eclipse,spring. Each click plays keyframes with the Web Animations API (transform and opacity only). Users with reduced motion get an instant swap. documentplays every toggle there and back without changing the theme, handy for a “Play all” button..dispatchEvent(new Event("markas-theme-demo")) - The button keeps its own
data-state(light or dark) and follows thedarkclass on<html>, so several toggles, or a theme set elsewhere, stay in sync.
Props
| Name | Type | Default | Description |
|---|---|---|---|
animation | 'rotate' | 'morph' | 'flip' | 'slide' | 'eclipse' | 'spring' | rotate | Icon animation, played on click with the Web Animations API (transform and opacity only, 650ms). |
variant | 'ghost' | 'outline' | 'solid' | ghost | Visual style. |
size | 'sm' | 'md' | 'lg' | md | Size 32, 40, or 48px, the same heights as Button. |
theme | 'light' | 'dark' | - | Controlled theme in React and Vue: the parent saves it and handles clicks. Blade applies it once on load. |
storageKey | string | markas-theme | localStorage key that keeps the choice. |
showText | boolean | false | Shows the label as visible text next to the icon. Pair it with short labels such as Dark mode. |
lightLabel | string | Switch to light theme | Name while the dark theme is on. Visible text with showText. |
darkLabel | string | Switch to dark theme | Name while the light theme is on. Visible text with showText. |
onThemeChange | (theme: 'light' | 'dark') => void | - | React callback after a click. Vue emits change. Every version also dispatches markas-theme-change on document. |
themeChange | output<"light" | "dark"> | - | Angular only. Emits the theme a click asked for. Svelte uses onThemeChange. |
Accessibility
- A native button element, so Enter and Space work and focus shows a 2px primary outline.
- The name says the action, Switch to dark theme or Switch to light theme, and follows the button data-state.
- The icon is aria-hidden, so screen readers only hear the label.
- With prefers-reduced-motion the icon swaps at once, without animation.
Related components
More markasui components with the same classes in every framework.
- Bottom NavigationMobile app style bottom bar. A pill glides to the selected item, its label rises in, and the bar can shrink to icons while content scrolls.
- Card StackLayered stack of cards. Swipe, arrow keys, or buttons throw the top card away and the next one rises. Loops, with a position indicator.
- Chat MessageMessage in an AI conversation. User bubbles on the right, assistant replies with an avatar, hover actions, a typing indicator, and optional token streaming.
- Currency InputMoney field that formats as you type (Rp 12.500.000), keeps the caret in place, and posts the plain number. Optional quick amount chips.
- DockmacOS style dock. Icons grow smoothly toward the pointer or focus, show a label above, mark open items with a dot, and bounce on launch.
- Drag ElementsArea of cards or stickers you can drag around with light momentum, kept inside its bounds. Arrow keys move a focused item, Escape puts it back.