-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_components.py
More file actions
392 lines (334 loc) · 13.5 KB
/
ui_components.py
File metadata and controls
392 lines (334 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
CodeSense - Reusable UI Components
Streamlit components for scores, issues, DSA cards, feedback panels, etc.
"""
import streamlit as st
from typing import Any, Dict, List, Optional
from constants import (
COLOR_PRIMARY, COLOR_SUCCESS, COLOR_WARNING, COLOR_ERROR,
COLOR_INFO, COLOR_NEUTRAL,
)
# ─── CSS ──────────────────────────────────────────────────────────────────────
GLOBAL_CSS = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fira+Code:wght@400;500&display=swap');
html, body, [class*="css"] {
font-family: 'Inter', sans-serif;
}
code, pre, .stCodeBlock {
font-family: 'Fira Code', monospace !important;
}
/* Card */
.cs-card {
background: #1E1E2E;
border: 1px solid #2D2D3F;
border-radius: 12px;
padding: 20px 24px;
margin-bottom: 16px;
}
.cs-card-header {
font-size: 18px;
font-weight: 600;
margin-bottom: 12px;
color: #E2E8F0;
}
/* Score ring */
.score-ring {
display: flex;
align-items: center;
gap: 24px;
}
.score-number {
font-size: 56px;
font-weight: 700;
line-height: 1;
}
.grade-badge {
display: inline-block;
padding: 4px 16px;
border-radius: 999px;
font-size: 14px;
font-weight: 600;
}
/* Issue severity */
.sev-error { border-left: 4px solid #E53935; padding-left: 12px; }
.sev-warning { border-left: 4px solid #FDD835; padding-left: 12px; }
.sev-info { border-left: 4px solid #00ACC1; padding-left: 12px; }
.sev-positive{ border-left: 4px solid #43A047; padding-left: 12px; }
/* Metric pill */
.metric-pill {
display: inline-flex;
align-items: center;
gap: 6px;
background: #252535;
border-radius: 8px;
padding: 6px 14px;
font-size: 13px;
color: #A0AEC0;
margin: 4px;
}
.metric-pill b { color: #E2E8F0; }
/* Badge */
.badge {
display: inline-block;
border-radius: 4px;
padding: 2px 8px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
}
.badge-critical { background:#E53935; color:#fff; }
.badge-high { background:#FF7043; color:#fff; }
.badge-medium { background:#FDD835; color:#000; }
.badge-low { background:#43A047; color:#fff; }
.badge-info { background:#00ACC1; color:#fff; }
/* Step indicator */
.step-circle {
width: 28px; height: 28px;
border-radius: 50%;
background: #1E88E5;
color: #fff;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 13px;
font-weight: 700;
flex-shrink: 0;
}
/* Progress bar */
.cs-progress-bar {
background: #252535;
border-radius: 999px;
height: 8px;
overflow: hidden;
margin: 8px 0;
}
.cs-progress-fill {
height: 100%;
border-radius: 999px;
transition: width 0.5s ease;
}
/* Tabs */
.stTabs [data-baseweb="tab-list"] {
gap: 4px;
background: #1E1E2E;
border-radius: 8px;
padding: 4px;
}
.stTabs [data-baseweb="tab"] {
border-radius: 6px;
padding: 8px 18px;
color: #A0AEC0;
}
.stTabs [aria-selected="true"] {
background: #1E88E5 !important;
color: #fff !important;
}
/* Button */
.stButton > button {
border-radius: 8px;
font-weight: 600;
transition: all 0.2s ease;
}
.stButton > button:hover {
transform: scale(1.03);
}
/* Sidebar */
[data-testid="stSidebar"] {
background: #1E1E2E;
border-right: 1px solid #2D2D3F;
}
</style>
"""
def inject_css() -> None:
st.markdown(GLOBAL_CSS, unsafe_allow_html=True)
# ─── Score Display ────────────────────────────────────────────────────────────
def score_card(score: float, grade: str, confidence: float,
label: str = "", improvement: Optional[float] = None) -> None:
"""
Score card using st.columns layout — avoids nested HTML divs which
Streamlit's sanitizer strips, causing raw </div> text to appear.
"""
color = _score_color(score)
lbl = label or _score_label(score)
pct = int(score)
# Outer card shell — single div, no nesting, safe
st.markdown(
f'<div style="background:#1E1E2E;border:1px solid #2D2D3F;border-radius:12px;padding:16px 20px;margin-bottom:8px">',
unsafe_allow_html=True,
)
col_ring, col_info = st.columns([1, 1.6])
with col_ring:
# Flat ring using span elements only (no nested divs)
st.markdown(f"""
<span style="display:block;width:90px;height:90px;border-radius:50%;
background:conic-gradient({color} {pct}%,#252535 {pct}%);
display:flex;align-items:center;justify-content:center;margin:auto">
<span style="background:#1E1E2E;width:68px;height:68px;border-radius:50%;
display:flex;flex-direction:column;align-items:center;justify-content:center">
<b style="font-size:22px;color:{color};line-height:1.1">{score:.0f}</b>
<small style="font-size:10px;color:#757575">/100</small>
</span>
</span>""", unsafe_allow_html=True)
with col_info:
st.markdown(f'<b style="font-size:36px;color:{color}">{grade}</b>',
unsafe_allow_html=True)
st.markdown(f'<span style="color:#A0AEC0;font-size:13px;display:block">{lbl}</span>',
unsafe_allow_html=True)
st.markdown(f'<span style="color:#757575;font-size:11px">±{confidence:.1f} confidence</span>',
unsafe_allow_html=True)
if improvement is not None:
sign = "+" if improvement >= 0 else ""
color2 = COLOR_SUCCESS if improvement >= 0 else COLOR_ERROR
st.markdown(
f'<span style="color:{color2};font-size:12px;display:block;margin-top:4px">' +
f'{sign}{improvement:.1f} pts vs last</span>',
unsafe_allow_html=True,
)
st.markdown('</div>', unsafe_allow_html=True)
def progress_bar(value: float, max_val: float = 100,
color: str = COLOR_PRIMARY, label: str = "") -> None:
pct = min(100, value / max_val * 100) if max_val else 0
st.markdown(f"""
<div style="margin:4px 0">
{"<small style='color:#A0AEC0'>" + label + "</small>" if label else ""}
<div class="cs-progress-bar">
<div class="cs-progress-fill" style="width:{pct}%;background:{color}"></div>
</div>
</div>
""", unsafe_allow_html=True)
# ─── Issue Cards ─────────────────────────────────────────────────────────────
def issue_card(item: Dict) -> None:
"""
Render an issue card. Uses st.code() for code snippets to avoid
Streamlit's HTML sanitizer stripping nested tags inside st.markdown.
"""
sev = item.get("severity", "info")
title = item.get("title", "")
msg = item.get("message", "")
line = item.get("line")
bef = item.get("code_before", "")
aft = item.get("code_after", "")
res = item.get("resource")
border = {
"error": "#E53935",
"warning": "#FDD835",
"info": "#00ACC1",
"positive": "#43A047",
}.get(sev, "#757575")
line_badge = (
f'<span style="color:#757575;font-size:12px;margin-left:8px">Line {line}</span>'
if line else ""
)
resource_html = ""
if res and res.get("url"):
resource_html = (
f'<a href="{res["url"]}" target="_blank" '
f'style="color:#1E88E5;font-size:12px;text-decoration:none">'
f'📖 {res.get("title","Learn more")}</a>'
)
# Header rendered via st.markdown (no nested code — safe from sanitizer)
st.markdown(f"""
<div style="border-left:4px solid {border};background:#1E1E2E;border-radius:0 8px 8px 0;
padding:12px 16px;margin-bottom:4px;border:1px solid #2D2D3F;
border-left:4px solid {border}">
<div style="font-weight:600;color:#E2E8F0;font-size:14px">{_esc(title)}{line_badge}</div>
<div style="color:#A0AEC0;font-size:13px;margin-top:4px">{_esc(msg)}</div>
<div style="margin-top:6px">{resource_html}</div>
</div>
""", unsafe_allow_html=True)
# Code snippets via st.code — completely bypasses HTML sanitizer
if bef:
st.caption("📄 Your code:")
st.code(bef, language="python")
if aft:
st.caption("✅ Suggestion:")
st.code(aft, language="python")
st.markdown("<div style='height:4px'></div>", unsafe_allow_html=True)
# ─── DSA Cards ───────────────────────────────────────────────────────────────
def algo_card(algo: Dict) -> None:
cx = algo.get("complexity", {})
conf = int(algo.get("confidence", 0) * 100)
color = COLOR_SUCCESS if cx.get("avg", "").startswith("O(log") or \
cx.get("avg", "").startswith("O(n log") else COLOR_WARNING
st.markdown(f"""
<div class="cs-card">
<div style="display:flex;justify-content:space-between;align-items:center">
<span style="font-weight:600;color:#E2E8F0">🧠 {algo['display_name']}</span>
<span class="badge badge-info">{algo.get('category','')}</span>
</div>
<div style="color:#A0AEC0;font-size:13px;margin:6px 0">
Lines {algo.get('start_line','?')}–{algo.get('end_line','?')} |
Confidence: {conf}%
</div>
<div style="margin:8px 0">
<span class="metric-pill">⏱ Best <b>{cx.get('best','?')}</b></span>
<span class="metric-pill">⏱ Avg <b>{cx.get('avg','?')}</b></span>
<span class="metric-pill">⏱ Worst <b>{cx.get('worst','?')}</b></span>
<span class="metric-pill">💾 Space <b>{cx.get('space','?')}</b></span>
</div>
<div style="color:#A0AEC0;font-size:13px;font-style:italic">{algo.get('reason','')}</div>
{"<div style='margin-top:8px;color:#FDD835;font-size:13px'>💡 " + algo.get('suggestion','') + "</div>" if algo.get('suggestion') else ""}
</div>
""", unsafe_allow_html=True)
def ds_chip(ds: Dict) -> None:
st.markdown(
f'<span class="metric-pill">📦 <b>{ds["display_name"]}</b> (line {ds["line"]})</span>',
unsafe_allow_html=True,
)
# ─── Stats Metrics Row ───────────────────────────────────────────────────────
def stat_row(items: List[Dict]) -> None:
"""
Render a horizontal row of stat cards.
Each item: {label, value, delta, color, icon}
"""
cols = st.columns(len(items))
for col, item in zip(cols, items):
with col:
delta_html = ""
if "delta" in item and item["delta"] is not None:
d = item["delta"]
c = COLOR_SUCCESS if d >= 0 else COLOR_ERROR
delta_html = f'<div style="color:{c};font-size:12px">{"▲" if d >= 0 else "▼"} {abs(d):.1f}</div>'
col.markdown(f"""
<div class="cs-card" style="text-align:center;padding:16px">
<div style="font-size:24px">{item.get('icon','')}</div>
<div style="font-size:28px;font-weight:700;color:{item.get('color', COLOR_PRIMARY)}">{item['value']}</div>
<div style="color:#A0AEC0;font-size:13px">{item['label']}</div>
{delta_html}
</div>
""", unsafe_allow_html=True)
# ─── Loading States ───────────────────────────────────────────────────────────
def loading_spinner(message: str = "Analyzing your code...") -> None:
st.markdown(f"""
<div style="text-align:center;padding:40px">
<div style="font-size:32px;animation:spin 1s linear infinite">⚙️</div>
<div style="color:#A0AEC0;margin-top:12px">{message}</div>
</div>
<style>@keyframes spin {{from{{transform:rotate(0deg)}}to{{transform:rotate(360deg)}}}}</style>
""", unsafe_allow_html=True)
# ─── Achievement Badge ───────────────────────────────────────────────────────
def achievement_badge(title: str, icon: str, description: str) -> None:
st.markdown(f"""
<div class="cs-card" style="display:flex;align-items:center;gap:16px;padding:12px 20px">
<div style="font-size:36px">{icon}</div>
<div>
<div style="font-weight:600;color:#E2E8F0">{title}</div>
<div style="color:#A0AEC0;font-size:13px">{description}</div>
</div>
</div>
""", unsafe_allow_html=True)
# ─── Helpers ──────────────────────────────────────────────────────────────────
def _score_color(score: float) -> str:
if score >= 85: return COLOR_SUCCESS
if score >= 70: return COLOR_PRIMARY
if score >= 50: return COLOR_WARNING
return COLOR_ERROR
def _score_label(score: float) -> str:
if score >= 90: return "Excellent"
if score >= 75: return "Good"
if score >= 60: return "Average"
if score >= 40: return "Below Average"
return "Poor"
def _esc(text: str) -> str:
return (text.replace("&", "&").replace("<", "<").replace(">", ">"))