"""Composite widget builder for combining multiple widgets.""" import re 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 and tags to get just the content inner = re.sub(r']*>', '', inner, count=1) inner = re.sub(r'\s*$', '', inner) return inner, h def compose_widget( widgets: dict[str, str], enabled: list[str], theme_name: str = "dark", username: str = "", avatar_b64: str = "", ) -> str: """ Takes rendered SVG strings for each widget type and composes them into a single unified profile widget by inlining widget SVGs directly. """ t = THEMES[theme_name] total_w = 420 header_h = 60 padding = 20 gap = 16 # Extract inner content from each widget SVG parts = [] for key in enabled: if key in widgets and widgets[key]: 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 # Header avatar_svg = "" if avatar_b64: avatar_svg = f''' ''' else: avatar_svg = f'' header = f''' {avatar_svg} {escape(username or "Developer")} ''' # Inline widgets using sub-documents positioned with x/y y_offset = header_h + padding embedded = "" for key, inner, h in parts: embedded += f''' {inner} ''' y_offset += h + gap return f''' {header} {embedded} Generated with gh-stats '''