useTheme

主题切换 Hook

概述

useTheme 提供主题状态管理和切换功能。

导入

import { useTheme } from '@linch-tech/desktop-core';

基本用法

import { useTheme } from '@linch-tech/desktop-core';

function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  return (
    <select value={theme} onChange={(e) => setTheme(e.target.value as Theme)}>
      <option value="light">浅色</option>
      <option value="dark">深色</option>
      <option value="system">跟随系统</option>
    </select>
  );
}

返回值

interface UseThemeReturn {
  theme: Theme;                    // 当前主题设置
  setTheme: (theme: Theme) => void; // 设置主题
}

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

主题值

说明
light浅色模式
dark深色模式
system跟随系统设置

工作原理

  1. 主题值存储在 localStorage(key: vite-ui-theme
  2. 根据主题值,在 <html> 元素上添加 lightdark
  3. 如果是 system,会监听系统主题变化并自动切换

使用 CSS 变量

主题切换通过 Tailwind CSS 的暗黑模式实现:

/* 浅色模式 */
:root {
  --background: #ffffff;
  --foreground: #000000;
}

/* 深色模式 */
.dark {
  --background: #1a1a1a;
  --foreground: #ffffff;
}

内置组件

可以直接使用 ThemeSwitcher 组件:

import { ThemeSwitcher } from '@linch-tech/desktop-core';

<ThemeSwitcher />

示例:主题按钮

import { useTheme } from '@linch-tech/desktop-core';
import { Sun, Moon, Monitor } from 'lucide-react';

function ThemeButton() {
  const { theme, setTheme } = useTheme();

  const icons = {
    light: <Sun className="h-4 w-4" />,
    dark: <Moon className="h-4 w-4" />,
    system: <Monitor className="h-4 w-4" />,
  };

  const next: Record<Theme, Theme> = {
    light: 'dark',
    dark: 'system',
    system: 'light',
  };

  return (
    <button onClick={() => setTheme(next[theme])}>
      {icons[theme]}
    </button>
  );
}

持久化

主题设置自动持久化到 localStorage,刷新页面后保持。

// 读取
localStorage.getItem('vite-ui-theme'); // 'light' | 'dark' | 'system'

// 写入(由 setTheme 自动处理)
localStorage.setItem('vite-ui-theme', 'dark');