-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
844 lines (730 loc) · 30.1 KB
/
Copy pathcontent.js
File metadata and controls
844 lines (730 loc) · 30.1 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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
// 监听来自扩展弹出窗口的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("收到消息:", request);
if (request.action === 'startToeflPractice') {
// 立即回复消息,表明已收到
sendResponse({status: "正在处理..."});
try {
startToeflPractice();
} catch (error) {
console.error("启动托福练习时出错:", error);
alert("启动托福练习时出错: " + error.message);
}
}
// 返回true表示异步处理响应
return true;
});
// 启动托福阅读练习
async function startToeflPractice() {
try {
// 提取页面中的文本内容
let content = extractPageContent();
// 如果没有足够的内容,退出
if (content.length === 0) {
// 不需要额外提示,extractPageContent已经显示了适当的提示
return;
}
// 获取模型信息
const settings = await new Promise((resolve) => {
chrome.storage.local.get(['apiKey'], function(result) {
resolve({
apiKey: result.apiKey,
model: config.model,
systemPrompt: config.systemPrompt
});
});
});
let selectedModel = settings.model;
// 生成加载提示
showLoadingOverlay(`Generating TOEFL questions using ${selectedModel}...`);
// 生成TOEFL问题 - 使用await等待异步操作完成
const questions = await generateToeflQuestions(content);
// 移除加载提示
removeLoadingOverlay();
// 创建TOEFL界面
createToeflInterface(content, questions, questions.modelInfo || selectedModel);
} catch (error) {
// 移除加载提示
removeLoadingOverlay();
console.error("启动托福练习时出错:", error);
alert("启动托福练习时出错: " + error.message);
}
}
// 显示加载中的覆盖层
function showLoadingOverlay(message, model) {
const overlay = document.createElement('div');
overlay.id = 'toefl-loading-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9999;
color: white;
font-family: Arial, sans-serif;
`;
const spinner = document.createElement('div');
spinner.className = 'toefl-spinner';
spinner.style.cssText = `
border: 5px solid #f3f3f3;
border-top: 5px solid #0a5eb7;
border-radius: 50%;
width: 50px;
height: 50px;
animation: toefl-spin 2s linear infinite;
margin-bottom: 20px;
`;
const style = document.createElement('style');
style.innerHTML = `
@keyframes toefl-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
const messageElem = document.createElement('div');
messageElem.textContent = message || 'Loading...';
messageElem.style.cssText = `
font-size: 18px;
margin-top: 15px;
`;
document.head.appendChild(style);
overlay.appendChild(spinner);
overlay.appendChild(messageElem);
document.body.appendChild(overlay);
}
// 移除加载覆盖层
function removeLoadingOverlay() {
const overlay = document.getElementById('toefl-loading-overlay');
if (overlay) {
overlay.remove();
}
}
// 提取页面中的文本内容 - 优先使用用户选中的文本
function extractPageContent() {
// 检查用户是否有选中的文本
const selectedText = window.getSelection().toString().trim();
// 按空格分割计算词数
const wordCount = selectedText ? selectedText.split(/\s+/).length : 0;
// 检查选中文本的词数
if (selectedText.length === 0) {
alert('No text selected. Please select some text from the page.');
return '';
} else if (wordCount < 300) {
alert(`The selected text is too short (${wordCount} words). Please select at least 300 words.`);
return '';
} else if (wordCount > 1400) {
alert(`The selected text is too long (${wordCount} words). Please select no more than 1400 words.`);
return '';
}
// 如果文本词数符合要求,直接返回选中的文本
console.log("使用用户选中的文本,词数:", wordCount);
return selectedText;
}
// 生成托福阅读题
async function generateToeflQuestions(content) {
try {
// 获取保存的API设置
const settings = await new Promise((resolve) => {
chrome.storage.local.get(['apiKey'], function(result) {
resolve({
apiKey: result.apiKey,
model: config.model,
systemPrompt: config.systemPrompt
});
});
});
// 验证API密钥
if (!settings.apiKey) {
throw new Error("OpenRouter API key not found. Please configure it in the extension settings.");
}
// 计算文本长度与推荐题目数量的关系
const wordCount = content.split(/\s+/).length;
// 根据文本长度动态选择模型
let selectedModel = config.model;
if (wordCount > 1000) {
selectedModel = "google/gemini-2.0-flash-001";
console.log(`文本长度超过1000词(${wordCount}词),使用模型: ${selectedModel}`);
} else {
console.log(`文本长度为${wordCount}词,使用默认模型: ${selectedModel}`);
}
// 按照700词对应10题的比例计算,但至少3道题
const recommendedQuestionCount = Math.max(3, Math.round(wordCount * 10 / 700));
// 计算推荐时间(按照700词20分钟的比例,但至少2分钟)
const recommendedTimeMinutes = Math.max(2, Math.round(wordCount * 20 / 700));
// 构建用户提示
const userPrompt = `
Create exactly ${recommendedQuestionCount} TOEFL reading comprehension questions based on the following passage.
The questions should be of varying types: main idea, detail, inference, vocabulary, rhetorical purpose, reference, and paraphrase.
IMPORTANT REQUIREMENTS:
1. Each question must have 4 options (A, B, C, D) and indicate the correct answer.
2. QUESTION ORDER: Questions must follow the passage's organization.
- First questions should relate to the beginning of the passage
- Middle questions to the middle sections
- Only the last 1-2 questions should be summary/main idea questions about the entire passage
3. For each question, include an explanation field that explains why the correct answer is right and why other options are wrong.
At the same time, avoid answers always appearing in the longest or shortest option.
4. One third of the questions should be thought-provoking, but the answer must be clearly deducible. There should be no ambiguity in the answer.
5. Return your response in valid JSON format as an array of question objects:
${config.exampleFormat}
Here is the passage:
"${content.substring(0, 3000)}" // Limit content length to avoid token limits
`;
console.log("Sending request to OpenRouter API");
// 将计算出的时间传递给界面
const practiceTimeMinutes = recommendedTimeMinutes;
// 调用OpenRouter API
const response = await fetch(config.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${settings.apiKey}`,
'HTTP-Referer': 'https://toefl-practice.extension'
},
body: JSON.stringify({
model: selectedModel,
messages: [
{
role: "system",
content: settings.systemPrompt
},
{
role: "user",
content: userPrompt
}
],
max_tokens: 25000,
temperature: 0.7
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`OpenRouter API Error: ${errorData.error?.message || response.statusText}`);
}
const data = await response.json();
const aiResponse = data.choices[0].message.content;
console.log("Received response from OpenRouter API");
// 扩展返回的question对象,添加modelInfo字段
const modelInfo = data.model || selectedModel;
// 解析AI响应中的JSON
let parsedQuestions;
try {
// 查找JSON部分
const jsonMatch = aiResponse.match(/\[[\s\S]*\]/);
if (jsonMatch) {
parsedQuestions = JSON.parse(jsonMatch[0]);
} else {
throw new Error("No valid JSON found in the response");
}
} catch (error) {
console.error("Error parsing AI response:", error);
console.log("Raw AI response:", aiResponse);
// 回退到硬编码的问题
const fallbackQuestions = generateFallbackQuestions(content, recommendedQuestionCount);
fallbackQuestions.modelInfo = "Fallback Generator";
fallbackQuestions.practiceTimeMinutes = practiceTimeMinutes;
fallbackQuestions.wordCount = wordCount;
return fallbackQuestions;
}
// 验证问题格式
const validatedQuestions = validateQuestions(parsedQuestions, recommendedQuestionCount, content);
validatedQuestions.modelInfo = modelInfo;
validatedQuestions.practiceTimeMinutes = practiceTimeMinutes;
validatedQuestions.wordCount = wordCount;
return validatedQuestions;
} catch (error) {
console.error("Error generating questions using API:", error);
alert(`Error: ${error.message}. Falling back to basic questions.`);
// 回退到硬编码的问题
const fallbackQuestions = generateFallbackQuestions(content, recommendedQuestionCount);
fallbackQuestions.modelInfo = "Fallback Generator";
fallbackQuestions.practiceTimeMinutes = recommendedTimeMinutes || 20;
fallbackQuestions.wordCount = wordCount || 700;
return fallbackQuestions;
}
}
// 验证问题格式并确保必要的字段
function validateQuestions(questions, count, content) {
const validQuestions = questions.filter(q => {
return q && q.text && Array.isArray(q.options) &&
q.options.length === 4 &&
typeof q.correctAnswer === 'number' &&
q.correctAnswer >= 0 && q.correctAnswer < 4;
});
// 确保所有问题都有解释字段
validQuestions.forEach(q => {
if (!q.explanation) {
q.explanation = `The correct answer is option ${['A', 'B', 'C', 'D'][q.correctAnswer]} because it best matches the information presented in the passage.`;
}
});
// 确保问题数量符合要求
if (validQuestions.length < count) {
const diff = count - validQuestions.length;
const fallback = generateFallbackQuestions(content, diff);
return [...validQuestions, ...fallback].slice(0, count);
}
return validQuestions.slice(0, count);
}
// 生成回退用的基础问题(与原始函数相同)
function generateFallbackQuestions(content, count) {
const questions = [];
// 问题类型
const questionTypes = config.questionTypes;
// 提取内容中的重要单词
const contentWords = content.split(/\s+/);
const significantWords = contentWords.filter(word =>
word.length > 5 &&
!/^\d+$/.test(word) &&
!['which', 'there', 'their', 'about', 'would', 'could'].includes(word.toLowerCase())
);
// 生成主要思想问题
questions.push({
type: 'main idea',
text: 'What is the main idea of the passage?',
options: [
'The text primarily discusses developments in a specific field',
'The passage mainly criticizes a popular theory or approach',
'The author primarily describes historical events and their significance',
'The text focuses on comparing different perspectives on an issue'
],
correctAnswer: 0,
explanation: 'The text primarily discusses developments in a specific field, presenting different aspects and factors related to the main topic. The other options do not accurately capture the overall focus of the passage.'
});
// 生成细节问题
for (let i = 0; i < Math.min(count - 2, 4); i++) {
// 随机选择一个单词作为问题的焦点
const randomIndex = Math.floor(Math.random() * significantWords.length);
const focusWord = significantWords[randomIndex];
const correctIndex = Math.floor(Math.random() * 4);
questions.push({
type: 'detail',
text: `According to the passage, what does the author say about ${focusWord}?`,
options: [
`${focusWord} is mentioned as an important factor in the discussion`,
`${focusWord} is described as having minimal relevance to the main topic`,
`The author criticizes common misconceptions about ${focusWord}`,
`${focusWord} is presented as evidence supporting the author's argument`
],
correctAnswer: correctIndex,
explanation: `Option ${['A', 'B', 'C', 'D'][correctIndex]} is correct based on the context in which ${focusWord} appears in the passage. The other options misrepresent how ${focusWord} is discussed by the author.`
});
}
// 生成词汇题
const vocabularyWords = significantWords.filter(word => word.length > 6);
if (vocabularyWords.length > 0) {
const randomWord = vocabularyWords[Math.floor(Math.random() * vocabularyWords.length)];
const correctIndex = Math.floor(Math.random() * 4);
questions.push({
type: 'vocabulary',
text: `The word "${randomWord}" in paragraph 2 is closest in meaning to:`,
options: [
'A synonym option 1',
'A synonym option 2',
'A synonym option 3',
'A synonym option 4'
],
correctAnswer: correctIndex,
explanation: `Option ${['A', 'B', 'C', 'D'][correctIndex]} provides the closest meaning to "${randomWord}" as it is used in the context of paragraph 2. The other options do not accurately capture the intended meaning of the word in this context.`
});
}
// 生成推断题
const inferenceCorrectIndex = Math.floor(Math.random() * 4);
questions.push({
type: 'inference',
text: 'What can be inferred from the passage about the topic?',
options: [
'The subject is likely to evolve significantly in the near future',
'There is widespread disagreement about the fundamental principles involved',
'Traditional approaches to the subject are being gradually abandoned',
'The topic remains relevant despite changes in related fields'
],
correctAnswer: inferenceCorrectIndex,
explanation: `Option ${['A', 'B', 'C', 'D'][inferenceCorrectIndex]} can be reasonably inferred from the information presented in the passage, even though it is not explicitly stated. The other options go beyond what can be logically concluded from the text.`
});
// 确保问题数量符合要求
while (questions.length < count) {
const questionType = questionTypes[Math.floor(Math.random() * questionTypes.length)];
const additionalCorrectIndex = Math.floor(Math.random() * 4);
questions.push({
type: questionType,
text: `[${questionType.toUpperCase()}] Additional question about the passage:`,
options: [
'Option A',
'Option B',
'Option C',
'Option D'
],
correctAnswer: additionalCorrectIndex,
explanation: `Option ${['A', 'B', 'C', 'D'][additionalCorrectIndex]} is the correct answer based on the passage content. The other options are not supported by information in the text.`
});
}
// 如果生成了过多的问题,只返回要求的数量
return questions.slice(0, count);
}
// 创建托福风格的界面
function createToeflInterface(content, questions, modelName) {
// 保存当前页面的内容,以便稍后还原
const originalContent = document.documentElement.innerHTML;
// 将原始内容保存到本地存储中
chrome.storage.local.set({ originalContent: originalContent });
// 获取练习时间(分钟)和文章字数
const practiceTime = questions.practiceTimeMinutes || 20;
const wordCount = questions.wordCount || content.split(/\s+/).length;
// 创建托福风格的界面HTML
const toeflHTML = `
<div class="toefl-container">
<div class="toefl-header">
<div class="toefl-logo">TOEFL iBT® Reading Practice</div>
<div class="toefl-model-info">Generated by ${modelName}</div>
<div class="toefl-info">
<div class="toefl-wordcount">${wordCount} words</div>
<div class="toefl-timer">
<span id="toefl-minutes">${practiceTime}</span>:<span id="toefl-seconds">00</span>
</div>
</div>
<button id="toefl-exit" class="toefl-button">Exit Practice</button>
</div>
<div class="toefl-main">
<div class="toefl-reading-section">
<h3>Reading Passage</h3>
<div class="toefl-passage">
${formatContent(content)}
</div>
</div>
<div class="toefl-questions-section">
<h3>Questions</h3>
<div class="toefl-questions">
${generateQuestionsHTML(questions)}
</div>
<div class="toefl-navigation">
<button id="toefl-prev" class="toefl-button toefl-nav-button" disabled>Previous</button>
<div class="toefl-question-numbers">
${generateQuestionNumbersHTML(questions.length)}
</div>
<button id="toefl-next" class="toefl-button toefl-nav-button">Next</button>
</div>
<button id="toefl-review" class="toefl-button">Review Answers</button>
</div>
</div>
</div>
`;
// 创建新的文档
document.open();
document.write(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TOEFL Reading Practice</title>
<link rel="stylesheet" href="${chrome.runtime.getURL('toefl-style.css')}">
</head>
<body>
${toeflHTML}
<script src="${chrome.runtime.getURL('toefl-interface.js')}"></script>
</body>
</html>
`);
document.close();
// 添加托福界面的交互逻辑
setupToeflInterface(questions);
}
// 格式化阅读内容,添加段落编号
function formatContent(content) {
// 分段 - 使用更强的分段逻辑,同时保留原始段落结构
const paragraphs = content
.replace(/\n{2,}/g, '\n\n') // 规范化多个换行
.split(/\n\n+/) // 按照空行分段
.filter(p => p.trim().length > 0)
.map(p => p.trim()); // 去除每段首尾空白
return paragraphs.map((paragraph, index) => {
// 清理段落内的格式问题
const cleanedParagraph = paragraph
.replace(/\n/g, ' ') // 将段落内换行转为空格
.replace(/\s+/g, ' ') // 合并多个空格
.replace(/(\d+)\s*:/g, '') // 移除行号格式 (如 "1:")
.trim();
return `<div class="toefl-paragraph">
<span class="toefl-paragraph-number">${index + 1}</span>
<p>${cleanedParagraph}</p>
</div>`;
}).join('');
}
// 生成问题HTML
function generateQuestionsHTML(questions) {
return questions.map((question, index) => {
const optionLetters = ['A', 'B', 'C', 'D'];
return `
<div class="toefl-question" id="question-${index + 1}" ${index > 0 ? 'style="display: none;"' : ''}>
<div class="toefl-question-number">${index + 1} of ${questions.length}</div>
<div class="toefl-question-text">${question.text}</div>
<div class="toefl-options">
${question.options.map((option, optIndex) => `
<div class="toefl-option">
<label>
<input type="radio" name="q${index + 1}" value="${optIndex}" data-question="${index + 1}" data-option="${optIndex}">
<span class="toefl-option-letter">${optionLetters[optIndex]}</span>
<span class="toefl-option-text">${option}</span>
</label>
</div>
`).join('')}
</div>
<div class="toefl-explanation">
<h4>Explanation</h4>
<p>${question.explanation || 'No explanation available for this question.'}</p>
</div>
</div>
`;
}).join('');
}
// 生成问题导航数字HTML
function generateQuestionNumbersHTML(count) {
let html = '';
for (let i = 1; i <= count; i++) {
html += `<div class="toefl-question-number-item ${i === 1 ? 'active' : ''}" data-question="${i}">${i}</div>`;
}
return html;
}
// 设置托福界面的交互逻辑
function setupToeflInterface(questions) {
// 当DOM加载完成后执行
window.addEventListener('DOMContentLoaded', () => {
// 获取UI元素
const prevButton = document.getElementById('toefl-prev');
const nextButton = document.getElementById('toefl-next');
const numberItems = document.querySelectorAll('.toefl-question-number-item');
const questionElements = document.querySelectorAll('.toefl-question');
const exitButton = document.getElementById('toefl-exit');
const reviewButton = document.getElementById('toefl-review');
const minutesElement = document.getElementById('toefl-minutes');
const secondsElement = document.getElementById('toefl-seconds');
// 获取模型信息 (如果有的话)
const modelInfo = questions.modelInfo || document.querySelector('.toefl-model-info').textContent.replace('Generated by ', '');
// 当前问题索引
let currentQuestionIndex = 0;
// 用户回答
const userAnswers = new Array(questions.length).fill(null);
// 设置计时器
const practiceTime = questions.practiceTimeMinutes || 20;
let timeLeft = practiceTime * 60; // 转换为秒
const timerInterval = setInterval(() => {
timeLeft -= 1;
if (timeLeft <= 0) {
clearInterval(timerInterval);
showResults();
return;
}
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
minutesElement.textContent = minutes.toString().padStart(2, '0');
secondsElement.textContent = seconds.toString().padStart(2, '0');
}, 1000);
// 导航到特定问题
function navigateToQuestion(index) {
// 隐藏所有问题
questionElements.forEach(elem => elem.style.display = 'none');
// 显示当前问题
questionElements[index].style.display = 'block';
// 更新活动问题编号
numberItems.forEach((item, idx) => {
if (idx === index) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
// 更新导航按钮状态
prevButton.disabled = index === 0;
nextButton.disabled = index === questions.length - 1;
// 更新当前问题索引
currentQuestionIndex = index;
}
// 监听问题编号点击
numberItems.forEach((item, index) => {
item.addEventListener('click', () => {
navigateToQuestion(index);
});
});
// 监听下一题按钮
nextButton.addEventListener('click', () => {
if (currentQuestionIndex < questions.length - 1) {
navigateToQuestion(currentQuestionIndex + 1);
}
});
// 监听上一题按钮
prevButton.addEventListener('click', () => {
if (currentQuestionIndex > 0) {
navigateToQuestion(currentQuestionIndex - 1);
}
});
// 监听答案选择
document.querySelectorAll('input[type="radio"]').forEach(input => {
input.addEventListener('change', (e) => {
const questionIndex = parseInt(e.target.dataset.question) - 1;
const optionIndex = parseInt(e.target.dataset.option);
// 保存用户答案
userAnswers[questionIndex] = optionIndex;
// 更新问题编号样式以显示已回答
numberItems[questionIndex].classList.add('answered');
});
});
// 退出练习
exitButton.addEventListener('click', () => {
if (confirm('Are you sure you want to exit? Your progress will be lost.')) {
// 直接重新加载原始页面URL
window.location.reload();
}
});
// 显示结果
function showResults() {
// 计算得分
let correctCount = 0;
userAnswers.forEach((answer, index) => {
if (answer === questions[index].correctAnswer) {
correctCount++;
}
});
// 清除计时器
clearInterval(timerInterval);
// 禁用所有问题选项但不禁用导航
document.querySelectorAll('input[type="radio"]').forEach(input => {
input.disabled = true;
});
// 保持导航按钮可用,但改为查看答案模式
prevButton.disabled = currentQuestionIndex === 0;
nextButton.disabled = currentQuestionIndex === questions.length - 1;
reviewButton.disabled = true;
// 为计时器添加完成标记并在标题旁显示分数
document.querySelector('.toefl-timer').innerHTML += ' <span style="color: #4caf50;">(Completed)</span>';
// 在标题旁显示分数
const logoElement = document.querySelector('.toefl-logo');
logoElement.innerHTML = `TOEFL iBT® Reading Practice <span>${correctCount}/${questions.length}</span>`;
// 将问题部分切换到评估模式
const questionsSection = document.querySelector('.toefl-questions-section');
questionsSection.classList.add('review-mode');
// 更新问题导航标记,根据答案正确与否设置不同的样式
numberItems.forEach((item, index) => {
// 清除原来的回答标记
item.classList.remove('answered');
// 如果用户回答了这个问题
if (userAnswers[index] !== null) {
// 检查是否回答正确
if (userAnswers[index] === questions[index].correctAnswer) {
item.classList.add('answered-correct');
} else {
item.classList.add('answered-incorrect');
}
}
});
// 标记所有问题的选项为正确或错误
questionElements.forEach((questionElement, index) => {
const options = questionElement.querySelectorAll('.toefl-option');
options.forEach((option, optIndex) => {
// 清除现有的高亮
option.classList.remove('correct-answer', 'incorrect-answer');
// 标记正确答案
if (optIndex === questions[index].correctAnswer) {
option.classList.add('correct-answer');
}
// 如果用户选择了错误答案,标记为错误
if (userAnswers[index] !== null &&
optIndex === userAnswers[index] &&
userAnswers[index] !== questions[index].correctAnswer) {
option.classList.add('incorrect-answer');
}
});
// 显示解释 - 不再需要手动设置style.display,通过CSS控制
const explanationDiv = questionElement.querySelector('.toefl-explanation');
if (explanationDiv) {
// 移除这一行,因为我们现在通过CSS类控制显示
// explanationDiv.style.display = 'block';
}
});
// 添加保存按钮到退出按钮旁边
const saveButton = document.createElement('button');
saveButton.id = 'toefl-save';
saveButton.className = 'toefl-button';
saveButton.textContent = 'Save';
saveButton.style.marginLeft = '10px';
// 在退出按钮之后插入保存按钮
const headerElement = document.querySelector('.toefl-header');
headerElement.appendChild(saveButton);
// 监听保存按钮点击事件
saveButton.addEventListener('click', () => {
// 收集所有需要保存的数据
const practiceData = {
// 原文内容
passage: content,
// 字数
wordCount: content.split(/\s+/).length,
// 实际花费的做题时间(分钟和秒)
timeSpent: {
minutes: practiceTime - Math.floor(timeLeft / 60) - 1,
seconds: 60 - (timeLeft % 60)
},
// 问题、选项、用户选择和正确答案
questions: questions.map((question, index) => ({
text: question.text,
options: question.options,
userAnswer: userAnswers[index],
correctAnswer: question.correctAnswer,
explanation: question.explanation
})),
// 得分
score: {
correct: correctCount,
total: questions.length
}
};
// 创建JSON文件并下载
const dataStr = JSON.stringify(practiceData, null, 2);
const dataBlob = new Blob([dataStr], {type: 'application/json'});
const url = URL.createObjectURL(dataBlob);
// 创建下载链接
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = `toefl_practice_${new Date().toISOString().slice(0, 10)}.json`;
// 触发下载
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
// 触发导航函数更新界面
navigateToQuestion(currentQuestionIndex);
}
// 生成回顾HTML - 已不再使用,但保留以备将来需要
function generateReviewHTML(questions, userAnswers) {
return questions.map((question, index) => {
const optionLetters = ['A', 'B', 'C', 'D'];
const isCorrect = userAnswers[index] === question.correctAnswer;
return `
<div class="toefl-review-item ${isCorrect ? 'correct' : 'incorrect'}">
<div class="toefl-review-question">
<span class="toefl-review-number">${index + 1}.</span>
<span class="toefl-review-text">${question.text}</span>
</div>
<div class="toefl-review-result">
<span class="toefl-review-status">${isCorrect ? 'Correct' : 'Incorrect'}</span>
<div class="toefl-review-answers">
<div>Your answer: ${userAnswers[index] !== null ? optionLetters[userAnswers[index]] : 'Not answered'}</div>
<div>Correct answer: ${optionLetters[question.correctAnswer]}</div>
</div>
</div>
</div>
`;
}).join('');
}
// 查看结果按钮
reviewButton.addEventListener('click', () => {
// 确认是否提前结束
if (confirm('Are you sure you want to submit your answers and see your results?')) {
clearInterval(timerInterval);
showResults();
}
});
});
}