Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌃

Implemented Dark Mode on Zenn

に公開4件
Inside Zennの記事です

Background

Support for dark mode on Zenn has been a feature that was desired since its initial release.

https://github.com/zenn-dev/zenn-community/issues/267

This issue was once closed in 2023. At that time, there was no designer on the Zenn team, and there were no established design systems or guidelines. Applying a dark theme to dozens of pages and hundreds of components was a task where even estimating the effort was impossible.

However, due to the continued demand and the contributions of fujisawa, a designer who joined the Zenn team afterward, the design guidelines gradually improved, and we were finally able to tackle the dark theme implementation.

In this article, I will explain the technical aspects of implementing dark mode on Zenn. I hope that fujisawa will share the design aspects someday.

Implementation

fujisawa created a design prototype, and we proceeded with the implementation from there.

Theme Switching

First, we implemented the mechanism for managing and switching the theme state across the entire site.

Zenn allows users to select from three themes: light, dark, and system theme. The system theme determines light or dark based on the OS settings.

We referred to the following site for implementation:

https://blog.stin.ink/articles/how-to-implement-a-perfect-dark-mode

The key points are:

  • How to suppress flicker during initial rendering: Since waiting for React rendering causes flicker, JavaScript is used to determine the initial state.
  • Whether to follow the OS theme: If following, prefers-color-scheme is used.

These points are explained in detail on the above site, so there is no need to elaborate further, but I will include Zenn's implementation.

① Determining the initial state and monitoring the OS theme

We determine the initial state and monitor the OS theme within a script in _document.page.tsx. For the initial state, we refer to local storage; if a setting exists, we use it; otherwise, we default to light mode. We also monitor OS theme changes and update the theme setting. (Note: OS theme monitoring is also done in a custom hook described later, but it is also performed here to ensure it works even on pages that do not load the custom hook.)

_document.page.tsx(内のScript)
// Reference system theme
function getSystemTheme() {
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        return 'dark-blue';
    }
    return 'light';
}

// Apply theme
function applyTheme(theme) {
    let actualTheme;
    if (theme === 'system') {
        actualTheme = getSystemTheme();
    } else {
        actualTheme = theme;
    }
    // Set theme on the HTML data attribute
    window.document.documentElement.dataset.theme = actualTheme;
}

// Determine initial state
const storedTheme = localStorage.getItem('theme');
const theme = storedTheme || 'light'; // Default to light theme
applyTheme(theme);

// Monitor system theme changes
if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function() {
        const currentTheme = localStorage.getItem('theme') || 'light';
        if (currentTheme === 'system') {
            applyTheme('system');
        }
    });
}

② Theme State Management

This is a custom hook for managing the theme. It manages the theme state and provides functions for obtaining and updating the theme. For components that have their own themes, such as codemirror and react-diff-viewer, this custom hook retrieves the theme state and reflects it.

useTheme.tsx
import { useState, useEffect, useCallback, useMemo } from 'react';

type ThemeType = 'light' | 'dark-blue' | 'system';

export const useTheme = () => {
  const [theme, setTheme] = useState<ThemeType>('light');
  const [actualTheme, setActualTheme] = useState<'light' | 'dark-blue'>(
    'light'
  );

  const isDarkMode = useMemo(() => actualTheme !== 'light', [actualTheme]);

  const getSystemTheme = useCallback((): 'light' | 'dark-blue' => {
    if (
      typeof window !== 'undefined' &&
      window.matchMedia &&
      window.matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      return 'dark-blue';
    }
    return 'light';
  }, []);

  const applyTheme = useCallback(
    (themeToApply: ThemeType) => {
      const htmlElement = document.documentElement;
      let resolvedTheme: 'light' | 'dark-blue';

      if (themeToApply === 'system') {
        resolvedTheme = getSystemTheme();
      } else {
        resolvedTheme = themeToApply;
      }

      htmlElement.setAttribute('data-theme', resolvedTheme);
      setActualTheme(resolvedTheme);
    },
    [getSystemTheme]
  );

  const updateTheme = useCallback(
    (newTheme: ThemeType) => {
      localStorage.setItem('theme', newTheme);
      setTheme(newTheme);
      applyTheme(newTheme);
    },
    [applyTheme]
  );

  useEffect(() => {
    const storedTheme = (localStorage.getItem('theme') as ThemeType) || 'light';
    setTheme(storedTheme);
    applyTheme(storedTheme);

    // Monitor system theme changes (only in browser environment)
    if (typeof window === 'undefined' || !window.matchMedia) {
      return;
    }

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleChange = () => {
      const currentTheme =
        (localStorage.getItem('theme') as ThemeType) || 'light';
      if (currentTheme === 'system') {
        applyTheme('system');
      }
    };

    mediaQuery.addEventListener('change', handleChange);

    // Monitor data-theme attribute changes (to respond to external changes)
    const htmlElement = document.documentElement;
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.attributeName === 'data-theme') {
          const newTheme = htmlElement.getAttribute('data-theme') as
            | 'light'
            | 'dark-blue';
          if (newTheme) {
            setActualTheme(newTheme);
          }
        }
      });
    });

    observer.observe(htmlElement, { attributes: true });

    return () => {
      mediaQuery.removeEventListener('change', handleChange);
      observer.disconnect();
    };
  }, [applyTheme]);

  return {
    theme,
    actualTheme,
    isDarkMode,
    updateTheme,
    getSystemTheme,
  };
};

Switching Themes with CSS

Next, we implement theme switching using CSS.

The mechanism is to refer to the data-theme attribute of the HTML root set in the previous step and define styles according to the value of that attribute in CSS.

A simplified example is as follows:

.component {
  --background-color: #fff;
  --text-color: #000000;
}

[data-theme='dark-blue'] .component {
  --background-color: #000;
  --text-color: #fff;
}

However, it is not practical to set theme-specific styles in all CSS. Therefore, we define semantic color tokens and use appropriate tokens for each component to switch themes.

Simplified image:

// Define semantic color tokens in global CSS
:root {
  --color-background: #fff;
  --color-text: #000;
}

:root[data-theme='dark-blue'] {
  --color-background: #000;
  --color-text: #fff;
}

// Use semantic color tokens in component CSS
.component {
  background-color: var(--color-background);
  color: var(--color-text);
}

By doing this, we can use semantic color tokens in CSS and define theme-specific styles.

The article on Qiita was very helpful for designing the color palette and semantic color tokens.

https://qiita.com/degudegu2510/items/d3095fd83dff9e61f54f

Since Zenn was originally implemented with only one theme, the color palette and semantic color tokens were not well organized. Additionally, Zenn has many custom components outside the design system, and appropriate styles needed to be applied to these components as well. Organizing these was the most labor-intensive part of implementing the dark theme. Through this work, I once again felt the importance of a design system.

Handling Embedded Content

Embedded content refers to LinkCards, GitHub/Gist snippets, Mermaid diagrams, X posts, etc., displayed within Zenn articles. These are hosted on a different domain from zenn.dev and are displayed in iframes. To support Zenn's dark theme, these embedded contents also needed to be adapted to the dark theme to match the overall Zenn theme.

Initially, we used color-scheme and prefers-color-scheme to automatically switch the theme of embedded content.

Simplified image:

// CSS on zenn.dev side
iframe {
  color-scheme: light;
}

[data-theme='dark-blue'] iframe {
  color-scheme: dark;
}

// CSS on the iframe side
:root {
  color-scheme: light;
  --color-background: #fff;
  --color-text: #000;

  @media (prefers-color-scheme: dark) {
    color-scheme: dark;
    --color-background: #000;
    --color-text: #fff;
  }
}

prefers-color-scheme is a media query used by the browser to determine the user's requested theme (light or dark). Normally, the OS setting is reflected, but in iframes, the set color-scheme takes precedence. As shown in the example above, by setting color-scheme on the iframe's style to match Zenn's theme, the embedded content automatically switches according to Zenn's theme.

Additionally, by setting color-scheme on the root of the iframe side, the background inside the iframe can be made transparent. (Reference: https://drafts.csswg.org/css-color-adjust-1/#color-scheme-effect)

However, theme determination based on prefers-color-scheme worked as expected on PC (macOS), but on mobile (iOS) environments, color-scheme was not properly reflected. On iOS, color-scheme was not reflected, and only the OS theme affected prefers-color-scheme. Even when hosting the iframe on the same domain, the result was the same.

As a workaround, we adopted a method using postMessage to communicate the Zenn theme to the iframe. Inside the iframe, we switch the style according to the received theme.

The implementation is a bit complex, so I'll illustrate it with a sequence diagram.

For the initial rendering of the iframe, to minimize flickering, we refer to prefers-color-scheme to set color-scheme (though on mobile environments, flickering is unavoidable). Then, when Zenn's theme is determined, we send the theme information to the iframe and update the styles inside the iframe.

Conclusion

Adapting an existing site to support dark mode turned out to be a much more challenging task than expected. If I were to implement dark mode again in a similar situation, I would first thoroughly establish the design system and color tokens. Once that foundation is in place, implementing dark mode should be relatively straightforward.

After the release, we received a tremendous amount of positive feedback from Zenn users, and I am truly glad we implemented it.

GitHubで編集を提案
Zenn Tech Blog
Zenn Tech Blog

Discussion

RionRion

少し青すぎませんか?
ブランドカラーに青があるとはいえ少し青すぎな気もするのですが...

5
しゃあるしゃある

統計ダッシュボードすら青みがかっていて、少し見づらいと思います

3
chaploudchaploud

Dark Mode対応ありがとうございます!
Gistのコードを埋め込んでみたのですが、本記事の意図とは異なり、ZennがDark Mode表示でもGist領域が白いままでした。(Mac/Google Chrome)

1