-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAllProblems.tsx
More file actions
760 lines (684 loc) · 22.9 KB
/
Copy pathAllProblems.tsx
File metadata and controls
760 lines (684 loc) · 22.9 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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import { useEffect, useRef, useState, useCallback, useMemo } from "react";
import { AgGridReact } from "ag-grid-react";
import type {
ColDef,
ICellRendererParams,
ITooltipParams,
} from "ag-grid-community";
import {
ModuleRegistry,
AllCommunityModule,
themeQuartz,
} from "ag-grid-community";
import { supabase } from "~/supabase/supabaseClient";
import { ArrowUpRight, CheckCircle2, EyeOff, Eye } from "lucide-react";
import { useAppContext } from "~/context/useAppContext";
import { Badge } from "~/components/ui/badge";
import { getCompanyColor } from "~/utils/companyColors";
import { cn } from "~/lib/utils";
import { Separator } from "~/components/ui/separator";
import { TagFilterDropdown } from "~/components/TagFilterDropdown";
ModuleRegistry.registerModules([AllCommunityModule]);
/* ─────────────────────────────────────────────────────────── */
/* Types */
/* ─────────────────────────────────────────────────────────── */
type Difficulty = "Easy" | "Medium" | "Hard";
type Problem = {
id: number;
title: string;
url: string | null;
difficulty: Difficulty | null;
acceptance: number | null;
frequency: number | null;
tags: string[];
other_companies: string[];
completed: boolean;
timeframe_tag: TimeFrameTag | null;
isToggling?: boolean; // UI-only state to indicate if we're currently toggling completion status
};
type TimeFrameTag = "six-months" | "three-months" | "thirty-days";
/* ─────────────────────────────────────────────────────────── */
/* Constants */
/* ─────────────────────────────────────────────────────────── */
const DIFFICULTY_ORDER: Record<string, number> = {
Easy: 0,
Medium: 1,
Hard: 2,
};
const DIFFICULTY_STYLES: Record<string, string> = {
Easy: "text-emerald-500 bg-emerald-500/10",
Medium: "text-amber-500 bg-amber-500/10",
Hard: "text-rose-500 bg-rose-500/10",
};
/* ─────────────────────────────────────────────────────────── */
/* Helpers */
/* ─────────────────────────────────────────────────────────── */
async function fetchAllProblems() {
const PAGE_SIZE = 4000;
let from = 0;
const allRows: any[] = [];
while (true) {
const { data, error } = await supabase
.from("problems")
.select(
`
id,
title,
url,
difficulty,
acceptance,
frequency,
problem_tags ( tag ),
company_problems (
company:companies ( id, name ),
timeframe_tag
)
`,
)
.range(from, from + PAGE_SIZE - 1);
if (error || !data) break;
allRows.push(...data);
if (data.length < PAGE_SIZE) break;
from += PAGE_SIZE;
}
return allRows;
}
/* ─────────────────────────────────────────────────────────── */
/* Cell Renderers */
/* ─────────────────────────────────────────────────────────── */
function CompletedCellRenderer(props: ICellRendererParams<Problem>) {
const { value, data, api } = props;
if (!data) return null;
const isLoading = (data as any).isToggling;
const handleToggle = async (e: React.MouseEvent) => {
e.stopPropagation();
if (isLoading) return;
const {
data: { session },
} = await supabase.auth.getSession();
if (!session?.user) {
alert("Please sign in to mark problems as completed.");
return;
}
const userId = session.user.id;
const problemId = data.id;
const newCompleted = !value;
// Show loader immediately
const loadingRow = { ...data, isToggling: true };
api.applyTransaction({
update: [loadingRow],
});
// 👇 FORCE CELL REFRESH
api.refreshCells({
rowNodes: [props.node],
force: true,
});
try {
if (newCompleted) {
const { error } = await supabase
.from("user_completed_problems")
.insert({
user_id: userId,
problem_id: problemId,
});
if (error) throw error;
} else {
const { error } = await supabase
.from("user_completed_problems")
.delete()
.eq("user_id", userId)
.eq("problem_id", problemId);
if (error) throw error;
}
// Success → update completed state
api.applyTransaction({
update: [
{
...data,
completed: newCompleted,
isToggling: false,
},
],
});
} catch (err) {
console.error("Toggle failed:", err);
// Rollback + remove loader
api.applyTransaction({
update: [
{
...data,
completed: value,
isToggling: false,
},
],
});
}
};
return (
<div
className={`flex h-full items-center ${
isLoading ? "cursor-not-allowed opacity-50" : "cursor-pointer"
}`}
onClick={handleToggle}
>
{isLoading ? (
<div className="border-primary h-4 w-4 animate-spin rounded-full border-2 border-t-transparent" />
) : value ? (
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
) : (
<div className="border-border h-4 w-4 rounded-full border" />
)}
</div>
);
}
function TitleCellRenderer({ data }: ICellRendererParams<Problem>) {
if (!data) return null;
return (
<div className="flex h-full items-center">
{data.url ? (
<a
href={data.url}
target="_blank"
rel="noopener noreferrer"
className="hover:text-primary group inline-flex items-center gap-1 text-sm font-medium transition-colors"
onClick={(e) => e.stopPropagation()}
>
{data.title}
<ArrowUpRight className="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" />
</a>
) : (
<span className="text-sm font-medium">{data.title}</span>
)}
</div>
);
}
function DifficultyBadgeCellRenderer({ value }: ICellRendererParams) {
if (!value) return <span className="text-muted-foreground text-xs">—</span>;
return (
<div className="flex h-full items-center">
<span
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${DIFFICULTY_STYLES[value] ?? "text-muted-foreground"}`}
>
{value}
</span>
</div>
);
}
function AcceptanceCellRenderer({ value }: ICellRendererParams) {
return (
<div className="text-muted-foreground flex h-full items-center text-xs tabular-nums">
{value != null ? `${Number(value).toFixed(1)}%` : "—"}
</div>
);
}
function FrequencyCellRenderer({ value }: ICellRendererParams) {
if (value == null) {
return (
<div className="text-muted-foreground flex h-full items-center text-xs">
—
</div>
);
}
return (
<div className="flex h-full items-center gap-1.5">
<div className="bg-muted h-1.5 w-14 overflow-hidden rounded-full">
<div
className="bg-primary h-full rounded-full"
style={{ width: `${Math.min(value, 100)}%` }}
/>
</div>
<span className="text-muted-foreground text-xs tabular-nums">
{value.toFixed(0)}%
</span>
</div>
);
}
function TagsTooltip({ value }: ITooltipParams<Problem, string[]>) {
if (!value || value.length === 0) return null;
return (
<div className="bg-background rounded-md border p-2 shadow-lg">
<div className="flex max-w-xs flex-wrap gap-1">
{value.map((tag) => (
<Badge
key={tag}
variant="secondary"
className="text-muted-foreground text-md"
>
{tag}
</Badge>
))}
</div>
</div>
);
}
function TagsCellRenderer({ value }: ICellRendererParams<Problem, string[]>) {
if (!value || value.length === 0) return null;
return (
<div className="gap-y-0. flex h-full flex-wrap items-center gap-x-1">
{value.slice(0, 3).map((tag) => (
<Badge
variant={"secondary"}
className="text-muted-foreground my-0 px-2"
>
{tag}
</Badge>
))}
{value.length > 3 && (
<span className="text-muted-foreground text-[10px]">
+{value.length - 3}
</span>
)}
</div>
);
}
function OtherCompaniesTooltip({ value }: ITooltipParams<Problem, string[]>) {
if (!value || value.length === 0) return null;
return (
<div className="bg-background rounded-md border p-2 shadow-lg">
<div className="flex max-w-xs flex-wrap gap-1">
{value.map((name) => (
<Badge
key={name}
variant="outline"
className={cn(
"text-muted-foreground text-md",
getCompanyColor(name),
)}
>
{name}
</Badge>
))}
</div>
</div>
);
}
function OtherCompaniesCellRenderer({
value,
}: ICellRendererParams<Problem, string[]>) {
if (!value || value.length === 0) return null;
return (
<div className="flex h-full flex-wrap items-center gap-x-0.5 gap-y-0">
{value.slice(0, 3).map((name) => (
<Badge
variant={"outline"}
key={name}
className={cn("text-muted-foreground my-0", getCompanyColor(name))}
>
{name}
</Badge>
))}
{value.length > 3 && (
<span className="text-muted-foreground text-[10px]">
+{value.length - 3}
</span>
)}
</div>
);
}
/* ------------------- MAIN COMPONENT ------------------- */
export default function AllProblems() {
const { theme } = useAppContext();
const [problems, setProblems] = useState<Problem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [search, setSearch] = useState("");
const [diffFilter, setDiffFilter] = useState<Difficulty | "All">("All");
const [allTags, setAllTags] = useState<string[]>([]);
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [tagMatchMode, setTagMatchMode] = useState<"AND" | "OR">("AND");
const [hideCompleted, setHideCompleted] = useState(false);
const gridRef = useRef<AgGridReact<Problem>>(null);
// fetch
useEffect(() => {
async function fetchData() {
setLoading(true);
setError(null);
const data = await fetchAllProblems();
if (!data) {
setError("Failed to fetch problems.");
setLoading(false);
return;
}
let assembled: Problem[] = data.map((p: any) => ({
id: p.id,
title: p.title ?? "Untitled",
url: p.url ?? null,
difficulty: p.difficulty ?? null,
acceptance: p.acceptance ?? null,
frequency: p.frequency ?? null,
tags: p.problem_tags?.map((t: any) => t.tag) ?? [],
other_companies:
p.company_problems
?.map((cp: any) => cp.company?.name)
.filter(Boolean) ?? [],
completed: false,
timeframe_tag: null, // not needed anymore
isToggling: false,
}));
const {
data: { session },
} = await supabase.auth.getSession();
if (session?.user) {
const { data: completedRows } = await supabase
.from("user_completed_problems")
.select("problem_id")
.eq("user_id", session.user.id);
const completedSet = new Set(completedRows?.map((r) => r.problem_id));
assembled = assembled.map((p) => ({
...p,
completed: completedSet.has(p.id),
}));
}
setProblems(assembled);
setLoading(false);
}
fetchData();
}, []);
useEffect(() => {
async function fetchTags() {
const { data, error } = await supabase
.from("unique_problem_tags")
.select("*");
if (error || !data) return;
setAllTags(data.map((t) => t.tag));
}
fetchTags();
}, []);
// filter - AG Grid external filter handles difficulty, tag, and hide completed; quick filter handles search
useEffect(() => {
if (!gridRef.current?.api) return;
// AG Grid external filter handles difficulty; quick filter handles search
gridRef.current.api.setGridOption("quickFilterText", search);
gridRef.current.api.onFilterChanged();
}, [search, diffFilter, selectedTags, tagMatchMode, hideCompleted]);
const isExternalFilterPresent = useCallback(() => {
return diffFilter !== "All" || selectedTags.length > 0 || hideCompleted;
}, [diffFilter, selectedTags, hideCompleted]);
const doesExternalFilterPass = useCallback(
(node: { data?: Problem }) => {
const problem = node.data;
if (!problem) return false;
// Hide completed filter
if (hideCompleted && problem.completed) {
return false;
}
// Difficulty filter
if (diffFilter !== "All" && problem.difficulty !== diffFilter) {
return false;
}
// Tag filter
if (selectedTags.length > 0) {
const problemTags = problem.tags ?? [];
if (tagMatchMode === "AND") {
const matchesAll = selectedTags.every((tag) =>
problemTags.includes(tag),
);
if (!matchesAll) return false;
} else {
const matchesAny = selectedTags.some((tag) =>
problemTags.includes(tag),
);
if (!matchesAny) return false;
}
}
return true;
},
[diffFilter, selectedTags, tagMatchMode, hideCompleted],
);
/* --------------------- Column Defs -------------------- */
const columnDefs = useMemo<ColDef<Problem>[]>(
() => [
{
field: "completed",
headerName: "",
headerComponent: () => (
<div
className="flex h-full cursor-pointer items-center justify-center"
title={hideCompleted ? "Show completed" : "Hide completed"}
onClick={() => setHideCompleted((prev) => !prev)}
>
{hideCompleted ? (
<EyeOff className={`h-4 w-4 text-red-500`} />
) : (
<Eye className={`h-4 w-4`} />
)}
</div>
),
width: 48,
minWidth: 48,
maxWidth: 48,
sortable: false,
filter: false,
cellRenderer: CompletedCellRenderer,
pinned: "left",
},
{
field: "id",
headerName: "#",
width: 72,
minWidth: 60,
sort: null,
comparator: (a, b) => a - b,
},
{
field: "title",
headerName: "Title",
flex: 2,
minWidth: 200,
cellRenderer: TitleCellRenderer,
getQuickFilterText: (params) => params.value,
},
{
field: "difficulty",
headerName: "Difficulty",
width: 120,
cellRenderer: DifficultyBadgeCellRenderer,
comparator: (a, b) =>
(DIFFICULTY_ORDER[a ?? ""] ?? 99) - (DIFFICULTY_ORDER[b ?? ""] ?? 99),
},
{
field: "acceptance",
headerName: "Acceptance",
width: 110,
cellRenderer: AcceptanceCellRenderer,
comparator: (a, b) => (a ?? -1) - (b ?? -1),
},
{
field: "frequency",
headerName: "Frequency",
headerTooltip: "How frequently this problem is asked at this company.",
width: 150,
sort: "desc",
filter: "agNumberColumnFilter",
cellRenderer: FrequencyCellRenderer,
comparator: (a, b) => (a ?? -1) - (b ?? -1),
},
{
field: "tags",
headerName: "Tags",
flex: 1.5,
minWidth: 150,
sortable: false,
filter: false,
cellRenderer: TagsCellRenderer,
tooltipComponent: TagsTooltip,
tooltipValueGetter: (params) => params.value,
},
{
field: "other_companies",
headerName: "Also Asked At",
flex: 1.5,
minWidth: 150,
filter: false,
cellRenderer: OtherCompaniesCellRenderer,
comparator: (a, b) => (b?.length ?? 0) - (a?.length ?? 0),
tooltipComponent: OtherCompaniesTooltip,
tooltipValueGetter: (params) => params.value,
},
],
[hideCompleted],
);
const defaultColDef = useMemo<ColDef>(
() => ({
sortable: true,
filter: false,
resizable: true,
suppressMovable: false,
cellStyle: { display: "flex", alignItems: "center" },
}),
[],
);
/* ------------------------ Stats ----------------------- */
const easyCnt = problems.filter((p) => p.difficulty === "Easy").length;
const medCnt = problems.filter((p) => p.difficulty === "Medium").length;
const hardCnt = problems.filter((p) => p.difficulty === "Hard").length;
const completedCnt = problems.filter((p) => p.completed).length;
if (loading) {
return (
<div className="flex items-center justify-center">
<div className="border-primary h-7 w-7 animate-spin rounded-full border-2 border-t-transparent" />
</div>
);
}
if (error) {
return (
<div className="flex min-h-screen items-center justify-center">
<p className="text-muted-foreground">{error}</p>
</div>
);
}
return (
<div className="font-geist bg-background text-primary flex flex-col">
{/* Header */}
<div className="border-border border-b px-6 py-6">
<div className="mx-auto sm:px-8 md:px-16">
<div className="flex items-center justify-between gap-4">
<div>
<h1 className="text-3xl font-semibold capitalize">
All Problems
</h1>
</div>
<div className="flex flex-col items-center">
<div className="flex gap-6">
{[
{ label: "Easy", count: easyCnt, style: "text-emerald-500" },
{ label: "Medium", count: medCnt, style: "text-amber-500" },
{ label: "Hard", count: hardCnt, style: "text-rose-500" },
].map(({ label, count, style }) => (
<div key={label} className="text-center">
<div
className={`text-sm font-semibold tabular-nums sm:text-2xl ${style}`}
>
{count}
</div>
<div className="text-muted-foreground text-xs">{label}</div>
</div>
))}
</div>
<Separator className="mt-1.5" />
<p className="text-muted-foreground mt-1 text-xs sm:text-sm">
{problems.length} problems · {completedCnt} completed
</p>
</div>
</div>
{/* Filters */}
<div className="mt-6 flex flex-wrap items-center gap-3 sm:mt-2">
<input
type="text"
placeholder="Filter problems…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="bg-muted/20 border-border text-primary placeholder:text-muted-foreground h-8 rounded-md border px-3 text-sm outline-none focus:ring-1 focus:ring-white/10"
/>
<div className="flex items-center gap-1">
{(["All", "Easy", "Medium", "Hard"] as const).map((d) => (
<button
key={d}
onClick={() => setDiffFilter(d)}
className={`h-7 cursor-pointer rounded-md px-3 text-xs font-medium transition-colors ${
diffFilter === d
? d === "All"
? "bg-primary text-primary-foreground"
: d === "Easy"
? "bg-emerald-500/20 text-emerald-500"
: d === "Medium"
? "bg-amber-500/20 text-amber-500"
: "bg-rose-500/20 text-rose-500"
: "text-muted-foreground hover:text-primary hover:bg-muted/40"
}`}
>
{d}
</button>
))}
</div>
<Separator orientation="vertical" className="h-5" />
<TagFilterDropdown
allTags={allTags}
selectedTags={selectedTags}
setSelectedTags={setSelectedTags}
tagMatchMode={tagMatchMode}
setTagMatchMode={setTagMatchMode}
/>
</div>
</div>
</div>
{/* AG Grid */}
<div className="flex-1 px-6 py-4">
<div
className="max-w-9xl mx-auto"
style={{ height: "calc(100vh - 260px)" }}
>
<div
className={`h-full w-full ${
theme === "light" ? "ag-theme-quartz" : "ag-theme-quartz-dark"
}`}
>
<AgGridReact
ref={gridRef}
rowData={problems}
columnDefs={columnDefs}
defaultColDef={defaultColDef}
rowHeight={56}
tooltipShowDelay={300}
tooltipShowMode="standard"
headerHeight={40}
theme={themeQuartz
.withParams({
cellFontFamily: "geist, sans-serif",
})
.withParams(
theme === "light"
? {
rowBorder: {
style: "solid",
width: "2px",
color: "#e5e7eb",
},
}
: {
rowBorder: {
style: "solid",
width: "1px",
color: "#2e3135",
},
rowHoverColor: "#151515", // charcoal-700
backgroundColor: "#0a0a0a",
foregroundColor: "#bfbfbf", // charcoal-100
browserColorScheme: "dark", // to change scrollbar color
},
)}
animateRows
suppressCellFocus
isExternalFilterPresent={isExternalFilterPresent}
doesExternalFilterPass={doesExternalFilterPass}
getRowId={(params) => params.data.id.toString()}
onGridReady={(params) => {
params.api.setGridOption("quickFilterText", search);
}}
/>
</div>
</div>
</div>
</div>
);
}