import { Section, GlobalStyles, DEFAULT_GLOBAL_STYLES, getColumnWidths } from '../types'
import { renderBlockToHtml } from './block-renderers'
export interface RenderOptions {
subject?: string
preheaderText?: string
}
/**
* Converts sections to a full email-safe HTML document.
* Uses table-based layout with inline CSS for maximum email client compatibility.
*/
export function renderToEmailHtml(
sections: Section[],
globalStyles: GlobalStyles = DEFAULT_GLOBAL_STYLES,
options: RenderOptions = {}
): string {
const { subject = '', preheaderText = '' } = options
const contentWidth = globalStyles.contentWidth || 600
const bgColor = globalStyles.backgroundColor || '#f3f4f6'
const fontFamily = globalStyles.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
const sectionsHtml = sections.map((section) => renderSection(section, globalStyles, contentWidth)).join('')
const preheader = preheaderText
? `
${preheaderText}
`
: ''
return `
${subject}
${preheader}
`
}
function renderSection(section: Section, globalStyles: GlobalStyles, contentWidth: number): string {
const bgColor = section.backgroundColor || '#ffffff'
const pt = section.paddingTop ?? 16
const pb = section.paddingBottom ?? 16
const pl = section.paddingLeft ?? 0
const pr = section.paddingRight ?? 0
const rowsHtml = section.rows.map((row) => {
const widths = getColumnWidths(row.layout)
const colCount = widths.length
if (colCount === 1) {
// Single column: simple
const blocksHtml = row.columns[0]
?.map((block) => renderBlockToHtml(block, globalStyles))
.join('') || ''
return `| ${blocksHtml} |
`
}
// Multi-column: use nested table
const columnsHtml = widths
.map((widthPct, i) => {
const colBlocks = row.columns[i] || []
const blocksHtml = colBlocks
.map((block) => renderBlockToHtml(block, globalStyles))
.join('')
const pxWidth = Math.round((contentWidth - pl - pr) * (widthPct / 100))
return `${blocksHtml} | `
})
.join('')
return `|
|
`
}).join('')
return `|
|
| |
`
}
/**
* Render sections to a simple HTML string (for preview iframe, not for sending).
*/
export function renderToPreviewHtml(
sections: Section[],
globalStyles: GlobalStyles = DEFAULT_GLOBAL_STYLES
): string {
return renderToEmailHtml(sections, globalStyles)
}