mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(widgets): add settings parameter to multiple widget render functions
This commit is contained in:
@@ -494,6 +494,7 @@ def generate_widgets_from_github(
|
||||
custom_tags: list[str] = None,
|
||||
hidden_languages: list[str] = None,
|
||||
enabled: list[str] = None,
|
||||
widget_settings: dict[str, dict] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
Takes raw GitHub API data and returns rendered SVG strings
|
||||
@@ -506,33 +507,36 @@ def generate_widgets_from_github(
|
||||
hidden_languages: Optional list of languages to exclude from stats
|
||||
enabled: Optional list of widget keys to generate; others are skipped.
|
||||
Defaults to ENABLED_WIDGETS from config.
|
||||
widget_settings: Optional per-widget settings dict, keyed by widget name.
|
||||
Each value is a dict of settings for that widget's renderer.
|
||||
"""
|
||||
from ..config import ENABLED_WIDGETS
|
||||
|
||||
if enabled is None:
|
||||
enabled = ENABLED_WIDGETS
|
||||
enabled_set = set(enabled)
|
||||
ws = widget_settings or {}
|
||||
|
||||
widgets: dict[str, str] = {}
|
||||
|
||||
if "grade" in enabled_set:
|
||||
grade = compute_grade(github_data, custom_tags=custom_tags)
|
||||
widgets["grade"] = render_grade_widget(grade, theme)
|
||||
widgets["grade"] = render_grade_widget(grade, theme, settings=ws.get("grade"))
|
||||
|
||||
if "impact" in enabled_set:
|
||||
impact = compute_impact_timeline(github_data)
|
||||
widgets["impact"] = render_impact_widget(impact, theme)
|
||||
widgets["impact"] = render_impact_widget(impact, theme, settings=ws.get("impact"))
|
||||
|
||||
if "collaborators" in enabled_set:
|
||||
collabs = compute_collaborators(github_data)
|
||||
widgets["collaborators"] = render_collaborators_widget(collabs, theme)
|
||||
widgets["collaborators"] = render_collaborators_widget(collabs, theme, settings=ws.get("collaborators"))
|
||||
|
||||
if "focus" in enabled_set:
|
||||
focus = compute_focus(github_data, hidden_languages=hidden_languages)
|
||||
widgets["focus"] = render_focus_widget(focus, theme, period="1y")
|
||||
widgets["focus"] = render_focus_widget(focus, theme, period="1y", settings=ws.get("focus"))
|
||||
|
||||
if "languages" in enabled_set:
|
||||
languages = compute_languages(github_data, hidden_languages=hidden_languages)
|
||||
widgets["languages"] = render_languages_widget(languages, theme)
|
||||
widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages"))
|
||||
|
||||
return widgets
|
||||
|
||||
@@ -60,6 +60,7 @@ def generate():
|
||||
custom_tags = body.get("custom_tags")
|
||||
hidden_languages = body.get("hidden_languages")
|
||||
achievements_raw = body.get("achievements") or []
|
||||
widget_settings = body.get("widget_settings") or {}
|
||||
fmt = body.get("format", "svg")
|
||||
|
||||
github_data, used_dummy = _load_with_fallback(username)
|
||||
@@ -70,6 +71,7 @@ def generate():
|
||||
custom_tags=custom_tags,
|
||||
hidden_languages=hidden_languages,
|
||||
enabled=enabled,
|
||||
widget_settings=widget_settings,
|
||||
)
|
||||
|
||||
# Render achievements if provided and enabled
|
||||
@@ -85,7 +87,7 @@ def generate():
|
||||
if a.get("title")
|
||||
]
|
||||
if achs:
|
||||
widgets["achievements"] = render_achievements_widget(achs, theme)
|
||||
widgets["achievements"] = render_achievements_widget(achs, theme, settings=widget_settings.get("achievements"))
|
||||
|
||||
ordered = [w for w in widget_order if w in enabled and w in widgets and widgets[w]]
|
||||
display_name = username if not used_dummy else username
|
||||
|
||||
@@ -6,17 +6,24 @@ def escape(text: str) -> str:
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
||||
|
||||
|
||||
def card_wrapper(inner_svg: str, width: int, height: int, theme: dict, title: str = "") -> str:
|
||||
"""Wraps content in a styled card with rounded corners and border."""
|
||||
def card_wrapper(inner_svg: str, width: int, height: int, theme: dict, title: str = "", id_prefix: str = "") -> str:
|
||||
"""Wraps content in a styled card with rounded corners and border.
|
||||
|
||||
Args:
|
||||
id_prefix: Optional prefix for SVG IDs to avoid conflicts when
|
||||
multiple widgets are inlined in the same document.
|
||||
"""
|
||||
shadow_id = f"{id_prefix}shadow" if id_prefix else "shadow"
|
||||
clip_id = f"{id_prefix}avatarClip" if id_prefix else "avatarClip"
|
||||
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" fill="none">
|
||||
<defs>
|
||||
<filter id="shadow" x="-2%" y="-2%" width="104%" height="104%">
|
||||
<filter id="{shadow_id}" x="-2%" y="-2%" width="104%" height="104%">
|
||||
<feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#000" flood-opacity="0.15"/>
|
||||
</filter>
|
||||
<clipPath id="avatarClip"><circle cx="0" cy="0" r="18"/></clipPath>
|
||||
<clipPath id="{clip_id}"><circle cx="0" cy="0" r="18"/></clipPath>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="{width-2}" height="{height-2}" rx="10" ry="10"
|
||||
fill="{theme["card_bg"]}" stroke="{theme["card_border"]}" stroke-width="1" filter="url(#shadow)"/>
|
||||
fill="{theme["card_bg"]}" stroke="{theme["card_border"]}" stroke-width="1" filter="url(#{shadow_id})"/>
|
||||
{f'<text x="20" y="30" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Noto Sans,Helvetica,Arial,sans-serif" font-size="11" font-weight="600" fill="{theme["text_secondary"]}" letter-spacing="0.8" opacity="0.7">{escape(title.upper())}</text>' if title else ''}
|
||||
<g transform="translate(0, {36 if title else 0})">
|
||||
{inner_svg}
|
||||
|
||||
@@ -32,10 +32,17 @@ def _achievement_icon_svg(icon_type: str, color: str) -> str:
|
||||
def render_achievements_widget(
|
||||
achievements: list[AchievementData],
|
||||
theme_name: str = "dark",
|
||||
max_items: int = 5
|
||||
max_items: int = 5,
|
||||
settings: dict | None = None,
|
||||
) -> str:
|
||||
"""Renders the achievements widget with icons and descriptions."""
|
||||
"""Renders the achievements widget with icons and descriptions.
|
||||
|
||||
Settings:
|
||||
max_items (int): Max achievements to show (default 5)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_items = min(max(int(s.get("max_items", max_items)), 1), 10)
|
||||
items = ""
|
||||
accent_colors = [t["orange"], t["green"], t["accent"], t["purple"], t["pink"]]
|
||||
|
||||
|
||||
@@ -5,12 +5,20 @@ from ..themes import THEMES
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark") -> str:
|
||||
"""Renders the top collaborators widget with avatars and contribution bars."""
|
||||
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the top collaborators widget with avatars and contribution bars.
|
||||
|
||||
Settings:
|
||||
max_count (int): Number of collaborators to show (default 5)
|
||||
bar_color (str): Hex color for the contribution bars (default theme purple)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_count = min(max(int(s.get("max_count", 5)), 1), 10)
|
||||
bar_color = s.get("bar_color") or t["purple"]
|
||||
items = ""
|
||||
|
||||
for i, c in enumerate(collabs[:5]):
|
||||
for i, c in enumerate(collabs[:max_count]):
|
||||
y = i * 50
|
||||
avatar_el = ""
|
||||
|
||||
@@ -24,7 +32,7 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="14" font-weight="600" fill="white">{escape(c.username[0].upper())}</text>'''
|
||||
|
||||
bar_max = max((x.shared_commits for x in collabs[:5]), default=1) or 1
|
||||
bar_max = max((x.shared_commits for x in collabs[:max_count]), default=1) or 1
|
||||
bar_w = c.shared_commits / bar_max * 120
|
||||
|
||||
items += f'''
|
||||
@@ -35,10 +43,10 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
|
||||
<text x="28" y="14" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="10" fill="{t["text_secondary"]}">{c.shared_repos} repos · {c.shared_commits} commits</text>
|
||||
<rect x="200" y="-6" width="130" height="8" rx="4" fill="{t["grid"]}"/>
|
||||
<rect x="200" y="-6" width="{bar_w}" height="8" rx="4" fill="{t["purple"]}" opacity="0.8">
|
||||
<rect x="200" y="-6" width="{bar_w}" height="8" rx="4" fill="{bar_color}" opacity="0.8">
|
||||
<animate attributeName="width" from="0" to="{bar_w}" dur="0.6s" fill="freeze"/>
|
||||
</rect>
|
||||
</g>'''
|
||||
|
||||
total_h = len(collabs[:5]) * 50 + 48
|
||||
total_h = len(collabs[:max_count]) * 50 + 48
|
||||
return card_wrapper(items, 380, total_h, t, "Top Collaborators")
|
||||
|
||||
+38
-12
@@ -1,11 +1,39 @@
|
||||
"""Composite widget builder for combining multiple widgets."""
|
||||
|
||||
import re
|
||||
import base64
|
||||
from ..themes import THEMES
|
||||
from ..utils import escape
|
||||
|
||||
|
||||
def _extract_inner(svg: str, widget_key: str) -> tuple[str, int]:
|
||||
"""Extract the inner content from a widget SVG and rewrite IDs to be unique.
|
||||
|
||||
Returns (inner_svg_content, height).
|
||||
"""
|
||||
# Parse height
|
||||
hm = re.search(r'height="(\d+)"', svg)
|
||||
h = int(hm.group(1)) if hm else 160
|
||||
|
||||
# Rewrite IDs to avoid conflicts: shadow, avatarClip, areaGrad, etc.
|
||||
# Prefix all id="..." and url(#...) and href="#..." references
|
||||
prefix = f"{widget_key}_"
|
||||
|
||||
# Find all IDs in the SVG
|
||||
ids = re.findall(r'id="([^"]+)"', svg)
|
||||
inner = svg
|
||||
for old_id in ids:
|
||||
new_id = f"{prefix}{old_id}"
|
||||
inner = inner.replace(f'id="{old_id}"', f'id="{new_id}"')
|
||||
inner = inner.replace(f'url(#{old_id})', f'url(#{new_id})')
|
||||
inner = inner.replace(f'href="#{old_id}"', f'href="#{new_id}"')
|
||||
|
||||
# Strip the outer <svg> and </svg> tags to get just the content
|
||||
inner = re.sub(r'<svg[^>]*>', '', inner, count=1)
|
||||
inner = re.sub(r'</svg>\s*$', '', inner)
|
||||
|
||||
return inner, h
|
||||
|
||||
|
||||
def compose_widget(
|
||||
widgets: dict[str, str],
|
||||
enabled: list[str],
|
||||
@@ -15,7 +43,7 @@ def compose_widget(
|
||||
) -> str:
|
||||
"""
|
||||
Takes rendered SVG strings for each widget type and composes them
|
||||
into a single unified profile widget.
|
||||
into a single unified profile widget by inlining widget SVGs directly.
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
total_w = 420
|
||||
@@ -23,14 +51,12 @@ def compose_widget(
|
||||
padding = 20
|
||||
gap = 16
|
||||
|
||||
# Parse each widget's height from its SVG
|
||||
# Extract inner content from each widget SVG
|
||||
parts = []
|
||||
for key in enabled:
|
||||
if key in widgets and widgets[key]:
|
||||
svg = widgets[key]
|
||||
hm = re.search(r'height="(\d+)"', svg)
|
||||
h = int(hm.group(1)) if hm else 160
|
||||
parts.append((key, svg, h))
|
||||
inner, h = _extract_inner(widgets[key], key)
|
||||
parts.append((key, inner, h))
|
||||
|
||||
content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0)
|
||||
total_h = header_h + content_h + padding * 2 + 10
|
||||
@@ -51,14 +77,14 @@ def compose_widget(
|
||||
<line x1="{padding}" y1="{header_h}" x2="{total_w - padding}" y2="{header_h}"
|
||||
stroke="{t["card_border"]}" stroke-width="0.5"/>'''
|
||||
|
||||
# Stack widgets via base64 data URI embedding
|
||||
# Inline widgets using <svg> sub-documents positioned with x/y
|
||||
y_offset = header_h + padding
|
||||
embedded = ""
|
||||
for key, svg, h in parts:
|
||||
svg_b64 = base64.b64encode(svg.encode("utf-8")).decode("ascii")
|
||||
for key, inner, h in parts:
|
||||
embedded += f'''
|
||||
<image x="{padding}" y="{y_offset}" width="380" height="{h}"
|
||||
href="data:image/svg+xml;base64,{svg_b64}"/>'''
|
||||
<svg x="{padding}" y="{y_offset}" width="380" height="{h}" viewBox="0 0 380 {h}">
|
||||
{inner}
|
||||
</svg>'''
|
||||
y_offset += h + gap
|
||||
|
||||
return f'''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
|
||||
@@ -5,10 +5,16 @@ from ..themes import THEMES, FOCUS_COLORS
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark", period: str = "1y") -> str:
|
||||
"""Renders the focus areas widget with horizontal bars."""
|
||||
def render_focus_widget(categories: list[FocusCategory], theme_name: str = "dark", period: str = "1y", settings: dict | None = None) -> str:
|
||||
"""Renders the focus areas widget with horizontal bars.
|
||||
|
||||
Settings:
|
||||
max_categories (int): Max categories to show (default 6)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
cats = sorted(categories, key=lambda c: -c.percentage)[:6]
|
||||
s = settings or {}
|
||||
max_cats = min(max(int(s.get("max_categories", 6)), 1), 10)
|
||||
cats = sorted(categories, key=lambda c: -c.percentage)[:max_cats]
|
||||
if not cats:
|
||||
return ""
|
||||
|
||||
|
||||
+15
-2
@@ -6,9 +6,22 @@ from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
|
||||
from ..utils import escape, card_wrapper, icon_svg
|
||||
|
||||
|
||||
def render_grade_widget(data: GradeData, theme_name: str = "dark") -> str:
|
||||
"""Renders the developer grade widget with stats and tags."""
|
||||
def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the developer grade widget with stats and tags.
|
||||
|
||||
Settings:
|
||||
max_tags (int): Max tags to display (default all)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
max_tags = s.get("max_tags")
|
||||
if max_tags is not None:
|
||||
max_tags = min(max(int(max_tags), 1), 20)
|
||||
data = GradeData(
|
||||
grade=data.grade, score=data.score, stats=data.stats,
|
||||
tags=data.tags[:max_tags] if data.tags else [],
|
||||
breakdown=data.breakdown,
|
||||
)
|
||||
base = data.grade[0]
|
||||
color = GRADE_COLORS.get(base, t["accent"])
|
||||
score = data.score
|
||||
|
||||
+11
-5
@@ -5,9 +5,15 @@ from ..themes import THEMES
|
||||
from ..utils import card_wrapper
|
||||
|
||||
|
||||
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo") -> str:
|
||||
"""Renders the impact timeline chart widget."""
|
||||
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
|
||||
"""Renders the impact timeline chart widget.
|
||||
|
||||
Settings:
|
||||
line_color (str): Hex color for the chart line/area (default theme accent)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
line_color = s.get("line_color") or t["accent"]
|
||||
w, h = 380, 200
|
||||
chart_x, chart_y = 40, 8
|
||||
chart_w, chart_h = 316, 82
|
||||
@@ -71,14 +77,14 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
|
||||
inner = f'''
|
||||
<defs>
|
||||
<linearGradient id="areaGrad" x1="0" y1="{chart_y}" x2="0" y2="{chart_y + chart_h}" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="{t["accent"]}" stop-opacity="0.35"/>
|
||||
<stop offset="100%" stop-color="{t["accent"]}" stop-opacity="0.02"/>
|
||||
<stop offset="0%" stop-color="{line_color}" stop-opacity="0.35"/>
|
||||
<stop offset="100%" stop-color="{line_color}" stop-opacity="0.02"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
{y_labels}
|
||||
{x_labels}
|
||||
<path d="{area_d}" fill="url(#areaGrad)"/>
|
||||
<path d="{path_d}" fill="none" stroke="{t["accent"]}" stroke-width="2" stroke-linecap="round"/>
|
||||
<path d="{path_d}" fill="none" stroke="{line_color}" stroke-width="2" stroke-linecap="round"/>
|
||||
<g transform="translate(20, {summary_y})">
|
||||
<text x="0" y="0" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="13" font-weight="700" fill="{t["text"]}">{total:,}</text>
|
||||
|
||||
@@ -6,10 +6,16 @@ from ..themes import THEMES, LANG_COLORS, FOCUS_COLORS
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
def render_languages_widget(languages: list[LanguageData], theme_name: str = "dark") -> str:
|
||||
"""Renders the languages donut chart widget."""
|
||||
def render_languages_widget(languages: list[LanguageData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||
"""Renders the languages donut chart widget.
|
||||
|
||||
Settings:
|
||||
max_languages (int): Max languages to show (default 5)
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
top_langs = sorted(languages, key=lambda l: -l.percentage)[:5]
|
||||
s = settings or {}
|
||||
max_langs = min(max(int(s.get("max_languages", 5)), 1), 10)
|
||||
top_langs = sorted(languages, key=lambda l: -l.percentage)[:max_langs]
|
||||
if not top_langs:
|
||||
return ""
|
||||
|
||||
@@ -18,7 +24,7 @@ def render_languages_widget(languages: list[LanguageData], theme_name: str = "da
|
||||
langs = list(top_langs)
|
||||
|
||||
# Add "Other" category if there are remaining languages
|
||||
if total_percentage < 99.9 and len(languages) > 5:
|
||||
if total_percentage < 99.9 and len(languages) > max_langs:
|
||||
other_percentage = 100 - total_percentage
|
||||
from ..models import LanguageData
|
||||
langs.append(LanguageData(
|
||||
@@ -27,7 +33,7 @@ def render_languages_widget(languages: list[LanguageData], theme_name: str = "da
|
||||
loc=0
|
||||
))
|
||||
elif total_percentage < 99.9:
|
||||
# If we have <= 5 languages total but they don't sum to 100%,
|
||||
# If we have <= max_langs languages total but they don't sum to 100%,
|
||||
# adjust the percentages proportionally to sum to 100%
|
||||
if total_percentage > 0:
|
||||
factor = 100 / total_percentage
|
||||
|
||||
Reference in New Issue
Block a user