Mariam-cards / templates /index.html
Docfile's picture
Update templates/index.html
d191a18 verified
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mariam M-1 | Solution Mathématique</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Highlight.js pour la coloration syntaxique -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<!-- Configuration de MathJax -->
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$']],
displayMath: [['$$', '$$']],
processEscapes: true,
packages: {'[+]': ['autoload', 'ams']}
},
options: {
enableMenu: false,
messageStyle: 'none'
},
startup: {
pageReady: () => { window.mathJaxReady = true; }
}
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap');
body { font-family: 'Space Grotesk', sans-serif; }
.uploadArea {
background: #f3f4f6;
border: 2px dashed #d1d5db;
transition: border-color 0.2s ease;
}
.uploadArea:hover { border-color: #3b82f6; }
.blue-button { background: #3b82f6; transition: background-color 0.2s ease; }
.blue-button:hover:not(:disabled) { background: #2563eb; } /* Hover only when not disabled */
.blue-button:disabled {
background: #9ca3af; /* Gray background for disabled */
cursor: not-allowed;
}
.loader {
width: 48px;
height: 48px;
border: 3px solid #3b82f6;
border-bottom-color: transparent;
border-radius: 50%;
display: inline-block;
animation: rotation 1s linear infinite;
}
@keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.thought-box {
transition: max-height 0.3s ease-out;
max-height: 0;
overflow: hidden;
}
.thought-box.open { max-height: 500px; }
#thoughtsContent, #answerContent {
max-height: 500px;
overflow-y: auto;
scroll-behavior: smooth;
white-space: pre-wrap;
}
.preview-image { max-width: 300px; max-height: 300px; object-fit: contain; }
.timestamp { color: #3b82f6; font-size: 0.9em; margin-left: 8px; }
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1rem;
}
th, td {
border: 1px solid #d1d5db;
padding: 0.5rem;
text-align: left;
}
th { background-color: #f3f4f6; font-weight: 600; }
.table-responsive { overflow-x: auto; }
/* Style pour le bouton Sauvegarder afin de le mettre en évidence */
#saveButton {
background: #3b82f6;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
transition: background-color 0.2s ease;
}
#saveButton:hover { background: #2563eb; }
/* Modal plein écran pour les sauvegardes */
#savedModal {
display: none;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 50;
}
#savedModal.active { display: block; }
#savedModalContent {
background: #fff;
width: 100%;
height: 100%;
overflow-y: auto;
}
/* Styles spécifiques pour le code et son exécution */
pre {
background-color: #f8f8f8;
border: 1px solid #e2e8f0;
border-radius: 0.375rem;
padding: 1rem;
margin: 1rem 0;
overflow-x: auto;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
code {
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
.code-execution-result {
background-color: #f0fff4;
border-left: 4px solid #48bb78;
padding: 1rem;
margin: 1rem 0;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
white-space: pre-wrap;
}
/* Styles pour les types de contenu spécifiques */
.content-text {}
.content-code { padding: 0; }
.content-result {
background-color: #f0fff4;
border-left: 4px solid #48bb78;
padding: 1rem;
margin: 0.5rem 0;
}
.content-image { margin: 1rem 0; text-align: center; }
.content-image img { max-width: 100%; }
</style>
</head>
<body class="p-4">
<div class="max-w-4xl mx-auto">
<header class="p-6 text-center mb-8">
<h1 class="text-4xl font-bold text-blue-600">Mariam M-?</h1>
<p class="text-gray-600">Solution Mathématique/Physique/Chimie Intelligente, avec intégration d'une calculatrice.</p>
<p style="color: red;">Mode standard. Passez au premium pour de très hautes performances.</p>
<div class="mt-4 flex justify-end">
<button id="openSaved" class="blue-button px-4 py-2 text-white rounded">Sauvegardes</button>
</div>
</header>
<main id="mainContent">
<form id="problemForm" class="space-y-6" novalidate>
<!-- Zone de dépôt / sélection d'image -->
<div class="uploadArea p-8 text-center relative" aria-label="Zone de dépôt d'image">
<input type="file" id="imageInput" name="image" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" aria-label="Choisir une image">
<div class="space-y-3">
<div class="w-16 h-16 mx-auto border-2 border-blue-400 rounded-full flex items-center justify-center">
<svg class="w-8 h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<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" />
</svg>
</div>
<p class="text-gray-700 font-medium">Déposez votre image ici</p>
<p class="text-gray-500 text-sm">ou cliquez pour sélectionner</p>
</div>
</div>
<!-- Aperçu de l'image -->
<div id="imagePreview" class="hidden text-center">
<img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image">
</div>
<!-- Le bouton de soumission -->
<button type="submit" id="submitButton" class="blue-button w-full py-3 text-white font-medium rounded-lg">
Résoudre le problème
</button>
</form>
<!-- Loader -->
<div id="loader" class="hidden mt-8 text-center">
<span class="loader"></span>
<p class="mt-4 text-gray-600">Analyse en cours...</p>
</div>
<!-- Zone d'affichage de la solution -->
<section id="solution" class="hidden mt-8 space-y-6 relative">
<div class="border-t pt-4">
<button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-2">
<span class="font-medium text-gray-700">Processus de Réflexion</span>
<span id="timestamp" class="timestamp"></span>
</button>
<div id="thoughtsBox" class="thought-box">
<div id="thoughtsContent" class="p-4 text-gray-600"></div>
</div>
</div>
<div class="border-t pt-6">
<div class="flex justify-between items-center">
<h3 class="text-xl font-bold text-gray-800 mb-4">Solution</h3>
<!-- Bouton Sauvegarder mis en évidence -->
<button id="saveButton">Sauvegarder</button>
</div>
<div id="answerContent" class="text-gray-700 table-responsive"></div>
</div>
</section>
</main>
</div>
<!-- Modal plein écran pour les sauvegardes -->
<div id="savedModal">
<div id="savedModalContent" class="p-6">
<header class="flex justify-between items-center border-b pb-4">
<h2 class="text-2xl font-bold">Sauvegardes</h2>
<button id="closeSaved" class="text-3xl text-gray-600">×</button>
</header>
<div id="savedListContainer" class="mt-4">
<ul id="savedList" class="space-y-4">
<!-- Liste des sauvegardes insérée dynamiquement -->
</ul>
</div>
<div class="mt-6">
<button id="newExercise" class="blue-button w-full py-3 text-white font-medium rounded-lg">
Résoudre un nouvel exercice
</button>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Récupération des éléments
const form = document.getElementById('problemForm');
const imageInput = document.getElementById('imageInput');
const submitButton = document.getElementById('submitButton'); // Get the submit button
const loader = document.getElementById('loader');
const solutionSection = document.getElementById('solution');
const thoughtsContent = document.getElementById('thoughtsContent');
const answerContent = document.getElementById('answerContent');
const thoughtsToggle = document.getElementById('thoughtsToggle');
const thoughtsBox = document.getElementById('thoughtsBox');
const imagePreview = document.getElementById('imagePreview');
const previewImage = document.getElementById('previewImage');
const timestamp = document.getElementById('timestamp');
const saveButton = document.getElementById('saveButton');
const openSaved = document.getElementById('openSaved');
const closeSaved = document.getElementById('closeSaved');
const savedModal = document.getElementById('savedModal');
const savedList = document.getElementById('savedList');
const newExercise = document.getElementById('newExercise');
const mainContent = document.getElementById('mainContent'); // This variable is not used in the original logic, keeping it but it could be removed.
let startTime = null;
let timerInterval = null;
let thoughtsBuffer = '';
let answerBuffer = '';
let currentMode = null;
let updateTimeout = null;
// --- Délai de soumission local ---
const COOLDOWN_DURATION = 3 * 60 * 1000; // 3 minutes en millisecondes
const LAST_SUBMISSION_KEY = 'lastSubmissionTime';
let cooldownTimer = null; // Pour l'intervalle de mise à jour du bouton
// Fonction pour récupérer le timestamp de la dernière soumission depuis localStorage
const getLastSubmissionTime = () => {
const timestamp = localStorage.getItem(LAST_SUBMISSION_KEY);
return timestamp ? parseInt(timestamp, 10) : null;
};
// Fonction pour enregistrer le timestamp de la soumission actuelle dans localStorage
const setLastSubmissionTime = () => {
localStorage.setItem(LAST_SUBMISSION_KEY, Date.now().toString());
};
// Fonction pour vérifier le délai et mettre à jour l'état du bouton
const updateSubmitButtonState = () => {
const lastSubmit = getLastSubmissionTime();
const now = Date.now();
if (lastSubmit && now - lastSubmit < COOLDOWN_DURATION) {
const remainingTime = COOLDOWN_DURATION - (now - lastSubmit);
const minutes = Math.floor(remainingTime / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000);
submitButton.disabled = true;
submitButton.textContent = `Prochaine soumission dans ${minutes}:${seconds.toString().padStart(2, '0')}`;
// Démarrer le timer si ce n'est pas déjà fait
if (!cooldownTimer) {
cooldownTimer = setInterval(updateSubmitButtonState, 1000);
}
} else {
// Le délai est terminé ou il n'y a pas de soumission précédente
submitButton.disabled = false;
submitButton.textContent = 'Résoudre le problème';
// Arrêter le timer s'il était en cours
if (cooldownTimer) {
clearInterval(cooldownTimer);
cooldownTimer = null;
}
}
};
// Appeler la fonction au chargement de la page pour initialiser l'état du bouton
updateSubmitButtonState();
// --- Fin Délai de soumission local ---
// Mise à jour du temps écoulé (pour l'analyse en cours)
const updateTimestamp = () => {
if (startTime) {
const seconds = Math.floor((Date.now() - startTime) / 1000);
timestamp.textContent = `${seconds}s`;
}
};
const startTimer = () => { startTime = Date.now(); timerInterval = setInterval(updateTimestamp, 1000); updateTimestamp(); };
const stopTimer = () => { clearInterval(timerInterval); startTime = null; timestamp.textContent = ''; };
// Affichage de l'image sélectionnée
const handleFileSelect = file => {
if (!file) return;
const reader = new FileReader();
reader.onload = e => {
previewImage.src = e.target.result;
imagePreview.classList.remove('hidden');
};
reader.readAsDataURL(file);
};
thoughtsToggle.addEventListener('click', () => { thoughtsBox.classList.toggle('open'); });
imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0]));
// Gestion du glisser-déposer
const dropZone = document.querySelector('.uploadArea');
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('border-blue-400'); });
dropZone.addEventListener('dragleave', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400'); });
dropZone.addEventListener('drop', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400'); handleFileSelect(e.dataTransfer.files[0]); });
// Fonction pour appliquer la coloration syntaxique
const applyHighlighting = () => {
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightBlock(block);
});
};
// Rendu MathJax et mise à jour de l'affichage
const typesetAnswerIfReady = async () => {
if (window.mathJaxReady) {
// Target specific elements for MathJax typesetting if needed, or document.body
// Targeting answerContent and thoughtsContent is safer for performance
MathJax.startup.document.elements = [document.getElementById('answerContent'), document.getElementById('thoughtsContent')];
await MathJax.typesetPromise();
applyHighlighting(); // Apply highlighting after MathJax
// Keep scrolling behavior only for the main answer content maybe
// answerContent.scrollTop = answerContent.scrollHeight; // Auto-scroll might be jumpy with streaming
} else { setTimeout(typesetAnswerIfReady, 200); }
};
const updateDisplay = async () => {
// Use innerHTML = marked.parse(...) for streaming updates
thoughtsContent.innerHTML = marked.parse(thoughtsBuffer);
answerContent.innerHTML = marked.parse(answerBuffer);
// Trigger MathJax typesetting and highlighting *after* updating innerHTML
await typesetAnswerIfReady();
// Optional: auto-scroll only the answer content if it's the active stream
if (currentMode === 'answering') {
answerContent.scrollTop = answerContent.scrollHeight;
} else if (currentMode === 'thinking') {
thoughtsContent.scrollTop = thoughtsContent.scrollHeight;
}
updateTimeout = null;
};
const scheduleUpdate = () => { if (!updateTimeout) updateTimeout = setTimeout(updateDisplay, 200); };
marked.setOptions({
gfm: true,
breaks: true,
highlight: function(code, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (error) {
console.error("Highlighting error:", error);
return code; // Return original code on error
}
}
// Default highlighting for unrecognised languages or no language specified
try {
return hljs.highlightAuto(code).value;
} catch (error) {
console.error("Auto highlighting error:", error);
return code; // Return original code on error
}
}
});
// Envoi de l'image pour résolution
form.addEventListener('submit', async e => {
e.preventDefault(); // Empêcher la soumission par défaut pour gérer le délai
// --- Vérification du délai ---
const lastSubmit = getLastSubmissionTime();
const now = Date.now();
if (lastSubmit && now - lastSubmit < COOLDOWN_DURATION) {
const remainingTime = COOLDOWN_DURATION - (now - lastSubmit);
const minutes = Math.floor(remainingTime / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000);
Swal.fire({
icon: 'warning',
title: 'Veuillez patienter',
text: `Vous devez attendre ${minutes} minute(s) et ${seconds.toString().padStart(2, '0')} seconde(s) avant de soumettre à nouveau.`
});
// Mettre à jour l'état du bouton immédiatement après le message d'erreur
updateSubmitButtonState();
return; // Arrêter le processus de soumission
}
// --- Fin Vérification du délai ---
const file = imageInput.files[0];
if (!file) {
Swal.fire({
icon: 'error',
title: 'Image manquante',
text: 'Veuillez sélectionner une image.'
});
// Re-vérifier et potentiellement réactiver le bouton si aucune image n'est sélectionnée
updateSubmitButtonState();
return;
}
// --- Le délai est passé ou n'existait pas, on procède ---
setLastSubmissionTime(); // Enregistrer le nouveau timestamp *avant* de commencer
updateSubmitButtonState(); // Désactiver et mettre à jour le bouton
startTimer();
loader.classList.remove('hidden');
solutionSection.classList.add('hidden');
thoughtsContent.innerHTML = ''; // Vider le contenu précédent
answerContent.innerHTML = ''; // Vider le contenu précédent
thoughtsBuffer = ''; // Vider les buffers
answerBuffer = '';
currentMode = null; // Reset mode
// thoughtsBox starts open by default, keep it open during processing
thoughtsBox.classList.add('open');
const formData = new FormData();
formData.append('image', file);
try {
// Hardcode the endpoint to /solved
const response = await fetch('/solved', { method: 'POST', body: formData });
if (!response.ok) {
// Handle HTTP errors
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
}
if (!response.body) {
throw new Error('Response body is not available (e.g., not a streaming response)');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const processChunk = async chunk => {
buffer += decoder.decode(chunk, { stream: true });
const lines = buffer.split('\n\n');
buffer = lines.pop(); // Keep the last potentially incomplete line in buffer
for (const line of lines) {
if (!line.startsWith('data:')) {
// console.warn('Skipping non-data line:', line); // Log non-data lines
continue;
}
try {
const data = JSON.parse(line.slice(5));
if (data.mode) {
currentMode = data.mode;
// Hide loader and show solution section once streaming starts
loader.classList.add('hidden');
solutionSection.classList.remove('hidden');
}
// Process content based on currentMode and data type
if (data.content !== undefined) { // Check for undefined to allow empty strings
if (currentMode === 'thinking') {
thoughtsBuffer += data.content;
} else if (currentMode === 'answering') {
// Handle different types within answering mode
switch(data.type) {
case 'code':
// Use markdown code block syntax
answerBuffer += "\n```\n" + data.content + "\n```\n";
break;
case 'result':
// Format results clearly, handling multiple lines
const formattedResult = data.content.split('\n').map(line => `> ${line}`).join('\n');
answerBuffer += "\n" + formattedResult + "\n";
break;
case 'image':
// Include images as markdown images
answerBuffer += `\n![Résultat](data:image/png;base64,${data.content})\n`;
break;
case 'text': // Explicitly handle text within answering mode
default: // Default behavior is to append text
answerBuffer += data.content;
break;
}
}
}
if (data.error) {
// Append error to the relevant buffer or main answer buffer
if (currentMode === 'thinking') {
thoughtsBuffer += `\n**Erreur pendant la réflexion:** ${data.error}\n`;
} else { // Assume error relates to the answer process
answerBuffer += `\n**Erreur:** ${data.error}\n`;
}
}
} catch (e) {
console.error('Error parsing JSON data:', line.slice(5), e);
// Append a parsing error message to the output
if (currentMode === 'thinking') { thoughtsBuffer += `\n[Erreur de traitement du flux]`; }
else { answerBuffer += `\n[Erreur de traitement du flux]`; }
}
}
scheduleUpdate(); // Schedule display update after processing a batch of lines
};
// Start processing the stream
while (true) {
const { done, value } = await reader.read();
if (done) {
// Process any remaining buffer
if (buffer.length > 0) { // Process any data left in the buffer
// Even if it's not a full line, decode and append what's left
// Note: This might result in incomplete markdown being displayed
if (currentMode === 'thinking') {
thoughtsBuffer += decoder.decode(buffer, { stream: true });
} else if (currentMode === 'answering') {
answerBuffer += decoder.decode(buffer, { stream: true });
}
buffer = ''; // Clear buffer after processing
}
scheduleUpdate(); // Final display update to render last buffer content
break; // Exit loop
}
// Process the received chunk
await processChunk(value);
}
} catch (error) {
console.error('Erreur de Fetch ou du Stream:', error);
// Append a user-friendly error message to the answer area if nothing is there, or append to existing content
if(answerContent.innerHTML === '' && answerBuffer === '') { // If solution area is empty
answerContent.innerHTML = `<div class="text-red-500">Une erreur est survenue lors du traitement de votre demande: ${error.message}</div>`;
} else { // If some output exists, append the error
answerBuffer += `\n\n<div class="text-red-500">Une erreur est survenue: ${error.message}</div>`;
scheduleUpdate(); // Update display with the appended error
}
Swal.fire({
icon: 'error',
title: 'Erreur de connexion ou de traitement',
text: `Une erreur est survenue lors du traitement de votre demande. Détails: ${error.message}`
});
} finally {
// Code qui s'exécute après try/catch, qu'il y ait eu une erreur ou non
stopTimer(); // Arrêter le timer de l'analyse
loader.classList.add('hidden'); // Cacher le loader
solutionSection.classList.remove('hidden'); // S'assurer que la section solution est visible
// --- Mise à jour finale de l'état du bouton ---
updateSubmitButtonState(); // Vérifier si le délai est terminé et mettre à jour le bouton
// --- Fin Mise à jour finale ---
}
});
// Sauvegarde de la solution avec SweetAlert2
saveButton.addEventListener('click', () => {
Swal.fire({
title: 'Sauvegarder la solution',
input: 'text',
inputLabel: 'Nom de la sauvegarde',
inputPlaceholder: 'Entrez un nom pour cette sauvegarde',
showCancelButton: true,
confirmButtonText: 'Sauvegarder',
cancelButtonText: 'Annuler',
inputValidator: (value) => {
if (!value) {
return 'Veuillez donner un nom à votre sauvegarde !';
}
}
}).then((result) => {
if (result.isConfirmed && result.value) {
const saveName = result.value;
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
if (savedExercises[saveName]) {
// Ask if user wants to overwrite
Swal.fire({
title: `Sauvegarde "${saveName}" existe déjà. Écraser ?`,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Oui, écraser',
cancelButtonText: 'Annuler'
}).then((overwriteResult) => {
if (overwriteResult.isConfirmed) {
saveCurrentSolution(saveName, savedExercises);
}
});
} else {
saveCurrentSolution(saveName, savedExercises);
}
}
});
});
const saveCurrentSolution = (saveName, existingSaves) => {
const saveData = {
answer: answerContent.innerHTML, // Save the rendered HTML
thinking: thoughtsContent.innerHTML, // Save the rendered HTML
date: new Date().toLocaleString()
};
existingSaves[saveName] = saveData;
localStorage.setItem('savedExercises', JSON.stringify(existingSaves));
Swal.fire({
icon: 'success',
title: 'Sauvegarde réussie',
text: 'Votre solution a bien été sauvegardée !',
timer: 2000,
showConfirmButton: false
});
};
// Chargement des sauvegardes dans le modal
const loadSavedList = () => {
savedList.innerHTML = '';
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
if (Object.keys(savedExercises).length === 0) {
savedList.innerHTML = '<li class="text-gray-500 text-center py-8">Aucune sauvegarde disponible</li>';
return;
}
// Sort by date, newest first (optional but nice)
const sortedEntries = Object.entries(savedExercises).sort(([,a], [,b]) => new Date(b.date) - new Date(a.date));
for (const [name, data] of sortedEntries) {
const li = document.createElement('li');
li.className = 'border-b pb-2';
li.innerHTML = `
<div class="flex justify-between items-center">
<button class="text-left text-blue-600 hover:underline" data-save="${encodeURIComponent(name)}">
${name} <span class="text-gray-500 text-xs">(${data.date})</span>
</button>
<button class="text-red-500 hover:text-red-700" data-delete="${encodeURIComponent(name)}">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
</svg>
</button>
</div>
`;
savedList.appendChild(li);
}
};
// Gestion des clics sur les sauvegardes
savedList.addEventListener('click', (e) => {
// Chargement d'une sauvegarde
if (e.target && e.target.dataset.save) {
const saveName = decodeURIComponent(e.target.dataset.save);
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
const data = savedExercises[saveName];
if (data) {
// Hide the form and loader, show the solution section
form.classList.add('hidden');
loader.classList.add('hidden');
solutionSection.classList.remove('hidden');
// Load the saved HTML content
thoughtsContent.innerHTML = data.thinking;
answerContent.innerHTML = data.answer;
// Close the modal
savedModal.classList.remove('active');
// Re-render MathJax and apply highlighting to the loaded HTML
// Use MathJax.typesetPromise() on the specific elements
if (window.mathJaxReady) {
MathJax.startup.document.elements = [thoughtsContent, answerContent]; // Target both potentially
MathJax.typesetPromise().then(() => {
applyHighlighting(); // Apply highlighting after MathJax
}).catch((err) => console.error("MathJax typesetting failed:", err));
} else {
console.warn("MathJax not ready yet, cannot typeset saved content.");
}
// Ensure thoughts box is open when viewing a saved solution
thoughtsBox.classList.add('open');
// Reset buffers and timer as this is static content
thoughtsBuffer = ''; // Buffers are for streaming, not needed for static load
answerBuffer = ''; // Buffers are for streaming, not needed for static load
currentMode = null; // Not streaming
stopTimer(); // Stop the live timer
timestamp.textContent = data.date; // Show saved date as timestamp
submitButton.disabled = true; // Disable submit button while viewing a save
submitButton.textContent = `Vue de la sauvegarde: ${saveName}`;
}
}
// Suppression d'une sauvegarde
if (e.target && (e.target.dataset.delete || e.target.closest('[data-delete]'))) {
const deleteName = decodeURIComponent(e.target.dataset.delete || e.target.closest('[data-delete]').dataset.delete);
Swal.fire({
title: 'Êtes-vous sûr ?',
text: "Cette sauvegarde sera définitivement supprimée.",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Oui, supprimer',
cancelButtonText: 'Annuler'
}).then((result) => {
if (result.isConfirmed) {
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
delete savedExercises[deleteName];
localStorage.setItem('savedExercises', JSON.stringify(savedExercises));
Swal.fire(
'Supprimé !',
'La sauvegarde a été supprimée.',
'success'
);
loadSavedList(); // Refresh the list in the modal
// If the deleted save was being viewed, reset the view
if (submitButton.textContent.includes(`Vue de la sauvegarde: ${deleteName}`)) {
resetToNewExerciseState();
}
}
});
}
});
// Ouverture / fermeture du modal de sauvegardes
openSaved.addEventListener('click', () => { loadSavedList(); savedModal.classList.add('active'); });
closeSaved.addEventListener('click', () => { savedModal.classList.remove('active'); });
// Fonction pour réinitialiser l'état pour un nouvel exercice
const resetToNewExerciseState = () => {
// Reset form and hide solution
form.reset();
form.classList.remove('hidden');
solutionSection.classList.add('hidden');
imagePreview.classList.add('hidden'); // Hide image preview
previewImage.src = ''; // Clear image source
// Clear content areas and buffers
thoughtsContent.innerHTML = '';
answerContent.innerHTML = '';
thoughtsBuffer = '';
answerBuffer = '';
currentMode = null; // Reset mode
// Stop timer and clear timestamp
stopTimer();
timestamp.textContent = '';
// Ensure thoughts box is collapsed for a new exercise
thoughtsBox.classList.remove('open');
// Update button state based on cooldown
updateSubmitButtonState(); // This will enable/disable based on the 3-min rule
// Close the modal if open
savedModal.classList.remove('active');
};
// Bouton présent uniquement dans le modal pour lancer un nouvel exercice
newExercise.addEventListener('click', resetToNewExerciseState);
// Initial check for cooldown on page load
updateSubmitButtonState();
});
</script>
</body>
</html>