Skip to content

The open alternative to Salesforce, designed for AI.

2.0 KB
Raw Blame
import { type ReactNode } from 'react';
import { Body, Container, Head, Html } from 'react-email';
import { type JSONContent } from '@tiptap/core';
import {
  CANVAS_THEME_DEFAULTS,
  type CanvasTheme,
  EMAIL_TYPOGRAPHY,
  resolveCanvasTheme,
} from 'twenty-shared/utils';
import { mappedNodeContent } from 'src/utils/email-renderer/renderers/render-node';

const BASE_STYLE_RESET = `blockquote,h1,h2,h3,img,li,ol,p,ul{margin-top:0;margin-bottom:0}`;

const BASE_TYPOGRAPHY = {
  fontFamily: EMAIL_TYPOGRAPHY.fontFamily,
  fontSize: EMAIL_TYPOGRAPHY.fontSize,
  lineHeight: EMAIL_TYPOGRAPHY.lineHeight,
};

const themedBody = (theme: CanvasTheme, children: ReactNode) => (
  <Body
    style={{
      ...BASE_TYPOGRAPHY,
      backgroundColor: theme.pageBackground,
      color: theme.textColor,
      margin: 0,
      padding: theme.pagePadding,
    }}
  >
    <Container
      style={{
        backgroundColor: theme.bodyBackground || undefined,
        border:
          theme.borderWidth !== '' && theme.borderWidth !== '0px'
            ? `${theme.borderWidth} solid ${theme.borderColor}`
            : undefined,
        borderRadius: theme.cornerRadius,
        color: theme.textColor,
        maxWidth: theme.width,
        padding: theme.padding,
        textAlign: theme.textAlign,
      }}
    >
      {children}
    </Container>
  </Body>
);

export const reactMarkupFromJSON = (json: JSONContent | string) => {
  if (typeof json === 'string') {
    return json;
  }

  const canvasTheme = resolveCanvasTheme(json.attrs?.canvasTheme);
  const textColor = canvasTheme?.textColor ?? CANVAS_THEME_DEFAULTS.textColor;
  const jsxNodes = mappedNodeContent(json, { color: textColor });

  return (
    <Html>
      <Head>
        <style
          dangerouslySetInnerHTML={{
            __html: BASE_STYLE_RESET,
          }}
        />
      </Head>
      {canvasTheme !== null ? (
        themedBody(canvasTheme, jsxNodes)
      ) : (
        <Body style={{ ...BASE_TYPOGRAPHY, color: textColor }}>{jsxNodes}</Body>
      )}
    </Html>
  );
};