-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
468 lines (399 loc) · 16.7 KB
/
script.js
File metadata and controls
468 lines (399 loc) · 16.7 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
let topics = [];
let currentFilter = 'all';
let currentSearch = '';
let currentTopic = null;
let currentLanguage = 'en';
function openFeedbackForm() {
window.open('https://docs.google.com/forms/d/e/1FAIpQLScKU5S8Qd1oNRANrFGIPTO35b9fa24aTY5wWOBkTLRdsG1DPA/viewform?usp=dialog', '_blank');
}
// Load topics from JSON file
async function loadTopics() {
try {
const categories = ['algorithms', 'core', 'data-structures', 'programming', 'setup'];
const allTopics = [];
// Load each category file
for (const category of categories) {
try {
const response = await fetch(`data/${category}/${category}.json`);
const categoryTopics = await response.json();
allTopics.push(...categoryTopics);
} catch (error) {
console.warn(`Could not load ${category}.json:`, error);
}
}
topics = allTopics;
init();
} catch (error) {
console.error('Error loading topics:', error);
topics = [];
init();
}
}
function init() {
renderCategories();
renderTopics();
loadTheme();
loadAccessibilitySettings();
}
function renderCategories() {
const categories = ['all', ...new Set(topics.map(t => t.category))];
const container = document.getElementById('categories');
container.innerHTML = categories.map(cat =>
`<button class="category-btn ${cat === 'all' ? 'active' : ''}" onclick="filterByCategory('${cat}')">
${cat.charAt(0).toUpperCase() + cat.slice(1).replace('-', ' ')}
</button>`
).join('');
}
function renderTopics() {
const filtered = topics.filter(topic => {
const matchesCategory = currentFilter === 'all' || topic.category === currentFilter;
const matchesSearch = currentSearch === '' ||
topic.title.toLowerCase().includes(currentSearch.toLowerCase()) ||
topic.description.toLowerCase().includes(currentSearch.toLowerCase());
return matchesCategory && matchesSearch;
});
const grid = document.getElementById('topicsGrid');
if (filtered.length === 0) {
grid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: var(--text-secondary);">No topics found. Try a different search or category.</p>';
return;
}
grid.innerHTML = filtered.map(topic => `
<div class="topic-card" onclick="showDetailPage('${topic.title.replace(/'/g, "\\'")}')">
<div class="topic-category">${topic.category}</div>
<div class="topic-title">${topic.title}</div>
<div class="topic-description">${topic.description}</div>
</div>
`).join('');
}
function filterByCategory(category) {
currentFilter = category;
document.querySelectorAll('.category-btn').forEach(btn => {
btn.classList.toggle('active', btn.textContent.toLowerCase().trim() === category.replace('-', ' '));
});
renderTopics();
}
function filterTopics() {
currentSearch = document.getElementById('searchInput').value;
renderTopics();
}
function showDetailPage(title) {
currentTopic = topics.find(t => t.title === title);
if (!currentTopic) return;
// Add to browser history
history.pushState({ page: 'detail', title: title }, '', `#${encodeURIComponent(title)}`);
document.getElementById('homePage').style.display = 'none';
document.getElementById('detailPage').classList.add('active');
document.getElementById('detailTitle').textContent = currentTopic.title;
document.getElementById('detailCategory').textContent = currentTopic.category;
document.getElementById('detailOverview').textContent = currentTopic.description;
document.getElementById('detailExplanation').textContent = currentTopic.details;
// Handle video - only show if videoUrl exists and is not empty
const videoSection = document.getElementById('videoSection');
if (currentTopic.videoUrl && currentTopic.videoUrl.trim() !== '') {
videoSection.style.display = 'block';
const videoContainer = document.getElementById('videoContainer');
videoContainer.innerHTML = `<iframe src="${currentTopic.videoUrl}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
} else {
videoSection.style.display = 'none';
}
const examplesList = document.getElementById('detailExamples');
if (currentTopic.examples && currentTopic.examples.length > 0) {
examplesList.innerHTML = currentTopic.examples.map(ex => `<li>${ex}</li>`).join('');
} else {
examplesList.innerHTML = '<p style="color: var(--text-secondary);">Examples will be added soon.</p>';
}
const resourceList = document.getElementById('resourceList');
if (currentTopic.resources && currentTopic.resources.length > 0) {
resourceList.innerHTML = currentTopic.resources.map(res => `
<li class="resource-item" onclick="window.open('${res.url}', '_blank')">
<span class="resource-icon">${res.icon}</span>
<span>${res.title}</span>
</li>
`).join('');
} else {
resourceList.innerHTML = '<p style="color: var(--text-secondary);">No external resources available yet.</p>';
}
// Render code exercises
const codeExercisesContainer = document.getElementById('codeExercisesContainer');
if (currentTopic.codeExercises && currentTopic.codeExercises.length > 0) {
document.getElementById('codeExercisesSection').style.display = 'block';
codeExercisesContainer.innerHTML = currentTopic.codeExercises.map(exercise => `
<div class="exercise-card">
<div class="exercise-header">
<h3>${exercise.title}</h3>
<span class="difficulty-badge ${exercise.difficulty.toLowerCase()}">${exercise.difficulty}</span>
</div>
<button class="download-btn" onclick="downloadFile('exercises/${exercise.filename}', '${exercise.filename}')">
📥 Download ${exercise.filename}
</button>
</div>
`).join('');
} else {
document.getElementById('codeExercisesSection').style.display = 'none';
}
renderQuiz();
window.scrollTo(0, 0);
}
function showHomePage() {
// Add to browser history if not already on home
if (window.location.hash) {
history.pushState({ page: 'home' }, '', window.location.pathname);
}
document.getElementById('homePage').style.display = 'block';
document.getElementById('detailPage').classList.remove('active');
window.scrollTo(0, 0);
}
function downloadFile(filepath, filename) {
const link = document.createElement('a');
link.href = filepath;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function renderQuiz() {
const container = document.getElementById('quizContainer');
if (!currentTopic.quiz || currentTopic.quiz.length === 0) {
container.innerHTML = '<p style="color: var(--text-secondary);">No practice questions available yet.</p>';
return;
}
container.innerHTML = currentTopic.quiz.map((q, idx) => `
<div class="quiz-question">
<div class="question-text">${idx + 1}. ${q.question}</div>
<div class="quiz-options">
${q.options.map((opt, optIdx) => `
<div class="quiz-option" onclick="selectOption(${idx}, ${optIdx})" data-question="${idx}" data-option="${optIdx}">
${opt}
</div>
`).join('')}
</div>
<button class="check-answer-btn" onclick="checkAnswer(${idx}, ${q.correct})" disabled>Check Answer</button>
<div class="feedback" id="feedback-${idx}"></div>
</div>
`).join('');
}
function selectOption(questionIdx, optionIdx) {
const options = document.querySelectorAll(`[data-question="${questionIdx}"]`);
options.forEach((opt, idx) => {
opt.classList.toggle('selected', idx === optionIdx);
});
const btn = options[0].parentElement.nextElementSibling;
btn.disabled = false;
btn.dataset.selected = optionIdx;
}
function checkAnswer(questionIdx, correctIdx) {
const btn = event.target;
const selectedIdx = parseInt(btn.dataset.selected);
const options = document.querySelectorAll(`[data-question="${questionIdx}"]`);
const feedback = document.getElementById(`feedback-${questionIdx}`);
options.forEach((opt, idx) => {
opt.onclick = null;
if (idx === correctIdx) {
opt.classList.add('correct');
} else if (idx === selectedIdx) {
opt.classList.add('incorrect');
}
opt.classList.remove('selected');
});
if (selectedIdx === correctIdx) {
feedback.textContent = '✅ Correct! Well done!';
feedback.className = 'feedback correct show';
} else {
feedback.textContent = '❌ Incorrect. Try reviewing the material above.';
feedback.className = 'feedback incorrect show';
}
btn.disabled = true;
}
function toggleTheme() {
const html = document.documentElement;
const currentTheme = html.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeButton(newTheme);
}
function updateThemeButton(theme) {
document.getElementById('themeIcon').textContent = theme === 'dark' ? '☀️' : '🌙';
document.getElementById('themeText').textContent = theme === 'dark' ? 'Light Mode' : 'Dark Mode';
}
function loadTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeButton(savedTheme);
}
// Language selector functions
function toggleLanguageDropdown() {
const dropdown = document.getElementById('languageDropdown');
const btn = document.querySelector('.language-btn');
dropdown.classList.toggle('show');
btn.classList.toggle('active');
}
function changeLanguage(langCode, displayText) {
currentLanguage = langCode;
document.getElementById('currentLanguage').textContent = displayText;
toggleLanguageDropdown();
// If switching to English, just reload the page
if (langCode === 'en') {
// Store current page state
const currentTopic = window.location.hash;
// Clear any Google Translate cookies
document.cookie = 'googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = 'googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=' + window.location.hostname;
// Reload page
if (currentTopic) {
window.location.href = window.location.pathname + currentTopic;
} else {
window.location.href = window.location.pathname;
}
return;
}
// For other languages, use Google Translate
setTimeout(() => {
const select = document.querySelector('.goog-te-combo');
if (select) {
select.value = langCode;
select.dispatchEvent(new Event('change'));
}
}, 500);
}
// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
const languageSelector = document.querySelector('.language-selector');
if (languageSelector && !languageSelector.contains(event.target)) {
document.getElementById('languageDropdown').classList.remove('show');
const btn = document.querySelector('.language-btn');
if (btn) btn.classList.remove('active');
}
});
// Handle browser back/forward buttons
window.addEventListener('popstate', function(event) {
if (event.state && event.state.page === 'detail') {
const title = event.state.title;
const topic = topics.find(t => t.title === title);
if (topic) {
showDetailPage(title);
}
} else {
showHomePage();
}
});
// Handle page load with hash (direct links)
window.addEventListener('load', function() {
if (window.location.hash) {
const title = decodeURIComponent(window.location.hash.substring(1));
const topic = topics.find(t => t.title === title);
if (topic) {
showDetailPage(title);
}
}
});
// Accessibility Functions
let accessibilitySettings = {
fontSize: 'medium',
highContrast: false,
dyslexiaFont: false,
reducedMotion: false,
focusHighlight: false
};
function toggleAccessibilityPanel() {
const panel = document.getElementById('accessibilityPanel');
panel.classList.toggle('open');
}
function changeFontSize(size) {
document.body.classList.remove('font-small', 'font-medium', 'font-large', 'font-xlarge', 'font-xxlarge');
document.body.classList.add(`font-${size}`);
document.querySelectorAll('.font-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.size === size) {
btn.classList.add('active');
}
});
accessibilitySettings.fontSize = size;
saveAccessibilitySettings();
}
function toggleHighContrast() {
const isChecked = document.getElementById('highContrast').checked;
document.body.classList.toggle('high-contrast', isChecked);
accessibilitySettings.highContrast = isChecked;
saveAccessibilitySettings();
}
function toggleDyslexiaFont() {
const isChecked = document.getElementById('dyslexiaFont').checked;
document.body.classList.toggle('dyslexia-font', isChecked);
accessibilitySettings.dyslexiaFont = isChecked;
saveAccessibilitySettings();
}
function toggleReducedMotion() {
const isChecked = document.getElementById('reducedMotion').checked;
document.body.classList.toggle('reduced-motion', isChecked);
accessibilitySettings.reducedMotion = isChecked;
saveAccessibilitySettings();
}
function toggleFocusHighlight() {
const isChecked = document.getElementById('focusHighlight').checked;
document.body.classList.toggle('focus-highlight', isChecked);
accessibilitySettings.focusHighlight = isChecked;
saveAccessibilitySettings();
}
function resetAccessibility() {
accessibilitySettings = {
fontSize: 'medium',
highContrast: false,
dyslexiaFont: false,
reducedMotion: false,
focusHighlight: false
};
document.body.classList.remove('font-small', 'font-large', 'font-xlarge', 'font-xxlarge', 'high-contrast', 'dyslexia-font', 'reduced-motion', 'focus-highlight');
document.body.classList.add('font-medium');
document.getElementById('highContrast').checked = false;
document.getElementById('dyslexiaFont').checked = false;
document.getElementById('reducedMotion').checked = false;
document.getElementById('focusHighlight').checked = false;
document.querySelectorAll('.font-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.size === 'medium') {
btn.classList.add('active');
}
});
saveAccessibilitySettings();
}
function saveAccessibilitySettings() {
localStorage.setItem('accessibilitySettings', JSON.stringify(accessibilitySettings));
}
function loadAccessibilitySettings() {
const saved = localStorage.getItem('accessibilitySettings');
if (saved) {
accessibilitySettings = JSON.parse(saved);
changeFontSize(accessibilitySettings.fontSize);
if (accessibilitySettings.highContrast) {
document.getElementById('highContrast').checked = true;
document.body.classList.add('high-contrast');
}
if (accessibilitySettings.dyslexiaFont) {
document.getElementById('dyslexiaFont').checked = true;
document.body.classList.add('dyslexia-font');
}
if (accessibilitySettings.reducedMotion) {
document.getElementById('reducedMotion').checked = true;
document.body.classList.add('reduced-motion');
}
if (accessibilitySettings.focusHighlight) {
document.getElementById('focusHighlight').checked = true;
document.body.classList.add('focus-highlight');
}
}
}
// Close accessibility panel when clicking outside
document.addEventListener('click', function(event) {
const panel = document.getElementById('accessibilityPanel');
const toggleBtn = document.querySelector('.accessibility-toggle');
if (panel && toggleBtn && !panel.contains(event.target) && !toggleBtn.contains(event.target)) {
panel.classList.remove('open');
}
});
// Load accessibility settings on page load
window.addEventListener('load', function() {
loadAccessibilitySettings();
});
// Start the app
loadTopics();