From ba442f94317d9ac5c9717416e734fb9fb9c1e356 Mon Sep 17 00:00:00 2001 From: Joseph Garrone Date: Tue, 10 Dec 2024 18:07:49 +0100 Subject: [PATCH] Change color scheme when user system pref. changes #347 --- src/useIsDark/client.ts | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/useIsDark/client.ts b/src/useIsDark/client.ts index 8d9f5729..0ef44d63 100644 --- a/src/useIsDark/client.ts +++ b/src/useIsDark/client.ts @@ -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); @@ -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: @@ -113,13 +117,13 @@ 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"); @@ -127,6 +131,26 @@ export function startClientSideIsDarkLogic(params: { 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;