Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/email-templates/src/render.ts
T

58 lines
2.0 KiB
TypeScript

/**
* Render-helper for sequence templates.
*
* Uses `react-dom/server.renderToStaticMarkup` (already a runtime dep of
* the web app) to emit a self-contained HTML document plus a flat text
* fallback for clients that prefer text/plain. We intentionally avoid the
* full `react-email` package here — that migration is task #75 and
* pulling it forward in V1 would force a 60+MB dep tree onto every worker
* image. See docs/improvement-plan/05-business-features/marketing-funnel-phase-3.md.
*/
import type { ReactElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
export interface RenderedEmail {
readonly html: string;
readonly text: string;
}
/**
* Convert HTML to a usable plain-text fallback. Strips tags and collapses
* whitespace while preserving anchor URLs as `[text] (url)` for clients
* that fall back to the text alternative.
*/
export function htmlToPlainText(html: string): string {
// Preserve anchor URLs in the text fallback before stripping tags.
const withAnchorUrls = html.replace(
/<a\s+[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/giu,
(_, href: string, label: string) => `${label.replace(/<[^>]+>/gu, "").trim()} (${href})`
);
return withAnchorUrls
.replace(/<style[\s\S]*?<\/style>/giu, "")
.replace(/<script[\s\S]*?<\/script>/giu, "")
.replace(/<br\s*\/?>(\r?\n)?/giu, "\n")
.replace(/<\/(p|h1|h2|h3|li|div|tr)>/giu, "\n")
.replace(/<[^>]+>/gu, "")
.replace(/&nbsp;/giu, " ")
.replace(/&amp;/giu, "&")
.replace(/&lt;/giu, "<")
.replace(/&gt;/giu, ">")
.replace(/&#39;/giu, "'")
.replace(/&quot;/giu, '"')
.replace(/[ \t]+\n/gu, "\n")
.replace(/\n{3,}/gu, "\n\n")
.trim();
}
/**
* Render a React element to `{ html, text }`. The HTML is prefixed with
* a DOCTYPE so mail-clients render in standards mode.
*/
export function renderEmail(element: ReactElement): RenderedEmail {
const body = renderToStaticMarkup(element);
const html = `<!DOCTYPE html>${body}`;
const text = htmlToPlainText(body);
return { html, text };
}