Skip to content

Add support for Dark/Light mode (and system default) #18

@rucub100

Description

@rucub100

1. State Management (Rust Backend)

  • In your AppState (or a dedicated ThemeState struct), store the current theme preference:
#[derive(Clone, Serialize, Deserialize)]
pub enum Theme {
    Light,
    Dark,
    System, // Follow system settings
}
  • Initialize the theme (e.g., to Theme::System by default) in your main function when setting up the Tauri application.

2. Tauri Commands

  • Create Tauri commands to:
    • get_theme: Retrieve the current theme from the Rust backend.
    • set_theme: Update the theme preference in the Rust state.

3. React Context API

  • Create a React context to provide the theme to your components:
import { createContext, useContext, useEffect, useState } from 'react';
import { invoke } from '@tauri-apps/api/tauri';

const ThemeContext = createContext<Theme>('system'); // Default to system theme

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState<Theme>('system');

  useEffect(() => {
    const fetchTheme = async () => {
      const initialTheme = await invoke<Theme>('get_theme');
      setTheme(initialTheme);
    };
    fetchTheme();
  }, []);

  return (
    <ThemeContext.Provider value={theme}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => useContext(ThemeContext);

4. Tailwind CSS Configuration

  • In your tailwind.config.js, configure the darkMode option:
module.exports = {
  // ... other configurations
  darkMode: 'class', // Use the 'class' strategy
};

5. Apply Theme in React Components

  • Use the useTheme hook to access the theme in your components:
const MyComponent = () => {
  const theme = useTheme();

  return (
    <div className={`${theme === 'dark' ? 'dark' : ''} bg-white dark:bg-gray-800`}>
      {/* ... your component content */}
    </div>
  );
};
  • Apply the dark class to the body element based on the theme (you might need to do this in your top-level component or layout).

6. Theme Switching

  • Create a UI element (e.g., a toggle switch) to allow users to change the theme.
  • When the user changes the theme, call the set_theme Tauri command to update the state in Rust.
  • Update the dark class on the body element accordingly.

This architecture provides a robust and maintainable way to implement dark/light mode in your Tauri application.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions