question-bank-framework 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +105 -2
  2. package/bin/qb.js +119 -0
  3. package/bin/qb.ts +128 -0
  4. package/core/config.tsx +38 -0
  5. package/core/index.ts +17 -0
  6. package/core/types.ts +111 -0
  7. package/framework/components/app-shell.tsx +54 -0
  8. package/framework/components/filter-builder.tsx +471 -0
  9. package/framework/components/markdown-content.tsx +109 -0
  10. package/framework/components/question-bank.tsx +654 -0
  11. package/framework/components/quiz-list.tsx +110 -0
  12. package/framework/components/quiz-page.tsx +240 -0
  13. package/framework/components/ui/badge.tsx +47 -0
  14. package/framework/components/ui/button.tsx +63 -0
  15. package/framework/components/ui/checkbox.tsx +29 -0
  16. package/framework/components/ui/dropdown-menu.tsx +256 -0
  17. package/framework/components/ui/input.tsx +20 -0
  18. package/framework/components/ui/popover.tsx +88 -0
  19. package/framework/components/ui/select.tsx +187 -0
  20. package/framework/components/ui/sheet.tsx +140 -0
  21. package/framework/components/ui/table.tsx +121 -0
  22. package/framework/convex/questionStatuses.ts +30 -0
  23. package/framework/convex/quizzes.ts +50 -0
  24. package/framework/convex/schema.ts +18 -0
  25. package/framework/index.ts +26 -0
  26. package/framework/lib/convex-api.ts +36 -0
  27. package/framework/lib/question-filter-store.ts +116 -0
  28. package/framework/lib/question-filter.ts +362 -0
  29. package/framework/lib/question-status-storage.ts +117 -0
  30. package/framework/lib/quiz-storage.ts +118 -0
  31. package/framework/lib/utils.ts +6 -0
  32. package/package.json +65 -3
  33. package/template/bank.config.ts +72 -0
  34. package/template/content/answers.ts +6 -0
  35. package/template/content/questions.json +35 -0
  36. package/template/src/routes/__root.tsx +44 -0
  37. package/template/src/routes/index.tsx +4 -0
  38. package/template/src/routes/quiz.$quizId.tsx +4 -0
  39. package/template/src/routes/quizzes.tsx +4 -0
