Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

functional theme switcher

Oleg Isonen2c2e3455d37c
diff --git a/apps/designer/app/designer/features/topbar/menu/menu.tsx b/apps/designer/app/designer/features/topbar/menu/menu.tsx
index a4f312342b..d28b8b896e 100644
--- a/apps/designer/app/designer/features/topbar/menu/menu.tsx
+++ b/apps/designer/app/designer/features/topbar/menu/menu.tsx
@@ -1,5 +1,5 @@
import { useNavigate } from "react-router-dom";
-import { publish, type Publish } from "@webstudio-is/sdk";
+import { type Publish } from "@webstudio-is/sdk";
import {
DropdownMenu,
DropdownMenuContent,
@@ -20,7 +20,7 @@ import {
useIsPublishDialogOpen,
} from "~/designer/shared/nano-states";
import { isFeatureEnabled } from "~/shared/feature-flags";
-import { getBrowserTheme } from "~/shared/theme";
+import { getThemeOption, setThemeOption } from "~/shared/theme";
const menuItemCss = {
display: "flex",
@@ -37,26 +37,14 @@ const textCss = {
const ThemeMenuItem = () => {
if (isFeatureEnabled("theme") === false) return null;
-
- const currentTheme = getBrowserTheme();
-
- const publishThemeChange = (value: string) => {
- publish({
- type: "setClientSetting",
- payload: {
- name: "theme",
- value,
- },
- });
- };
-
+ const currentOption = getThemeOption();
const labels = {
light: "Light",
dark: "Dark",
system: "System theme",
} as const;
- const themes = Object.keys(labels) as Array<keyof typeof labels>;
+ const options = Object.keys(labels) as Array<keyof typeof labels>;
return (
<DropdownMenu>
@@ -65,16 +53,16 @@ const ThemeMenuItem = () => {
<ChevronRightIcon />
</DropdownMenuTriggerItem>
<DropdownMenuContent>
- {themes.map((theme) => (
+ {options.map((option) => (
<DropdownMenuCheckboxItem
- key={theme}
- checked={currentTheme === theme}
+ key={option}
+ checked={currentOption === option}
css={menuItemCss}
onSelect={() => {
- publishThemeChange(theme);
+ setThemeOption(option);
}}
>
- <Text css={textCss}>{labels[theme]}</Text>
+ <Text css={textCss}>{labels[option]}</Text>
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
diff --git a/apps/designer/app/entry.server.tsx b/apps/designer/app/entry.server.tsx
index 245bda73b5..971c090aa0 100644
--- a/apps/designer/app/entry.server.tsx
+++ b/apps/designer/app/entry.server.tsx
@@ -5,7 +5,6 @@ import type { EntryContext } from "@remix-run/node";
import * as Sentry from "@sentry/remix";
import { initSentry } from "./shared/sentry";
import { prisma } from "./shared/db/prisma.server";
-import { insertTheme } from "./shared/theme";
initSentry({
integrations: [new Sentry.Integrations.Prisma({ client: prisma })],
@@ -22,9 +21,9 @@ export default async function handleRequest(
);
markup = insertCriticalCss(markup, request.url);
- markup = await insertTheme(markup, request.headers);
responseHeaders.set("Content-Type", "text/html");
+ responseHeaders.set("Accept-CH", "Sec-CH-Prefers-Color-Scheme");
return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
diff --git a/apps/designer/app/routes/dashboard.tsx b/apps/designer/app/routes/dashboard.tsx
index 936c0f8323..ca41594442 100644
--- a/apps/designer/app/routes/dashboard.tsx
+++ b/apps/designer/app/routes/dashboard.tsx
@@ -1,10 +1,14 @@
import type { LoaderFunction, MetaFunction } from "@remix-run/node";
import { Designer } from "~/shared/documents/designer";
import env from "~/env.server";
+import { getServerTheme } from "~/shared/theme/theme.server";
-export const loader: LoaderFunction = () => ({
- env,
-});
+export const loader: LoaderFunction = async ({ request }) => {
+ return {
+ env,
+ theme: await getServerTheme(request),
+ };
+};
export const meta: MetaFunction = () => {
return { title: "Webstudio Dashboard" };
diff --git a/apps/designer/app/routes/designer.tsx b/apps/designer/app/routes/designer.tsx
index 748f54ac9b..e7ebd09bc3 100644
--- a/apps/designer/app/routes/designer.tsx
+++ b/apps/designer/app/routes/designer.tsx
@@ -1,21 +1,17 @@
-import type {
- HeadersFunction,
- LoaderFunction,
- MetaFunction,
-} from "@remix-run/node";
+import type { LoaderFunction, MetaFunction } from "@remix-run/node";
import { Designer } from "~/shared/documents/designer";
import env from "~/env.server";
+import { getServerTheme } from "~/shared/theme/theme.server";
-export const loader: LoaderFunction = () => ({
- env,
-});
+export const loader: LoaderFunction = async ({ request }) => {
+ return {
+ env,
+ theme: await getServerTheme(request),
+ };
+};
export const meta: MetaFunction = () => {
return { title: "Webstudio" };
};
-export const headers: HeadersFunction = () => ({
- "Accept-CH": "Sec-CH-Prefers-Color-Scheme",
-});
-
export default Designer;
diff --git a/apps/designer/app/routes/designer/$id.tsx b/apps/designer/app/routes/designer/$id.tsx
index 3babd37a9a..e76fddaf30 100644
--- a/apps/designer/app/routes/designer/$id.tsx
+++ b/apps/designer/app/routes/designer/$id.tsx
@@ -1,13 +1,18 @@
import { useLoaderData } from "@remix-run/react";
-import type { LoaderFunction } from "@remix-run/node";
+import { LoaderFunction, redirect } from "@remix-run/node";
import type { Project } from "@webstudio-is/sdk";
import { Designer, links } from "~/designer";
import * as db from "~/shared/db";
import config from "~/config";
import env from "~/env.server";
+import { authenticator } from "~/services/auth.server";
export { links };
-export const loader: LoaderFunction = async ({ params }) => {
+export const loader: LoaderFunction = async ({ request, params }) => {
+ const user = await authenticator.isAuthenticated(request);
+ if (!user) {
+ return redirect(config.loginPath);
+ }
if (params.id === undefined) throw new Error("Project id undefined");
const project = await db.project.loadById(params.id);
if (project === null) {
diff --git a/apps/designer/app/routes/index.tsx b/apps/designer/app/routes/index.tsx
index 138289439f..26211f87dd 100644
--- a/apps/designer/app/routes/index.tsx
+++ b/apps/designer/app/routes/index.tsx
@@ -1,8 +1,4 @@
-import {
- type HeadersFunction,
- redirect,
- type LoaderFunction,
-} from "@remix-run/node";
+import { redirect, type LoaderFunction } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { Root, type Data } from "@webstudio-is/sdk";
import config from "~/config";
@@ -17,10 +13,6 @@ type LoaderReturnProps = Promise<
(Data & { env: Env }) | (Error & { env: Env }) | Response
>;
-export const headers: HeadersFunction = () => ({
- "Accept-CH": "Sec-CH-Prefers-Color-Scheme",
-});
-
export const loader: LoaderFunction = async ({
request,
}): LoaderReturnProps => {
diff --git a/apps/designer/app/routes/login.tsx b/apps/designer/app/routes/login.tsx
index 2c24216657..66b2c3c640 100644
--- a/apps/designer/app/routes/login.tsx
+++ b/apps/designer/app/routes/login.tsx
@@ -1,10 +1,14 @@
import { LoaderFunction, MetaFunction } from "@remix-run/node";
import { Designer } from "~/shared/documents/designer";
import env from "~/env.server";
+import { getServerTheme } from "~/shared/theme/theme.server";
-export const loader: LoaderFunction = () => ({
- env,
-});
+export const loader: LoaderFunction = async ({ request }) => {
+ return {
+ env,
+ theme: await getServerTheme(request),
+ };
+};
export const meta: MetaFunction = () => {
return { title: "Webstudio Login" };
diff --git a/apps/designer/app/routes/rest/theme.$option.ts b/apps/designer/app/routes/rest/theme.$option.ts
new file mode 100644
index 0000000000..384e703391
--- /dev/null
+++ b/apps/designer/app/routes/rest/theme.$option.ts
@@ -0,0 +1,10 @@
+import { json, type LoaderFunction } from "@remix-run/node";
+import { themeCookieParser } from "~/shared/theme/index.server";
+
+export const loader: LoaderFunction = async ({ params }) => {
+ const { option } = params;
+ const headers = {
+ "Set-Cookie": await themeCookieParser.serialize(option),
+ };
+ return json({ option }, { headers });
+};
diff --git a/apps/designer/app/shared/documents/designer.tsx b/apps/designer/app/shared/documents/designer.tsx
index c4771f8dbb..859680748d 100644
--- a/apps/designer/app/shared/documents/designer.tsx
+++ b/apps/designer/app/shared/documents/designer.tsx
@@ -1,11 +1,12 @@
import { Links, LiveReload, Meta, Outlet, Scripts } from "@remix-run/react";
import { CriticalCss } from "@webstudio-is/sdk";
import { Env } from "~/shared/env";
-import { getThemePlaceholder } from "~/shared/theme";
+import { useThemeProps } from "~/shared/theme";
export const Designer = () => {
+ const themeProps = useThemeProps();
return (
- <html lang="en" {...getThemePlaceholder()}>
+ <html lang="en" {...themeProps}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
diff --git a/apps/designer/app/shared/feature-flags/feature.ts b/apps/designer/app/shared/feature-flags/feature.ts
index c000c73826..0385a3adff 100644
--- a/apps/designer/app/shared/feature-flags/feature.ts
+++ b/apps/designer/app/shared/feature-flags/feature.ts
@@ -28,5 +28,5 @@ export const isFeatureEnabled = (name: Name): boolean => {
const defaultValue = flags[name];
const envValue = parse(env.FEATURE).includes(name);
const localValue = readLocal().includes(name);
- return localValue ?? envValue ?? defaultValue;
+ return localValue || envValue || defaultValue;
};
diff --git a/apps/designer/app/shared/theme/index.server.ts b/apps/designer/app/shared/theme/index.server.ts
new file mode 100644
index 0000000000..6a20ed7455
--- /dev/null
+++ b/apps/designer/app/shared/theme/index.server.ts
@@ -0,0 +1,2 @@
+export * from "./theme";
+export * from "./theme.server";
diff --git a/apps/designer/app/shared/theme/shared.ts b/apps/designer/app/shared/theme/shared.ts
new file mode 100644
index 0000000000..e415297314
--- /dev/null
+++ b/apps/designer/app/shared/theme/shared.ts
@@ -0,0 +1,5 @@
+export type ThemeName = "dark" | "light";
+
+export type ThemeOption = ThemeName | "system";
+
+export const cookieNamespace = "theme";
diff --git a/apps/designer/app/shared/theme/theme.server.ts b/apps/designer/app/shared/theme/theme.server.ts
new file mode 100644
index 0000000000..40f5d44c4c
--- /dev/null
+++ b/apps/designer/app/shared/theme/theme.server.ts
@@ -0,0 +1,14 @@
+import { createCookie } from "@remix-run/node";
+import { cookieNamespace, type ThemeName, type ThemeOption } from "./shared";
+
+export const themeCookieParser = createCookie(cookieNamespace);
+
+export const getServerTheme = async (
+ request: Request
+): Promise<{ system?: ThemeName; option?: ThemeOption }> => {
+ const system = (request.headers.get("Sec-CH-Prefers-Color-Scheme") ??
+ undefined) as ThemeName | undefined;
+ const option: ThemeOption =
+ (await themeCookieParser.parse(request.headers.get("Cookie"))) ?? undefined;
+ return { system, option };
+};
diff --git a/apps/designer/app/shared/theme/theme.ts b/apps/designer/app/shared/theme/theme.ts
index 6103d3d242..f87aa7e098 100644
--- a/apps/designer/app/shared/theme/theme.ts
+++ b/apps/designer/app/shared/theme/theme.ts
@@ -1,48 +1,75 @@
-import { createCookie } from "@remix-run/node";
-import browserCookies from "js-cookie";
-import { darkTheme } from "~/shared/design-system/stitches.config";
+import { useLoaderData } from "@remix-run/react";
+import { darkTheme } from "~/shared/design-system";
+import { type ThemeName, type ThemeOption } from "./shared";
-type ColorScheme = "dark" | "light";
+// User selected theme option.
+let option: ThemeOption = "dark";
+// Current systeme theme.
+let system: ThemeName;
-const placeholder = "__theme_placeholder__";
+const subscribeSystemTheme = () => {
+ if (typeof matchMedia === "undefined") return;
+ const query = matchMedia("(prefers-color-scheme: light)");
+ const getTheme = (query: MediaQueryList | MediaQueryListEvent) =>
+ query.matches ? "light" : "dark";
-const cookieNamespace = "theme";
+ system = getTheme(query);
-// @todo todo switch to light by default once ready
-const defaultTheme = "dark";
+ query.addEventListener("change", (queryEvent) => {
+ system = getTheme(queryEvent);
+ setDomProps();
+ });
+};
+
+subscribeSystemTheme();
-export const getBrowserTheme = () => {
- return browserCookies.get(cookieNamespace) || defaultTheme;
+export const getThemeOption = (): ThemeOption => {
+ return option;
};
-const getCookieTheme = async (headers: Headers): Promise<ColorScheme> => {
- const cookieTheme = await createCookie(cookieNamespace).parse(
- headers.get("Cookie")
- );
- if (cookieTheme === "system") {
- const system = headers.get("Sec-CH-Prefers-Color-Scheme");
- if (system === "light" || system === "dark") {
- return system;
- }
+// @todo todo switch to light by default once ready
+export const defaultTheme = "dark";
+
+const selectTheme = ({
+ system = defaultTheme,
+ option,
+}: {
+ system: ThemeName;
+ option?: ThemeOption;
+}): ThemeName => {
+ if (option === "system") {
+ return system;
}
- return cookieTheme || defaultTheme;
+ return option || defaultTheme;
};
-export const getThemePlaceholder = () => {
- if (typeof document === "undefined") {
- return {
- className: placeholder,
- style: { colorScheme: placeholder },
- };
+const getThemeProps = () => {
+ const theme = selectTheme({ option, system });
+ if (theme === "dark") {
+ // We need to call it so that vars get injected!!!
+ darkTheme.toString();
}
- const theme = getBrowserTheme();
return {
- className: theme === "dark" ? darkTheme.toString() : "light",
+ className: theme,
style: { colorScheme: theme },
};
};
-export const insertTheme = async (markup: string, headers: Headers) => {
- const theme = await getCookieTheme(headers);
- return markup.replace(new RegExp(placeholder, "gi"), theme);
+const setDomProps = () => {
+ const props = getThemeProps();
+ document.documentElement.className = props.className;
+ document.documentElement.style.colorScheme = props.style.colorScheme;
+};
+
+export const setThemeOption = (nextOption: ThemeOption) => {
+ option = nextOption;
+ setDomProps();
+ fetch(`/rest/theme/${option}`);
+};
+
+export const useThemeProps = () => {
+ const data = useLoaderData();
+ if (data.theme.option) option = data.theme.option;
+ if (data.theme.system) system = data.theme.system;
+ return getThemeProps();
};
diff --git a/apps/designer/package.json b/apps/designer/package.json
index cc32e758b8..87fe48f801 100644
--- a/apps/designer/package.json
+++ b/apps/designer/package.json
@@ -60,7 +60,6 @@
"hyphenate-style-name": "^1.0.4",
"immer": "^9.0.12",
"immerhin": "^0.1.2",
- "js-cookie": "^3.0.1",
"lexical": "^0.3.5",
"lodash.capitalize": "^4.2.1",
"lodash.debounce": "^4.0.8",
diff --git a/yarn.lock b/yarn.lock
index 9ddce00c82..b27560e4e0 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -10229,11 +10229,6 @@ js-cookie@^2.2.1:
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8"
integrity sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==
-js-cookie@^3.0.1:
- version "3.0.1"
- resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-3.0.1.tgz#9e39b4c6c2f56563708d7d31f6f5f21873a92414"
- integrity sha512-+0rgsUXZu4ncpPxRL+lNEptWMOWl9etvPHc/koSRp6MPwpRYAhmk0dUG00J4bxVV3r9uUzfo24wW0knS07SKSw==
-
js-string-escape@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/js-string-escape/-/js-string-escape-1.0.1.tgz#e2625badbc0d67c7533e9edc1068c587ae4137ef"