Files
summercms/admin/src/components/mail/insertImage.ts

36 lines
1.3 KiB
TypeScript

// Pure snippet builder for mail image insertion (UI-SPEC C4, D-19/D-20).
// The SPA never builds image URLs; callers pass the absolute URL the server returned.
export type InsertImageLanguage = 'markdown' | 'html' | 'css' | 'text'
function escapeMarkdownAlt(alt: string): string {
return alt.replace(/\\/g, '\\\\').replace(/\[/g, '\\[').replace(/\]/g, '\\]')
}
/** Percent-encode spaces and parentheses in Markdown URLs (research Pitfall 4). */
function encodeMarkdownUrl(url: string): string {
// encodeURIComponent leaves () alone; Markdown link destinations need them escaped.
return url.replace(/[ ()]/g, (ch) => (ch === ' ' ? '%20' : ch === '(' ? '%28' : '%29'))
}
function escapeHtmlAttr(value: string): string {
return value
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
/** Builds the snippet inserted into a mail body or code editor. */
export function insertImage(language: InsertImageLanguage, url: string, alt: string): string {
switch (language) {
case 'markdown':
return `![${escapeMarkdownAlt(alt)}](${encodeMarkdownUrl(url)})`
case 'html':
return `<img src="${escapeHtmlAttr(url)}" alt="${escapeHtmlAttr(alt)}">`
case 'css':
return `url("${url.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}")`
case 'text':
return url
}
}