mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-22 07:56:18 -05:00
ui: theme tokens and a four-theme runtime
Every color now resolves through CSS custom properties on html[data-theme=...], so a theme is a table of values rather than code. Four themes ship: light, dark, night (red hues only, to preserve dark adaptation off-grid) and amber (monochrome amber terminal). Fonts are exposed as two roles, --font-body and --font-mono, which a theme assigns a bundled face to; amber uses the mono face. Faces must be self-hosted, never fetched from a CDN, so the app keeps working offline. Night mode also filters media that cannot consume tokens - video, images, PDFs, embedded pages, canvases - through an SVG color matrix that maps luminance onto the red channel. Tag such an element with `.media`; a filter on an app-level ancestor would create a containing block and break fixed positioning. ThemeProvider persists the choice and index.html stamps data-theme from localStorage before the bundle loads, so the first paint already matches the saved theme on a slow connection. The OS preference is followed only while "system" is selected; night and amber are explicit choices. The nav toggle becomes a five-item picker. Semantic components still render themselves, so only the shell is token-driven for now; the inverted props stay in place until each component is migrated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
616424b223
commit
806727023d
12 changed files with 669 additions and 92 deletions
|
|
@ -9,6 +9,7 @@ import {
|
|||
Container,
|
||||
Dimmer,
|
||||
DimmerDimmable,
|
||||
Dropdown,
|
||||
GridColumn,
|
||||
GridRow,
|
||||
Icon as SIcon,
|
||||
|
|
@ -25,6 +26,7 @@ import {useBluetooth, useDesktop, useHotspot, useSearchDirectories, useSearchOrd
|
|||
import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts";
|
||||
import {
|
||||
Accordion,
|
||||
amberTheme,
|
||||
Breadcrumb,
|
||||
Button,
|
||||
Card as ThemedCard,
|
||||
|
|
@ -37,9 +39,11 @@ import {
|
|||
Loader,
|
||||
Menu,
|
||||
Modal,
|
||||
nightTheme,
|
||||
Popup,
|
||||
Segment,
|
||||
Statistic
|
||||
Statistic,
|
||||
systemTheme
|
||||
} from "./Theme";
|
||||
import {FilePreviewContext} from "./FilePreview";
|
||||
import _ from "lodash";
|
||||
|
|
@ -1378,20 +1382,37 @@ export function LoadStatistic({label, value, cores, ...props}) {
|
|||
{...props}/>;
|
||||
}
|
||||
|
||||
export function DarkModeToggle() {
|
||||
const {savedTheme, cycleSavedTheme} = useContext(ThemeContext);
|
||||
let iconName = 'lightbulb outline';
|
||||
if (savedTheme === darkTheme) {
|
||||
iconName = 'moon';
|
||||
} else if (savedTheme === lightTheme) {
|
||||
iconName = 'sun';
|
||||
}
|
||||
// Theme picker entries. `night` and `amber` are only reachable here; neither is ever applied
|
||||
// automatically. See ui-design.md.
|
||||
const themeChoices = [
|
||||
{value: systemTheme, text: 'System', icon: 'lightbulb outline'},
|
||||
{value: lightTheme, text: 'Light', icon: 'sun'},
|
||||
{value: darkTheme, text: 'Dark', icon: 'moon'},
|
||||
{value: nightTheme, text: 'Night', icon: 'eye'},
|
||||
{value: amberTheme, text: 'Amber', icon: 'terminal'},
|
||||
];
|
||||
|
||||
return <Icon
|
||||
name={iconName}
|
||||
onClick={cycleSavedTheme}
|
||||
style={{cursor: 'pointer', marginRight: '0.8em'}}
|
||||
/>
|
||||
export function DarkModeToggle() {
|
||||
const {savedTheme, setTheme} = useContext(ThemeContext);
|
||||
const active = themeChoices.find(i => i.value === savedTheme) || themeChoices[0];
|
||||
|
||||
return <Dropdown
|
||||
item
|
||||
icon={<Icon name={active.icon} style={{margin: 0}}/>}
|
||||
title={`Theme: ${active.text}`}
|
||||
style={{padding: 0, marginRight: '0.8em'}}
|
||||
>
|
||||
<Dropdown.Menu>
|
||||
<Dropdown.Header content='Theme'/>
|
||||
{themeChoices.map(choice => <Dropdown.Item
|
||||
key={choice.value}
|
||||
icon={choice.icon}
|
||||
text={choice.text}
|
||||
active={choice.value === active.value}
|
||||
onClick={() => setTheme(choice.value)}
|
||||
/>)}
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -100,10 +100,47 @@ import {ThemeContextValue, ThemeName, SavedThemeName} from "../types/theme";
|
|||
|
||||
export const darkTheme = 'dark';
|
||||
export const lightTheme = 'light';
|
||||
export const nightTheme = 'night';
|
||||
export const amberTheme = 'amber';
|
||||
export const defaultTheme = lightTheme;
|
||||
export const systemTheme = 'system';
|
||||
export const themeSessionKey = 'color-scheme';
|
||||
|
||||
// Every theme a user can apply, in the order the theme picker offers them.
|
||||
export const themeNames: ThemeName[] = [lightTheme, darkTheme, nightTheme, amberTheme];
|
||||
// Themes built on a dark background. Semantic components are `inverted` in these.
|
||||
const darkThemes: ThemeName[] = [darkTheme, nightTheme, amberTheme];
|
||||
// Themes a user must choose deliberately; `prefers-color-scheme` never picks them.
|
||||
const explicitOnlyThemes: ThemeName[] = [nightTheme, amberTheme];
|
||||
|
||||
export const isDarkTheme = (theme: ThemeName): boolean => darkThemes.includes(theme);
|
||||
|
||||
const isThemeName = (value: unknown): value is ThemeName => themeNames.includes(value as ThemeName);
|
||||
|
||||
/** Resolve the saved preference to the theme that should be applied right now. */
|
||||
export const resolveTheme = (saved: SavedThemeName): ThemeName => {
|
||||
if (isThemeName(saved)) {
|
||||
return saved;
|
||||
}
|
||||
// `system`, null, or a value written by an older version.
|
||||
const prefersDark = typeof window.matchMedia === 'function'
|
||||
&& window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
return prefersDark ? darkTheme : lightTheme;
|
||||
}
|
||||
|
||||
const readSavedTheme = (): SavedThemeName => {
|
||||
try {
|
||||
const value = localStorage.getItem(themeSessionKey);
|
||||
if (isThemeName(value) || value === systemTheme) {
|
||||
return value;
|
||||
}
|
||||
} catch (e) {
|
||||
// localStorage can throw when cookies/storage are blocked.
|
||||
console.error('Unable to read the saved theme', e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface ThemeProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
|
@ -114,98 +151,89 @@ export function ThemeProvider({children, ...props}: ThemeProviderProps) {
|
|||
console.error('ThemeWrapper does not support props!');
|
||||
}
|
||||
|
||||
// Properties to manipulate elements with theme.
|
||||
// Invert when Semantic supports it. Example: <Menu {...i}>
|
||||
const [i, setI] = useState<{inverted?: boolean}>({});
|
||||
// Invert style when Semantic does not support it. Example: <p {...s}>This paragraph changes style</p>
|
||||
const [s, setS] = useState<{style?: CSSProperties}>({});
|
||||
// Invert text when Semantic does not support it.
|
||||
const [t, setT] = useState<{style?: CSSProperties}>({});
|
||||
const [inverted, setInverted] = useState<string>('');
|
||||
// savedTheme is the user's preference: a theme name, `system`, or null (never chosen).
|
||||
const [savedTheme, setSavedTheme] = useState<SavedThemeName>(readSavedTheme);
|
||||
// theme is what is currently applied.
|
||||
const [theme, setThemeName] = useState<ThemeName>(() => resolveTheme(readSavedTheme()));
|
||||
|
||||
// theme can be one of [darkTheme, lightTheme]
|
||||
const [theme, setTheme] = useState<ThemeName>(lightTheme);
|
||||
// savedTheme can be one of [null, darkTheme, lightTheme, systemTheme]
|
||||
const [savedTheme, setSavedTheme] = useState<SavedThemeName>(
|
||||
localStorage.getItem('color-scheme') as SavedThemeName
|
||||
);
|
||||
// `data-theme` on <html> is what the token CSS keys off of. index.html stamps it before
|
||||
// first paint from the same localStorage value, so the first render already matches.
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
}, [theme]);
|
||||
|
||||
const setDarkTheme = (save = false) => {
|
||||
console.debug('setDarkTheme');
|
||||
setI({inverted: true});
|
||||
setS({style: {backgroundColor: '#1B1C1D', color: '#dddddd'}});
|
||||
setT({style: {color: '#eeeeee'}});
|
||||
setInverted('inverted');
|
||||
setTheme(darkTheme);
|
||||
document.body.style.background = '#171616';
|
||||
if (save) {
|
||||
saveTheme(darkTheme);
|
||||
// Follow the OS preference only while the user has not chosen a specific theme.
|
||||
useEffect(() => {
|
||||
if (isThemeName(savedTheme) || typeof window.matchMedia !== 'function') {
|
||||
return;
|
||||
}
|
||||
const query = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const onChange = () => setThemeName(resolveTheme(savedTheme));
|
||||
query.addEventListener('change', onChange);
|
||||
return () => query.removeEventListener('change', onChange);
|
||||
}, [savedTheme]);
|
||||
|
||||
const saveTheme = (value: SavedThemeName) => {
|
||||
setSavedTheme(value);
|
||||
try {
|
||||
if (value === null) {
|
||||
localStorage.removeItem(themeSessionKey);
|
||||
} else {
|
||||
localStorage.setItem(themeSessionKey, value);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Unable to save the theme', e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply and persist a theme. Pass `system` to follow the OS preference. */
|
||||
const setTheme = (value: SavedThemeName) => {
|
||||
if (value !== systemTheme && value !== null && !isThemeName(value)) {
|
||||
console.error(`Unknown theme! ${value}`);
|
||||
return;
|
||||
}
|
||||
saveTheme(value);
|
||||
setThemeName(resolveTheme(value));
|
||||
}
|
||||
|
||||
// Retained for callers written against the old two-theme API.
|
||||
const setDarkTheme = (save = false) => {
|
||||
setThemeName(darkTheme);
|
||||
if (save) saveTheme(darkTheme);
|
||||
}
|
||||
|
||||
const setLightTheme = (save = false) => {
|
||||
console.debug('setLightTheme');
|
||||
setI({inverted: undefined});
|
||||
setS({});
|
||||
setT({});
|
||||
setInverted('');
|
||||
setTheme(lightTheme);
|
||||
document.body.style.background = '#FFFFFF';
|
||||
if (save) {
|
||||
saveTheme(lightTheme);
|
||||
}
|
||||
}
|
||||
|
||||
const saveTheme = (value: ThemeName) => {
|
||||
setSavedTheme(value);
|
||||
localStorage.setItem(themeSessionKey, value);
|
||||
setThemeName(lightTheme);
|
||||
if (save) saveTheme(lightTheme);
|
||||
}
|
||||
|
||||
const cycleSavedTheme = (e?: React.MouseEvent) => {
|
||||
// Cycle: System -> Dark -> Light
|
||||
// Cycle: System -> Light -> Dark -> Night -> Amber -> System
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
}
|
||||
if (savedTheme === systemTheme || savedTheme == null) {
|
||||
saveTheme(darkTheme);
|
||||
} else if (savedTheme === darkTheme) {
|
||||
saveTheme(lightTheme);
|
||||
} else if (savedTheme === lightTheme) {
|
||||
saveTheme(systemTheme as ThemeName);
|
||||
} else {
|
||||
console.error(`Unknown theme! savedTheme=${savedTheme}`);
|
||||
}
|
||||
applyTheme();
|
||||
const order: SavedThemeName[] = [systemTheme, ...themeNames];
|
||||
const current = order.indexOf(isThemeName(savedTheme) ? savedTheme : systemTheme);
|
||||
setTheme(order[(current + 1) % order.length]);
|
||||
}
|
||||
|
||||
const matchTheme = (): ThemeName => {
|
||||
// Returns darkTheme if saved theme is dark, lightTheme if saved theme is dark,
|
||||
// darkTheme if system prefers dark, otherwise lightTheme.
|
||||
const colorScheme = localStorage.getItem(themeSessionKey);
|
||||
setSavedTheme(colorScheme as SavedThemeName);
|
||||
if (colorScheme === darkTheme) {
|
||||
return darkTheme;
|
||||
} else if (colorScheme === lightTheme) {
|
||||
return lightTheme
|
||||
}
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? darkTheme : lightTheme;
|
||||
const dark = isDarkTheme(theme);
|
||||
|
||||
// Compatibility layer for components which have not been migrated to tokens yet. Semantic
|
||||
// has no concept of the night/amber themes, so they reuse its dark treatment while pulling
|
||||
// their colors from the tokens. These values disappear with the last Semantic component.
|
||||
const i = dark ? {inverted: true} : {inverted: undefined};
|
||||
const inverted = dark ? 'inverted' : '';
|
||||
let s: {style?: CSSProperties} = {};
|
||||
let t: {style?: CSSProperties} = {};
|
||||
if (theme === darkTheme) {
|
||||
s = {style: {backgroundColor: '#1B1C1D', color: '#dddddd'}};
|
||||
t = {style: {color: '#eeeeee'}};
|
||||
} else if (explicitOnlyThemes.includes(theme)) {
|
||||
s = {style: {backgroundColor: 'var(--panel)', color: 'var(--text)'}};
|
||||
t = {style: {color: 'var(--text)'}};
|
||||
}
|
||||
|
||||
const applyTheme = () => {
|
||||
const match = matchTheme();
|
||||
if (match === darkTheme) {
|
||||
setDarkTheme();
|
||||
} else {
|
||||
setLightTheme();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
applyTheme();
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applyTheme);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const themeValue: ThemeContextValue = {
|
||||
i, // Used for Semantic elements which support "inverted".
|
||||
s, // Used to invert the style some elements.
|
||||
|
|
@ -213,6 +241,8 @@ export function ThemeProvider({children, ...props}: ThemeProviderProps) {
|
|||
inverted, // Used to add "invert" to className.
|
||||
theme,
|
||||
savedTheme,
|
||||
isDark: dark,
|
||||
setTheme,
|
||||
setDarkTheme,
|
||||
setLightTheme,
|
||||
cycleSavedTheme,
|
||||
|
|
|
|||
169
app/src/components/ThemeProvider.test.js
Normal file
169
app/src/components/ThemeProvider.test.js
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import React, {useContext} from 'react';
|
||||
import {act, render, screen} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {ThemeContext} from '../contexts/contexts';
|
||||
import {
|
||||
amberTheme,
|
||||
darkTheme,
|
||||
isDarkTheme,
|
||||
lightTheme,
|
||||
nightTheme,
|
||||
resolveTheme,
|
||||
systemTheme,
|
||||
ThemeProvider,
|
||||
themeSessionKey,
|
||||
} from './Theme';
|
||||
|
||||
// Lets a test drive `prefers-color-scheme` and assert on what the provider applied.
|
||||
let prefersDark = false;
|
||||
|
||||
const mockMatchMedia = () => {
|
||||
const listeners = new Set();
|
||||
window.matchMedia = jest.fn().mockImplementation(query => ({
|
||||
matches: query === '(prefers-color-scheme: dark)' ? prefersDark : false,
|
||||
media: query,
|
||||
addEventListener: (_event, listener) => listeners.add(listener),
|
||||
removeEventListener: (_event, listener) => listeners.delete(listener),
|
||||
addListener: (listener) => listeners.add(listener),
|
||||
removeListener: (listener) => listeners.delete(listener),
|
||||
dispatchEvent: () => false,
|
||||
}));
|
||||
return {
|
||||
// Emulate the OS switching to dark/light while the app is open.
|
||||
change: (value) => {
|
||||
prefersDark = value;
|
||||
act(() => listeners.forEach(listener => listener({matches: value})));
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
function ThemeProbe() {
|
||||
const {theme, savedTheme, isDark, setTheme, cycleSavedTheme} = useContext(ThemeContext);
|
||||
return <>
|
||||
<span data-testid='theme'>{theme}</span>
|
||||
<span data-testid='saved'>{String(savedTheme)}</span>
|
||||
<span data-testid='dark'>{String(isDark)}</span>
|
||||
<button onClick={() => setTheme(nightTheme)}>night</button>
|
||||
<button onClick={() => setTheme(systemTheme)}>system</button>
|
||||
<button onClick={cycleSavedTheme}>cycle</button>
|
||||
</>
|
||||
}
|
||||
|
||||
const renderProvider = () => render(<ThemeProvider><ThemeProbe/></ThemeProvider>);
|
||||
|
||||
const appliedTheme = () => document.documentElement.getAttribute('data-theme');
|
||||
|
||||
describe('ThemeProvider', () => {
|
||||
beforeEach(() => {
|
||||
prefersDark = false;
|
||||
localStorage.clear();
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
mockMatchMedia();
|
||||
});
|
||||
|
||||
it('applies the saved theme and stamps it on <html>', () => {
|
||||
localStorage.setItem(themeSessionKey, nightTheme);
|
||||
|
||||
renderProvider();
|
||||
|
||||
expect(screen.getByTestId('theme')).toHaveTextContent(nightTheme);
|
||||
expect(appliedTheme()).toBe(nightTheme);
|
||||
});
|
||||
|
||||
it('falls back to the OS preference when no theme is saved', () => {
|
||||
prefersDark = true;
|
||||
|
||||
renderProvider();
|
||||
|
||||
expect(screen.getByTestId('theme')).toHaveTextContent(darkTheme);
|
||||
expect(screen.getByTestId('saved')).toHaveTextContent('null');
|
||||
});
|
||||
|
||||
it('persists a chosen theme so it survives a reload', async () => {
|
||||
renderProvider();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', {name: 'night'}));
|
||||
|
||||
expect(localStorage.getItem(themeSessionKey)).toBe(nightTheme);
|
||||
expect(appliedTheme()).toBe(nightTheme);
|
||||
});
|
||||
|
||||
it('follows the OS preference while `system` is chosen', async () => {
|
||||
const media = mockMatchMedia();
|
||||
renderProvider();
|
||||
await userEvent.click(screen.getByRole('button', {name: 'system'}));
|
||||
|
||||
media.change(true);
|
||||
|
||||
expect(screen.getByTestId('theme')).toHaveTextContent(darkTheme);
|
||||
expect(appliedTheme()).toBe(darkTheme);
|
||||
});
|
||||
|
||||
it('ignores the OS preference once a specific theme is chosen', async () => {
|
||||
const media = mockMatchMedia();
|
||||
renderProvider();
|
||||
await userEvent.click(screen.getByRole('button', {name: 'night'}));
|
||||
|
||||
media.change(true);
|
||||
|
||||
expect(screen.getByTestId('theme')).toHaveTextContent(nightTheme);
|
||||
});
|
||||
|
||||
it('reports night and amber as dark themes', async () => {
|
||||
renderProvider();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', {name: 'night'}));
|
||||
|
||||
expect(screen.getByTestId('dark')).toHaveTextContent('true');
|
||||
});
|
||||
|
||||
it('cycles through every theme and back to system', async () => {
|
||||
renderProvider();
|
||||
const cycle = screen.getByRole('button', {name: 'cycle'});
|
||||
|
||||
const seen = [];
|
||||
for (let index = 0; index < 5; index++) {
|
||||
await userEvent.click(cycle);
|
||||
seen.push(screen.getByTestId('saved').textContent);
|
||||
}
|
||||
|
||||
expect(seen).toEqual([lightTheme, darkTheme, nightTheme, amberTheme, systemTheme]);
|
||||
});
|
||||
|
||||
it('recovers from a theme name written by an older version', () => {
|
||||
localStorage.setItem(themeSessionKey, 'sepia');
|
||||
|
||||
renderProvider();
|
||||
|
||||
expect(screen.getByTestId('theme')).toHaveTextContent(lightTheme);
|
||||
expect(appliedTheme()).toBe(lightTheme);
|
||||
});
|
||||
});
|
||||
|
||||
describe('theme helpers', () => {
|
||||
beforeEach(() => {
|
||||
prefersDark = false;
|
||||
mockMatchMedia();
|
||||
});
|
||||
|
||||
it('resolves explicit theme names as themselves', () => {
|
||||
[lightTheme, darkTheme, nightTheme, amberTheme].forEach(theme => {
|
||||
expect(resolveTheme(theme)).toBe(theme);
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves `system` and null from the OS preference', () => {
|
||||
expect(resolveTheme(systemTheme)).toBe(lightTheme);
|
||||
expect(resolveTheme(null)).toBe(lightTheme);
|
||||
|
||||
prefersDark = true;
|
||||
expect(resolveTheme(systemTheme)).toBe(darkTheme);
|
||||
});
|
||||
|
||||
it('knows which themes are built on a dark background', () => {
|
||||
expect(isDarkTheme(lightTheme)).toBe(false);
|
||||
expect(isDarkTheme(darkTheme)).toBe(true);
|
||||
expect(isDarkTheme(nightTheme)).toBe(true);
|
||||
expect(isDarkTheme(amberTheme)).toBe(true);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue