Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated theme mode 'auto' to remove storage integration #1400

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
18 changes: 14 additions & 4 deletions packages/ui/src/hooks/use-theme-mode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import debounce from "debounce";
import { useEffect, useState } from "react";
import { isClient } from "../helpers/is-client";
import { useWatchLocalStorageValue } from "../hooks/use-watch-localstorage-value";
Expand Down Expand Up @@ -40,12 +41,13 @@ export const useThemeMode = () => {
/**
* Sets `mode` to a given value: `light | dark` | `auto`
*/
const handleSetMode = (mode: ThemeMode) => {
const _handleSetMode = (mode: ThemeMode) => {
setMode(mode);
setModeInLS(mode);
setModeInDOM(mode);
document.dispatchEvent(new CustomEvent(SYNC_THEME_MODE, { detail: mode }));
};
const handleSetMode = debounce(_handleSetMode, 25, { immediate: true });

/**
* Toggles between: `light | dark`
Expand Down Expand Up @@ -89,9 +91,17 @@ const useSyncMode = (onChange: (mode: ThemeMode) => void) => {
};

/**
* Sets the give value in local storage
* Sets the give value in local storage.
* "auto" will remove the local storage value if present.
*/
const setModeInLS = (mode: ThemeMode) => localStorage.setItem(LS_THEME_MODE, mode);
const setModeInLS = (mode: ThemeMode) => {
if (mode === "auto") {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this will break the current logic, auto value is meant to be saved in LS and from that computed to either light or dark

localStorage.deleteItem(LS_THEME_MODE);
return;
}

localStorage.setItem(LS_THEME_MODE, mode);
};
SutuSebastian marked this conversation as resolved.
Show resolved Hide resolved

/**
* Add or remove class `dark` on `html` element
Expand Down Expand Up @@ -123,7 +133,7 @@ const computeModeValue = (mode: ThemeMode): ThemeMode => {
};

/**
* Get browser prefered color scheme
* Get browser preferred color scheme
* @returns `light` | `dark`
*/
const prefersColorScheme = (): ThemeMode => {
Expand Down
Loading