Skip to content

feat(react-email): added a theme switcher to the dev preview #1749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dirty-needles-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-email": minor
---

Theme switcher for email template
29 changes: 14 additions & 15 deletions packages/react-email/src/app/preview/[...slug]/preview.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import React, { useRef } from 'react';
import { Toaster } from 'sonner';
import type { EmailRenderingResult } from '../../../actions/render-email-by-path';
import { CodeContainer } from '../../../components/code-container';
import { Shell } from '../../../components/shell';
import { Tooltip } from '../../../components/tooltip';
import { useEmailRenderingResult } from '../../../hooks/use-email-rendering-result';
import { useHotreload } from '../../../hooks/use-hot-reload';
import { useIframeColorScheme } from '../../../hooks/use-iframe-color-scheme';
import { useRenderingMetadata } from '../../../hooks/use-rendering-metadata';
import { RenderingError } from './rendering-error';

Expand All @@ -29,6 +30,7 @@ const Preview = ({
const pathname = usePathname();
const searchParams = useSearchParams();

const activeTheme = searchParams.get('theme') ?? 'light';
const activeView = searchParams.get('view') ?? 'desktop';
const activeLang = searchParams.get('lang') ?? 'jsx';

Expand All @@ -43,6 +45,9 @@ const Preview = ({
serverRenderingResult,
);

const iframeRef = useRef<HTMLIFrameElement>(null);
useIframeColorScheme(iframeRef, activeTheme);

if (process.env.NEXT_PUBLIC_IS_BUILDING !== 'true') {
// this will not change on runtime so it doesn't violate
// the rules of hooks
Expand All @@ -60,28 +65,20 @@ const Preview = ({
});
}

const handleViewChange = (view: string) => {
const params = new URLSearchParams(searchParams);
params.set('view', view);
router.push(`${pathname}?${params.toString()}`);
};
const hasNoErrors = typeof renderedEmailMetadata !== 'undefined';

const handleLangChange = (lang: string) => {
const setActiveLang = (lang: string) => {
const params = new URLSearchParams(searchParams);
params.set('view', 'source');
params.set('lang', lang);
router.push(`${pathname}?${params.toString()}`);
};

const hasNoErrors = typeof renderedEmailMetadata !== 'undefined';

return (
<Shell
activeView={hasNoErrors ? activeView : undefined}
currentEmailOpenSlug={slug}
markup={renderedEmailMetadata?.markup}
pathSeparator={pathSeparator}
setActiveView={hasNoErrors ? handleViewChange : undefined}
>
{/* This relative is so that when there is any error the user can still switch between emails */}
<div className="relative h-full">
Expand All @@ -93,22 +90,24 @@ const Preview = ({
<>
{activeView === 'desktop' && (
<iframe
className="w-full bg-white h-[calc(100vh_-_140px)] lg:h-[calc(100vh_-_70px)]"
className="h-[calc(100vh_-_140px)] w-full bg-white lg:h-[calc(100vh_-_70px)]"
ref={iframeRef}
srcDoc={renderedEmailMetadata.markup}
title={slug}
/>
)}

{activeView === 'mobile' && (
<iframe
className="w-[360px] bg-white h-[calc(100vh_-_140px)] lg:h-[calc(100vh_-_70px)] mx-auto"
className="mx-auto h-[calc(100vh_-_140px)] w-[360px] bg-white lg:h-[calc(100vh_-_70px)]"
ref={iframeRef}
srcDoc={renderedEmailMetadata.markup}
title={slug}
/>
)}

{activeView === 'source' && (
<div className="flex gap-6 mx-auto p-6 max-w-3xl">
<div className="mx-auto flex max-w-3xl gap-6 p-6">
<Tooltip.Provider>
<CodeContainer
activeLang={activeLang}
Expand All @@ -126,7 +125,7 @@ const Preview = ({
content: renderedEmailMetadata.plainText,
},
]}
setActiveLang={handleLangChange}
setActiveLang={setActiveLang}
/>
</Tooltip.Provider>
</div>
Expand Down
16 changes: 16 additions & 0 deletions packages/react-email/src/components/icons/icon-moon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as React from 'react';
import type { IconElement, IconProps } from './icon-base';
import { IconBase } from './icon-base';

export const IconMoon = React.forwardRef<IconElement, Readonly<IconProps>>(
({ ...props }, forwardedRef) => (
<IconBase ref={forwardedRef} {...props}>
<path
fill="currentColor"
d="m17.75 4.09l-2.53 1.94l.91 3.06l-2.63-1.81l-2.63 1.81l.91-3.06l-2.53-1.94L12.44 4l1.06-3l1.06 3zm3.5 6.91l-1.64 1.25l.59 1.98l-1.7-1.17l-1.7 1.17l.59-1.98L15.75 11l2.06-.05L18.5 9l.69 1.95zm-2.28 4.95c.83-.08 1.72 1.1 1.19 1.85c-.32.45-.66.87-1.08 1.27C15.17 23 8.84 23 4.94 19.07c-3.91-3.9-3.91-10.24 0-14.14c.4-.4.82-.76 1.27-1.08c.75-.53 1.93.36 1.85 1.19c-.27 2.86.69 5.83 2.89 8.02a9.96 9.96 0 0 0 8.02 2.89m-1.64 2.02a12.08 12.08 0 0 1-7.8-3.47c-2.17-2.19-3.33-5-3.49-7.82c-2.81 3.14-2.7 7.96.31 10.98c3.02 3.01 7.84 3.12 10.98.31"
/>
</IconBase>
),
);

IconMoon.displayName = 'IconMoon';
16 changes: 16 additions & 0 deletions packages/react-email/src/components/icons/icon-sun.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as React from 'react';
import type { IconElement, IconProps } from './icon-base';
import { IconBase } from './icon-base';

export const IconSun = React.forwardRef<IconElement, Readonly<IconProps>>(
({ ...props }, forwardedRef) => (
<IconBase ref={forwardedRef} {...props}>
<path
fill="currentColor"
d="m3.55 19.09l1.41 1.41l1.8-1.79l-1.42-1.42M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6s6-2.69 6-6c0-3.32-2.69-6-6-6m8 7h3v-2h-3m-2.76 7.71l1.8 1.79l1.41-1.41l-1.79-1.8M20.45 5l-1.41-1.4l-1.8 1.79l1.42 1.42M13 1h-2v3h2M6.76 5.39L4.96 3.6L3.55 5l1.79 1.81zM1 13h3v-2H1m12 9h-2v3h2"
/>
</IconBase>
),
);

IconSun.displayName = 'IconSun';
8 changes: 1 addition & 7 deletions packages/react-email/src/components/shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,13 @@ interface ShellProps extends RootProps {
markup?: string;
currentEmailOpenSlug?: string;
pathSeparator?: string;
activeView?: string;
setActiveView?: (view: string) => void;
}

export const Shell = ({
currentEmailOpenSlug,
children,
pathSeparator,
markup,
activeView,
setActiveView,
}: ShellProps) => {
const [sidebarToggled, setSidebarToggled] = React.useState(false);
const [triggerTransition, setTriggerTransition] = React.useState(false);
Expand Down Expand Up @@ -89,7 +85,6 @@ export const Shell = ({
>
{currentEmailOpenSlug && pathSeparator ? (
<Topbar
activeView={activeView}
currentEmailOpenSlug={currentEmailOpenSlug}
markup={markup}
onToggleSidebar={() => {
Expand All @@ -104,11 +99,10 @@ export const Shell = ({
}, 300);
}}
pathSeparator={pathSeparator}
setActiveView={setActiveView}
/>
) : null}

<div className="h-[calc(100vh_-_70px)] overflow-auto mx-auto">
<div className="h-[calc(100vh_-_70px)] overflow-auto mx-auto ">
{children}
</div>
</main>
Expand Down
112 changes: 99 additions & 13 deletions packages/react-email/src/components/topbar.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,58 @@
'use client';
import * as ToggleGroup from '@radix-ui/react-toggle-group';
import { motion } from 'framer-motion';
import type * as React from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { cn } from '../utils';
import { tabTransition } from '../utils/constants';
import { Heading } from './heading';
import { IconHideSidebar } from './icons/icon-hide-sidebar';
import { IconMonitor } from './icons/icon-monitor';
import { IconMoon } from './icons/icon-moon';
import { IconPhone } from './icons/icon-phone';
import { IconSource } from './icons/icon-source';
import { IconSun } from './icons/icon-sun';
import { Send } from './send';
import { Tooltip } from './tooltip';

interface TopbarProps {
currentEmailOpenSlug: string;
pathSeparator: string;
activeView?: string;
markup?: string;
onToggleSidebar?: () => void;
setActiveView?: (view: string) => void;
}

export const Topbar: React.FC<Readonly<TopbarProps>> = ({
currentEmailOpenSlug,
pathSeparator,
markup,
activeView,
setActiveView,
onToggleSidebar,
}) => {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const activeTheme = searchParams.get('theme') ?? 'light';
const activeView = searchParams.get('view') ?? 'desktop';

const setActiveView = (view: string) => {
const params = new URLSearchParams(searchParams);
params.set('view', view);
router.push(`${pathname}?${params.toString()}`);
};

const setTheme = (theme: string) => {
const params = new URLSearchParams(searchParams);
params.set('theme', theme);
router.push(`${pathname}?${params.toString()}`);
};

return (
<Tooltip.Provider>
<header className="flex relative items-center px-4 justify-between h-[70px] border-b border-slate-6">
<header className="relative flex h-[70px] items-center justify-between border-slate-6 border-b px-4">
<Tooltip>
<Tooltip.Trigger asChild>
<button
className="hidden lg:flex rounded-lg px-2 py-2 transition ease-in-out duration-200 relative hover:bg-slate-5 text-slate-11 hover:text-slate-12"
className="relative hidden rounded-lg px-2 py-2 text-slate-11 transition duration-200 ease-in-out hover:bg-slate-5 hover:text-slate-12 lg:flex"
onClick={() => {
if (onToggleSidebar) {
onToggleSidebar();
Expand All @@ -49,18 +66,87 @@ export const Topbar: React.FC<Readonly<TopbarProps>> = ({
<Tooltip.Content>Show/hide sidebar</Tooltip.Content>
</Tooltip>

<div className="items-center overflow-hidden hidden lg:flex text-center absolute left-1/2 transform -translate-x-1/2 top-1/2 -translate-y-1/2">
<div className="-translate-x-1/2 -translate-y-1/2 absolute top-1/2 left-1/2 hidden transform items-center overflow-hidden text-center lg:flex">
<Heading as="h2" className="truncate" size="2" weight="medium">
{currentEmailOpenSlug.split(pathSeparator).pop()}
</Heading>
</div>

<div className="flex gap-3 justify-between lg:justify-start w-full lg:w-fit">
<div className="flex w-full justify-between gap-3 lg:w-fit lg:justify-start">
<ToggleGroup.Root
aria-label="Color Scheme"
className="inline-block items-center bg-slate-2 border border-slate-6 rounded-md overflow-hidden h-[36px]"
id="theme-toggle"
onValueChange={(value) => {
if (value) setTheme(value);
}}
type="single"
value={activeTheme}
>
<ToggleGroup.Item value="light">
<Tooltip>
<Tooltip.Trigger asChild>
<div
className={cn(
'relative px-3 py-2 transition duration-200 ease-in-out hover:text-slate-12',
{
'text-slate-11': activeTheme !== 'light',
'text-slate-12': activeTheme === 'light',
},
)}
>
{activeTheme === 'light' && (
<motion.span
animate={{ opacity: 1 }}
className="absolute top-0 right-0 bottom-0 left-0 bg-slate-4"
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
layoutId="topbar-theme-tabs"
transition={tabTransition}
/>
)}
<IconSun />
</div>
</Tooltip.Trigger>
<Tooltip.Content>Light</Tooltip.Content>
</Tooltip>
</ToggleGroup.Item>
<ToggleGroup.Item value="dark">
<Tooltip>
<Tooltip.Trigger asChild>
<div
className={cn(
'relative px-3 py-2 transition duration-200 ease-in-out hover:text-slate-12',
{
'text-slate-11': activeTheme !== 'dark',
'text-slate-12': activeTheme === 'dark',
},
)}
>
{activeTheme === 'dark' && (
<motion.span
animate={{ opacity: 1 }}
className="absolute top-0 right-0 bottom-0 left-0 bg-slate-4"
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
layoutId="topbar-theme-tabs"
transition={tabTransition}
/>
)}
<IconMoon />
</div>
</Tooltip.Trigger>
<Tooltip.Content>Dark</Tooltip.Content>
</Tooltip>
</ToggleGroup.Item>
</ToggleGroup.Root>

<ToggleGroup.Root
aria-label="View mode"
className="inline-block items-center bg-slate-2 border border-slate-6 rounded-md overflow-hidden h-[36px]"
id="view-toggle"
onValueChange={(value) => {
if (value) setActiveView?.(value);
if (value) setActiveView(value);
}}
type="single"
value={activeView}
Expand All @@ -83,7 +169,7 @@ export const Topbar: React.FC<Readonly<TopbarProps>> = ({
className="absolute left-0 right-0 top-0 bottom-0 bg-slate-4"
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
layoutId="topbar-tabs"
layoutId="topbar-view-tabs"
transition={tabTransition}
/>
)}
Expand Down Expand Up @@ -111,7 +197,7 @@ export const Topbar: React.FC<Readonly<TopbarProps>> = ({
className="absolute left-0 right-0 top-0 bottom-0 bg-slate-4"
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
layoutId="topbar-tabs"
layoutId="topbar-view-tabs"
transition={tabTransition}
/>
)}
Expand Down Expand Up @@ -139,7 +225,7 @@ export const Topbar: React.FC<Readonly<TopbarProps>> = ({
className="absolute left-0 right-0 top-0 bottom-0 bg-slate-4"
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
layoutId="topbar-tabs"
layoutId="topbar-view-tabs"
transition={tabTransition}
/>
)}
Expand Down
Loading
Loading