A–Z Index
A bar of letters over a grouped list: a click glides to the group, an ink pill follows the letter you read, empty letters stay dimmed. Sticks to the top.
View codeA button that switches the page between light and dark, sun to moon. It starts from the system, keeps the visitor's choice, and swaps images that have a night version.
With your AI
Say it to your AI. It gets the exact code below, not its best guess, and knows where it goes.
Add the Kodza Theme Toggle to my page.
claude mcp add -t http kodza https://kodza.dev/api/mcp
<button class="kodza-theme-toggle" type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle>
<svg class="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<g class="kodza-theme-toggle__rays">
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
</g>
<circle class="kodza-theme-toggle__disc" cx="12" cy="12" r="4"/>
</svg>
</button>
<button class="kodza-theme-toggle kodza-theme-toggle--label" type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle>
<svg class="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<g class="kodza-theme-toggle__rays">
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
<path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
</g>
<circle class="kodza-theme-toggle__disc" cx="12" cy="12" r="4"/>
</svg>
<span class="kodza-theme-toggle__words" aria-hidden="true">
<span class="kodza-theme-toggle__word">Light</span>
<span class="kodza-theme-toggle__word">Dark</span>
</span>
</button>
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Theme Toggle
A real button that switches the page between light and dark. Its sun becomes a moon with the
strokes of Morph Icons: the rays draw back into the disc, the disc swells, and a shadow slides
over it from the top right. The page puts its lights out; images that have a night version
(a logo, a screenshot, a lamp lit) get it laid over the day one, in the same box, so nothing
moves and the logo never stays dark on a dark page.
The button shows the theme the page is in: the sun while aria-pressed is false, the moon while it
is true. The script sets it, and keeps every toggle of the page in step.
Everything is tuned with the --kz-theme-toggle-* variables. */
.kodza-theme-toggle {
--kz-theme-toggle-size: 40px;
--kz-theme-toggle-icon: 20px;
--kz-theme-toggle-stroke: 1.75px; /* in icon units, 24 across */
--kz-theme-toggle-ink: #0a0a0a;
--kz-theme-toggle-surface: rgba(10, 10, 10, 0.06); /* the button at rest */
--kz-theme-toggle-hover: rgba(10, 10, 10, 0.11); /* under the pointer */
--kz-theme-toggle-duration: 0.5s;
--kz-theme-toggle-ease: cubic-bezier(0.65, 0, 0.35, 1); /* in and out, so the strokes are seen travelling */
--kz-theme-toggle-recolor: 0s; /* when the ink flips: at once for a page that switches at once, half its
colour transition for one that fades, so it never goes grey on grey */
display: inline-grid;
grid-auto-flow: column;
flex: none;
place-items: center;
box-sizing: border-box;
width: var(--kz-theme-toggle-size);
height: var(--kz-theme-toggle-size);
margin: 0;
padding: 0;
border: 0;
border-radius: var(--kz-radius-pill, 999px);
background: var(--kz-theme-toggle-surface);
color: var(--kz-theme-toggle-ink);
font: inherit;
line-height: 1;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
transition:
background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
color 0s linear calc(var(--kz-theme-toggle-recolor) * var(--kz-motion-scale, 1)),
scale calc(0.15s * var(--kz-motion-scale, 1)) cubic-bezier(0.22, 1, 0.36, 1);
}
.kodza-theme-toggle:focus-visible {
outline: 2px solid var(--kz-theme-toggle-ink);
outline-offset: 3px;
}
.kodza-theme-toggle:active {
scale: 0.94;
}
@media (hover: hover) {
.kodza-theme-toggle:hover {
background: var(--kz-theme-toggle-hover);
}
}
/* With its word: Light or Dark beside the icon, the old word rolls out as the new one comes in */
.kodza-theme-toggle--label {
gap: 8px;
width: auto;
padding: 0 16px 0 12px;
}
.kodza-theme-toggle__words {
display: grid;
overflow: hidden;
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 15px);
font-weight: var(--kz-font-label-weight, 500);
line-height: var(--kz-font-label-leading, 20px);
letter-spacing: var(--kz-font-label-tracking, -0.01em);
text-transform: var(--kz-font-label-case, inherit);
white-space: nowrap;
}
.kodza-theme-toggle__word {
grid-area: 1 / 1;
transition: transform 0s var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle__word + .kodza-theme-toggle__word,
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word {
transform: translateY(105%);
}
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word:first-child {
transform: translateY(-105%);
}
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word + .kodza-theme-toggle__word {
transform: none;
}
/* The icon. The moon's shadow is a hole in a mask that slides over the disc: waiting off the top
right corner on the sun, over the disc on the moon. No id, no animated d, so Safari plays it */
.kodza-theme-toggle__icon {
--kz-theme-toggle-hole: calc(var(--kz-theme-toggle-icon) * 0.2708); /* 6.5 icon units */
display: block;
width: var(--kz-theme-toggle-icon);
height: var(--kz-theme-toggle-icon);
overflow: hidden;
fill: none;
stroke: currentColor;
stroke-width: var(--kz-theme-toggle-stroke);
stroke-linecap: round;
pointer-events: none;
-webkit-mask-image: radial-gradient(circle, transparent calc(var(--kz-theme-toggle-hole) - 0.4px), #000 calc(var(--kz-theme-toggle-hole) + 0.4px));
mask-image: radial-gradient(circle, transparent calc(var(--kz-theme-toggle-hole) - 0.4px), #000 calc(var(--kz-theme-toggle-hole) + 0.4px));
-webkit-mask-size: calc(var(--kz-theme-toggle-icon) * 3) calc(var(--kz-theme-toggle-icon) * 3);
mask-size: calc(var(--kz-theme-toggle-icon) * 3) calc(var(--kz-theme-toggle-icon) * 3);
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
-webkit-mask-position: calc(var(--kz-theme-toggle-icon) * -0.2) calc(var(--kz-theme-toggle-icon) * -1.8);
mask-position: calc(var(--kz-theme-toggle-icon) * -0.2) calc(var(--kz-theme-toggle-icon) * -1.8);
transition-property: -webkit-mask-position, mask-position;
transition-duration: 0s;
transition-timing-function: var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__icon {
-webkit-mask-position: calc(var(--kz-theme-toggle-icon) * -0.8083) calc(var(--kz-theme-toggle-icon) * -1.1917);
mask-position: calc(var(--kz-theme-toggle-icon) * -0.8083) calc(var(--kz-theme-toggle-icon) * -1.1917);
}
.kodza-theme-toggle__disc {
fill: currentColor;
stroke: none;
transform-box: view-box;
transform-origin: 12px 12px;
transition: transform 0s var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__disc {
transform: scale(2.125); /* radius 4 to 8.5 */
}
.kodza-theme-toggle__rays {
transform-box: view-box;
transform-origin: 12px 12px;
transition: transform 0s var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__rays {
transform: rotate(45deg);
}
/* Every ray is the 24-unit line of Morph Icons, M-12 0H12, turned and pushed out from the middle by
a transform; the dash shows 2 units of it: dasharray 2 48, offset 2/2 - 12. On the moon it draws
back towards the disc, shrinks to its middle and thins out with it. The rays go one after the
other from the top right, where the shadow comes in */
.kodza-theme-toggle__ray {
--kz-theme-toggle-turn: 0deg;
--kz-theme-toggle-rank: 1;
transform: translate(12px, 12px) rotate(var(--kz-theme-toggle-turn)) translateX(8.25px);
transform-box: view-box;
transform-origin: 0 0;
stroke-dasharray: 2px 48px;
stroke-dashoffset: -11px;
transition-property: transform, stroke-dasharray, stroke-dashoffset, stroke-width;
transition-duration: 0s;
transition-timing-function: var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle__ray:nth-child(2) { --kz-theme-toggle-turn: 45deg; --kz-theme-toggle-rank: 2; }
.kodza-theme-toggle__ray:nth-child(3) { --kz-theme-toggle-turn: 90deg; --kz-theme-toggle-rank: 3; }
.kodza-theme-toggle__ray:nth-child(4) { --kz-theme-toggle-turn: 135deg; --kz-theme-toggle-rank: 4; }
.kodza-theme-toggle__ray:nth-child(5) { --kz-theme-toggle-turn: 180deg; --kz-theme-toggle-rank: 3; }
.kodza-theme-toggle__ray:nth-child(6) { --kz-theme-toggle-turn: 225deg; --kz-theme-toggle-rank: 2; }
.kodza-theme-toggle__ray:nth-child(7) { --kz-theme-toggle-turn: 270deg; --kz-theme-toggle-rank: 1; }
.kodza-theme-toggle__ray:nth-child(8) { --kz-theme-toggle-turn: 315deg; --kz-theme-toggle-rank: 0; }
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__ray {
transform: translate(12px, 12px) rotate(var(--kz-theme-toggle-turn)) translateX(6px);
stroke-dasharray: 0px 48px;
stroke-dashoffset: -12px;
stroke-width: 0;
}
/* Motion starts once the script is ready, so nothing moves on load. To the moon: the rays first,
then the disc swells and the shadow slides in. Back to the sun: the shadow leaves first, the disc
shrinks, and the rays come back last, the top right one first */
.kodza-theme-toggle.is-ready :is(.kodza-theme-toggle__icon, .kodza-theme-toggle__disc, .kodza-theme-toggle__rays, .kodza-theme-toggle__ray, .kodza-theme-toggle__word) {
transition-duration: calc(var(--kz-theme-toggle-duration) * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready .kodza-theme-toggle__ray {
transition-delay: calc(var(--kz-theme-toggle-duration) * (0.3 + 0.05 * var(--kz-theme-toggle-rank)) * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready .kodza-theme-toggle__disc {
transition-delay: calc(var(--kz-theme-toggle-duration) * 0.1 * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__ray {
transition-delay: calc(var(--kz-theme-toggle-duration) * 0.05 * var(--kz-theme-toggle-rank) * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__disc {
transition-delay: calc(var(--kz-theme-toggle-duration) * 0.08 * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__icon {
transition-delay: calc(var(--kz-theme-toggle-duration) * 0.18 * var(--kz-motion-scale, 1));
}
/* Night images, outside the button: the script wraps each img[data-dark-src] of the page in a pair,
the day image and its night twin in the same grid cell. The night one lights up over the day one,
which fades out under it, so a logo with a transparent background never shows both */
.kodza-theme-toggle-pair {
--kz-theme-toggle-fade: 0.6s;
--kz-theme-toggle-lag: 0.12s; /* the lamp comes on just after the page goes dark (none on the way back) */
display: inline-grid;
max-width: 100%;
}
.kodza-theme-toggle-pair--block {
display: grid;
grid-template-columns: minmax(0, 1fr);
}
.kodza-theme-toggle-pair > img {
grid-area: 1 / 1;
}
.kodza-theme-toggle-night {
opacity: 0;
pointer-events: none;
}
.kodza-theme-toggle-pair.is-night > img:first-child {
opacity: 0;
}
.kodza-theme-toggle-pair.is-night > .kodza-theme-toggle-night {
opacity: 1;
}
/* Back to day, no wait: both images turn with the page, so the night one never lingers on a white page */
.kodza-theme-toggle-pair.is-ready > img {
transition: opacity calc(var(--kz-theme-toggle-fade) * var(--kz-motion-scale, 1)) cubic-bezier(0.65, 0, 0.35, 1);
}
/* To night, the lamp comes on just after the page has gone dark */
.kodza-theme-toggle-pair.is-ready.is-night > img {
transition: opacity calc(var(--kz-theme-toggle-fade) * var(--kz-motion-scale, 1)) cubic-bezier(0.55, 0, 1, 0.45) calc(var(--kz-theme-toggle-lag) * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle-pair.is-ready.is-night > .kodza-theme-toggle-night {
transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
}
@media (prefers-reduced-motion: reduce) {
.kodza-theme-toggle,
.kodza-theme-toggle *,
.kodza-theme-toggle-pair > img {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
/* kodza-guard 171ad3d0177f — generated by Kodza, do not edit.
Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
component. :not(#_) is always true and weighs as much as an id, so these lines win over
theme rules made of classes and tags. Customise the component through its --kz-* variables. */
/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */
:where(.kodza-theme-toggle):not(#_) {
outline: revert;
outline-offset: revert;
}
:where(.kodza-theme-toggle__icon):not(#_) {
transition-delay: revert;
}
/* What the browser gives, on everything the component leaves to it */
.kodza-theme-toggle:not(#_) {
text-decoration: revert;
list-style: revert;
position: revert;
box-shadow: revert;
appearance: revert;
max-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
white-space: revert;
min-height: revert;
}
.kodza-theme-toggle__icon:not(#_) {
border: revert;
margin: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
list-style: revert;
box-sizing: revert;
float: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
color: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-theme-toggle__rays:not(#_),
.kodza-theme-toggle__ray:not(#_),
.kodza-theme-toggle__disc:not(#_),
.kodza-theme-toggle__words:not(#_),
.kodza-theme-toggle__word:not(#_) {
box-sizing: revert;
}
/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */
.kodza-theme-toggle:not(#_) {
display: inline-grid;
grid-auto-flow: column;
flex: none;
place-items: center;
box-sizing: border-box;
width: var(--kz-theme-toggle-size);
height: var(--kz-theme-toggle-size);
margin: 0;
padding: 0;
border: 0;
border-radius: var(--kz-radius-pill, 999px);
background: var(--kz-theme-toggle-surface);
color: var(--kz-theme-toggle-ink);
font: inherit;
line-height: 1;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
transition: background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
color 0s linear calc(var(--kz-theme-toggle-recolor) * var(--kz-motion-scale, 1)),
scale calc(0.15s * var(--kz-motion-scale, 1)) cubic-bezier(0.22, 1, 0.36, 1);
}
.kodza-theme-toggle:focus-visible:not(#_) {
outline: 2px solid var(--kz-theme-toggle-ink);
outline-offset: 3px;
}
.kodza-theme-toggle:active:not(#_) {
scale: 0.94;
}
@media (hover: hover) {
.kodza-theme-toggle:hover:not(#_) {
background: var(--kz-theme-toggle-hover);
}
}
.kodza-theme-toggle--label:not(#_) {
gap: 8px;
width: auto;
padding: 0 16px 0 12px;
}
.kodza-theme-toggle__icon:not(#_) {
display: block;
transition-property: -webkit-mask-position, mask-position;
transition-duration: 0s;
transition-timing-function: var(--kz-theme-toggle-ease);
}
.kodza-theme-toggle.is-ready :is(.kodza-theme-toggle__icon, .kodza-theme-toggle__disc, .kodza-theme-toggle__rays, .kodza-theme-toggle__ray, .kodza-theme-toggle__word):where(svg):not(#_) {
transition-duration: calc(var(--kz-theme-toggle-duration) * var(--kz-motion-scale, 1));
}
.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__icon:not(#_) {
transition-delay: calc(var(--kz-theme-toggle-duration) * 0.18 * var(--kz-motion-scale, 1));
}
@media (prefers-reduced-motion: reduce) {
.kodza-theme-toggle:not(#_) {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
@media (prefers-reduced-motion: reduce) {
.kodza-theme-toggle *:where(svg):not(#_) {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Theme Toggle
// Switches the page between light and dark. The theme is written where the site reads it, on <html>
// by default as data-theme="dark" or "light". It starts from the visitor's saved choice, else from
// what the page already says, else from the system setting, which it keeps following until the
// visitor makes a choice. Every toggle on the page stays in step, other tabs too. Images with a night
// version (data-dark-src) get it laid over the day one, loaded the first time the page goes dark.
// Settings, on the button: data-target (the element that carries the theme: by default the nearest
// one around the button that already has the attribute, else <html>), data-attribute (the attribute
// written, "data-theme" by default) or data-class (a class added in the dark, such as "dark",
// instead of the attribute), data-storage (the localStorage key, "kodza-theme" by default; empty,
// nothing is saved). A toggle that themes one part of the page (a section with its own data-theme)
// saves nothing unless data-storage says where, and keeps its theme when the system changes.
//
// Against a white flash on load, put this line in a script tag at the top of <head>, before the
// stylesheets (same key and attribute as the button):
// try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){}
(() => {
const SELECTOR = '[data-kodza-theme-toggle]';
const TARGET = 'html'; // the element that carries the theme, when none around the button has it
const ATTRIBUTE = 'data-theme'; // written "dark" or "light" on it
const STORAGE = 'kodza-theme'; // where the visitor's choice is kept
const NIGHT = 'img[data-dark-src]'; // images that have a night version
// Shared by every toggle of the page, whichever copy of this script started it
const PAIRED = Symbol.for('kodza theme-toggle pair'); // on an image already given its night twin
const CHOSEN = Symbol.for('kodza theme-toggle chosen'); // on a target whose theme the visitor picked
const system = window.matchMedia('(prefers-color-scheme: dark)');
const valid = (theme) => (theme === 'dark' || theme === 'light' ? theme : null);
// One instance, with its own state: two copies on a page never interfere. Everything it
// starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
// 'abort' event), so kodza:destroy stops it all.
function mount(root, signal) {
const name = root.dataset.class;
const attribute = root.dataset.attribute || ATTRIBUTE;
const selector = root.dataset.target || (name ? TARGET : `[${attribute}]`);
const target = root.closest(selector) || document.querySelector(root.dataset.target || TARGET) || document.documentElement;
const page = target === document.documentElement;
const key = root.hasAttribute('data-storage') ? root.dataset.storage : page ? STORAGE : '';
const pairs = new Set(); // the pairs this toggle made, taken apart on destroy
let live = false; // after the start, a change of theme is seen happening
const stored = () => {
if (!key) return null;
try { return valid(localStorage.getItem(key)); } catch { return null; }
};
const store = (theme) => {
if (!key) return;
try { localStorage.setItem(key, theme); } catch { /* private mode: the choice lasts the page */ }
};
const given = () => (name ? (target.classList.contains(name) ? 'dark' : null) : valid(target.getAttribute(attribute)));
const read = () => given() || 'light';
const preferred = () => (system.matches ? 'dark' : 'light');
// Each night image goes in a pair with its day one, the night twin a clone that keeps its
// classes and size, so it lands exactly on top
const pairUp = () => target.querySelectorAll(NIGHT).forEach((img) => {
if (img[PAIRED] || img.classList.contains('kodza-theme-toggle-night')) return;
const pair = document.createElement('span');
pair.className = 'kodza-theme-toggle-pair';
if (getComputedStyle(img).display === 'block') pair.classList.add('kodza-theme-toggle-pair--block');
const night = img.cloneNode(false);
['id', 'src', 'srcset', 'sizes', 'loading', 'fetchpriority', 'data-dark-src'].forEach((attr) => night.removeAttribute(attr));
night.alt = '';
night.setAttribute('aria-hidden', 'true');
night.classList.add('kodza-theme-toggle-night');
img.replaceWith(pair);
pair.append(img, night);
img[PAIRED] = pair;
pairs.add(pair);
});
// The night twins light up once their image is decoded, never as an empty box
const shade = (dark) => target.querySelectorAll('.kodza-theme-toggle-pair').forEach((pair) => {
const [img, night] = pair.children;
if (!night) return;
if (live) pair.classList.add('is-ready');
if (!dark) return pair.classList.remove('is-night');
if (!night.getAttribute('src')) night.src = img.dataset.darkSrc;
night.decode().catch(() => {}).then(() => {
if (!signal.aborted && read() === 'dark') pair.classList.add('is-night');
});
});
const sync = () => {
const theme = read();
root.setAttribute('aria-pressed', String(theme === 'dark'));
pairUp();
shade(theme === 'dark');
};
const apply = (theme) => {
if (given() !== theme) {
if (name) target.classList.toggle(name, theme === 'dark');
else target.setAttribute(attribute, theme);
}
sync();
};
// The visitor's choice first, then what the page says (the line in <head> wrote it), then the system
const follows = page || !given(); // a part of the page with its own theme keeps it
apply(stored() || given() || preferred());
live = true;
// Whoever changes the theme (another toggle, the site's own script), this button follows
const observer = new MutationObserver(sync);
observer.observe(target, { attributes: true, attributeFilter: [name ? 'class' : attribute] });
root.addEventListener('click', () => {
const theme = read() === 'dark' ? 'light' : 'dark';
target[CHOSEN] = true;
store(theme);
apply(theme);
root.dispatchEvent(new CustomEvent('kodza:theme-toggle', { bubbles: true, detail: { theme } }));
}, { signal });
system.addEventListener('change', () => {
if (follows && !target[CHOSEN] && !stored()) apply(preferred());
}, { signal });
// Chosen in another tab
window.addEventListener('storage', (event) => {
if (key && event.key === key) apply(valid(event.newValue) || preferred());
}, { signal });
signal.addEventListener('abort', () => {
observer.disconnect();
pairs.forEach((pair) => {
const img = pair.firstElementChild;
delete img[PAIRED];
pair.replaceWith(img);
});
});
}
// Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
// event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
// markup back. For themes and apps that swap content without a page load. Each running root
// keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
// component inside another one is saved as written, not half-started, and stopped with it. Two
// components on one root (a reveal on a stat card) both start, and stop together.
const KODZA = Symbol.for('kodza');
const RUNNING = Symbol.for(`kodza ${SELECTOR}`); // a root this component runs on, for every copy of this script
const instances = new WeakMap();
const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
const put = (el, saved) => {
[...el.attributes].forEach((a) => el.removeAttribute(a.name));
saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
el.innerHTML = saved.html;
};
// The markup inside a root as written: Kodza components already running in it give back their own
const written = (root) => {
const all = [...root.querySelectorAll('*')];
if (!all.some((el) => el[KODZA])) return root.innerHTML;
const copy = root.cloneNode(true);
const twins = copy.querySelectorAll('*');
let last = null;
all.forEach((el, i) => {
if (!el[KODZA] || last?.contains(el)) return;
last = el;
put(twins[i], el[KODZA]);
});
return copy.innerHTML;
};
const init = (scope) => find(scope).forEach((root) => {
// Already running, maybe from another copy of this script. Marked is-ready with no Kodza component
// running on it, a root is a copy of a started one (a cloned slide): it is left as it is
if (root[RUNNING] || (root.classList.contains('is-ready') && !root[KODZA])) return;
// Rendered by React (data-kodza-manual): React starts it, with an init aimed at that markup once
// it has hydrated it. Any earlier start would change markup React has not taken over yet
const owner = root.closest('[data-kodza-manual]');
if (owner && !(scope && owner.contains(scope))) return;
const controller = new AbortController();
// Another Kodza component already running on this root: its markup as written is kept, and the
// two stop together
const before = root[KODZA];
const saved = { html: before ? before.html : written(root), attrs: before ? before.attrs : attrsOf(root), stop: () => destroy(root) };
if (before) before.above = saved;
instances.set(root, { controller, saved, before });
root[KODZA] = saved;
root[RUNNING] = true;
mount(root, controller.signal);
root.classList.add('is-ready');
});
const destroy = (scope) => find(scope).forEach((root) => {
const instance = instances.get(root);
if (!instance) return;
instances.delete(root);
instance.saved.above?.stop(); // a Kodza component started after it on the same root stops first
// The Kodza components running inside it stop first: once its markup is put back, their own
// script could not find them any more
root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
instance.controller.abort();
delete root[RUNNING];
// Started on top of another one: that one stops next, and puts the markup back
if (instance.before) {
delete instance.before.above;
root[KODZA] = instance.before;
return instance.before.stop();
}
delete root[KODZA];
put(root, instance.saved);
});
document.addEventListener('kodza:init', (event) => init(event.detail?.root));
document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
init();
// Loaded in <head>, the script runs before the markup exists: once more when it is parsed
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
'use client';
// Kodza — Theme Toggle, for React. From https://kodza.dev/components/theme-toggle/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: theme-toggle.css and theme-toggle.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// data-kodza-manual keeps the script from starting it on its own: the effect below does, once
// React has hydrated the markup (on a page that streams in, the script can load first).
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './theme-toggle.css';
type Variant = "label";
export type ThemeToggleProps = Omit<ComponentPropsWithoutRef<'button'>, "children" | "variant" | "vars" | "onThemeToggle"> & {
/** Modifier class(es): .kodza-theme-toggle--label */
variant?: Variant | Variant[];
/** Settings, as CSS variables on the root */
vars?: {
/** default: 40px */
"--kz-theme-toggle-size"?: string | number;
/** default: 20px */
"--kz-theme-toggle-icon"?: string | number;
/** in icon units, 24 across — default: 1.75px */
"--kz-theme-toggle-stroke"?: string | number;
/** default: #0a0a0a */
"--kz-theme-toggle-ink"?: string | number;
/** the button at rest — default: rgba(10, 10, 10, 0.06) */
"--kz-theme-toggle-surface"?: string | number;
/** under the pointer — default: rgba(10, 10, 10, 0.11) */
"--kz-theme-toggle-hover"?: string | number;
/** default: 0.5s */
"--kz-theme-toggle-duration"?: string | number;
/** in and out, so the strokes are seen travelling — default: cubic-bezier(0.65, 0, 0.35, 1) */
"--kz-theme-toggle-ease"?: string | number;
/** when the ink flips: at once for a page that switches at once, half its
colour transition for one that fades, so it never goes grey on grey — default: 0s */
"--kz-theme-toggle-recolor"?: string | number;
};
/** "kodza:theme-toggle", fired by the script (bubbles from the root) */
onThemeToggle?: (event: CustomEvent) => void;
className?: string;
};
export function ThemeToggle({ variant, vars, onThemeToggle, className, style, ...rest }: ThemeToggleProps) {
const ref = useRef<ComponentRef<'button'>>(null);
const classes = ["kodza-theme-toggle", ...([] as string[]).concat(variant ?? []).map((v) => `kodza-theme-toggle--${v}`), className].filter(Boolean).join(' ');
// Everything the markup is made of: when it changes, React gets a fresh element (see the top)
const key = JSON.stringify([classes, vars, style, rest]);
// Starts the script on this element once React has rendered it, stops it when it goes
useEffect(() => {
const root = ref.current;
let live = true;
// @ts-ignore: a plain script, no types to find
import('./theme-toggle.js').then(() => {
if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
});
return () => {
live = false;
document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
};
}, [key]);
useEffect(() => {
const root = ref.current;
if (!root || !onThemeToggle) return;
const listener = (event: Event) => onThemeToggle(event as CustomEvent);
root.addEventListener("kodza:theme-toggle", listener);
return () => root.removeEventListener("kodza:theme-toggle", listener);
}, [onThemeToggle, key]);
return (
<button type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle="" key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
<svg className="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<g className="kodza-theme-toggle__rays">
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
<path className="kodza-theme-toggle__ray" d="M-12 0H12" />
</g>
<circle className="kodza-theme-toggle__disc" cx="12" cy="12" r="4" />
</svg>
</button>
);
}
Checked
Robots poked at it before you did. Every component goes through the same checks, and again each time it changes.