-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
456 lines (404 loc) · 19 KB
/
Copy pathApp.tsx
File metadata and controls
456 lines (404 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
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { BookOpen, List, Wand2, FileText, AlertCircle, Plus, ChevronRight, Upload, FileType, Loader2, Trash2, History, Save } from 'lucide-react';
import { SectionBuilder } from './components/SectionBuilder';
import { ExamPreview } from './components/ExamPreview';
import { Button } from './components/Button';
import { generateExam } from './services/geminiService';
import { extractTextFromPDF } from './services/pdfService';
import { AppState, QuestionType, SectionConfig, GradeLevel, Difficulty, PastPaper } from './types';
const INITIAL_SECTION: SectionConfig = {
id: '1',
type: QuestionType.MCQ,
questionCount: 5,
marksPerQuestion: 2,
title: '甲部:多項選擇題',
instructions: '請選出最正確的答案。'
};
const App: React.FC = () => {
const [state, setState] = useState<AppState>({
step: 1,
textbookContent: '',
pastPapers: [],
examTitle: '常識科測驗',
gradeLevel: GradeLevel.P3, // Default
difficulty: Difficulty.MEDIUM, // Default
sections: [INITIAL_SECTION],
generatedExam: null,
isLoading: false,
error: null
});
const [isReadingPdf, setIsReadingPdf] = useState(false);
const [isReadingPastPaper, setIsReadingPastPaper] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const pastPaperInputRef = useRef<HTMLInputElement>(null);
// Load past papers from localStorage on mount
useEffect(() => {
const savedPapers = localStorage.getItem('seg_past_papers');
if (savedPapers) {
try {
const parsed = JSON.parse(savedPapers);
setState(prev => ({ ...prev, pastPapers: parsed }));
} catch (e) {
console.error("Failed to load past papers", e);
}
}
}, []);
// Save past papers to localStorage whenever they change
useEffect(() => {
localStorage.setItem('seg_past_papers', JSON.stringify(state.pastPapers));
}, [state.pastPapers]);
const updateSection = useCallback((id: string, updates: Partial<SectionConfig>) => {
setState(prev => ({
...prev,
sections: prev.sections.map(s => s.id === id ? { ...s, ...updates } : s)
}));
}, []);
const addSection = useCallback(() => {
const newId = Math.random().toString(36).substr(2, 9);
const sectionIndex = state.sections.length;
const sectionChar = ["乙", "丙", "丁", "戊", "己", "庚"][sectionIndex] || String.fromCharCode(66 + sectionIndex);
const newSection: SectionConfig = {
id: newId,
type: QuestionType.SHORT_ANSWER,
questionCount: 3,
marksPerQuestion: 5,
title: `${sectionChar}部:短答題`,
instructions: '請簡短回答下列問題。'
};
setState(prev => ({
...prev,
sections: [...prev.sections, newSection]
}));
}, [state.sections]);
const removeSection = useCallback((id: string) => {
setState(prev => ({
...prev,
sections: prev.sections.filter(s => s.id !== id)
}));
}, []);
const handleTextbookUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
if (file.type !== 'application/pdf') {
setState(prev => ({ ...prev, error: "請上傳 PDF 格式的檔案。" }));
return;
}
setIsReadingPdf(true);
setState(prev => ({ ...prev, error: null }));
try {
const text = await extractTextFromPDF(file);
setState(prev => ({
...prev,
textbookContent: text
}));
} catch (err: any) {
setState(prev => ({ ...prev, error: err.message || "讀取 PDF 時發生錯誤。" }));
} finally {
setIsReadingPdf(false);
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
const handlePastPaperUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
if (file.type !== 'application/pdf') {
setState(prev => ({ ...prev, error: "過往試卷必須是 PDF 格式。" }));
return;
}
setIsReadingPastPaper(true);
setState(prev => ({ ...prev, error: null }));
try {
const text = await extractTextFromPDF(file);
const newPaper: PastPaper = {
id: Math.random().toString(36).substr(2, 9),
fileName: file.name,
content: text,
uploadDate: Date.now()
};
setState(prev => ({
...prev,
pastPapers: [...prev.pastPapers, newPaper]
}));
} catch (err: any) {
setState(prev => ({ ...prev, error: err.message || "讀取過往試卷 PDF 時發生錯誤。" }));
} finally {
setIsReadingPastPaper(false);
if (pastPaperInputRef.current) pastPaperInputRef.current.value = '';
}
};
const removePastPaper = (id: string) => {
setState(prev => ({
...prev,
pastPapers: prev.pastPapers.filter(p => p.id !== id)
}));
};
const handleGenerate = async () => {
if (!state.textbookContent.trim()) {
setState(prev => ({ ...prev, error: "請先輸入教科書內容或上傳 PDF。" }));
return;
}
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
const exam = await generateExam(
state.textbookContent,
state.pastPapers,
state.sections,
state.examTitle,
state.gradeLevel,
state.difficulty
);
setState(prev => ({ ...prev, generatedExam: exam, isLoading: false, step: 3 }));
} catch (err: any) {
setState(prev => ({ ...prev, isLoading: false, error: err.message || "發生未知錯誤。" }));
}
};
const handleReset = () => {
setState(prev => ({ ...prev, step: 1, generatedExam: null, error: null }));
};
return (
<div className="min-h-screen bg-gray-50 pb-20 font-sans">
{/* Header */}
<nav className="bg-white border-b border-gray-200 sticky top-0 z-10">
<div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="bg-indigo-600 p-2 rounded-lg">
<BookOpen className="text-white w-5 h-5" />
</div>
<span className="font-bold text-xl text-gray-900 tracking-tight">智能試卷生成器</span>
</div>
<div className="flex items-center gap-4 text-sm font-medium text-gray-500">
<span className={`flex items-center gap-1 ${state.step >= 1 ? 'text-indigo-600' : ''}`}>
<span className="w-6 h-6 rounded-full bg-indigo-100 flex items-center justify-center text-xs mr-1">1</span> 內容
</span>
<ChevronRight size={14} />
<span className={`flex items-center gap-1 ${state.step >= 2 ? 'text-indigo-600' : ''}`}>
<span className="w-6 h-6 rounded-full bg-indigo-100 flex items-center justify-center text-xs mr-1">2</span> 設定
</span>
<ChevronRight size={14} />
<span className={`flex items-center gap-1 ${state.step >= 3 ? 'text-indigo-600' : ''}`}>
<span className="w-6 h-6 rounded-full bg-indigo-100 flex items-center justify-center text-xs mr-1">3</span> 結果
</span>
</div>
</div>
</nav>
<main className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{state.error && (
<div className="mb-6 bg-red-50 border-l-4 border-red-500 p-4 rounded flex items-start gap-3">
<AlertCircle className="text-red-600 mt-0.5" />
<p className="text-red-700">{state.error}</p>
</div>
)}
{state.step === 1 && (
<div className="space-y-6 animate-fade-in">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">步驟一:提供教材與過往試卷</h1>
<p className="text-gray-500">請提供本次考試範圍的教科書內容,並可上傳過往試卷以避免題目重複。</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column: Textbook Input */}
<div className="lg:col-span-2 bg-white p-6 rounded-xl shadow-sm border border-gray-200 space-y-4">
<h2 className="font-bold text-gray-800 flex items-center gap-2 border-b pb-2">
<FileText className="text-indigo-600" size={20} /> 教科書內容 (本次範圍)
</h2>
{/* Textbook File Upload */}
<div className="border-2 border-dashed border-gray-300 rounded-lg p-6 flex flex-col items-center justify-center bg-gray-50 transition-colors hover:bg-indigo-50 hover:border-indigo-300">
<input
type="file"
accept="application/pdf"
ref={fileInputRef}
onChange={handleTextbookUpload}
className="hidden"
/>
{isReadingPdf ? (
<div className="flex flex-col items-center text-indigo-600">
<Loader2 className="w-8 h-8 animate-spin mb-2" />
<span className="font-medium">正在讀取 PDF...</span>
</div>
) : (
<div className="flex flex-col items-center">
<div className="bg-white p-3 rounded-full shadow-sm mb-3">
<Upload className="text-indigo-600 w-6 h-6" />
</div>
<Button variant="secondary" onClick={() => fileInputRef.current?.click()} className="mb-2">
上傳教科書 PDF
</Button>
<p className="text-xs text-gray-400">支援 PDF 格式檔案</p>
</div>
)}
</div>
{/* Text Area */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
或手動輸入文字
</label>
<textarea
className="w-full h-80 p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all font-mono text-sm leading-relaxed bg-white text-gray-900"
placeholder="在此貼上教科書內容..."
value={state.textbookContent}
onChange={(e) => setState(prev => ({...prev, textbookContent: e.target.value}))}
></textarea>
<div className="mt-2 text-right text-xs text-gray-400">
{state.textbookContent.length} 字
</div>
</div>
</div>
{/* Right Column: Past Papers */}
<div className="lg:col-span-1 bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col h-full">
<h2 className="font-bold text-gray-800 flex items-center gap-2 border-b pb-2 mb-4">
<History className="text-orange-600" size={20} /> 過往試卷 (防撞題)
</h2>
<div className="bg-orange-50 p-3 rounded-lg text-xs text-orange-800 mb-4 leading-relaxed border border-orange-100">
<span className="font-bold">提示:</span> 上傳過往 3 年的試卷 PDF。AI 將會分析這些內容,避免出題高度重複。內容會自動儲存在此瀏覽器中。
</div>
<input
type="file"
accept="application/pdf"
ref={pastPaperInputRef}
onChange={handlePastPaperUpload}
className="hidden"
/>
<Button
variant="secondary"
onClick={() => pastPaperInputRef.current?.click()}
isLoading={isReadingPastPaper}
className="w-full mb-4 border-dashed"
icon={<Plus size={16}/>}
>
加入過往試卷
</Button>
<div className="flex-1 overflow-y-auto space-y-3 min-h-[200px]">
{state.pastPapers.length === 0 ? (
<div className="text-center text-gray-400 py-8 italic text-sm">
暫無過往試卷紀錄
</div>
) : (
state.pastPapers.map(paper => (
<div key={paper.id} className="group flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100 hover:border-indigo-200 transition-all">
<div className="flex items-center gap-3 overflow-hidden">
<div className="bg-white p-2 rounded text-red-500 shadow-sm">
<FileType size={16} />
</div>
<div className="flex flex-col min-w-0">
<span className="text-sm font-medium text-gray-700 truncate block max-w-[150px]" title={paper.fileName}>
{paper.fileName}
</span>
<span className="text-[10px] text-gray-400">
{new Date(paper.uploadDate).toLocaleDateString()}
</span>
</div>
</div>
<button
onClick={() => removePastPaper(paper.id)}
className="text-gray-400 hover:text-red-500 p-1 rounded hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all"
>
<Trash2 size={16} />
</button>
</div>
))
)}
</div>
</div>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={() => setState(prev => ({ ...prev, step: 2 }))}
disabled={!state.textbookContent.trim() || isReadingPdf || isReadingPastPaper}
icon={<ChevronRight size={18} />}
>
下一步:設定試卷
</Button>
</div>
</div>
)}
{state.step === 2 && (
<div className="space-y-8 animate-fade-in">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">步驟二:試卷架構</h1>
<p className="text-gray-500">定義各部分的題型、題目數量及分數。</p>
</div>
<div className="bg-white p-6 rounded-xl border border-gray-200 shadow-sm grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="md:col-span-2">
<label className="block text-sm font-bold text-gray-700 mb-2">試卷標題</label>
<input
type="text"
value={state.examTitle}
onChange={(e) => setState(prev => ({...prev, examTitle: e.target.value}))}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white text-gray-900"
placeholder="例如:常識科期中試"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">適用年級</label>
<select
value={state.gradeLevel}
onChange={(e) => setState(prev => ({...prev, gradeLevel: e.target.value as GradeLevel}))}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white text-gray-900"
>
{Object.values(GradeLevel).map(g => (
<option key={g} value={g}>{g}</option>
))}
</select>
<p className="text-xs text-gray-500 mt-1">小四或以下年級,填充題會自動提供供詞欄 (Word Bank)。</p>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">題目難度</label>
<select
value={state.difficulty}
onChange={(e) => setState(prev => ({...prev, difficulty: e.target.value as Difficulty}))}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white text-gray-900"
>
{Object.values(Difficulty).map(d => (
<option key={d} value={d}>{d}</option>
))}
</select>
</div>
</div>
<div>
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold text-gray-800 flex items-center gap-2">
<List size={20} />
考核部分 (Sections)
</h2>
<Button variant="secondary" onClick={addSection} icon={<Plus size={16} />}>
新增部分
</Button>
</div>
{state.sections.map((section, index) => (
<SectionBuilder
key={section.id}
section={section}
index={index}
onUpdate={updateSection}
onRemove={removeSection}
/>
))}
<div className="bg-indigo-50 p-4 rounded-lg flex justify-between items-center border border-indigo-100">
<span className="text-indigo-800 font-medium">全卷總分</span>
<span className="text-2xl font-bold text-indigo-700">
{state.sections.reduce((acc, curr) => acc + (curr.questionCount * curr.marksPerQuestion), 0)} 分
</span>
</div>
</div>
<div className="flex justify-between pt-4 border-t border-gray-200">
<Button variant="ghost" onClick={() => setState(prev => ({...prev, step: 1}))}>
返回
</Button>
<Button
onClick={handleGenerate}
isLoading={state.isLoading}
icon={<Wand2 size={18} />}
className="bg-indigo-600 hover:bg-indigo-700"
>
生成試卷
</Button>
</div>
</div>
)}
{state.step === 3 && state.generatedExam && (
<ExamPreview exam={state.generatedExam} onReset={handleReset} />
)}
</main>
</div>
);
};
export default App;