calcom/apps/web/lib/hooks/useTheme.tsx
Hariom Balhara 174ed9f6d1
Embed Snippet Generator (#2597)
* Add support to dynamically change the theme

* Add Embed UI in app

* Update UI as per Figma

* Dynamicaly update Embed Code

* Get differnet modes working in preview

* Support Embed on EventType Edit, Team Link Fix and Mobile unsupported

* Fix auto theme switch in Embed Snippet generator

* Fix types

* Self Review fixes

* Remove Embed from App section

* Move get query after the middleware to let middleware work on it

* Add sandboxes in the document

* Add error handling for embed loading

* Fix types

* Update snapshots and fix bug identified by tests

* UI Fixes

* Add Embed Tests

* Respond in preview to width and height

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-05 08:29:49 -06:00

59 lines
1.8 KiB
TypeScript

import Head from "next/head";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useEmbedTheme } from "@calcom/embed-core";
import { Maybe } from "@trpc/server";
// 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.remove("dark");
document.documentElement.classList.remove("light");
document.documentElement.classList.add(theme);
}
};
mediaQueryList.onchange = function (e) {
applyTheme(theme, e.matches);
};
applyTheme(theme, mediaQueryList.matches);
}
// makes sure the ui doesn't flash
export default function useTheme(theme?: Maybe<string>) {
const [isReady, setIsReady] = useState(false);
const embedTheme = useEmbedTheme();
// Embed UI configuration takes more precedence over App Configuration
theme = embedTheme || theme;
const [_theme, setTheme] = useState<Maybe<string>>(null);
useEffect(() => {
// TODO: isReady doesn't seem required now. This is also impacting PSI Score for pages which are using isReady.
setIsReady(true);
setTheme(theme);
}, [theme]);
function Theme() {
const code = applyThemeAndAddListener.toString();
const themeStr = _theme ? `"${_theme}"` : null;
return (
<Head>
<script dangerouslySetInnerHTML={{ __html: `(${code})(${themeStr})` }}></script>
</Head>
);
}
return {
isReady,
Theme,
};
}