DEV Community

Cover image for Tauri (4) - Get the theme switching function fixed
Rain9
Rain9

Posted on

Tauri (4) - Get the theme switching function fixed

Introduction

The inspiration for this title comes from a classic advertisement slogan:

"Take the white pill during the day to stay awake; take the black pill at night to sleep well."

Do you still remember "White Plus Black"? I used to take it when I was a kid! However, this medicine seems to have been discontinued now. Let’s not delve into the reasons to stay on topic. πŸ˜„


Auto

As shown above, this is the appearance settings of the Mac system, mainly divided into three modes: Light, Dark, and Auto.

Among them, Light and Dark are the core themes, while Auto switches between them automatically based on the time of day: Light mode for daytime and Dark mode for nighttime (in line with the title, πŸ˜„).

Next, let's explore the differences between Light and Dark themes.


Light vs. Dark Themes

Aspect Light Theme Dark Theme
Color Scheme - Dominated by light colors, usually with white or light gray backgrounds
- Text is dark, such as black or dark gray
- Dominated by dark colors, usually with black or dark gray backgrounds
- Text is light, such as white or light gray
Visual Fatigue - May cause eye strain in low-light environments
- More comfortable in well-lit environments
- Reduces brightness and eye strain in low-light environments
- May appear less clear in bright environments
Contrast & Readability - Lower contrast (dark text on light background), suitable for text-heavy scenarios
- Good readability and easy to adapt to
- Higher contrast (light text on dark background), ideal for visually sensitive users
- Clearer display for graphics or complex interfaces
Aesthetic & Emotion - Conveys freshness and brightness
- Suitable for documentation and office applications, appearing formal and professional
- Conveys a sense of modernity and technology
- Suitable for multimedia and development environments, appearing sleek and stylish
Energy Consumption - OLED/AMOLED Screens: Light pixels consume more energy
- LCD Screens: Minimal difference compared to Dark theme
- OLED/AMOLED Screens: Dark pixels save more energy
- LCD Screens: Minimal difference compared to Light theme
Usage Scenarios - Ideal for office work, reading documents, and browsing news
- Suitable for general users and well-lit environments
- Ideal for programming, design, video editing, and entertainment
- Suitable for visually sensitive users and low-light environments
Time of Use - Daytime or well-lit hours - Nighttime or low-light hours
Example Light Dark

Best Practice: Provide a theme switch feature to let users freely choose based on their environment and preferences.

Practice

User Settings Interface

To meet users' personalized needs, we can design a settings page that allows users to adjust the interface theme according to their preferences. Through this settings page, users can easily select their preferred Light or Dark theme, switch to Auto mode, or default to Auto mode. In Auto mode, the app automatically follows the computer's theme settings.

Setting

Implementation in code:

import { Monitor, Moon, Sun } from "lucide-react";

import { useTheme } from "./ThemeContext";

export type AppTheme = "auto" | "light" | "dark"

function ThemeOption({
  icon: Icon,
  title,
  theme,
}: {
  icon: any;
  title: string;
  theme: AppTheme;
}) {
  const { theme: currentTheme, changeTheme } = useTheme();

  const isSelected = currentTheme === theme;

  return (
    <button
      onClick={() => changeTheme(theme)}
      className={`p-4 rounded-lg border-2 ${
        isSelected
          ? "border-blue-500 bg-blue-50 dark:bg-blue-900/20"
          : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"
      } flex flex-col items-center justify-center space-y-2 transition-all`}
    >
      <Icon className={`w-6 h-6 ${isSelected ? "text-blue-500" : ""}`} />
      <span
        className={`text-sm font-medium ${isSelected ? "text-blue-500" : ""}`}
      >
        {title}
      </span>
    </button>
  );
}

export default function ThemeSetting() {
    return (
        <div className="grid grid-cols-3 gap-4">
            <ThemeOption icon={Sun} title="Light" theme="light" />
            <ThemeOption icon={Moon} title="Dark" theme="dark" />
            <ThemeOption icon={Monitor} title="Auto" theme="auto" />
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Core Logic Breakdown

Before writing code, planning the core logic can help streamline development:

  1. Auto Mode If the user selects Auto mode, the app will automatically switch according to the system's theme.
  2. System Theme Listener In Auto mode, the app must listen to system theme changes to synchronize updates.
  3. User-Defined Mode If the user explicitly selects a theme (Light or Dark), the app will prioritize the user's choice and ignore the system's settings.
  4. App Window Synchronization Whether in Auto mode or user-defined settings, theme changes must be propagated to all app windows to ensure a consistent interface style.

A clear logic flow ensures an efficient implementation of the theme-switching functionality while enhancing the user experience.

Key File: ThemeContext.tsx

...

Continue reading on GitHub for the full implementation and detailed explanations of system theme listening, context setup, and Tailwind integration.


Summary

Theme development is a critical aspect of desktop app design. It not only defines the app's visual style but also directly impacts user experience and satisfaction. With careful design and implementation, you can create a visually appealing and highly functional theme, giving your app a unique charm in a competitive market.

We hope this article inspires and helps you in your journey to building themes for desktop applications!


Open Source Project Sharing

Recently, I started developing a project based on Tauri, called Coco. The project is open source, and we’re actively improving it. Feel free to check it out and give it a star 🌟 if you find it helpful!

This is my first project with Tauri, and I’ve been learning and exploring along the way. I look forward to connecting with like-minded developers to exchange ideas and grow together!

Thank you so much for your support and attention!

Top comments (0)