forked from Priyanshu-byte-coder/devtrack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodingActivityInsightsCard.tsx
More file actions
411 lines (370 loc) · 12 KB
/
Copy pathCodingActivityInsightsCard.tsx
File metadata and controls
411 lines (370 loc) · 12 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// @ts-nocheck
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { RefreshCw, Loader2 } from "lucide-react";
import {
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
type TooltipProps,
} from "recharts";
import { Skeleton } from "@/components/Skeleton";
import { useAccount } from "@/components/AccountContext";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
formatHourRange,
type CodingActivityInsight,
} from "@/lib/coding-activity-insights";
const DATA_WINDOW_DAYS = 90;
function formatCommitCount(count: number): string {
return `${count} commit${count === 1 ? "" : "s"}`;
}
function InsightRow({
label,
value,
}: {
label: string;
value: string;
}) {
return (
<div className="rounded-lg bg-[var(--control)] px-3 py-2">
<p className="text-xs font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
{label}
</p>
<p className="mt-1 text-sm font-medium text-[var(--card-foreground)]">
{value}
</p>
</div>
);
}
function TrendBadge({
direction,
percentage,
}: {
direction: "up" | "down" | "stable";
percentage: number;
}) {
const styles =
direction === "up"
? "bg-green-500/10 text-green-400 border-green-500/20"
: direction === "down"
? "bg-red-500/10 text-red-400 border-red-500/20"
: "bg-blue-500/10 text-blue-400 border-blue-500/20";
const label =
direction === "up"
? `↑ ${percentage}% Improving`
: direction === "down"
? `↓ ${percentage}% Declining`
: "Stable Activity";
return (
<div
className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium ${styles}`} >
{label}
</div>
);
}
function HourTooltip({
active,
payload,
}: any) {
if (!active || !payload || payload.length === 0) {
return null;
}
const entry = payload[0]?.payload as { hour?: number; count?: number } | undefined;
if (!entry || typeof entry.hour !== "number") {
return null;
}
const count = entry.count ?? 0;
return (
<div className="rounded-md border border-[var(--border)] bg-[var(--tooltip)] px-3 py-2 text-sm text-[var(--tooltip-foreground)] shadow-lg">
<div className="font-medium">{formatHourRange(entry.hour)}</div>
<div className="mt-1 text-xs text-[var(--muted-foreground)]">
{formatCommitCount(count)}
</div>
</div>
);
}
export default function CodingActivityInsightsCard() {
const { selectedAccount } = useAccount();
const [timezone, setTimezone] = useState<string | null>(null);
const [data, setData] = useState<CodingActivityInsight | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const requestIdRef = useRef(0);
useEffect(() => {
setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone ?? null);
}, []);
const fetchInsights = useCallback(() => {
if (!timezone) {
return;
}
const requestId = ++requestIdRef.current;
setLoading(true);
setError(null);
const params = new URLSearchParams();
params.set("timeZone", timezone);
if (selectedAccount !== null) {
params.set("accountId", selectedAccount);
}
fetch(`/api/metrics/coding-activity-insights?${params.toString()}`)
.then((response) => {
if (!response.ok) {
throw new Error("API error");
}
return response.json();
})
.then((payload: CodingActivityInsight) => {
if (requestId !== requestIdRef.current) {
return;
}
setData(payload);
})
.catch(() => {
if (requestId !== requestIdRef.current) {
return;
}
setError("We couldn't load your AI Productivity Insights right now. Please try again in a moment.");
})
.finally(() => {
if (requestId !== requestIdRef.current) {
return;
}
setLoading(false);
});
}, [selectedAccount, timezone]);
useEffect(() => {
if (!timezone) {
return;
}
fetchInsights();
}, [fetchInsights, timezone]);
const chartData = useMemo(
() => data?.hourlyCounts.map(({ hour, count }) => ({ hour, count })) ?? [],
[data]
);
const hasData = Boolean(
data && data.totalActivities > 0 && chartData.some((entry) => entry.count > 0)
);
const insightRows = useMemo(() => {
if (!data) {
return [];
}
const rows = [
{
label: "Most active",
value: `${data.mostActiveHour.label} with ${formatCommitCount(data.mostActiveHour.count)}`,
},
{
label: "Least active",
value: `${data.leastActiveHour.label} with ${formatCommitCount(data.leastActiveHour.count)}`,
},
{
label: "Consistency",
value: `${data.consistencyScore ?? 0}% weekly consistency`,
},
{
label: "Productivity",
value:
data.productivityLevel === "Excellent"
? "🟢 Excellent"
: data.productivityLevel === "Very Good"
? "🔵 Very Good"
: data.productivityLevel === "Good"
? "🟡 Good"
: data.productivityLevel === "Moderate"
? "🟠 Moderate"
: "🔴 Low",
},
{
label: "Daily Average",
value: `${data.averageDailyCommits ?? 0} commits/day`,
},
];
if (data.mostActiveDay) {
rows.push({
label: "Best day",
value: `${data.mostActiveDay.day} with ${formatCommitCount(data.mostActiveDay.count)}`,
});
}
return rows;
}, [data]);
const dataWindowLabel = `Last ${DATA_WINDOW_DAYS} days`;
const subtitle = data
? `${dataWindowLabel} · Commits by hour · ${data.timezone}`
: timezone
? `${dataWindowLabel} · Commits by hour · ${timezone}`
: `${dataWindowLabel} · Commits by hour · Local timezone`;
return (
<div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm transition-all duration-300 hover:shadow-md hover:-translate-y-1">
<div className="mb-4 flex items-start justify-between gap-3">
<div>
<CardTitle>Coding Activity Insights</CardTitle>
{data?.weeklyTrend ? (
<div className="mt-2 mb-1">
<TrendBadge
direction={data.weeklyTrend.direction}
percentage={data.weeklyTrend.percentage}
/>
</div>
) : null}
<CardDescription className="mt-1">
{subtitle}
</CardDescription>
</div>
<button aria-label="Refresh"
type="button"
onClick={fetchInsights}
disabled={loading}
className="flex items-center gap-2 rounded-md border border-[var(--border)] px-3 py-1.5 text-xs font-medium text-[var(--muted-foreground)] transition-all hover:bg-[var(--control)] disabled:cursor-not-allowed disabled:opacity-50 hover:opacity-90 active:scale-95"
>
{loading ? (
<>
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
Refreshing
</>
) : (
"Refresh"
)}
</button>
</div>
{loading ? (
<div
role="status"
aria-live="polite"
aria-busy="true"
className="space-y-4"
>
<span className="sr-only">Loading coding activity insights</span>
<Skeleton className="h-[260px] rounded-lg" />
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3].map((item) => (
<Skeleton key={item} aria-hidden="true" className="h-16 rounded-lg" />
<Skeleton className="h-[260px] w-full rounded-lg" />
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3].map((item) => (
<Skeleton key={item} className="h-16 w-full rounded-lg" />
))}
</div>
</div>
) : error ? (
<div className="rounded-lg border border-[var(--destructive)]/20 bg-[var(--destructive)]/10 p-4 text-sm text-[var(--destructive)]">
<p>{error}</p>
<Button
variant="outline"
size="sm"
onClick={fetchInsights}
className="mt-3 border-[var(--destructive)]/30 text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
>
Try again
</Button>
</div>
) : !hasData ? (
<div className="flex min-h-[320px] items-center justify-center rounded-lg border border-dashed border-[var(--border)] bg-[var(--card-muted)] px-4 text-center">
<p className="text-sm text-[var(--muted-foreground)]">
Not enough coding activity was detected to generate AI-powered productivity insights yet.
</p>
</div>
) : (
<div className="space-y-4">
<div className="h-[260px] min-h-[260px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={chartData}
margin={{ top: 8, right: 12, left: 0, bottom: 0 }}
>
<CartesianGrid
strokeDasharray="3 3"
vertical={false}
stroke="var(--border)"
opacity={0.35}
/>
<XAxis
dataKey="hour"
axisLine={false}
tickLine={false}
interval={2}
tickFormatter={(value) => String(value)}
style={{ fill: "var(--muted-foreground)", fontSize: "0.75rem" }}
/>
<YAxis
allowDecimals={false}
axisLine={false}
tickLine={false}
width={28}
style={{ fill: "var(--muted-foreground)", fontSize: "0.75rem" }}
/>
<Tooltip content={HourTooltip} />
<Bar
dataKey="count"
fill="var(--accent)"
radius={[4, 4, 0, 0]}
barSize={10}
/>
</BarChart>
</ResponsiveContainer>
</div>
<div
className={`grid gap-3 ${
data?.mostActiveDay
? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"
: "grid-cols-1 sm:grid-cols-2"
}`}
>
{insightRows.map((row) => (
<InsightRow
key={row.label}
label={row.label}
value={row.value}
/>
))}
</div>
{(data?.summary?.length || data?.recommendations?.length) && (
<div className="space-y-4 rounded-xl border border-[var(--border)] bg-[var(--card-muted)] p-4">
{data.summary?.length ? (
<div>
<h3 className="mb-2 text-sm font-semibold text-[var(--card-foreground)]">
AI Productivity Summary
</h3>
<div className="space-y-2">
{data.summary.map((item, index) => (
<div
key={index}
className="rounded-md bg-[var(--control)] px-3 py-2 text-sm text-[var(--card-foreground)]"
>
{item}
</div>
))}
</div>
</div>
) : null}
{data.recommendations?.length ? (
<div>
<h3 className="mb-2 text-sm font-semibold text-[var(--card-foreground)]">
Smart Recommendations
</h3>
<div className="space-y-2">
{data.recommendations.map((item, index) => (
<div
key={index}
className="rounded-md border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-sm text-[var(--muted-foreground)]"
>
• {item}
</div>
))}
</div>
</div>
) : null}
</div>
)}
</div>
)}
</CardContent>
</Card>
);
}