-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathreposTable.tsx
More file actions
513 lines (480 loc) · 19 KB
/
reposTable.tsx
File metadata and controls
513 lines (480 loc) · 19 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
"use client"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants"
import { cn, getCodeHostCommitUrl, getCodeHostIcon, getRepoImageSrc, isServiceError } from "@/lib/utils"
import {
type ColumnDef,
type VisibilityState,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table"
import { cva } from "class-variance-authority"
import { ArrowDown, ArrowUp, ArrowUpDown, Loader2, RefreshCwIcon } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { useEffect, useRef, useState } from "react"
import { getBrowsePath } from "../../browse/hooks/utils"
import { useRouter, useSearchParams, usePathname } from "next/navigation"
import { useToast } from "@/components/hooks/use-toast";
import { DisplayDate } from "../../components/DisplayDate"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { NotificationDot } from "../../components/notificationDot"
import { CodeHostType } from "@sourcebot/db"
import { useHotkeys } from "react-hotkeys-hook"
import { indexRepo } from "@/features/workerApi/actions"
import { RepoActionsDropdown } from "./repoActionsDropdown"
// @see: https://v0.app/chat/repo-indexing-status-uhjdDim8OUS
export type Repo = {
id: number
name: string
displayName: string | null
isArchived: boolean
isPublic: boolean
indexedAt: Date | null
createdAt: Date
webUrl: string | null
codeHostType: CodeHostType
imageUrl: string | null
indexedCommitHash: string | null
latestJobStatus: "PENDING" | "IN_PROGRESS" | "COMPLETED" | "FAILED" | null
isFirstTimeIndex: boolean
}
const statusBadgeVariants = cva("", {
variants: {
status: {
PENDING: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
IN_PROGRESS: "bg-primary text-primary-foreground hover:bg-primary/90",
COMPLETED: "bg-green-600 text-white hover:bg-green-700",
FAILED: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
},
},
})
const getStatusBadge = (status: Repo["latestJobStatus"]) => {
if (!status) {
return "-";
}
const labels = {
PENDING: "Pending",
IN_PROGRESS: "In Progress",
COMPLETED: "Completed",
FAILED: "Failed",
}
return <Badge className={statusBadgeVariants({ status })}>{labels[status]}</Badge>
}
interface ColumnsContext {
onSortChange: (sortBy: string) => void;
currentSortBy?: string;
currentSortOrder: string;
onTriggerSync: (repoId: number) => void;
}
export const getColumns = (context: ColumnsContext): ColumnDef<Repo>[] => [
{
accessorKey: "displayName",
size: 400,
header: () => {
const isActive = context.currentSortBy === 'displayName';
const Icon = isActive
? (context.currentSortOrder === 'asc' ? ArrowUp : ArrowDown)
: ArrowUpDown;
return (
<Button
variant="ghost"
onClick={() => context.onSortChange('displayName')}
>
Repository
<Icon className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const repo = row.original;
const codeHostIcon = getCodeHostIcon(repo.codeHostType);
const repoImageSrc = repo.imageUrl ? getRepoImageSrc(repo.imageUrl, repo.id) : undefined;
// Internal API routes require authentication headers (cookies/API keys) to be passed through.
// Next.js Image Optimization doesn't forward these headers, so we use unoptimized=true
// to bypass the optimization and make direct requests that include auth headers.
const isInternalApiImage = repoImageSrc?.startsWith('/api/');
return (
<div className="flex flex-row gap-2 items-center">
{
repoImageSrc ? (
<Image
src={repoImageSrc}
alt={`${repo.displayName} logo`}
width={32}
height={32}
className="object-cover"
unoptimized={isInternalApiImage}
/>
) : <Image
src={codeHostIcon.src}
alt={`${repo.displayName} logo`}
width={32}
height={32}
className={cn(codeHostIcon.className)}
/>
}
{/* Link to the details page (instead of browse) when the repo is indexing
as the code will not be available yet */}
<Link
href={repo.isFirstTimeIndex ? `/${SINGLE_TENANT_ORG_DOMAIN}/repos/${repo.id}` : getBrowsePath({
repoName: repo.name,
path: '/',
pathType: 'tree',
domain: SINGLE_TENANT_ORG_DOMAIN,
})}
className="font-medium hover:underline"
>
<span>{repo.displayName || repo.name}</span>
</Link>
{repo.isFirstTimeIndex && (
<Tooltip>
<TooltipTrigger asChild>
<span>
<NotificationDot className="ml-1.5" />
</span>
</TooltipTrigger>
<TooltipContent>
<span>This is the first time Sourcebot is indexing this repository. It may take a few minutes to complete.</span>
</TooltipContent>
</Tooltip>
)}
</div>
)
},
},
{
accessorKey: "latestJobStatus",
size: 150,
header: "Latest status",
cell: ({ row }) => getStatusBadge(row.getValue("latestJobStatus")),
},
{
accessorKey: "indexedAt",
size: 200,
header: () => {
const isActive = context.currentSortBy === 'indexedAt';
const Icon = isActive
? (context.currentSortOrder === 'asc' ? ArrowUp : ArrowDown)
: ArrowUpDown;
return (
<Button
variant="ghost"
onClick={() => context.onSortChange('indexedAt')}
>
Last synced
<Icon className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const indexedAt = row.getValue("indexedAt") as Date | null;
if (!indexedAt) {
return "-";
}
return (
<DisplayDate date={indexedAt} className="ml-3" />
)
}
},
{
accessorKey: "indexedCommitHash",
size: 150,
header: "Synced commit",
cell: ({ row }) => {
const hash = row.getValue("indexedCommitHash") as string | null;
if (!hash) {
return "-";
}
const smallHash = hash.slice(0, 7);
const repo = row.original;
const codeHostType = repo.codeHostType;
const webUrl = repo.webUrl;
const commitUrl = getCodeHostCommitUrl({
webUrl,
codeHostType,
commitHash: hash,
});
const HashComponent = commitUrl ? (
<Link
href={commitUrl}
className="font-mono text-sm text-link hover:underline"
>
{smallHash}
</Link>
) : (
<span className="font-mono text-sm text-muted-foreground">
{smallHash}
</span>
)
return (
<Tooltip>
<TooltipTrigger asChild>
{HashComponent}
</TooltipTrigger>
<TooltipContent>
<span className="font-mono">{hash}</span>
</TooltipContent>
</Tooltip>
);
},
},
{
id: "actions",
size: 80,
enableHiding: false,
cell: ({ row }) => {
const repo = row.original
return <RepoActionsDropdown repo={repo} />
},
},
]
interface ReposTableProps {
data: Repo[];
currentPage: number;
pageSize: number;
totalCount: number;
initialSearch: string;
initialStatus: string;
initialSortBy?: string;
initialSortOrder: string;
stats: {
numCompleted: number
numFailed: number
numPending: number
numInProgress: number
numNoJobs: number
}
}
export const ReposTable = ({
data,
currentPage,
pageSize,
totalCount,
initialSearch,
initialStatus,
initialSortBy,
initialSortOrder,
stats,
}: ReposTableProps) => {
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [rowSelection, setRowSelection] = useState({})
const [searchValue, setSearchValue] = useState(initialSearch)
const [isPendingSearch, setIsPendingSearch] = useState(false)
const searchInputRef = useRef<HTMLInputElement>(null)
const router = useRouter();
const searchParams = useSearchParams();
const pathname = usePathname();
const { toast } = useToast();
// Focus search box when '/' is pressed
useHotkeys('/', (event) => {
event.preventDefault();
searchInputRef.current?.focus();
});
// Debounced search effect - only runs when searchValue changes
useEffect(() => {
setIsPendingSearch(true);
const timer = setTimeout(() => {
const params = new URLSearchParams(searchParams.toString());
if (searchValue) {
params.set('search', searchValue);
} else {
params.delete('search');
}
params.set('page', '1'); // Reset to page 1 on search
router.replace(`${pathname}?${params.toString()}`);
setIsPendingSearch(false);
}, 300);
return () => {
clearTimeout(timer);
setIsPendingSearch(false);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchValue]);
const updateStatusFilter = (value: string) => {
const params = new URLSearchParams(searchParams.toString());
if (value === 'all') {
params.delete('status');
} else {
params.set('status', value);
}
params.set('page', '1'); // Reset to page 1 on filter change
router.replace(`${pathname}?${params.toString()}`);
};
const handleSortChange = (sortBy: string) => {
const params = new URLSearchParams(searchParams.toString());
// Toggle sort order if clicking the same column
if (initialSortBy === sortBy) {
const newOrder = initialSortOrder === 'asc' ? 'desc' : 'asc';
params.set('sortOrder', newOrder);
} else {
// Default to ascending when changing columns
params.set('sortBy', sortBy);
params.set('sortOrder', 'asc');
}
params.set('page', '1'); // Reset to page 1 on sort change
router.replace(`${pathname}?${params.toString()}`);
};
const handleTriggerSync = async (repoId: number) => {
const response = await indexRepo(repoId);
if (!isServiceError(response)) {
const { jobId } = response;
toast({
description: `✅ Repository sync triggered successfully. Job ID: ${jobId}`,
});
router.refresh();
} else {
toast({
description: `❌ Failed to sync repository. ${response.message}`,
});
}
};
const totalPages = Math.ceil(totalCount / pageSize);
const columns = getColumns({
onSortChange: handleSortChange,
currentSortBy: initialSortBy,
currentSortOrder: initialSortOrder,
onTriggerSync: handleTriggerSync
});
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
columnResizeMode: 'onChange',
enableColumnResizing: false,
state: {
columnVisibility,
rowSelection,
},
})
return (
<div className="w-full">
<div className="flex items-center gap-4 py-4">
<InputGroup className="max-w-sm">
<InputGroupInput
ref={searchInputRef}
placeholder="Filter repositories..."
value={searchValue}
onChange={(event) => setSearchValue(event.target.value)}
className="ring-0"
/>
{isPendingSearch && (
<InputGroupAddon align="inline-end">
<Loader2 className="h-4 w-4 animate-spin" />
</InputGroupAddon>
)}
</InputGroup>
<Select
value={initialStatus}
onValueChange={updateStatusFilter}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filter by status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Filter by status</SelectItem>
<SelectItem value="COMPLETED">Completed ({stats.numCompleted})</SelectItem>
<SelectItem value="IN_PROGRESS">In progress ({stats.numInProgress})</SelectItem>
<SelectItem value="PENDING">Pending ({stats.numPending})</SelectItem>
<SelectItem value="FAILED">Failed ({stats.numFailed})</SelectItem>
<SelectItem value="none">No status ({stats.numNoJobs})</SelectItem>
</SelectContent>
</Select>
<Button
variant="outline"
className="ml-auto"
onClick={() => {
router.refresh();
toast({
description: "Page refreshed",
});
}}
>
<RefreshCwIcon className="w-3 h-3" />
Refresh
</Button>
</div>
<div className="rounded-md border">
<Table style={{ width: '100%' }}>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead
key={header.id}
style={{ width: `${header.getSize()}px` }}
>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
style={{ width: `${cell.column.getSize()}px` }}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-end space-x-2 py-4">
<div className="flex-1 text-sm text-muted-foreground">
{totalCount} {totalCount !== 1 ? 'repositories' : 'repository'} total
{totalPages > 1 && ` • Page ${currentPage} of ${totalPages}`}
</div>
<div className="space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => {
const params = new URLSearchParams(searchParams.toString());
params.set('page', String(currentPage - 1));
router.push(`${pathname}?${params.toString()}`);
}}
disabled={currentPage <= 1}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
const params = new URLSearchParams(searchParams.toString());
params.set('page', String(currentPage + 1));
router.push(`${pathname}?${params.toString()}`);
}}
disabled={currentPage >= totalPages}
>
Next
</Button>
</div>
</div>
</div>
)
}