/* ═══════════════════════════════════════════════════════════════ NEWSLETTER: email-ready HTML and plain text from a list of parts The admin's Newsletter tool (AdminNewsletter.tsx) edits a draft as one ordered list of parts (060_newsletter_layout.sql); this turns it into one email to paste into Mailchimp, Gmail or Church Center. Nothing is sent from here. The parts, each aligned left or center: header the band above the title: text, a logo, its color (or no band); left out when the part is removed title the email's heading picks a section of picked events, blog posts or front page cards: its heading and underline, each card's left bar, and the button label footer the closing lines (blank: the site's name and address) and the rule above them social a band of the site's platform icons, each linked (PNGs in public/email/: scripts/email-icons.mjs) countdown a picture of the time left until a picked event, drawn by the API when the email is opened (server/src/routes/countdown.js), with a fixed line under it, as of copying, for when images don't load any block drawn as its email-safe equivalent: headings, paragraphs (with **bold**, *italic* and [links](url)), callouts, quotes, lists, link and button rows, images, cards and dividers (with their color, thickness and spacing); a video is its still linked to the video Colors are any hex color, picked in the builder, or "none"; blank is the default (EMAIL_COLOR). No unsubscribe link: Mailchimp adds its own to every send. Email clients ignore stylesheets, CSS variables and most layout, so the HTML is tables with inline styles at 600px, images with width and alt, and the palette written out as hex (the one place the site's colors are literals: an inbox has no theme tokens). A plain-text copy goes alongside for clients that show no HTML. ═══════════════════════════════════════════════════════════════ */ import { readableOn } from './color.ts' import { PLATFORMS } from './platforms.ts' import { firstWords } from '../lib/words.ts' export type NewsletterItem = { title: string /** A line under the title: dates and place, a byline. */ meta?: string | null text?: string | null /** An absolute image URL. */ image?: string | null /** An absolute link. */ href: string cta: string } export type PickSource = 'events' | 'posts' | 'cards' /* One part of the email, as the builder's editor holds it. Blocks use the content block fields; the other parts add their own. */ export type NewsletterPart = { type: string align?: 'left' | 'center' | '' | null text?: string | null media?: string | null href?: string | null alt?: string | null cite?: string | null items?: Array<{ text?: string | null; detail?: string | null; url?: string | null; media?: string | null }> /** The header's band, a divider's line. */ color?: string | null /** A divider's thickness and the space above it, in pixels. */ size?: string | number | null space?: string | number | null /** A picks section: what it picks from, its picks in order, its button label. */ source?: PickSource | '' | null picked?: Array<{ ref?: string | null }> cta?: string | null /** A picks section's underline, the footer's rule. */ rule?: string | null /** The bar down the left of a picks section's cards. */ bar?: string | null /** A social bar's links, in order. */ socials?: Array<{ platform?: string | null; url?: string | null }> /** A countdown's event. */ event?: string | null } /* What a countdown needs of its event. */ export type CountdownEvent = { title: string; starts_on?: string | null; href: string } export type Newsletter = { parts: NewsletterPart[] /** A picks part's items, ready to draw (picked, published, in order). */ itemsFor: (part: NewsletterPart) => NewsletterItem[] /** A countdown's event, if it's one that can be counted to. */ eventFor: (id: string) => CountdownEvent | null /** Now, for the countdown's fixed line. */ now: number /** A social bar with no links of its own shows these (the footer's). */ defaultSocials: Array<{ platform: string; url: string }> /** The site's address, for the header link and footer. */ origin: string siteName: string /** A site path or upload as an absolute address (blocks hold paths and bare filenames). */ absolute: (pathOrFile: string, kind: 'link' | 'image') => string } /* The palette as an inbox needs it. */ export const EMAIL_COLOR = { ink: '#001011', body: '#003a45', muted: '#3b5456', teal: '#00748a', page: '#f5f9f8', card: '#ffffff', rule: '#d6f5fa', } const COLOR = EMAIL_COLOR /* What each picks section is called and says on its buttons, unless the part says otherwise. */ export const PICK_DEFAULTS: Record = { events: { heading: 'Coming up', cta: 'Event details' }, posts: { heading: 'From the blog', cta: 'Read the post' }, cards: { heading: 'Featured', cta: 'Learn more' }, } export const DEFAULT_TITLE = (siteName: string) => `News from ${siteName}` const FONT = "'Poppins', Helvetica, Arial, sans-serif" const BODY_FONT = "'Montserrat', Helvetica, Arial, sans-serif" const escape = (value: string) => value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') /* A part's color: blank is `fallback`, "none" is no color at all, and anything but a hex color (it lands in a style attribute) is the fallback too. */ function colorOf(value: string | null | undefined, fallback: string): string | null { if (value === 'none') return null return value && /^#[0-9a-f]{6}$/i.test(value) ? value : fallback } /* A whole number of pixels within bounds, or the fallback. */ function px(value: string | number | null | undefined, fallback: number, min: number, max: number): number { const n = Math.round(Number(value)) return value === '' || value == null || !Number.isFinite(n) ? fallback : Math.min(max, Math.max(min, n)) } const alignOf = (part: NewsletterPart) => (part.align === 'center' ? 'center' : 'left') /* A link an email can follow: the site's own paths made absolute, anything but http, https and mailto refused. */ function safeHref(href: string, n: Newsletter): string | null { const value = href.trim() if (/^(https?:|mailto:)/i.test(value)) return value if (value.startsWith('/')) return n.absolute(value, 'link') return null } /* Escaped text with the editor's **bold**, *italic* and [text](url). */ function inline(text: string, n: Newsletter): string { return escape(text) .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_whole, label, href) => { const url = safeHref(href.replace(/&/g, '&'), n) return url ? `${label}` : label }) .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*]+)\*/g, '$1') } /* Paragraphs from text with blank lines between them, formatted when given the newsletter (its links need the site's address). */ const paragraphs = (text: string, style: string, n?: Newsletter) => text .split(/\n\s*\n/) .map((part) => part.trim()) .filter(Boolean) .map((part) => `

${(n ? inline(part, n) : escape(part)).replace(/\n/g, '
')}

`) .join('') const TEXT = `margin:12px 0 0;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};` const buttonHtml = (href: string, label: string, align: string) => `${escape(label)}` /* A full-width picture; centered by its row when it's narrower. */ const imageTag = (src: string, alt: string) => `${escape(alt)}` function blockHtml(block: NewsletterPart, n: Newsletter): string { // An email can't animate: rotating words ({Next|Now}) are their first. const text = firstWords(block.text).trim() const href = block.href ? safeHref(block.href, n) : null const items = block.items ?? [] const align = alignOf(block) switch (block.type) { case 'heading': return text ? `

${escape(text)}

` : '' case 'subheading': return text ? `

${escape(text)}

` : '' case 'paragraph': return text ? paragraphs(text, TEXT, n) : '' case 'callout': return text ? `
${paragraphs(text, TEXT, n)}
` : '' case 'quote': return text ? `
${paragraphs(text, `${TEXT}font-style:italic;`, n)}${ block.cite ? `

${escape(block.cite)}

` : '' }
` : '' case 'list': return items.length ? `` : '' case 'links': { const buttons = items .map((item) => (item.url ? safeHref(item.url, n) : null)) .map((url, i) => (url ? buttonHtml(url, items[i].text || url, align) : '')) .join('') return buttons ? `

${buttons}

` : '' } case 'button': return href && text ? `

${buttonHtml(href, text, align)}

` : '' case 'image': case 'video': { if (!block.media) return '' const img = imageTag(n.absolute(block.media, 'image'), block.alt ?? '') const caption = text ? `

${escape(text)}

` : '' return `
${href ? `${img}` : img}${caption}
` } case 'cards': return items .map((item) => { const url = item.url ? safeHref(item.url, n) : null if (!url || !item.text) return '' return `

${escape(item.text)}

${item.detail ? paragraphs(item.detail, TEXT) : ''}
` }) .join('') case 'divider': { const color = colorOf(block.color, COLOR.rule) // "none" keeps the space without a line. const line = color ? `border-top:${px(block.size, 2, 1, 8)}px solid ${color};` : '' return `
` } default: return '' } } function headerHtml(part: NewsletterPart, n: Newsletter): string { const band = colorOf(part.color, COLOR.body) const ink = band ? readableOn(band) : COLOR.ink const align = alignOf(part) const logo = part.media ? `${escape(part.text?.trim() || n.siteName)}` : '' // With a logo, words only when written; without one, the site's name. const words = part.text?.trim() || (part.media ? '' : n.siteName) const name = words ? `${escape(words)}` : '' return `${logo}${logo && name ? `
${name}
` : name}` } function itemHtml(item: NewsletterItem, part: NewsletterPart, align: string): string { const bar = colorOf(part.bar, COLOR.teal) const image = item.image ? `${imageTag(item.image, '')}` : '' const meta = item.meta ? `

${escape(item.meta)}

` : '' const text = item.text ? paragraphs(item.text, TEXT) : '' return ` ${image}

${escape(item.title)}

${meta}${text}

${buttonHtml(item.href, item.cta, align)}

` } function picksHtml(part: NewsletterPart, n: Newsletter): string { const items = n.itemsFor(part) if (items.length === 0) return '' const source = (part.source || 'events') as PickSource const heading = part.text?.trim() || PICK_DEFAULTS[source].heading const rule = colorOf(part.rule, COLOR.rule) const align = alignOf(part) return `

${escape(heading)}

${items.map((item) => itemHtml(item, part, align)).join('')} ` } function footerHtml(part: NewsletterPart, n: Newsletter): string { const rule = colorOf(part.rule, COLOR.rule) const lines = part.text?.trim() ? paragraphs(part.text, `margin:0 0 8px;font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};`, n) : `${escape(n.siteName)}
${escape(n.origin.replace(/^https?:\/\//, ''))}` return `
${lines}
` } /* The site's platform icons as PNGs, white or ink to read on the band. */ const platformLabel = (id: string) => PLATFORMS.find((p) => p.id === id)?.label ?? id const socialsOf = (part: NewsletterPart, n: Newsletter) => (part.socials?.length ? part.socials : n.defaultSocials).filter((link) => link.platform && link.url) const iconUrl = (n: Newsletter, platform: string, band: string | null) => `${n.origin}/email/${encodeURIComponent(platform)}-${band && readableOn(band) === '#ffffff' ? 'white' : 'ink'}.png` function socialHtml(part: NewsletterPart, n: Newsletter): string { const band = colorOf(part.color, COLOR.body) const links = socialsOf(part, n) .map((link) => ({ platform: link.platform!, url: safeHref(link.url!, n) })) .filter((link) => link.url) if (links.length === 0) return '' const icons = links .map( (link) => `${escape(platformLabel(link.platform))}`, ) .join('') return `
${icons}
` } /* "12 days to go", as of `now`: an event starts at its date's midnight. Null once it has, or with no date. */ export function countdownLine(event: CountdownEvent, now: number): string | null { if (!event.starts_on) return null const [y, m, d] = event.starts_on.split('-').map(Number) const days = Math.ceil((new Date(y, m - 1, d).getTime() - now) / 86_400_000) if (days <= 0) return null return days === 1 ? '1 day to go' : `${days} days to go` } function countdownHtml(part: NewsletterPart, n: Newsletter): string { const event = part.event ? n.eventFor(part.event) : null if (!event || !part.event) return '' const band = colorOf(part.color, COLOR.body) ?? COLOR.page const label = part.text?.trim() || event.title const query = new URLSearchParams({ bg: band.slice(1), fg: readableOn(band).slice(1), t: label }) const src = `${n.origin}/api/countdown/${encodeURIComponent(part.event)}.png?${query}` const line = countdownLine(event, n.now) ?? 'Happening now' return ` ${imageTag(src, `${label}: ${line}`)}

${escape(line)}: ${escape(event.title)}

` } function partHtml(part: NewsletterPart, n: Newsletter): string { switch (part.type) { case 'header': return headerHtml(part, n) case 'title': return `

${escape(part.text?.trim() || DEFAULT_TITLE(n.siteName))}

` case 'picks': return picksHtml(part, n) case 'footer': return footerHtml(part, n) case 'social': return socialHtml(part, n) case 'countdown': return countdownHtml(part, n) default: { const html = blockHtml(part, n) return html ? `${html}` : '' } } } /* The email's title, for the HTML's and the drafts list. */ export function newsletterTitle(n: Pick<Newsletter, 'parts' | 'siteName'>): string { return n.parts.find((part) => part.type === 'title')?.text?.trim() || DEFAULT_TITLE(n.siteName) } export function newsletterHtml(n: Newsletter): string { return `<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>${escape(newsletterTitle(n))}
${n.parts.map((part) => partHtml(part, n)).join('\n ')}
` } function blockText(block: NewsletterPart, n: Newsletter): string[] { const text = firstWords(block.text).trim() const items = block.items ?? [] const link = (url: string) => safeHref(url, n) ?? url switch (block.type) { case 'heading': return text ? [text.toUpperCase(), ''] : [] case 'subheading': case 'paragraph': case 'callout': case 'image': return text ? [text, ''] : [] case 'quote': return text ? [`"${text}"`, ...(block.cite ? [` ${block.cite}`] : []), ''] : [] case 'list': return items.length ? [...items.map((item) => `- ${item.text ?? ''}${item.detail ? `: ${item.detail}` : ''}${item.url ? ` (${link(item.url)})` : ''}`), ''] : [] case 'links': case 'cards': { const lines = items.filter((item) => item.url).map((item) => `${item.text ?? ''}: ${link(item.url!)}`) return lines.length ? [...lines, ''] : [] } case 'button': case 'video': return block.href ? [`${text || 'Link'}: ${link(block.href)}`, ''] : [] case 'divider': return ['---', ''] default: return [] } } function partText(part: NewsletterPart, n: Newsletter): string[] { switch (part.type) { case 'header': return [part.text?.trim() || n.siteName, ''] case 'title': { const title = part.text?.trim() || DEFAULT_TITLE(n.siteName) return [title, '='.repeat(Math.min(title.length, 60)), ''] } case 'picks': { const items = n.itemsFor(part) if (items.length === 0) return [] const source = (part.source || 'events') as PickSource const lines = [(part.text?.trim() || PICK_DEFAULTS[source].heading).toUpperCase(), ''] for (const item of items) { lines.push(item.title) if (item.meta) lines.push(item.meta) if (item.text) lines.push(item.text.trim()) lines.push(`${item.cta}: ${item.href}`, '') } return lines } case 'footer': return ['--', ...(part.text?.trim() ? [part.text.trim()] : [n.siteName, n.origin]), ''] case 'social': { const lines = socialsOf(part, n).map((link) => `${platformLabel(link.platform!)}: ${link.url}`) return lines.length ? [...lines, ''] : [] } case 'countdown': { const event = part.event ? n.eventFor(part.event) : null if (!event) return [] return [`${countdownLine(event, n.now) ?? 'Happening now'}: ${event.title}`, event.href, ''] } default: return blockText(part, n) } } export function newsletterText(n: Newsletter): string { return n.parts.flatMap((part) => partText(part, n)).join('\n').trim() }