question-bank-framework 0.0.0-stage → 0.1.0

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 +52 -0
  5. package/core/index.ts +35 -0
  6. package/core/types.ts +256 -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 +690 -0
  11. package/framework/components/quiz-list.tsx +118 -0
  12. package/framework/components/quiz-page.tsx +454 -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 +376 -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 +66 -4
  33. package/template/bank.config.ts +72 -0
  34. package/template/content/answers.ts +8 -0
  35. package/template/content/questions.json +76 -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,376 @@
1
+ // Generic filter DSL. Ported from the COMP20008 bank; the hardcoded
2
+ // FilterFieldId union (title/id/tags/year/semester/marks/status) is replaced
3
+ // by config-defined `BankFieldDef[]` plus the three built-ins.
4
+ // Framework-owned: eject with `qb reveal framework/lib/question-filter.ts`.
5
+
6
+ import { questionKind, questionKindLabels, questionKinds, questionStatuses, type BankFieldDef, type BankFilterOperatorId, type BaseQuestion, type QuestionStatus } from '../../core/types.ts';
7
+
8
+ export type FilterMatch = 'and' | 'or';
9
+
10
+ export type FilterFieldType = 'text' | 'number' | 'select' | 'multiselect';
11
+
12
+ export type FilterOperatorId = BankFilterOperatorId;
13
+
14
+ export type FilterOption = { value: string; label: string };
15
+
16
+ export type FilterField = {
17
+ id: string;
18
+ label: string;
19
+ type: FilterFieldType;
20
+ operators: readonly FilterOperatorId[];
21
+ options?: readonly FilterOption[];
22
+ placeholder?: string;
23
+ searchable?: boolean;
24
+ };
25
+
26
+ export type FilterRule = {
27
+ id: string;
28
+ field: string;
29
+ operator: FilterOperatorId;
30
+ value: string[];
31
+ };
32
+
33
+ const textOperators: readonly FilterOperatorId[] = [
34
+ 'is',
35
+ 'isNot',
36
+ 'contains',
37
+ 'doesNotContain',
38
+ 'startsWith',
39
+ 'endsWith',
40
+ 'isEmpty',
41
+ 'isNotEmpty',
42
+ ];
43
+
44
+ const numberOperators: readonly FilterOperatorId[] = [
45
+ 'eq',
46
+ 'neq',
47
+ 'gt',
48
+ 'lt',
49
+ 'gte',
50
+ 'lte',
51
+ 'between',
52
+ 'isEmpty',
53
+ 'isNotEmpty',
54
+ ];
55
+
56
+ const selectOperators: readonly FilterOperatorId[] = ['is', 'isNot', 'isEmpty', 'isNotEmpty'];
57
+
58
+ const multiSelectOperators: readonly FilterOperatorId[] = ['contains', 'doesNotContain', 'isEmpty', 'isNotEmpty'];
59
+
60
+ export const defaultOperatorByType: Record<FilterFieldType, FilterOperatorId> = {
61
+ text: 'contains',
62
+ number: 'eq',
63
+ select: 'is',
64
+ multiselect: 'contains',
65
+ };
66
+
67
+ export const fieldTypeLabels: Record<FilterFieldType, string> = {
68
+ text: 'Text',
69
+ number: 'Number',
70
+ select: 'Select',
71
+ multiselect: 'Multi-select',
72
+ };
73
+
74
+ export const operatorLabels: Record<FilterOperatorId, string> = {
75
+ is: 'Is',
76
+ isNot: 'Is not',
77
+ contains: 'Contains',
78
+ doesNotContain: 'Does not contain',
79
+ startsWith: 'Starts with',
80
+ endsWith: 'Ends with',
81
+ eq: '=',
82
+ neq: '≠',
83
+ gt: '>',
84
+ lt: '<',
85
+ gte: '≥',
86
+ lte: '≤',
87
+ between: 'Is between',
88
+ isEmpty: 'Is empty',
89
+ isNotEmpty: 'Is not empty',
90
+ };
91
+
92
+ export const questionStatusLabels: Record<QuestionStatus, string> = {
93
+ unanswered: 'Unanswered',
94
+ revisit: 'Revisit',
95
+ complete: 'Complete',
96
+ };
97
+
98
+ /** Built-in fields present in every bank. */
99
+ function builtinFields(): FilterField[] {
100
+ return [
101
+ { id: 'title', label: 'Question', type: 'text', operators: textOperators, placeholder: 'Type a value…' },
102
+ { id: 'id', label: 'ID', type: 'text', operators: textOperators, placeholder: 'Type a value…' },
103
+ { id: 'tags', label: 'Tags', type: 'multiselect', operators: multiSelectOperators },
104
+ {
105
+ id: 'kind',
106
+ label: 'Type',
107
+ type: 'select',
108
+ operators: selectOperators,
109
+ options: questionKinds.map((kind) => ({ value: kind, label: questionKindLabels[kind] })),
110
+ },
111
+ {
112
+ id: 'status',
113
+ label: 'Status',
114
+ type: 'select',
115
+ operators: selectOperators,
116
+ options: questionStatuses.map((status) => ({ value: status, label: questionStatusLabels[status] })),
117
+ },
118
+ ];
119
+ }
120
+
121
+ function distinctStrings(values: Array<string | number | null | readonly string[]>): string[] {
122
+ const out = new Set<string>();
123
+ for (const value of values) {
124
+ if (value === null || value === undefined) continue;
125
+ if (Array.isArray(value)) {
126
+ for (const item of value) out.add(String(item));
127
+ } else {
128
+ out.add(String(value));
129
+ }
130
+ }
131
+ return [...out].sort((a, b) => a.localeCompare(b));
132
+ }
133
+
134
+ /**
135
+ * Build filter fields from bank config. Select/multiselect options default to
136
+ * the distinct values across questions unless the field declares `options`.
137
+ */
138
+ export function createFilterFields(questions: readonly BaseQuestion[], fieldDefs: readonly BankFieldDef[]): FilterField[] {
139
+ const customs: FilterField[] = fieldDefs.map((def) => {
140
+ let options: readonly FilterOption[] | undefined;
141
+ if (def.options) {
142
+ options = def.options;
143
+ } else if (def.type === 'select' || def.type === 'multiselect') {
144
+ const distinct = distinctStrings(questions.map((q) => def.getValue(q)));
145
+ options = distinct.map((value) => ({ value, label: value }));
146
+ }
147
+ const defaultOperators =
148
+ def.type === 'text'
149
+ ? textOperators
150
+ : def.type === 'number'
151
+ ? numberOperators
152
+ : def.type === 'select'
153
+ ? selectOperators
154
+ : multiSelectOperators;
155
+ return {
156
+ id: def.id,
157
+ label: def.label,
158
+ type: def.type,
159
+ operators: def.operators ?? defaultOperators,
160
+ options,
161
+ placeholder: def.placeholder,
162
+ searchable: def.searchable,
163
+ };
164
+ });
165
+
166
+ const builtins = builtinFields();
167
+ // Attach tag options derived from the bank (like the original).
168
+ const tags = [...new Set(questions.flatMap((q) => q.tags))].sort((a, b) => a.localeCompare(b));
169
+ const withTags = builtins.map((field) =>
170
+ field.id === 'tags' ? { ...field, options: tags.map((tag) => ({ value: tag, label: tag })) } : field,
171
+ );
172
+
173
+ // Order: title, id, tags, ...customs, status (status last like the original).
174
+ const status = withTags.find((f) => f.id === 'status')!;
175
+ const head = withTags.filter((f) => f.id !== 'status');
176
+ return [...head, ...customs, status];
177
+ }
178
+
179
+ export function filterFieldType(fields: readonly FilterField[], fieldId: string): FilterFieldType {
180
+ return fields.find((f) => f.id === fieldId)?.type ?? 'text';
181
+ }
182
+
183
+ // ---------------------------------------------------------------------------
184
+ // Matching.
185
+ // ---------------------------------------------------------------------------
186
+
187
+ function parseNumber(raw: string | undefined): number | null {
188
+ if (raw === undefined || raw.trim() === '') return null;
189
+ const value = Number(raw);
190
+ return Number.isFinite(value) ? value : null;
191
+ }
192
+
193
+ function toText(value: string | number | null | readonly string[]): string {
194
+ if (value === null || value === undefined) return '';
195
+ if (Array.isArray(value)) return value.join(' ');
196
+ return String(value);
197
+ }
198
+
199
+ function toNumber(value: string | number | null | readonly string[]): number | null {
200
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
201
+ if (typeof value === 'string') {
202
+ if (value.trim() === '') return null;
203
+ const parsed = Number(value);
204
+ return Number.isFinite(parsed) ? parsed : null;
205
+ }
206
+ return null;
207
+ }
208
+
209
+ function toSelect(value: string | number | null | readonly string[]): string {
210
+ if (value === null || value === undefined) return '';
211
+ if (Array.isArray(value)) return value.join(' ');
212
+ return String(value);
213
+ }
214
+
215
+ function toMultiSelect(value: string | number | null | readonly string[]): readonly string[] {
216
+ if (Array.isArray(value)) return value.map(String);
217
+ if (value === null || value === undefined || value === '') return [];
218
+ return [String(value)];
219
+ }
220
+
221
+ function resolveFieldValue(
222
+ def: BankFieldDef | undefined,
223
+ ruleField: string,
224
+ question: BaseQuestion,
225
+ ): string | number | null | readonly string[] {
226
+ if (!def) {
227
+ if (ruleField === 'title') return question.title;
228
+ if (ruleField === 'id') return question.id;
229
+ if (ruleField === 'tags') return question.tags;
230
+ return (question[ruleField] as string | number | null | readonly string[]) ?? null;
231
+ }
232
+ return def.getValue(question);
233
+ }
234
+
235
+ /**
236
+ * A rule with an unfinished value (e.g. "Question contains" with an empty
237
+ * input) is treated as inactive rather than matching nothing.
238
+ */
239
+ export function isRuleActive(rule: FilterRule, fields: readonly FilterField[]): boolean {
240
+ if (rule.operator === 'isEmpty' || rule.operator === 'isNotEmpty') return true;
241
+ const type = filterFieldType(fields, rule.field);
242
+ if (type === 'number') {
243
+ if (rule.operator === 'between') {
244
+ return parseNumber(rule.value[0]) !== null && parseNumber(rule.value[1]) !== null;
245
+ }
246
+ return parseNumber(rule.value[0]) !== null;
247
+ }
248
+ if (type === 'select' || type === 'multiselect') return rule.value.length > 0;
249
+ return (rule.value[0] ?? '').trim().length > 0;
250
+ }
251
+
252
+ function matchText(subject: string, rule: FilterRule): boolean {
253
+ const needle = (rule.value[0] ?? '').trim().toLowerCase();
254
+ const haystack = subject.toLowerCase();
255
+ switch (rule.operator) {
256
+ case 'is':
257
+ return haystack === needle;
258
+ case 'isNot':
259
+ return haystack !== needle;
260
+ case 'contains':
261
+ return haystack.includes(needle);
262
+ case 'doesNotContain':
263
+ return !haystack.includes(needle);
264
+ case 'startsWith':
265
+ return haystack.startsWith(needle);
266
+ case 'endsWith':
267
+ return haystack.endsWith(needle);
268
+ case 'isEmpty':
269
+ return haystack.length === 0;
270
+ case 'isNotEmpty':
271
+ return haystack.length > 0;
272
+ default:
273
+ return true;
274
+ }
275
+ }
276
+
277
+ function matchNumber(subject: number | null, rule: FilterRule): boolean {
278
+ if (rule.operator === 'isEmpty') return subject === null;
279
+ if (rule.operator === 'isNotEmpty') return subject !== null;
280
+ if (subject === null) return false;
281
+ const first = parseNumber(rule.value[0]);
282
+ const second = parseNumber(rule.value[1]);
283
+ switch (rule.operator) {
284
+ case 'eq':
285
+ return first !== null && subject === first;
286
+ case 'neq':
287
+ return first !== null && subject !== first;
288
+ case 'gt':
289
+ return first !== null && subject > first;
290
+ case 'lt':
291
+ return first !== null && subject < first;
292
+ case 'gte':
293
+ return first !== null && subject >= first;
294
+ case 'lte':
295
+ return first !== null && subject <= first;
296
+ case 'between':
297
+ return first !== null && second !== null && subject >= Math.min(first, second) && subject <= Math.max(first, second);
298
+ default:
299
+ return true;
300
+ }
301
+ }
302
+
303
+ function matchSelect(subject: string, rule: FilterRule): boolean {
304
+ if (rule.operator === 'isEmpty') return subject.length === 0;
305
+ if (rule.operator === 'isNotEmpty') return subject.length > 0;
306
+ const selected = new Set(rule.value);
307
+ if (rule.operator === 'is') return selected.has(subject);
308
+ if (rule.operator === 'isNot') return !selected.has(subject);
309
+ return true;
310
+ }
311
+
312
+ function matchMultiSelect(subject: readonly string[], rule: FilterRule): boolean {
313
+ if (rule.operator === 'isEmpty') return subject.length === 0;
314
+ if (rule.operator === 'isNotEmpty') return subject.length > 0;
315
+ const selected = new Set(rule.value);
316
+ const overlaps = subject.some((item) => selected.has(item));
317
+ if (rule.operator === 'contains') return overlaps;
318
+ if (rule.operator === 'doesNotContain') return !overlaps;
319
+ return true;
320
+ }
321
+
322
+ export function matchesRule(
323
+ rule: FilterRule,
324
+ fields: readonly FilterField[],
325
+ fieldDefs: readonly BankFieldDef[],
326
+ question: BaseQuestion,
327
+ status: QuestionStatus,
328
+ ): boolean {
329
+ const type = filterFieldType(fields, rule.field);
330
+ if (rule.field === 'status') return matchSelect(status, rule);
331
+ if (rule.field === 'kind') return matchSelect(questionKind(question), rule);
332
+ const def = fieldDefs.find((d) => d.id === rule.field);
333
+ const raw = resolveFieldValue(def, rule.field, question);
334
+ if (type === 'text') return matchText(toText(raw), rule);
335
+ if (type === 'number') return matchNumber(toNumber(raw), rule);
336
+ if (type === 'select') return matchSelect(toSelect(raw), rule);
337
+ return matchMultiSelect(toMultiSelect(raw), rule);
338
+ }
339
+
340
+ export function matchesFilters(
341
+ filters: readonly FilterRule[],
342
+ match: FilterMatch,
343
+ fields: readonly FilterField[],
344
+ fieldDefs: readonly BankFieldDef[],
345
+ question: BaseQuestion,
346
+ status: QuestionStatus,
347
+ ): boolean {
348
+ const active = filters.filter((rule) => isRuleActive(rule, fields));
349
+ if (active.length === 0) return true;
350
+ return match === 'and'
351
+ ? active.every((rule) => matchesRule(rule, fields, fieldDefs, question, status))
352
+ : active.some((rule) => matchesRule(rule, fields, fieldDefs, question, status));
353
+ }
354
+
355
+ /** Free-text search across id/title/prompt/tags/options plus `searchable` custom fields. */
356
+ export function matchesSearch(
357
+ question: BaseQuestion,
358
+ query: string,
359
+ fieldDefs: readonly BankFieldDef[],
360
+ ): boolean {
361
+ const q = query.trim().toLowerCase();
362
+ if (!q) return true;
363
+ const parts = [
364
+ question.id,
365
+ question.title,
366
+ question.prompt,
367
+ question.tags.join(' '),
368
+ (question.options ?? []).map((o) => o.text).join(' '),
369
+ ];
370
+ for (const def of fieldDefs) {
371
+ if (!def.searchable) continue;
372
+ const raw = def.getValue(question);
373
+ parts.push(Array.isArray(raw) ? raw.join(' ') : String(raw ?? ''));
374
+ }
375
+ return parts.join(' ').toLowerCase().includes(q);
376
+ }
@@ -0,0 +1,117 @@
1
+ // Per-question status (unanswered/revisit/complete), Convex + localStorage.
2
+ // Framework-owned: eject with `qb reveal framework/lib/question-status-storage.ts`.
3
+
4
+ import { ConvexHttpClient } from 'convex/browser';
5
+ import { convexApi } from './convex-api.ts';
6
+ import { questionStatuses, type QuestionStatus, type QuestionStatusMap } from '../../core/types.ts';
7
+
8
+ const convexUrl = import.meta.env?.VITE_CONVEX_URL || (import.meta.env?.CONVEX_URL as string | undefined);
9
+ const convexClient = convexUrl ? new ConvexHttpClient(convexUrl) : null;
10
+
11
+ type StoredQuestionStatus = {
12
+ status: QuestionStatus;
13
+ updatedAt: number;
14
+ pending: boolean;
15
+ };
16
+
17
+ type QuestionStatusDocument = {
18
+ questionId: string;
19
+ status: QuestionStatus;
20
+ updatedAt: number;
21
+ };
22
+
23
+ const keyFor = (namespace: string) => `${namespace}-question-bank-statuses`;
24
+
25
+ const isQuestionStatus = (value: unknown): value is QuestionStatus =>
26
+ typeof value === 'string' && (questionStatuses as readonly string[]).includes(value);
27
+
28
+ const readLocalStatuses = (namespace: string): Record<string, StoredQuestionStatus> => {
29
+ if (typeof window === 'undefined') return {};
30
+ try {
31
+ const value: unknown = JSON.parse(window.localStorage.getItem(keyFor(namespace)) ?? '{}');
32
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
33
+ return Object.fromEntries(
34
+ Object.entries(value).flatMap(([questionId, entry]) => {
35
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [];
36
+ const stored = entry as Partial<StoredQuestionStatus>;
37
+ if (!isQuestionStatus(stored.status) || typeof stored.updatedAt !== 'number') return [];
38
+ return [
39
+ [
40
+ questionId,
41
+ { status: stored.status, updatedAt: stored.updatedAt, pending: stored.pending === true },
42
+ ],
43
+ ];
44
+ }),
45
+ );
46
+ } catch {
47
+ return {};
48
+ }
49
+ };
50
+
51
+ const writeLocalStatuses = (namespace: string, statuses: Record<string, StoredQuestionStatus>) => {
52
+ if (typeof window !== 'undefined') window.localStorage.setItem(keyFor(namespace), JSON.stringify(statuses));
53
+ };
54
+
55
+ const toStatusMap = (statuses: Record<string, StoredQuestionStatus>): QuestionStatusMap =>
56
+ Object.fromEntries(Object.entries(statuses).map(([questionId, entry]) => [questionId, entry.status]));
57
+
58
+ async function syncPendingStatuses(namespace: string, statuses: Record<string, StoredQuestionStatus>) {
59
+ if (!convexClient) return statuses;
60
+ await Promise.all(
61
+ Object.entries(statuses).map(async ([questionId, entry]) => {
62
+ if (!entry.pending) return;
63
+ try {
64
+ const updatedAt = await convexClient.mutation(convexApi.questionStatuses.set, {
65
+ questionId,
66
+ status: entry.status,
67
+ });
68
+ const latest = readLocalStatuses(namespace);
69
+ if (latest[questionId]?.pending && latest[questionId]?.updatedAt === entry.updatedAt) {
70
+ latest[questionId] = { status: entry.status, updatedAt, pending: false };
71
+ writeLocalStatuses(namespace, latest);
72
+ statuses[questionId] = latest[questionId];
73
+ }
74
+ } catch {
75
+ // Keep the local status pending so it can be retried later.
76
+ }
77
+ }),
78
+ );
79
+ return statuses;
80
+ }
81
+
82
+ export async function getQuestionStatuses(namespace: string): Promise<QuestionStatusMap> {
83
+ const localStatuses = readLocalStatuses(namespace);
84
+ if (!convexClient) return toStatusMap(localStatuses);
85
+ await syncPendingStatuses(namespace, localStatuses);
86
+ try {
87
+ const documents = (await convexClient.query(convexApi.questionStatuses.list, {})) as QuestionStatusDocument[];
88
+ const merged: Record<string, StoredQuestionStatus> = Object.fromEntries(
89
+ documents.map((document) => [document.questionId, { status: document.status, updatedAt: document.updatedAt, pending: false }]),
90
+ );
91
+ for (const [questionId, localStatus] of Object.entries(localStatuses)) {
92
+ if (localStatus.pending || !merged[questionId]) merged[questionId] = localStatus;
93
+ }
94
+ writeLocalStatuses(namespace, merged);
95
+ return toStatusMap(merged);
96
+ } catch {
97
+ return toStatusMap(localStatuses);
98
+ }
99
+ }
100
+
101
+ export async function setQuestionStatus(namespace: string, questionId: string, status: QuestionStatus): Promise<void> {
102
+ const statuses = readLocalStatuses(namespace);
103
+ const localStatus: StoredQuestionStatus = { status, updatedAt: Date.now(), pending: true };
104
+ statuses[questionId] = localStatus;
105
+ writeLocalStatuses(namespace, statuses);
106
+ if (!convexClient) return;
107
+ try {
108
+ const updatedAt = await convexClient.mutation(convexApi.questionStatuses.set, { questionId, status });
109
+ const latest = readLocalStatuses(namespace);
110
+ if (latest[questionId]?.pending && latest[questionId]?.updatedAt === localStatus.updatedAt) {
111
+ latest[questionId] = { status, updatedAt, pending: false };
112
+ writeLocalStatuses(namespace, latest);
113
+ }
114
+ } catch {
115
+ // The local copy remains available and will be retried on the next status read.
116
+ }
117
+ }
@@ -0,0 +1,118 @@
1
+ // Quiz persistence: Convex when VITE_CONVEX_URL is set, localStorage fallback.
2
+ // Namespaced per bank via `namespace` so multiple banks can coexist.
3
+ // Framework-owned: eject with `qb reveal framework/lib/quiz-storage.ts`.
4
+
5
+ import { ConvexHttpClient } from 'convex/browser';
6
+ import { convexApi } from './convex-api.ts';
7
+ import type { QuizSession } from '../../core/types.ts';
8
+
9
+ const convexUrl = import.meta.env?.VITE_CONVEX_URL || (import.meta.env?.CONVEX_URL as string | undefined);
10
+ const convexClient = convexUrl ? new ConvexHttpClient(convexUrl) : null;
11
+
12
+ type QuizDocument = QuizSession & { _id: string; _creationTime: number };
13
+
14
+ const keyFor = (namespace: string) => `${namespace}-question-bank-quizzes`;
15
+
16
+ const readLocalQuizzes = (namespace: string): QuizSession[] => {
17
+ if (typeof window === 'undefined') return [];
18
+ try {
19
+ const value: unknown = JSON.parse(window.localStorage.getItem(keyFor(namespace)) ?? '[]');
20
+ return Array.isArray(value) ? (value as QuizSession[]) : [];
21
+ } catch {
22
+ return [];
23
+ }
24
+ };
25
+
26
+ const writeLocalQuizzes = (namespace: string, quizzes: QuizSession[]) => {
27
+ if (typeof window !== 'undefined') window.localStorage.setItem(keyFor(namespace), JSON.stringify(quizzes));
28
+ };
29
+
30
+ export function saveQuizLocally(namespace: string, session: QuizSession): void {
31
+ writeLocalQuizzes(namespace, [session, ...readLocalQuizzes(namespace).filter((quiz) => quiz.id !== session.id)]);
32
+ }
33
+
34
+ export async function deleteQuiz(namespace: string, id: string): Promise<void> {
35
+ if (convexClient && !id.startsWith('local_')) {
36
+ await convexClient.mutation(convexApi.quizzes.remove, { quizId: id });
37
+ }
38
+ writeLocalQuizzes(
39
+ namespace,
40
+ readLocalQuizzes(namespace).filter((quiz) => quiz.id !== id),
41
+ );
42
+ }
43
+
44
+ const fromDocument = (document: QuizDocument): QuizSession => ({
45
+ id: document._id,
46
+ title: document.title,
47
+ questionIds: document.questionIds,
48
+ answers: document.answers,
49
+ currentQuestion: document.currentQuestion,
50
+ completed: document.completed,
51
+ createdAt: document.createdAt ?? document._creationTime,
52
+ });
53
+
54
+ export async function createQuiz(namespace: string, title: string, questionIds: string[]): Promise<QuizSession> {
55
+ const localSession: QuizSession = {
56
+ id: `local_${crypto.randomUUID()}`,
57
+ title,
58
+ questionIds,
59
+ answers: {},
60
+ currentQuestion: 0,
61
+ completed: false,
62
+ createdAt: Date.now(),
63
+ };
64
+
65
+ if (convexClient) {
66
+ try {
67
+ const id = await convexClient.mutation(convexApi.quizzes.create, { title, questionIds });
68
+ return { ...localSession, id };
69
+ } catch {
70
+ writeLocalQuizzes(namespace, [localSession, ...readLocalQuizzes(namespace)]);
71
+ return localSession;
72
+ }
73
+ }
74
+
75
+ writeLocalQuizzes(namespace, [localSession, ...readLocalQuizzes(namespace)]);
76
+ return localSession;
77
+ }
78
+
79
+ export async function getQuiz(namespace: string, id: string): Promise<QuizSession | null> {
80
+ const localSession = readLocalQuizzes(namespace).find((quiz) => quiz.id === id);
81
+ if (id.startsWith('local_') || !convexClient) return localSession ?? null;
82
+ try {
83
+ const document = await convexClient.query(convexApi.quizzes.get, { quizId: id });
84
+ return document ? fromDocument(document) : (localSession ?? null);
85
+ } catch {
86
+ return localSession ?? null;
87
+ }
88
+ }
89
+
90
+ export async function saveQuizProgress(
91
+ namespace: string,
92
+ session: QuizSession,
93
+ progress: Pick<QuizSession, 'title' | 'answers' | 'currentQuestion' | 'completed'>,
94
+ ): Promise<void> {
95
+ const updated = { ...session, ...progress };
96
+ saveQuizLocally(namespace, updated);
97
+ if (!convexClient || updated.id.startsWith('local_')) return;
98
+ await convexClient.mutation(convexApi.quizzes.saveProgress, {
99
+ quizId: updated.id,
100
+ title: updated.title,
101
+ answers: updated.answers,
102
+ currentQuestion: updated.currentQuestion,
103
+ completed: updated.completed,
104
+ });
105
+ }
106
+
107
+ export async function listQuizzes(namespace: string): Promise<QuizSession[]> {
108
+ const localQuizzes = readLocalQuizzes(namespace);
109
+ if (!convexClient) return localQuizzes;
110
+ try {
111
+ const documents = await convexClient.query(convexApi.quizzes.list, {});
112
+ const remoteQuizzes = documents.map(fromDocument);
113
+ const ids = new Set(remoteQuizzes.map((quiz) => quiz.id));
114
+ return [...remoteQuizzes, ...localQuizzes.filter((quiz) => !ids.has(quiz.id))];
115
+ } catch {
116
+ return localQuizzes;
117
+ }
118
+ }
@@ -0,0 +1,6 @@
1
+ import { clsx, type ClassValue } from 'clsx';
2
+ import { twMerge } from 'tailwind-merge';
3
+
4
+ export function cn(...inputs: ClassValue[]) {
5
+ return twMerge(clsx(inputs));
6
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "question-bank-framework",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Framework-style question bank: TanStack Start + TanStack Table grid, quizzes, and filter DSL. Bring your own bank.config.ts + content/. Eject any framework/ file with `qb reveal` (Vike-style).",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/wra-bradshaw/question-bank.git"
10
+ },
11
+ "exports": {
12
+ ".": "./core/index.ts",
13
+ "./core": "./core/index.ts",
14
+ "./framework": "./framework/index.ts",
15
+ "./framework/*": "./framework/*",
16
+ "./template/*": "./template/*"
17
+ },
18
+ "bin": {
19
+ "qb": "./bin/qb.js"
20
+ },
21
+ "files": [
22
+ "core",
23
+ "framework",
24
+ "template",
25
+ "bin",
26
+ "README.md"
27
+ ],
28
+ "scripts": {
29
+ "typecheck": "tsc --noEmit",
30
+ "changeset": "changeset",
31
+ "version-packages": "changeset version",
32
+ "release": "pnpm build:bin && changeset publish",
33
+ "reveal": "node ./bin/qb.js reveal",
34
+ "template:check": "node ./bin/qb.js check-template",
35
+ "build:bin": "tsc bin/qb.ts --ignoreConfig --outDir bin --target es2022 --module nodenext --moduleResolution nodenext --strict --skipLibCheck --types node && chmod +x bin/qb.js"
36
+ },
37
+ "peerDependencies": {
38
+ "@tanstack/react-router": "^1.170.0",
39
+ "react": "^19.2.0",
40
+ "react-dom": "^19.2.0"
41
+ },
42
+ "dependencies": {
43
+ "@tanstack/react-table": "^8.21.3",
44
+ "@tanstack/react-virtual": "^3.14.19",
45
+ "class-variance-authority": "^0.7.1",
46
+ "clsx": "^2.1.1",
47
+ "convex": "^1.46.0",
48
+ "katex": "^0.19.0",
49
+ "lucide-react": "^1.57.0",
50
+ "radix-ui": "^1.8.1",
51
+ "react-markdown": "^10.1.0",
52
+ "rehype-katex": "^7.0.1",
53
+ "remark-gfm": "^4.0.1",
54
+ "remark-math": "^6.0.0",
55
+ "tailwind-merge": "^3.7.0",
56
+ "zustand": "^5.0.15"
57
+ },
58
+ "devDependencies": {
59
+ "@changesets/changelog-github": "^1.0.1",
60
+ "@changesets/cli": "^3.0.3",
61
+ "@tanstack/react-router": "1.170.44",
62
+ "@types/node": "^22.10.2",
63
+ "@types/react": "^19.2.0",
64
+ "@types/react-dom": "^19.2.0",
65
+ "typescript": "^6.0.2",
66
+ "vite": "^8.3.5"
67
+ }
68
+ }