Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/ThemeContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import './styles/theme-transition.css';

type Theme = 'light' | 'dark' | 'system';

Expand All @@ -22,6 +23,16 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
return (resolvedTheme === 'light' || resolvedTheme === 'dark') ? resolvedTheme : 'dark';
});

// Enable color-token transitions only after the first paint, so the initial
// theme is applied instantly (no flash) while subsequent switches animate.
useEffect(() => {
const root = window.document.documentElement;
const id = window.requestAnimationFrame(() => {
root.classList.add('theme-transitions-ready');
});
return () => window.cancelAnimationFrame(id);
}, []);

useEffect(() => {
localStorage.setItem('callora-theme', theme);

Expand Down
31 changes: 31 additions & 0 deletions src/styles/theme-transition.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* theme-transition.css
*
* Smooth the light <-> dark theme switch by animating the color tokens
* (background, text and border colors) instead of swapping them instantly.
*
* The transition is only active once the ThemeProvider has mounted and added
* the `theme-transitions-ready` class to <html>. This prevents the colors from
* animating on the very first paint (which would otherwise look like a flash
* of the wrong theme fading in).
*/

html.theme-transitions-ready,
html.theme-transitions-ready body,
html.theme-transitions-ready *:not(.no-theme-transition) {
transition:
background-color var(--transition-speed, 240ms) ease,
border-color var(--transition-speed, 240ms) ease,
color var(--transition-speed, 240ms) ease,
fill var(--transition-speed, 240ms) ease,
stroke var(--transition-speed, 240ms) ease;
}

/* Respect users who prefer reduced motion: switch instantly. */
@media (prefers-reduced-motion: reduce) {
html.theme-transitions-ready,
html.theme-transitions-ready body,
html.theme-transitions-ready * {
transition: none !important;
}
}