Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/kit

src/html.ts

58 lines · 2.2 KB · TypeScript
/**
 * Small HTML helpers for Kit email bodies. These emit generic Liquid/HTML —
 * they do not encode a particular sender, list, or template.
 */

export function buildLiquidGreeting(options: { withName: string; withoutName: string }): string {
	return `<p>{% if subscriber.first_name != blank %}${options.withName}{% else %}${options.withoutName}{% endif %}</p>`
}

export function buildParagraph(html: string): string {
	return `<p>${html}</p>`
}

export function buildLinkedImage(options: { href: string; src: string; alt?: string }): string {
	const alt = options.alt ?? ''
	return `<p><a href="${options.href}"><img src="${options.src}" alt="${alt}" style="width:100%;max-width:600px;display:block;" /></a></p>`
}

export function buildLinkedImageBlock(options: {
	href: string
	src: string
	alt?: string
	caption?: string
}): string {
	const alt = options.alt ?? ''
	const figcaption = options.caption
		? `<figcaption style="text-align:center;display:block">${options.caption}</figcaption>`
		: ''
	return `<table width="100%" border="0" cellSpacing="0" cellPadding="0" style="text-align:center;table-layout:fixed;float:none" class="email-image"><tbody><tr><td align="center"><figure style="margin-top:12px;margin-bottom:12px;margin-left:0;margin-right:0;max-width:800px;width:100%"><a style="display:block" href="${options.href}" target="_blank" rel="noopener noreferrer" class="kit-image-link"><img src="${options.src}" width="800" height="auto" alt="${alt}" style="border-radius:4px;width:800px;height:auto;object-fit:contain"/></a>${figcaption}</figure></td></tr></tbody></table>`
}

export function buildUnorderedList(items: Array<string>): string {
	const lis = items.map((item) => `<li>${item}</li>`).join('\n')
	return `<ul>\n${lis}\n</ul>`
}

export function joinEmailBlocks(blocks: Array<string>, options: { separator?: string } = {}): string {
	return blocks.filter(Boolean).join(options.separator ?? '\n\n')
}

/**
 * HTML builder catalog.
 * @example
 * import html from 'kody:@kody/kit/html'
 * const catalog = await html()
 */
export default async function htmlOverview() {
	return {
		builders: [
			'buildLiquidGreeting',
			'buildParagraph',
			'buildLinkedImage',
			'buildLinkedImageBlock',
			'buildUnorderedList',
			'joinEmailBlocks',
		],
	}
}