feat: release design system engine, studio and component contracts

This commit is contained in:
Clintchiz committed 2026-10-19 13:09:03 +05:30
1 parent ff1065fb27
commit 3943b946d6
693 files changed
+175546 -3894

No files matched your search

+221 -51
View File
@@ -41,15 +41,20 @@ const mjmlDocumentHead = (node: BlockNode, context: unknown) => {
return `<mj-head><mj-title>${html(meta?.emailSubject)}</mj-title>${meta?.emailPreheader ? `<mj-preview>${html(meta.emailPreheader)}</mj-preview>` : ""}<mj-attributes><mj-all font-family="${html(attrs(node).fontFamily ?? "Arial, sans-serif")}" /><mj-text color="${html(attrs(node).textColor ?? "#111827")}" /><mj-button background-color="${html(attrs(node).linkColor ?? "#2563eb")}" /></mj-attributes></mj-head>`;
};
export const ampLayoutClass = (node: BlockNode) =>
"wrn-layout-" + Array.from(node.id, char => char.codePointAt(0)!.toString(16)).join("-");
"wrn-layout-" + Array.from(node.id, (char) => char.codePointAt(0)!.toString(16)).join("-");
export function ampLayoutCss(node: BlockNode, brandLinkColor?: string): string {
const props = attrs(node);
if (node.type === "content.button")
return `.button.${ampLayoutClass(node)}{background-color:${buttonBackground(node, { brandLinkColor })};${buttonVisualCss(node)}}`;
if (node.type === "layout.section") {
const background = safeCssValue(props.background, /^(#[0-9a-f]{3,8}|rgba?\([0-9., %]+\))$/i) || "#ffffff";
const padding = safeCssValue(props.padding, /^\d+(?:\.\d+)?(?:px|rem|em|%)?(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)?){0,3}$/) || "24px";
const background =
safeCssValue(props.background, /^(#[0-9a-f]{3,8}|rgba?\([0-9., %]+\))$/i) || "#ffffff";
const padding =
safeCssValue(
props.padding,
/^\d+(?:\.\d+)?(?:px|rem|em|%)?(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)?){0,3}$/,
) || "24px";
return `.${ampLayoutClass(node)}{background:${background};padding:${padding}}`;
}
if (node.type === "content.spacer") {
@@ -58,22 +63,37 @@ export function ampLayoutCss(node: BlockNode, brandLinkColor?: string): string {
}
return "";
}
const multilineText = (value: unknown) => html(value).replace(/\r\n?|\n/g, "<br />");
const imageDimension = (fallback: string, minimum = 1): ValueSchema<string> => ({
kind: "string",
defaultValue: fallback,
parse(value = fallback, path = "value") {
return typeof value === "string" && /^\d{1,4}$/.test(value) && Number(value) >= minimum && Number(value) <= 4000
return typeof value === "string" &&
/^\d{1,4}$/.test(value) &&
Number(value) >= minimum &&
Number(value) <= 4000
? { ok: true, value }
: { ok: false, errors: [{code:"email.image-dimension",message:`Dimensions must be between ${minimum} and 4000 pixels.`,severity:"error",path}] };
: {
ok: false,
errors: [
{
code: "email.image-dimension",
message: `Dimensions must be between ${minimum} and 4000 pixels.`,
severity: "error",
path,
},
],
};
},
});
const marketingImage = (node: BlockNode, target: "html" | "amp" | "mjml") => {
const p = attrs(node);
if (!p.image) return "";
const width = html(p.width ?? "600"), height = html(p.height ?? "400");
const src = html(p.image), alt = html(p.title);
if (target === "amp") return `<amp-img class="marketing-image" src="${src}" alt="${alt}" width="${width}" height="${height}" layout="responsive"></amp-img>`;
const width = html(p.width ?? "600"),
height = html(p.height ?? "400");
const src = html(p.image),
alt = html(p.title);
if (target === "amp")
return `<amp-img class="marketing-image" src="${src}" alt="${alt}" width="${width}" height="${height}" layout="responsive"></amp-img>`;
if (target === "mjml") return `<mj-image src="${src}" alt="${alt}" width="${width}px" />`;
return `<img src="${src}" alt="${alt}" width="${width}" style="display:block;height:auto;width:100%;max-width:${width}px;" />`;
};
@@ -126,11 +146,27 @@ const buttonVisualCss = (node: BlockNode) => {
const buttonAlignment = (node: BlockNode, context: unknown) => {
const value = emailStyleValue("textAlign", styleBase(node, "textAlign")) || "start";
const rtl = (context as { direction?: string } | undefined)?.direction === "rtl";
return value === "start" ? (rtl ? "right" : "left") : value === "end" ? (rtl ? "left" : "right") : value;
return value === "start"
? rtl
? "right"
: "left"
: value === "end"
? rtl
? "left"
: "right"
: value;
};
const emailCell = (body: string, node: BlockNode, align?: string) => {
// Button visuals belong to the clickable element, never the full-width cell.
const cellNode = node.type === "content.button" ? { ...node, styles: Object.fromEntries(Object.entries(node.styles).filter(([key]) => ["textAlign", "margin"].includes(key))) } : node;
const cellNode =
node.type === "content.button"
? {
...node,
styles: Object.fromEntries(
Object.entries(node.styles).filter(([key]) => ["textAlign", "margin"].includes(key)),
),
}
: node;
return `<tr><td data-block-id="${html(node.id)}"${align ? ` align="${html(align)}"` : ""} style="padding:0;${semanticStyle(cellNode)}">${body}</td></tr>`;
};
@@ -161,7 +197,18 @@ export const emailDocumentBlock = defineBlock({
id: id(),
type: "layout.email-document",
version: 1,
props: { width: "600", background: "#f3f4f6", contentBackground: "#ffffff", fontFamily: "Arial, sans-serif", textColor: "#111827", linkColor: "#2563eb", logoUrl: "", logoAlt: "", logoWidth: "200", logoHeight: "64" },
props: {
width: "600",
background: "#f3f4f6",
contentBackground: "#ffffff",
fontFamily: "Arial, sans-serif",
textColor: "#111827",
linkColor: "#2563eb",
logoUrl: "",
logoAlt: "",
logoWidth: "200",
logoHeight: "64",
},
styles: {},
slots: { content: [] },
}),
@@ -212,9 +259,10 @@ export const sectionBlock = defineBlock({
),
mjml: ({ node, slots }) => {
const children = node.slots.content ?? [];
const body = children.length === 1 && children[0]?.type === "layout.columns"
? slots.content
: `<mj-column>${slots.content}</mj-column>`;
const body =
children.length === 1 && children[0]?.type === "layout.columns"
? slots.content
: `<mj-column>${slots.content}</mj-column>`;
return `<mj-section background-color="${html(attrs(node).background ?? "#ffffff")}" padding="${html(attrs(node).padding ?? "24px")}">${body}</mj-section>`;
},
},
@@ -256,10 +304,14 @@ export const columnsBlock = defineBlock({
node,
),
ampEmail: ({ node, slots }) =>
emailCell(`<table role="presentation" width="100%"><tr class="wrn-columns">${slots.columns}</tr></table>`, node),
mjml: ({ node, slots, context }) => isEmailRootChild(node, context)
? `<mj-section padding="0">${slots.columns}</mj-section>`
: slots.columns,
emailCell(
`<table role="presentation" width="100%"><tr class="wrn-columns">${slots.columns}</tr></table>`,
node,
),
mjml: ({ node, slots, context }) =>
isEmailRootChild(node, context)
? `<mj-section padding="0">${slots.columns}</mj-section>`
: slots.columns,
},
textRenderer: ({ slots }) => slots.columns,
} satisfies BlockDefinition);
@@ -318,12 +370,16 @@ const leaf = (
create: ({ id }) => ({ id: id(), type, version: 1, props: {}, styles: {}, slots: {} }),
renderers: {
...renderers,
...(renderers?.mjml ? { mjml: async (input) => {
const content = await renderers.mjml!(input);
return isEmailRootChild(input.node, input.context)
? `<mj-section padding="0"><mj-column padding="0">${content}</mj-column></mj-section>`
: content;
} } : {}),
...(renderers?.mjml
? {
mjml: async (input) => {
const content = await renderers.mjml!(input);
return isEmailRootChild(input.node, input.context)
? `<mj-section padding="0"><mj-column padding="0">${content}</mj-column></mj-section>`
: content;
},
}
: {}),
},
textRenderer,
});
@@ -344,7 +400,10 @@ export const headingBlock = leaf(
node,
),
ampEmail: ({ node }) =>
emailCell(`<h${attrs(node).level}>${renderRichText(attrs(node))}</h${attrs(node).level}>`, node),
emailCell(
`<h${attrs(node).level}>${renderRichText(attrs(node))}</h${attrs(node).level}>`,
node,
),
mjml: ({ node }) =>
`<mj-text font-size="24px" font-weight="700">${renderRichText(attrs(node))}</mj-text>`,
},
@@ -465,9 +524,18 @@ export const videoBlock = leaf(
height: imageDimension("338"),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" style="border:0;display:block;height:auto;width:100%;max-width:${html(attrs(node).width)}px;" /></a>`, node),
ampEmail: ({ node }) => emailCell(`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><amp-img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" layout="responsive"></amp-img></a>`, node),
mjml: ({ node }) => `<mj-image href="${html(attrs(node).href)}" src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}px" height="${html(attrs(node).height)}px" />`,
emailHtml: ({ node }) =>
emailCell(
`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" style="border:0;display:block;height:auto;width:100%;max-width:${html(attrs(node).width)}px;" /></a>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><amp-img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" layout="responsive"></amp-img></a>`,
node,
),
mjml: ({ node }) =>
`<mj-image href="${html(attrs(node).href)}" src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}px" height="${html(attrs(node).height)}px" />`,
},
({ node }) => `${String(attrs(node).title)}: ${String(attrs(node).href)}\n\n`,
);
@@ -484,11 +552,53 @@ export const socialBlock = leaf(
x: safeUrl({ schemes: ["https"], optional: true }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<p style="font-family:inherit;margin:0 0 16px;">${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}" style="margin-right:12px;">${name}</a>`).join("")}</p>`, node),
ampEmail: ({ node }) => emailCell(`<p>${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}">${name}</a>`).join(" ")}</p>`, node),
mjml: ({ node }) => `<mj-text>${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}">${name}</a>`).join(" ")}</mj-text>`,
emailHtml: ({ node }) =>
emailCell(
`<p style="font-family:inherit;margin:0 0 16px;">${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}" style="margin-right:12px;">${name}</a>`)
.join("")}</p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<p>${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}">${name}</a>`)
.join(" ")}</p>`,
node,
),
mjml: ({ node }) =>
`<mj-text>${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}">${name}</a>`)
.join(" ")}</mj-text>`,
},
({ node }) => `${String(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`${name}: ${url}`).join(" · ")}\n\n`,
({ node }) =>
`${String(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `${name}: ${url}`)
.join(" · ")}\n\n`,
);
const countdownUrl = (node: BlockNode, context: unknown): string | undefined => {
@@ -513,57 +623,117 @@ export const countdownBlock = leaf(
{
emailHtml: ({ node, context }) => {
const url = countdownUrl(node, context);
return emailCell(`<p style="font-family:inherit;font-size:20px;font-weight:700;margin:0 0 16px;">${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<img src="${url}" width="320" height="64" alt="${html(attrs(node).label)} — ${html(attrs(node).deadline)}" style="display:block;width:320px;max-width:100%;height:auto;" />` : ""}`, node);
return emailCell(
`<p style="font-family:inherit;font-size:20px;font-weight:700;margin:0 0 16px;">${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<img src="${url}" width="320" height="64" alt="${html(attrs(node).label)} — ${html(attrs(node).deadline)}" style="display:block;width:320px;max-width:100%;height:auto;" />` : ""}`,
node,
);
},
ampEmail: ({ node, context }) => {
const url = countdownUrl(node, context);
return emailCell(`<p>${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<amp-img src="${url}" width="320" height="64" layout="responsive" alt="${html(attrs(node).label)}"></amp-img>` : ""}`, node);
return emailCell(
`<p>${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<amp-img src="${url}" width="320" height="64" layout="responsive" alt="${html(attrs(node).label)}"></amp-img>` : ""}`,
node,
);
},
mjml: ({ node, context }) => {
const url = countdownUrl(node, context);
return `<mj-text font-size="20px" font-weight="700">${html(attrs(node).label)}: ${html(attrs(node).deadline)}</mj-text>${url ? `<mj-image src="${url}" width="320px" alt="${html(attrs(node).label)}" />` : ""}`;
},
},
({ node }) => `${String(attrs(node).label)}: ${String(attrs(node).deadline)}\n${String(attrs(node).fallback)}\n\n`,
({ node }) =>
`${String(attrs(node).label)}: ${String(attrs(node).deadline)}\n${String(attrs(node).fallback)}\n\n`,
);
export const surveyBlock = leaf(
"content.survey",
"Survey",
"icon-[lucide--list-checks]",
object({ question: string({ min: 1, max: 500 }), buttonLabel: string({ min: 1, max: 200, default: "Answer survey" }), href: safeUrl({ schemes: ["https"] }) }) as never,
object({
question: string({ min: 1, max: 500 }),
buttonLabel: string({ min: 1, max: 200, default: "Answer survey" }),
href: safeUrl({ schemes: ["https"] }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<p style="font-family:inherit;margin:0 0 12px;">${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
ampEmail: ({ node }) => emailCell(`<p>${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
mjml: ({ node }) => `<mj-text>${html(attrs(node).question)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
emailHtml: ({ node }) =>
emailCell(
`<p style="font-family:inherit;margin:0 0 12px;">${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<p>${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
mjml: ({ node }) =>
`<mj-text>${html(attrs(node).question)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
},
({ node }) => `${String(attrs(node).question)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).question)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
);
export const feedItemBlock = leaf(
"content.feed-item",
"RSS article",
"icon-[lucide--rss]",
object({ width: imageDimension("600"), height: imageDimension("400"), feedUrl: safeUrl({ schemes: ["https"], optional: true }), title: string({ min: 1, max: 500 }), summary: string({ max: 2_000, default: "" }), href: safeUrl({ schemes: ["https"] }), image: safeUrl({ schemes: ["https"], optional: true }) }) as never,
object({
width: imageDimension("600"),
height: imageDimension("400"),
feedUrl: safeUrl({ schemes: ["https"], optional: true }),
title: string({ min: 1, max: 500 }),
summary: string({ max: 2_000, default: "" }),
href: safeUrl({ schemes: ["https"] }),
image: safeUrl({ schemes: ["https"], optional: true }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`${marketingImage(node, "html")}<h2 style="font-family:inherit;"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p style="font-family:inherit;">${html(attrs(node).summary)}</p>`, node),
ampEmail: ({ node }) => emailCell(`${marketingImage(node, "amp")}<h2><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p>${html(attrs(node).summary)}</p>`, node),
mjml: ({ node }) => `${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></mj-text><mj-text>${html(attrs(node).summary)}</mj-text>`,
emailHtml: ({ node }) =>
emailCell(
`${marketingImage(node, "html")}<h2 style="font-family:inherit;"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p style="font-family:inherit;">${html(attrs(node).summary)}</p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`${marketingImage(node, "amp")}<h2><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p>${html(attrs(node).summary)}</p>`,
node,
),
mjml: ({ node }) =>
`${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></mj-text><mj-text>${html(attrs(node).summary)}</mj-text>`,
},
({ node }) => `${String(attrs(node).title)}\n${String(attrs(node).summary)}\n${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).title)}\n${String(attrs(node).summary)}\n${String(attrs(node).href)}\n\n`,
);
export const productBlock = leaf(
"commerce.product",
"Product",
"icon-[lucide--shopping-bag]",
object({ width: imageDimension("600"), height: imageDimension("400"), provider: choice(["shopify", "woocommerce", "manual"] as const, { default: "manual" }), storeUrl: safeUrl({ schemes: ["https"], optional: true }), productId: string({ max: 300, default: "" }), title: string({ min: 1, max: 500 }), price: string({ max: 100 }), image: safeUrl({ schemes: ["https"] }), href: safeUrl({ schemes: ["https"] }), buttonLabel: string({ max: 200, default: "Shop now" }) }) as never,
object({
width: imageDimension("600"),
height: imageDimension("400"),
provider: choice(["shopify", "woocommerce", "manual"] as const, { default: "manual" }),
storeUrl: safeUrl({ schemes: ["https"], optional: true }),
productId: string({ max: 300, default: "" }),
title: string({ min: 1, max: 500 }),
price: string({ max: 100 }),
image: safeUrl({ schemes: ["https"] }),
href: safeUrl({ schemes: ["https"] }),
buttonLabel: string({ max: 200, default: "Shop now" }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`${marketingImage(node, "html")}<h2 style="font-family:inherit;">${html(attrs(node).title)}</h2><p style="font-family:inherit;font-weight:700;">${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
ampEmail: ({ node }) => emailCell(`${marketingImage(node, "amp")}<h2>${html(attrs(node).title)}</h2><p>${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
mjml: ({ node }) => `${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700">${html(attrs(node).title)}</mj-text><mj-text>${html(attrs(node).price)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
emailHtml: ({ node }) =>
emailCell(
`${marketingImage(node, "html")}<h2 style="font-family:inherit;">${html(attrs(node).title)}</h2><p style="font-family:inherit;font-weight:700;">${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`${marketingImage(node, "amp")}<h2>${html(attrs(node).title)}</h2><p>${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
mjml: ({ node }) =>
`${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700">${html(attrs(node).title)}</mj-text><mj-text>${html(attrs(node).price)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
},
({ node }) => `${String(attrs(node).title)} — ${String(attrs(node).price)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).title)} — ${String(attrs(node).price)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
);
export const emailCoreBlocks: readonly BlockDefinition[] = [
+30 -13
View File
@@ -1,7 +1,14 @@
/** Browser-safe HTML/text rendering. Production AMP/MJML validation stays on the server. */
import {
DEFAULT_LIMITS, defineDocumentKind, escapeHtml, object, registryForKind,
resolveDocumentVariables, renderTree, string, type BlockDocument,
DEFAULT_LIMITS,
defineDocumentKind,
escapeHtml,
object,
registryForKind,
resolveDocumentVariables,
renderTree,
string,
type BlockDocument,
} from "@wrnexus/blocks";
import { emailCoreBlocks } from "./blocks.ts";
export const emailKind = defineDocumentKind({
@@ -30,18 +37,25 @@ export const emailHtmlHead = (document: BlockDocument, body: string, direction:
return `<!doctype html><html lang="${escapeHtml(document.meta.lang)}" dir="${direction}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="x-apple-disable-message-reformatting"><meta name="color-scheme" content="light dark"><title>${escapeHtml(document.meta.subject)}</title><style>a{color:${linkColor}}@media only screen and (max-width:480px){.wrn-email{width:100%!important}.wrn-columns{display:block!important}.wrn-column{display:block!important;width:100%!important}}</style></head><body style="margin:0;padding:0;color:${textColor};font-family:${fontFamily};">${document.meta.preheader ? `<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${escapeHtml(document.meta.preheader)}</div>` : ""}${body}</body></html>`;
};
export async function renderEmailPreview(document: BlockDocument, options: {
variables?: Record<string, unknown>;
direction?: "ltr" | "rtl";
countdownImageUrl?: string;
} = {}) {
export async function renderEmailPreview(
document: BlockDocument,
options: {
variables?: Record<string, unknown>;
direction?: "ltr" | "rtl";
countdownImageUrl?: string;
} = {},
) {
const resolved = resolveDocumentVariables(document, emailKind.variables, options.variables);
if (!resolved.ok) return resolved;
const source = resolved.value;
const context = {
locale: "en", timezone: "UTC", direction: options.direction ?? "ltr",
locale: "en",
timezone: "UTC",
direction: options.direction ?? "ltr",
brandLinkColor: String(source.root.props.linkColor ?? "#2563eb"),
rootBlockIds: Object.values(source.root.slots).flat().map(node => node.id),
rootBlockIds: Object.values(source.root.slots)
.flat()
.map((node) => node.id),
countdownImageUrl: options.countdownImageUrl,
} as const;
const registry = registryForKind(emailKind).freeze();
@@ -51,8 +65,11 @@ export async function renderEmailPreview(document: BlockDocument, options: {
]);
if (!html.ok) return html;
if (!text.ok) return text;
return { ok: true as const, value: {
html: emailHtmlHead(source, html.value.content, context.direction),
text: text.value.content.trimEnd() + "\n",
} };
return {
ok: true as const,
value: {
html: emailHtmlHead(source, html.value.content, context.direction),
text: text.value.content.trimEnd() + "\n",
},
};
}
+50 -17
View File
@@ -2,24 +2,43 @@ import { createRequire } from "node:module";
const { GIFEncoder } = createRequire(import.meta.url)("gifenc") as {
GIFEncoder(): {
writeFrame(pixels: Uint8Array, width: number, height: number, options: {
palette: number[][]; delay: number; repeat: number;
}): void;
writeFrame(
pixels: Uint8Array,
width: number,
height: number,
options: {
palette: number[][];
delay: number;
repeat: number;
},
): void;
finish(): void;
bytes(): Uint8Array;
};
};
const glyphs: Record<string, string> = {
"0": "111101101101111", "1": "010110010010111", "2": "111001111100111",
"3": "111001111001111", "4": "101101111001001", "5": "111100111001111",
"6": "111100111101111", "7": "111001001001001", "8": "111101111101111",
"9": "111101111001111", ":": "000010000010000", " ": "000000000000000",
D: "110101101101110", H: "101101111101101", M: "101111111101101", S: "111100111001111",
"0": "111101101101111",
"1": "010110010010111",
"2": "111001111100111",
"3": "111001111001111",
"4": "101101111001001",
"5": "111100111001111",
"6": "111100111101111",
"7": "111001001001001",
"8": "111101111101111",
"9": "111101111001111",
":": "000010000010000",
" ": "000000000000000",
D: "110101101101110",
H: "101101111101101",
M: "101111111101101",
S: "111100111001111",
};
export function countdownLabel(deadline: number, now: number): string {
if (!Number.isFinite(deadline) || !Number.isFinite(now)) throw new Error("Invalid countdown time.");
if (!Number.isFinite(deadline) || !Number.isFinite(now))
throw new Error("Invalid countdown time.");
const seconds = Math.max(0, Math.ceil((deadline - now) / 1000));
const days = Math.floor(seconds / 86400);
if (days > 999) throw new Error("Countdown cannot exceed 999 days.");
@@ -29,9 +48,12 @@ export function countdownLabel(deadline: number, now: number): string {
/** A bounded, non-looping animation. The caller injects its clock for deterministic rendering. */
export function renderCountdownGif(deadline: number, now: number, frames = 60): Uint8Array {
if (!Number.isInteger(frames) || frames < 1 || frames > 60) throw new Error("Countdown requires 1–60 frames.");
if (!Number.isInteger(frames) || frames < 1 || frames > 60)
throw new Error("Countdown requires 1–60 frames.");
countdownLabel(deadline, now);
const width = 320, height = 64, scale = 4;
const width = 320,
height = 64,
scale = 4;
const encoder = GIFEncoder();
const count = Math.min(frames, Math.max(1, Math.ceil((deadline - now) / 1000) + 1));
for (let frame = 0; frame < count; frame++) {
@@ -40,14 +62,25 @@ export function renderCountdownGif(deadline: number, now: number, frames = 60):
const left = Math.floor((width - label.length * 4 * scale) / 2);
for (let character = 0; character < label.length; character++) {
const glyph = glyphs[label[character]!]!;
for (let row = 0; row < 5; row++) for (let col = 0; col < 3; col++) {
if (glyph[row * 3 + col] !== "1") continue;
for (let y = 0; y < scale; y++) for (let x = 0; x < scale; x++) {
pixels[(22 + row * scale + y) * width + left + character * 4 * scale + col * scale + x] = 1;
for (let row = 0; row < 5; row++)
for (let col = 0; col < 3; col++) {
if (glyph[row * 3 + col] !== "1") continue;
for (let y = 0; y < scale; y++)
for (let x = 0; x < scale; x++) {
pixels[
(22 + row * scale + y) * width + left + character * 4 * scale + col * scale + x
] = 1;
}
}
}
}
encoder.writeFrame(pixels, width, height, { palette: [[17, 24, 39], [255, 255, 255]], delay: 1000, repeat: -1 });
encoder.writeFrame(pixels, width, height, {
palette: [
[17, 24, 39],
[255, 255, 255],
],
delay: 1000,
repeat: -1,
});
}
encoder.finish();
return encoder.bytes();
+67 -6
View File
@@ -2,21 +2,82 @@ import type { BlockNode } from "@wrnexus/blocks";
import { emailCoreBlocks } from "./blocks.ts";
/** Complete trusted editor pack, including schema-valid content factories. */
export const emailEditorBlocks = emailCoreBlocks.map(definition =>
export const emailEditorBlocks = emailCoreBlocks.map((definition) =>
definition.manifest.category === "content" || definition.manifest.type.startsWith("commerce.")
? { ...definition, create: (context: { id(): string }) => createEmailBlock(definition.manifest.type, context) }
? {
...definition,
create: (context: { id(): string }) => createEmailBlock(definition.manifest.type, context),
}
: definition,
);
/** Canonical initial content for palette blocks; time and instance IDs are injectable. */
export function createEmailBlock(type: string, context: { id(): string; now?: number }): BlockNode {
const now = context.now ?? Date.now();
const defaults: Record<string, Record<string, unknown>> = {"content.heading":{text:'New heading',level:'2'},"content.text":{text:'New paragraph'},"content.button":{label:'Call to action',href:'https://example.com'},"content.image":{src:'https://placehold.co/600x300',alt:'',width:'600',height:'300',decorative:false},"content.divider":{},"content.spacer":{height:'24'},"content.video":{title:'Watch video',href:'https://example.com',thumbnail:'https://placehold.co/600x338',alt:'Video thumbnail',width:'600',height:'338'},"content.social":{label:'Follow us',facebook:'',instagram:'',linkedin:'',x:''},"content.countdown":{label:'Offer ends',deadline:new Date(now+86400000).toISOString(),fallback:'This offer has ended.'},"content.survey":{question:'What do you think?',buttonLabel:'Answer survey',href:'https://example.com'},"content.feed-item":{width:'600',height:'400',feedUrl:'',title:'Latest article',summary:'Article summary',href:'https://example.com',image:''},"commerce.product":{width:'600',height:'400',provider:'manual',storeUrl:'',productId:'',title:'Featured product',price:'$0.00',image:'https://placehold.co/600x400',href:'https://example.com',buttonLabel:'Shop now'}};
const definition = emailCoreBlocks.find(block => block.manifest.type === type);
const defaults: Record<string, Record<string, unknown>> = {
"content.heading": { text: "New heading", level: "2" },
"content.text": { text: "New paragraph" },
"content.button": { label: "Call to action", href: "https://example.com" },
"content.image": {
src: "https://placehold.co/600x300",
alt: "",
width: "600",
height: "300",
decorative: false,
},
"content.divider": {},
"content.spacer": { height: "24" },
"content.video": {
title: "Watch video",
href: "https://example.com",
thumbnail: "https://placehold.co/600x338",
alt: "Video thumbnail",
width: "600",
height: "338",
},
"content.social": { label: "Follow us", facebook: "", instagram: "", linkedin: "", x: "" },
"content.countdown": {
label: "Offer ends",
deadline: new Date(now + 86400000).toISOString(),
fallback: "This offer has ended.",
},
"content.survey": {
question: "What do you think?",
buttonLabel: "Answer survey",
href: "https://example.com",
},
"content.feed-item": {
width: "600",
height: "400",
feedUrl: "",
title: "Latest article",
summary: "Article summary",
href: "https://example.com",
image: "",
},
"commerce.product": {
width: "600",
height: "400",
provider: "manual",
storeUrl: "",
productId: "",
title: "Featured product",
price: "$0.00",
image: "https://placehold.co/600x400",
href: "https://example.com",
buttonLabel: "Shop now",
},
};
const definition = emailCoreBlocks.find((block) => block.manifest.type === type);
if (!definition || !Object.prototype.hasOwnProperty.call(defaults, type))
throw new Error("This block is not available for palette insertion.");
const props = definition.manifest.props.parse(defaults[type], "props");
if (!props.ok) throw new Error(props.errors.map(error => error.message).join("\n"));
if (!props.ok) throw new Error(props.errors.map((error) => error.message).join("\n"));
const node = definition.create(context);
return { ...node, type: definition.manifest.type, version: definition.manifest.version, props: props.value };
return {
...node,
type: definition.manifest.type,
version: definition.manifest.version,
props: props.value,
};
}
+78 -19
View File
@@ -1,18 +1,14 @@
import { createRequire } from "node:module";
import {
DEFAULT_LIMITS,
defineDocumentKind,
escapeHtml,
object,
registryForKind,
resolveDocumentVariables,
renderTree,
string,
type BlockDocument,
type Diagnostic,
type Result,
} from "@wrnexus/blocks";
import { emailCoreBlocks, ampLayoutCss } from "./blocks.ts";
import { ampLayoutCss } from "./blocks.ts";
import { validateMjml } from "./mjml.ts";
interface AmpValidationError {
@@ -58,7 +54,9 @@ export interface EmailRenderBundle {
export { emailKind } from "./browser.ts";
import { emailKind, emailHtmlHead as head } from "./browser.ts";
const ampHead = (document: BlockDocument, body: string, direction: "ltr" | "rtl") => {
const layoutCss = (node: BlockDocument["root"]): string => ampLayoutCss(node, String(document.root.props.linkColor ?? "#2563eb")) + Object.values(node.slots).flat().map(layoutCss).join("");
const layoutCss = (node: BlockDocument["root"]): string =>
ampLayoutCss(node, String(document.root.props.linkColor ?? "#2563eb")) +
Object.values(node.slots).flat().map(layoutCss).join("");
const props = document.root.props as Record<string, unknown>;
const css = `@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}.marketing-image img{object-fit:contain}body{margin:0;color:${props.textColor ?? "#111827"};font-family:${props.fontFamily ?? "Arial, sans-serif"}}a{color:${props.linkColor ?? "#2563eb"}}.brand-logo{max-width:${props.logoWidth ?? "200"}px;width:100%;margin:20px auto}.email-bg{table-layout:fixed;width:100%;background:${props.background ?? "#f3f4f6"}}.email-body{max-width:${props.width ?? "600"}px;width:100%;background:${props.contentBackground ?? "#ffffff"}}`;
return `<!doctype html><html amp4email data-css-strict lang="${escapeHtml(document.meta.lang)}" dir="${direction}"><head><meta charset="utf-8"><script async src="https://cdn.ampproject.org/v0.js"></script><style amp4email-boilerplate>body{visibility:hidden}</style><style amp-custom>${css}${layoutCss(document.root)}.button{background:#2563eb;border-radius:6px;color:#fff;display:inline-block;font-weight:700;padding:12px 20px;text-decoration:none}</style></head><body>${body}</body></html>`;
@@ -104,9 +102,27 @@ export async function renderEmail(
if (options.countdownImageUrl) {
try {
const url = new URL(options.countdownImageUrl);
if (url.username || url.password || (url.protocol !== "https:" && !(url.protocol === "http:" && (url.hostname === "localhost" || url.hostname.endsWith(".localhost"))))) throw new Error();
if (
url.username ||
url.password ||
(url.protocol !== "https:" &&
!(
url.protocol === "http:" &&
(url.hostname === "localhost" || url.hostname.endsWith(".localhost"))
))
)
throw new Error();
} catch {
return { ok: false, errors: [{ code: "countdown.endpoint", message: "Countdown images require HTTPS (or a local development host).", severity: "error" }] };
return {
ok: false,
errors: [
{
code: "countdown.endpoint",
message: "Countdown images require HTTPS (or a local development host).",
severity: "error",
},
],
};
}
}
const source = personalized.value;
@@ -119,13 +135,27 @@ export async function renderEmail(
brandLinkColor: String(source.root.props.linkColor ?? "#2563eb"),
emailSubject: String(source.meta.subject),
emailPreheader: String(source.meta.preheader ?? ""),
rootBlockIds: Object.values(source.root.slots).flat().map(node => node.id),
rootBlockIds: Object.values(source.root.slots)
.flat()
.map((node) => node.id),
};
const [htmlResult, textResult, mjmlResult] = await Promise.all([
renderTree(source, emailKind, registry, { ...base, target: "emailHtml", data: options.variables }),
renderTree(source, emailKind, registry, { ...base, target: "plainText", data: options.variables }),
renderTree(source, emailKind, registry, {
...base,
target: "emailHtml",
data: options.variables,
}),
renderTree(source, emailKind, registry, {
...base,
target: "plainText",
data: options.variables,
}),
options.mjml
? renderTree(source, emailKind, registry, { ...base, target: "mjml", data: options.variables })
? renderTree(source, emailKind, registry, {
...base,
target: "mjml",
data: options.variables,
})
: Promise.resolve(undefined),
]);
if (!htmlResult.ok) return htmlResult;
@@ -151,31 +181,60 @@ export async function renderEmail(
if (mjmlResult?.ok) {
const diagnostics = await validateMjml(mjmlResult.value.content);
if (!diagnostics.length) bundle.exports = { mjml: mjmlResult.value.content };
else warnings.push(...diagnostics.map(diagnostic => ({ ...diagnostic, severity: "warning" as const })));
else
warnings.push(
...diagnostics.map((diagnostic) => ({ ...diagnostic, severity: "warning" as const })),
);
} else if (mjmlResult) {
warnings.push(...mjmlResult.errors.map(diagnostic => ({ ...diagnostic, severity: "warning" as const })));
warnings.push(
...mjmlResult.errors.map((diagnostic) => ({ ...diagnostic, severity: "warning" as const })),
);
}
if (options.amp) {
const amp = await renderTree(source, emailKind, registry, { ...base, target: "ampEmail", data: options.variables });
const amp = await renderTree(source, emailKind, registry, {
...base,
target: "ampEmail",
data: options.variables,
});
if (amp.ok) {
const content = ampHead(source, amp.value.content, base.direction);
let timer: ReturnType<typeof setTimeout> | undefined;
let validation: ValidationReport;
const requestedTimeout = options.ampValidationTimeoutMs ?? 2000;
const timeout = Number.isFinite(requestedTimeout) ? Math.min(10000, Math.max(10, requestedTimeout)) : 2000;
const timeout = Number.isFinite(requestedTimeout)
? Math.min(10000, Math.max(10, requestedTimeout))
: 2000;
try {
validation = await Promise.race([
Promise.resolve().then(() => (options.ampValidator ?? validateAmpEmail)(content)),
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("AMP validation timed out.")), timeout); }),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error("AMP validation timed out.")), timeout);
}),
]);
} catch {
validation = { valid: false, diagnostics: [{code:"amp.validatorUnavailable",message:"AMP validation was unavailable or timed out. HTML and plain text remain available.",severity:"warning"}] };
validation = {
valid: false,
diagnostics: [
{
code: "amp.validatorUnavailable",
message:
"AMP validation was unavailable or timed out. HTML and plain text remain available.",
severity: "warning",
},
],
};
} finally {
if (timer !== undefined) clearTimeout(timer);
}
if (validation.valid)
bundle.parts.amp = { contentType: "text/x-amp-html; charset=utf-8", content, validation };
else warnings.push(...validation.diagnostics.map(diagnostic => ({...diagnostic,severity:"warning" as const})));
else
warnings.push(
...validation.diagnostics.map((diagnostic) => ({
...diagnostic,
severity: "warning" as const,
})),
);
} else
warnings.push(...amp.errors.map((error) => ({ ...error, severity: "warning" as const })));
}
+128 -35
View File
@@ -101,30 +101,65 @@ export function importMjml(
};
}
const errors: MjmlDiagnostic[] = [];
if (!ast || ast.tagName !== "mjml") return { ok: false, errors: [{ code: "mjml.root", message: "MJML requires an mjml root element.", severity: "error" }] };
if (!ast || ast.tagName !== "mjml")
return {
ok: false,
errors: [
{ code: "mjml.root", message: "MJML requires an mjml root element.", severity: "error" },
],
};
const pending = [{ node: ast, depth: 0 }];
let nodeCount = 0;
while (pending.length) {
const { node, depth } = pending.pop()!;
if (++nodeCount > DEFAULT_LIMITS.maxNodes || depth > DEFAULT_LIMITS.maxDepth) {
return { ok: false, errors: [{ code: "mjml.limits", message: "MJML exceeds document node or depth limits.", severity: "error" }] };
return {
ok: false,
errors: [
{
code: "mjml.limits",
message: "MJML exceeds document node or depth limits.",
severity: "error",
},
],
};
}
for (const child of node.children ?? []) pending.push({ node: child, depth: depth + 1 });
}
const decode = (value: string) => value.replace(/&(?:#(x[0-9a-f]+|[0-9]+)|(amp|lt|gt|quot|apos));/gi, (original, numeric: string | undefined, name: string | undefined) => {
if (numeric) {
const point = numeric[0]!.toLowerCase() === "x" ? Number.parseInt(numeric.slice(1), 16) : Number(numeric);
return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : original;
}
return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record<string, string>)[name!.toLowerCase()]!;
});
const decode = (value: string) =>
value.replace(
/&(?:#(x[0-9a-f]+|[0-9]+)|(amp|lt|gt|quot|apos));/gi,
(original, numeric: string | undefined, name: string | undefined) => {
if (numeric) {
const point =
numeric[0]!.toLowerCase() === "x"
? Number.parseInt(numeric.slice(1), 16)
: Number(numeric);
return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
? String.fromCodePoint(point)
: original;
}
return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record<string, string>)[
name!.toLowerCase()
]!;
},
);
const brand: Record<string, string> = {};
let importedSubject = "", importedPreheader = "";
const attributeError = (node: MjmlAst, attribute?: string) => errors.push({ code: "mjml.header", message: `Unsupported MJML header setting ${node.tagName}${attribute ? `.${attribute}` : ""}.`, severity: "error", element: node.tagName, attribute });
let importedSubject = "",
importedPreheader = "";
const attributeError = (node: MjmlAst, attribute?: string) =>
errors.push({
code: "mjml.header",
message: `Unsupported MJML header setting ${node.tagName}${attribute ? `.${attribute}` : ""}.`,
severity: "error",
element: node.tagName,
attribute,
});
const onlyAttributes = (node: MjmlAst, allowed: string[]) => {
for (const key of Object.keys(node.attributes ?? {})) if (!allowed.includes(key)) attributeError(node, key);
for (const key of Object.keys(node.attributes ?? {}))
if (!allowed.includes(key)) attributeError(node, key);
};
for (const head of (ast.children ?? []).filter(node => node.tagName === "mj-head")) {
for (const head of (ast.children ?? []).filter((node) => node.tagName === "mj-head")) {
onlyAttributes(head, []);
for (const node of head.children ?? []) {
if (node.tagName === "mj-title" || node.tagName === "mj-preview") {
@@ -136,13 +171,15 @@ export function importMjml(
for (const defaults of node.children ?? []) {
if (defaults.tagName === "mj-all") {
onlyAttributes(defaults, ["font-family"]);
if (defaults.attributes?.["font-family"]) brand.fontFamily = decode(defaults.attributes["font-family"]);
if (defaults.attributes?.["font-family"])
brand.fontFamily = decode(defaults.attributes["font-family"]);
} else if (defaults.tagName === "mj-text") {
onlyAttributes(defaults, ["color"]);
if (defaults.attributes?.color) brand.textColor = decode(defaults.attributes.color);
} else if (defaults.tagName === "mj-button") {
onlyAttributes(defaults, ["background-color"]);
if (defaults.attributes?.["background-color"]) brand.linkColor = decode(defaults.attributes["background-color"]);
if (defaults.attributes?.["background-color"])
brand.linkColor = decode(defaults.attributes["background-color"]);
} else attributeError(defaults);
}
} else if (node.tagName === "mj-breakpoint") {
@@ -151,31 +188,67 @@ export function importMjml(
} else attributeError(node);
}
}
const bodyAttributes = (ast.children ?? []).find(node => node.tagName === "mj-body")?.attributes ?? {};
const bodyAttributes =
(ast.children ?? []).find((node) => node.tagName === "mj-body")?.attributes ?? {};
const wrapColumns = (nodes: BlockNode[]): BlockNode[] => {
const output: BlockNode[] = [];
for (let index = 0; index < nodes.length;) {
if (nodes[index]!.type !== "layout.column") { output.push(nodes[index++]!); continue; }
if (nodes[index]!.type !== "layout.column") {
output.push(nodes[index++]!);
continue;
}
const columns: BlockNode[] = [];
while (index < nodes.length && nodes[index]!.type === "layout.column") columns.push(nodes[index++]!);
while (index < nodes.length && nodes[index]!.type === "layout.column")
columns.push(nodes[index++]!);
let explicit = 0;
const missing = columns.filter(column => !column.props.width);
const missing = columns.filter((column) => !column.props.width);
for (const column of columns) {
const width = String(column.props.width || "");
if (!width) continue;
if (!/^\d+(?:\.\d+)?%$/.test(width) || Number.parseFloat(width) <= 0 || Number.parseFloat(width) > 100) {
errors.push({ code: "mjml.column-width", message: "Column width must be a percentage between 0 and 100.", severity: "error", element: "mj-column", attribute: "width" });
if (
!/^\d+(?:\.\d+)?%$/.test(width) ||
Number.parseFloat(width) <= 0 ||
Number.parseFloat(width) > 100
) {
errors.push({
code: "mjml.column-width",
message: "Column width must be a percentage between 0 and 100.",
severity: "error",
element: "mj-column",
attribute: "width",
});
} else explicit += Number.parseFloat(width);
}
if (explicit > 100 || (!missing.length && Math.abs(explicit - 100) > 0.001) || (missing.length && explicit >= 100)) {
errors.push({ code: "mjml.column-width", message: "Column widths must fill one 100% row.", severity: "error", element: "mj-column", attribute: "width" });
if (
explicit > 100 ||
(!missing.length && Math.abs(explicit - 100) > 0.001) ||
(missing.length && explicit >= 100)
) {
errors.push({
code: "mjml.column-width",
message: "Column widths must fill one 100% row.",
severity: "error",
element: "mj-column",
attribute: "width",
});
}
let assigned = 0;
missing.forEach((column, position) => {
const width = position === missing.length - 1 ? 100 - explicit - assigned : Math.round((100 - explicit) / missing.length * 100) / 100;
column.props.width = `${width}%`; assigned += width;
const width =
position === missing.length - 1
? 100 - explicit - assigned
: Math.round(((100 - explicit) / missing.length) * 100) / 100;
column.props.width = `${width}%`;
assigned += width;
});
output.push({
id: options.id(),
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: { columns },
});
output.push({ id: options.id(), type: "layout.columns", version: 1, props: {}, styles: {}, slots: { columns } });
}
return output;
};
@@ -191,7 +264,10 @@ export function importMjml(
return [];
}
const converted = (node.children ?? []).flatMap(convert);
const children = containers.has(node.tagName) && node.tagName !== "mj-column" ? wrapColumns(converted) : converted;
const children =
containers.has(node.tagName) && node.tagName !== "mj-column"
? wrapColumns(converted)
: converted;
if (node.tagName === "mjml" || node.tagName === "mj-head" || node.tagName === "mj-body")
return children;
if (
@@ -262,14 +338,23 @@ export function importMjml(
"font-size": ["fontSize", /^\d+(?:\.\d+)?(?:px|rem|em|%)$/],
"font-weight": ["fontWeight", /^(normal|bold|[1-9]00)$/],
"border-radius": ["borderRadius", /^\d+(?:\.\d+)?(?:px|rem|em|%)$/],
"inner-padding": ["padding", /^\d+(?:\.\d+)?(?:px|rem|em|%)(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)){0,3}$/],
"inner-padding": [
"padding",
/^\d+(?:\.\d+)?(?:px|rem|em|%)(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)){0,3}$/,
],
};
for (const [attribute, raw] of Object.entries(a)) {
if (attribute === "href") continue;
const mapping = mappings[attribute];
const value = decode(raw).trim();
if (!mapping || value.length > 80 || !mapping[1].test(value)) {
errors.push({ code: "mjml.button-attribute", message: `Unsupported button attribute or value: ${attribute}.`, severity: "error", element: node.tagName, attribute });
errors.push({
code: "mjml.button-attribute",
message: `Unsupported button attribute or value: ${attribute}.`,
severity: "error",
element: node.tagName,
attribute,
});
} else buttonStyles[mapping[0]] = { base: value };
}
return [
@@ -304,7 +389,11 @@ export function importMjml(
id: options.id(),
type: "layout.email-document",
version: 1,
props: { width: (bodyAttributes.width ?? "600").replace(/px$/, ""), background: bodyAttributes["background-color"] ?? "#f3f4f6", ...brand },
props: {
width: (bodyAttributes.width ?? "600").replace(/px$/, ""),
background: bodyAttributes["background-color"] ?? "#f3f4f6",
...brand,
},
styles: {},
slots: {
content: content.map((node) =>
@@ -322,11 +411,15 @@ export function importMjml(
},
};
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: options.subject ?? (importedSubject || "Imported email"), preheader: options.preheader ?? importedPreheader, lang: "en" },
theme: { tokens: {} },
root,
schemaVersion: 1,
kind: "email",
meta: {
subject: options.subject ?? (importedSubject || "Imported email"),
preheader: options.preheader ?? importedPreheader,
lang: "en",
},
theme: { tokens: {} },
root,
};
const validated = validateDocument(document, emailKind, registryForKind(emailKind).freeze());
if (!validated.ok) return { ok: false, errors: validated.errors };
+232 -77
View File
@@ -2,100 +2,255 @@ import type { BlockNode, JsonObject } from "@wrnexus/blocks";
/** Designed compositions made entirely from native, editable email blocks. */
export function createSectionPreset(name: string, id: () => string): BlockNode {
const node = (type: string, props: JsonObject, slots: Record<string, BlockNode[]> = {}, appearance: Record<string, string> = {}): BlockNode => ({
id: id(), type, version: 1, props,
styles: Object.fromEntries(Object.entries(appearance).map(([key, base]) => [key, {base}])), slots,
const node = (
type: string,
props: JsonObject,
slots: Record<string, BlockNode[]> = {},
appearance: Record<string, string> = {},
): BlockNode => ({
id: id(),
type,
version: 1,
props,
styles: Object.fromEntries(Object.entries(appearance).map(([key, base]) => [key, { base }])),
slots,
});
const text = (value: string, appearance: Record<string, string> = {}) =>
node("content.text", {text: value}, {}, {fontSize: "16px", color: "#475569", ...appearance});
node(
"content.text",
{ text: value },
{},
{ fontSize: "16px", color: "#475569", ...appearance },
);
const heading = (value: string, appearance: Record<string, string> = {}) =>
node("content.heading", {text: value, level: "2"}, {}, {fontSize: "22px", color: "#14213d", ...appearance});
const eyebrow = (value: string, color = "#0f766e") => text(value, {fontSize: "11px", fontWeight: "700", color});
const button = (label: string, background = "#14213d", color = "#ffffff", href = "https://example.com") =>
node("content.button", {label, href}, {}, {backgroundColor: background, color, padding: "14px 24px", borderRadius: "8px", fontSize: "14px", fontWeight: "700"});
const space = (height = "16") => node("content.spacer", {height});
const column = (content: BlockNode[], width = "100%") => node("layout.column", {width}, {content});
const row = (columns: BlockNode[]) => node("layout.columns", {}, {columns});
let rows: BlockNode[], background = "#ffffff", padding = "40px";
node(
"content.heading",
{ text: value, level: "2" },
{},
{ fontSize: "22px", color: "#14213d", ...appearance },
);
const eyebrow = (value: string, color = "#0f766e") =>
text(value, { fontSize: "11px", fontWeight: "700", color });
const button = (
label: string,
background = "#14213d",
color = "#ffffff",
href = "https://example.com",
) =>
node(
"content.button",
{ label, href },
{},
{
backgroundColor: background,
color,
padding: "14px 24px",
borderRadius: "8px",
fontSize: "14px",
fontWeight: "700",
},
);
const space = (height = "16") => node("content.spacer", { height });
const column = (content: BlockNode[], width = "100%") =>
node("layout.column", { width }, { content });
const row = (columns: BlockNode[]) => node("layout.columns", {}, { columns });
let rows: BlockNode[],
background = "#ffffff",
padding = "40px";
if (name === "welcome") {
background = "#edf7f3";
rows = [row([column([
eyebrow("A FRESH START"),
heading("Good things start here.", {fontSize: "26px"}),
text("Welcome, {{recipientName|friend}}. A little inspiration, thoughtful discoveries, and more of what you love — all in one place."),
space("8"), button("Make yourself at home", "#0f766e"),
space("24"), text("YOUR NEXT CHAPTER / STARTS TODAY", {fontSize: "10px", color: "#0f766e", fontWeight: "700"}),
])])];
} else if (name === "feature") {
background = "#f4f1eb";
rows = [row([
column([
text("THE EDIT", {fontSize: "11px", fontWeight: "700", color: "#9a3412"}),
heading("Less noise.\nMore possibility.", {fontSize: "23px"}),
text("Meet your next everyday favorite. Thoughtfully made, beautifully simple, and ready for whatever comes next.", {fontSize: "14px"}),
space("8"), button("Discover the collection", "#9a3412"),
], "65%"),
column([
text("01", {fontSize: "64px", fontWeight: "700", color: "#9a3412", textAlign: "center", backgroundColor: "#eadfd1", padding: "24px 8px"}),
text("THOUGHTFULLY\nCURATED", {fontSize: "11px", fontWeight: "700", textAlign: "center", color: "#9a3412", padding: "16px 8px"}),
], "35%"),
])];
} else if (name === "announcement") {
background = "#14213d";
rows = [row([column([
eyebrow("JUST RELEASED", "#a7f3d0"),
heading("Something new.\nMade for you.", {fontSize: "28px", color: "#ffffff"}),
text("A fresh perspective. A better experience. Discover the latest chapter and see what we’ve been working on.", {color: "#cbd5e1"}),
space("12"), button("Take a first look", "#a7f3d0", "#14213d"),
space("20"), text("BE THE FIRST TO EXPLORE", {fontSize: "10px", color: "#a7f3d0", fontWeight: "700"}),
])])];
} else if (name === "testimonial") {
background = "#fff7ed";
rows = [row([column([
eyebrow("FROM OUR COMMUNITY", "#9a3412"),
text("“", {fontSize: "64px", color: "#c2410c", fontWeight: "700"}),
heading("The details make\nall the difference.", {fontSize: "23px", color: "#431407"}),
text("“A thoughtful experience from start to finish. Everything felt effortless — and the result was even better than I imagined.”", {color: "#7c2d12"}),
space("12"), text("CUSTOMER NAME", {fontSize: "12px", fontWeight: "700", color: "#431407"}),
text("Customer story · Replace with an approved quote", {fontSize: "11px", color: "#9a3412"}),
])])];
} else if (name === "two-column") {
rows = [
row([column([eyebrow("A LITTLE INSPIRATION"), heading("Two ways to find your next favorite."), space("12")])]),
row([
column([
text("01 / DISCOVER", {fontSize: "11px", fontWeight: "700", color: "#0f766e", backgroundColor: "#edf7f3", padding: "20px 16px"}),
heading("Fresh perspectives", {fontSize: "16px", padding: "16px 16px 0"}),
text("Ideas and inspiration to make every day feel a little different.", {fontSize: "14px", padding: "0 16px"}),
button("Explore ideas", "#0f766e"),
], "50%"),
eyebrow("A FRESH START"),
heading("Good things start here.", { fontSize: "26px" }),
text(
"Welcome, {{recipientName|friend}}. A little inspiration, thoughtful discoveries, and more of what you love — all in one place.",
),
space("8"),
button("Make yourself at home", "#0f766e"),
space("24"),
text("YOUR NEXT CHAPTER / STARTS TODAY", {
fontSize: "10px",
color: "#0f766e",
fontWeight: "700",
}),
]),
]),
];
} else if (name === "feature") {
background = "#f4f1eb";
rows = [
row([
column(
[
text("THE EDIT", { fontSize: "11px", fontWeight: "700", color: "#9a3412" }),
heading("Less noise.\nMore possibility.", { fontSize: "23px" }),
text(
"Meet your next everyday favorite. Thoughtfully made, beautifully simple, and ready for whatever comes next.",
{ fontSize: "14px" },
),
space("8"),
button("Discover the collection", "#9a3412"),
],
"65%",
),
column(
[
text("01", {
fontSize: "64px",
fontWeight: "700",
color: "#9a3412",
textAlign: "center",
backgroundColor: "#eadfd1",
padding: "24px 8px",
}),
text("THOUGHTFULLY\nCURATED", {
fontSize: "11px",
fontWeight: "700",
textAlign: "center",
color: "#9a3412",
padding: "16px 8px",
}),
],
"35%",
),
]),
];
} else if (name === "announcement") {
background = "#14213d";
rows = [
row([
column([
text("02 / EXPLORE", {fontSize: "11px", fontWeight: "700", color: "#9a3412", backgroundColor: "#fff7ed", padding: "20px 16px"}),
heading("Thoughtful essentials", {fontSize: "16px", padding: "16px 16px 0"}),
text("Considered details. Everyday favorites. Find something that fits.", {fontSize: "14px", padding: "0 16px"}),
button("Find your favorite", "#9a3412"),
], "50%"),
eyebrow("JUST RELEASED", "#a7f3d0"),
heading("Something new.\nMade for you.", { fontSize: "28px", color: "#ffffff" }),
text(
"A fresh perspective. A better experience. Discover the latest chapter and see what we’ve been working on.",
{ color: "#cbd5e1" },
),
space("12"),
button("Take a first look", "#a7f3d0", "#14213d"),
space("20"),
text("BE THE FIRST TO EXPLORE", {
fontSize: "10px",
color: "#a7f3d0",
fontWeight: "700",
}),
]),
]),
];
} else if (name === "testimonial") {
background = "#fff7ed";
rows = [
row([
column([
eyebrow("FROM OUR COMMUNITY", "#9a3412"),
text("“", { fontSize: "64px", color: "#c2410c", fontWeight: "700" }),
heading("The details make\nall the difference.", { fontSize: "23px", color: "#431407" }),
text(
"“A thoughtful experience from start to finish. Everything felt effortless — and the result was even better than I imagined.”",
{ color: "#7c2d12" },
),
space("12"),
text("CUSTOMER NAME", { fontSize: "12px", fontWeight: "700", color: "#431407" }),
text("Customer story · Replace with an approved quote", {
fontSize: "11px",
color: "#9a3412",
}),
]),
]),
];
} else if (name === "two-column") {
rows = [
row([
column([
eyebrow("A LITTLE INSPIRATION"),
heading("Two ways to find your next favorite."),
space("12"),
]),
]),
row([
column(
[
text("01 / DISCOVER", {
fontSize: "11px",
fontWeight: "700",
color: "#0f766e",
backgroundColor: "#edf7f3",
padding: "20px 16px",
}),
heading("Fresh perspectives", { fontSize: "16px", padding: "16px 16px 0" }),
text("Ideas and inspiration to make every day feel a little different.", {
fontSize: "14px",
padding: "0 16px",
}),
button("Explore ideas", "#0f766e"),
],
"50%",
),
column(
[
text("02 / EXPLORE", {
fontSize: "11px",
fontWeight: "700",
color: "#9a3412",
backgroundColor: "#fff7ed",
padding: "20px 16px",
}),
heading("Thoughtful essentials", { fontSize: "16px", padding: "16px 16px 0" }),
text("Considered details. Everyday favorites. Find something that fits.", {
fontSize: "14px",
padding: "0 16px",
}),
button("Find your favorite", "#9a3412"),
],
"50%",
),
]),
];
} else if (name === "footer") {
background = "#f1f5f9";
padding = "32px 40px";
rows = [row([column([
eyebrow("LET’S STAY CONNECTED", "#334155"),
heading("Thanks for being here.", {fontSize: "18px"}),
text("Good things are better shared. We’re glad you’re part of our community.", {fontSize: "13px"}),
node("content.divider", {}),
text("{{organizationAddress|Add your organization address}}", {fontSize: "12px", color: "#64748b"}),
text("You’re receiving this email because you signed up for our updates.", {fontSize: "11px", color: "#64748b"}),
button("Unsubscribe", "#e2e8f0", "#334155", "{{unsubscribeUrl|https://example.com/unsubscribe}}"),
])])];
rows = [
row([
column([
eyebrow("LET’S STAY CONNECTED", "#334155"),
heading("Thanks for being here.", { fontSize: "18px" }),
text("Good things are better shared. We’re glad you’re part of our community.", {
fontSize: "13px",
}),
node("content.divider", {}),
text("{{organizationAddress|Add your organization address}}", {
fontSize: "12px",
color: "#64748b",
}),
text("You’re receiving this email because you signed up for our updates.", {
fontSize: "11px",
color: "#64748b",
}),
button(
"Unsubscribe",
"#e2e8f0",
"#334155",
"{{unsubscribeUrl|https://example.com/unsubscribe}}",
),
]),
]),
];
} else throw new Error("Unknown section preset.");
return node("layout.section", {background, padding}, {content: rows});
return node("layout.section", { background, padding }, { content: rows });
}
export const emailPresets = ["welcome", "feature", "announcement", "testimonial", "two-column", "footer"].map(id => ({
export const emailPresets = [
"welcome",
"feature",
"announcement",
"testimonial",
"two-column",
"footer",
].map((id) => ({
id,
name: {key: "email.presets." + id, fallback: id[0].toUpperCase() + id.slice(1)},
name: { key: "email.presets." + id, fallback: id[0].toUpperCase() + id.slice(1) },
icon: "icon-[lucide--layout-template]",
create: (context: {id(): string}) => createSectionPreset(id, context.id),
create: (context: { id(): string }) => createSectionPreset(id, context.id),
}));
+51 -12
View File
@@ -1,26 +1,65 @@
import type { ValueSchema } from "@wrnexus/blocks";
export interface TextRun { text: string; bold?: boolean; italic?: boolean; underline?: boolean }
export interface TextRun {
text: string;
bold?: boolean;
italic?: boolean;
underline?: boolean;
}
export const richTextSchema: ValueSchema<TextRun[]> = {
kind: "rich-text",
parse(value = [], path = "richText") {
if (!Array.isArray(value) || value.length > 4000 || value.some(run => !run || typeof run !== "object" || typeof run.text !== "string" || Object.keys(run).some(key => !["text", "bold", "italic", "underline"].includes(key)) || ["bold", "italic", "underline"].some(key => run[key] !== undefined && typeof run[key] !== "boolean")) || value.reduce((size, run) => size + run.text.length, 0) > 200000)
return { ok: false, errors: [{code: "email.rich-text", message: "Invalid or oversized rich text.", severity: "error", path}] };
if (
!Array.isArray(value) ||
value.length > 4000 ||
value.some(
(run) =>
!run ||
typeof run !== "object" ||
typeof run.text !== "string" ||
Object.keys(run).some((key) => !["text", "bold", "italic", "underline"].includes(key)) ||
["bold", "italic", "underline"].some(
(key) => run[key] !== undefined && typeof run[key] !== "boolean",
),
) ||
value.reduce((size, run) => size + run.text.length, 0) > 200000
)
return {
ok: false,
errors: [
{
code: "email.rich-text",
message: "Invalid or oversized rich text.",
severity: "error",
path,
},
],
};
return { ok: true, value };
},
};
const escape = (value: string) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;").replace(/\r\n?|\n/g, "<br />");
const escape = (value: string) =>
value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;")
.replace(/\r\n?|\n/g, "<br />");
/** Ignore stale formatting if a plain-text inspector or importer changed the text. */
export function renderRichText(props: Record<string, unknown>): string {
const parsed = richTextSchema.parse(props.richText);
const text = String(props.text ?? "");
if (!parsed.ok || !parsed.value.length || parsed.value.map(run => run.text).join("") !== text) return escape(text);
return parsed.value.map(run => {
let result = escape(run.text);
if (run.underline) result = `<u>${result}</u>`;
if (run.italic) result = `<em>${result}</em>`;
if (run.bold) result = `<strong>${result}</strong>`;
return result;
}).join("");
if (!parsed.ok || !parsed.value.length || parsed.value.map((run) => run.text).join("") !== text)
return escape(text);
return parsed.value
.map((run) => {
let result = escape(run.text);
if (run.underline) result = `<u>${result}</u>`;
if (run.italic) result = `<em>${result}</em>`;
if (run.bold) result = `<strong>${result}</strong>`;
return result;
})
.join("");
}
+26 -10
View File
@@ -1,7 +1,12 @@
const color = /^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\([0-9., %]+\))$/i;
const spacing = /^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))(?:\s+(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))){0,3}$/;
const color =
/^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\([0-9., %]+\))$/i;
const spacing =
/^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))(?:\s+(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))){0,3}$/;
const patterns: Record<string, RegExp> = {
color, backgroundColor: color, padding: spacing, margin: spacing,
color,
backgroundColor: color,
padding: spacing,
margin: spacing,
fontSize: /^\d+(?:\.\d+)?(?:px|rem|em|%)$/,
borderRadius: /^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))$/,
textAlign: /^(left|center|right|start|end)$/,
@@ -11,11 +16,11 @@ const patterns: Record<string, RegExp> = {
function validColor(value: string): boolean {
if (!/^rgba?\(/i.test(value)) return true;
const match = /^(rgb|rgba)\((.*)\)$/i.exec(value)!;
const channels = match[2]!.split(",").map(part => part.trim());
const channels = match[2]!.split(",").map((part) => part.trim());
if (channels.length !== (match[1]!.toLowerCase() === "rgba" ? 4 : 3)) return false;
const numeric = /^(?:\d+(?:\.\d+)?|\.\d+)%?$/;
if (!channels.every(channel => numeric.test(channel))) return false;
const percentages = channels.slice(0, 3).filter(channel => channel.endsWith("%")).length;
if (!channels.every((channel) => numeric.test(channel))) return false;
const percentages = channels.slice(0, 3).filter((channel) => channel.endsWith("%")).length;
if (percentages !== 0 && percentages !== 3) return false;
return channels.every((channel, index) => {
const maximum = channel.endsWith("%") ? 100 : index === 3 ? 1 : 255;
@@ -27,13 +32,24 @@ function validColor(value: string): boolean {
export function emailStyleValue(key: string, value: unknown): string {
if (typeof value !== "string") return "";
const candidate = value.trim();
if (candidate.length > 80 || !Object.prototype.hasOwnProperty.call(patterns, key) || !patterns[key]!.test(candidate)) return "";
if (
candidate.length > 80 ||
!Object.prototype.hasOwnProperty.call(patterns, key) ||
!patterns[key]!.test(candidate)
)
return "";
if ((key === "color" || key === "backgroundColor") && !validColor(candidate)) return "";
if (["padding", "margin", "fontSize", "borderRadius"].includes(key) &&
candidate.split(/\s+/).some(part => Number.parseFloat(part) > 4000)) return "";
if (
["padding", "margin", "fontSize", "borderRadius"].includes(key) &&
candidate.split(/\s+/).some((part) => Number.parseFloat(part) > 4000)
)
return "";
return candidate;
}
export function validateEmailStyleValue(key: string, value: string): void {
if (!emailStyleValue(key, value)) throw new Error(`styles.${key}: Unsupported style value. Use an email-safe value with units where required.`);
if (!emailStyleValue(key, value))
throw new Error(
`styles.${key}: Unsupported style value. Use an email-safe value with units where required.`,
);
}