javascript
// Email Templating Toolkit
// A component-driven library for rendering responsive HTML emails, MJML source, and AMP4Email variants.
// Usage: Define email as a tree of components, render to desired format.
// Extensible: Register custom components with registerRenderer(type, format, rendererFn).
const renderers = {
html: new Map(),
mjml: new Map(),
amp: new Map()
};
function registerRenderer(type, format, rendererFn) {
if (!renderers[format]) {
throw new Error(`Unknown format: ${format}`);
}
renderers[format].set(type, rendererFn);
}
function renderComponent(node, format) {
const formatRenderers = renderers[format];
const renderer = formatRenderers.get(node.type);
if (!renderer) {
throw new Error(`No renderer registered for type '${node.type}' in format '${format}'.`);
}
const childHTMLs = node.children ? node.children.map(child => renderComponent(child, format)).join('') : '';
return renderer(node.props, childHTMLs, format);
}
const HTML_STYLES = `
/*** RESET ***/
table { border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
td { padding: 0; }
img { border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; max-width: 100%; }
p { margin: 0; }
/*** RESPONSIVE ***/
@media only screen and (max-width: 600px) {
.mobile-column {
display: block !important;
width: 100% !important;
}
.button a {
display: block !important;
width: 100% !important;
text-align: center !important;
}
}
/*** OUTLOOK ***/
#outlook a { padding: 0; }
.ExternalClass { width: 100%; }
.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div { line-height: 100%; }
`;
function generateDocument(bodyContent, format, props = {}) {
const subject = props.subject || 'Newsletter';
const backgroundColor = props.backgroundColor || '#f4f4f4';
switch (format) {
case 'html':
return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="x-apple-disable-message-reformatting">
<title>${subject}</title>
<style type="text/css">
${HTML_STYLES}
</style>
</head>
<body style="margin:0; padding:20px; background-color:${backgroundColor}; font-family:Helvetica,Arial,sans-serif;">
${bodyContent}
</body>
</html>`;
case 'mjml':
return `<mjml>
<mj-head>
<mj-preview>${subject}</mj-preview>
<mj-attributes>
<mj-all font-family="Helvetica, Arial, sans-serif" color="#333333"></mj-all>
<mj-text font-size="16px" line-height="1.5"></mj-text>
</mj-attributes>
</mj-head>
<mj-body background-color="${backgroundColor}">
${bodyContent}
</mj-body>
</mjml>`;
case 'amp':
return `<?xml version="1.0" encoding="UTF-8"?>
<!doctype html>
<html amp4email>
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-img" src="https://cdn.ampproject.org/v0/amp-img-0.1.js"></script>
<style amp4email>
body { margin: 0; padding: 20px; background-color: ${backgroundColor}; font-family: sans-serif; }
table { border-collapse: collapse; }
td { padding: 0; vertical-align: top; }
img { border: 0; max-width: 100%; height: auto; display: block; }
a { color: inherit; text-decoration: none; }
@media (max-width: 600px) {
.mobile-column { display: block !important; width: 100% !important; }
}
</style>
</head>
<body>
${bodyContent}
</body>
</html>`;
default:
throw new Error(`Unsupported format: ${format}`);
}
}
function renderEmail(emailTree, format) {
if (emailTree.type !== 'body') {
throw new Error('Root node must be type "body"');
}
const bodyContent = renderComponent(emailTree, format);
return generateDocument(bodyContent, format, emailTree.props);
}
// Register core components
// body (root): passthrough
['html', 'mjml', 'amp'].forEach(format => {
registerRenderer('body', format, (props, childHTMLs) => childHTMLs);
});
// container: centered 600px wrapper
registerRenderer('container', 'html', (props, childHTMLs) => {
const bgcolor = props.bgcolor || '#ffffff';
return `<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: ${bgcolor}; max-width: 600px; margin: 0 auto;">${childHTMLs}</table>`;
});
registerRenderer('container', 'mjml', (props, childHTMLs) => childHTMLs); // passthrough
registerRenderer('container', 'amp', (props, childHTMLs) => {
const bgcolor = props.bgcolor || '#ffffff';
return `<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; background-color: ${bgcolor}; max-width: 600px; margin: 0 auto;">${childHTMLs}</table>`;
});
// section: row wrapper with padding
registerRenderer('section', 'html', (props, childHTMLs) => {
const padding = props.padding || '20px 0';
return `<tr>
<td style="padding: ${padding};">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>${childHTMLs}</tr>
</table>
</td>
</tr>`;
});
registerRenderer('section', 'mjml', (props, childHTMLs) => `<mj-section padding="${props.padding || '20px'}">${childHTMLs}</mj-section>`);
registerRenderer('section', 'amp', (props, childHTMLs) => {
const padding = props.padding || '20px 0';
return `<tr><td style="padding: ${padding};"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>${childHTMLs}</tr></table></td></tr>`;
});
// column: responsive column
registerRenderer('column', 'html', (props, childHTMLs) => {
const width = props.width || '100%';
return `<td class="mobile-column" valign="top" width="${width}" style="width: ${width}; vertical-align: top;">${childHTMLs}</td>`;
});
registerRenderer('column', 'mjml', (props, childHTMLs) => `<mj-column width="${props.width || '100%'}">${childHTMLs}</mj-column>`);
registerRenderer('column', 'amp', (props, childHTMLs) => {
const width = props.width || '100%';
return `<td class="mobile-column" valign="top" width="${width}" style="width: ${width}; vertical-align: top;">${childHTMLs}</td>`;
});
// text
registerRenderer('text', 'html', (props, childHTMLs) => {
const color = props.color || '#333333';
return `<div style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.5; color: ${color}; margin: 0 0 20px 0;">${props.content}</div>`;
});
registerRenderer('text', 'mjml', (props, childHTMLs) => `<mj-text color="${props.color || '#333333'}" padding-bottom="20px">${props.content}</mj-text>`);
registerRenderer('text', 'amp', (props, childHTMLs) => {
const color = props.color || '#333333';
return `<div style="font-size: 16px; line-height: 1.5; color: ${color}; margin: 0 0 20px 0;">${props.content}</div>`;
});
// button
registerRenderer('button', 'html', (props, childHTMLs) => {
const bgcolor = props.bgcolor || '#007bff';
const label = props.label || 'Button';
const href = props.href || '#';
return `<table role="presentation" cellspacing="0" cellpadding="0" border="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
<tr>
<td style="border-radius: 4px; background-color: ${bgcolor};" align="center">
<a href="${href}" style="font-size: 16px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; padding: 12px 24px; display: inline-block; border-radius: 4px;">${label}</a>
</td>
</tr>
</table>`;
});
registerRenderer('button', 'mjml', (props, childHTMLs) => {
const bgcolor = props.bgcolor || '#007bff';
return `<mj-button background-color="${bgcolor}" href="${props.href || '#'}" padding="12px 24px" border-radius="4px" font-size="16px">${props.label || 'Button'}</mj-button>`;
});
registerRenderer('button', 'amp', (props, childHTMLs) => {
const bgcolor = props.bgcolor || '#007bff';
const label = props.label || 'Button';
const href = props.href || '#';
return `<table role="presentation" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse;">
<tr>
<td style="border-radius: 4px; background-color: ${bgcolor};" align="center">
<a href="${href}" style="font-size: 16px; color: #ffffff; text-decoration: none; padding: 12px 24px; display: inline-block; border-radius: 4px;">${label}</a>
</td>
</tr>
</table>`;
});
// image (requires width & height for AMP)
registerRenderer('image', 'html', (props, childHTMLs) => {
const width = props.width || 600;
return `<img src="${props.src}" alt="${props.alt || ''}" width="${width}" style="max-width: 100%; height: auto; display: block; border: 0; outline: none; text-decoration: none;" />`;
});
registerRenderer('image', 'mjml', (props, childHTMLs) => `<mj-image src="${props.src}" alt="${props.alt || ''}" width="${props.width || 600}" padding="10px 0" />`);
registerRenderer('image', 'amp', (props, childHTMLs) => {
const width = props.width || 600;
const height = props.height || 200; // AMP requires height
return `<amp-img src="${props.src}" alt="${props.alt || ''}" width="${width}" height="${height}" layout="responsive"></amp-img>`;
});
// spacer
registerRenderer('spacer', 'html', (props, childHTMLs) => {
const size = props.size || 20;
return `<tr><td height="${size}" style="font-size: 0; line-height: 0; mso-line-height-rule: exactly; height: ${size}px;"> </td></tr>`;
});
registerRenderer('spacer', 'mjml', (props, childHTMLs) => `<mj-spacer height="${props.size || 20}" />`);
registerRenderer('spacer', 'amp', (props, childHTMLs) => {
const size = props.size || 20;
return `<tr><td height="${size}" style="font-size: 0; line-height: 0; height: ${size}px;"> </td></tr>`;
});
// Export for Node.js/ES modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = { renderEmail, registerRenderer, renderers };
} else {
window.EmailToolkit = { renderEmail, registerRenderer, renderers };
}
// Example Usage
const exampleEmail = {
type: 'body',
props: {
subject: 'Welcome to Our Newsletter!',
backgroundColor: '#f4f4f4'
},
children: [
{
type: 'container',
props: { bgcolor: '#ffffff' },
children: [
{
type: 'section',
props: {},
children: [
{
type: 'column',
props: { width: '100%' },
children: [
{
type: 'text',
props: { content: '<strong>Hello, World!</strong><br>This is a <em>responsive</em> email.' }
},
{ type: 'image', props: { src: 'https://via.placeholder.com/600x200/007bff/ffffff?text=Hero+Image', alt: 'Hero', width: 600, height: 200 } },
{ type: 'spacer', props: { size: 30 } },
{
type: 'button',
props: { href: 'https://example.com', label: 'Get Started', bgcolor: '#007bff' }
},
{ type: 'spacer', props: { size: 20 } },
{
type: 'text',
props: { content: 'Multi-column example below (stacks on mobile):' }
}
]
}
]
},
{
type: 'section',
props: {},
children: [
{
type: 'column',
props: { width: '50%' },
children: [
{ type: 'text', props: { content: 'Left Column' } }
]
},
{
type: 'column',
props: { width: '50%' },
children: [
{ type: 'text', props: { content: 'Right Column' } }
]
}
]
}
]
}
]
};
console.log('HTML:\n', renderEmail(exampleEmail, 'html'));
console.log('\nMJML:\n', renderEmail(exampleEmail, 'mjml'));
console.log('\nAMP:\n', renderEmail(exampleEmail, 'amp'));