Docfile commited on
Commit
55af5a2
·
verified ·
1 Parent(s): 9aabf46

Create index.html

Browse files
Files changed (1) hide show
  1. templates/index.html +712 -0
templates/index.html ADDED
@@ -0,0 +1,712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="fr">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <!-- Updated Title -->
7
+ <title>Mariam M-1 | Solution Maths/Physique/Chimie</title>
8
+
9
+ <!-- Tailwind CSS -->
10
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet" integrity="sha384-CYN1GZJ4bX7Z1P+H/jD0Rfsd8C/n+5ZunG7P21/6f2e3vLg/fH7f1e8t0" crossorigin="anonymous">
11
+
12
+ <!-- SweetAlert2 -->
13
+ <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11" integrity="sha384-HeeY8JpXPqZXrC+j9gB6jS57+b9LhE/Vf4+qQ9oE9pY/t2uQ/w1Kj/tqV4g0" crossorigin="anonymous"></script>
14
+
15
+ <!-- Marked.js for Markdown -->
16
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js" integrity="sha384-vJIvV7fGv2z1vJ+w0q+Gz5Y8F8A1+z/c5f2m5g0L3g0" crossorigin="anonymous"></script>
17
+
18
+ <!-- MathJax Configuration -->
19
+ <script>
20
+ window.MathJax = {
21
+ tex: {
22
+ inlineMath: [['$', '$']],
23
+ displayMath: [['$$', '$$']],
24
+ processEscapes: true,
25
+ // Added 'mhchem' for chemistry, kept 'ams' and 'autoload'
26
+ packages: {'[+]': ['ams', 'mhchem', 'autoload']}
27
+ },
28
+ options: {
29
+ enableMenu: false,
30
+ messageStyle: 'none'
31
+ },
32
+ startup: {
33
+ // Ensure MathJax signals readiness correctly
34
+ ready: () => {
35
+ console.log('MathJax is ready');
36
+ MathJax.startup.defaultReady();
37
+ window.mathJaxReady = true;
38
+ }
39
+ }
40
+ };
41
+ </script>
42
+ <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async integrity="sha384-q/9w/uN/w/L+7xPj6qF7zQ/eGg6z/P9bI1+5s8l+gP7x2t/w//d/h" crossorigin="anonymous"></script>
43
+
44
+ <style>
45
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap');
46
+ body { font-family: 'Space Grotesk', sans-serif; background-color: #f9fafb; } /* Light gray background */
47
+
48
+ .uploadArea {
49
+ background: #f3f4f6;
50
+ border: 2px dashed #d1d5db;
51
+ transition: border-color 0.2s ease, background-color 0.2s ease;
52
+ border-radius: 0.5rem; /* Slightly rounded corners */
53
+ }
54
+ .uploadArea:hover { border-color: #3b82f6; background-color: #eef2ff; }
55
+
56
+ .blue-button { background: #3b82f6; transition: background-color 0.2s ease; }
57
+ .blue-button:hover { background: #2563eb; }
58
+ .blue-button:disabled { background: #9ca3af; cursor: not-allowed; }
59
+
60
+ .loader {
61
+ width: 48px;
62
+ height: 48px;
63
+ border: 4px solid #3b82f6; /* Slightly thicker border */
64
+ border-bottom-color: transparent;
65
+ border-radius: 50%;
66
+ display: inline-block;
67
+ animation: rotation 1s linear infinite;
68
+ }
69
+ @keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
70
+
71
+ .thought-box {
72
+ transition: max-height 0.4s ease-in-out; /* Smoother transition */
73
+ max-height: 0;
74
+ overflow: hidden;
75
+ background-color: #f8f9fa; /* Light background for thoughts */
76
+ border-radius: 0.375rem;
77
+ border: 1px solid #e5e7eb;
78
+ }
79
+ .thought-box.open { max-height: 60vh; } /* Use viewport height */
80
+
81
+ #thoughtsContent, #answerContent {
82
+ max-height: 60vh; /* Consistent max height */
83
+ overflow-y: auto;
84
+ scroll-behavior: smooth;
85
+ white-space: pre-wrap; /* Keep line breaks */
86
+ word-wrap: break-word; /* Prevent long unbroken strings from overflowing */
87
+ background: #ffffff; /* White background for content */
88
+ border: 1px solid #e5e7eb;
89
+ border-radius: 0.375rem;
90
+ padding: 1rem; /* Add padding inside content areas */
91
+ }
92
+ #thoughtsContent { background-color: #f8f9fa; } /* Slightly different bg for thoughts */
93
+
94
+ .preview-image { max-width: 100%; height: auto; max-height: 350px; object-fit: contain; margin-top: 1rem; border-radius: 0.375rem; border: 1px solid #e5e7eb; }
95
+
96
+ .timestamp { color: #1e40af; font-size: 0.85em; margin-left: 10px; font-weight: 500;}
97
+
98
+ /* Ensure tables look good on mobile */
99
+ .table-responsive { overflow-x: auto; }
100
+ table {
101
+ border-collapse: collapse;
102
+ width: 100%;
103
+ margin-bottom: 1rem;
104
+ border: 1px solid #d1d5db;
105
+ }
106
+ th, td {
107
+ border: 1px solid #e5e7eb;
108
+ padding: 0.75rem; /* Slightly more padding */
109
+ text-align: left;
110
+ vertical-align: top; /* Align content top */
111
+ }
112
+ th { background-color: #f3f4f6; font-weight: 600; }
113
+ /* Zebra striping for readability */
114
+ tbody tr:nth-child(odd) { background-color: #f9fafb; }
115
+
116
+ #saveButton {
117
+ background: #10b981; /* Green for save action */
118
+ color: white;
119
+ padding: 0.5rem 1rem;
120
+ border-radius: 0.375rem;
121
+ transition: background-color 0.2s ease;
122
+ font-weight: 500;
123
+ }
124
+ #saveButton:hover { background: #059669; }
125
+
126
+ /* Modal styling */
127
+ #savedModal {
128
+ display: none;
129
+ position: fixed;
130
+ inset: 0;
131
+ background: rgba(0, 0, 0, 0.6); /* Darker overlay */
132
+ z-index: 50;
133
+ padding: 1rem; /* Padding for modal itself */
134
+ overflow-y: auto; /* Allow modal scroll if content is too long */
135
+ }
136
+ #savedModal.active { display: flex; align-items: center; justify-content: center; }
137
+ #savedModalContent {
138
+ background: #fff;
139
+ width: 100%;
140
+ max-width: 600px; /* Max width for modal content */
141
+ max-height: 90vh; /* Max height */
142
+ overflow-y: auto;
143
+ border-radius: 0.5rem;
144
+ box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
145
+ display: flex;
146
+ flex-direction: column; /* Stack header, list, footer */
147
+ }
148
+ #savedModalHeader {
149
+ padding: 1rem 1.5rem;
150
+ border-bottom: 1px solid #e5e7eb;
151
+ display: flex;
152
+ justify-content: space-between;
153
+ align-items: center;
154
+ }
155
+ #savedListContainer {
156
+ padding: 1.5rem;
157
+ flex-grow: 1; /* Allow list to take available space */
158
+ overflow-y: auto; /* Scroll list independently */
159
+ }
160
+ #savedModalFooter {
161
+ padding: 1rem 1.5rem;
162
+ border-top: 1px solid #e5e7eb;
163
+ }
164
+
165
+ /* Style for saved list items */
166
+ #savedList li button {
167
+ display: block; /* Make button take full width */
168
+ padding: 0.75rem 0.5rem;
169
+ border-radius: 0.25rem;
170
+ transition: background-color 0.2s ease;
171
+ }
172
+ #savedList li button:hover {
173
+ background-color: #eef2ff; /* Light blue hover */
174
+ }
175
+ </style>
176
+ </head>
177
+ <body class="p-4 bg-gray-50">
178
+ <div class="max-w-4xl mx-auto bg-white shadow-md rounded-lg overflow-hidden">
179
+ <header class="p-6 text-center border-b border-gray-200">
180
+ <!-- Updated Header -->
181
+ <h1 class="text-3xl sm:text-4xl font-bold text-blue-700">Mariam M-1</h1>
182
+ <p class="text-gray-600 mt-1">Votre Assistant Intelligent pour Maths, Physique et Chimie</p>
183
+ <div class="mt-4 flex justify-end">
184
+ <button id="openSaved" class="blue-button px-4 py-2 text-white rounded-md text-sm font-medium">
185
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
186
+ <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z" />
187
+ </svg>
188
+ Sauvegardes
189
+ </button>
190
+ </div>
191
+ </header>
192
+
193
+ <main id="mainContent" class="p-6">
194
+ <form id="problemForm" class="space-y-6" novalidate>
195
+ <!-- Zone de dépôt / sélection d'image -->
196
+ <div class="uploadArea p-6 sm:p-8 text-center relative cursor-pointer" aria-label="Zone de dépôt d'image">
197
+ <input type="file" id="imageInput" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" aria-label="Choisir une image">
198
+ <div class="space-y-3">
199
+ <div class="w-16 h-16 mx-auto border-2 border-blue-400 rounded-full flex items-center justify-center bg-blue-50">
200
+ <svg class="w-8 h-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
201
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
202
+ </svg>
203
+ </div>
204
+ <p class="text-gray-700 font-medium">Déposez l'image de votre exercice ici</p>
205
+ <p class="text-gray-500 text-sm">ou cliquez pour sélectionner un fichier</p>
206
+ </div>
207
+ </div>
208
+ <!-- Aperçu de l'image -->
209
+ <div id="imagePreview" class="hidden text-center">
210
+ <img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image">
211
+ </div>
212
+ <button type="submit" id="submitButton" class="blue-button w-full py-3 text-white font-semibold rounded-lg text-lg flex items-center justify-center space-x-2" disabled>
213
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
214
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd" />
215
+ </svg>
216
+ <span>Résoudre le problème</span>
217
+ </button>
218
+ </form>
219
+
220
+ <!-- Loader -->
221
+ <div id="loader" class="hidden mt-8 text-center">
222
+ <span class="loader"></span>
223
+ <p class="mt-4 text-gray-600 text-lg font-medium">Analyse en cours, veuillez patienter...</p>
224
+ </div>
225
+
226
+ <!-- Zone d'affichage de la solution -->
227
+ <section id="solution" class="hidden mt-8 space-y-6">
228
+ <!-- Thoughts Section -->
229
+ <div class="border rounded-md overflow-hidden">
230
+ <button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-3 bg-gray-100 hover:bg-gray-200 transition duration-150">
231
+ <span class="font-semibold text-gray-800">Processus de Réflexion</span>
232
+ <div class="flex items-center">
233
+ <span id="timestamp" class="timestamp"></span>
234
+ <svg id="toggleIcon" class="w-5 h-5 text-gray-600 ml-2 transform transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
235
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
236
+ </svg>
237
+ </div>
238
+
239
+ </button>
240
+ <div id="thoughtsBox" class="thought-box">
241
+ <div id="thoughtsContent" class="p-4 text-sm text-gray-700"></div>
242
+ </div>
243
+ </div>
244
+ <!-- Answer Section -->
245
+ <div class="border-t border-gray-200 pt-6">
246
+ <div class="flex justify-between items-center mb-4 px-1">
247
+ <h3 class="text-xl font-bold text-gray-800">Solution Détaillée</h3>
248
+ <button id="saveButton">
249
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
250
+ <path d="M7.707 10.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V6a1 1 0 10-2 0v5.586L7.707 10.293zM5 3a1 1 0 011-1h8a1 1 0 110 2H6a1 1 0 01-1-1z" />
251
+ <path d="M3 8a2 2 0 012-2h10a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V8zm3 1a1 1 0 000 2h8a1 1 0 100-2H6z" />
252
+ </svg>
253
+ Sauvegarder
254
+ </button>
255
+ </div>
256
+ <div id="answerContent" class="text-gray-800 table-responsive leading-relaxed"></div>
257
+ </div>
258
+ </section>
259
+ </main>
260
+ </div>
261
+
262
+ <!-- Modal plein écran pour les sauvegardes -->
263
+ <div id="savedModal">
264
+ <div id="savedModalContent">
265
+ <header id="savedModalHeader">
266
+ <h2 class="text-2xl font-bold text-gray-800">Exercices Sauvegardés</h2>
267
+ <button id="closeSaved" class="text-3xl text-gray-500 hover:text-gray-700">×</button>
268
+ </header>
269
+ <div id="savedListContainer">
270
+ <ul id="savedList" class="space-y-2">
271
+ <!-- Liste des sauvegardes insérée dynamiquement -->
272
+ <!-- Exemple: <li><button>Nom Sauvegarde (Date)</button></li> -->
273
+ </ul>
274
+ <p id="noSavesMessage" class="text-center text-gray-500 hidden mt-4">Aucun exercice sauvegardé pour le moment.</p>
275
+ </div>
276
+ <footer id="savedModalFooter">
277
+ <button id="newExercise" class="blue-button w-full py-3 text-white font-medium rounded-lg">
278
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
279
+ <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
280
+ </svg>
281
+ Résoudre un nouvel exercice
282
+ </button>
283
+ </footer>
284
+ </div>
285
+ </div>
286
+
287
+ <script>
288
+ document.addEventListener('DOMContentLoaded', () => {
289
+ // --- DOM Elements ---
290
+ const form = document.getElementById('problemForm');
291
+ const imageInput = document.getElementById('imageInput');
292
+ const loader = document.getElementById('loader');
293
+ const solutionSection = document.getElementById('solution');
294
+ const thoughtsContent = document.getElementById('thoughtsContent');
295
+ const answerContent = document.getElementById('answerContent');
296
+ const thoughtsToggle = document.getElementById('thoughtsToggle');
297
+ const thoughtsBox = document.getElementById('thoughtsBox');
298
+ const toggleIcon = document.getElementById('toggleIcon');
299
+ const imagePreview = document.getElementById('imagePreview');
300
+ const previewImage = document.getElementById('previewImage');
301
+ const timestamp = document.getElementById('timestamp');
302
+ const saveButton = document.getElementById('saveButton');
303
+ const openSaved = document.getElementById('openSaved');
304
+ const closeSaved = document.getElementById('closeSaved');
305
+ const savedModal = document.getElementById('savedModal');
306
+ const savedList = document.getElementById('savedList');
307
+ const noSavesMessage = document.getElementById('noSavesMessage');
308
+ const newExercise = document.getElementById('newExercise');
309
+ const mainContent = document.getElementById('mainContent');
310
+ const submitButton = document.getElementById('submitButton');
311
+
312
+ // --- State Variables ---
313
+ let startTime = null;
314
+ let timerInterval = null;
315
+ let thoughtsBuffer = '';
316
+ let answerBuffer = '';
317
+ let currentMode = null; // 'thinking' or 'answering'
318
+ let updateTimeout = null;
319
+ let currentSaveData = null; // Holds data for potential saving
320
+
321
+ // --- Helper Functions ---
322
+
323
+ // Timer functions
324
+ const updateTimestamp = () => {
325
+ if (startTime) {
326
+ const seconds = Math.floor((Date.now() - startTime) / 1000);
327
+ timestamp.textContent = `${seconds}s`;
328
+ } else {
329
+ timestamp.textContent = '';
330
+ }
331
+ };
332
+ const startTimer = () => { startTime = Date.now(); timerInterval = setInterval(updateTimestamp, 1000); updateTimestamp(); };
333
+ const stopTimer = () => { clearInterval(timerInterval); timerInterval = null; updateTimestamp(); /* Update one last time */ }; // Keep final time displayed until reset
334
+
335
+ // Reset UI to initial state
336
+ const resetUI = () => {
337
+ form.reset();
338
+ form.classList.remove('hidden');
339
+ submitButton.disabled = true; // Disable submit until image selected
340
+ solutionSection.classList.add('hidden');
341
+ imagePreview.classList.add('hidden');
342
+ previewImage.src = '';
343
+ thoughtsContent.innerHTML = '';
344
+ answerContent.innerHTML = '';
345
+ thoughtsBuffer = '';
346
+ answerBuffer = '';
347
+ currentSaveData = null;
348
+ stopTimer(); // Clear timer display
349
+ thoughtsBox.classList.remove('open'); // Collapse thoughts
350
+ toggleIcon.style.transform = 'rotate(0deg)';
351
+ loader.classList.add('hidden');
352
+ savedModal.classList.remove('active'); // Ensure modal is closed
353
+ };
354
+
355
+ // Image preview handler
356
+ const handleFileSelect = file => {
357
+ if (!file || !file.type.startsWith('image/')) {
358
+ previewImage.src = '';
359
+ imagePreview.classList.add('hidden');
360
+ submitButton.disabled = true;
361
+ if (file) { // If a file was selected but wasn't an image
362
+ Swal.fire('Fichier Invalide', 'Veuillez sélectionner un fichier image (jpeg, png, gif, etc.).', 'warning');
363
+ }
364
+ return;
365
+ }
366
+ const reader = new FileReader();
367
+ reader.onload = e => {
368
+ previewImage.src = e.target.result;
369
+ imagePreview.classList.remove('hidden');
370
+ submitButton.disabled = false; // Enable submit button
371
+ };
372
+ reader.onerror = () => {
373
+ Swal.fire('Erreur Fichier', "Impossible de lire le fichier sélectionné.", 'error');
374
+ submitButton.disabled = true;
375
+ };
376
+ reader.readAsDataURL(file);
377
+ };
378
+
379
+ // Render MathJax and update display
380
+ const typesetContentIfReady = async () => {
381
+ if (window.mathJaxReady && (thoughtsBuffer.length > 0 || answerBuffer.length > 0)) {
382
+ try {
383
+ // Tell MathJax which elements might contain math
384
+ const elementsToTypeset = [thoughtsContent, answerContent];
385
+ MathJax.startup.document.updateDocument(); // Clear previous math
386
+ await MathJax.typesetPromise(elementsToTypeset);
387
+
388
+ // Scroll answer section to bottom smoothly
389
+ answerContent.scrollTo({ top: answerContent.scrollHeight, behavior: 'smooth' });
390
+ } catch (err) {
391
+ console.error("MathJax typesetting error:", err);
392
+ // Maybe display a subtle error to the user if MathJax fails repeatedly
393
+ }
394
+ } else if (!window.mathJaxReady) {
395
+ console.log("MathJax not ready, retrying typesetting...");
396
+ setTimeout(typesetContentIfReady, 300); // Retry if MathJax isn't ready
397
+ }
398
+ };
399
+
400
+ // Update displayed content (throttled)
401
+ const updateDisplay = async () => {
402
+ // Use marked to parse Markdown (ensure it's safe if source is untrusted)
403
+ thoughtsContent.innerHTML = marked.parse(thoughtsBuffer);
404
+ answerContent.innerHTML = marked.parse(answerBuffer);
405
+ await typesetContentIfReady(); // Render MathJax
406
+ updateTimeout = null; // Clear timeout flag
407
+ };
408
+
409
+ // Schedule UI update to avoid excessive re-rendering during streaming
410
+ const scheduleUpdate = () => {
411
+ if (!updateTimeout) {
412
+ updateTimeout = setTimeout(updateDisplay, 150); // Adjust delay as needed (e.g., 150-250ms)
413
+ }
414
+ };
415
+
416
+ // Configure Marked
417
+ marked.setOptions({
418
+ gfm: true, // Enable GitHub Flavored Markdown
419
+ breaks: true, // Convert single line breaks to <br>
420
+ sanitize: false, // IMPORTANT: Only use false if backend output is TRUSTED. If not, use a sanitizer library like DOMPurify.
421
+ mangle: false, // Disable email address mangling
422
+ headerIds: false // Disable automatic header IDs
423
+ });
424
+
425
+ // --- Event Listeners ---
426
+
427
+ // Thoughts toggle
428
+ thoughtsToggle.addEventListener('click', () => {
429
+ thoughtsBox.classList.toggle('open');
430
+ toggleIcon.style.transform = thoughtsBox.classList.contains('open') ? 'rotate(180deg)' : 'rotate(0deg)';
431
+ });
432
+
433
+ // Image selection
434
+ imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0]));
435
+
436
+ // Drag and Drop
437
+ const dropZone = document.querySelector('.uploadArea');
438
+ dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('border-blue-400', 'bg-blue-100'); });
439
+ dropZone.addEventListener('dragleave', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400', 'bg-blue-100'); });
440
+ dropZone.addEventListener('drop', e => {
441
+ e.preventDefault();
442
+ dropZone.classList.remove('border-blue-400', 'bg-blue-100');
443
+ if (e.dataTransfer.files.length > 0) {
444
+ imageInput.files = e.dataTransfer.files; // Assign dropped file(s) to input
445
+ handleFileSelect(e.dataTransfer.files[0]); // Process the first file
446
+ }
447
+ });
448
+ // Also trigger file input on click
449
+ dropZone.addEventListener('click', () => imageInput.click());
450
+
451
+
452
+ // Form submission (problem solving)
453
+ form.addEventListener('submit', async e => {
454
+ e.preventDefault();
455
+ const file = imageInput.files[0];
456
+ if (!file) {
457
+ Swal.fire('Aucune Image', 'Veuillez sélectionner une image avant de soumettre.', 'warning');
458
+ return;
459
+ }
460
+
461
+ // Reset relevant parts before starting
462
+ solutionSection.classList.add('hidden');
463
+ thoughtsContent.innerHTML = '';
464
+ answerContent.innerHTML = '';
465
+ thoughtsBuffer = '';
466
+ answerBuffer = '';
467
+ currentMode = null;
468
+ currentSaveData = null; // Clear previous potential save data
469
+ stopTimer(); // Reset timer before starting
470
+ thoughtsBox.classList.add('open'); // Default to open thoughts
471
+ toggleIcon.style.transform = 'rotate(180deg)';
472
+
473
+ // Show loader and start timer
474
+ loader.classList.remove('hidden');
475
+ submitButton.disabled = true; // Disable submit while processing
476
+ startTimer();
477
+
478
+ const formData = new FormData();
479
+ formData.append('image', file);
480
+
481
+ try {
482
+ const response = await fetch('/solve', { method: 'POST', body: formData });
483
+
484
+ if (!response.ok) {
485
+ // Handle HTTP errors like 4xx, 5xx
486
+ let errorMsg = `Erreur serveur: ${response.status} ${response.statusText}`;
487
+ try {
488
+ const errorData = await response.json();
489
+ errorMsg = errorData.error || errorMsg; // Use server-provided error if available
490
+ } catch(jsonError) { /* Ignore if response is not JSON */ }
491
+
492
+ throw new Error(errorMsg);
493
+ }
494
+
495
+
496
+ const reader = response.body.getReader();
497
+ const decoder = new TextDecoder();
498
+ let buffer = ''; // Buffer for incomplete chunks
499
+
500
+ const processChunk = async ({ done, value }) => {
501
+ if (done) {
502
+ // Process any remaining data in the buffer when the stream ends
503
+ if (buffer.startsWith('data:')) {
504
+ try {
505
+ const data = JSON.parse(buffer.slice(5));
506
+ if (data.content) {
507
+ if (currentMode === 'thinking') thoughtsBuffer += data.content;
508
+ else if (currentMode === 'answering') answerBuffer += data.content;
509
+ }
510
+ } catch (e) {
511
+ console.warn("Could not parse final JSON chunk:", buffer, e);
512
+ }
513
+ }
514
+ buffer = ''; // Clear buffer
515
+ return; // Exit loop
516
+ }
517
+
518
+ buffer += decoder.decode(value, { stream: true });
519
+ const lines = buffer.split('\n\n'); // Split by double newline SSE convention
520
+ buffer = lines.pop(); // Keep the potentially incomplete last part
521
+
522
+ for (const line of lines) {
523
+ if (!line.startsWith('data:')) continue; // Ignore non-data lines
524
+
525
+ try {
526
+ const data = JSON.parse(line.slice(5)); // Remove "data:" prefix and parse
527
+
528
+ if (data.mode) { // Check for mode change ('thinking' or 'answering')
529
+ currentMode = data.mode;
530
+ if (!solutionSection.classList.contains('hidden')) {
531
+ loader.classList.add('hidden'); // Hide loader only once mode is known
532
+ solutionSection.classList.remove('hidden');
533
+ }
534
+ }
535
+ if (data.content) { // Append content based on current mode
536
+ if (currentMode === 'thinking') { thoughtsBuffer += data.content; }
537
+ else if (currentMode === 'answering') { answerBuffer += data.content; }
538
+ }
539
+ } catch (e) {
540
+ console.warn("Could not parse JSON chunk:", line, e);
541
+ // Optionally inform user about corrupted data stream
542
+ }
543
+ }
544
+ scheduleUpdate(); // Schedule UI update after processing chunks
545
+ return reader.read().then(processChunk); // Read the next chunk
546
+ };
547
+
548
+ // Start processing the stream
549
+ await reader.read().then(processChunk);
550
+
551
+ // Final actions after stream ends
552
+ stopTimer();
553
+ loader.classList.add('hidden');
554
+ submitButton.disabled = false; // Re-enable submit
555
+ await updateDisplay(); // Ensure the very last content is displayed and typeset
556
+
557
+ // Prepare data for potential saving
558
+ currentSaveData = {
559
+ answer: answerContent.innerHTML,
560
+ thinking: thoughtsContent.innerHTML,
561
+ date: new Date().toLocaleString('fr-FR') // Use French locale for date
562
+ };
563
+
564
+ } catch (error) {
565
+ console.error('Erreur lors de la résolution:', error);
566
+ Swal.fire({
567
+ icon: 'error',
568
+ title: 'Erreur de Traitement',
569
+ text: `Impossible de résoudre le problème. ${error.message}`,
570
+ });
571
+ loader.classList.add('hidden');
572
+ submitButton.disabled = false; // Re-enable submit on error
573
+ stopTimer();
574
+ }
575
+ });
576
+
577
+ // Save solution
578
+ saveButton.addEventListener('click', async () => {
579
+ if (!currentSaveData) {
580
+ Swal.fire('Aucune Solution', 'Il n\'y a pas de solution à sauvegarder.', 'info');
581
+ return;
582
+ }
583
+
584
+ const { value: saveName } = await Swal.fire({
585
+ title: 'Nommer la Sauvegarde',
586
+ input: 'text',
587
+ inputLabel: 'Donnez un nom unique à cet exercice',
588
+ inputPlaceholder: 'Ex: Chapitre 3 - Exercice 5',
589
+ showCancelButton: true,
590
+ confirmButtonText: 'Sauvegarder',
591
+ cancelButtonText: 'Annuler',
592
+ inputValidator: (value) => {
593
+ if (!value) {
594
+ return 'Le nom ne peut pas être vide !';
595
+ }
596
+ // Optional: Check if name already exists
597
+ // let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
598
+ // if (savedExercises[value]) { return 'Ce nom existe déjà!'; }
599
+ }
600
+ });
601
+
602
+ if (saveName) {
603
+ try {
604
+ let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
605
+ savedExercises[saveName] = currentSaveData; // Use the prepared save data
606
+ localStorage.setItem('savedExercises', JSON.stringify(savedExercises));
607
+ Swal.fire({
608
+ icon: 'success',
609
+ title: 'Sauvegardé!',
610
+ text: `L'exercice "${saveName}" a été sauvegardé.`,
611
+ timer: 2000,
612
+ showConfirmButton: false
613
+ });
614
+ } catch (storageError) {
615
+ console.error("Erreur localStorage:", storageError);
616
+ Swal.fire('Erreur Sauvegarde', 'Impossible de sauvegarder. Le stockage local est peut-être plein ou indisponible.', 'error');
617
+ }
618
+ }
619
+ });
620
+
621
+ // Load saved exercises list into modal
622
+ const loadSavedList = () => {
623
+ savedList.innerHTML = ''; // Clear previous list
624
+ let hasSaves = false;
625
+ try {
626
+ const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
627
+ const sortedNames = Object.keys(savedExercises).sort((a, b) => {
628
+ // Optional: Sort by date if available, otherwise by name
629
+ const dateA = savedExercises[a].date ? new Date(savedExercises[a].date.split('/').reverse().join('-')) : 0; // Handle FR date format if needed
630
+ const dateB = savedExercises[b].date ? new Date(savedExercises[b].date.split('/').reverse().join('-')) : 0;
631
+ if (dateA && dateB && dateB !== dateA) return dateB - dateA; // Sort newest first
632
+ return a.localeCompare(b); // Fallback to name sort
633
+ });
634
+
635
+ for (const name of sortedNames) {
636
+ const data = savedExercises[name];
637
+ const li = document.createElement('li');
638
+ li.innerHTML = `
639
+ <button class="w-full text-left text-blue-600 hover:underline hover:bg-gray-100 rounded px-2 py-1 text-sm flex justify-between items-center" data-save="${name}">
640
+ <span>${name}</span>
641
+ <span class="text-gray-500 text-xs ml-2">${data.date || 'Date inconnue'}</span>
642
+ </button>`;
643
+ savedList.appendChild(li);
644
+ hasSaves = true;
645
+ }
646
+ } catch (e) {
647
+ console.error("Error loading saved exercises:", e);
648
+ savedList.innerHTML = '<li class="text-red-500">Erreur lors du chargement des sauvegardes.</li>';
649
+ }
650
+ noSavesMessage.classList.toggle('hidden', hasSaves); // Show/hide 'no saves' message
651
+ };
652
+
653
+ // Handle click on a saved item
654
+ savedList.addEventListener('click', async (e) => {
655
+ const button = e.target.closest('button[data-save]');
656
+ if (button) {
657
+ const saveName = button.dataset.save;
658
+ try {
659
+ const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
660
+ const data = savedExercises[saveName];
661
+ if (data) {
662
+ resetUI(); // Reset the UI first
663
+ form.classList.add('hidden'); // Hide form
664
+ solutionSection.classList.remove('hidden'); // Show solution area
665
+ thoughtsContent.innerHTML = data.thinking || ''; // Load thoughts
666
+ answerContent.innerHTML = data.answer || ''; // Load answer
667
+ currentSaveData = data; // Store loaded data in case user wants to re-save/update
668
+
669
+ // IMPORTANT: Re-render MathJax for the loaded content
670
+ // Use setTimeout to ensure DOM is updated before MathJax runs
671
+ setTimeout(async () => {
672
+ thoughtsBuffer = data.thinking || ''; // Update buffers for potential re-render logic
673
+ answerBuffer = data.answer || '';
674
+ await typesetContentIfReady();
675
+ }, 50); // Small delay
676
+
677
+ savedModal.classList.remove('active'); // Close modal
678
+ } else {
679
+ Swal.fire('Erreur', `Sauvegarde "${saveName}" non trouvée.`, 'error');
680
+ loadSavedList(); // Refresh list in case it was deleted elsewhere
681
+ }
682
+ } catch (e) {
683
+ console.error("Error loading save:", e);
684
+ Swal.fire('Erreur Chargement', 'Impossible de charger la sauvegarde.', 'error');
685
+ }
686
+ }
687
+ });
688
+
689
+ // Open/Close Saved Exercises Modal
690
+ openSaved.addEventListener('click', () => { loadSavedList(); savedModal.classList.add('active'); });
691
+ closeSaved.addEventListener('click', () => { savedModal.classList.remove('active'); });
692
+ // Close modal if clicking outside the content area
693
+ savedModal.addEventListener('click', (e) => {
694
+ if (e.target === savedModal) { // Check if the click is on the backdrop
695
+ savedModal.classList.remove('active');
696
+ }
697
+ });
698
+
699
+
700
+ // "New Exercise" button inside the modal
701
+ newExercise.addEventListener('click', () => {
702
+ resetUI(); // Reset everything to start fresh
703
+ // Modal is already closed by resetUI
704
+ });
705
+
706
+ // --- Initial Setup ---
707
+ resetUI(); // Initialize the UI on page load
708
+
709
+ });
710
+ </script>
711
+ </body>
712
+ </html>