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 }[] 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 WidgetData = { grade?: GradeData impact?: ImpactWeek[] collaborators?: CollaboratorData[] focus?: FocusCategory[] languages?: LanguageData[] } export type PerWidgetSettings = { grade?: { max_tags?: number } impact?: { line_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' 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.tag.replace(/-/g,' ').replace(/\b\w/g, c => c.toUpperCase()) 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 let inner = `${esc(data.grade)}${data.score.toFixed(0)} / 100 Developer ProfileGrade ${esc(data.grade)} · ${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') } 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] items += `${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 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('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) widgetSvgs.languages = renderLanguages(opts.data.languages, 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 ♥ ` }