-
Notifications
You must be signed in to change notification settings - Fork 290
Expand file tree
/
Copy pathDashboardHeader.tsx
More file actions
354 lines (303 loc) · 13 KB
/
DashboardHeader.tsx
File metadata and controls
354 lines (303 loc) · 13 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
"use client";
import React from "react";
import NotificationBell from "@/components/NotificationBell";
import {
createContext,
ReactNode,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from "react";
import { useSession } from "next-auth/react";
import AccountToggle from "@/components/AccountToggle";
import SignOutButton from "@/components/SignOutButton";
import ThemeToggle from "@/components/ThemeToggle";
import UserAvatar from "@/components/UserAvatar";
import KeyboardShortcuts from "@/components/KeyboardShortcuts";
import { Moon, Sun } from "lucide-react";
import { toast } from "sonner";
type DashboardSyncContextValue = {
lastSynced: Date | null;
};
const DashboardSyncContext = createContext<DashboardSyncContextValue>({
lastSynced: null,
});
function getRequestPath(input: RequestInfo | URL): string {
if (typeof input === "string") {
return input.startsWith("http") ? new URL(input).pathname : input;
}
if (input instanceof URL) {
return input.pathname;
}
return new URL(input.url).pathname;
}
function isDashboardDataRequest(input: RequestInfo | URL): boolean {
const requestPath = getRequestPath(input);
return (
requestPath.startsWith("/api/metrics/") ||
requestPath === "/api/goals" ||
requestPath.startsWith("/api/goals/") ||
requestPath.startsWith("/api/streak/") ||
requestPath === "/api/user/github-accounts" ||
requestPath.startsWith("/api/badge/")
);
}
export function DashboardSyncProvider({ children }: { children: ReactNode }) {
const [lastSynced, setLastSynced] = useState<Date | null>(null);
useLayoutEffect(() => {
const originalFetch = window.fetch;
window.fetch = async (...args) => {
const response = await originalFetch(...args);
if (response.ok && isDashboardDataRequest(args[0])) {
setLastSynced(new Date());
}
return response;
};
return () => {
window.fetch = originalFetch;
};
}, []);
const value = useMemo(() => ({ lastSynced }), [lastSynced]);
return (
<DashboardSyncContext.Provider value={value}>
{children}
</DashboardSyncContext.Provider>
);
}
function useDashboardSync() {
return useContext(DashboardSyncContext);
}
export default function DashboardHeader() {
const { data: session } = useSession();
const [isPublic, setIsPublic] = useState<boolean | null>(null);
const [greeting, setGreeting] = useState<string>("Welcome back");
const [isNightOwl, setIsNightOwl] = useState<boolean>(false);
const [isEarlyBird, setIsEarlyBird] = useState<boolean>(false);
useEffect(() => {
const computeCurrentGreeting = () => {
const currentHour = new Date().getHours();
if (currentHour >= 5 && currentHour < 12) return "Good morning ☀️";
if (currentHour >= 12 && currentHour < 17) return "Good afternoon 🌤️";
if (currentHour >= 17 && currentHour < 22) return "Good evening 🌙";
return "Burning the midnight oil 🦉";
};
setGreeting(computeCurrentGreeting());
}, []);
useEffect(() => {
if (!session?.githubLogin) return;
async function evaluateCodingDistributionMilestones() {
try {
const res = await fetch("/api/metrics/repos?days=90");
if (!res.ok) return;
const data = await res.json();
const commitsArray = data.repos || [];
let nightOwlCommitsCount = 0;
let earlyBirdCommitsCount = 0;
commitsArray.forEach((repo: any) => {
if (repo.last_commit_date) {
const commitHour = new Date(repo.last_commit_date).getHours();
if (commitHour >= 0 && commitHour <= 4) nightOwlCommitsCount++;
if (commitHour >= 5 && commitHour <= 8) earlyBirdCommitsCount++;
}
});
if (nightOwlCommitsCount >= 1) setIsNightOwl(true);
if (earlyBirdCommitsCount >= 1) setIsEarlyBird(true);
} catch (err) {
console.error("Failed to compile milestone hour distribution profiles:", err);
}
}
evaluateCodingDistributionMilestones();
}, [session]);
const [copied, setCopied] = useState(false);
const [greeting, setGreeting] = useState<string>("Welcome back");
const handleCopyLink = () => {
if (!session?.githubLogin) return;
const profileUrl = `${window.location.origin}/u/${session.githubLogin}`;
navigator.clipboard.writeText(profileUrl).then(() => {
setCopied(true);
toast.success("Profile link copied!");
setTimeout(() => setCopied(false), 2000);
}).catch(() => {
toast.error("Failed to copy link");
});
};
// Determine the user's personalized greeting string based on local timestamp metrics
useEffect(() => {
const computeCurrentGreeting = () => {
const currentHour = new Date().getHours();
if (currentHour >= 5 && currentHour < 12) {
return "Good morning ☀️";
} else if (currentHour >= 12 && currentHour < 17) {
return "Good afternoon 🌤️";
} else if (currentHour >= 17 && currentHour < 22) {
return "Good evening 🌙";
} else {
return "Burning the midnight oil 🦉";
}
};
setGreeting(computeCurrentGreeting());
}, []);
const { lastSynced } = useDashboardSync();
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!session) {
setIsPublic(null);
return;
}
async function loadSettings() {
try {
const res = await fetch("/api/user/settings");
if (res.ok) {
const data = await res.json();
setIsPublic(data.is_public === true);
} else {
setIsPublic(false);
}
} catch (error) {
console.error("Failed to load settings:", error);
setIsPublic(false);
}
}
loadSettings();
}, [session]);
// Extract a fallback username parameter from active session data strings
const displayName = session?.user?.name || session?.githubLogin || "Developer";
useEffect(() => {
if (!lastSynced) return;
const interval = setInterval(() => {
setNow(Date.now());
}, 60000);
return () => clearInterval(interval);
}, [lastSynced]);
const minutesAgo = lastSynced
? Math.floor((now - lastSynced.getTime()) / 60000)
: null;
return (
<header className="relative mb-8 overflow-hidden rounded-3xl border border-[var(--border)] bg-[var(--card)]/95 p-5 shadow-[var(--shadow-soft)] backdrop-blur-md transition-all duration-300 hover:shadow-[var(--shadow-medium)] md:p-6">
<div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[var(--accent)]/40 to-transparent" />
<div className="pointer-events-none absolute -right-10 -top-12 h-32 w-32 rounded-full bg-[var(--accent)]/10 blur-3xl" />
<div className="flex min-w-0 flex-col gap-5 md:flex-row md:items-end md:justify-between">
{/* Left Section */}
<div>
<div className="flex flex-col gap-1.5">
<div className="flex flex-wrap items-center gap-2">
<div className="inline-flex items-center gap-1.5 rounded-full bg-[var(--accent)]/10 border border-[var(--accent)]/20 px-2.5 py-0.5 text-xs font-semibold text-[var(--accent)] transition-all duration-300">
<span className="relative flex h-1.5 w-1.5">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[var(--accent)] opacity-75"></span>
<span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-[var(--accent)]"></span>
</span>
<span>
{greeting}, {displayName}!
</span>
</div>
{isNightOwl && (
<div
title="Night Owl Milestone: You push code between Midnight and 4 AM!"
className="inline-flex items-center gap-1 rounded-full bg-indigo-500/10 border border-indigo-500/30 px-2 py-0.5 text-[11px] font-bold text-indigo-400 transition-all duration-300 hover:bg-indigo-500/20 cursor-help"
>
<Moon className="h-3 w-3 shrink-0 text-indigo-400" />
<span>Night Owl</span>
</div>
)}
{isEarlyBird && (
<div
title="Early Bird Milestone: You push code between 5 AM and 8 AM!"
className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 border border-amber-500/30 px-2 py-0.5 text-[11px] font-bold text-amber-400 transition-all duration-300 hover:bg-amber-500/20 cursor-help"
>
<Sun className="h-3 w-3 shrink-0 text-amber-400" />
<span>Early Bird</span>
</div>
)}
<div className="flex flex-col gap-1">
{/* Dynamic Personalized Friendly Greeting Badge Element Overlay */}
<div className="inline-flex items-center gap-1.5 self-start rounded-full bg-[var(--accent)]/10 border border-[var(--accent)]/20 px-2.5 py-0.5 text-xs font-semibold text-[var(--accent)] transition-all duration-300">
<span className="relative flex h-1.5 w-1.5">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[var(--accent)] opacity-75"></span>
<span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-[var(--accent)]"></span>
</span>
<span>
{greeting}, {displayName}!
</span>
</div>
<h1 className="bg-gradient-to-r from-[var(--foreground)] via-[var(--foreground)] to-[var(--accent)] bg-clip-text text-3xl font-extrabold text-transparent md:text-4xl mt-1">
Dashboard
</h1>
</div>
<p className="mt-2 text-sm md:text-base text-[var(--muted-foreground)]">
Your coding activity at a glance 🚀
<div className="min-w-0">
<p
className="text-[11px] font-semibold uppercase tracking-[0.24em] text-[var(--muted-foreground)]"
style={{ fontFamily: "var(--font-jetbrains, ui-monospace, monospace)" }}
>
Dashboard overview
</p>
<h1 className="mt-2 bg-gradient-to-r from-[var(--foreground)] via-[var(--foreground)] to-[var(--accent)] bg-clip-text text-3xl font-extrabold text-transparent md:text-4xl">
Dashboard
</h1>
<p
className="mt-2 max-w-xl text-sm leading-6 text-[var(--muted-foreground)]"
style={{ fontFamily: "var(--font-jetbrains, ui-monospace, monospace)", letterSpacing: "0.06em" }}
>
coding activity at a glance
</p>
{minutesAgo !== null && (
<p className="mt-1 text-xs text-[var(--muted-foreground)]">
{minutesAgo <= 0 ? "Synced just now" : `Synced ${minutesAgo} min ago`}
</p>
)}
</div>
{/* Right Section */}
<div className="flex min-w-0 flex-col gap-3 sm:items-end">
<div className="flex flex-wrap items-center gap-3">
{isPublic === true && session?.githubLogin && (
<>
<a
href={`/u/${session.githubLogin}`}
target="_blank"
rel="noopener noreferrer"
className="primary-button inline-flex items-center justify-center rounded-xl px-4 py-2 text-sm font-semibold"
title="View your public profile"
>
Share Profile
</a>
<button
type="button"
onClick={handleCopyLink}
title="Copy profile link to clipboard"
aria-label="Copy profile link"
className="rounded-xl border border-[var(--border)] bg-[var(--card)] hover:bg-[var(--control-hover)] px-3 py-2 text-sm font-medium text-[var(--foreground)] transition-all active:scale-95 whitespace-nowrap"
>
{copied ? "Copied! ✓" : "Copy Link 📋"}
</button>
</>
)}
<div className="flex items-center gap-2 rounded-2xl border border-[var(--border)] bg-[var(--card-muted)]/50 p-2 shadow-sm backdrop-blur-sm">
<div className="transition-transform duration-200 hover:scale-[1.05]">
<KeyboardShortcuts />
</div>
<div className="transition-transform duration-200 hover:scale-[1.05]">
<NotificationBell />
</div>
<div className="transition-transform duration-200 hover:scale-[1.05]">
<UserAvatar />
</div>
<div className="transition-transform duration-200 hover:rotate-12">
<ThemeToggle />
</div>
<div className="transition-transform duration-200 hover:scale-[1.05]">
<SignOutButton />
</div>
</div>
</div>
</div>
</div>
{/* Bottom Toggle */}
<div className="mt-5">
<AccountToggle />
</div>
</header>
);
}