forked from recodehive/recode-website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatsProvider.tsx
More file actions
594 lines (515 loc) · 18.1 KB
/
statsProvider.tsx
File metadata and controls
594 lines (515 loc) · 18.1 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { githubService, type GitHubOrgStats } from "../services/githubService";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
// Time filter types
export type TimeFilter = "week" | "month" | "year" | "all";
interface ICommunityStatsContext {
githubStarCount: number;
githubStarCountText: string;
githubContributorsCount: number;
githubContributorsCountText: string;
githubForksCount: number;
githubForksCountText: string;
githubReposCount: number;
githubReposCountText: string;
githubDiscussionsCount: number;
githubDiscussionsCountText: string;
loading: boolean;
error: string | null;
lastUpdated: Date | null;
refetch: (signal: AbortSignal) => Promise<void>;
clearCache: () => void;
// Leaderboard properties
contributors: Contributor[];
stats: Stats | null;
// New time filter properties
currentTimeFilter: TimeFilter;
setTimeFilter: (filter: TimeFilter) => void;
getFilteredPRsForContributor: (username: string) => PRDetails[];
}
// Define types for leaderboard data
interface PRDetails {
title: string;
url: string;
mergedAt: string;
repoName: string;
number: number;
points: number;
}
interface Contributor {
username: string;
avatar: string;
profile: string;
points: number;
prs: number;
prDetails?: PRDetails[];
}
interface Stats {
flooredTotalPRs: number;
totalContributors: number;
flooredTotalPoints: number;
}
interface PullRequestItem {
user: {
login: string;
avatar_url: string;
html_url: string;
};
merged_at?: string | null;
title?: string;
html_url?: string;
number?: number;
labels?: Array<{ name: string }>;
}
// Enhanced contributor type for internal processing (stores all PRs)
interface FullContributor extends Omit<Contributor, "points" | "prs"> {
allPRDetails: PRDetails[]; // All PRs regardless of filter
points: number; // Filtered points
prs: number; // Filtered PR count
}
export const CommunityStatsContext = createContext<
ICommunityStatsContext | undefined
>(undefined);
interface CommunityStatsProviderProps {
children: ReactNode;
}
const GITHUB_ORG = "recodehive";
const POINTS_PER_PR = 10;
const MAX_CONCURRENT_REQUESTS = 15;
const CACHE_DURATION = 20 * 60 * 1000; // 20 minutes cache
const MAX_PAGES_PER_REPO = 10;
// Function to calculate points based on PR labels
const calculatePointsForPR = (labels?: Array<{ name: string }>): number => {
if (!labels || labels.length === 0) {
return 0; // No points if no labels
}
const labelNames = labels.map((label) => label.name.toLowerCase());
// Check if PR has the "recode" label
if (!labelNames.includes("recode")) {
return 0; // No points if "recode" label is missing
}
// Check for level labels and assign points accordingly with new point system
const levelPointsMap: { [key: string]: number } = {
"level 1": 10,
"level 2": 30,
"level 3": 50,
};
const matchedLevel = labelNames.find((label) =>
levelPointsMap.hasOwnProperty(label),
);
if (matchedLevel) {
return levelPointsMap[matchedLevel];
}
return 0; // No points if no level label
};
// Time filter utility functions
const getTimeFilterDate = (filter: TimeFilter): Date | null => {
const now = new Date();
switch (filter) {
case "week":
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case "month": {
const lastMonth = new Date(now);
lastMonth.setMonth(now.getMonth() - 1);
return lastMonth;
}
case "year":
return new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
case "all":
default:
return null; // No filter
}
};
const isPRInTimeRange = (mergedAt: string, filter: TimeFilter): boolean => {
if (filter === "all") return true;
const filterDate = getTimeFilterDate(filter);
if (!filterDate) return true;
const prDate = new Date(mergedAt);
return prDate >= filterDate;
};
export function CommunityStatsProvider({
children,
}: CommunityStatsProviderProps) {
const {
siteConfig: { customFields },
} = useDocusaurusContext();
const token = customFields?.gitToken || "";
const [loading, setLoading] = useState(false); // Start with false to avoid hourglass
const [error, setError] = useState<string | null>(null);
const [githubStarCount, setGithubStarCount] = useState(984); // Placeholder value - updated to match production
const [githubContributorsCount, setGithubContributorsCount] = useState(467); // Placeholder value - updated to match production
const [githubForksCount, setGithubForksCount] = useState(1107); // Placeholder value - updated to match production
const [githubReposCount, setGithubReposCount] = useState(10); // Placeholder value - updated to match production
const [githubDiscussionsCount, setGithubDiscussionsCount] = useState(0);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
// Time filter state
const [currentTimeFilter, setCurrentTimeFilter] =
useState<TimeFilter>("week");
// Enhanced state for leaderboard data (stores all contributors with full PR history)
const [allContributors, setAllContributors] = useState<FullContributor[]>([]);
const [stats, setStats] = useState<Stats | null>(null);
// Cache state (stores raw data without filters)
const [cache, setCache] = useState<{
data: {
contributors: FullContributor[];
rawStats: { totalPRs: number };
} | null;
timestamp: number;
}>({ data: null, timestamp: 0 });
// Computed filtered contributors based on current time filter
const contributors = useMemo(() => {
if (!allContributors.length) return [];
const filteredContributors = allContributors
.map((contributor) => {
const filteredPRs = contributor.allPRDetails.filter((pr) =>
isPRInTimeRange(pr.mergedAt, currentTimeFilter),
);
// Calculate total points from all filtered PRs
const totalPoints = filteredPRs.reduce((sum, pr) => sum + pr.points, 0);
return {
username: contributor.username,
avatar: contributor.avatar,
profile: contributor.profile,
points: totalPoints,
prs: filteredPRs.length,
prDetails: filteredPRs, // For backward compatibility, though we'll use the new function
};
})
.filter((contributor) => contributor.prs > 0) // Only show contributors with PRs in the time range
.sort((a, b) => b.points - a.points || b.prs - a.prs);
return filteredContributors;
}, [allContributors, currentTimeFilter]);
// Update stats when contributors change
useEffect(() => {
if (contributors.length > 0) {
setStats({
flooredTotalPRs: contributors.reduce((sum, c) => sum + c.prs, 0),
totalContributors: contributors.length,
flooredTotalPoints: contributors.reduce((sum, c) => sum + c.points, 0),
});
}
}, [contributors]);
// Function to get filtered PRs for a specific contributor (for PR view modal)
const getFilteredPRsForContributor = useCallback(
(username: string): PRDetails[] => {
const contributor = allContributors.find((c) => c.username === username);
if (!contributor) return [];
return contributor.allPRDetails
.filter((pr) => isPRInTimeRange(pr.mergedAt, currentTimeFilter))
.sort(
(a, b) =>
new Date(b.mergedAt).getTime() - new Date(a.mergedAt).getTime(),
); // Sort by newest first
},
[allContributors, currentTimeFilter],
);
// Time filter setter function
const setTimeFilter = useCallback((filter: TimeFilter) => {
setCurrentTimeFilter(filter);
}, []);
const fetchAllOrgRepos = useCallback(
async (headers: Record<string, string>) => {
const repos: any[] = [];
let page = 1;
while (true) {
const resp = await fetch(
`https://api.github.com/orgs/${GITHUB_ORG}/repos?type=public&per_page=100&page=${page}`,
{
headers,
},
);
if (!resp.ok) {
throw new Error(
`Failed to fetch org repos: ${resp.status} ${resp.statusText}`,
);
}
const data = await resp.json();
repos.push(...data);
if (!Array.isArray(data) || data.length < 100) break;
page++;
}
return repos;
},
[],
);
const fetchMergedPRsForRepo = useCallback(
async (repoName: string, headers: Record<string, string>) => {
const mergedPRs: PullRequestItem[] = [];
// First, get the first page to estimate total pages
const firstResp = await fetch(
`https://api.github.com/repos/${GITHUB_ORG}/${repoName}/pulls?state=closed&per_page=100&page=1`,
{ headers },
);
if (!firstResp.ok) {
console.warn(
`Failed to fetch PRs for ${repoName}: ${firstResp.status} ${firstResp.statusText}`,
);
return [];
}
const firstPRs: PullRequestItem[] = await firstResp.json();
if (!Array.isArray(firstPRs) || firstPRs.length === 0) return [];
const firstPageMerged = firstPRs.filter((pr) => Boolean(pr.merged_at));
mergedPRs.push(...firstPageMerged);
// If we got less than 100, that's all there is
if (firstPRs.length < 100) return mergedPRs;
// Create parallel requests for remaining pages
const pagePromises: Promise<PullRequestItem[]>[] = [];
const maxPages = Math.min(MAX_PAGES_PER_REPO, 10);
for (let i = 2; i <= maxPages; i++) {
pagePromises.push(
fetch(
`https://api.github.com/repos/${GITHUB_ORG}/${repoName}/pulls?state=closed&per_page=100&page=${i}`,
{ headers },
)
.then(async (resp) => {
if (!resp.ok) return [];
const prs: PullRequestItem[] = await resp.json();
if (!Array.isArray(prs)) return [];
return prs.filter((pr) => Boolean(pr.merged_at));
})
.catch(() => []),
);
}
// Wait for all pages in parallel
const remainingPages = await Promise.all(pagePromises);
remainingPages.forEach((pagePRs) => {
if (pagePRs.length > 0) mergedPRs.push(...pagePRs);
});
return mergedPRs;
},
[],
);
// Enhanced processing function that stores only valid PRs with points
const processBatch = useCallback(
async (
repos: any[],
headers: Record<string, string>,
): Promise<{
contributorMap: Map<string, FullContributor>;
totalMergedPRs: number;
}> => {
const contributorMap = new Map<string, FullContributor>();
let totalMergedPRs = 0;
// Process repos in batches to control concurrency
for (let i = 0; i < repos.length; i += MAX_CONCURRENT_REQUESTS) {
const batch = repos.slice(i, i + MAX_CONCURRENT_REQUESTS);
const promises = batch.map(async (repo) => {
if (repo.archived) return { mergedPRs: [], repoName: repo.name };
try {
const mergedPRs = await fetchMergedPRsForRepo(repo.name, headers);
return { mergedPRs, repoName: repo.name };
} catch (error) {
console.warn(`Skipping repo ${repo.name} due to error:`, error);
return { mergedPRs: [], repoName: repo.name };
}
});
// Wait for current batch to complete
const results = await Promise.all(promises);
// Process results from this batch
results.forEach(({ mergedPRs, repoName }) => {
mergedPRs.forEach((pr) => {
// Calculate points for this PR based on labels
const prPoints = calculatePointsForPR(pr.labels);
// ONLY store PRs that have points (i.e., have "recode" label and a level label)
if (prPoints > 0) {
totalMergedPRs++;
const username = pr.user.login;
if (!contributorMap.has(username)) {
contributorMap.set(username, {
username,
avatar: pr.user.avatar_url,
profile: pr.user.html_url,
points: 0, // Will be calculated later based on filter
prs: 0, // Will be calculated later based on filter
allPRDetails: [], // Store only valid PRs here
});
}
const contributor = contributorMap.get(username)!;
// Add detailed PR information only if it has all required fields
if (pr.title && pr.html_url && pr.merged_at && pr.number) {
contributor.allPRDetails.push({
title: pr.title,
url: pr.html_url,
mergedAt: pr.merged_at,
repoName,
number: pr.number,
points: prPoints,
});
}
}
});
});
}
return { contributorMap, totalMergedPRs };
},
[fetchMergedPRsForRepo],
);
const fetchAllStats = useCallback(
async (signal: AbortSignal) => {
// Check cache first and load it immediately without showing loading state
const now = Date.now();
const isCacheValid = cache.data && now - cache.timestamp < CACHE_DURATION;
if (isCacheValid) {
// Use cached data immediately
setAllContributors(cache.data.contributors);
setLoading(false);
return;
}
// If cache is expired or empty, show cached data anyway but fetch fresh data
// This provides immediate content while updating in the background
if (cache.data) {
setAllContributors(cache.data.contributors);
setLoading(false); // Don't show loading state for background refresh
} else {
setLoading(true); // Only show loading on first load
}
setError(null);
if (!token) {
setError(
"GitHub token not found. Please set customFields.gitToken in docusaurus.config.js.",
);
setLoading(false);
return;
}
try {
const headers: Record<string, string> = {
Authorization: `token ${token}`,
Accept: "application/vnd.github.v3+json",
};
// Fetch both org stats and repos in parallel
const [orgStats, repos] = await Promise.all([
githubService.fetchOrganizationStats(signal),
fetchAllOrgRepos(headers),
]);
// Set org stats immediately
setGithubStarCount(orgStats.totalStars);
setGithubContributorsCount(orgStats.totalContributors);
setGithubForksCount(orgStats.totalForks);
setGithubReposCount(orgStats.publicRepositories);
setGithubDiscussionsCount(orgStats.discussionsCount);
setLastUpdated(new Date(orgStats.lastUpdated));
// Process leaderboard data with concurrent processing
const { contributorMap, totalMergedPRs } = await processBatch(
repos,
headers,
);
const contributorsArray = Array.from(contributorMap.values());
setAllContributors(contributorsArray);
// Cache the results (raw data without filtering)
setCache({
data: {
contributors: contributorsArray,
rawStats: { totalPRs: totalMergedPRs },
},
timestamp: now,
});
} catch (err: any) {
if (err.name !== "AbortError") {
console.error("Error fetching GitHub organization stats:", err);
setError(
err instanceof Error ? err.message : "Failed to fetch GitHub stats",
);
// Set fallback values on error
setGithubStarCount(0);
setGithubContributorsCount(140);
setGithubForksCount(0);
setGithubReposCount(20);
setGithubDiscussionsCount(0);
}
} finally {
setLoading(false);
}
},
[token, fetchAllOrgRepos, processBatch, cache],
);
const clearCache = useCallback(() => {
githubService.clearCache();
setCache({ data: null, timestamp: 0 });
const abortController = new AbortController();
fetchAllStats(abortController.signal);
}, [fetchAllStats]);
useEffect(() => {
const abortController = new AbortController();
fetchAllStats(abortController.signal);
return () => {
abortController.abort();
};
}, [fetchAllStats]);
const githubStarCountText = useMemo(
() => convertStatToText(githubStarCount),
[githubStarCount],
);
const githubContributorsCountText = useMemo(
() => convertStatToText(githubContributorsCount),
[githubContributorsCount],
);
const githubForksCountText = useMemo(
() => convertStatToText(githubForksCount),
[githubForksCount],
);
const githubReposCountText = useMemo(
() => convertStatToText(githubReposCount),
[githubReposCount],
);
const githubDiscussionsCountText = useMemo(
() => convertStatToText(githubDiscussionsCount),
[githubDiscussionsCount],
);
const value: ICommunityStatsContext = {
githubStarCount,
githubStarCountText,
githubContributorsCount,
githubContributorsCountText,
githubForksCount,
githubForksCountText,
githubReposCount,
githubReposCountText,
githubDiscussionsCount,
githubDiscussionsCountText,
loading,
error,
lastUpdated,
refetch: fetchAllStats,
clearCache,
contributors,
stats,
currentTimeFilter,
setTimeFilter,
getFilteredPRsForContributor,
};
return (
<CommunityStatsContext.Provider value={value}>
{children}
</CommunityStatsContext.Provider>
);
}
export const useCommunityStatsContext = (): ICommunityStatsContext => {
const context = useContext(CommunityStatsContext);
if (context === undefined) {
throw new Error(
"useCommunityStatsContext must be used within a CommunityStatsProvider",
);
}
return context;
};
export const convertStatToText = (num: number): string => {
const hasIntlSupport =
typeof Intl === "object" && Intl && typeof Intl.NumberFormat === "function";
if (!hasIntlSupport) {
return `${(num / 1000).toFixed(1)}k`;
}
const formatter = new Intl.NumberFormat("en-US", {
notation: "compact",
compactDisplay: "short",
maximumSignificantDigits: 3,
});
return formatter.format(num);
};