import { useState, useMemo, type ReactNode } from 'react' import DOMPurify from 'dompurify' import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' import type { Me } from '../lib/auth' // Defense-in-depth: the client-rendered preview assembles SVG from // GitHub-sourced strings (collaborator logins, repo names) and user-typed // achievement text. renderWidgets escapes known fields, but one missed // interpolation anywhere upstream would turn into HTML in the preview. // DOMPurify neutralises that without affecting normal SVG shapes/styles. const SVG_SANITIZE_CONFIG = { USE_PROFILES: { svg: true, svgFilters: true }, ADD_TAGS: [ 'image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform', 'feDropShadow', 'filter', 'linearGradient', 'stop', ], ADD_ATTR: [ 'xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio', 'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur', 'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity', 'filter', 'flood-color', 'flood-opacity', 'stdDeviation', ], } // 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 = [ { id: 'midnight', label: 'Midnight', bg: '#121820', card: '#1a2230', border: '#2a3444', accent: '#58a6ff', light: false }, { id: 'onyx', label: 'Onyx', bg: '#09090b', card: '#18181b', border: '#27272a', accent: '#a78bfa', light: false }, { id: 'nord', label: 'Nord', bg: '#1e2433', card: '#2a3142', border: '#3d4659', accent: '#88c0d0', light: false }, { id: 'clean', label: 'Clean', bg: '#ffffff', card: '#f6f8fa', border: '#d8dee4', accent: '#0969da', light: true }, { id: 'paper', label: 'Paper', bg: '#faf8f5', card: '#f5f0eb', border: '#e0d8cf', accent: '#b45309', light: true }, ] 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: 'impact', label: 'Impact Timeline' }, { id: 'streaks', label: 'Streaks' }, { id: 'collaborators', label: 'Top Collaborators' }, { id: 'focus', label: 'Recent Focus' }, { id: 'languages', label: 'Languages' }, { id: 'achievements', label: 'Achievements' }, ] // Lucide-style hollow glyphs: consistent stroke-weight + viewBox so the 4 // buttons line up and read as one icon family. Kept as JSX so they inherit // currentColor from the surrounding button's text color. const ICON_SVG_PROPS = { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.75, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const, } const ICONS: { id: string; svg: ReactNode }[] = [ { id: 'trophy', svg: ( ), }, { id: 'medal', svg: ( ), }, { id: 'star', svg: ( ), }, { id: 'hackathon', svg: ( ), }, ] const COLOR_PRESETS = [ '#58a6ff', '#a78bfa', '#4ade80', '#fb923c', '#f472b6', '#ff6b6b', '#38bdf8', '#facc15', '#34d399', '#c084fc', ] function ChevronIcon({ open }: { open: boolean }) { return ( ) } function NumberStepper({ value, min, max, onChange }: { value: number; min: number; max: number; onChange: (v: number) => void }) { return (
{value}
) } // Common "noise" languages users typically want to hide — shown even when // the account-level detection hasn't surfaced them yet (e.g., first load). const COMMON_HIDE_LANGS = ['HTML', 'CSS', 'SCSS', 'Jupyter Notebook', 'TeX', 'Shell', 'Dockerfile', 'Makefile', 'Batchfile'] function HiddenLanguagesPicker({ detected, hidden, onChange, }: { detected: { language: string }[] hidden: string[] onChange: (next: string[]) => void }) { const seen = new Set() const options: string[] = [] for (const d of detected) if (d.language && !seen.has(d.language)) { seen.add(d.language); options.push(d.language) } for (const c of COMMON_HIDE_LANGS) if (!seen.has(c)) { seen.add(c); options.push(c) } // Preserve any user-set hidden that we haven't otherwise seen. for (const h of hidden) if (!seen.has(h)) { seen.add(h); options.push(h) } const toggle = (lang: string) => { onChange(hidden.includes(lang) ? hidden.filter(h => h !== lang) : [...hidden, lang]) } return (
Hide languages {hidden.length > 0 && ( )}
{options.map(lang => { const active = hidden.includes(lang) return ( ) })}
) } function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) { return (
{COLOR_PRESETS.map(c => (
) } type Props = { username: string settings: WidgetSettings onSettingsChange: (s: WidgetSettings) => void onGenerate: () => void onBack: () => void fetchDone: boolean fetchError: string | null widgetData: WidgetData | null isDemoData: boolean me: Me onAuthChange?: (m: Me) => void } export function WorkshopScreen({ username, settings, onSettingsChange, onGenerate, onBack, fetchDone, fetchError, widgetData, isDemoData, me, }: Props) { const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase() const [expandedWidget, setExpandedWidget] = useState(null) // Index being dragged + index currently hovered (for drop-line indicator). const [dragIndex, setDragIndex] = useState(null) const [dropIndex, setDropIndex] = useState(null) // Same pattern for the achievements list so the two drag interactions // don't share state and fight each other. const [achDragIndex, setAchDragIndex] = useState(null) const [achDropIndex, setAchDropIndex] = useState(null) // Build the render-order list from settings.widgetOrder, tolerating // stale persisted data: drop unknown ids, append any known widgets // the stored order forgot. Keeps the UI functional if ALL_WIDGETS // gains or loses an entry between releases. 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 seen = new Set() const out: string[] = ['name'] seen.add('name') for (const id of settings.widgetOrder) { if (knownIds.has(id) && !seen.has(id)) { seen.add(id); out.push(id) } } for (const w of ALL_WIDGETS) { if (!seen.has(w.id)) { seen.add(w.id); out.push(w.id) } } return out }, [settings.widgetOrder, knownIds]) const moveWidget = (from: number, to: number) => { 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 [item] = next.splice(from, 1) next.splice(to, 0, item) onSettingsChange({ ...settings, widgetOrder: next }) } const updateSetting = (key: K, val: WidgetSettings[K]) => { onSettingsChange({ ...settings, [key]: val }) } const updateWidgetSetting = (widget: keyof PerWidgetSettings, key: string, val: unknown) => { const current = settings.widgetSettings[widget] || {} const next = { ...settings.widgetSettings, [widget]: { ...current, [key]: val } } updateSetting('widgetSettings', next) } const getWidgetSetting = (widget: keyof PerWidgetSettings, key: string, fallback: T): T => { const ws = settings.widgetSettings[widget] as Record | undefined return (ws?.[key] as T) ?? fallback } const toggleWidget = (id: string) => { const next = settings.widgets.includes(id) ? settings.widgets.filter(w => w !== id) : [...settings.widgets, id] updateSetting('widgets', next) } const toggleAdvanced = (id: string) => { setExpandedWidget(expandedWidget === id ? null : id) } const addAchievement = () => { updateSetting('achievements', [ ...settings.achievements, { title: '', subtitle: '', event_date: '', icon: 'trophy' }, ]) } const updateAchievement = (idx: number, field: keyof Achievement, val: string) => { const next = settings.achievements.map((a, i) => i === idx ? { ...a, [field]: val } : a ) updateSetting('achievements', next) } const removeAchievement = (idx: number) => { updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx)) } const moveAchievement = (from: number, to: number) => { const list = settings.achievements if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return const next = list.slice() const [item] = next.splice(from, 1) next.splice(to, 0, item) updateSetting('achievements', next) } // Render SVG client-side whenever settings change (instant, no API call) const svgContent = useMemo(() => { if (!widgetData) return '' const raw = renderAllWidgets({ data: widgetData, theme: settings.theme, widgets: settings.widgets, widgetOrder: orderedIds, achievements: settings.achievements, widgetSettings: settings.widgetSettings, hiddenLanguages: settings.hiddenLanguages, username, }) return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG) }, [widgetData, settings, username, orderedIds]) return (
{/* Left settings panel */}
{/* Back */}
{username}
{fetchError && (
{fetchError}
)} {!canEdit && me.login && (
{`Signed in as ${me.login}. Changes here produce a shareable link with query params. Only ${username} can save them permanently.`}
)} {/* Theme */}
Theme
{THEMES.map(t => ( ))}
{THEMES.find(t => t.id === settings.theme)?.label}
{/* Widgets with inline advanced settings */}
Widgets
{orderedIds.map((id, idx) => { const w = ALL_WIDGETS.find(x => x.id === id) if (!w) return null const enabled = settings.widgets.includes(w.id) const hasAdvanced = ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) const isExpanded = expandedWidget === w.id && enabled // "name" is pinned — no drag affordance, no drop lines. // 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. const showDropLineBelow = !isPinned && idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null return (
{showDropLineAbove &&
}
{ setDragIndex(idx) e.dataTransfer.effectAllowed = 'move' // Firefox needs some payload to start a drag. e.dataTransfer.setData('text/plain', String(idx)) }} onDragOver={isPinned ? undefined : e => { if (dragIndex === null) return e.preventDefault() e.dataTransfer.dropEffect = 'move' // Midpoint decides whether the drop slot is this row // or the next — gives a predictable feel between rows. const rect = e.currentTarget.getBoundingClientRect() const after = e.clientY - rect.top > rect.height / 2 const target = after ? idx + 1 : idx // Landing on the drag source's own slot is a no-op; // hide the indicator so it doesn't look interactive. if (target === dragIndex || target === dragIndex + 1) { setDropIndex(null) } else { setDropIndex(target) } }} onDrop={isPinned ? undefined : e => { e.preventDefault() if (dragIndex === null || dropIndex === null) { setDragIndex(null); setDropIndex(null); return } // Removing the source before inserting shifts later // indices down by one — adjust the target accordingly. const to = dropIndex > dragIndex ? dropIndex - 1 : dropIndex moveWidget(dragIndex, to) setDragIndex(null); setDropIndex(null) }} onDragEnd={isPinned ? undefined : () => { setDragIndex(null); setDropIndex(null) }} > {isPinned ? ( ) : ( ⋮⋮ )} {hasAdvanced && enabled && ( )}
{showDropLineBelow &&
} {isExpanded && (
{w.id === 'grade' && (
Max tags updateWidgetSetting('grade', 'max_tags', v)} />
)} {w.id === 'impact' && (
Line color updateWidgetSetting('impact', 'line_color', v)} />
)} {w.id === 'streaks' && (
Streak color updateWidgetSetting('streaks', 'color', v)} />
)} {w.id === 'collaborators' && (
Max shown updateWidgetSetting('collaborators', 'max_count', v)} />
Bar color updateWidgetSetting('collaborators', 'bar_color', v)} />
)} {w.id === 'focus' && (
Max categories updateWidgetSetting('focus', 'max_categories', v)} />
)} {w.id === 'languages' && (
Max languages updateWidgetSetting('languages', 'max_languages', v)} />
)} {w.id === 'achievements' && (
Max shown updateWidgetSetting('achievements', 'max_items', v)} />
{settings.achievements.map((ach, aidx) => { const achIsDragging = achDragIndex === aidx const achShowLineAbove = aidx > 0 && achDropIndex === aidx && achDragIndex !== null && achDragIndex !== aidx const achShowLineBelow = aidx === settings.achievements.length - 1 && achDropIndex === settings.achievements.length && achDragIndex !== null return (
{achShowLineAbove &&
}
{ setAchDragIndex(aidx) e.dataTransfer.effectAllowed = 'move' e.dataTransfer.setData('text/plain', String(aidx)) }} onDragOver={e => { if (achDragIndex === null) return e.preventDefault() e.dataTransfer.dropEffect = 'move' const rect = e.currentTarget.getBoundingClientRect() const after = e.clientY - rect.top > rect.height / 2 const target = after ? aidx + 1 : aidx if (target === achDragIndex || target === achDragIndex + 1) { setAchDropIndex(null) } else { setAchDropIndex(target) } }} onDrop={e => { e.preventDefault() if (achDragIndex === null || achDropIndex === null) { setAchDragIndex(null); setAchDropIndex(null); return } const to = achDropIndex > achDragIndex ? achDropIndex - 1 : achDropIndex moveAchievement(achDragIndex, to) setAchDragIndex(null); setAchDropIndex(null) }} onDragEnd={() => { setAchDragIndex(null); setAchDropIndex(null) }} >
{ICONS.map(ic => { const selected = ach.icon === ic.id return ( ) })}
updateAchievement(aidx, 'title', e.target.value)} placeholder="Title (e.g. Hackathon Winner)" className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" /> updateAchievement(aidx, 'subtitle', e.target.value)} placeholder="Subtitle (e.g. 1st Place · AI Track)" className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" /> updateAchievement(aidx, 'event_date', e.target.value)} placeholder="Date (e.g. 2025-01)" className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300" />
{achShowLineBelow &&
}
) })}
)}
)}
) })}
{/* Right preview area */}
{isDemoData && svgContent && (
Sample data until your stats finish building
)} {svgContent ? (
) : (
{!fetchDone ? (
) : (

No data available

)}
)}
) }