feat(composite): add show_name parameter to control header visibility.

This commit is contained in:
shay
2026-04-20 15:04:09 -04:00
parent b66f966adb
commit 96dc98142f
7 changed files with 235 additions and 98 deletions
+40 -10
View File
@@ -7,6 +7,7 @@ import { AuthButton } from './components/AuthButton'
import type { WidgetData } from './lib/renderWidgets' import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData' import { DEMO_WIDGET_DATA } from './lib/demoData'
import { fetchMe, type Me } from './lib/auth' import { fetchMe, type Me } from './lib/auth'
import { buildEmbedUrl } from './lib/settingsQuery'
export type Achievement = { export type Achievement = {
title: string title: string
@@ -38,8 +39,8 @@ export type WidgetSettings = {
const DEFAULT_SETTINGS: WidgetSettings = { const DEFAULT_SETTINGS: WidgetSettings = {
theme: 'midnight', theme: 'midnight',
widgets: ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages'], widgets: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages'],
widgetOrder: ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'], widgetOrder: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'],
impactPeriod: '6mo', impactPeriod: '6mo',
customTags: [], customTags: [],
hiddenLanguages: [], hiddenLanguages: [],
@@ -65,6 +66,11 @@ export default function App() {
const [generatedSvg, setGeneratedSvg] = useState<string | null>(null) const [generatedSvg, setGeneratedSvg] = useState<string | null>(null)
const [generateError, setGenerateError] = useState<string | null>(null) const [generateError, setGenerateError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false) const [generating, setGenerating] = useState(false)
// The URL we actually fetched for the preview — also the one we show as
// the embed snippet. For owners this is /api/<u> (backed by stored
// settings). For visitors it's /api/<u>?<query>, which round-trips their
// Workshop edits without touching the owner's saved widget.
const [embedUrl, setEmbedUrl] = useState<string>('')
const pollTimer = useRef<number | null>(null) const pollTimer = useRef<number | null>(null)
const pollStart = useRef<number>(0) const pollStart = useRef<number>(0)
const aborted = useRef(false) const aborted = useRef(false)
@@ -185,12 +191,11 @@ export default function App() {
setGenerating(true) setGenerating(true)
setGeneratedSvg(null) setGeneratedSvg(null)
setGenerateError(null) setGenerateError(null)
const isOwner = !!me.login && me.login.toLowerCase() === username.toLowerCase()
try { try {
// Push the user's Workshop choices to the backend BEFORE rendering. if (isOwner) {
// The backend's /generate endpoint re-reads settings from SQLite and // Owner path: persist settings, then force a server-side render
// renders with them, so without this PATCH the SVG would reflect // against the stored payload. The resulting /api/<u> is the embed.
// whatever was last persisted (usually the enroll-time defaults)
// rather than the user's current selections.
const backendSettings = { const backendSettings = {
theme: settings.theme, theme: settings.theme,
enabled: settings.widgets, enabled: settings.widgets,
@@ -224,14 +229,38 @@ export default function App() {
setGenerateError(`Generate failed (HTTP ${r.status})`) setGenerateError(`Generate failed (HTTP ${r.status})`)
return return
} }
// Fetch the backend-rendered composite SVG. Cache-bust so regenerate const cleanUrl = `${window.location.origin}/api/${encodeURIComponent(username)}`
// after settings change shows the new version, not a stale browser copy. // Cache-bust so regenerate after settings change shows the new
const svgRes = await fetch(`/api/${encodeURIComponent(username)}?t=${Date.now()}`) // version, not a stale browser copy. The cache-busting `t` param
// is not read server-side (not in the allow-list) so the render
// stays cacheable at the edge.
const svgRes = await fetch(`${cleanUrl}?t=${Date.now()}`)
if (!svgRes.ok) { if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`) setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return return
} }
setGeneratedSvg(await svgRes.text()) setGeneratedSvg(await svgRes.text())
setEmbedUrl(cleanUrl)
} else {
// Visitor path: encode Workshop edits into a query string and hit
// the same URL we'll hand the user for their README. No owner
// settings are written. The backend renders ad-hoc against the
// fetcher's cached payload for this user.
const url = buildEmbedUrl(window.location.origin, username, settings)
// Same cache-bust trick — unknown query params are ignored by the
// sanitizer, so this doesn't alter the rendered output.
const svgRes = await fetch(`${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`)
if (svgRes.status === 404) {
setGenerateError('User not enrolled — ask them to sign in and generate first')
return
}
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
setEmbedUrl(url)
}
} catch (e) { } catch (e) {
console.warn('generate call failed:', e) console.warn('generate call failed:', e)
setGenerateError('Network error') setGenerateError('Network error')
@@ -277,6 +306,7 @@ export default function App() {
generating={generating} generating={generating}
generatedSvg={generatedSvg} generatedSvg={generatedSvg}
generateError={generateError} generateError={generateError}
embedUrl={embedUrl}
onBack={handleBack} onBack={handleBack}
onRegenerate={handleGenerate} onRegenerate={handleGenerate}
/> />
+19 -4
View File
@@ -426,8 +426,10 @@ export function renderAllWidgets(opts: {
widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements) widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements)
// Compose // Compose
const totalW = 420, headerH = 60, padding = 20, gap = 16 const showName = enabled.has('name')
const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k]) const totalW = 420, headerH = showName ? 60 : 0, padding = 20, gap = 16
// "name" is a pseudo-widget — it controls the header, not a rendered svg.
const ordered = opts.widgetOrder.filter(k => k !== 'name' && enabled.has(k) && widgetSvgs[k])
const parts = ordered.map(key => { const parts = ordered.map(key => {
const { inner, h } = extractInner(widgetSvgs[key], key) const { inner, h } = extractInner(widgetSvgs[key], key)
@@ -437,8 +439,21 @@ export function renderAllWidgets(opts: {
const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0) 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 totalH = headerH + contentH + padding * 2 + 10
const avatar = `<circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>` // Header (avatar + username). Only drawn when "name" is enabled. The
const header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>` // avatar pulls from github.com/<user>.png which redirects to
// avatars.githubusercontent.com; the accent circle underneath is a
// fallback for missing users / slow loads.
let header = ''
if (showName) {
const avatarUrl = opts.username
? `https://github.com/${encodeURIComponent(opts.username)}.png?size=64`
: ''
const avatarImg = avatarUrl
? `<image x="14" y="14" width="32" height="32" href="${esc(avatarUrl)}" clip-path="url(#mainAvatarClip)" preserveAspectRatio="xMidYMid slice"/>`
: ''
const avatar = `<defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs><circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>${avatarImg}`
header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>`
}
let yOffset = headerH + padding let yOffset = headerH + padding
let embedded = '' let embedded = ''
@@ -25,15 +25,21 @@ const SVG_SANITIZE_CONFIG = {
], ],
} }
// Mini-preview swatches (bg + card + accent). Flat-color swatches all read
// the same dark/light — showing the accent color is what actually separates
// Midnight (blue) from Onyx (purple) from Nord (cyan), etc.
const THEMES = [ const THEMES = [
{ id: 'midnight', label: 'Midnight', color: '#121820' }, { id: 'midnight', label: 'Midnight', bg: '#121820', card: '#1a2230', border: '#2a3444', accent: '#58a6ff', light: false },
{ id: 'onyx', label: 'Onyx', color: '#09090b' }, { id: 'onyx', label: 'Onyx', bg: '#09090b', card: '#18181b', border: '#27272a', accent: '#a78bfa', light: false },
{ id: 'nord', label: 'Nord', color: '#1e2433' }, { id: 'nord', label: 'Nord', bg: '#1e2433', card: '#2a3142', border: '#3d4659', accent: '#88c0d0', light: false },
{ id: 'clean', label: 'Clean', color: '#ffffff', border: true }, { id: 'clean', label: 'Clean', bg: '#ffffff', card: '#f6f8fa', border: '#d8dee4', accent: '#0969da', light: true },
{ id: 'paper', label: 'Paper', color: '#faf8f5', border: true }, { id: 'paper', label: 'Paper', bg: '#faf8f5', card: '#f5f0eb', border: '#e0d8cf', accent: '#b45309', light: true },
] ]
const ALL_WIDGETS = [ const ALL_WIDGETS = [
// "name" is the avatar + username header. Pinned at the top — can be
// toggled off but never reordered. Keep this entry first.
{ id: 'name', label: 'Name' },
{ id: 'grade', label: 'Grade' }, { id: 'grade', label: 'Grade' },
{ id: 'impact', label: 'Impact Timeline' }, { id: 'impact', label: 'Impact Timeline' },
{ id: 'streaks', label: 'Streaks' }, { id: 'streaks', label: 'Streaks' },
@@ -75,8 +81,12 @@ const ICONS: { id: string; svg: ReactNode }[] = [
id: 'medal', id: 'medal',
svg: ( svg: (
<svg {...ICON_SVG_PROPS}> <svg {...ICON_SVG_PROPS}>
<circle cx="12" cy="8" r="6" /> <path d="M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15" />
<path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526" /> <path d="M11 12 5.12 2.2" />
<path d="m13 12 5.88-9.8" />
<path d="M8 7h8" />
<circle cx="12" cy="17" r="5" />
<path d="M12 18v-2h-.5" />
</svg> </svg>
), ),
}, },
@@ -199,7 +209,7 @@ function ColorPicker({ value, onChange }: { value: string; onChange: (v: string)
key={c} key={c}
onClick={() => onChange(c)} onClick={() => onChange(c)}
className={`w-5 h-5 rounded-full transition-all ${ className={`w-5 h-5 rounded-full transition-all ${
value === c ? 'ring-2 ring-offset-1 ring-blue-500' : 'hover:ring-1 hover:ring-gray-300' value === c ? 'ring-2 ring-offset-1 ring-gray-900' : 'hover:ring-1 hover:ring-gray-300'
}`} }`}
style={{ backgroundColor: c }} style={{ backgroundColor: c }}
/> />
@@ -243,9 +253,13 @@ export function WorkshopScreen({
// the stored order forgot. Keeps the UI functional if ALL_WIDGETS // the stored order forgot. Keeps the UI functional if ALL_WIDGETS
// gains or loses an entry between releases. // gains or loses an entry between releases.
const knownIds = useMemo(() => new Set(ALL_WIDGETS.map(w => w.id)), []) const knownIds = useMemo(() => new Set(ALL_WIDGETS.map(w => w.id)), [])
// "name" is pinned at index 0 regardless of persisted order. We still keep
// it in orderedIds so the composite-render path can find it, but the drag
// UI below treats it as non-reorderable.
const orderedIds = useMemo(() => { const orderedIds = useMemo(() => {
const seen = new Set<string>() const seen = new Set<string>()
const out: string[] = [] const out: string[] = ['name']
seen.add('name')
for (const id of settings.widgetOrder) { for (const id of settings.widgetOrder) {
if (knownIds.has(id) && !seen.has(id)) { seen.add(id); out.push(id) } if (knownIds.has(id) && !seen.has(id)) { seen.add(id); out.push(id) }
} }
@@ -257,6 +271,8 @@ export function WorkshopScreen({
const moveWidget = (from: number, to: number) => { const moveWidget = (from: number, to: number) => {
if (from === to || from < 0 || to < 0 || from >= orderedIds.length || to >= orderedIds.length) return if (from === to || from < 0 || to < 0 || from >= orderedIds.length || to >= orderedIds.length) return
// Never move "name" and never drop another widget above it (index 0).
if (orderedIds[from] === 'name' || to === 0) return
const next = orderedIds.slice() const next = orderedIds.slice()
const [item] = next.splice(from, 1) const [item] = next.splice(from, 1)
next.splice(to, 0, item) next.splice(to, 0, item)
@@ -367,15 +383,23 @@ export function WorkshopScreen({
key={t.id} key={t.id}
onClick={() => updateSetting('theme', t.id)} onClick={() => updateSetting('theme', t.id)}
title={t.label} title={t.label}
className={`w-9 h-9 rounded-lg transition-all ${ aria-label={t.label}
className={`w-9 h-9 rounded-lg overflow-hidden transition-all ${
settings.theme === t.id settings.theme === t.id
? 'ring-2 ring-blue-500 ring-offset-2' ? 'ring-2 ring-gray-900 ring-offset-2'
: t.border : t.light
? 'border border-gray-200 hover:border-gray-300' ? 'ring-1 ring-gray-200 hover:ring-gray-300'
: 'hover:ring-1 hover:ring-gray-300 hover:ring-offset-1' : 'hover:ring-1 hover:ring-gray-400 hover:ring-offset-1'
}`} }`}
style={{ backgroundColor: t.color }} >
/> <svg viewBox="0 0 36 36" width="36" height="36">
<rect width="36" height="36" rx="8" fill={t.bg} />
<rect x="6" y="8" width="24" height="20" rx="4" fill={t.card} stroke={t.border} strokeWidth="1" />
<circle cx="11" cy="18" r="3" fill={t.accent} />
<rect x="16" y="16.25" width="10" height="1.75" rx="0.875" fill={t.accent} opacity="0.75" />
<rect x="16" y="19.75" width="7" height="1.5" rx="0.75" fill={t.accent} opacity="0.35" />
</svg>
</button>
))} ))}
</div> </div>
<div className="text-[10px] text-gray-400 mt-1.5"> <div className="text-[10px] text-gray-400 mt-1.5">
@@ -393,24 +417,28 @@ export function WorkshopScreen({
const enabled = settings.widgets.includes(w.id) const enabled = settings.widgets.includes(w.id)
const hasAdvanced = ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) const hasAdvanced = ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id)
const isExpanded = expandedWidget === w.id && enabled const isExpanded = expandedWidget === w.id && enabled
const isDragging = dragIndex === idx // "name" is pinned — no drag affordance, no drop lines.
const showDropLineAbove = dropIndex === idx && dragIndex !== null && dragIndex !== idx // The dropIndex comparisons below still use the real idx
// so downstream rows behave normally when name is skipped.
const isPinned = w.id === 'name'
const isDragging = !isPinned && dragIndex === idx
const showDropLineAbove = !isPinned && idx > 0 && dropIndex === idx && dragIndex !== null && dragIndex !== idx
// Drop-line below the last row when dragging past the end. // Drop-line below the last row when dragging past the end.
const showDropLineBelow = idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null const showDropLineBelow = !isPinned && idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null
return ( return (
<div key={w.id}> <div key={w.id}>
{showDropLineAbove && <div className="h-0.5 bg-blue-400 rounded-full mx-2 mb-0.5" />} {showDropLineAbove && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mb-0.5" />}
<div <div
className={`flex items-center transition-opacity ${isDragging ? 'opacity-40' : ''}`} className={`flex items-center transition-opacity ${isDragging ? 'opacity-40' : ''}`}
draggable draggable={!isPinned}
onDragStart={e => { onDragStart={isPinned ? undefined : e => {
setDragIndex(idx) setDragIndex(idx)
e.dataTransfer.effectAllowed = 'move' e.dataTransfer.effectAllowed = 'move'
// Firefox needs some payload to start a drag. // Firefox needs some payload to start a drag.
e.dataTransfer.setData('text/plain', String(idx)) e.dataTransfer.setData('text/plain', String(idx))
}} }}
onDragOver={e => { onDragOver={isPinned ? undefined : e => {
if (dragIndex === null) return if (dragIndex === null) return
e.preventDefault() e.preventDefault()
e.dataTransfer.dropEffect = 'move' e.dataTransfer.dropEffect = 'move'
@@ -427,7 +455,7 @@ export function WorkshopScreen({
setDropIndex(target) setDropIndex(target)
} }
}} }}
onDrop={e => { onDrop={isPinned ? undefined : e => {
e.preventDefault() e.preventDefault()
if (dragIndex === null || dropIndex === null) { if (dragIndex === null || dropIndex === null) {
setDragIndex(null); setDropIndex(null); return setDragIndex(null); setDropIndex(null); return
@@ -438,8 +466,20 @@ export function WorkshopScreen({
moveWidget(dragIndex, to) moveWidget(dragIndex, to)
setDragIndex(null); setDropIndex(null) setDragIndex(null); setDropIndex(null)
}} }}
onDragEnd={() => { setDragIndex(null); setDropIndex(null) }} onDragEnd={isPinned ? undefined : () => { setDragIndex(null); setDropIndex(null) }}
> >
{isPinned ? (
<span
className="px-1 text-gray-300 select-none"
title="Pinned — can't be reordered"
aria-hidden
>
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="11" width="18" height="10" rx="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</svg>
</span>
) : (
<span <span
className="px-1 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing select-none" className="px-1 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing select-none"
title="Drag to reorder" title="Drag to reorder"
@@ -447,6 +487,7 @@ export function WorkshopScreen({
> >
⋮⋮ ⋮⋮
</span> </span>
)}
<button <button
onClick={() => toggleWidget(w.id)} onClick={() => toggleWidget(w.id)}
className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${ className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
@@ -455,7 +496,7 @@ export function WorkshopScreen({
: 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50' : 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50'
}`} }`}
> >
<div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-blue-500' : 'bg-gray-200'}`} /> <div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-gray-900' : 'bg-gray-200'}`} />
{w.label} {w.label}
</button> </button>
{hasAdvanced && enabled && ( {hasAdvanced && enabled && (
@@ -468,7 +509,7 @@ export function WorkshopScreen({
</button> </button>
)} )}
</div> </div>
{showDropLineBelow && <div className="h-0.5 bg-blue-400 rounded-full mx-2 mt-0.5" />} {showDropLineBelow && <div className="h-0.5 bg-gray-900 rounded-full mx-2 mt-0.5" />}
{isExpanded && ( {isExpanded && (
<div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5"> <div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5">
+4 -3
View File
@@ -55,10 +55,11 @@ DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" """Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
# Widget settings # Widget settings
WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] WIDGET_ORDER = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Default order of widgets. Customize by reordering this list.""" """Default order of widgets. "name" is the avatar+username header and is
always pinned first in the UI — it can be toggled off but not reordered."""
ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] ENABLED_WIDGETS = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Which widgets to display. Remove any you don't want to show.""" """Which widgets to display. Remove any you don't want to show."""
# Language filtering # Language filtering
+14 -5
View File
@@ -40,20 +40,29 @@ def compose_widget(
theme_name: str = "dark", theme_name: str = "dark",
username: str = "", username: str = "",
avatar_b64: str = "", avatar_b64: str = "",
show_name: bool = True,
) -> str: ) -> str:
""" """
Takes rendered SVG strings for each widget type and composes them Takes rendered SVG strings for each widget type and composes them
into a single unified profile widget by inlining widget SVGs directly. into a single unified profile widget by inlining widget SVGs directly.
`show_name` controls whether the avatar + username header block is
drawn. It's the "name" pseudo-widget — pinned first in the UI, can be
toggled off but not reordered. When false, widgets start at the top
edge (minus the standard padding) so there's no orphan gap.
""" """
t = THEMES[theme_name] t = THEMES[theme_name]
total_w = 420 total_w = 420
header_h = 60 header_h = 60 if show_name else 0
padding = 20 padding = 20
gap = 16 gap = 16
# Extract inner content from each widget SVG # Extract inner content from each widget SVG. "name" has no rendered
# widget — it maps to the header block and is consumed by show_name.
parts = [] parts = []
for key in enabled: for key in enabled:
if key == "name":
continue
if key in widgets and widgets[key]: if key in widgets and widgets[key]:
inner, h = _extract_inner(widgets[key], key) inner, h = _extract_inner(widgets[key], key)
parts.append((key, inner, h)) parts.append((key, inner, h))
@@ -61,15 +70,15 @@ def compose_widget(
content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0) content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0)
total_h = header_h + content_h + padding * 2 + 10 total_h = header_h + content_h + padding * 2 + 10
# Header # Header (avatar + username). Only drawn when "name" is enabled.
avatar_svg = "" header = ""
if show_name:
if avatar_b64: if avatar_b64:
avatar_svg = f''' avatar_svg = f'''
<defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs> <defs><clipPath id="mainAvatarClip"><circle cx="30" cy="30" r="16"/></clipPath></defs>
<image x="14" y="14" width="32" height="32" href="data:image/png;base64,{avatar_b64}" clip-path="url(#mainAvatarClip)"/>''' <image x="14" y="14" width="32" height="32" href="data:image/png;base64,{avatar_b64}" clip-path="url(#mainAvatarClip)"/>'''
else: else:
avatar_svg = f'<circle cx="30" cy="30" r="16" fill="{t["accent"]}" opacity="0.3"/>' avatar_svg = f'<circle cx="30" cy="30" r="16" fill="{t["accent"]}" opacity="0.3"/>'
header = f''' header = f'''
{avatar_svg} {avatar_svg}
<text x="54" y="38" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <text x="54" y="38" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
+32 -1
View File
@@ -67,10 +67,18 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
achievements=settings.get("achievements") or [], achievements=settings.get("achievements") or [],
stored_streak=stored_streak, stored_streak=stored_streak,
) )
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]] enabled_set = set(enabled)
show_name = "name" in enabled_set
# Preserve "name" in the ordered list so the composite honors its
# user-ordered position (always 0 today, but future-proof).
ordered = [
w for w in order
if w in enabled_set and (w == "name" or (w in widgets and widgets[w]))
]
composite = compose_widget( composite = compose_widget(
widgets=widgets, enabled=ordered, theme_name=theme, widgets=widgets, enabled=ordered, theme_name=theme,
username=username, avatar_b64=payload.get("avatar_b64", ""), username=username, avatar_b64=payload.get("avatar_b64", ""),
show_name=show_name,
) )
out = {name: svg for name, svg in widgets.items() if svg} out = {name: svg for name, svg in widgets.items() if svg}
out["composite"] = composite out["composite"] = composite
@@ -113,6 +121,29 @@ def process_one() -> bool:
return True return True
def render_composite_adhoc(username: str, override_settings: dict) -> str | None:
"""Render the composite SVG for `username` using stored settings merged
with the per-request `override_settings`. Does NOT persist anything.
Used by the public `GET /api/<u>?...` endpoint so unauthenticated visitors
can preview/embed a widget configured purely via query string, without
touching the owner's stored settings.
Returns the SVG string, or None if the user isn't enrolled / the fetcher
has no data for them (caller should fall through to the cached path).
"""
settings_row = db.get_settings(username)
if settings_row is None:
return None
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if not payload or payload.get("error") == "not_found":
return None
effective = {**settings_row["settings"], **(override_settings or {})}
widgets = _render_widgets(username, payload, effective)
return widgets.get("composite")
def render_widgets_now(username: str) -> dict[str, str]: def render_widgets_now(username: str) -> dict[str, str]:
"""Phase 2: synchronously render composite SVG and persist it. """Phase 2: synchronously render composite SVG and persist it.
+10
View File
@@ -137,6 +137,16 @@ def test_login_rejects_external_next(api_client):
assert s.get("oauth_next") == "/" assert s.get("oauth_next") == "/"
@pytest.mark.parametrize("bad_next", ["//evil.example", "//evil.example/x", "/\\evil.example"])
def test_login_rejects_protocol_relative_next(api_client, bad_next):
# Browsers resolve //host and /\host against the current scheme, so these
# are open-redirect vectors even though they start with "/".
r = api_client.get(f"/api/auth/github/login?next={bad_next}")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_next") == "/"
def test_callback_state_mismatch_400(api_client): def test_callback_state_mismatch_400(api_client):
with api_client.session_transaction() as s: with api_client.session_transaction() as s:
s["oauth_state"] = "correct" s["oauth_state"] = "correct"