From 0de5b344e7b19d6ef397b54b8868afcd3bdc9ebf Mon Sep 17 00:00:00 2001 From: Mayank Date: Mon, 17 Jun 2024 13:06:25 +0530 Subject: [PATCH 1/5] refactor: supressHydrationWarning and improve readability --- lib/src/client/core/core.test.tsx | 4 ++-- lib/src/client/core/core.tsx | 29 ++++++++++++++++++++++++----- lib/src/constants.ts | 6 +++--- lib/src/hooks/use-mode.ts | 2 +- lib/src/utils.ts | 2 +- 5 files changed, 31 insertions(+), 12 deletions(-) diff --git a/lib/src/client/core/core.test.tsx b/lib/src/client/core/core.test.tsx index 299e71e8..5f116ba5 100644 --- a/lib/src/client/core/core.test.tsx +++ b/lib/src/client/core/core.test.tsx @@ -1,6 +1,6 @@ import { act, cleanup, fireEvent, render, renderHook } from "@testing-library/react"; import { afterEach, beforeEach, describe, test } from "vitest"; -import { Core, s } from "./core"; +import { Core, noFOUCScript } from "./core"; import { useMode } from "../../hooks"; import { DARK, LIGHT } from "../../constants"; @@ -9,7 +9,7 @@ describe("theme-switcher", () => { afterEach(cleanup); beforeEach(() => { - s(STORAGE_KEY); + noFOUCScript(STORAGE_KEY); render(); }); diff --git a/lib/src/client/core/core.tsx b/lib/src/client/core/core.tsx index 73eff48f..1106e0c9 100644 --- a/lib/src/client/core/core.tsx +++ b/lib/src/client/core/core.tsx @@ -1,14 +1,16 @@ import { DARK, LIGHT } from "../../constants"; import { ColorSchemePreference, ResolvedScheme, Store, useStore } from "../../utils"; -import { useEffect } from "react"; +import { memo, useEffect } from "react"; declare global { + // skipcq: JS-0102, JS-0239 var u: (mode: ColorSchemePreference, systemMode: ResolvedScheme) => void; + // skipcq: JS-0102, JS-0239 var m: MediaQueryList; } /** function to be injected in script tag for avoiding FOUC */ -export const s = (storageKey: string) => { +export const noFOUCScript = (storageKey: string) => { const [SYSTEM, DARK] = ["system", "dark"] as const; window.u = (mode: ColorSchemePreference, systemMode: ResolvedScheme) => { const resolvedMode = mode === SYSTEM ? systemMode : mode; @@ -30,6 +32,23 @@ export const s = (storageKey: string) => { let media: MediaQueryList, updateDOM: (mode: ColorSchemePreference, systemMode: ResolvedScheme) => void; +interface ScriptProps { + /** nonce */ + n?: string; + /** storageKey */ + k: string; +} + +/** Avoid rerender of script */ +const Script = memo(({ n, k }: ScriptProps) => ( +