import { THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS, type Theme } from './themes' // --- Types matching the API `format=data` response --- export type GradeData = { grade: string; score: number stats: Record tags: { tag: string; source: string; confidence: number; label?: string | null }[] breakdown: Record } export type ImpactWeek = { week_start: string; commits: number } export type CollaboratorData = { username: string; shared_repos: number; shared_commits: number } export type FocusCategory = { category: string; percentage: number; commit_count: number } export type LanguageData = { language: string; percentage: number; loc: number } export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string } export type StreakData = { current: number; max: number current_start?: string; last_active_date?: string max_start?: string; max_end?: string } export type WidgetData = { grade?: GradeData impact?: ImpactWeek[] collaborators?: CollaboratorData[] focus?: FocusCategory[] languages?: LanguageData[] streaks?: StreakData } export type PerWidgetSettings = { grade?: { max_tags?: number } impact?: { line_color?: string } streaks?: { color?: string } collaborators?: { max_count?: number; bar_color?: string } focus?: { max_categories?: number } languages?: { max_languages?: number } achievements?: { max_items?: number } } // --- Helpers --- const esc = (s: string) => s.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"') const font = '-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif' const TAG_ACRONYMS = new Set(['ml','ai','ui','ux','api','cli','sql','css','html','js','ios']) function formatTagLabel(tag: string): string { return tag.split('-') .map(w => TAG_ACRONYMS.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1)) .join(' ') } function cardWrapper(inner: string, w: number, h: number, t: Theme, title: string, prefix = '') { const sid = `${prefix}shadow` return ` ${title ? `${esc(title.toUpperCase())}` : ''} ${inner} ` } function iconSvg(kind: string, color: string): string { const icons: Record = { commits: ``, prs: ``, stars: ``, repos: ``, followers: ``, } return `${icons[kind] ?? ''}` } // --- Widget renderers --- function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): string { const tags = s?.max_tags ? data.tags.slice(0, s.max_tags) : data.tags const base = data.grade[0] const color = GRADE_COLORS[base] ?? t.accent const radius = 36 const circ = 2 * Math.PI * radius const offset = circ * (1 - data.score / 100) const gf = data.grade.length <= 2 ? 30 : 22 const statLabels: Record = { commits:'Commits', prs:'PRs', stars:'Stars', repos:'Repos', followers:'Followers' } const statKeys = ['commits','prs','stars','repos','followers'].filter(k => k in data.stats) const sw = 340 / Math.max(statKeys.length, 1) let statsSvg = '' for (let i = 0; i < statKeys.length; i++) { const k = statKeys[i], v = data.stats[k] const sx = i * sw + sw / 2 const vs = v < 100000 ? v.toLocaleString() : `${Math.round(v/1000)}k` statsSvg += `${iconSvg(k, t.text_secondary)}${vs}${statLabels[k]??k}` } let tagsSvg = '', tx = 0, ty = 0 for (const tag of tags) { const tc = TAG_COLORS[tag.tag] ?? t.accent const label = tag.label || formatTagLabel(tag.tag) const tw = Math.round(label.length * 6.6 + 18) const po = tag.source === 'earned' ? 0.9 : 0.55 if (tx + tw > 340) { tx = 0; ty += 30 } tagsSvg += `${esc(label)}` tx += tw + 6 } const tagsH = tags.length ? ty + 24 : 0 const statsY = 100, tagsY = statsY + 54 const tagPad = tagsH > 24 ? 18 : 14 const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54 const breakdownLabels: Record = { commits: 'Commits', consistency: 'Consistency', repos: 'Repos', stars: 'Stars', forks: 'Forks', activity: 'Activity', followers: 'Followers', } const topStrengths = Object.entries(data.breakdown || {}) .sort((a, b) => b[1] - a[1]) .slice(0, 2) .map(([k]) => breakdownLabels[k] ?? k.charAt(0).toUpperCase() + k.slice(1)) const strengthsLine = topStrengths.length ? `Strong in ${topStrengths.join(' · ')}` : '' let inner = `${esc(data.grade)} Developer Profile${esc(strengthsLine)}Score ${data.score.toFixed(0)} / 100 ${statsSvg}` if (tags.length) { inner += `${tagsSvg}` } return cardWrapper(inner, 380, cardH, t, '') } function renderImpact(weeks: ImpactWeek[], t: Theme, s?: { line_color?: string }): string { const w = 380, h = 200, cx = 40, cy = 8, cw = 316, ch = 82 const lineColor = s?.line_color ?? t.accent if (!weeks.length) { const inner = ` No contribution data yet 0commits over 6mo` return cardWrapper(inner, w, h, t, 'Impact Timeline') } const maxC = Math.max(...weeks.map(w => w.commits), 1) const n = weeks.length const pts = weeks.map((wk, i) => ({ x: cx + (i / Math.max(n-1, 1)) * cw, y: cy + ch - (wk.commits / maxC) * ch, })) let pathD = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}` for (let i = 1; i < pts.length; i++) { const mx = (pts[i-1].x + pts[i].x) / 2 pathD += ` C ${mx.toFixed(1)} ${pts[i-1].y.toFixed(1)}, ${mx.toFixed(1)} ${pts[i].y.toFixed(1)}, ${pts[i].x.toFixed(1)} ${pts[i].y.toFixed(1)}` } const areaD = pathD + ` L ${pts[n-1].x.toFixed(1)} ${cy+ch} L ${pts[0].x.toFixed(1)} ${cy+ch} Z` let yLabels = '' for (let i = 0; i < 3; i++) { const v = Math.round(maxC * (1 - i/2)) const yy = cy + (i/2) * ch yLabels += `${v}` } let xLabels = '' const li = n > 2 ? [0, Math.floor(n/2), n-1] : Array.from({length: n}, (_, i) => i) for (const idx of li) { if (idx < weeks.length) { const px = cx + (idx / Math.max(n-1,1)) * cw xLabels += `${weeks[idx].week_start.slice(0,7)}` } } const total = weeks.reduce((a, w) => a + w.commits, 0) const sy = cy + ch + 46 const inner = ` ${yLabels}${xLabels} ${total.toLocaleString()}commits over 6mo` return cardWrapper(inner, w, h, t, 'Impact Timeline') } function renderCollaborators(collabs: CollaboratorData[], t: Theme, s?: { max_count?: number; bar_color?: string }): string { const maxCount = Math.min(Math.max(s?.max_count ?? 5, 1), 10) const barColor = s?.bar_color ?? t.purple const shown = collabs.slice(0, maxCount) const barMax = Math.max(...shown.map(c => c.shared_commits), 1) let items = '' for (let i = 0; i < shown.length; i++) { const c = shown[i], y = i * 50 const hue = [...c.username].reduce((h, ch) => h + ch.charCodeAt(0), 0) % 360 const avatar = `${esc(c.username[0].toUpperCase())}` const bw = (c.shared_commits / barMax * 120).toFixed(1) items += `${avatar}${esc(c.username)}${c.shared_repos} repos · ${c.shared_commits} commits` } return cardWrapper(items, 380, shown.length * 50 + 48, t, 'Top Collaborators') } function renderFocus(cats: FocusCategory[], t: Theme, s?: { max_categories?: number }): string { const maxCats = Math.min(Math.max(s?.max_categories ?? 6, 1), 10) const sorted = [...cats].sort((a, b) => b.percentage - a.percentage).slice(0, maxCats) if (!sorted.length) return '' const maxPct = Math.max(sorted[0].percentage, 1) const barMaxW = 210 let items = '' for (let i = 0; i < sorted.length; i++) { const cat = sorted[i], y = i * 36 const color = FOCUS_COLORS[i % FOCUS_COLORS.length] const bw = (cat.percentage / maxPct * barMaxW).toFixed(1) items += `${esc(cat.category)}${cat.commit_count} commits${Math.round(cat.percentage)}%` } const subY = sorted.length * 36 + 8 items += `Recent activity · last year` return cardWrapper(items, 380, sorted.length * 36 + 54, t, 'Recent Focus') } function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_languages?: number }): string { const maxLangs = Math.min(Math.max(s?.max_languages ?? 5, 1), 10) const topLangs = [...languages].sort((a, b) => b.percentage - a.percentage).slice(0, maxLangs) if (!topLangs.length) return '' const totalPct = topLangs.reduce((a, l) => a + l.percentage, 0) const langs = [...topLangs] if (totalPct < 99.9 && languages.length > maxLangs) { langs.push({ language: 'Other', percentage: Math.round((100 - totalPct) * 10) / 10, loc: 0 }) } else if (totalPct < 99.9 && totalPct > 0) { const f = 100 / totalPct for (const l of langs) l.percentage = Math.round(l.percentage * f * 10) / 10 } const legendStart = 20, legendH = langs.length * 22 const ccy = legendStart + legendH / 2, ccx = 60, r = 44, innerR = 28 const circ = 2 * Math.PI * r let arcs = '', legend = '', offset = 0 for (let i = 0; i < langs.length; i++) { const lang = langs[i] const color = lang.language === 'Other' ? t.text_secondary : (LANG_COLORS[lang.language] ?? FOCUS_COLORS[i % FOCUS_COLORS.length]) const dash = circ * lang.percentage / 100 const gap = circ - dash arcs += `` offset += dash const ly = i * 22 legend += `${esc(lang.language)}${Math.round(lang.percentage)}%` } const center = `${esc(langs[0].language)}` const inner = `${arcs}${center}${legend}` const rowsH = Math.max(langs.length * 22 + 40, 120) return cardWrapper(inner, 380, rowsH + 36, t, 'Languages') } const STREAK_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] const STREAK_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/ function streaksSafeColor(value: string | undefined, fallback: string): string { if (typeof value !== 'string' || value.length > 32) return fallback return STREAK_COLOR_RE.test(value) ? value : fallback } function streakParseDate(iso?: string): { y: number; m: number; d: number } | null { if (!iso) return null const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso) if (!m) return null const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]) if (!y || mo < 1 || mo > 12 || d < 1 || d > 31) return null return { y, m: mo, d } } function streakFmtDay(dt: { y: number; m: number; d: number }, includeYear: boolean): string { return includeYear ? `${STREAK_MONTHS[dt.m-1]} ${dt.d}, ${dt.y}` : `${STREAK_MONTHS[dt.m-1]} ${dt.d}` } function fmtStreakCurrent(startIso?: string, todayIso?: string): string { const s = streakParseDate(startIso); if (!s) return '' const t = streakParseDate(todayIso) ?? { y: new Date().getFullYear(), m: 1, d: 1 } return `${streakFmtDay(s, s.y !== t.y)} – Today` } function fmtStreakLongest(startIso?: string, endIso?: string): string { const s = streakParseDate(startIso), e = streakParseDate(endIso) if (s && e) { if (s.y === e.y) return `${streakFmtDay(s, false)} – ${streakFmtDay(e, true)}` return `${streakFmtDay(s, true)} – ${streakFmtDay(e, true)}` } if (e) return streakFmtDay(e, true) if (s) return streakFmtDay(s, true) return '' } function renderStreaks(data: StreakData, t: Theme, s?: { color?: string }): string { const width = 380, height = 170 const currentColor = streaksSafeColor(s?.color, t.accent) const maxColor = t.text const leftX = 105, rightX = 275, dividerX = 190 const barX = 50, barW = 280 const fraction = data.max > 0 ? Math.max(0, Math.min(1, data.current / data.max)) : 0 const fillW = +(barW * fraction).toFixed(2) const currentCaption = data.current > 0 ? fmtStreakCurrent(data.current_start, data.last_active_date) : '' const longestCaption = fmtStreakLongest(data.max_start, data.max_end) const endDot = fillW > 0 ? `` : '' const inner = ` CURRENT ${data.current} LONGEST ${data.max} ${endDot} ${esc(currentCaption)} ${esc(longestCaption)}` return cardWrapper(inner, width, height, t, 'Streaks') } function achievementIconSvg(iconType: string, color: string): string { // Mirrors generator/src/widgets/achievements.py::_achievement_icon_svg so // the Workshop client preview matches the backend-rendered composite. const icons: Record = { trophy: ``, medal: ``, star: ``, hackathon: ``, } return icons[iconType] ?? icons.trophy } function renderAchievements(achievements: AchievementInput[], t: Theme, s?: { max_items?: number }): string { const maxItems = Math.min(Math.max(s?.max_items ?? 5, 1), 10) const shown = achievements.filter(a => a.title.trim()).slice(0, maxItems) if (!shown.length) return '' const accentColors = [t.orange, t.green, t.accent, t.purple, t.pink] let items = '' for (let i = 0; i < shown.length; i++) { const ach = shown[i], y = i * 56 const color = accentColors[i % accentColors.length] const icon = achievementIconSvg(ach.icon, color) items += `${icon}${esc(ach.title)}${esc(ach.subtitle)}${ach.event_date ? ' · ' + ach.event_date : ''}` } return cardWrapper(items, 380, shown.length * 56 + 50, t, 'Achievements') } // --- Composite --- function extractInner(svg: string, key: string): { inner: string; h: number } { const hm = svg.match(/height="(\d+)"/) const h = hm ? parseInt(hm[1]) : 160 // Prefix IDs const ids = [...svg.matchAll(/id="([^"]+)"/g)].map(m => m[1]) let inner = svg for (const id of ids) { const nid = `${key}_${id}` inner = inner.replaceAll(`id="${id}"`, `id="${nid}"`) inner = inner.replaceAll(`url(#${id})`, `url(#${nid})`) inner = inner.replaceAll(`href="#${id}"`, `href="#${nid}"`) } inner = inner.replace(/]*>/, '').replace(/<\/svg>\s*$/, '') return { inner, h } } // --- Main export --- export function renderAllWidgets(opts: { data: WidgetData theme: string widgets: string[] widgetOrder: string[] achievements: AchievementInput[] widgetSettings: PerWidgetSettings hiddenLanguages?: string[] username: string }): string { const t = THEMES[opts.theme] ?? THEMES.dark const enabled = new Set(opts.widgets) const widgetSvgs: Record = {} if (enabled.has('grade') && opts.data.grade) widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade) if (enabled.has('impact') && opts.data.impact) widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact) if (enabled.has('streaks') && opts.data.streaks) widgetSvgs.streaks = renderStreaks(opts.data.streaks, t, opts.widgetSettings.streaks) if (enabled.has('collaborators') && opts.data.collaborators) widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators) if (enabled.has('focus') && opts.data.focus) widgetSvgs.focus = renderFocus(opts.data.focus, t, opts.widgetSettings.focus) if (enabled.has('languages') && opts.data.languages) { // Apply hidden_languages client-side too so the Workshop preview reflects // the user's choice instantly — backend filtering only kicks in on the // next prefetch or on POST /generate. const hiddenSet = new Set(opts.hiddenLanguages ?? []) const filtered = opts.data.languages.filter(l => !hiddenSet.has(l.language)) const total = filtered.reduce((a, l) => a + l.percentage, 0) || 1 const rescaled = filtered.map(l => ({ ...l, percentage: Math.round(l.percentage / total * 1000) / 10 })) widgetSvgs.languages = renderLanguages(rescaled, t, opts.widgetSettings.languages) } if (enabled.has('achievements')) widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements) // Compose const totalW = 420, headerH = 60, padding = 20, gap = 16 const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k]) const parts = ordered.map(key => { const { inner, h } = extractInner(widgetSvgs[key], key) return { key, inner, h } }) const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0) const totalH = headerH + contentH + padding * 2 + 10 const avatar = `` const header = `${avatar}${esc(opts.username || 'Developer')}` let yOffset = headerH + padding let embedded = '' for (const { inner, h } of parts) { embedded += `${inner}` yOffset += h + gap } return ` ${header}${embedded} Generated with gh-stats ` }