Skip to content
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

feat(react-email): Customizable email view size #1837

Open
wants to merge 16 commits into
base: 4.0
Choose a base branch
from
Open
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/empty-phones-relax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-email": minor
---

Make the width and height for the preview of the email customizable
1 change: 1 addition & 0 deletions packages/react-email/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"devDependencies": {
"@radix-ui/colors": "1.0.1",
"@radix-ui/react-collapsible": "1.1.0",
"@radix-ui/react-dropdown-menu": "2.1.4",
"@radix-ui/react-popover": "1.1.1",
"@radix-ui/react-slot": "1.1.0",
"@radix-ui/react-toggle-group": "1.1.0",
Expand Down
75 changes: 56 additions & 19 deletions packages/react-email/src/app/preview/[...slug]/preview.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import { Toaster } from 'sonner';
import { useHotreload } from '../../../hooks/use-hot-reload';
import type { EmailRenderingResult } from '../../../actions/render-email-by-path';
Expand All @@ -10,6 +9,11 @@ import { Shell } from '../../../components/shell';
import { Tooltip } from '../../../components/tooltip';
import { useEmails } from '../../../contexts/emails';
import { useRenderingMetadata } from '../../../hooks/use-rendering-metadata';
import {
makeIframeDocumentBubbleEvents,
ResizableWarpper,
} from '../../../components/resizable-wrapper';
import { useClampedState } from '../../../hooks/use-clamped-state';
import { RenderingError } from './rendering-error';

interface PreviewProps {
Expand All @@ -29,7 +33,7 @@ const Preview = ({
const pathname = usePathname();
const searchParams = useSearchParams();

const activeView = searchParams.get('view') ?? 'desktop';
const activeView = searchParams.get('view') ?? 'preview';
const activeLang = searchParams.get('lang') ?? 'jsx';
const { useEmailRenderingResult } = useEmails();

Expand Down Expand Up @@ -76,37 +80,70 @@ const Preview = ({

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

const [width, setWidth] = useClampedState(600, 350, Number.POSITIVE_INFINITY);
const [height, setHeight] = useClampedState(
1024,
600,
Number.POSITIVE_INFINITY,
);

return (
<Shell
activeView={hasNoErrors ? activeView : undefined}
activeView={activeView}
currentEmailOpenSlug={slug}
markup={renderedEmailMetadata?.markup}
pathSeparator={pathSeparator}
setActiveView={hasNoErrors ? handleViewChange : undefined}
setActiveView={handleViewChange}
setViewHeight={setHeight}
setViewWidth={setWidth}
viewHeight={height}
viewWidth={width}
>
{/* This relative is so that when there is any error the user can still switch between emails */}
<div className="relative h-full">
<div className="relative h-full flex">
{'error' in renderingResult ? (
<RenderingError error={renderingResult.error} />
) : null}

{/* If this is undefined means that the initial server render of the email had errors */}
{hasNoErrors ? (
<>
{activeView === 'desktop' && (
<iframe
className="w-full bg-white h-[calc(100vh_-_140px)] lg:h-[calc(100vh_-_70px)]"
srcDoc={renderedEmailMetadata.markup}
title={slug}
/>
)}

{activeView === 'mobile' && (
<iframe
className="w-[360px] bg-white h-[calc(100vh_-_140px)] lg:h-[calc(100vh_-_70px)] mx-auto"
srcDoc={renderedEmailMetadata.markup}
title={slug}
/>
{activeView === 'preview' && (
<ResizableWarpper
height={height}
onResize={(difference, direction) => {
switch (direction) {
case 'north':
setHeight((h) => h + 2 * difference);
break;
case 'south':
setHeight((h) => h + 2 * difference);
break;
case 'east':
setWidth((w) => w + 2 * difference);
break;
case 'west':
setWidth((w) => w + 2 * difference);
break;
}
}}
width={width}
>
<iframe
className="bg-white rounded-lg max-h-full"
ref={(iframe) => {
if (iframe) {
return makeIframeDocumentBubbleEvents(iframe);
}
}}
srcDoc={renderedEmailMetadata.markup}
style={{
width: `${width}px`,
height: `${height}px`,
}}
title={slug}
/>
</ResizableWarpper>
)}

{activeView === 'source' && (
Expand Down
128 changes: 128 additions & 0 deletions packages/react-email/src/components/resizable-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { useEffect } from 'react';

type Direction = 'north' | 'south' | 'east' | 'west';

interface ResizableWarpperProps {
width: number;
height: number;

onResize: (difference: number, direction: Direction) => void;

children: React.ReactNode;
}

export const makeIframeDocumentBubbleEvents = (iframe: HTMLIFrameElement) => {
const mouseMoveBubbler = (event: MouseEvent) => {
document.dispatchEvent(new MouseEvent('mousemove', event));
};
const mouseUpBubbler = (event: MouseEvent) => {
document.dispatchEvent(new MouseEvent('mouseup', event));
};
iframe.contentDocument?.addEventListener('mousemove', mouseMoveBubbler);
iframe.contentDocument?.addEventListener('mouseup', mouseUpBubbler);
return () => {
iframe.contentDocument?.removeEventListener('mousemove', mouseMoveBubbler);
iframe.contentDocument?.removeEventListener('mouseup', mouseUpBubbler);
};
};

export const ResizableWarpper = ({
width,
height,
onResize,
children,
}: ResizableWarpperProps) => {
let mouseMoveListener: ((event: MouseEvent) => void) | undefined;

const handleStopResizing = () => {
if (mouseMoveListener) {
document.removeEventListener('mousemove', mouseMoveListener);
}
document.removeEventListener('mouseup', handleStopResizing);
};

const handleStartResizing = (direction: Direction) => {
mouseMoveListener = (event) => {
if (event.button === 0) {
const signMultiplier =
direction === 'west' || direction === 'north' ? -1 : 1;
const difference =
direction === 'east' || direction === 'west'
? event.movementX
: event.movementY;
onResize(difference * signMultiplier, direction);
} else {
handleStopResizing();
}
};

document.addEventListener('mouseup', handleStopResizing);
document.addEventListener('mousemove', mouseMoveListener);
};

useEffect(() => {
return () => {
handleStopResizing();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<div className="relative box-content px-4 py-2 mx-auto my-auto">
<div
aria-label="resize-west"
aria-valuenow={width}
className="absolute [user-drag:none] cursor-w-resize p-2 left-2 top-1/2 -translate-x-1/2 -translate-y-1/2"
draggable="false"
onMouseDown={() => {
handleStartResizing('west');
}}
role="slider"
tabIndex={0}
>
<div className="rounded-md w-1 h-8 bg-slate-8" />
</div>
<div
aria-label="resize-east"
aria-valuenow={width}
className="absolute [user-drag:none] cursor-e-resize p-2 left-full top-1/2 -translate-x-full -translate-y-1/2"
draggable="false"
onMouseDown={() => {
handleStartResizing('east');
}}
role="slider"
tabIndex={0}
>
<div className="rounded-md w-1 h-8 bg-slate-8" />
</div>
<div
aria-label="resize-north"
aria-valuenow={height}
className="absolute [user-drag:none] cursor-n-resize p-2 left-1/2 top-0 -translate-x-1/2 -translate-y-1/2"
draggable="false"
onMouseDown={() => {
handleStartResizing('north');
}}
role="slider"
tabIndex={0}
>
<div className="rounded-md w-8 h-1 bg-slate-8" />
</div>
<div
aria-label="resize-south"
aria-valuenow={height}
className="absolute [user-drag:none] cursor-s-resize p-2 left-1/2 top-full -translate-x-1/2 -translate-y-1/2"
draggable="false"
onMouseDown={() => {
handleStartResizing('south');
}}
role="slider"
tabIndex={0}
>
<div className="rounded-md w-8 h-1 bg-slate-8" />
</div>

{children}
</div>
);
};
14 changes: 14 additions & 0 deletions packages/react-email/src/components/shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@ interface ShellProps extends RootProps {
markup?: string;
currentEmailOpenSlug?: string;
pathSeparator?: string;

activeView?: string;
setActiveView?: (view: string) => void;

viewWidth?: number;
setViewWidth?: (width: number) => void;
viewHeight?: number;
setViewHeight?: (height: number) => void;
}

export const Shell = ({
Expand All @@ -22,6 +28,10 @@ export const Shell = ({
markup,
activeView,
setActiveView,
viewHeight,
viewWidth,
setViewHeight,
setViewWidth,
}: ShellProps) => {
const [sidebarToggled, setSidebarToggled] = React.useState(false);
const [triggerTransition, setTriggerTransition] = React.useState(false);
Expand Down Expand Up @@ -105,6 +115,10 @@ export const Shell = ({
}}
pathSeparator={pathSeparator}
setActiveView={setActiveView}
setViewHeight={setViewHeight}
setViewWidth={setViewWidth}
viewHeight={viewHeight}
viewWidth={viewWidth}
/>
) : null}

Expand Down
Loading
Loading