Files
superlist/apps/web/src/components/theme-provider.tsx
Jose Selesan 86d4796d88 fix(web): reload the installed iOS app when the theme changes
An iOS home-screen app only reads theme-color on page load, so updating
the meta in place left the status bar with the previous theme's color.
Reload when the resolved theme changes; the pre-paint script applies the
stored theme before the first paint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:10:03 -03:00

108 lines
3.7 KiB
TypeScript

import type { ReactNode } from 'react'
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
export type Theme = 'light' | 'dark' | 'system'
type ResolvedTheme = Exclude<Theme, 'system'>
type ThemeContextValue = {
/** The preference the user picked, `system` included. */
theme: Theme
/** The preference already resolved against the OS setting. */
resolvedTheme: ResolvedTheme
setTheme: (theme: Theme) => void
}
const STORAGE_KEY = 'superlist-theme'
const DARK_QUERY = '(prefers-color-scheme: dark)'
/** Browser chrome color (the iOS status bar) per theme. Keep in sync with `index.html`. */
const THEME_COLORS: Record<ResolvedTheme, string> = { light: '#f9f8f5', dark: '#0f1411' }
/**
* This theme handling is hand-rolled on purpose. Libraries such as `next-themes`
* avoid the pre-paint flash by rendering a `<script>` from React, but React 19
* never executes scripts rendered by components (it even logs a warning). Since
* this app is client-rendered, the flash is prevented by the static script in
* `index.html`, which runs before React mounts and uses this same storage key
* and `.dark` class.
*/
const ThemeContext = createContext<ThemeContextValue>({
theme: 'system',
resolvedTheme: 'light',
setTheme: () => {},
})
function readStoredTheme(): Theme {
try {
const stored = window.localStorage.getItem(STORAGE_KEY)
if (stored === 'light' || stored === 'dark' || stored === 'system') return stored
} catch {
// Storage can be unavailable (private mode, blocked cookies); fall back to system.
}
return 'system'
}
function systemTheme(): ResolvedTheme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'
}
function resolveTheme(theme: Theme): ResolvedTheme {
return theme === 'system' ? systemTheme() : theme
}
/** iOS home-screen app (`navigator.standalone` only exists in iOS Safari). */
function isIosStandalone() {
return 'standalone' in navigator && navigator.standalone === true
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
const resolvedTheme: ResolvedTheme = theme === 'system' ? (systemDark ? 'dark' : 'light') : theme
useEffect(() => {
const media = window.matchMedia(DARK_QUERY)
const onChange = (event: MediaQueryListEvent) => setSystemDark(event.matches)
media.addEventListener('change', onChange)
return () => media.removeEventListener('change', onChange)
}, [])
useEffect(() => {
const root = document.documentElement
root.classList.toggle('dark', resolvedTheme === 'dark')
root.style.colorScheme = resolvedTheme
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', THEME_COLORS[resolvedTheme])
}, [resolvedTheme])
const setTheme = useCallback(
(next: Theme) => {
setThemeState(next)
try {
window.localStorage.setItem(STORAGE_KEY, next)
} catch {
// Ignore storage failures: the theme still applies for this session.
}
// An installed iOS app only reads `theme-color` when the page loads, so
// the status bar keeps the old color until a reload. The stored theme is
// applied again before the first paint by the script in `index.html`.
if (isIosStandalone() && resolveTheme(next) !== resolvedTheme) window.location.reload()
},
[resolvedTheme],
)
const value = useMemo(
() => ({ theme, resolvedTheme, setTheme }),
[theme, resolvedTheme, setTheme],
)
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}
export function useTheme() {
return useContext(ThemeContext)
}