2022-02-10 11:07:14 +00:00
|
|
|
import Head from "next/head";
|
2022-03-31 08:45:47 +00:00
|
|
|
import { useRouter } from "next/router";
|
2022-02-10 11:07:14 +00:00
|
|
|
import { useEffect, useState } from "react";
|
2021-07-09 22:59:21 +00:00
|
|
|
|
2021-10-14 19:22:01 +00:00
|
|
|
import { Maybe } from "@trpc/server";
|
|
|
|
|
2022-02-16 15:53:26 +00:00
|
|
|
// This method is stringified and executed only on client. So,
|
|
|
|
// - Pass all the params explicitly to this method. Don't use closure
|
|
|
|
function applyThemeAndAddListener(theme: string) {
|
|
|
|
const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
|
|
|
|
const applyTheme = function (theme: string, darkMatch: boolean) {
|
|
|
|
if (!theme) {
|
|
|
|
if (darkMatch) {
|
|
|
|
document.documentElement.classList.add("dark");
|
|
|
|
} else {
|
|
|
|
document.documentElement.classList.remove("dark");
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
document.documentElement.classList.add(theme);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
mediaQueryList.onchange = function (e) {
|
|
|
|
applyTheme(theme, e.matches);
|
|
|
|
};
|
|
|
|
applyTheme(theme, mediaQueryList.matches);
|
|
|
|
}
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
// makes sure the ui doesn't flash
|
2021-09-27 16:09:19 +00:00
|
|
|
export default function useTheme(theme?: Maybe<string>) {
|
2021-07-09 22:59:21 +00:00
|
|
|
const [isReady, setIsReady] = useState(false);
|
2022-03-31 08:45:47 +00:00
|
|
|
const router = useRouter();
|
|
|
|
|
|
|
|
// Embed UI configuration takes more precedence over App Configuration
|
|
|
|
theme = (router.query.theme as string | null) || theme;
|
2022-02-16 15:53:26 +00:00
|
|
|
|
2022-02-10 11:07:14 +00:00
|
|
|
useEffect(() => {
|
2022-02-16 15:53:26 +00:00
|
|
|
// TODO: isReady doesn't seem required now. This is also impacting PSI Score for pages which are using isReady.
|
2022-02-08 19:19:33 +00:00
|
|
|
setIsReady(true);
|
2022-02-10 11:07:14 +00:00
|
|
|
}, []);
|
2022-02-16 15:53:26 +00:00
|
|
|
|
2022-02-10 11:07:14 +00:00
|
|
|
function Theme() {
|
2022-02-16 15:53:26 +00:00
|
|
|
const code = applyThemeAndAddListener.toString();
|
|
|
|
const themeStr = theme ? `"${theme}"` : null;
|
2022-02-10 11:07:14 +00:00
|
|
|
return (
|
|
|
|
<Head>
|
2022-02-16 15:53:26 +00:00
|
|
|
<script dangerouslySetInnerHTML={{ __html: `(${code})(${themeStr})` }}></script>
|
2022-02-10 11:07:14 +00:00
|
|
|
</Head>
|
|
|
|
);
|
|
|
|
}
|
2021-07-09 22:59:21 +00:00
|
|
|
|
|
|
|
return {
|
2021-07-11 19:35:56 +00:00
|
|
|
isReady,
|
2022-02-10 11:07:14 +00:00
|
|
|
Theme,
|
2021-07-11 19:35:56 +00:00
|
|
|
};
|
|
|
|
}
|