Skip to content
← Public packages

@kentcdodds/photo-portfolio

A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.

FollowFork

Files

markdown.ts

93 lines · 2.9 KB · TypeScript
/**
 * A small, safe Markdown renderer for the bio: paragraphs, `#`–`###` headings,
 * `-`/`1.` lists, **bold**, *italic*, and [links](https://…). Raw HTML is
 * always escaped, and links only allow http(s), mailto, tel, or relative URLs.
 */
export function renderMarkdown(source: string): string {
	const blocks = source
		.replace(/\r\n?/g, '\n')
		.trim()
		.split(/\n{2,}/)
	return blocks.map(renderBlock).filter(Boolean).join('\n')
}

function renderBlock(block: string): string {
	const lines = block.split('\n').map((line) => line.trimEnd())
	const heading = /^(#{1,3})\s+(.+)$/.exec(lines[0] ?? '')
	if (heading && lines.length === 1) {
		const level = heading[1]!.length + 1
		return `<h${level}>${renderInline(heading[2]!)}</h${level}>`
	}
	if (lines.every((line) => /^\s*[-*]\s+/.test(line))) {
		const items = lines.map(
			(line) => `<li>${renderInline(line.replace(/^\s*[-*]\s+/, ''))}</li>`,
		)
		return `<ul>${items.join('')}</ul>`
	}
	if (lines.every((line) => /^\s*\d+[.)]\s+/.test(line))) {
		const items = lines.map(
			(line) => `<li>${renderInline(line.replace(/^\s*\d+[.)]\s+/, ''))}</li>`,
		)
		return `<ol>${items.join('')}</ol>`
	}
	const text = lines.join('\n').trim()
	if (!text) return ''
	return `<p>${lines.map(renderInline).join('<br>')}</p>`
}

export function escapeHtml(value: string) {
	return value
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#39;')
}

function safeHref(raw: string): string | null {
	const href = raw.trim()
	if (/^(https?:|mailto:|tel:)/i.test(href)) return href
	if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return null
	if (href.startsWith('//')) return null
	return href
}

function renderInline(text: string): string {
	const tokens: Array<string> = []
	const stash = (html: string) => `\u0000${tokens.push(html) - 1}\u0000`
	let working = text.replace(
		/\[([^\]]+)\]\(([^)\s]+)\)/g,
		(match, label: string, href: string) => {
			const safe = safeHref(href)
			if (!safe) return match
			const external = /^https?:/i.test(safe)
			return stash(
				`<a href="${escapeHtml(safe)}"${external ? ' rel="noopener"' : ''}>${renderEmphasis(escapeHtml(label))}</a>`,
			)
		},
	)
	working = renderEmphasis(escapeHtml(working))
	return working.replace(
		/\u0000(\d+)\u0000/g,
		(_m, index: string) => tokens[Number(index)] ?? '',
	)
}

function renderEmphasis(escaped: string) {
	return escaped
		.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
		.replace(/(^|[^\w*])\*(?!\s)(.+?)\*(?!\w)/g, '$1<em>$2</em>')
		.replace(/(^|[^\w])_(?!\s)(.+?)_(?!\w)/g, '$1<em>$2</em>')
}

/** Plain-text excerpt (for meta descriptions and teasers). */
export function markdownToText(source: string, maxLength = 200) {
	const plain = source
		.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
		.replace(/[*_#>`]/g, '')
		.replace(/^\s*[-\d.)]+\s+/gm, '')
		.replace(/\s+/g, ' ')
		.trim()
	if (plain.length <= maxLength) return plain
	return `${plain.slice(0, maxLength - 1).replace(/\s+\S*$/, '')}…`
}