import { Verdana110 as calcWidth } from './calc-text-width' import colorPresets from './color-presets' type StyleOption = 'flat' | 'classic' interface BadgenOptions { status: string; subject?: string; color?: string; label?: string; labelColor?: string style?: StyleOption; icon?: string; iconWidth?: number; scale?: number } export function badgen ({ label, subject, status, color = 'blue', style, icon, iconWidth = 13, labelColor = '555', scale = 1 }: BadgenOptions) { typeAssert(typeof status === 'string', ' must be string') label = label === undefined ? subject : label // subject is deprecated if (!label && !icon) { return bare({ status, color, style }) } color = colorPresets[color] || color labelColor = colorPresets[labelColor] || labelColor iconWidth = iconWidth * 10 const iconSpanWidth = icon ? (label.length ? iconWidth + 30 : iconWidth - 18) : 0 const sbTextStart = icon ? (iconSpanWidth + 50) : 50 const sbTextWidth = calcWidth(label) const stTextWidth = calcWidth(status) const sbRectWidth = sbTextWidth + 100 + iconSpanWidth const stRectWidth = stTextWidth + 100 const width = sbRectWidth + stRectWidth const xlink = icon ? ' xmlns:xlink="http://www.w3.org/1999/xlink"' : '' label = sanitize(label) status = sanitize(status) if (style === 'flat') { return ` ${label} ${label} ${status} ${status} ${icon ? `` : ''} ` } return ` ${label} ${label} ${status} ${status} ${icon ? `` : ''} ` } function bare ({ status, color, style }) { typeAssert(typeof status === 'string', ' must be string') color = colorPresets[color] || color || colorPresets.blue const stTextWidth = calcWidth(status) const stRectWidth = stTextWidth + 115 status = sanitize(status) if (style === 'flat') { return ` ${status} ${status} ` } return ` ${status} ${status} ` } function sanitize (str: string): string { return str.replace(/\u0026/g, '&').replace(/\u003C/g, '<') } function typeAssert (assertion: boolean, message: string): void { if (!assertion) throw new TypeError(message) } declare global { interface Window { badgen: typeof badgen; } } if (typeof window === 'object') { window.badgen = badgen }