-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1748 lines (1508 loc) · 70.1 KB
/
script.js
File metadata and controls
1748 lines (1508 loc) · 70.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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// script.js
// Audio setup using Tone.js
// A simple synth for the chime sound
const chime = new Tone.Synth().toDestination();
// A membrane synth for a percussive buzzer sound
const buzzer = new Tone.MembraneSynth().toDestination();
// Theme Management
// Removed currentTheme variable as there's only one theme (light)
let customColors = {
light: {}
};
// Default color definitions (as hex, for storage and pickers)
const defaultLightColors = {
'--primary-color': '#6C63FF',
'--secondary-color': '#D9FF87',
'--bg-primary': '#ffffff',
'--bg-secondary': '#f8f9ff',
'--text-primary': '#2c3e50',
'--text-secondary': '#7f8c8d',
'--glass-bg': '#ffffff', // Stored as hex, alpha applied when setting CSS var
'--glass-border': '#6C63FF', // Stored as hex, alpha applied when setting CSS var
'--card-bg': '#ffffff', // Stored as hex, alpha applied when setting CSS var
'--popup-bg-start': '#f0f0f0',
'--popup-bg-end': '#e0e0e0',
'--popup-border': '#cccccc',
'--popup-shadow-color': '#000000', // Stored as hex, alpha applied when setting CSS var
'--popup-accent-glow': '#6C63FF' // Stored as hex, alpha applied when setting CSS var
};
// Removed defaultDarkColors
// Define default alpha values for specific variables based on theme
const defaultAlphas = {
light: {
'--glass-bg': 0.25,
'--glass-border': 0.1,
'--card-bg': 0.7,
'--popup-shadow-color': 0.2,
'--popup-accent-glow': 0.2
}
// Removed dark alpha values
};
// Helper to convert hex to RGB object {r, g, b}
function hexToRgb(hex) {
// Remove '#' if present
const cleanHex = hex.startsWith('#') ? hex.slice(1) : hex;
const bigint = parseInt(cleanHex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return { r, g, b };
}
// Helper to convert hex to RGBA string with a given alpha
function hexToRgba(hex, alpha) {
const { r, g, b } = hexToRgb(hex);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
function applyCustomColors() {
console.log('applyCustomColors executing');
const root = document.documentElement;
// Always apply light theme colors
const themeColors = customColors.light;
for (const [prop, value] of Object.entries(themeColors)) {
if (defaultAlphas.light && defaultAlphas.light[prop] !== undefined) {
// If it's an RGBA variable, convert hex to RGBA with its default alpha
const rgbaValue = hexToRgba(value, defaultAlphas.light[prop]);
root.style.setProperty(prop, rgbaValue);
console.log(`Setting CSS var ${prop} to RGBA: ${rgbaValue}`);
} else {
// Otherwise, set the property directly (it's likely a solid color)
root.style.setProperty(prop, value);
console.log(`Setting CSS var ${prop} to HEX: ${value}`);
}
}
}
function resetToDefaultColors() {
console.log('resetToDefaultColors called');
const root = document.documentElement;
const targetColors = defaultLightColors; // Always target light colors
// Reset customColors.light to defaultLightColors
for (const [prop, value] of Object.entries(targetColors)) {
customColors.light[prop] = value; // Store hex value in customColors for light theme
console.log(`Resetting customColors.light['${prop}'] to ${value}`);
}
// Apply the colors to the CSS variables
applyCustomColors();
console.log('applyCustomColors called after reset');
// Update the color pickers in the UI
updateThemeColorPickers();
console.log('updateThemeColorPickers called after reset');
// Save the reset settings to localStorage
saveSettings();
showTemporaryMessage('Colors restored to default!');
}
// Removed toggleTheme function
// Sidebar Management
let sidebarCollapsed = false;
function toggleSidebar() {
const sidebar = document.getElementById('sidebar');
const sidebarDisplay = document.getElementById('sidebarDisplay');
if (sidebar) sidebar.classList.toggle('collapsed', sidebarCollapsed);
if (sidebarDisplay) {
sidebarDisplay.textContent = sidebarCollapsed ? 'Collapsed' : 'Expanded';
}
sidebarCollapsed = !sidebarCollapsed;
}
// Navigation Management
function switchPage(pageId) {
const navLinks = document.querySelectorAll('.nav-link');
const pages = document.querySelectorAll('.page');
navLinks.forEach(link => link.classList.remove('active'));
pages.forEach(page => page.classList.remove('active'));
const targetLink = document.querySelector(`[data-page="${pageId}"]`);
if (targetLink) targetLink.classList.add('active');
const targetPageElement = document.getElementById(pageId);
if (targetPageElement) targetPageElement.classList.add('active');
}
// Tab Management
function switchTab(tabId) {
const tabBtns = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');
tabBtns.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
const targetBtn = document.querySelector(`[data-tab="${tabId}"]`);
if (targetBtn) targetBtn.classList.add('active');
const targetTabContent = document.getElementById(tabId);
if (targetTabContent) targetTabContent.classList.add('active');
// If switching to the general tab, redraw the pie chart
if (tabId === 'general') {
renderPieChart();
renderSliders();
} else if (tabId === 'theme') {
updateThemeColorPickers(); // Update color pickers when switching to theme tab
}
}
// Modal Management
function showModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.classList.add('active');
document.body.style.overflow = 'hidden';
}
}
function hideModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.classList.remove('active');
document.body.style.overflow = '';
}
}
// Loading State
function showLoadingState(button) {
if (!button) return;
const originalText = button.textContent;
button.textContent = 'Loading...';
button.disabled = true;
button.style.opacity = '0.7';
}
// Chart Animation (for the old chart, can be removed if not needed elsewhere)
function animateChart() {
const chartPoints = document.querySelectorAll('.chart-point');
chartPoints.forEach((point, index) => {
setTimeout(() => {
if (point) point.style.animation = 'pulse 0.5s ease';
}, index * 100);
});
}
// Function to display a temporary message
function showTemporaryMessage(message, duration = 3000) {
const messageElement = document.getElementById('saveConfirmationMessage');
if (!messageElement) return;
const messageText = messageElement.querySelector('span');
if (messageText) messageText.textContent = message;
messageElement.classList.add('show');
setTimeout(() => {
messageElement.classList.remove('show');
}, duration);
}
// Operation Proportions - Pie Chart Logic (using Chart.js)
let pieChart; // Chart.js instance
function getChartContext() {
const canvas = document.getElementById('operationPieChart');
if (canvas) {
return canvas.getContext('2d');
}
console.error("Canvas element 'operationPieChart' not found.");
return null;
}
const operations = [
{ name: 'Addition', key: 'addition', enabled: true },
{ name: 'Subtraction', key: 'subtract', enabled: true },
{ name: 'Multiplication', key: 'multiply', enabled: true },
{ name: 'Division', key: 'divide', enabled: true }
];
let proportions = {};
function calculateEqualProportions() {
const active = operations.filter(op => op.enabled);
const portion = active.length > 0 ? Math.floor(100 / active.length) : 0;
let total = portion * active.length;
let remaining = 100 - total;
proportions = {};
active.forEach((op, index) => {
proportions[op.key] = portion + (index === 0 ? remaining : 0);
});
// Set disabled operations to 0 proportion
operations.filter(op => !op.enabled).forEach(op => {
proportions[op.key] = 0;
});
console.log('Proportions after equal calculation:', proportions);
}
function getChartData() {
const enabledOps = operations.filter(op => op.enabled);
const data = enabledOps.map(op => proportions[op.key]);
const labels = enabledOps.map(op => op.name);
const backgroundColors = enabledOps.map(op => {
// Map to your desired colors
switch (op.key) {
case 'addition': return '#6C63FF';
case 'subtract': return '#FF6B6B';
case 'multiply': return '#FFD166';
case 'divide': return '#06D6A0';
default: return '#CCCCCC';
}
});
return {
labels: labels,
datasets: [{
data: data,
backgroundColor: backgroundColors,
borderWidth: 1
}]
};
}
function renderPieChart() {
const ctx = getChartContext();
if (!ctx || typeof Chart === 'undefined') {
console.error("Cannot render pie chart: Chart.js not loaded or canvas context unavailable.");
return;
}
try {
if (pieChart) pieChart.destroy();
pieChart = new Chart(ctx, {
type: 'pie',
data: getChartData(),
options: {
responsive: true,
plugins: {
legend: { position: 'bottom' },
tooltip: {
callbacks: {
label: function (context) {
const label = context.label || '';
const value = context.raw || 0;
return `${label}: ${Math.round(value)}%`;
}
}
}
}
}
});
console.log('Pie chart rendered successfully.');
} catch (error) {
console.error("Error rendering pie chart:", error);
}
}
function renderSliders() {
const sliderContainer = document.getElementById('slidersContainer');
if (!sliderContainer) {
console.error("Slider container not found.");
return;
}
sliderContainer.innerHTML = '';
const activeOps = operations.filter(op => op.enabled);
activeOps.forEach(op => {
const wrapper = document.createElement('div');
wrapper.style.margin = '0.5rem 0';
const label = document.createElement('label');
label.innerText = `${op.name}: ${Math.round(proportions[op.key])}%`;
label.style.display = 'block';
label.style.marginBottom = '0.25rem';
label.style.color = 'var(--text-primary)';
const input = document.createElement('input');
input.type = 'range';
input.min = '0';
input.max = '100';
input.value = Math.round(proportions[op.key]);
input.dataset.key = op.key;
input.addEventListener('input', onSliderInput);
wrapper.appendChild(label);
wrapper.appendChild(input);
sliderContainer.appendChild(wrapper);
});
updateSliderUI(); // Call to initialize slider UI after rendering
}
function updateSliderUI() {
document.querySelectorAll('#slidersContainer input[type="range"]').forEach(input => {
const key = input.dataset.key;
const labelElement = input.previousElementSibling; // Assuming label is right before input
if (labelElement) {
labelElement.innerText = `${operations.find(op => op.key === key).name}: ${Math.round(proportions[key])}%`;
}
input.value = Math.round(proportions[key]);
});
}
function onSliderInput(e) {
const changedKey = e.target.dataset.key;
const newValue = parseInt(e.target.value);
// Immediately update the label of the current slider being dragged
const labelElement = e.target.previousElementSibling;
if (labelElement) {
labelElement.innerText = `${operations.find(op => op.key === changedKey).name}: ${newValue}%`;
}
// Call adjustProportions, which will now update all sliders more efficiently
adjustProportions(changedKey, newValue);
}
function adjustProportions(changedKey, newValue) {
let enabledKeys = operations.filter(op => op.enabled).map(op => op.key);
let otherEnabledKeys = enabledKeys.filter(k => k !== changedKey);
let totalOther = otherEnabledKeys.reduce((sum, k) => sum + proportions[k], 0);
let remaining = 100 - newValue;
if (remaining < 0) {
newValue = 100;
remaining = 0;
}
if (otherEnabledKeys.length === 0) {
proportions[changedKey] = 100;
} else if (totalOther === 0) {
const evenShare = remaining / otherEnabledKeys.length;
otherEnabledKeys.forEach(k => {
proportions[k] = evenShare;
});
} else {
const scale = remaining / totalOther;
otherEnabledKeys.forEach(k => {
proportions[k] = proportions[k] * scale;
});
}
proportions[changedKey] = newValue;
let sum = 0;
enabledKeys.forEach(k => {
proportions[k] = Math.round(proportions[k]);
sum += proportions[k];
});
let diff = 100 - sum;
if (diff !== 0 && enabledKeys.length > 0) {
for (let i = 0; i < Math.abs(diff); i++) {
const index = i % enabledKeys.length;
if (diff > 0) {
proportions[enabledKeys[index]]++;
} else {
proportions[enabledKeys[index]]--;
}
}
}
renderPieChart();
updateSliderUI(); // Call the new function to update slider UI
saveSettings();
}
// Function to save settings to localStorage
function saveSettings() {
const settings = {};
// Practice Mode
const practiceModeRadio = document.querySelector('input[name="practiceMode"]:checked');
settings.practiceMode = practiceModeRadio ? practiceModeRadio.value : 'timed';
const timedMinutesInput = document.getElementById('timedMinutes');
settings.timedMinutes = timedMinutesInput ? parseInt(timedMinutesInput.value) : 5;
const fixedProblemsInput = document.getElementById('fixedProblems');
settings.fixedProblems = fixedProblemsInput ? parseInt(fixedProblemsInput.value) : 25;
// Operation Types
settings.operations = {};
document.querySelectorAll('.operation-item').forEach(item => {
const operationKey = item.getAttribute('data-operation');
const toggleControl = item.querySelector('.toggle-control');
const isEnabled = toggleControl ? toggleControl.getAttribute('data-state') === 'enabled' : false;
const rangeStartInput = item.querySelector('.range-start');
const rangeStart = rangeStartInput ? parseInt(rangeStartInput.value) : 1;
const rangeEndInput = item.querySelector('.range-end');
const rangeEnd = rangeEndInput ? parseInt(rangeEndInput.value) : (operationKey === 'multiply' ? 12 : 100);
let specificSettings = {};
if (operationKey === 'subtract') {
const largerFirstCheckbox = item.querySelector('.larger-first');
specificSettings.largerFirst = largerFirstCheckbox ? largerFirstCheckbox.checked : false;
}
settings.operations[operationKey] = {
enabled: isEnabled,
range: { start: rangeStart, end: rangeEnd },
proportion: proportions[operationKey] || 0,
...specificSettings
};
});
// Performance Settings (Audio & Feedback, Timing Behavior, Failure Conditions)
document.querySelectorAll('#performance .toggle-control').forEach(control => {
const settingId = control.getAttribute('data-setting-id');
settings[settingId] = control.getAttribute('data-state') === 'enabled';
});
const maxResponseTimeInput = document.querySelector('[data-setting-id="maxResponseTime"]');
settings.maxResponseTime = maxResponseTimeInput ? parseInt(maxResponseTimeInput.value) : 3;
const failureActionSelect = document.querySelector('[data-setting-id="failureAction"]');
settings.failureAction = failureActionSelect ? failureActionSelect.value : 'end';
const maxMistakesInput = document.querySelector('[data-setting-id="maxMistakes"]');
settings.maxMistakes = maxMistakesInput ? parseInt(maxMistakesInput.value) : 3;
// Problem Presentation Mode
settings.problemPresentationMode = document.querySelector('input[name="problemPresentationMode"]:checked')?.value || 'displayVisual';
// Save brief display duration
settings.briefDisplayDuration = parseInt(document.getElementById('briefDisplayDuration').value);
// Save custom colors (only for light mode now)
settings.customColors = { light: {} };
document.querySelectorAll('#theme input[type="color"]').forEach(input => {
const colorVar = input.dataset.colorVar;
settings.customColors.light[colorVar] = input.value;
});
localStorage.setItem('mathMindProSettings', JSON.stringify(settings));
console.log('Settings saved:', settings);
showTemporaryMessage('Settings saved successfully!');
}
// Function to load settings from localStorage
function loadSettings() {
const savedSettings = localStorage.getItem('mathMindProSettings');
if (savedSettings) {
try {
const settings = JSON.parse(savedSettings);
console.log('Settings loaded:', settings);
// Apply Practice Mode
const practiceModeRadio = document.querySelector(`input[name="practiceMode"][value="${settings.practiceMode}"]`);
if (practiceModeRadio) practiceModeRadio.checked = true;
const timedMinutesInput = document.getElementById('timedMinutes');
if (timedMinutesInput && settings.timedMinutes !== undefined) timedMinutesInput.value = settings.timedMinutes;
const fixedProblemsInput = document.getElementById('fixedProblems');
if (fixedProblemsInput && settings.fixedProblems !== undefined) fixedProblemsInput.value = settings.fixedProblems;
// Apply Operation Types and Proportions
let loadedProportions = {};
operations.forEach(op => {
loadedProportions[op.key] = 0;
});
for (const opKey in settings.operations) {
const item = document.querySelector(`.operation-item[data-operation="${opKey}"]`);
if (item) {
const opSettings = settings.operations[opKey];
const globalOp = operations.find(o => o.key === opKey);
if (globalOp) {
globalOp.enabled = opSettings.enabled;
}
const toggleControl = item.querySelector('.toggle-control');
if (toggleControl && opSettings.enabled !== undefined) {
toggleControl.setAttribute('data-state', opSettings.enabled ? 'enabled' : 'disabled');
toggleControl.textContent = opSettings.enabled ? 'Enabled' : 'Disabled';
}
const rangeStartInput = item.querySelector('.range-start');
if (rangeStartInput && opSettings.range && opSettings.range.start !== undefined) rangeStartInput.value = opSettings.range.start;
const rangeEndInput = item.querySelector('.range-end');
if (rangeEndInput && opSettings.range && opSettings.range.end !== undefined) rangeEndInput.value = opSettings.range.end;
if (opKey === 'subtract' && opSettings.largerFirst !== undefined) {
const largerFirstCheckbox = item.querySelector('.larger-first');
if (largerFirstCheckbox) largerFirstCheckbox.checked = opSettings.largerFirst;
}
if (opSettings.proportion !== undefined) {
loadedProportions[opKey] = opSettings.proportion;
}
}
}
proportions = loadedProportions;
console.log('Proportions after loading from settings:', proportions);
let currentSum = operations.filter(op => op.enabled).reduce((sum, op) => sum + proportions[op.key], 0);
let enabledCount = operations.filter(op => op.enabled).length;
if (currentSum !== 100 || (enabledCount > 0 && currentSum === 0)) {
console.warn('Proportions sum not 100% or all zero for enabled ops. Recalculating equal proportions.');
calculateEqualProportions();
} else {
operations.filter(op => !op.enabled).forEach(op => {
proportions[op.key] = 0;
});
}
renderPieChart();
renderSliders();
// Apply Performance Settings
document.querySelectorAll('#performance .toggle-control').forEach(control => {
const settingId = control.getAttribute('data-setting-id');
if (settings[settingId] !== undefined) {
control.setAttribute('data-state', settings[settingId] ? 'enabled' : 'disabled');
control.textContent = settings[settingId] ? 'Enabled' : 'Disabled';
}
});
const maxResponseTimeInput = document.querySelector('[data-setting-id="maxResponseTime"]');
if (maxResponseTimeInput && settings.maxResponseTime !== undefined) {
maxResponseTimeInput.value = settings.maxResponseTime;
}
const failureActionSelect = document.querySelector('[data-setting-id="failureAction"]');
if (failureActionSelect && settings.failureAction !== undefined) {
failureActionSelect.value = settings.failureAction;
}
const maxMistakesInput = document.querySelector('[data-setting-id="maxMistakes"]');
if (maxMistakesInput && settings.maxMistakes !== undefined) {
maxMistakesInput.value = settings.maxMistakes;
}
// Apply Problem Presentation Mode
const problemPresentationModeRadio = document.querySelector(`input[name="problemPresentationMode"][value="${settings.problemPresentationMode}"]`);
if (problemPresentationModeRadio) problemPresentationModeRadio.checked = true;
// Load brief display duration
const briefDisplayDurationInput = document.getElementById('briefDisplayDuration');
if (briefDisplayDurationInput && settings.briefDisplayDuration !== undefined) {
briefDisplayDurationInput.value = settings.briefDisplayDuration;
}
// Load custom colors (only for light mode now)
if (settings.customColors && settings.customColors.light) {
customColors.light = settings.customColors.light;
} else {
// If no custom colors saved, initialize with defaults
resetToDefaultColors(); // Only reset light mode
}
applyCustomColors(); // Apply loaded custom colors
updateThemeColorPickers(); // Populate color pickers with loaded values
} catch (e) {
console.error("Error parsing or applying settings from localStorage:", e);
// Fallback to default if parsing fails
calculateEqualProportions();
renderPieChart();
renderSliders();
resetToDefaultColors();
applyCustomColors();
}
} else {
console.log('No settings found in localStorage. Initializing with defaults.');
calculateEqualProportions();
renderPieChart();
renderSliders();
// Initialize with default colors if no settings are saved
resetToDefaultColors(); // Only reset light mode
applyCustomColors();
}
}
// Function to update the color pickers in the Theme tab
function updateThemeColorPickers() {
console.log('updateThemeColorPickers executing');
document.querySelectorAll('#theme input[type="color"]').forEach(input => {
const colorVar = input.dataset.colorVar;
// Always get colors from the light mode object
if (customColors.light && customColors.light[colorVar]) {
input.value = customColors.light[colorVar];
console.log(`Updating picker for ${colorVar} to ${input.value}`);
} else {
// Fallback to default hex if not in customColors (shouldn't happen if resetToDefaultColors is called)
if (defaultLightColors[colorVar]) {
input.value = defaultLightColors[colorVar];
console.log(`Updating picker for ${colorVar} to default ${input.value} (fallback)`);
}
}
// Update the visual swatch display
updateColorSwatch(input);
});
}
// Helper to convert RGB to Hex (for initial picker population if needed)
// This function is generally for reading computed styles which are RGB(A) and converting them to hex for the picker.
function rgbToHex(rgb) {
if (!rgb || !rgb.startsWith('rgb')) return rgb; // Return as is if not rgb or null/undefined
const parts = rgb.match(/\d+/g);
if (!parts || parts.length < 3) return rgb;
const hex = parts.slice(0, 3).map(function(n) { // Only take RGB parts, ignore A
return ("0" + parseInt(n).toString(16)).slice(-2);
}).join("");
return "#" + hex;
}
// Function to update the visual color swatch and display hex value
function updateColorSwatch(colorInput) {
const swatch = colorInput.nextElementSibling; // The span.color-display-swatch
if (swatch) {
const hexValue = colorInput.value;
swatch.style.backgroundColor = hexValue;
swatch.textContent = hexValue.toUpperCase(); // Display hex value in uppercase
// Adjust text color for readability based on background
const rgb = hexToRgb(hexValue);
const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
swatch.style.color = brightness > 180 ? '#333' : '#FFF'; // Dark text for light colors, light text for dark colors
}
}
// Training Session Variables
let trainingSettings = {};
let currentProblem = {};
let problemSolvedCount = 0;
let correctScore = 0;
let incorrectScore = 0;
let timerInterval;
let stopwatchInterval;
let stopwatchMilliseconds = 0;
let timeLeft;
let totalProblemsToSolve;
let sessionStartTime;
let isProblemSubmitted = false;
let sessionEndedPrematurely = false;
const problemDisplay = document.getElementById('problemDisplay');
const answerInput = document.getElementById('answerInput');
const feedbackMessage = document.getElementById('feedbackMessage');
const problemCountDisplay = document.getElementById('problemCountDisplay');
const timerDisplay = document.getElementById('timerDisplay');
const stopwatchDisplay = document.getElementById('stopwatchDisplay');
const trainingProgressBar = document.getElementById('trainingProgressBar');
const currentProblemNumberSpan = document.getElementById('currentProblemNumber');
const totalProblemsSpan = document.getElementById('totalProblems');
const correctScoreSpan = document.getElementById('correctScore');
const incorrectScoreSpan = document.getElementById('incorrectScore');
const endSessionBtn = document.getElementById('endSessionBtn');
const endSessionConfirmation = document.getElementById('endSessionConfirmation');
const confirmEndBtn = document.getElementById('confirmEndBtn');
const cancelEndBtn = document.getElementById('cancelEndBtn');
const countdownDisplay = document.getElementById('countdownDisplay');
const repeatProblemBtn = document.getElementById('repeatProblemBtn'); // Get the new repeat button
const summaryCorrect = document.getElementById('summaryCorrect');
const summaryIncorrect = document.getElementById('summaryIncorrect');
const summaryAccuracy = document.getElementById('summaryAccuracy');
const summaryTimeElapsed = document.getElementById('summaryTimeElapsed');
const summaryAvgTime = document.getElementById('summaryAvgTime');
const summaryModalTitle = document.getElementById('summaryModalTitle');
const problemsSolvedCountElement = document.getElementById('problemsSolvedCount');
// Function for Text-to-Speech
let speechVoices = [];
function populateVoices() {
speechVoices = window.speechSynthesis.getVoices();
}
// Populate voices as soon as they are loaded
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoices;
}
function textToSpeech(text) {
if ('speechSynthesis' in window) {
// Ensure voices are loaded before attempting to speak
if (speechVoices.length === 0) {
populateVoices(); // Try to populate them now
}
const utterance = new SpeechSynthesisUtterance(text);
// Optional: Select a specific voice, e.g., an English US female voice
const englishVoice = speechVoices.find(voice => voice.lang === 'en-US' && voice.name.includes('Google') && voice.name.includes('Female'));
if (englishVoice) {
utterance.voice = englishVoice;
} else {
// Fallback to any English voice
utterance.voice = speechVoices.find(voice => voice.lang.startsWith('en'));
}
utterance.pitch = 1; // Default pitch
utterance.rate = 1; // Default rate
// Ensure audio context is running (Tone.js already handles this on click, but good to double check)
if (Tone.context.state !== 'running') {
Tone.start().then(() => {
window.speechSynthesis.speak(utterance);
}).catch(e => console.error("Failed to start Tone.js audio context for speech:", e));
} else {
window.speechSynthesis.speak(utterance);
}
} else {
console.warn("Speech Synthesis API not supported in this browser.");
// Fallback: play a chime if speech is not supported
chime.triggerAttackRelease("C5", "8n");
}
}
// Function to start a training session
async function startTrainingSession() {
if (Tone.context.state !== 'running') {
await Tone.start();
console.log("Tone.js audio context started.");
}
try {
trainingSettings = JSON.parse(localStorage.getItem('mathMindProSettings')) || {};
} catch (e) {
console.error("Error parsing settings from localStorage:", e);
trainingSettings = {};
}
// Ensure operations settings are initialized if not found
if (!trainingSettings.operations) {
trainingSettings.operations = {};
operations.forEach(op => {
trainingSettings.operations[op.key] = {
enabled: true,
range: { start: 1, end: (op.key === 'multiply' ? 12 : 100) },
proportion: 0
};
if (op.key === 'subtract') {
trainingSettings.operations[op.key].largerFirst = true;
}
});
calculateEqualProportions();
}
// Ensure problemPresentationMode is initialized
if (!trainingSettings.problemPresentationMode) {
trainingSettings.problemPresentationMode = 'displayVisual';
}
// Ensure briefDisplayDuration is initialized
if (trainingSettings.briefDisplayDuration === undefined) {
trainingSettings.briefDisplayDuration = 2; // Default to 2 seconds
}
// Log the current presentation mode for debugging
console.log("Current problemPresentationMode:", trainingSettings.problemPresentationMode);
const enabledOperations = operations.filter(op => trainingSettings.operations[op.key]?.enabled);
if (enabledOperations.length === 0) {
showTemporaryMessage('Please enable at least one operation type in settings to start training.');
return;
}
showModal('trainingModal');
problemSolvedCount = 0;
correctScore = 0;
incorrectScore = 0;
feedbackMessage.textContent = '';
answerInput.value = '';
sessionStartTime = Date.now();
sessionEndedPrematurely = false;
endSessionBtn.style.display = 'block';
endSessionConfirmation.classList.remove('active');
// Initially hide problem display and answer input, will be shown after countdown
problemDisplay.style.display = 'none';
answerInput.parentElement.style.display = 'none'; // Hide the container for input and button
problemCountDisplay.style.display = 'none';
timerDisplay.style.display = 'none';
stopwatchDisplay.style.display = 'none';
endSessionBtn.style.display = 'none';
repeatProblemBtn.style.display = 'none'; // Hide repeat button by default
if (trainingSettings.practiceMode === 'timed') {
totalProblemsToSolve = Infinity;
timeLeft = trainingSettings.timedMinutes * 60;
document.getElementById('trainingModalTitle').textContent = `Timed Practice (${trainingSettings.timedMinutes} min)`;
} else {
totalProblemsToSolve = trainingSettings.fixedProblems;
document.getElementById('trainingModalTitle').textContent = `Fixed Quantity Practice (${trainingSettings.fixedProblems} problems)`;
}
startCountdown();
}
// Function to handle the countdown
function startCountdown() {
let count = 3;
countdownDisplay.textContent = count;
countdownDisplay.style.display = 'block';
const countdownInterval = setInterval(() => {
count--;
if (count > 0) {
countdownDisplay.textContent = count;
} else if (count === 0) {
countdownDisplay.textContent = 'Go!';
} else {
clearInterval(countdownInterval);
countdownDisplay.style.display = 'none';
// Show elements based on initial presentation mode
if (trainingSettings.problemPresentationMode !== 'speakAloud') {
problemDisplay.style.display = 'block';
} else {
problemDisplay.style.display = 'none'; // Keep hidden for audio-only
}
answerInput.parentElement.style.display = 'flex'; // Show the container for input and button
problemCountDisplay.style.display = 'flex';
endSessionBtn.style.display = 'block';
// Show repeat button only if speech is enabled
if (trainingSettings.problemPresentationMode === 'speakAloud' || trainingSettings.problemPresentationMode === 'displaySpeak') {
repeatProblemBtn.style.display = 'flex';
} else {
repeatProblemBtn.style.display = 'none';
}
if (trainingSettings.practiceMode === 'timed') {
timerDisplay.style.display = 'block';
updateTimerDisplay();
timerInterval = setInterval(updateTimer, 1000);
}
stopwatchDisplay.style.display = 'block';
answerInput.focus();
generateProblem();
}
}, 1000);
}
// Function to start the individual problem stopwatch
function startStopwatch() {
clearInterval(stopwatchInterval);
stopwatchMilliseconds = 0;
updateStopwatchDisplay();
const problemStartTime = Date.now();
stopwatchInterval = setInterval(() => {
stopwatchMilliseconds = Date.now() - problemStartTime;
updateStopwatchDisplay();
if (trainingSettings.enableMaxResponseTime && !isProblemSubmitted) {
const maxResponseTimeSeconds = trainingSettings.maxResponseTime ?? 3;
if ((stopwatchMilliseconds / 1000) > maxResponseTimeSeconds) {
checkAnswer(true);
}
}
}, 10);
}
// Function to stop the individual problem stopwatch
function stopStopwatch() {
clearInterval(stopwatchInterval);
}
// Function to update the individual problem stopwatch display
function updateStopwatchDisplay() {
if (trainingSettings.hideTimer) {
stopwatchDisplay.style.display = 'none';
return;
}
const totalSeconds = (stopwatchMilliseconds / 1000).toFixed(1);
stopwatchDisplay.textContent = `${totalSeconds}s`;
stopwatchDisplay.style.display = 'block';
}
// Function to request ending the training session (shows confirmation)
function requestEndSession() {
clearInterval(timerInterval);
stopStopwatch();
problemDisplay.style.display = 'none';
answerInput.parentElement.style.display = 'none'; // Hide the container for input and button
problemCountDisplay.style.display = 'none';
timerDisplay.style.display = 'none';
stopwatchDisplay.style.display = 'none';
countdownDisplay.style.display = 'none';
repeatProblemBtn.style.display = 'none'; // Hide repeat button
endSessionBtn.style.display = 'none';
endSessionConfirmation.classList.add('active');
sessionEndedPrematurely = true;
}
// Function to confirm and end the training session (finalizes)
function confirmEndSession() {
hideModal('trainingModal');
clearInterval(timerInterval);
stopStopwatch();
const totalProblemsAttempted = correctScore + incorrectScore;
const finalAccuracy = totalProblemsAttempted > 0 ? ((correctScore / totalProblemsAttempted) * 100).toFixed(1) : 0;
const timeElapsedMilliseconds = Date.now() - sessionStartTime;
const totalSeconds = Math.floor(timeElapsedMilliseconds / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const formattedTimeElapsed = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
const avgTimePerProblem = totalProblemsAttempted > 0 ? (timeElapsedMilliseconds / totalProblemsAttempted / 1000).toFixed(1) : 0;
summaryCorrect.textContent = correctScore;
summaryIncorrect.textContent = incorrectScore;
summaryAccuracy.textContent = `${finalAccuracy}%`;
summaryTimeElapsed.textContent = formattedTimeElapsed;
summaryAvgTime.textContent = `${avgTimePerProblem}s`;
if (sessionEndedPrematurely) {
summaryModalTitle.textContent = 'Practice Incomplete — 🤷♂️';
} else {
summaryModalTitle.textContent = 'Practice Complete! 🎉';
}
const sessionStartDateTime = new Date(sessionStartTime);
const sessionData = {
sessionId: crypto.randomUUID(),
date: sessionStartDateTime.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }),
startTimeISO: sessionStartDateTime.toISOString(),
practiceMode: trainingSettings.practiceMode === 'timed' ? `Timed Practice (${trainingSettings.timedMinutes} min)` : `Fixed Quantity (${trainingSettings.fixedProblems} problems)`,
operationTypes: operations.filter(op => trainingSettings.operations[op.key]?.enabled).map(op => op.name).join(', '),
operationProportions: Object.entries(proportions).filter(([key, value]) => value > 0).map(([key, value]) => {
const opName = operations.find(op => op.key === key)?.name;
return `${opName}: ${Math.round(value)}%`;
}).join(' / '),
operationRanges: Object.entries(trainingSettings.operations)
.filter(([key, op]) => op.enabled)
.map(([key, op]) => {
const opName = operations.find(o => o.key === key)?.name;
return `${opName}: ${op.range.start}-${op.range.end}`;
})
.join('; '),
correctAnswers: correctScore,
incorrectAnswers: incorrectScore,
finalAccuracy: finalAccuracy,
timeElapsed: formattedTimeElapsed,
avgTimePerProblem: `${avgTimePerProblem}s`,