Skip to content

Commit

Permalink
Change color scheme when user system pref. changes #347
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej committed Dec 10, 2024
1 parent e3e82a3 commit ba442f9
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/useIsDark/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ export function getIsDarkClientSide() {
return $isAfterFirstEffect.current ? $clientSideIsDark.current : ssrWasPerformedWithIsDark;
}

function getSystemColorScheme() {
return typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}

export const useIsDarkClientSide: UseIsDark = () => {
useRerenderOnChange($clientSideIsDark);
useRerenderOnChange($isAfterFirstEffect);
Expand All @@ -54,10 +61,7 @@ export const useIsDarkClientSide: UseIsDark = () => {
: newIsDarkOrDeduceNewIsDarkFromCurrentIsDark
) {
case "system":
return typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
return getSystemColorScheme();
case true:
return "dark";
case false:
Expand Down Expand Up @@ -113,20 +117,40 @@ export function startClientSideIsDarkLogic(params: {
trustedTypesPolicyName
} = params;

reset_user_preference: {
reset_persisted_value_if_website_config_changed: {
const localStorageKey = "scheme-default";

const localStorageValue = localStorage.getItem(localStorageKey);

if (localStorageValue === colorSchemeExplicitlyProvidedAsParameter) {
break reset_user_preference;
break reset_persisted_value_if_website_config_changed;
}

localStorage.removeItem("scheme");

localStorage.setItem(localStorageKey, colorSchemeExplicitlyProvidedAsParameter);
}

reset_persisted_value_if_system_pref_changed: {
if (colorSchemeExplicitlyProvidedAsParameter !== "system") {
break reset_persisted_value_if_system_pref_changed;
}

const localStorageKey = "scheme-system";

const localStorageValue = localStorage.getItem(localStorageKey);

const systemColorScheme = getSystemColorScheme();

if (localStorageValue === systemColorScheme) {
break reset_persisted_value_if_system_pref_changed;
}

localStorage.removeItem("scheme");

localStorage.setItem(localStorageKey, systemColorScheme);
}

const { clientSideIsDark, ssrWasPerformedWithIsDark: ssrWasPerformedWithIsDark_ } = ((): {
clientSideIsDark: boolean;
ssrWasPerformedWithIsDark: boolean;
Expand Down

0 comments on commit ba442f9

Please sign in to comment.