Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

og.ts

164 lines · 6.6 KB · TypeScript
/**
 * Per-event share image (1200x630 PNG).
 *
 * Satori lays out the text (title, date chip, place, tagline) and turns the
 * glyphs into SVG paths. Kody package code cannot compile WebAssembly, so
 * resvg-wasm cannot run here; instead ./raster.ts fills those paths onto the
 * pre-rendered cozy background (./og-bg.ts) and encodes a PNG. Results are
 * cached in memory by event version; the URL carries the version so browsers,
 * Discord and other crawlers can cache it for a year.
 */
import satori from 'satori'
import { FREDOKA_600, FREDOKA_700, NUNITO_800 } from './fonts.ts'
import { OG_BG_PNG_BASE64 } from './og-bg.ts'
import { decodePng, encodePng, fillShape, svgShapes, type Image } from './raster.ts'
import { THEMES, type ThemeName } from './pies.ts'

export type OgInput = {
	title: string
	day?: string
	time?: string
	place?: string
	tagline?: string
	kicker?: string
	theme?: ThemeName
}

const W = 1200
const H = 630
const TEXT_LEFT = 636
const TEXT_TOP = 84
const TEXT_WIDTH = 540
const TEXT_BOTTOM = 548

// Marker colors so the rasterizer can find the title and chip and add their
// chunky drop shadows (Satori's own shadows become filters we cannot draw).
const TITLE_MARK = '#fff4e3'
const CHIP_MARK = '#fff4e5'

function bytes(b64: string) {
	const bin = atob(b64)
	const out = new Uint8Array(bin.length)
	for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
	return out
}

let fonts: Array<{ name: string; data: ArrayBuffer; weight: 600 | 700 | 800; style: 'normal' }> | null = null
function loadFonts() {
	fonts ??= [
		{ name: 'Fredoka', data: bytes(FREDOKA_600).buffer as ArrayBuffer, weight: 600, style: 'normal' },
		{ name: 'Fredoka', data: bytes(FREDOKA_700).buffer as ArrayBuffer, weight: 700, style: 'normal' },
		{ name: 'Nunito', data: bytes(NUNITO_800).buffer as ArrayBuffer, weight: 800, style: 'normal' },
	]
	return fonts
}

let background: Promise<Image> | null = null
function loadBackground() {
	background ??= decodePng(bytes(OG_BG_PNG_BASE64)).catch((error) => {
		background = null
		throw error
	})
	return background
}

/** Keep only characters the subset fonts can draw (Latin), so no tofu boxes. */
export function ogText(value: string | undefined, max: number) {
	return String(value ?? '')
		.replace(/[^\u0020-\u007e\u00a0-\u00ff\u2013\u2014\u2018-\u201d\u2022\u2026]/g, ' ')
		.replace(/\s+/g, ' ')
		.trim()
		.slice(0, max)
}

function titleSize(title: string) {
	const n = title.length
	if (n <= 10) return 126
	if (n <= 16) return 104
	if (n <= 24) return 86
	if (n <= 36) return 70
	return 58
}

type El = { type: string; props: { style?: Record<string, unknown>; children?: unknown } }
const el = (type: string, style: Record<string, unknown>, children?: unknown): El => ({ type, props: { style, children } })