@@ -0,0 +1,654 @@
1
+ // Framework-owned: eject with `qb reveal framework/components/question-bank.tsx`.
2
+ // Generic grid: columns + filters derive from bank.fields (config-defined
3
+ // schema). Built-ins: select, id, title, tags, status.
4
+
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
6
+ import { useNavigate } from '@tanstack/react-router';
7
+ import { useVirtualizer } from '@tanstack/react-virtual';
8
+ import {
9
+ flexRender,
10
+ getCoreRowModel,
11
+ getFilteredRowModel,
12
+ getSortedRowModel,
13
+ useReactTable,
14
+ type ColumnDef,
15
+ type RowSelectionState,
16
+ type SortingState,
17
+ } from '@tanstack/react-table';
18
+ import { Search } from 'lucide-react';
19
+ import { useBank } from '../../core/config.tsx';
20
+ import type { BaseQuestion, QuestionStatus, QuestionStatusMap } from '../../core/types.ts';
21
+ import { Badge } from './ui/badge';
22
+ import { Button } from './ui/button';
23
+ import { Checkbox } from './ui/checkbox';
24
+ import { Input } from './ui/input';
25
+ import { FilterBuilder } from './filter-builder';
26
+ import { MarkdownContent } from './markdown-content';
27
+ import { Popover, PopoverAnchor, PopoverContent } from './ui/popover';
28
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
29
+ import {
30
+ createFilterFields,
31
+ defaultOperatorByType,
32
+ matchesFilters,
33
+ matchesSearch,
34
+ questionStatusLabels,
35
+ } from '../lib/question-filter.ts';
36
+ import { useQuestionFilterStore } from '../lib/question-filter-store.ts';
37
+ import { cn } from '../lib/utils.ts';
38
+ import { getQuestionStatuses } from '../lib/question-status-storage.ts';
39
+ import { createQuiz } from '../lib/quiz-storage.ts';
40
+
41
+ type DragSelection = {
42
+ value: boolean;
43
+ startIndex: number;
44
+ currentIndex: number;
45
+ originalSelection: RowSelectionState;
46
+ pointerId: number;
47
+ startX: number;
48
+ startY: number;
49
+ clientX: number;
50
+ clientY: number;
51
+ moved: boolean;
52
+ };
53
+
54
+ const previewCloseDelay = 180;
55
+ const previewOpenDelay = 400;
56
+ const questionStatusStyles: Record<QuestionStatus, string> = {
57
+ unanswered: 'border-gray-300 bg-gray-50 text-gray-700',
58
+ revisit: 'border-amber-300 bg-amber-50 text-amber-900',
59
+ complete: 'border-green-300 bg-green-50 text-green-800',
60
+ };
61
+
62
+ function QuestionPreviewPopover({ question }: { question: BaseQuestion }) {
63
+ const [open, setOpen] = useState(false);
64
+ const openTimeout = useRef<number | null>(null);
65
+ const closeTimeout = useRef<number | null>(null);
66
+ const openedByPointer = useRef(false);
67
+
68
+ const clearOpenTimeout = () => {
69
+ if (openTimeout.current !== null) {
70
+ window.clearTimeout(openTimeout.current);
71
+ openTimeout.current = null;
72
+ }
73
+ };
74
+ const clearCloseTimeout = () => {
75
+ if (closeTimeout.current !== null) {
76
+ window.clearTimeout(closeTimeout.current);
77
+ closeTimeout.current = null;
78
+ }
79
+ };
80
+ const openPreview = () => {
81
+ clearOpenTimeout();
82
+ clearCloseTimeout();
83
+ setOpen(true);
84
+ };
85
+ const scheduleOpen = () => {
86
+ clearOpenTimeout();
87
+ clearCloseTimeout();
88
+ openTimeout.current = window.setTimeout(() => {
89
+ setOpen(true);
90
+ openTimeout.current = null;
91
+ }, previewOpenDelay);
92
+ };
93
+ const scheduleClose = () => {
94
+ clearOpenTimeout();
95
+ clearCloseTimeout();
96
+ closeTimeout.current = window.setTimeout(() => {
97
+ setOpen(false);
98
+ openedByPointer.current = false;
99
+ closeTimeout.current = null;
100
+ }, previewCloseDelay);
101
+ };
102
+
103
+ useEffect(
104
+ () => () => {
105
+ if (openTimeout.current !== null) window.clearTimeout(openTimeout.current);
106
+ if (closeTimeout.current !== null) window.clearTimeout(closeTimeout.current);
107
+ },
108
+ [],
109
+ );
110
+
111
+ return (
112
+ <Popover
113
+ open={open}
114
+ onOpenChange={(nextOpen) => {
115
+ if (nextOpen) {
116
+ openPreview();
117
+ } else {
118
+ clearOpenTimeout();
119
+ clearCloseTimeout();
120
+ setOpen(false);
121
+ openedByPointer.current = false;
122
+ }
123
+ }}
124
+ >
125
+ <PopoverAnchor asChild>
126
+ <button
127
+ type="button"
128
+ aria-haspopup="dialog"
129
+ aria-expanded={open}
130
+ aria-label={`Preview question: ${question.title}`}
131
+ className="block max-w-full rounded-sm text-left text-base font-semibold leading-6 text-foreground hover:underline hover:decoration-dotted hover:underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
132
+ onPointerEnter={() => {
133
+ openedByPointer.current = true;
134
+ scheduleOpen();
135
+ }}
136
+ onPointerLeave={scheduleClose}
137
+ onFocus={() => {
138
+ if (!openedByPointer.current) scheduleOpen();
139
+ }}
140
+ onBlur={scheduleClose}
141
+ onClick={(event) => {
142
+ event.stopPropagation();
143
+ scheduleOpen();
144
+ }}
145
+ >
146
+ {question.title}
147
+ </button>
148
+ </PopoverAnchor>
149
+ <PopoverContent
150
+ side="right"
151
+ align="start"
152
+ sideOffset={8}
153
+ collisionPadding={12}
154
+ aria-label={`Preview: ${question.title}`}
155
+ className="max-h-[min(70dvh,calc(100dvh-1.5rem))] w-[min(680px,calc(100vw-2rem))] max-w-[calc(100vw-1.5rem)] overflow-y-auto p-0"
156
+ onOpenAutoFocus={(event) => {
157
+ if (openedByPointer.current) event.preventDefault();
158
+ }}
159
+ onPointerEnter={openPreview}
160
+ onPointerLeave={scheduleClose}
161
+ onFocusCapture={openPreview}
162
+ onBlurCapture={scheduleClose}
163
+ >
164
+ <div className="px-4 py-3">
165
+ <MarkdownContent content={question.prompt} />
166
+ </div>
167
+ </PopoverContent>
168
+ </Popover>
169
+ );
170
+ }
171
+
172
+ function formatCellValue(value: unknown): string {
173
+ if (value === null || value === undefined || value === '') return '—';
174
+ if (Array.isArray(value)) return value.join(', ');
175
+ return String(value);
176
+ }
177
+
178
+ export function QuestionBank() {
179
+ const bank = useBank();
180
+ const navigate = useNavigate();
181
+ const search = useQuestionFilterStore((state) => state.search);
182
+ const filters = useQuestionFilterStore((state) => state.filters);
183
+ const filterMatch = useQuestionFilterStore((state) => state.filterMatch);
184
+ const setSearch = useQuestionFilterStore((state) => state.setSearch);
185
+ const addFilter = useQuestionFilterStore((state) => state.addFilter);
186
+ const updateFilter = useQuestionFilterStore((state) => state.updateFilter);
187
+ const removeFilter = useQuestionFilterStore((state) => state.removeFilter);
188
+ const clearFilters = useQuestionFilterStore((state) => state.clearFilters);
189
+ const setFilterMatch = useQuestionFilterStore((state) => state.setFilterMatch);
190
+ const [questionStatusMap, setQuestionStatusMap] = useState<QuestionStatusMap>({});
191
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
192
+ const [sorting, setSorting] = useState<SortingState>(
193
+ (bank.defaultSorting ?? [{ id: 'id' }]).map((s) => ({ id: s.id, desc: s.desc ?? false })),
194
+ );
195
+ const [creatingQuiz, setCreatingQuiz] = useState(false);
196
+ const tableContainerRef = useRef<HTMLDivElement>(null);
197
+ const rowSelectionRef = useRef(rowSelection);
198
+ rowSelectionRef.current = rowSelection;
199
+ const dragSelection = useRef<DragSelection | null>(null);
200
+ const pendingCheckboxChange = useRef<{ rowId: string; value: boolean } | null>(null);
201
+ const suppressRowClick = useRef<string | null>(null);
202
+
203
+ const filterFields = useMemo(() => createFilterFields(bank.questions, bank.fields), [bank]);
204
+
205
+ const handleAddFilter = (field: string) => {
206
+ const type = filterFields.find((f) => f.id === field)?.type ?? 'text';
207
+ addFilter(field, defaultOperatorByType[type]);
208
+ };
209
+
210
+ useEffect(() => {
211
+ void useQuestionFilterStore.persist.rehydrate();
212
+ }, []);
213
+
214
+ useEffect(() => {
215
+ let active = true;
216
+ getQuestionStatuses(bank.namespace).then((statuses) => {
217
+ if (active) setQuestionStatusMap(statuses);
218
+ });
219
+ return () => {
220
+ active = false;
221
+ };
222
+ }, [bank.namespace]);
223
+
224
+ const filteredQuestions = useMemo(
225
+ () =>
226
+ bank.questions.filter(
227
+ (question) =>
228
+ matchesFilters(filters, filterMatch, filterFields, bank.fields, question, questionStatusMap[question.id] ?? 'unanswered') &&
229
+ matchesSearch(question, search, bank.fields),
230
+ ),
231
+ [bank, filters, filterMatch, filterFields, questionStatusMap, search],
232
+ );
233
+
234
+ const columns = useMemo<ColumnDef<BaseQuestion>[]>(() => {
235
+ const customs: ColumnDef<BaseQuestion>[] = bank.fields
236
+ .filter((def) => def.column !== false)
237
+ .map((def) => {
238
+ const header = def.column && typeof def.column === 'object' && def.column.header ? def.column.header : def.label;
239
+ const width = def.column && typeof def.column === 'object' && def.column.width ? def.column.width : undefined;
240
+ const sortable = def.column && typeof def.column === 'object' && def.column.sortable === false ? false : true;
241
+ return {
242
+ id: def.id,
243
+ accessorFn: (row) => {
244
+ const raw = def.getValue(row);
245
+ return Array.isArray(raw) ? raw.join(', ') : (raw ?? '');
246
+ },
247
+ header,
248
+ cell: ({ row }) => {
249
+ const raw = def.getValue(row.original);
250
+ if (def.type === 'multiselect' && Array.isArray(raw)) {
251
+ return (
252
+ <div className="flex flex-wrap gap-1">
253
+ {(raw as readonly string[]).map((tag) => (
254
+ <Badge key={String(tag)} variant="secondary">
255
+ {String(tag)}
256
+ </Badge>
257
+ ))}
258
+ </div>
259
+ );
260
+ }
261
+ return <span className="text-sm text-foreground">{formatCellValue(raw)}</span>;
262
+ },
263
+ enableSorting: sortable,
264
+ size: width,
265
+ } satisfies ColumnDef<BaseQuestion>;
266
+ });
267
+
268
+ return [
269
+ {
270
+ id: 'select',
271
+ header: ({ table }) => (
272
+ <Checkbox
273
+ aria-label="Select all matching questions"
274
+ checked={table.getIsAllPageRowsSelected() ? true : table.getIsSomePageRowsSelected() ? 'indeterminate' : false}
275
+ onCheckedChange={(checked) => table.toggleAllPageRowsSelected(checked === true)}
276
+ />
277
+ ),
278
+ cell: ({ row }) => (
279
+ <Checkbox
280
+ aria-label={`Select ${row.original.title}`}
281
+ checked={row.getIsSelected()}
282
+ onPointerDown={(event) => {
283
+ if (event.button !== 0) return;
284
+ const startIndex = Number(event.currentTarget.closest<HTMLElement>('[data-virtual-index]')?.dataset.virtualIndex);
285
+ if (!Number.isInteger(startIndex)) return;
286
+ suppressRowClick.current = null;
287
+ const value = !row.getIsSelected();
288
+ pendingCheckboxChange.current = { rowId: row.id, value };
289
+ dragSelection.current = {
290
+ value,
291
+ startIndex,
292
+ currentIndex: startIndex,
293
+ originalSelection: { ...rowSelectionRef.current },
294
+ pointerId: event.pointerId,
295
+ startX: event.clientX,
296
+ startY: event.clientY,
297
+ clientX: event.clientX,
298
+ clientY: event.clientY,
299
+ moved: false,
300
+ };
301
+ setRowSelection((current) => (current[row.id] === value ? current : { ...current, [row.id]: value }));
302
+ }}
303
+ onCheckedChange={(checked) => {
304
+ const pendingChange = pendingCheckboxChange.current;
305
+ if (pendingChange?.rowId === row.id) pendingCheckboxChange.current = null;
306
+ const value = pendingChange?.rowId === row.id ? pendingChange.value : checked === true;
307
+ setRowSelection((current) => (current[row.id] === value ? current : { ...current, [row.id]: value }));
308
+ }}
309
+ />
310
+ ),
311
+ enableSorting: false,
312
+ size: 44,
313
+ },
314
+ {
315
+ accessorKey: 'id',
316
+ header: 'ID',
317
+ cell: ({ row }) => <span className="font-mono text-sm text-muted-foreground">{row.original.id}</span>,
318
+ size: 104,
319
+ },
320
+ {
321
+ accessorKey: 'title',
322
+ header: 'Question',
323
+ cell: ({ row }) => <QuestionPreviewPopover question={row.original} />,
324
+ size: 340,
325
+ },
326
+ {
327
+ id: 'tags',
328
+ accessorFn: (row) => row.tags.join(', '),
329
+ header: 'Tags',
330
+ cell: ({ row }) => (
331
+ <div className="flex flex-wrap gap-1">
332
+ {row.original.tags.map((tag) => (
333
+ <Badge key={tag} variant="secondary">
334
+ {tag}
335
+ </Badge>
336
+ ))}
337
+ </div>
338
+ ),
339
+ },
340
+ ...customs,
341
+ {
342
+ id: 'status',
343
+ accessorFn: (row) => questionStatusMap[row.id] ?? 'unanswered',
344
+ header: 'Status',
345
+ cell: ({ row }) => {
346
+ const status = questionStatusMap[row.original.id] ?? 'unanswered';
347
+ return (
348
+ <Badge variant="outline" className={questionStatusStyles[status]}>
349
+ {questionStatusLabels[status]}
350
+ </Badge>
351
+ );
352
+ },
353
+ size: 108,
354
+ },
355
+ ];
356
+ }, [bank.fields, questionStatusMap]);
357
+
358
+ const table = useReactTable({
359
+ data: filteredQuestions,
360
+ columns,
361
+ state: { globalFilter: search, rowSelection, sorting },
362
+ onRowSelectionChange: setRowSelection,
363
+ onSortingChange: setSorting,
364
+ globalFilterFn: (row, _columnId, filterValue) => matchesSearch(row.original, String(filterValue ?? ''), bank.fields),
365
+ getRowId: (row) => row.id,
366
+ getCoreRowModel: getCoreRowModel(),
367
+ getFilteredRowModel: getFilteredRowModel(),
368
+ getSortedRowModel: getSortedRowModel(),
369
+ });
370
+ const tableRows = table.getRowModel().rows;
371
+ const rowVirtualizer = useVirtualizer({
372
+ count: tableRows.length,
373
+ getScrollElement: () => tableContainerRef.current,
374
+ estimateSize: () => 56,
375
+ getItemKey: (index) => tableRows[index]?.id ?? index,
376
+ overscan: 8,
377
+ });
378
+ const virtualRows = rowVirtualizer.getVirtualItems();
379
+ const topPadding = virtualRows[0]?.start ?? 0;
380
+ const bottomPadding =
381
+ virtualRows.length > 0 ? Math.max(rowVirtualizer.getTotalSize() - virtualRows[virtualRows.length - 1]!.end, 0) : 0;
382
+
383
+ const updateDragRange = useCallback(
384
+ (index: number) => {
385
+ const activeDrag = dragSelection.current;
386
+ if (!activeDrag || index < 0 || index >= tableRows.length || activeDrag.currentIndex === index) return;
387
+ const previousStart = Math.min(activeDrag.startIndex, activeDrag.currentIndex);
388
+ const previousEnd = Math.max(activeDrag.startIndex, activeDrag.currentIndex);
389
+ const nextStart = Math.min(activeDrag.startIndex, index);
390
+ const nextEnd = Math.max(activeDrag.startIndex, index);
391
+ const affectedStart = Math.min(previousStart, nextStart);
392
+ const affectedEnd = Math.max(previousEnd, nextEnd);
393
+ activeDrag.currentIndex = index;
394
+ activeDrag.moved = true;
395
+ setRowSelection((current) => {
396
+ const next = { ...current };
397
+ let changed = false;
398
+ for (let rowIndex = affectedStart; rowIndex <= affectedEnd; rowIndex += 1) {
399
+ const row = tableRows[rowIndex];
400
+ if (!row) continue;
401
+ const selected = rowIndex >= nextStart && rowIndex <= nextEnd ? activeDrag.value : activeDrag.originalSelection[row.id] === true;
402
+ if ((current[row.id] === true) === selected) continue;
403
+ if (selected) next[row.id] = true;
404
+ else delete next[row.id];
405
+ changed = true;
406
+ }
407
+ return changed ? next : current;
408
+ });
409
+ },
410
+ [tableRows],
411
+ );
412
+
413
+ useEffect(() => {
414
+ let animationFrame = 0;
415
+ const autoScroll = () => {
416
+ animationFrame = 0;
417
+ const activeDrag = dragSelection.current;
418
+ const container = tableContainerRef.current;
419
+ if (!activeDrag?.moved || !container) return;
420
+ const rect = container.getBoundingClientRect();
421
+ const viewportTop = rect.top + container.clientTop;
422
+ const viewportBottom = viewportTop + container.clientHeight;
423
+ const edgeSize = Math.min(56, container.clientHeight / 3);
424
+ let scrollDelta = 0;
425
+ if (activeDrag.clientY < viewportTop + edgeSize) {
426
+ const distanceIntoEdge = Math.min(1, (viewportTop + edgeSize - activeDrag.clientY) / edgeSize);
427
+ scrollDelta = -Math.ceil(2 + 14 * distanceIntoEdge ** 2);
428
+ } else if (activeDrag.clientY > viewportBottom - edgeSize) {
429
+ const distanceIntoEdge = Math.min(1, (activeDrag.clientY - (viewportBottom - edgeSize)) / edgeSize);
430
+ scrollDelta = Math.ceil(2 + 14 * distanceIntoEdge ** 2);
431
+ }
432
+ if (scrollDelta !== 0) {
433
+ const previousScrollTop = container.scrollTop;
434
+ container.scrollTop += scrollDelta;
435
+ if (container.scrollTop !== previousScrollTop && animationFrame === 0) {
436
+ animationFrame = window.requestAnimationFrame(autoScroll);
437
+ }
438
+ }
439
+ let targetRow = document.elementFromPoint(activeDrag.clientX, activeDrag.clientY)?.closest<HTMLElement>('[data-virtual-index]');
440
+ if (!targetRow) {
441
+ const visibleRows = [...container.querySelectorAll<HTMLElement>('[data-virtual-index]')].filter((row) => {
442
+ const rowRect = row.getBoundingClientRect();
443
+ return rowRect.bottom > viewportTop && rowRect.top < viewportBottom;
444
+ });
445
+ if (activeDrag.clientY < viewportTop + edgeSize) targetRow = visibleRows[0];
446
+ else if (activeDrag.clientY > viewportBottom - edgeSize) targetRow = visibleRows[visibleRows.length - 1];
447
+ }
448
+ const targetIndex = Number(targetRow?.dataset.virtualIndex);
449
+ if (Number.isInteger(targetIndex)) updateDragRange(targetIndex);
450
+ };
451
+ const trackPointer = (event: PointerEvent) => {
452
+ const activeDrag = dragSelection.current;
453
+ if (!activeDrag || activeDrag.pointerId !== event.pointerId) return;
454
+ activeDrag.clientX = event.clientX;
455
+ activeDrag.clientY = event.clientY;
456
+ if (!activeDrag.moved && Math.hypot(event.clientX - activeDrag.startX, event.clientY - activeDrag.startY) >= 5) {
457
+ activeDrag.moved = true;
458
+ }
459
+ if (activeDrag.moved && animationFrame === 0) {
460
+ animationFrame = window.requestAnimationFrame(autoScroll);
461
+ }
462
+ };
463
+ const stopDragSelection = (event: PointerEvent) => {
464
+ const activeDrag = dragSelection.current;
465
+ if (!activeDrag || activeDrag.pointerId !== event.pointerId) return;
466
+ const target = event.target instanceof Element ? event.target : null;
467
+ const targetCheckbox = target?.closest<HTMLElement>('[role="checkbox"]');
468
+ const targetRow = target?.closest<HTMLElement>('[data-question-row]');
469
+ if (event.type === 'pointerup' && targetRow && !targetCheckbox) {
470
+ suppressRowClick.current = targetRow.dataset.questionRow ?? null;
471
+ }
472
+ const pendingChange = pendingCheckboxChange.current;
473
+ const checkboxRow = targetCheckbox?.closest<HTMLElement>('[data-question-row]');
474
+ if (event.type !== 'pointerup' || checkboxRow?.dataset.questionRow !== pendingChange?.rowId) {
475
+ pendingCheckboxChange.current = null;
476
+ } else if (pendingChange) {
477
+ window.setTimeout(() => {
478
+ if (pendingCheckboxChange.current === pendingChange) pendingCheckboxChange.current = null;
479
+ }, 0);
480
+ }
481
+ dragSelection.current = null;
482
+ if (animationFrame !== 0) window.cancelAnimationFrame(animationFrame);
483
+ animationFrame = 0;
484
+ };
485
+ window.addEventListener('pointermove', trackPointer);
486
+ window.addEventListener('pointerup', stopDragSelection);
487
+ window.addEventListener('pointercancel', stopDragSelection);
488
+ return () => {
489
+ window.removeEventListener('pointermove', trackPointer);
490
+ window.removeEventListener('pointerup', stopDragSelection);
491
+ window.removeEventListener('pointercancel', stopDragSelection);
492
+ if (animationFrame !== 0) window.cancelAnimationFrame(animationFrame);
493
+ };
494
+ }, [updateDragRange]);
495
+
496
+ useEffect(() => {
497
+ tableContainerRef.current?.scrollTo({ top: 0 });
498
+ }, [filteredQuestions, search, sorting]);
499
+
500
+ const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);
501
+
502
+ const makeQuiz = async () => {
503
+ const chosenQuestions = bank.questions.filter((question) => rowSelection[question.id]);
504
+ if (chosenQuestions.length === 0) return;
505
+ setCreatingQuiz(true);
506
+ const title = `${chosenQuestions.length}-question practice set`;
507
+ try {
508
+ const quiz = await createQuiz(bank.namespace, title, chosenQuestions.map((question) => question.id));
509
+ await navigate({ to: '/quiz/$quizId', params: { quizId: quiz.id } });
510
+ } finally {
511
+ setCreatingQuiz(false);
512
+ }
513
+ };
514
+
515
+ return (
516
+ <div className="flex min-h-0 flex-1 flex-col">
517
+ <div className="border-b bg-background px-4 py-3">
518
+ <div className="flex flex-wrap items-center gap-3">
519
+ <label className="relative min-w-[240px] flex-1">
520
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
521
+ <Input
522
+ value={search}
523
+ onChange={(event) => setSearch(event.target.value)}
524
+ placeholder="Search questions, topics, exams..."
525
+ aria-label="Search questions"
526
+ className="h-11 pl-10 text-base"
527
+ />
528
+ </label>
529
+ <FilterBuilder
530
+ fields={filterFields}
531
+ filters={filters}
532
+ match={filterMatch}
533
+ onAdd={handleAddFilter}
534
+ onChange={updateFilter}
535
+ onRemove={removeFilter}
536
+ onClear={clearFilters}
537
+ onMatchChange={setFilterMatch}
538
+ />
539
+ {filters.length > 0 && (
540
+ <Button variant="ghost" className="h-11 text-base" onClick={clearFilters}>
541
+ Clear filters
542
+ </Button>
543
+ )}
544
+ </div>
545
+ </div>
546
+
547
+ <Table containerRef={tableContainerRef} containerClassName="min-h-0 flex-1 overflow-auto" className="min-w-[1200px] table-fixed">
548
+ <TableHeader>
549
+ {table.getHeaderGroups().map((headerGroup) => (
550
+ <TableRow key={headerGroup.id}>
551
+ {headerGroup.headers.map((header) => (
552
+ <TableHead
553
+ key={header.id}
554
+ style={header.column.id === 'tags' ? undefined : { width: header.getSize() }}
555
+ className="sticky top-0 z-10 h-12 border-b bg-muted px-4 text-sm font-semibold text-foreground"
556
+ >
557
+ {header.isPlaceholder ? null : header.column.getCanSort() ? (
558
+ <button className="font-semibold hover:underline" onClick={header.column.getToggleSortingHandler()}>
559
+ {flexRender(header.column.columnDef.header, header.getContext())}
560
+ </button>
561
+ ) : (
562
+ flexRender(header.column.columnDef.header, header.getContext())
563
+ )}
564
+ </TableHead>
565
+ ))}
566
+ </TableRow>
567
+ ))}
568
+ </TableHeader>
569
+ <TableBody>
570
+ {tableRows.length > 0 ? (
571
+ <>
572
+ {topPadding > 0 && (
573
+ <TableRow aria-hidden="true" className="border-0">
574
+ <TableCell colSpan={columns.length} className="border-0 p-0" style={{ height: topPadding }} />
575
+ </TableRow>
576
+ )}
577
+ {virtualRows.map((virtualRow) => {
578
+ const row = tableRows[virtualRow.index];
579
+ if (!row) return null;
580
+ return (
581
+ <TableRow
582
+ key={row.id}
583
+ ref={rowVirtualizer.measureElement}
584
+ data-index={virtualRow.index}
585
+ data-virtual-index={virtualRow.index}
586
+ data-question-row={row.id}
587
+ data-state={row.getIsSelected() ? 'selected' : undefined}
588
+ className="group cursor-pointer"
589
+ onPointerEnter={() => updateDragRange(virtualRow.index)}
590
+ onClick={() => {
591
+ if (suppressRowClick.current === row.id) {
592
+ suppressRowClick.current = null;
593
+ return;
594
+ }
595
+ if (!dragSelection.current) row.toggleSelected();
596
+ }}
597
+ >
598
+ {row.getVisibleCells().map((cell) => (
599
+ <TableCell
600
+ key={cell.id}
601
+ className={cn('border-b px-4 py-2 align-middle', cell.column.id === 'title' && 'whitespace-normal')}
602
+ onClick={cell.column.id === 'select' ? (event) => event.stopPropagation() : undefined}
603
+ >
604
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
605
+ </TableCell>
606
+ ))}
607
+ </TableRow>
608
+ );
609
+ })}
610
+ {bottomPadding > 0 && (
611
+ <TableRow aria-hidden="true" className="border-0">
612
+ <TableCell colSpan={columns.length} className="border-0 p-0" style={{ height: bottomPadding }} />
613
+ </TableRow>
614
+ )}
615
+ </>
616
+ ) : (
617
+ <TableRow>
618
+ <TableCell colSpan={columns.length} className="h-40 text-center">
619
+ <p className="text-lg font-semibold">No matching questions</p>
620
+ <p className="mt-1 text-base text-muted-foreground">Try another search or clear your filters.</p>
621
+ <Button
622
+ variant="outline"
623
+ className="mt-4"
624
+ onClick={() => {
625
+ clearFilters();
626
+ setSearch('');
627
+ }}
628
+ >
629
+ Clear search and filters
630
+ </Button>
631
+ </TableCell>
632
+ </TableRow>
633
+ )}
634
+ </TableBody>
635
+ </Table>
636
+
637
+ {selectedIds.length > 0 && (
638
+ <div className="fixed bottom-5 right-1/2 z-30 flex w-[min(600px,calc(100vw-32px))] translate-x-1/2 items-center gap-3 rounded-xl border bg-background p-3 pl-4 shadow-lg">
639
+ <span className="text-base font-semibold">
640
+ {selectedIds.length} {selectedIds.length === 1 ? 'question' : 'questions'} selected
641
+ </span>
642
+ <Button variant="ghost" className="text-base" onClick={() => setRowSelection({})}>
643
+ Clear
644
+ </Button>
645
+ <div className="ml-auto">
646
+ <Button className="text-base" onClick={makeQuiz} disabled={creatingQuiz}>
647
+ {creatingQuiz ? 'Making quiz...' : 'Make quiz'}
648
+ </Button>
649
+ </div>
650
+ </div>
651
+ )}
652
+ </div>
653
+ );
654
+ }