mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-25 03:54:47 +03:00
feat(frontend): add a follow-system theme mode (#7026)
The theme had three settings, light, dark and ultra dark, so anyone whose desktop switches appearance on a schedule had to change the panel by hand. Add a System step to the theme button on the sidebar, the login page, the command palette and the subscription page. In that mode the panel follows the OS light/dark setting and repaints when it changes, without a reload. The stored preference moves to theme-mode; the legacy dark-mode boolean is still read on first load and still written, so existing users keep their theme.
This commit is contained in:
@@ -14,6 +14,7 @@ import {
|
||||
CopyOutlined,
|
||||
DashboardOutlined,
|
||||
DatabaseOutlined,
|
||||
DesktopOutlined,
|
||||
DiscordOutlined,
|
||||
ExportOutlined,
|
||||
FileTextOutlined,
|
||||
@@ -36,7 +37,7 @@ import { ClipboardManager, HttpUtil, SizeFormatter } from '@/utils';
|
||||
import { activateOnKey } from '@/utils/a11y';
|
||||
import { useInboundOptions } from '@/api/queries/useInboundOptions';
|
||||
import { useAllSettings } from '@/api/queries/useAllSettings';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { themeModeKey, useTheme } from '@/hooks/useTheme';
|
||||
import { PANEL_ROUTES } from '@/routes/panelRoutes';
|
||||
import type { ClientRecord, InboundOption } from '@/schemas/client';
|
||||
import { commandPaletteStore, useCommandPalette } from './useCommandPalette';
|
||||
@@ -90,7 +91,7 @@ export default function CommandPalette() {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const navigate = useNavigate();
|
||||
const { isDark, isUltra, toggleTheme, toggleUltra, antdThemeConfig } = useTheme();
|
||||
const { mode, isDark, isUltra, cycleTheme: advanceTheme, antdThemeConfig } = useTheme();
|
||||
const { isOpen, close } = useCommandPalette();
|
||||
const { allSetting } = useAllSettings();
|
||||
const { data: inbounds = [] } = useInboundOptions();
|
||||
@@ -240,17 +241,9 @@ export default function CommandPalette() {
|
||||
}, [close, messageApi, t]);
|
||||
|
||||
const cycleTheme = useCallback(() => {
|
||||
if (!isDark) {
|
||||
toggleTheme();
|
||||
if (isUltra) toggleUltra();
|
||||
} else if (!isUltra) {
|
||||
toggleUltra();
|
||||
} else {
|
||||
toggleUltra();
|
||||
toggleTheme();
|
||||
}
|
||||
advanceTheme();
|
||||
close();
|
||||
}, [isDark, isUltra, toggleTheme, toggleUltra, close]);
|
||||
}, [advanceTheme, close]);
|
||||
|
||||
const trimmedQuery = query.trim();
|
||||
const isDebouncing = isOpen && trimmedQuery.length > 0 && trimmedQuery !== debouncedQuery;
|
||||
@@ -551,9 +544,16 @@ export default function CommandPalette() {
|
||||
id: 'act-cycle-theme',
|
||||
category: 'actions',
|
||||
title: t('menu.theme'),
|
||||
subtitle: isUltra ? 'Ultra Dark' : isDark ? 'Dark' : 'Light',
|
||||
keywords: ['theme', 'light', 'dark', 'ultra'],
|
||||
icon: isDark ? <SunOutlined aria-hidden /> : <MoonOutlined aria-hidden />,
|
||||
subtitle: t(themeModeKey(mode, isUltra)),
|
||||
keywords: ['theme', 'light', 'dark', 'ultra', 'system', 'auto'],
|
||||
icon:
|
||||
mode === 'system' ? (
|
||||
<DesktopOutlined aria-hidden />
|
||||
) : isDark ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<SunOutlined aria-hidden />
|
||||
),
|
||||
action: cycleTheme,
|
||||
},
|
||||
{
|
||||
@@ -589,6 +589,7 @@ export default function CommandPalette() {
|
||||
query,
|
||||
clientSearch,
|
||||
inbounds,
|
||||
mode,
|
||||
isDark,
|
||||
isUltra,
|
||||
allSetting.subURI,
|
||||
|
||||
+105
-13
@@ -1,10 +1,24 @@
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { theme as antdTheme } from 'antd';
|
||||
import type { ThemeConfig } from 'antd';
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system';
|
||||
|
||||
const STORAGE_MODE = 'theme-mode';
|
||||
// Written alongside `theme-mode` because older panel builds and third-party
|
||||
// scripts still read the boolean.
|
||||
const STORAGE_DARK = 'dark-mode';
|
||||
const STORAGE_ULTRA = 'isUltraDarkThemeEnabled';
|
||||
const SCHEME_QUERY = '(prefers-color-scheme: dark)';
|
||||
|
||||
function readBool(key: string, fallback: boolean): boolean {
|
||||
const raw = localStorage.getItem(key);
|
||||
@@ -12,6 +26,62 @@ function readBool(key: string, fallback: boolean): boolean {
|
||||
return raw === 'true';
|
||||
}
|
||||
|
||||
function systemPrefersDark(): boolean {
|
||||
try {
|
||||
return window.matchMedia(SCHEME_QUERY).matches;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeSystemScheme(onChange: () => void): () => void {
|
||||
const mql = window.matchMedia(SCHEME_QUERY);
|
||||
mql.addEventListener('change', onChange);
|
||||
return () => mql.removeEventListener('change', onChange);
|
||||
}
|
||||
|
||||
/** Reads a stored preference, falling back to the legacy boolean panels wrote. */
|
||||
function parseStoredMode(raw: string | null, legacyDark: boolean): ThemeMode {
|
||||
if (raw === 'light' || raw === 'dark' || raw === 'system') return raw;
|
||||
return legacyDark ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
function readMode(): ThemeMode {
|
||||
try {
|
||||
return parseStoredMode(localStorage.getItem(STORAGE_MODE), readBool(STORAGE_DARK, true));
|
||||
} catch {
|
||||
return 'dark';
|
||||
}
|
||||
}
|
||||
|
||||
function readUltra(): boolean {
|
||||
try {
|
||||
return readBool(STORAGE_ULTRA, false);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveDark(mode: ThemeMode, systemDark: boolean): boolean {
|
||||
return mode === 'system' ? systemDark : mode === 'dark';
|
||||
}
|
||||
|
||||
/** Ultra dark rides on dark, so leaving system always lands on light. */
|
||||
function nextTheme(mode: ThemeMode, isUltra: boolean): { mode: ThemeMode; ultra: boolean } {
|
||||
if (mode === 'light') return { mode: 'dark', ultra: false };
|
||||
if (mode === 'dark') {
|
||||
return isUltra ? { mode: 'system', ultra: false } : { mode: 'dark', ultra: true };
|
||||
}
|
||||
return { mode: 'light', ultra: false };
|
||||
}
|
||||
|
||||
/** i18n key naming the current mode, used for the toggle's label and tooltip. */
|
||||
export function themeModeKey(mode: ThemeMode, isUltra: boolean): string {
|
||||
if (mode === 'system') return 'menu.themeSystem';
|
||||
if (mode === 'light') return 'menu.themeLight';
|
||||
return isUltra ? 'menu.themeUltraDark' : 'menu.themeDark';
|
||||
}
|
||||
|
||||
function applyDom(isDark: boolean, isUltra: boolean) {
|
||||
document.body.classList.remove('dark', 'light');
|
||||
document.body.classList.add(isDark ? 'dark' : 'light');
|
||||
@@ -30,9 +100,10 @@ function applyDom(isDark: boolean, isUltra: boolean) {
|
||||
}
|
||||
|
||||
// module load so the document is in the right theme before React mounts.
|
||||
const initialDark = readBool(STORAGE_DARK, true);
|
||||
const initialUltra = readBool(STORAGE_ULTRA, false);
|
||||
applyDom(initialDark, initialUltra);
|
||||
const initialMode = readMode();
|
||||
const initialUltra = readUltra();
|
||||
const initialDark = resolveDark(initialMode, systemPrefersDark());
|
||||
applyDom(initialDark, initialUltra && initialDark);
|
||||
|
||||
const DARK_TOKENS = {
|
||||
colorBgBase: '#1a1b1f',
|
||||
@@ -151,33 +222,54 @@ export function pauseAnimationsUntilLeave(elementId: string): void {
|
||||
}
|
||||
|
||||
interface ThemeContextValue {
|
||||
/** The stored preference: light, dark, or follow the OS. */
|
||||
mode: ThemeMode;
|
||||
/** Resolved appearance — `system` collapsed against the OS scheme. */
|
||||
isDark: boolean;
|
||||
/** Ultra dark is a variant of dark and never applies to light. */
|
||||
isUltra: boolean;
|
||||
toggleTheme: () => void;
|
||||
toggleUltra: () => void;
|
||||
/** Walks light → dark → ultra dark → system → light. */
|
||||
cycleTheme: () => void;
|
||||
antdThemeConfig: ThemeConfig;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [isDark, setIsDark] = useState<boolean>(initialDark);
|
||||
const [isUltra, setIsUltra] = useState<boolean>(initialUltra);
|
||||
// Read at mount so a preference written by another tab or a test is honoured.
|
||||
const [mode, setModeState] = useState<ThemeMode>(readMode);
|
||||
const [ultraRequested, setUltraRequested] = useState<boolean>(readUltra);
|
||||
// Tracks the OS scheme live so `system` mode follows the user flipping their
|
||||
// desktop appearance without a reload.
|
||||
const systemDark = useSyncExternalStore(subscribeSystemScheme, systemPrefersDark, () => false);
|
||||
|
||||
const isDark = resolveDark(mode, systemDark);
|
||||
const isUltra = ultraRequested && isDark;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
applyDom(isDark, isUltra);
|
||||
localStorage.setItem(STORAGE_MODE, mode);
|
||||
localStorage.setItem(STORAGE_DARK, String(isDark));
|
||||
localStorage.setItem(STORAGE_ULTRA, String(isUltra));
|
||||
}, [isDark, isUltra]);
|
||||
}, [mode, isDark, isUltra]);
|
||||
|
||||
const toggleTheme = useCallback(() => setIsDark((v) => !v), []);
|
||||
const toggleUltra = useCallback(() => setIsUltra((v) => !v), []);
|
||||
const cycleTheme = useCallback(() => {
|
||||
const next = nextTheme(mode, isUltra);
|
||||
setModeState(next.mode);
|
||||
setUltraRequested(next.ultra);
|
||||
}, [mode, isUltra]);
|
||||
|
||||
const antdThemeConfig = useMemo(() => buildAntdThemeConfig(isDark, isUltra), [isDark, isUltra]);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(
|
||||
() => ({ isDark, isUltra, toggleTheme, toggleUltra, antdThemeConfig }),
|
||||
[isDark, isUltra, toggleTheme, toggleUltra, antdThemeConfig],
|
||||
() => ({
|
||||
mode,
|
||||
isDark,
|
||||
isUltra,
|
||||
cycleTheme,
|
||||
antdThemeConfig,
|
||||
}),
|
||||
[mode, isDark, isUltra, cycleTheme, antdThemeConfig],
|
||||
);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ClusterOutlined,
|
||||
CodeOutlined,
|
||||
DatabaseOutlined,
|
||||
DesktopOutlined,
|
||||
DiscordOutlined,
|
||||
GithubOutlined,
|
||||
HeartOutlined,
|
||||
@@ -31,7 +32,8 @@ import {
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { formatPanelVersion } from '@/lib/panel-version';
|
||||
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
|
||||
import { pauseAnimationsUntilLeave, themeModeKey, useTheme } from '@/hooks/useTheme';
|
||||
import type { ThemeMode } from '@/hooks/useTheme';
|
||||
import { useAllSettings } from '@/api/queries/useAllSettings';
|
||||
import { useCommandPalette } from '@/components/command-palette/useCommandPalette';
|
||||
import { PANEL_ROUTES } from '@/routes/panelRoutes';
|
||||
@@ -100,24 +102,29 @@ function VersionBadge({ version, collapsed }: { version: string; collapsed?: boo
|
||||
|
||||
function ThemeCycleButton({
|
||||
id,
|
||||
mode,
|
||||
isDark,
|
||||
isUltra,
|
||||
onCycle,
|
||||
ariaLabel,
|
||||
}: {
|
||||
id: string;
|
||||
mode: ThemeMode;
|
||||
isDark: boolean;
|
||||
isUltra: boolean;
|
||||
onCycle: () => void;
|
||||
ariaLabel: string;
|
||||
}) {
|
||||
const icon = !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
const icon =
|
||||
mode === 'system' ? (
|
||||
<DesktopOutlined aria-hidden />
|
||||
) : !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
return (
|
||||
<button
|
||||
id={id}
|
||||
@@ -148,7 +155,7 @@ function saveSidebarPinned(pinned: boolean) {
|
||||
|
||||
export default function AppSidebar() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, toggleTheme, toggleUltra } = useTheme();
|
||||
const { mode, isDark, isUltra, cycleTheme: advanceTheme } = useTheme();
|
||||
const { open: openCommandPalette } = useCommandPalette();
|
||||
const navigate = useNavigate();
|
||||
const { pathname, hash } = useLocation();
|
||||
@@ -338,19 +345,13 @@ export default function AppSidebar() {
|
||||
const cycleTheme = useCallback(
|
||||
(id: string) => {
|
||||
pauseAnimationsUntilLeave(id);
|
||||
if (!isDark) {
|
||||
toggleTheme();
|
||||
if (isUltra) toggleUltra();
|
||||
} else if (!isUltra) {
|
||||
toggleUltra();
|
||||
} else {
|
||||
toggleUltra();
|
||||
toggleTheme();
|
||||
}
|
||||
advanceTheme();
|
||||
},
|
||||
[isDark, isUltra, toggleTheme, toggleUltra],
|
||||
[advanceTheme],
|
||||
);
|
||||
|
||||
const themeLabel = `${t('menu.theme')}: ${t(themeModeKey(mode, isUltra))}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
@@ -385,10 +386,11 @@ export default function AppSidebar() {
|
||||
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
|
||||
<ThemeCycleButton
|
||||
id="theme-cycle"
|
||||
mode={mode}
|
||||
isDark={isDark}
|
||||
isUltra={isUltra}
|
||||
onCycle={() => cycleTheme('theme-cycle')}
|
||||
ariaLabel={t('menu.theme')}
|
||||
ariaLabel={themeLabel}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -462,10 +464,11 @@ export default function AppSidebar() {
|
||||
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
|
||||
<ThemeCycleButton
|
||||
id="theme-cycle-drawer"
|
||||
mode={mode}
|
||||
isDark={isDark}
|
||||
isUltra={isUltra}
|
||||
onCycle={() => cycleTheme('theme-cycle-drawer')}
|
||||
ariaLabel={t('menu.theme')}
|
||||
ariaLabel={themeLabel}
|
||||
/>
|
||||
<button
|
||||
className="drawer-close"
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
message,
|
||||
} from 'antd';
|
||||
import {
|
||||
DesktopOutlined,
|
||||
KeyOutlined,
|
||||
LockOutlined,
|
||||
MoonFilled,
|
||||
@@ -27,7 +28,7 @@ import { HttpUtil, LanguageManager } from '@/utils';
|
||||
import { FormField, rhfZodValidate } from '@/components/form/rhf';
|
||||
import { setMessageInstance } from '@/utils/messageBus';
|
||||
import SponsorSlot from '@/components/sponsor/SponsorSlot';
|
||||
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
|
||||
import { pauseAnimationsUntilLeave, themeModeKey, useTheme } from '@/hooks/useTheme';
|
||||
import { LoginFormSchema, TwoFactorCodeSchema, type LoginFormValues } from '@/schemas/login';
|
||||
import './LoginPage.css';
|
||||
|
||||
@@ -39,7 +40,7 @@ const basePath = window.X_UI_BASE_PATH || '';
|
||||
|
||||
export default function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, toggleTheme, toggleUltra, antdThemeConfig } = useTheme();
|
||||
const { mode, isDark, isUltra, cycleTheme: advanceTheme, antdThemeConfig } = useTheme();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -94,16 +95,8 @@ export default function LoginPage() {
|
||||
|
||||
const cycleTheme = useCallback(() => {
|
||||
pauseAnimationsUntilLeave('login-theme-cycle');
|
||||
if (!isDark) {
|
||||
toggleTheme();
|
||||
if (isUltra) toggleUltra();
|
||||
} else if (!isUltra) {
|
||||
toggleUltra();
|
||||
} else {
|
||||
toggleUltra();
|
||||
toggleTheme();
|
||||
}
|
||||
}, [isDark, isUltra, toggleTheme, toggleUltra]);
|
||||
advanceTheme();
|
||||
}, [advanceTheme]);
|
||||
|
||||
const pageClass = useMemo(() => {
|
||||
const classes = ['login-app'];
|
||||
@@ -128,13 +121,17 @@ export default function LoginPage() {
|
||||
[],
|
||||
);
|
||||
|
||||
const themeIcon = !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
const themeIcon =
|
||||
mode === 'system' ? (
|
||||
<DesktopOutlined aria-hidden />
|
||||
) : !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
const themeLabel = `${t('menu.theme')}: ${t(themeModeKey(mode, isUltra))}`;
|
||||
|
||||
return (
|
||||
<ConfigProvider theme={antdThemeConfig}>
|
||||
@@ -147,8 +144,8 @@ export default function LoginPage() {
|
||||
shape="circle"
|
||||
size="large"
|
||||
className="toolbar-btn"
|
||||
aria-label={t('menu.theme')}
|
||||
title={t('menu.theme')}
|
||||
aria-label={themeLabel}
|
||||
title={themeLabel}
|
||||
icon={themeIcon}
|
||||
onClick={cycleTheme}
|
||||
/>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Menu, Popover, Space } from 'antd';
|
||||
import {
|
||||
DesktopOutlined,
|
||||
MoonFilled,
|
||||
MoonOutlined,
|
||||
SunOutlined,
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
|
||||
import { LanguageManager } from '@/utils';
|
||||
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
|
||||
import { pauseAnimationsUntilLeave, themeModeKey, useTheme } from '@/hooks/useTheme';
|
||||
|
||||
interface SubHeaderProps {
|
||||
title: string;
|
||||
@@ -22,19 +23,11 @@ interface SubHeaderProps {
|
||||
|
||||
export default function SubHeader({ title, sId, email, lang, onLangChange }: SubHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, toggleTheme, toggleUltra } = useTheme();
|
||||
const { mode, isDark, isUltra, cycleTheme: advanceTheme } = useTheme();
|
||||
|
||||
const cycleTheme = () => {
|
||||
pauseAnimationsUntilLeave('sub-theme-cycle');
|
||||
if (!isDark) {
|
||||
toggleTheme();
|
||||
if (isUltra) toggleUltra();
|
||||
} else if (!isUltra) {
|
||||
toggleUltra();
|
||||
} else {
|
||||
toggleUltra();
|
||||
toggleTheme();
|
||||
}
|
||||
advanceTheme();
|
||||
};
|
||||
|
||||
const langMenuItems = useMemo(
|
||||
@@ -53,13 +46,17 @@ export default function SubHeader({ title, sId, email, lang, onLangChange }: Sub
|
||||
[],
|
||||
);
|
||||
|
||||
const themeIcon = !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
const themeIcon =
|
||||
mode === 'system' ? (
|
||||
<DesktopOutlined aria-hidden />
|
||||
) : !isDark ? (
|
||||
<SunOutlined aria-hidden />
|
||||
) : !isUltra ? (
|
||||
<MoonOutlined aria-hidden />
|
||||
) : (
|
||||
<MoonFilled aria-hidden />
|
||||
);
|
||||
const themeLabel = `${t('menu.theme')}: ${t(themeModeKey(mode, isUltra))}`;
|
||||
const initial = Array.from(title)[0]?.toUpperCase();
|
||||
|
||||
return (
|
||||
@@ -83,8 +80,8 @@ export default function SubHeader({ title, sId, email, lang, onLangChange }: Sub
|
||||
shape="circle"
|
||||
size="large"
|
||||
className="toolbar-btn"
|
||||
aria-label={t('menu.theme')}
|
||||
title={t('menu.theme')}
|
||||
aria-label={themeLabel}
|
||||
title={themeLabel}
|
||||
icon={themeIcon}
|
||||
onClick={cycleTheme}
|
||||
/>
|
||||
|
||||
@@ -15,28 +15,32 @@ function StorybookTheme({ theme }: { theme: 'light' | 'dark' }) {
|
||||
}
|
||||
|
||||
function ThemeToggle() {
|
||||
const { toggleTheme } = useTheme();
|
||||
return <button onClick={toggleTheme}>toggle</button>;
|
||||
const { cycleTheme } = useTheme();
|
||||
return <button onClick={cycleTheme}>toggle</button>;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.className = '';
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
document.documentElement.style.colorScheme = '';
|
||||
// The provider seeds itself from storage at mount, so a toggle in one test
|
||||
// would otherwise be inherited by the next.
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
// Without color-scheme the browser paints native scrollbars light inside dark
|
||||
// modals, e.g. the Edit Client body.
|
||||
test('native scrollbars follow the panel theme', () => {
|
||||
localStorage.setItem('theme-mode', 'light');
|
||||
const { getByRole } = render(
|
||||
<ThemeProvider>
|
||||
<ThemeToggle />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
expect(document.documentElement.style.colorScheme).toBe('dark');
|
||||
expect(document.documentElement.style.colorScheme).toBe('light');
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
expect(document.documentElement.style.colorScheme).toBe('light');
|
||||
expect(document.documentElement.style.colorScheme).toBe('dark');
|
||||
});
|
||||
|
||||
test('native scrollbars follow the Storybook theme', () => {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { act, fireEvent, render } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { ThemeProvider, useTheme } from '@/hooks/useTheme';
|
||||
|
||||
// `system` must survive two things nothing else exercises: the OS flipping its
|
||||
// scheme while the tab stays open, and the legacy `dark-mode` boolean.
|
||||
|
||||
type SchemeListener = (event: { matches: boolean }) => void;
|
||||
|
||||
let systemDark = true;
|
||||
let listeners: SchemeListener[] = [];
|
||||
|
||||
function installMatchMedia() {
|
||||
window.matchMedia = ((query: string) => ({
|
||||
matches: query.includes('prefers-color-scheme') ? systemDark : false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
addEventListener: (_type: string, listener: SchemeListener) => {
|
||||
listeners.push(listener);
|
||||
},
|
||||
removeEventListener: (_type: string, listener: SchemeListener) => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
},
|
||||
dispatchEvent: () => false,
|
||||
})) as unknown as typeof window.matchMedia;
|
||||
}
|
||||
|
||||
function flipSystemScheme(dark: boolean) {
|
||||
systemDark = dark;
|
||||
act(() => {
|
||||
listeners.forEach((listener) => listener({ matches: dark }));
|
||||
});
|
||||
}
|
||||
|
||||
function Harness() {
|
||||
const { mode, isDark, isUltra, cycleTheme } = useTheme();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="mode">{mode}</span>
|
||||
<span data-testid="dark">{String(isDark)}</span>
|
||||
<span data-testid="ultra">{String(isUltra)}</span>
|
||||
<button type="button" onClick={cycleTheme}>
|
||||
cycle
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderHarness() {
|
||||
const utils = render(
|
||||
<ThemeProvider>
|
||||
<Harness />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
return {
|
||||
...utils,
|
||||
mode: () => utils.getByTestId('mode').textContent,
|
||||
dark: () => utils.getByTestId('dark').textContent,
|
||||
ultra: () => utils.getByTestId('ultra').textContent,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
systemDark = true;
|
||||
listeners = [];
|
||||
installMatchMedia();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.className = '';
|
||||
document.documentElement.style.colorScheme = '';
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
});
|
||||
|
||||
describe('theme mode', () => {
|
||||
it('honours the legacy dark-mode boolean when theme-mode was never written', () => {
|
||||
localStorage.setItem('dark-mode', 'false');
|
||||
|
||||
const ui = renderHarness();
|
||||
|
||||
expect(ui.mode()).toBe('light');
|
||||
expect(document.body.classList.contains('light')).toBe(true);
|
||||
});
|
||||
|
||||
it('follows the OS scheme in system mode', () => {
|
||||
localStorage.setItem('theme-mode', 'system');
|
||||
const ui = renderHarness();
|
||||
|
||||
expect(ui.mode()).toBe('system');
|
||||
expect(ui.dark()).toBe('true');
|
||||
expect(document.body.classList.contains('dark')).toBe(true);
|
||||
|
||||
flipSystemScheme(false);
|
||||
|
||||
expect(ui.dark()).toBe('false');
|
||||
expect(document.body.classList.contains('light')).toBe(true);
|
||||
expect(document.documentElement.style.colorScheme).toBe('light');
|
||||
});
|
||||
|
||||
it('keeps an explicit mode pinned when the OS scheme changes', () => {
|
||||
const ui = renderHarness();
|
||||
expect(ui.mode()).toBe('dark');
|
||||
|
||||
flipSystemScheme(false);
|
||||
|
||||
expect(ui.mode()).toBe('dark');
|
||||
expect(ui.dark()).toBe('true');
|
||||
expect(document.body.classList.contains('dark')).toBe(true);
|
||||
});
|
||||
|
||||
it('cycles light → dark → ultra dark → system → light', () => {
|
||||
const ui = renderHarness();
|
||||
const seen: string[] = [];
|
||||
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
fireEvent.click(ui.getByText('cycle'));
|
||||
seen.push(`${ui.mode()}:${ui.ultra()}`);
|
||||
}
|
||||
|
||||
expect(seen).toEqual(['dark:true', 'system:false', 'light:false', 'dark:false']);
|
||||
});
|
||||
});
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "فتح القائمة",
|
||||
"pinSidebar": "تثبيت الشريط الجانبي",
|
||||
"unpinSidebar": "إلغاء تثبيت الشريط الجانبي",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "فاتح",
|
||||
"themeDark": "داكن",
|
||||
"themeUltraDark": "داكن فائق",
|
||||
"themeSystem": "النظام"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Open menu",
|
||||
"pinSidebar": "Pin sidebar",
|
||||
"unpinSidebar": "Unpin sidebar",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "Light",
|
||||
"themeDark": "Dark",
|
||||
"themeUltraDark": "Ultra Dark",
|
||||
"themeSystem": "System"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Abrir menú",
|
||||
"pinSidebar": "Fijar barra lateral",
|
||||
"unpinSidebar": "Desfijar barra lateral",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "Claro",
|
||||
"themeDark": "Oscuro",
|
||||
"themeUltraDark": "Ultra oscuro",
|
||||
"themeSystem": "Sistema"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "باز کردن منو",
|
||||
"pinSidebar": "ثابت کردن نوار کناری",
|
||||
"unpinSidebar": "برداشتن تثبیت نوار کناری",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "روشن",
|
||||
"themeDark": "تیره",
|
||||
"themeUltraDark": "تیره فوقالعاده",
|
||||
"themeSystem": "سیستم"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Buka menu",
|
||||
"pinSidebar": "Sematkan bilah sisi",
|
||||
"unpinSidebar": "Lepas sematan bilah sisi",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "Terang",
|
||||
"themeDark": "Gelap",
|
||||
"themeUltraDark": "Gelap Ultra",
|
||||
"themeSystem": "Sistem"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "メニューを開く",
|
||||
"pinSidebar": "サイドバーを固定",
|
||||
"unpinSidebar": "サイドバーの固定を解除",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "ライト",
|
||||
"themeDark": "ダーク",
|
||||
"themeUltraDark": "ウルトラダーク",
|
||||
"themeSystem": "システム"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Abrir menu",
|
||||
"pinSidebar": "Fixar barra lateral",
|
||||
"unpinSidebar": "Desafixar barra lateral",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "Claro",
|
||||
"themeDark": "Escuro",
|
||||
"themeUltraDark": "Ultra escuro",
|
||||
"themeSystem": "Sistema"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Открыть меню",
|
||||
"pinSidebar": "Закрепить боковую панель",
|
||||
"unpinSidebar": "Открепить боковую панель",
|
||||
"subFormats": "Форматы подписки"
|
||||
"subFormats": "Форматы подписки",
|
||||
"themeLight": "Светлая",
|
||||
"themeDark": "Тёмная",
|
||||
"themeUltraDark": "Ультратёмная",
|
||||
"themeSystem": "Системная"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Otvoriť menu",
|
||||
"pinSidebar": "Pripnúť bočné menu",
|
||||
"unpinSidebar": "Odopnúť bočné menu",
|
||||
"subFormats": "Formáty odberu"
|
||||
"subFormats": "Formáty odberu",
|
||||
"themeLight": "Svetlá",
|
||||
"themeDark": "Tmavá",
|
||||
"themeUltraDark": "Ultra tmavá",
|
||||
"themeSystem": "Systém"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Menüyü aç",
|
||||
"pinSidebar": "Kenar çubuğunu sabitle",
|
||||
"unpinSidebar": "Kenar çubuğu sabitlemesini kaldır",
|
||||
"subFormats": "Abonelik Formatları"
|
||||
"subFormats": "Abonelik Formatları",
|
||||
"themeLight": "Açık",
|
||||
"themeDark": "Koyu",
|
||||
"themeUltraDark": "Ultra koyu",
|
||||
"themeSystem": "Sistem"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Відкрити меню",
|
||||
"pinSidebar": "Закріпити бічну панель",
|
||||
"unpinSidebar": "Відкріпити бічну панель",
|
||||
"subFormats": "Формати підписки"
|
||||
"subFormats": "Формати підписки",
|
||||
"themeLight": "Світла",
|
||||
"themeDark": "Темна",
|
||||
"themeUltraDark": "Ультратемна",
|
||||
"themeSystem": "Системна"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "Mở menu",
|
||||
"pinSidebar": "Ghim thanh bên",
|
||||
"unpinSidebar": "Bỏ ghim thanh bên",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "Sáng",
|
||||
"themeDark": "Tối",
|
||||
"themeUltraDark": "Siêu tối",
|
||||
"themeSystem": "Hệ thống"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "打开菜单",
|
||||
"pinSidebar": "固定侧边栏",
|
||||
"unpinSidebar": "取消固定侧边栏",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "浅色",
|
||||
"themeDark": "深色",
|
||||
"themeUltraDark": "极致深色",
|
||||
"themeSystem": "跟随系统"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
@@ -128,7 +128,11 @@
|
||||
"openMenu": "開啟選單",
|
||||
"pinSidebar": "固定側邊欄",
|
||||
"unpinSidebar": "取消固定側邊欄",
|
||||
"subFormats": "Sub Formats"
|
||||
"subFormats": "Sub Formats",
|
||||
"themeLight": "淺色",
|
||||
"themeDark": "深色",
|
||||
"themeUltraDark": "極致深色",
|
||||
"themeSystem": "跟隨系統"
|
||||
},
|
||||
"pages": {
|
||||
"login": {
|
||||
|
||||
Reference in New Issue
Block a user