async function layout(input: OgInput, size: number, withTagline: boolean) {
	const theme = THEMES[input.theme ?? 'harvest'] ?? THEMES.harvest
	const title = ogText(input.title, 60) || 'Pie Night'
	const when = [ogText(input.day, 40), ogText(input.time, 12)].filter(Boolean)
	const place = ogText(input.place, 80)
	const tagline = ogText(input.tagline ?? "Let us know what pie you're bringing!", 80)
	const children: El[] = [
		el('div', { fontFamily: 'Nunito', fontWeight: 800, fontSize: 26, letterSpacing: 5.5, color: theme.ogKicker, marginLeft: 6, marginBottom: 6 }, ogText(input.kicker ?? "You're invited", 40).toUpperCase()),
		el('div', { fontFamily: 'Fredoka', fontWeight: 700, fontSize: size, lineHeight: 0.95, maxWidth: title.length <= 10 ? 440 : TEXT_WIDTH, color: TITLE_MARK }, title),
	]
	if (when.length) {
		const parts: unknown[] = [when[0]]
		if (when[1]) parts.push(el('span', { color: theme.ogDot, marginLeft: 14, marginRight: 14 }, '·'), when[1])
		children.push(el('div', { display: 'flex', alignSelf: 'flex-start', alignItems: 'center', marginTop: 26, background: CHIP_MARK, color: theme.ogChipText, fontFamily: 'Fredoka', fontWeight: 600, fontSize: when.join(' · ').length > 28 ? 29 : 40, padding: '8px 28px', borderRadius: 999 }, parts))
	}
	if (place) children.push(el('div', { fontFamily: 'Nunito', fontWeight: 800, fontSize: 29, color: '#fff4e4', marginTop: 22, marginLeft: 6 }, place))
	if (withTagline && tagline) children.push(el('div', { fontFamily: 'Nunito', fontWeight: 800, fontSize: 27, color: '#ffe2b8', marginTop: 14, marginLeft: 6 }, tagline))
	const root = el('div', { display: 'flex', width: W, height: H, position: 'relative' }, [
		el('div', { display: 'flex', flexDirection: 'column', position: 'absolute', left: TEXT_LEFT, top: TEXT_TOP, width: TEXT_WIDTH }, children),
	])
	return satori(root as never, { width: W, height: H, fonts: loadFonts() })
}

function bottomOf(svg: string) {
	let max = 0
	for (const shape of svgShapes(svg)) for (const poly of shape.polys) for (const p of poly) if (p[1] > max) max = p[1]
	return max
}

const cache = new Map<string, Promise<Uint8Array>>()

/** Render (or reuse) the PNG for one event version. */
export function renderOgPng(key: string, input: OgInput): Promise<Uint8Array> {
	const hit = cache.get(key)
	if (hit) return hit
	const job = draw(input)
	cache.set(key, job)
	job.catch(() => cache.delete(key))
	if (cache.size > 40) cache.delete(cache.keys().next().value!)
	return job
}

async function draw(input: OgInput): Promise<Uint8Array> {
	const theme = THEMES[input.theme ?? 'harvest'] ?? THEMES.harvest
	const title = ogText(input.title, 60) || 'Pie Night'
	let size = titleSize(title)
	let svg = await layout(input, size, true)
	for (let tries = 0; tries < 6 && bottomOf(svg) > TEXT_BOTTOM; tries++) {
		svg = await layout(input, size, false)
		if (bottomOf(svg) <= TEXT_BOTTOM) break
		size = Math.round(size * 0.85)
		svg = await layout(input, size, true)
	}
	const bg = await loadBackground()
	const img: Image = { width: bg.width, height: bg.height, data: new Uint8Array(bg.data) }
	const shadow = hex(theme.ogShadow)
	for (const shape of svgShapes(svg)) {
		const mark = rgbHex(shape)
		if (mark === TITLE_MARK) {
			fillShape(img, shape, 0, 10, { ...hex('#000000'), a: 0.18 })
			fillShape(img, shape, 0, 6, { ...shadow, a: 1 })
			fillShape(img, shape, 0, 0, { ...hex('#fff4e4'), a: 1 })
		} else if (mark === CHIP_MARK) {
			fillShape(img, shape, 0, 14, { ...hex('#000000'), a: 0.16 })
			fillShape(img, shape, 0, 7, { ...shadow, a: 1 })
			fillShape(img, shape, 0, 0, { ...hex('#fff4e4'), a: 1 })
		} else fillShape(img, shape)
	}
	return encodePng(img)
}

function hex(value: string) {
	const n = (i: number) => parseInt(value.slice(i, i + 2), 16)
	return { r: n(1), g: n(3), b: n(5), a: 1 }
}

function rgbHex(c: { r: number; g: number; b: number }) {
	return '#' + [c.r, c.g, c.b].map((v) => Math.round(v).toString(16).padStart(2, '0')).join('')
}