Skip to content

Commit

Permalink
optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank1513 committed Dec 19, 2024
1 parent 63d2487 commit ad23856
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 21 deletions.
1 change: 1 addition & 0 deletions examples/nextjs/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
2 changes: 1 addition & 1 deletion lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"vitest": "^2.1.8"
},
"dependencies": {
"r18gs": "^3.0.1"
"r18gs": "2.0.2"
},
"peerDependencies": {
"@types/react": "16.8 - 19",
Expand Down
2 changes: 1 addition & 1 deletion lib/src/client/core/core.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe("theme-switcher", () => {
await act(() => {
// globalThis.window.media = LIGHT as ResolvedScheme;
// @ts-expect-error -- ok
m.onchange?.();
q.onchange?.();
});
expect(hook.result.current.mode).toBe(DARK);
});
Expand Down
30 changes: 15 additions & 15 deletions lib/src/client/core/core.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { DARK, LIGHT } from "../../constants";
import { ColorSchemePreference, ResolvedScheme, useStore } from "../../utils";
import { useEffect } from "react";
import { noFOUCScript } from "./no-fouc";

let media: MediaQueryList,
Expand Down Expand Up @@ -36,17 +35,18 @@ export interface CoreProps {

/** Modify transition globally to avoid patched transitions */
const modifyTransition = (themeTransition = "none", nonce = "") => {
const css = document.createElement("style");
const doc = document;
const css = doc.createElement("style");
/** split by ';' to prevent CSS injection */
css.textContent = `*,*:after,*:before{transition:${themeTransition.split(";")[0]} !important;}`;
nonce && css.setAttribute("nonce", nonce);
document.head.appendChild(css);
css.setAttribute("nonce", nonce);
doc.head.appendChild(css);

return () => {
// Force restyle
getComputedStyle(document.body);
getComputedStyle(doc.body);
// Wait for next tick before removing
setTimeout(() => document.head.removeChild(css), 1);
setTimeout(() => doc.head.removeChild(css), 1);
};
};

Expand All @@ -62,14 +62,15 @@ const modifyTransition = (themeTransition = "none", nonce = "") => {
* @source - Source code
*/
export const Core = ({ t, nonce, k = "o" }: CoreProps) => {
const isWindowDefined = typeof window != "undefined";
// handle client side exceptions when script is not run. <- for client side apps like vite or CRA
if (typeof window !== "undefined" && !window.m) noFOUCScript(k);
if (isWindowDefined && !window.q) noFOUCScript(k);

const [{ m: mode, s: systemMode }, setThemeState] = useStore();
const [{ m, s }, setThemeState] = useStore();

useEffect(() => {
if (!updateDOM && isWindowDefined) {
// store global functions to local variables to avoid any interference
[media, updateDOM] = [m, u];
[media, updateDOM] = [q, u];
/** Updating media: prefers-color-scheme*/
media.addEventListener("change", () =>
setThemeState(state => ({ ...state, s: media.matches ? DARK : LIGHT })),
Expand All @@ -78,13 +79,12 @@ export const Core = ({ t, nonce, k = "o" }: CoreProps) => {
addEventListener("storage", (e: StorageEvent): void => {
e.key === k && setThemeState(state => ({ ...state, m: e.newValue as ColorSchemePreference }));
});
}, []);

useEffect(() => {
}
if (updateDOM) {
const restoreTransitions = modifyTransition(t, nonce);
updateDOM(mode, systemMode);
updateDOM(m, s);
restoreTransitions();
}, [systemMode, mode, t, nonce]);
}

return <Script {...{ n: nonce, k }} />;
};
6 changes: 3 additions & 3 deletions lib/src/client/core/no-fouc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ declare global {
// skipcq: JS-0102, JS-C1002, JS-0239
var u: (mode: ColorSchemePreference, systemMode: ResolvedScheme) => void;
// skipcq: JS-0102, JS-C1002, JS-0239
var m: MediaQueryList;
var q: MediaQueryList;
}

/** function to be injected in script tag for avoiding FOUC */
Expand All @@ -23,6 +23,6 @@ export const noFOUCScript = (storageKey: string) => {
// System mode is decided by current system state and need not be stored in localStorage
localStorage.setItem(storageKey, mode);
};
window.m = matchMedia(`(prefers-color-scheme: ${DARK})`);
u((localStorage.getItem(storageKey) ?? SYSTEM) as ColorSchemePreference, m.matches ? DARK : "");
window.q = matchMedia(`(prefers-color-scheme: ${DARK})`);
u((localStorage.getItem(storageKey) ?? SYSTEM) as ColorSchemePreference, q.matches ? DARK : "");
};
2 changes: 1 addition & 1 deletion lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface Store {
/** local abstaction of RGS to avoid multiple imports */
export const useStore = () =>
useRGS<Store>("ndm", () => {
if (typeof document === "undefined") return { m: SYSTEM, s: DARK };
if (typeof document == "undefined") return { m: SYSTEM, s: DARK };
const [m, s] = ["m", "sm"].map(dt => document.documentElement.getAttribute("data-" + dt));
return {
m: (m ?? SYSTEM) as ColorSchemePreference,
Expand Down

0 comments on commit ad23856

Please sign in to comment.